]> BookStack Code Mirror - bookstack/blob - resources/js/editor/menu/item-html-source-button.js
Added source code view/set button
[bookstack] / resources / js / editor / menu / item-html-source-button.js
1 import DialogBox from "./DialogBox";
2 import DialogForm from "./DialogForm";
3 import DialogTextArea from "./DialogTextArea";
4
5 import {MenuItem} from "./menu";
6 import {icons} from "./icons";
7 import {htmlToDoc, stateToHtml} from "../util";
8
9 /**
10  * @param {(function(FormData))} submitter
11  * @param {Function} closer
12  * @return {DialogBox}
13  */
14 function getLinkDialog(submitter, closer) {
15     return new DialogBox([
16         new DialogForm([
17             new DialogTextArea({
18                 id: 'source',
19                 value: stateToHtml,
20                 attrs: {
21                     rows: 10,
22                     cols: 50,
23                 }
24             }),
25         ], {
26             canceler: closer,
27             action: submitter,
28         }),
29     ], {
30         label: 'View/Edit HTML Source',
31         closer: closer,
32     });
33 }
34
35 /**
36  * @param {FormData} formData
37  * @param {PmEditorState} state
38  * @param {PmDispatchFunction} dispatch
39  * @return {boolean}
40  */
41 function replaceEditorHtml(formData, state, dispatch) {
42     const html = formData.get('source');
43
44     if (dispatch) {
45         const tr = state.tr;
46
47         const newDoc = htmlToDoc(html);
48         tr.replaceWith(0, state.doc.content.size, newDoc.content);
49         dispatch(tr);
50     }
51
52     return true;
53 }
54
55
56 /**
57  * @param {PmEditorState} state
58  * @param {PmDispatchFunction} dispatch
59  * @param {PmView} view
60  * @param {Event} e
61  */
62 function onPress(state, dispatch, view, e) {
63     const dialog = getLinkDialog((data) => {
64         replaceEditorHtml(data, state, dispatch);
65         dom.remove();
66     }, () => {
67         dom.remove();
68     })
69
70     const {dom, update} = dialog.render(view);
71     update(state);
72     document.body.appendChild(dom);
73 }
74
75 /**
76  * @return {MenuItem}
77  */
78 function htmlSourceButtonItem() {
79     return new MenuItem({
80         title: "View HTML Source",
81         run: onPress,
82         enable: state => true,
83         icon: icons.source_code,
84     });
85 }
86
87 export default htmlSourceButtonItem;