]> BookStack Code Mirror - bookstack/blob - resources/js/editor/util.js
Added source code view/set button
[bookstack] / resources / js / editor / util.js
1 import schema from "./schema";
2 import {DOMParser, DOMSerializer} from "prosemirror-model";
3
4 /**
5  * @param {String} html
6  * @return {PmNode}
7  */
8 export function htmlToDoc(html) {
9     const renderDoc = document.implementation.createHTMLDocument();
10     renderDoc.body.innerHTML = html;
11     return DOMParser.fromSchema(schema).parse(renderDoc.body);
12 }
13
14 /**
15  * @param {PmNode} doc
16  * @return {string}
17  */
18 export function docToHtml(doc) {
19     const fragment = DOMSerializer.fromSchema(schema).serializeFragment(doc.content);
20     const renderDoc = document.implementation.createHTMLDocument();
21     renderDoc.body.appendChild(fragment);
22     return renderDoc.body.innerHTML;
23 }
24
25 /**
26  * @param {PmEditorState} state
27  * @return {String}
28  */
29 export function stateToHtml(state) {
30     const fragment = DOMSerializer.fromSchema(schema).serializeFragment(state.doc.content);
31     const renderDoc = document.implementation.createHTMLDocument();
32     renderDoc.body.appendChild(fragment);
33     return renderDoc.body.innerHTML;
34 }
35
36 /**
37  * @class KeyedMultiStack
38  * Holds many stacks, seperated via a key, with a simple
39  * interface to pop and push values to the stacks.
40  */
41 export class KeyedMultiStack {
42
43     constructor() {
44         this.stack = {};
45     }
46
47     /**
48      * @param {String} key
49      * @return {undefined|*}
50      */
51     pop(key) {
52         if (Array.isArray(this.stack[key])) {
53             return this.stack[key].pop();
54         }
55         return undefined;
56     }
57
58     /**
59      * @param {String} key
60      * @param {*} value
61      */
62     push(key, value) {
63         if (this.stack[key] === undefined) {
64             this.stack[key] = [];
65         }
66
67         this.stack[key].push(value);
68     }
69 }