2.2 KB82 lines
Blame
1import type { CstNode, GrammarAST, ValueType } from 'langium';
2import { DefaultValueConverter } from 'langium';
3
4import { accessibilityDescrRegex, accessibilityTitleRegex, titleRegex } from './matcher.js';
5
6const rulesRegexes: Record<string, RegExp> = {
7 ACC_DESCR: accessibilityDescrRegex,
8 ACC_TITLE: accessibilityTitleRegex,
9 TITLE: titleRegex,
10};
11
12export abstract class AbstractMermaidValueConverter extends DefaultValueConverter {
13 /**
14 * A method contains convert logic to be used by class.
15 *
16 * @param rule - Parsed rule.
17 * @param input - Matched string.
18 * @param cstNode - Node in the Concrete Syntax Tree (CST).
19 * @returns converted the value if it's available or `undefined` if it's not.
20 */
21 protected abstract runCustomConverter(
22 rule: GrammarAST.AbstractRule,
23 input: string,
24 cstNode: CstNode
25 ): ValueType | undefined;
26
27 protected override runConverter(
28 rule: GrammarAST.AbstractRule,
29 input: string,
30 cstNode: CstNode
31 ): ValueType {
32 let value: ValueType | undefined = this.runCommonConverter(rule, input, cstNode);
33
34 if (value === undefined) {
35 value = this.runCustomConverter(rule, input, cstNode);
36 }
37 if (value === undefined) {
38 return super.runConverter(rule, input, cstNode);
39 }
40
41 return value;
42 }
43
44 private runCommonConverter(
45 rule: GrammarAST.AbstractRule,
46 input: string,
47 _cstNode: CstNode
48 ): ValueType | undefined {
49 const regex: RegExp | undefined = rulesRegexes[rule.name];
50 if (regex === undefined) {
51 return undefined;
52 }
53 const match = regex.exec(input);
54 if (match === null) {
55 return undefined;
56 }
57 // single line title, accTitle, accDescr
58 if (match[1] !== undefined) {
59 return match[1].trim().replace(/[\t ]{2,}/gm, ' ');
60 }
61 // multi line accDescr
62 if (match[2] !== undefined) {
63 return match[2]
64 .replace(/^\s*/gm, '')
65 .replace(/\s+$/gm, '')
66 .replace(/[\t ]{2,}/gm, ' ')
67 .replace(/[\n\r]{2,}/gm, '\n');
68 }
69 return undefined;
70 }
71}
72
73export class CommonValueConverter extends AbstractMermaidValueConverter {
74 protected override runCustomConverter(
75 _rule: GrammarAST.AbstractRule,
76 _input: string,
77 _cstNode: CstNode
78 ): ValueType | undefined {
79 return undefined;
80 }
81}
82