1 | /*
|
2 | * Licensed under the Apache License, Version 2.0 (the "License");
|
3 | * you may not use this file except in compliance with the License.
|
4 | * You may obtain a copy of the License at
|
5 | *
|
6 | * http://www.apache.org/licenses/LICENSE-2.0
|
7 | *
|
8 | * Unless required by applicable law or agreed to in writing, software
|
9 | * distributed under the License is distributed on an "AS IS" BASIS,
|
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
11 | * See the License for the specific language governing permissions and
|
12 | * limitations under the License.
|
13 | */
|
14 |
|
15 | ;
|
16 |
|
17 | const toslateutil = require('./toslateutil');
|
18 | const commonmarktoslaterules = require('./commonmarktoslaterules');
|
19 |
|
20 | /**
|
21 | * Converts a Markdown DOM to a Slate DOM
|
22 | */
|
23 | class ToSlateVisitor {
|
24 | /**
|
25 | * Constructor for a new visitor to slate
|
26 | * @param {*} rules - additional rules
|
27 | */
|
28 | constructor(rules) {
|
29 | this.rules = commonmarktoslaterules;
|
30 | if (rules) {
|
31 | this.rules = Object.assign(this.rules,rules);
|
32 | }
|
33 | }
|
34 |
|
35 | /**
|
36 | * Returns the processed children
|
37 | * @param {*} thing a concerto ast node
|
38 | * @param {string} fieldName name of the field containing the children
|
39 | * @param {*} parameters the parameters
|
40 | * @returns {*} an array of slate nodes
|
41 | */
|
42 | processChildren(thing,fieldName,parameters) {
|
43 | const result = [];
|
44 | const nodes = thing[fieldName] ? thing[fieldName] : [];
|
45 |
|
46 | nodes.forEach(node => {
|
47 | //console.log(`Processing ${thing.getType()} > ${node.getType()}`);
|
48 | const newParameters = {
|
49 | serializer: parameters.serializer,
|
50 | strong: parameters.strong,
|
51 | emph: parameters.emph,
|
52 | };
|
53 | node.accept(this, newParameters);
|
54 | if (Array.isArray(newParameters.result)) {
|
55 | Array.prototype.push.apply(result,newParameters.result);
|
56 | } else {
|
57 | result.push(newParameters.result);
|
58 | }
|
59 | });
|
60 |
|
61 | return result;
|
62 | }
|
63 |
|
64 | /**
|
65 | * Visit a concerto ast node and return the corresponding slate node
|
66 | * @param {*} thing the object being visited
|
67 | * @param {*} parameters the parameters
|
68 | */
|
69 | visit(thing, parameters) {
|
70 |
|
71 | let result = null;
|
72 |
|
73 | const processChildren = (thing,fieldName,parameters) => {
|
74 | return this.processChildren(thing,fieldName,parameters);
|
75 | };
|
76 |
|
77 | const rule = this.rules[thing.getType()];
|
78 | if (!rule) {
|
79 | throw new Error(`Unhandled type ${thing.getType()}`);
|
80 | }
|
81 | result = rule(thing,processChildren,parameters);
|
82 |
|
83 | const cleanResult = toslateutil.cleanup(result);
|
84 | parameters.result = cleanResult;
|
85 | }
|
86 | }
|
87 |
|
88 | module.exports = ToSlateVisitor; |
\ | No newline at end of file |