UNPKG

2.75 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
17var CommonMarkUtils = require('@accordproject/markdown-common').CommonMarkUtils;
18var FromCommonMarkVisitor = require('@accordproject/markdown-common').FromCommonMarkVisitor;
19var fromcommonmarkrules = require('@accordproject/markdown-common').fromcommonmarkrules;
20var fromtemplatemarkrules = require('./fromtemplatemarkrules');
21
22/**
23 * Fixes up the root note, removing Clause or Contract indication
24 * @param {object} input the input templatemark
25 * @return {object} the fixed up templatemark
26 */
27function fixupRootNode(input) {
28 var rootNode = {
29 '$class': 'org.accordproject.commonmark.Document',
30 'xmlns': 'http://commonmark.org/xml/1.0',
31 'nodes': input.nodes[0].nodes
32 };
33 return rootNode;
34}
35
36/**
37 * Converts a TemplateMark DOM to a template markdown string.
38 */
39class ToMarkdownTemplateVisitor extends FromCommonMarkVisitor {
40 /**
41 * Construct the visitor.
42 * @param {object} [options] configuration options
43 * @param {*} resultSeq how to sequentially combine results
44 * @param {object} rules how to process each node type
45 */
46 constructor(options) {
47 var resultString = result => {
48 return result;
49 };
50 var resultSeq = (parameters, result) => {
51 result.forEach(next => {
52 parameters.result += next;
53 });
54 };
55 var setFirst = thingType => {
56 return thingType === 'Item' || thingType === 'ClauseDefinition' || thingType === 'ListBlockDefinition' ? true : false;
57 };
58 var rules = fromcommonmarkrules;
59 Object.assign(rules, fromtemplatemarkrules);
60 super(options, resultString, resultSeq, rules, setFirst);
61 }
62
63 /**
64 * Converts a TemplateMark DOM to a template markdown string.
65 * @param {*} serializer - TemplateMark serializer
66 * @param {*} input - TemplateMark DOM (JSON)
67 * @returns {string} the template markdown string
68 */
69 toMarkdownTemplate(serializer, input) {
70 var parameters = {};
71 var fixedInput = serializer.fromJSON(fixupRootNode(input));
72 parameters.result = this.resultString('');
73 parameters.stack = CommonMarkUtils.blocksInit();
74 fixedInput.accept(this, parameters);
75 return parameters.result.trim();
76 }
77}
78module.exports = ToMarkdownTemplateVisitor;
\No newline at end of file