UNPKG

2.54 kBJavaScriptView Raw
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'use strict';
16
17const { NS_PREFIX_CommonMarkModel } = require('@accordproject/markdown-common').CommonMarkModel;
18
19/**
20 * Utility: flattening array of arrays
21 * @param {*[]} arr - input array of arrays
22 * @return {*[]} flattened array
23 */
24function flatten(arr) {
25 return arr.reduce((acc, val) => acc.concat(val), []);
26}
27
28/**
29 * Converts a CiceroMark DOM to a CommonMark DOM
30 */
31class ToCommonMarkVisitor {
32 /**
33 * Construct the visitor
34 */
35 constructor() {
36 }
37
38 /**
39 * Visits a sub-tree and return the CommonMark DOM
40 * @param {*} visitor the visitor to use
41 * @param {*} thing the node to visit
42 * @param {*} [parameters] optional parameters
43 */
44 static visitChildren(visitor, thing, parameters) {
45 if(thing.nodes) {
46 const result =
47 thing.nodes.map(node => {
48 return node.accept(visitor, parameters);
49 });
50 thing.nodes = flatten(result);
51 }
52 }
53
54 /**
55 * Visit a node
56 * @param {*} thing the object being visited
57 * @param {*} parameters the parameters
58 * @return {*[]} result nodes
59 */
60 visit(thing, parameters) {
61 const thingType = thing.getType();
62 switch(thingType) {
63 case 'Clause': {
64 ToCommonMarkVisitor.visitChildren(this, thing, parameters);
65 return thing.nodes;
66 }
67 case 'Formula': {
68 // Revert to HtmlInline
69 thing.$classDeclaration = parameters.modelManager.getType(NS_PREFIX_CommonMarkModel + 'Text');
70 thing.text = decodeURIComponent(thing.value);
71
72 delete thing.elementType;
73 delete thing.name;
74 delete thing.value;
75 delete thing.code;
76 delete thing.dependencies;
77 }
78 break;
79 default:
80 ToCommonMarkVisitor.visitChildren(this, thing, parameters);
81 }
82 return [thing];
83 }
84}
85
86module.exports = ToCommonMarkVisitor;
\No newline at end of file