]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/ui/framework/forms.ts
Lexical: Linked table form to have caption toggle option
[bookstack] / resources / js / wysiwyg / ui / framework / forms.ts
1 import {
2     EditorUiContext,
3     EditorUiElement,
4     EditorContainerUiElement,
5     EditorUiBuilderDefinition,
6     isUiBuilderDefinition
7 } from "./core";
8 import {uniqueId} from "../../../services/util";
9 import {el} from "../../utils/dom";
10
11 export interface EditorFormFieldDefinition {
12     label: string;
13     name: string;
14     type: 'text' | 'select' | 'textarea' | 'checkbox';
15 }
16
17 export interface EditorSelectFormFieldDefinition extends EditorFormFieldDefinition {
18     type: 'select',
19     valuesByLabel: Record<string, string>
20 }
21
22 export type EditorFormFields = (EditorFormFieldDefinition|EditorUiBuilderDefinition)[];
23
24 interface EditorFormTabDefinition {
25     label: string;
26     contents: EditorFormFields;
27 }
28
29 export interface EditorFormDefinition {
30     submitText: string;
31     action: (formData: FormData, context: EditorUiContext) => Promise<boolean>;
32     fields: EditorFormFields;
33 }
34
35 export class EditorFormField extends EditorUiElement {
36     protected definition: EditorFormFieldDefinition;
37
38     constructor(definition: EditorFormFieldDefinition) {
39         super();
40         this.definition = definition;
41     }
42
43     setValue(value: string) {
44         const input = this.getDOMElement().querySelector('input,select,textarea') as HTMLInputElement;
45         if (this.definition.type === 'checkbox') {
46             input.checked = Boolean(value);
47         } else {
48             input.value = value;
49         }
50         input.dispatchEvent(new Event('change'));
51     }
52
53     getName(): string {
54         return this.definition.name;
55     }
56
57     protected buildDOM(): HTMLElement {
58         const id = `editor-form-field-${this.definition.name}-${Date.now()}`;
59         let input: HTMLElement;
60
61         if (this.definition.type === 'select') {
62             const options = (this.definition as EditorSelectFormFieldDefinition).valuesByLabel
63             const labels = Object.keys(options);
64             const optionElems = labels.map(label => el('option', {value: options[label]}, [this.trans(label)]));
65             input = el('select', {id, name: this.definition.name, class: 'editor-form-field-input'}, optionElems);
66         } else if (this.definition.type === 'textarea') {
67             input = el('textarea', {id, name: this.definition.name, class: 'editor-form-field-input'});
68         } else if (this.definition.type === 'checkbox') {
69             input = el('input', {id, name: this.definition.name, type: 'checkbox', class: 'editor-form-field-input-checkbox', value: 'true'});
70         } else {
71             input = el('input', {id, name: this.definition.name, class: 'editor-form-field-input'});
72         }
73
74         return el('div', {class: 'editor-form-field-wrapper'}, [
75             el('label', {class: 'editor-form-field-label', for: id}, [this.trans(this.definition.label)]),
76             input,
77         ]);
78     }
79 }
80
81 export class EditorForm extends EditorContainerUiElement {
82     protected definition: EditorFormDefinition;
83     protected onCancel: null|(() => void) = null;
84     protected onSuccessfulSubmit: null|(() => void) = null;
85
86     constructor(definition: EditorFormDefinition) {
87         let children: (EditorFormField|EditorUiElement)[] = definition.fields.map(fieldDefinition => {
88             if (isUiBuilderDefinition(fieldDefinition)) {
89                 return fieldDefinition.build();
90             }
91             return new EditorFormField(fieldDefinition)
92         });
93
94         super(children);
95         this.definition = definition;
96     }
97
98     setValues(values: Record<string, string>) {
99         for (const name of Object.keys(values)) {
100             const field = this.getFieldByName(name);
101             if (field) {
102                 field.setValue(values[name]);
103             }
104         }
105     }
106
107     setOnCancel(callback: () => void) {
108         this.onCancel = callback;
109     }
110
111     setOnSuccessfulSubmit(callback: () => void) {
112         this.onSuccessfulSubmit = callback;
113     }
114
115     protected getFieldByName(name: string): EditorFormField|null {
116
117         const search = (children: EditorUiElement[]): EditorFormField|null => {
118             for (const child of children) {
119                 if (child instanceof EditorFormField && child.getName() === name) {
120                     return child;
121                 } else if (child instanceof EditorContainerUiElement) {
122                     const matchingChild = search(child.getChildren());
123                     if (matchingChild) {
124                         return matchingChild;
125                     }
126                 }
127             }
128
129             return null;
130         };
131
132         return search(this.getChildren());
133     }
134
135     protected buildDOM(): HTMLElement {
136         const cancelButton = el('button', {type: 'button', class: 'editor-form-action-secondary'}, [this.trans('Cancel')]);
137         const form = el('form', {}, [
138             ...this.children.map(child => child.getDOMElement()),
139             el('div', {class: 'editor-form-actions'}, [
140                 cancelButton,
141                 el('button', {type: 'submit', class: 'editor-form-action-primary'}, [this.trans(this.definition.submitText)]),
142             ])
143         ]);
144
145         form.addEventListener('submit', async (event) => {
146             event.preventDefault();
147             const formData = new FormData(form as HTMLFormElement);
148             const result = await this.definition.action(formData, this.getContext());
149             if (result && this.onSuccessfulSubmit) {
150                 this.onSuccessfulSubmit();
151             }
152         });
153
154         cancelButton.addEventListener('click', (event) => {
155             if (this.onCancel) {
156                 this.onCancel();
157             }
158         });
159
160         return form;
161     }
162 }
163
164 export class EditorFormTab extends EditorContainerUiElement {
165
166     protected definition: EditorFormTabDefinition;
167     protected fields: EditorUiElement[];
168     protected id: string;
169
170     constructor(definition: EditorFormTabDefinition) {
171         const fields = definition.contents.map(fieldDef => {
172             if (isUiBuilderDefinition(fieldDef)) {
173                 return fieldDef.build();
174             }
175             return new EditorFormField(fieldDef)
176         });
177
178         super(fields);
179
180         this.definition = definition;
181         this.fields = fields;
182         this.id = uniqueId();
183     }
184
185     public getLabel(): string {
186         return this.getContext().translate(this.definition.label);
187     }
188
189     public getId(): string {
190         return this.id;
191     }
192
193     protected buildDOM(): HTMLElement {
194         return el(
195             'div',
196             {
197                 class: 'editor-form-tab-content',
198                 role: 'tabpanel',
199                 id: `editor-tabpanel-${this.id}`,
200                 'aria-labelledby': `editor-tab-${this.id}`,
201             },
202             this.fields.map(f => f.getDOMElement())
203         );
204     }
205 }
206 export class EditorFormTabs extends EditorContainerUiElement {
207
208     protected definitions: EditorFormTabDefinition[] = [];
209     protected tabs: EditorFormTab[] = [];
210
211     constructor(definitions: EditorFormTabDefinition[]) {
212         const tabs: EditorFormTab[] = definitions.map(d => new EditorFormTab(d));
213         super(tabs);
214
215         this.definitions = definitions;
216         this.tabs = tabs;
217     }
218
219     protected buildDOM(): HTMLElement {
220         const controls: HTMLElement[] = [];
221         const contents: HTMLElement[] = [];
222
223         const selectTab = (tabIndex: number) => {
224             for (let i = 0; i < controls.length; i++) {
225                 controls[i].setAttribute('aria-selected', (i === tabIndex) ? 'true' : 'false');
226             }
227             for (let i = 0; i < contents.length; i++) {
228                 contents[i].hidden = !(i === tabIndex);
229             }
230         };
231
232         for (const tab of this.tabs) {
233             const button = el('button', {
234                 class: 'editor-form-tab-control',
235                 type: 'button',
236                 role: 'tab',
237                 id: `editor-tab-${tab.getId()}`,
238                 'aria-controls': `editor-tabpanel-${tab.getId()}`
239             }, [tab.getLabel()]);
240             contents.push(tab.getDOMElement());
241             controls.push(button);
242
243             button.addEventListener('click', event => {
244                 selectTab(controls.indexOf(button));
245             });
246         }
247
248         selectTab(0);
249
250         return el('div', {class: 'editor-form-tab-container'}, [
251             el('div', {class: 'editor-form-tab-controls'}, controls),
252             el('div', {class: 'editor-form-tab-contents'}, contents),
253         ]);
254     }
255 }