]> BookStack Code Mirror - bookstack/blob - resources/js/components/add-remove-rows.js
Merge branch 'codemirror6' into codemirror6_take2
[bookstack] / resources / js / components / add-remove-rows.js
1 import {onChildEvent} from "../services/dom";
2 import {uniqueId} from "../services/util";
3 import {Component} from "./component";
4
5 /**
6  * AddRemoveRows
7  * Allows easy row add/remove controls onto a table.
8  * Needs a model row to use when adding a new row.
9  */
10 export class AddRemoveRows extends Component {
11     setup() {
12         this.modelRow = this.$refs.model;
13         this.addButton = this.$refs.add;
14         this.removeSelector = this.$opts.removeSelector;
15         this.rowSelector = this.$opts.rowSelector;
16         this.setupListeners();
17     }
18
19     setupListeners() {
20         this.addButton.addEventListener('click', this.add.bind(this));
21
22         onChildEvent(this.$el, this.removeSelector, 'click', (e) => {
23             const row = e.target.closest(this.rowSelector);
24             row.remove();
25         });
26     }
27
28     // For external use
29     add() {
30         const clone = this.modelRow.cloneNode(true);
31         clone.classList.remove('hidden');
32         this.setClonedInputNames(clone);
33         this.modelRow.parentNode.insertBefore(clone, this.modelRow);
34         window.$components.init(clone);
35     }
36
37     /**
38      * Update the HTML names of a clone to be unique if required.
39      * Names can use placeholder values. For exmaple, a model row
40      * may have name="tags[randrowid][name]".
41      * These are the available placeholder values:
42      * - randrowid - An random string ID, applied the same across the row.
43      * @param {HTMLElement} clone
44      */
45     setClonedInputNames(clone) {
46         const rowId = uniqueId();
47         const randRowIdElems = clone.querySelectorAll(`[name*="randrowid"]`);
48         for (const elem of randRowIdElems) {
49             elem.name = elem.name.split('randrowid').join(rowId);
50         }
51     }
52 }