circuitscript 0.0.21 → 0.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/dist/cjs/antlr/CircuitScriptLexer.js +288 -0
  2. package/dist/cjs/antlr/CircuitScriptParser.js +4905 -0
  3. package/dist/cjs/antlr/CircuitScriptVisitor.js +6 -0
  4. package/{src/draw_symbols.ts → dist/cjs/draw_symbols.js} +303 -614
  5. package/dist/cjs/execute.js +780 -0
  6. package/{src/export.ts → dist/cjs/export.js} +34 -56
  7. package/dist/cjs/fonts.js +4 -0
  8. package/dist/cjs/geometry.js +430 -0
  9. package/dist/cjs/globals.js +60 -0
  10. package/dist/cjs/helpers.js +99 -0
  11. package/dist/cjs/index.js +29 -0
  12. package/{src/layout.ts → dist/cjs/layout.js} +413 -1002
  13. package/dist/cjs/lexer.js +114 -0
  14. package/dist/cjs/logger.js +17 -0
  15. package/dist/cjs/main.js +87 -0
  16. package/dist/cjs/objects/ClassComponent.js +142 -0
  17. package/dist/cjs/objects/ExecutionScope.js +134 -0
  18. package/dist/cjs/objects/Frame.js +22 -0
  19. package/{src/objects/Net.ts → dist/cjs/objects/Net.js} +9 -24
  20. package/dist/cjs/objects/ParamDefinition.js +42 -0
  21. package/dist/cjs/objects/PinDefinition.js +31 -0
  22. package/dist/cjs/objects/PinTypes.js +11 -0
  23. package/dist/cjs/objects/Wire.js +9 -0
  24. package/dist/cjs/objects/types.js +9 -0
  25. package/dist/cjs/parser.js +299 -0
  26. package/dist/cjs/regenerate-tests.js +23 -0
  27. package/dist/cjs/render.js +155 -0
  28. package/{src/server.ts → dist/cjs/server.js} +15 -21
  29. package/dist/cjs/sizing.js +105 -0
  30. package/{src/utils.ts → dist/cjs/utils.js} +25 -35
  31. package/{src/visitor.ts → dist/cjs/visitor.js} +392 -948
  32. package/{build/src/antlr/CircuitScriptLexer.js → dist/esm/antlr/CircuitScriptLexer.mjs} +90 -91
  33. package/{build/src/antlr/CircuitScriptParser.js → dist/esm/antlr/CircuitScriptParser.mjs} +138 -136
  34. package/{build/src/draw_symbols.js → dist/esm/draw_symbols.mjs} +11 -11
  35. package/{build/src/execute.js → dist/esm/execute.mjs} +9 -8
  36. package/{build/src/export.js → dist/esm/export.mjs} +2 -2
  37. package/{build/src/geometry.js → dist/esm/geometry.mjs} +3 -7
  38. package/{build/src/helpers.js → dist/esm/helpers.mjs} +27 -7
  39. package/dist/esm/index.mjs +13 -0
  40. package/{build/src/layout.js → dist/esm/layout.mjs} +11 -11
  41. package/{build/src/lexer.js → dist/esm/lexer.mjs} +2 -2
  42. package/{build/src/main.js → dist/esm/main.mjs} +5 -5
  43. package/{build/src/objects/ClassComponent.js → dist/esm/objects/ClassComponent.mjs} +3 -3
  44. package/{build/src/objects/PinDefinition.js → dist/esm/objects/PinDefinition.mjs} +1 -1
  45. package/dist/esm/parser.mjs +269 -0
  46. package/{build/src/regenerate-tests.js → dist/esm/regenerate-tests.mjs} +1 -1
  47. package/{build/src/render.js → dist/esm/render.mjs} +7 -24
  48. package/{build/src/sizing.js → dist/esm/sizing.mjs} +22 -8
  49. package/{build/src/visitor.js → dist/esm/visitor.mjs} +10 -29
  50. package/dist/types/antlr/CircuitScriptLexer.d.ts +71 -0
  51. package/dist/types/antlr/CircuitScriptParser.d.ts +675 -0
  52. package/dist/types/antlr/CircuitScriptVisitor.d.ts +115 -0
  53. package/dist/types/draw_symbols.d.ts +162 -0
  54. package/dist/types/execute.d.ts +85 -0
  55. package/dist/types/export.d.ts +2 -0
  56. package/dist/types/fonts.d.ts +1 -0
  57. package/dist/types/geometry.d.ts +84 -0
  58. package/dist/types/globals.d.ts +50 -0
  59. package/dist/types/helpers.d.ts +9 -0
  60. package/dist/types/index.d.ts +13 -0
  61. package/dist/types/layout.d.ts +147 -0
  62. package/dist/types/lexer.d.ts +19 -0
  63. package/dist/types/logger.d.ts +6 -0
  64. package/dist/types/main.d.ts +2 -0
  65. package/dist/types/objects/ClassComponent.d.ts +40 -0
  66. package/dist/types/objects/ExecutionScope.d.ts +64 -0
  67. package/dist/types/objects/Frame.d.ts +15 -0
  68. package/dist/types/objects/Net.d.ts +10 -0
  69. package/dist/types/objects/ParamDefinition.d.ts +20 -0
  70. package/dist/types/objects/PinDefinition.d.ts +24 -0
  71. package/dist/types/objects/PinTypes.d.ts +7 -0
  72. package/dist/types/objects/Wire.d.ts +11 -0
  73. package/dist/types/objects/types.d.ts +49 -0
  74. package/dist/types/parser.d.ts +38 -0
  75. package/dist/types/regenerate-tests.d.ts +1 -0
  76. package/dist/types/render.d.ts +10 -0
  77. package/dist/types/server.d.ts +1 -0
  78. package/dist/types/sizing.d.ts +15 -0
  79. package/dist/types/utils.d.ts +19 -0
  80. package/dist/types/visitor.d.ts +135 -0
  81. package/package.json +30 -12
  82. package/.editorconfig +0 -15
  83. package/.eslintignore +0 -1
  84. package/.eslintrc.json +0 -27
  85. package/.gitlab-ci.yml +0 -81
  86. package/.prettierignore +0 -8
  87. package/.prettierrc +0 -16
  88. package/__tests__/expectedResults.ts +0 -657
  89. package/__tests__/helpers.ts +0 -82
  90. package/__tests__/parseScripts.ts +0 -593
  91. package/__tests__/renderData/script1.cst +0 -58
  92. package/__tests__/renderData/script1.cst.svg +0 -1
  93. package/__tests__/renderData/script2.cst +0 -16
  94. package/__tests__/renderData/script2.cst.svg +0 -1
  95. package/__tests__/renderData/script3.cst +0 -30
  96. package/__tests__/renderData/script3.cst.svg +0 -1
  97. package/__tests__/renderData/script4.cst +0 -54
  98. package/__tests__/renderData/script4.cst.svg +0 -1
  99. package/__tests__/renderData/script5.cst +0 -23
  100. package/__tests__/renderData/script5.cst.svg +0 -1
  101. package/__tests__/renderData/script6.cst +0 -28
  102. package/__tests__/renderData/script6.cst.svg +0 -1
  103. package/__tests__/renderData/script7.cst +0 -26
  104. package/__tests__/renderData/script7.cst.svg +0 -1
  105. package/__tests__/renderData/script8.cst +0 -37
  106. package/__tests__/renderData/script8.cst.svg +0 -1
  107. package/__tests__/testCLI.ts +0 -68
  108. package/__tests__/testMathOps.ts +0 -36
  109. package/__tests__/testMergeWires.ts +0 -141
  110. package/__tests__/testParse.ts +0 -263
  111. package/__tests__/testRender.ts +0 -38
  112. package/build/src/parser.js +0 -69
  113. package/documentation.md +0 -238
  114. package/examples/example_arduino_uno.cst +0 -1146
  115. package/examples/example_garden_pump.cst +0 -567
  116. package/examples/lib.cst +0 -185
  117. package/fonts/Inter-Bold.ttf +0 -0
  118. package/fonts/Inter-Regular.ttf +0 -0
  119. package/fonts/OpenSans-Regular.ttf +0 -0
  120. package/fonts/Roboto-Regular.ttf +0 -0
  121. package/jest.config.js +0 -23
  122. package/libs/lib.cst +0 -185
  123. package/refresh.html +0 -42
  124. package/server.cjs +0 -50
  125. package/src/antlr/CircuitScript.g4 +0 -209
  126. package/src/antlr/CircuitScriptLexer.ts +0 -317
  127. package/src/antlr/CircuitScriptParser.ts +0 -4979
  128. package/src/antlr/CircuitScriptVisitor.ts +0 -420
  129. package/src/execute.ts +0 -1227
  130. package/src/fonts.ts +0 -1
  131. package/src/geometry.ts +0 -638
  132. package/src/globals.ts +0 -67
  133. package/src/helpers.ts +0 -114
  134. package/src/lexer.ts +0 -151
  135. package/src/logger.ts +0 -17
  136. package/src/main.ts +0 -105
  137. package/src/objects/ClassComponent.ts +0 -223
  138. package/src/objects/ExecutionScope.ts +0 -201
  139. package/src/objects/Frame.ts +0 -20
  140. package/src/objects/ParamDefinition.ts +0 -49
  141. package/src/objects/PinDefinition.ts +0 -49
  142. package/src/objects/PinTypes.ts +0 -7
  143. package/src/objects/Wire.ts +0 -19
  144. package/src/objects/types.ts +0 -66
  145. package/src/parser.ts +0 -106
  146. package/src/regenerate-tests.ts +0 -25
  147. package/src/render.ts +0 -260
  148. package/src/sizing.ts +0 -96
  149. package/tsconfig.json +0 -26
  150. package/tsconfig.release.json +0 -8
  151. /package/{build/src/antlr/CircuitScriptVisitor.js → dist/esm/antlr/CircuitScriptVisitor.mjs} +0 -0
  152. /package/{build/src/fonts.js → dist/esm/fonts.mjs} +0 -0
  153. /package/{build/src/globals.js → dist/esm/globals.mjs} +0 -0
  154. /package/{build/src/logger.js → dist/esm/logger.mjs} +0 -0
  155. /package/{build/src/objects/ExecutionScope.js → dist/esm/objects/ExecutionScope.mjs} +0 -0
  156. /package/{build/src/objects/Frame.js → dist/esm/objects/Frame.mjs} +0 -0
  157. /package/{build/src/objects/Net.js → dist/esm/objects/Net.mjs} +0 -0
  158. /package/{build/src/objects/ParamDefinition.js → dist/esm/objects/ParamDefinition.mjs} +0 -0
  159. /package/{build/src/objects/PinTypes.js → dist/esm/objects/PinTypes.mjs} +0 -0
  160. /package/{build/src/objects/Wire.js → dist/esm/objects/Wire.mjs} +0 -0
  161. /package/{build/src/objects/types.js → dist/esm/objects/types.mjs} +0 -0
  162. /package/{build/src/server.js → dist/esm/server.mjs} +0 -0
  163. /package/{build/src/utils.js → dist/esm/utils.mjs} +0 -0
@@ -0,0 +1,299 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.CircuitscriptParserErrorListener = exports.SemanticTokensVisitor = exports.parseFileWithVisitor = void 0;
27
+ const antlr4_1 = require("antlr4");
28
+ const CircuitScriptParser_js_1 = __importStar(require("./antlr/CircuitScriptParser.js"));
29
+ const lexer_js_1 = require("./lexer.js");
30
+ const utils_js_1 = require("./utils.js");
31
+ function parseFileWithVisitor(visitor, data) {
32
+ const chars = new antlr4_1.CharStream(data);
33
+ const lexer = new lexer_js_1.MainLexer(chars);
34
+ const lexerTimer = new utils_js_1.SimpleStopwatch();
35
+ const tokens = new antlr4_1.CommonTokenStream(lexer);
36
+ tokens.fill();
37
+ const lexerTimeTaken = lexerTimer.lap();
38
+ const parserTimer = new utils_js_1.SimpleStopwatch();
39
+ const parser = new CircuitScriptParser_js_1.default(tokens);
40
+ parser.removeErrorListeners();
41
+ const errorListener = new CircuitscriptParserErrorListener();
42
+ parser.addErrorListener(errorListener);
43
+ const tree = parser.script();
44
+ let hasError = false;
45
+ try {
46
+ visitor.visit(tree);
47
+ }
48
+ catch (err) {
49
+ err.print(data);
50
+ hasError = true;
51
+ }
52
+ const parserTimeTaken = parserTimer.lap();
53
+ const semanticTokenVisitor = new SemanticTokensVisitor(lexer, data);
54
+ semanticTokenVisitor.visit(tree);
55
+ const semanticTokens = semanticTokenVisitor.semanticTokens;
56
+ const parsedTokens = prepareTokens(tokens.tokens, lexer, data);
57
+ const finalParsedTokens = [];
58
+ parsedTokens.forEach(token => {
59
+ const location = `${token.line}_${token.column}`;
60
+ if (semanticTokens.has(location)) {
61
+ finalParsedTokens.push(semanticTokens.get(location));
62
+ }
63
+ else {
64
+ finalParsedTokens.push(token);
65
+ }
66
+ });
67
+ return {
68
+ tree, parser,
69
+ hasParseError: errorListener.hasParseErrors(),
70
+ hasError,
71
+ parserTimeTaken,
72
+ lexerTimeTaken,
73
+ tokens: finalParsedTokens,
74
+ };
75
+ }
76
+ exports.parseFileWithVisitor = parseFileWithVisitor;
77
+ class SemanticTokensVisitor extends antlr4_1.ParseTreeVisitor {
78
+ constructor(lexer, script) {
79
+ super();
80
+ this.parsedTokens = [];
81
+ this.semanticTokens = new Map();
82
+ this.lexer = lexer;
83
+ this.script = script;
84
+ }
85
+ visit(ctx) {
86
+ const here = this;
87
+ if (Array.isArray(ctx)) {
88
+ return ctx.map(function (child) {
89
+ try {
90
+ here.checkContext(child);
91
+ return child.accept(this);
92
+ }
93
+ catch (err) {
94
+ this.handleError(child, err);
95
+ }
96
+ }, this);
97
+ }
98
+ else {
99
+ try {
100
+ this.checkContext(ctx);
101
+ return ctx.accept(this);
102
+ }
103
+ catch (err) {
104
+ this.handleError(ctx, err);
105
+ }
106
+ }
107
+ }
108
+ handleError(ctx, err) {
109
+ console.log('error!', err);
110
+ }
111
+ checkContext(ctx) {
112
+ if (ctx instanceof CircuitScriptParser_js_1.Function_def_exprContext) {
113
+ this.addSemanticToken(this.parseToken(ctx.ID(), ['declaration'], 'function'));
114
+ }
115
+ else if (ctx instanceof CircuitScriptParser_js_1.Create_component_exprContext
116
+ || ctx instanceof CircuitScriptParser_js_1.Create_graphic_exprContext) {
117
+ this.addSemanticToken(this.parseToken(ctx.Create(), ['defaultLibrary'], 'function'));
118
+ }
119
+ else if (ctx instanceof CircuitScriptParser_js_1.Atom_exprContext) {
120
+ if (ctx.ID()) {
121
+ if (ctx.trailer_expr_list().length > 0) {
122
+ this.addSemanticToken(this.parseToken(ctx.ID(), ['declaration'], 'function'));
123
+ }
124
+ else {
125
+ this.addSemanticToken(this.parseToken(ctx.ID(), ['declaration'], 'variable'));
126
+ }
127
+ }
128
+ }
129
+ else if (ctx instanceof CircuitScriptParser_js_1.Property_key_exprContext) {
130
+ let useToken = null;
131
+ if (ctx.ID()) {
132
+ useToken = ctx.ID();
133
+ }
134
+ else if (ctx.INTEGER_VALUE()) {
135
+ useToken = ctx.INTEGER_VALUE();
136
+ }
137
+ else if (ctx.STRING_VALUE()) {
138
+ useToken = ctx.STRING_VALUE();
139
+ }
140
+ useToken && this.addSemanticToken(this.parseToken(useToken, ['declaration'], 'property'));
141
+ }
142
+ else if (ctx instanceof CircuitScriptParser_js_1.Sub_exprContext) {
143
+ let useToken = null;
144
+ if (ctx.ID()) {
145
+ useToken = ctx.ID();
146
+ }
147
+ else if (ctx.Pin()) {
148
+ useToken = ctx.Pin();
149
+ }
150
+ useToken && this.addSemanticToken(this.parseToken(useToken, ['defaultLibrary'], 'function'));
151
+ }
152
+ }
153
+ addSemanticToken(parsedToken) {
154
+ this.semanticTokens.set(parsedToken.line + "_" + parsedToken.column, parsedToken);
155
+ }
156
+ parseToken(node, modifiers, tokenType = null) {
157
+ const token = node.symbol;
158
+ let stringValue = "";
159
+ let textPart = "";
160
+ if (this.lexer.symbolicNames[token.type] !== null && this.lexer.symbolicNames[token.type] !== undefined) {
161
+ stringValue = this.lexer.symbolicNames[token.type];
162
+ if (stringValue !== "NEWLINE") {
163
+ textPart = this.script.substring(token.start, token.stop + 1);
164
+ }
165
+ else {
166
+ textPart = token.text.length - 1;
167
+ }
168
+ }
169
+ else if (this.lexer.literalNames[token.type] !== null && this.lexer.literalNames[token.type] !== undefined) {
170
+ stringValue = this.lexer.literalNames[token.type];
171
+ textPart = this.script.substring(token.start, token.stop + 1);
172
+ }
173
+ else {
174
+ stringValue = token._text;
175
+ }
176
+ return {
177
+ line: token.line,
178
+ column: token.column,
179
+ length: token.stop - token.start + 1,
180
+ tokenType: tokenType !== null ? tokenType : stringValue,
181
+ tokenModifiers: modifiers,
182
+ textValue: textPart,
183
+ };
184
+ }
185
+ }
186
+ exports.SemanticTokensVisitor = SemanticTokensVisitor;
187
+ function prepareTokens(tokens, lexer, script) {
188
+ const parsedTokens = [];
189
+ tokens.forEach(item => {
190
+ if (item.type !== -1) {
191
+ let stringValue = "";
192
+ let textPart = "";
193
+ if (lexer.symbolicNames[item.type] !== null && lexer.symbolicNames[item.type] !== undefined) {
194
+ stringValue = lexer.symbolicNames[item.type];
195
+ if (stringValue !== "NEWLINE") {
196
+ textPart = script.substring(item.start, item.stop + 1);
197
+ }
198
+ else {
199
+ textPart = item.text.length - 1;
200
+ }
201
+ }
202
+ else if (lexer.literalNames[item.type] !== null && lexer.literalNames[item.type] !== undefined) {
203
+ stringValue = lexer.literalNames[item.type];
204
+ textPart = script.substring(item.start, item.stop + 1);
205
+ }
206
+ else {
207
+ stringValue = item._text;
208
+ }
209
+ if (textPart !== 0 && textPart !== '') {
210
+ parsedTokens.push({
211
+ line: item.line,
212
+ column: item.column,
213
+ length: item.stop - item.start + 1,
214
+ tokenType: resolveTokenType(stringValue),
215
+ tokenModifiers: resolveTokenModifiers(stringValue),
216
+ textValue: textPart,
217
+ });
218
+ }
219
+ }
220
+ });
221
+ return parsedTokens;
222
+ }
223
+ const languageKeywords = [
224
+ 'break', 'branch', 'create', 'component',
225
+ 'graphic', 'wire', 'pin', 'add', 'at', 'to',
226
+ 'point', 'join', 'parallel', 'return', 'def', 'import',
227
+ 'true', 'false', 'nc', 'frame',
228
+ ];
229
+ const operatorKeywords = [
230
+ 'at', 'to', 'wire', 'add', 'frame', 'join', 'parallel', 'point'
231
+ ];
232
+ function resolveTokenType(tokenType) {
233
+ if (operatorKeywords.indexOf(tokenType.toLowerCase()) !== -1) {
234
+ return 'graphKeyword';
235
+ }
236
+ else if (languageKeywords.indexOf(tokenType.toLowerCase()) !== -1) {
237
+ return 'keyword';
238
+ }
239
+ else {
240
+ switch (tokenType) {
241
+ case 'INTEGER_VALUE':
242
+ case 'NUMERIC_VALUE':
243
+ case 'DECIMAL_VALUE':
244
+ case 'PERCENTAGE_VALUE':
245
+ return 'number';
246
+ case 'STRING_VALUE':
247
+ return 'string';
248
+ case 'ID':
249
+ return 'variable';
250
+ case 'Define':
251
+ return 'keyword';
252
+ case 'COMMENT':
253
+ return 'comment';
254
+ }
255
+ return null;
256
+ }
257
+ }
258
+ function resolveTokenModifiers(tokenType) {
259
+ return [];
260
+ }
261
+ function dumpTokens(tokens, lexer, scriptData) {
262
+ tokens.forEach(item => {
263
+ if (item.type !== -1) {
264
+ let stringValue = "";
265
+ let textPart = "";
266
+ if (lexer.symbolicNames[item.type] !== null && lexer.symbolicNames[item.type] !== undefined) {
267
+ stringValue = lexer.symbolicNames[item.type];
268
+ if (stringValue !== "NEWLINE") {
269
+ textPart = scriptData.substring(item.start, item.stop + 1);
270
+ }
271
+ else {
272
+ textPart = item.text.length - 1;
273
+ }
274
+ }
275
+ else if (lexer.literalNames[item.type] !== null && lexer.literalNames[item.type] !== undefined) {
276
+ stringValue = lexer.literalNames[item.type];
277
+ textPart = scriptData.substring(item.start, item.stop + 1);
278
+ }
279
+ else {
280
+ stringValue = item._text;
281
+ }
282
+ console.log('line', item.line + ':' + item.column, `\t${stringValue} (${item.type})`.padEnd(30), textPart);
283
+ }
284
+ });
285
+ }
286
+ class CircuitscriptParserErrorListener extends antlr4_1.ErrorListener {
287
+ constructor() {
288
+ super(...arguments);
289
+ this.syntaxErrorCounter = 0;
290
+ }
291
+ syntaxError(recognizer, offendingSymbol, line, column, msg, e) {
292
+ console.log("Syntax error at line", line, ':', column, ' - ', msg);
293
+ this.syntaxErrorCounter++;
294
+ }
295
+ hasParseErrors() {
296
+ return (this.syntaxErrorCounter > 0);
297
+ }
298
+ }
299
+ exports.CircuitscriptParserErrorListener = CircuitscriptParserErrorListener;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const fs_1 = __importDefault(require("fs"));
7
+ const helpers_js_1 = require("./helpers.js");
8
+ const mainDir = './__tests__/renderData/';
9
+ const cstFiles = [];
10
+ const files = fs_1.default.readdirSync(mainDir);
11
+ files.forEach(file => {
12
+ if (file.endsWith('.cst')) {
13
+ cstFiles.push(file);
14
+ }
15
+ });
16
+ const useCurrentDir = './examples/';
17
+ cstFiles.forEach(file => {
18
+ const inputPath = mainDir + file;
19
+ const scriptData = fs_1.default.readFileSync(inputPath, { encoding: 'utf-8' });
20
+ const outputPath = inputPath + '.svg';
21
+ (0, helpers_js_1.renderScript)(scriptData, outputPath, { currentDirectory: useCurrentDir });
22
+ console.log('generated ', outputPath);
23
+ });
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateSVG2 = void 0;
4
+ const svg_js_1 = require("@svgdotjs/svg.js");
5
+ const layout_js_1 = require("./layout.js");
6
+ const sizing_js_1 = require("./sizing.js");
7
+ const globals_js_1 = require("./globals.js");
8
+ const ParamDefinition_js_1 = require("./objects/ParamDefinition.js");
9
+ const utils_js_1 = require("./utils.js");
10
+ function generateSVG2(graph) {
11
+ const window = (0, sizing_js_1.getCreateSVGWindow)()();
12
+ const document = window.document;
13
+ (0, svg_js_1.registerWindow)(window, document);
14
+ const canvas = (0, svg_js_1.SVG)(document.documentElement);
15
+ (0, sizing_js_1.applyFontsToSVG)(canvas);
16
+ generateSVGChild(canvas, graph.components, graph.wires, graph.junctions, graph.mergedWires, graph.frameObjects, graph.textObjects);
17
+ const { x, y, width, height } = canvas.bbox();
18
+ const margin = 5;
19
+ const widthAndMargin = width + margin * 2;
20
+ const heightAndMargin = height + margin * 2;
21
+ const scale = 1;
22
+ canvas.size(widthAndMargin * scale, heightAndMargin * scale);
23
+ canvas.viewbox(x - margin, y - margin, widthAndMargin, heightAndMargin);
24
+ return canvas.svg();
25
+ }
26
+ exports.generateSVG2 = generateSVG2;
27
+ function generateSVGChild(canvas, components, wires, junctions, mergedWires, frameObjects, textObjects) {
28
+ const displayWireId = false;
29
+ const bounds = (0, layout_js_1.getBounds)(components, wires, junctions, frameObjects);
30
+ drawGrid(canvas.group().translate(0, 0), {
31
+ x: bounds.xmin,
32
+ y: bounds.ymin,
33
+ x2: bounds.xmax,
34
+ y2: bounds.ymax
35
+ });
36
+ components.forEach(item => {
37
+ const { x, y, width, height } = item;
38
+ const symbolGroup = canvas.group();
39
+ symbolGroup.translate(x, y);
40
+ const { symbol = null } = item;
41
+ if (symbol !== null && symbol) {
42
+ const extra = {};
43
+ if (item.component.parameters.has('__is_net')) {
44
+ extra.net_name = item.component.parameters.get(globals_js_1.ParamKeys.net_name);
45
+ }
46
+ else if (item.component.parameters.has('value')) {
47
+ let tmpValue = item.component.parameters.get('value');
48
+ if (tmpValue instanceof ParamDefinition_js_1.NumericValue) {
49
+ tmpValue = tmpValue.value;
50
+ }
51
+ extra.value = tmpValue;
52
+ }
53
+ extra.instance_name = item.component.instanceName;
54
+ if (item.component.parameters.has('place')) {
55
+ extra.place = item.component.parameters.get('place');
56
+ }
57
+ else {
58
+ extra.place = true;
59
+ }
60
+ symbol.draw(symbolGroup, extra);
61
+ }
62
+ else {
63
+ symbolGroup.rect(width, height)
64
+ .fill(globals_js_1.bodyColor)
65
+ .stroke({ width: 1, color: '#333' });
66
+ }
67
+ });
68
+ if (displayWireId) {
69
+ const wiresGroup = canvas.group().translate(0, 0);
70
+ wires.forEach(wire => {
71
+ wiresGroup.text(wire.id.toString())
72
+ .font({
73
+ family: 'Inter',
74
+ size: 10,
75
+ })
76
+ .translate(wire.x + 5, wire.y + 5);
77
+ });
78
+ }
79
+ const mergedWireGroup = canvas.group();
80
+ mergedWires.forEach(tmpItem => {
81
+ const { segments, intersectPoints } = tmpItem;
82
+ segments.forEach(segment => {
83
+ const pt1 = segment[0];
84
+ const pt2 = segment[1];
85
+ mergedWireGroup.line([pt1, pt2])
86
+ .stroke({ width: 1, color: globals_js_1.wireColor, linecap: 'square' })
87
+ .fill('none');
88
+ });
89
+ intersectPoints.forEach(point => {
90
+ const [x, y, count] = point;
91
+ mergedWireGroup.circle(globals_js_1.junctionSize)
92
+ .translate(x - globals_js_1.junctionSize / 2, y - globals_js_1.junctionSize / 2)
93
+ .fill(globals_js_1.junctionColor)
94
+ .stroke('none');
95
+ });
96
+ });
97
+ const frameGroup = canvas.group();
98
+ const showElementFrames = false;
99
+ frameObjects.forEach(item => {
100
+ const { bounds, borderWidth } = item;
101
+ if (borderWidth > 0) {
102
+ const { width, height } = (0, utils_js_1.getBoundsSize)(bounds);
103
+ let strokeColor = '#111';
104
+ if (item.type === layout_js_1.RenderFrameType.Container) {
105
+ strokeColor = '#111';
106
+ }
107
+ else if (item.type === layout_js_1.RenderFrameType.Elements) {
108
+ strokeColor = '#aaa';
109
+ if (!showElementFrames) {
110
+ return;
111
+ }
112
+ }
113
+ const tmpRect = frameGroup.rect(width, height)
114
+ .fill('none')
115
+ .stroke({ width: borderWidth, color: strokeColor });
116
+ tmpRect.translate(item.x, item.y);
117
+ }
118
+ });
119
+ textObjects.forEach(item => {
120
+ const { x, y, symbol } = item;
121
+ const innerGroup = canvas.group();
122
+ innerGroup.translate(x, y);
123
+ symbol.draw(innerGroup);
124
+ });
125
+ const drawOrigin = false;
126
+ drawOrigin && canvas.group().translate(0, 0)
127
+ .circle(5)
128
+ .translate(-5 / 2, -5 / 2)
129
+ .stroke('none').fill('red');
130
+ }
131
+ function drawGrid(group, canvasSize) {
132
+ const gridSize = 20;
133
+ const { x, y, x2, y2 } = canvasSize;
134
+ const gridStartX = (Math.floor(x / gridSize) - 1) * gridSize;
135
+ const gridStartY = (Math.floor(y / gridSize) - 1) * gridSize;
136
+ const gridEndX = (Math.ceil(x2 / gridSize) + 1) * gridSize;
137
+ const gridEndY = (Math.ceil(y2 / gridSize) + 1) * gridSize;
138
+ const numCols = Math.ceil((gridEndX - gridStartX) / gridSize);
139
+ const lines = [];
140
+ for (let i = 0; i <= numCols; i++) {
141
+ const startX = gridStartX + i * gridSize;
142
+ const startY = gridStartY - 0.5;
143
+ const endY = gridEndY;
144
+ lines.push(`M ${startX} ${startY} L ${startX} ${endY}`);
145
+ }
146
+ group.path(lines.join(" "))
147
+ .fill('none')
148
+ .attr({
149
+ 'stroke-dasharray': '1,' + (gridSize - 1),
150
+ })
151
+ .stroke({
152
+ width: 1,
153
+ color: '#aaa'
154
+ });
155
+ }
@@ -1,16 +1,17 @@
1
- import express from 'express';
2
- import ws from 'ws';
3
- import fs from 'fs';
4
-
5
- const app = express()
6
-
7
- const wsServer = new ws.Server({ noServer: true });
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const express_1 = __importDefault(require("express"));
7
+ const ws_1 = __importDefault(require("ws"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const app = (0, express_1.default)();
10
+ const wsServer = new ws_1.default.Server({ noServer: true });
8
11
  wsServer.on('connection', socket => {
9
-
10
12
  const fileName = 'output.svg';
11
-
12
- function emitFile(): void {
13
- fs.readFile(fileName, 'utf8', (err, data) => {
13
+ function emitFile() {
14
+ fs_1.default.readFile(fileName, 'utf8', (err, data) => {
14
15
  if (err) {
15
16
  throw err;
16
17
  }
@@ -18,33 +19,26 @@ wsServer.on('connection', socket => {
18
19
  socket.send(data);
19
20
  });
20
21
  }
21
-
22
22
  let emitTimeout = null;
23
- fs.watch(fileName, (event, targetFile) => {
23
+ fs_1.default.watch(fileName, (event, targetFile) => {
24
24
  if (event === 'change') {
25
25
  console.log((new Date()).toISOString(), 'file changed!');
26
-
27
- // emit the change
28
26
  clearInterval(emitTimeout);
29
27
  emitTimeout = setTimeout(() => {
30
28
  emitFile();
31
29
  }, 200);
32
30
  }
33
31
  });
34
-
35
32
  socket.on('message', message => {
36
33
  console.log(message.toString());
37
34
  emitFile();
38
35
  });
39
36
  });
40
-
41
- app.use(express.static('./'))
42
-
37
+ app.use(express_1.default.static('./'));
43
38
  const server = app.listen(3000);
44
39
  server.on('upgrade', (request, socket, head) => {
45
40
  wsServer.handleUpgrade(request, socket, head, socket => {
46
41
  wsServer.emit('connection', socket, request);
47
42
  });
48
43
  });
49
-
50
- console.log('server started at port 3000');
44
+ console.log('server started at port 3000');
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.measureTextSize2 = exports.measureTextSize = exports.applyFontsToSVG = exports.getCreateSVGWindow = exports.prepareSVGEnvironment = void 0;
27
+ const svg_js_1 = require("@svgdotjs/svg.js");
28
+ const geometry_js_1 = require("./geometry.js");
29
+ const globals_js_1 = require("./globals.js");
30
+ const helpers_js_1 = require("./helpers.js");
31
+ let MainCanvas = null;
32
+ const supportedFonts = {};
33
+ let globalCreateSVGWindow;
34
+ async function prepareSVGEnvironment(fontsPath) {
35
+ const moduleType = (0, helpers_js_1.detectJSModuleType)();
36
+ if (moduleType === helpers_js_1.JSModuleType.CommonJs) {
37
+ const { config, createSVGWindow } = await Promise.resolve().then(() => __importStar(require('svgdom')));
38
+ globalCreateSVGWindow = createSVGWindow;
39
+ if (fontsPath !== null) {
40
+ await config.setFontDir(fontsPath)
41
+ .setFontFamilyMappings(supportedFonts)
42
+ .preloadFonts();
43
+ }
44
+ }
45
+ }
46
+ exports.prepareSVGEnvironment = prepareSVGEnvironment;
47
+ function getCreateSVGWindow() {
48
+ if (globalCreateSVGWindow === undefined) {
49
+ throw "SVG environment is not set up yet";
50
+ }
51
+ return globalCreateSVGWindow;
52
+ }
53
+ exports.getCreateSVGWindow = getCreateSVGWindow;
54
+ function applyFontsToSVG(canvas) {
55
+ }
56
+ exports.applyFontsToSVG = applyFontsToSVG;
57
+ async function measureTextSize(text, fontFamily, fontSize) {
58
+ return measureTextSize2(text, fontFamily, fontSize);
59
+ }
60
+ exports.measureTextSize = measureTextSize;
61
+ const measureTextSizeCache = {};
62
+ const measureTextSizeCacheHits = {};
63
+ function measureTextSize2(text, fontFamily, fontSize, fontWeight = 'regular', anchor = geometry_js_1.HorizontalAlign.Left, vanchor = geometry_js_1.VerticalAlign.Bottom) {
64
+ if (MainCanvas === null) {
65
+ const window = getCreateSVGWindow()();
66
+ const { document } = window;
67
+ (0, svg_js_1.registerWindow)(window, document);
68
+ MainCanvas = (0, svg_js_1.SVG)(document.documentElement);
69
+ }
70
+ const key = `${text}-${fontFamily}-${fontSize}-${fontWeight}-${anchor}-${vanchor}`;
71
+ if (measureTextSizeCache[key] === undefined) {
72
+ let dominantBaseline = 'hanging';
73
+ switch (vanchor) {
74
+ case geometry_js_1.VerticalAlign.Top:
75
+ dominantBaseline = 'hanging';
76
+ break;
77
+ case geometry_js_1.VerticalAlign.Middle:
78
+ dominantBaseline = 'middle';
79
+ break;
80
+ case geometry_js_1.VerticalAlign.Bottom:
81
+ dominantBaseline = 'text-top';
82
+ break;
83
+ }
84
+ fontFamily = globals_js_1.defaultFont;
85
+ const tmpTextElement = MainCanvas.text(text).font({
86
+ family: fontFamily,
87
+ size: fontSize,
88
+ anchor: anchor,
89
+ 'dominant-baseline': dominantBaseline,
90
+ weight: fontWeight,
91
+ }).fill('#333');
92
+ const textbox = tmpTextElement.bbox();
93
+ const { width, height } = textbox;
94
+ tmpTextElement.remove();
95
+ measureTextSizeCache[key] = {
96
+ width: Math.round(width * 100) / 100,
97
+ height: Math.round(height * 100) / 100,
98
+ box: textbox,
99
+ };
100
+ measureTextSizeCacheHits[key] = 0;
101
+ }
102
+ measureTextSizeCacheHits[key]++;
103
+ return measureTextSizeCache[key];
104
+ }
105
+ exports.measureTextSize2 = measureTextSize2;