circuitscript 0.0.22 → 0.0.25

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 (180) hide show
  1. package/dist/cjs/BaseVisitor.js +487 -0
  2. package/dist/cjs/SemanticTokenVisitor.js +218 -0
  3. package/dist/cjs/SymbolValidatorVisitor.js +233 -0
  4. package/dist/cjs/antlr/CircuitScriptLexer.js +302 -0
  5. package/dist/cjs/antlr/CircuitScriptParser.js +5128 -0
  6. package/dist/cjs/antlr/CircuitScriptVisitor.js +7 -0
  7. package/dist/cjs/draw_symbols.js +819 -0
  8. package/dist/cjs/execute.js +778 -0
  9. package/{src/export.ts → dist/cjs/export.js} +34 -56
  10. package/dist/cjs/fonts.js +4 -0
  11. package/dist/cjs/geometry.js +450 -0
  12. package/dist/cjs/globals.js +60 -0
  13. package/dist/cjs/helpers.js +269 -0
  14. package/dist/cjs/index.js +31 -0
  15. package/{src/layout.ts → dist/cjs/layout.js} +421 -1002
  16. package/dist/cjs/lexer.js +111 -0
  17. package/dist/cjs/logger.js +17 -0
  18. package/dist/cjs/main.js +82 -0
  19. package/dist/cjs/objects/ClassComponent.js +145 -0
  20. package/dist/cjs/objects/ExecutionScope.js +135 -0
  21. package/dist/cjs/objects/Frame.js +22 -0
  22. package/{src/objects/Net.ts → dist/cjs/objects/Net.js} +9 -24
  23. package/dist/cjs/objects/ParamDefinition.js +42 -0
  24. package/dist/cjs/objects/PinDefinition.js +31 -0
  25. package/dist/cjs/objects/PinTypes.js +11 -0
  26. package/dist/cjs/objects/Wire.js +9 -0
  27. package/dist/cjs/objects/types.js +15 -0
  28. package/dist/cjs/parser.js +70 -0
  29. package/dist/cjs/regenerate-tests.js +23 -0
  30. package/dist/cjs/render.js +155 -0
  31. package/{src/server.ts → dist/cjs/server.js} +15 -21
  32. package/dist/cjs/sizing.js +105 -0
  33. package/{src/utils.ts → dist/cjs/utils.js} +25 -35
  34. package/dist/cjs/validate.js +81 -0
  35. package/dist/cjs/visitor.js +844 -0
  36. package/dist/esm/BaseVisitor.mjs +488 -0
  37. package/dist/esm/SemanticTokenVisitor.mjs +215 -0
  38. package/dist/esm/SymbolValidatorVisitor.mjs +222 -0
  39. package/dist/esm/antlr/CircuitScriptLexer.mjs +276 -0
  40. package/dist/esm/antlr/CircuitScriptParser.mjs +5038 -0
  41. package/{build/src/antlr/CircuitScriptVisitor.js → dist/esm/antlr/CircuitScriptVisitor.mjs} +8 -3
  42. package/{build/src/draw_symbols.js → dist/esm/draw_symbols.mjs} +78 -33
  43. package/{build/src/execute.js → dist/esm/execute.mjs} +59 -60
  44. package/{build/src/export.js → dist/esm/export.mjs} +2 -2
  45. package/{build/src/geometry.js → dist/esm/geometry.mjs} +31 -15
  46. package/dist/esm/helpers.mjs +252 -0
  47. package/dist/esm/index.mjs +15 -0
  48. package/{build/src/layout.js → dist/esm/layout.mjs} +19 -11
  49. package/{build/src/lexer.js → dist/esm/lexer.mjs} +10 -10
  50. package/{build/src/main.js → dist/esm/main.mjs} +9 -14
  51. package/{build/src/objects/ClassComponent.js → dist/esm/objects/ClassComponent.mjs} +6 -3
  52. package/{build/src/objects/ExecutionScope.js → dist/esm/objects/ExecutionScope.mjs} +1 -0
  53. package/{build/src/objects/PinDefinition.js → dist/esm/objects/PinDefinition.mjs} +1 -1
  54. package/dist/esm/objects/types.mjs +12 -0
  55. package/dist/esm/parser.mjs +64 -0
  56. package/{build/src/regenerate-tests.js → dist/esm/regenerate-tests.mjs} +1 -1
  57. package/{build/src/render.js → dist/esm/render.mjs} +7 -24
  58. package/{build/src/sizing.js → dist/esm/sizing.mjs} +22 -8
  59. package/{src/main.ts → dist/esm/validate.mjs} +31 -62
  60. package/dist/esm/visitor.mjs +838 -0
  61. package/dist/types/BaseVisitor.d.ts +69 -0
  62. package/dist/types/SemanticTokenVisitor.d.ts +36 -0
  63. package/dist/types/SymbolValidatorVisitor.d.ts +61 -0
  64. package/{build/src → dist/types}/antlr/CircuitScriptLexer.d.ts +28 -27
  65. package/dist/types/antlr/CircuitScriptParser.d.ts +719 -0
  66. package/{build/src → dist/types}/antlr/CircuitScriptVisitor.d.ts +69 -59
  67. package/{build/src → dist/types}/draw_symbols.d.ts +11 -2
  68. package/{build/src → dist/types}/execute.d.ts +6 -9
  69. package/{build/src → dist/types}/geometry.d.ts +5 -1
  70. package/dist/types/helpers.d.ts +40 -0
  71. package/dist/types/index.d.ts +15 -0
  72. package/{build/src → dist/types}/layout.d.ts +10 -10
  73. package/{build/src → dist/types}/lexer.d.ts +2 -2
  74. package/{build/src → dist/types}/objects/ClassComponent.d.ts +2 -2
  75. package/{build/src → dist/types}/objects/ExecutionScope.d.ts +4 -1
  76. package/{build/src → dist/types}/objects/PinDefinition.d.ts +1 -1
  77. package/{build/src → dist/types}/objects/types.d.ts +5 -0
  78. package/dist/types/parser.d.ts +25 -0
  79. package/{build/src → dist/types}/render.d.ts +1 -1
  80. package/{build/src → dist/types}/sizing.d.ts +3 -1
  81. package/dist/types/validate.d.ts +2 -0
  82. package/dist/types/visitor.d.ts +80 -0
  83. package/libs/lib.cst +0 -2
  84. package/package.json +38 -15
  85. package/.editorconfig +0 -15
  86. package/.eslintignore +0 -1
  87. package/.eslintrc.json +0 -27
  88. package/.gitlab-ci.yml +0 -81
  89. package/.prettierignore +0 -8
  90. package/.prettierrc +0 -16
  91. package/__tests__/expectedResults.ts +0 -657
  92. package/__tests__/helpers.ts +0 -82
  93. package/__tests__/parseScripts.ts +0 -593
  94. package/__tests__/renderData/script1.cst +0 -58
  95. package/__tests__/renderData/script1.cst.svg +0 -1
  96. package/__tests__/renderData/script2.cst +0 -16
  97. package/__tests__/renderData/script2.cst.svg +0 -1
  98. package/__tests__/renderData/script3.cst +0 -30
  99. package/__tests__/renderData/script3.cst.svg +0 -1
  100. package/__tests__/renderData/script4.cst +0 -54
  101. package/__tests__/renderData/script4.cst.svg +0 -1
  102. package/__tests__/renderData/script5.cst +0 -23
  103. package/__tests__/renderData/script5.cst.svg +0 -1
  104. package/__tests__/renderData/script6.cst +0 -28
  105. package/__tests__/renderData/script6.cst.svg +0 -1
  106. package/__tests__/renderData/script7.cst +0 -26
  107. package/__tests__/renderData/script7.cst.svg +0 -1
  108. package/__tests__/renderData/script8.cst +0 -37
  109. package/__tests__/renderData/script8.cst.svg +0 -1
  110. package/__tests__/testCLI.ts +0 -68
  111. package/__tests__/testMathOps.ts +0 -36
  112. package/__tests__/testMergeWires.ts +0 -141
  113. package/__tests__/testParse.ts +0 -263
  114. package/__tests__/testRender.ts +0 -38
  115. package/build/src/antlr/CircuitScriptLexer.js +0 -287
  116. package/build/src/antlr/CircuitScriptParser.d.ts +0 -674
  117. package/build/src/antlr/CircuitScriptParser.js +0 -4841
  118. package/build/src/helpers.d.ts +0 -1
  119. package/build/src/helpers.js +0 -73
  120. package/build/src/objects/types.js +0 -6
  121. package/build/src/parser.js +0 -69
  122. package/build/src/visitor.d.ts +0 -133
  123. package/build/src/visitor.js +0 -1154
  124. package/documentation.md +0 -238
  125. package/examples/example_arduino_uno.cst +0 -1146
  126. package/examples/example_garden_pump.cst +0 -567
  127. package/examples/lib.cst +0 -185
  128. package/jest.config.js +0 -23
  129. package/refresh.html +0 -42
  130. package/server.cjs +0 -50
  131. package/src/antlr/CircuitScript.g4 +0 -209
  132. package/src/antlr/CircuitScriptLexer.ts +0 -317
  133. package/src/antlr/CircuitScriptParser.ts +0 -4979
  134. package/src/antlr/CircuitScriptVisitor.ts +0 -420
  135. package/src/draw_symbols.ts +0 -1085
  136. package/src/execute.ts +0 -1227
  137. package/src/fonts.ts +0 -1
  138. package/src/geometry.ts +0 -638
  139. package/src/globals.ts +0 -67
  140. package/src/helpers.ts +0 -114
  141. package/src/lexer.ts +0 -151
  142. package/src/logger.ts +0 -17
  143. package/src/objects/ClassComponent.ts +0 -223
  144. package/src/objects/ExecutionScope.ts +0 -201
  145. package/src/objects/Frame.ts +0 -20
  146. package/src/objects/ParamDefinition.ts +0 -49
  147. package/src/objects/PinDefinition.ts +0 -49
  148. package/src/objects/PinTypes.ts +0 -7
  149. package/src/objects/Wire.ts +0 -19
  150. package/src/objects/types.ts +0 -66
  151. package/src/parser.ts +0 -106
  152. package/src/regenerate-tests.ts +0 -25
  153. package/src/render.ts +0 -260
  154. package/src/sizing.ts +0 -96
  155. package/src/visitor.ts +0 -1691
  156. package/tsconfig.json +0 -27
  157. package/tsconfig.release.json +0 -8
  158. /package/{build/src/fonts.js → dist/esm/fonts.mjs} +0 -0
  159. /package/{build/src/globals.js → dist/esm/globals.mjs} +0 -0
  160. /package/{build/src/logger.js → dist/esm/logger.mjs} +0 -0
  161. /package/{build/src/objects/Frame.js → dist/esm/objects/Frame.mjs} +0 -0
  162. /package/{build/src/objects/Net.js → dist/esm/objects/Net.mjs} +0 -0
  163. /package/{build/src/objects/ParamDefinition.js → dist/esm/objects/ParamDefinition.mjs} +0 -0
  164. /package/{build/src/objects/PinTypes.js → dist/esm/objects/PinTypes.mjs} +0 -0
  165. /package/{build/src/objects/Wire.js → dist/esm/objects/Wire.mjs} +0 -0
  166. /package/{build/src/server.js → dist/esm/server.mjs} +0 -0
  167. /package/{build/src/utils.js → dist/esm/utils.mjs} +0 -0
  168. /package/{build/src → dist/types}/export.d.ts +0 -0
  169. /package/{build/src → dist/types}/fonts.d.ts +0 -0
  170. /package/{build/src → dist/types}/globals.d.ts +0 -0
  171. /package/{build/src → dist/types}/logger.d.ts +0 -0
  172. /package/{build/src → dist/types}/main.d.ts +0 -0
  173. /package/{build/src → dist/types}/objects/Frame.d.ts +0 -0
  174. /package/{build/src → dist/types}/objects/Net.d.ts +0 -0
  175. /package/{build/src → dist/types}/objects/ParamDefinition.d.ts +0 -0
  176. /package/{build/src → dist/types}/objects/PinTypes.d.ts +0 -0
  177. /package/{build/src → dist/types}/objects/Wire.d.ts +0 -0
  178. /package/{build/src → dist/types}/regenerate-tests.d.ts +0 -0
  179. /package/{build/src → dist/types}/server.d.ts +0 -0
  180. /package/{build/src → dist/types}/utils.d.ts +0 -0
@@ -1,20 +0,0 @@
1
- export class Frame {
2
- parameters: Map<string, any> = new Map();
3
- frameId: number;
4
-
5
- constructor(frameId: number) {
6
- this.frameId = frameId;
7
- }
8
- }
9
-
10
- export enum FrameParamKeys {
11
- Title = 'title',
12
- Direction = 'direction',
13
- Padding = 'padding',
14
- Border = 'border',
15
- }
16
-
17
- export enum FramePlotDirection {
18
- Row = 'row',
19
- Column = 'column',
20
- }
@@ -1,49 +0,0 @@
1
- export class ParamDefinition {
2
- paramName: string;
3
- paramValue: string | number | any;
4
-
5
- constructor(paramName: string, paramValue: any) {
6
- this.paramName = paramName;
7
- this.paramValue = paramValue;
8
- }
9
- }
10
-
11
- export class NumericValue {
12
- value: string | number;
13
-
14
- constructor(value: string | number) {
15
- this.value = value;
16
- }
17
-
18
- toString(): string {
19
- return 'numeric:' + this.value;
20
- }
21
-
22
- toDisplayString(): string {
23
- if (typeof this.value === 'number'){
24
- return this.value.toString();
25
-
26
- } else if (typeof this.value === 'string'){
27
- return this.value;
28
- }
29
- }
30
- }
31
- export class PercentageValue {
32
- value: string | number;
33
-
34
- constructor(value: string | number) {
35
- this.value = value;
36
- }
37
-
38
- toString(): string {
39
- return this.value.toString();
40
- }
41
- }
42
-
43
- export class PinBlankValue {
44
- blank: number;
45
-
46
- constructor(value: number) {
47
- this.blank = value;
48
- }
49
- }
@@ -1,49 +0,0 @@
1
- import { PinTypes } from './PinTypes.js';
2
-
3
- export type PinId = number | string;
4
-
5
- export class PinDefinition {
6
- id: PinId;
7
-
8
- idType: PinIdType;
9
-
10
- pinType: PinTypes;
11
-
12
- name: string;
13
- altNames: string[];
14
-
15
- side: string = PortSide.EAST;
16
-
17
- position = -1;
18
-
19
- constructor(
20
- id: PinId,
21
- idType: PinIdType,
22
- name: string,
23
- pinType = PinTypes.Any,
24
- altNames = [],
25
- ) {
26
- this.id = id;
27
- this.idType = idType;
28
-
29
- this.pinType = pinType;
30
-
31
- this.name = name;
32
- this.altNames = altNames;
33
- }
34
- }
35
-
36
- export enum PinIdType {
37
- Int = 'int',
38
- Str = 'str',
39
- }
40
-
41
- export enum PortSide {
42
- WEST = 'WEST',
43
- EAST = 'EAST',
44
- SOUTH = 'SOUTH',
45
- NORTH = 'NORTH'
46
- }
47
-
48
-
49
- export class PinReference {}
@@ -1,7 +0,0 @@
1
- export enum PinTypes {
2
- Any = 'any',
3
- Input = 'input',
4
- Output = 'output',
5
- IO = 'io',
6
- Power = 'power',
7
- }
@@ -1,19 +0,0 @@
1
- import { ClassComponent } from "./ClassComponent.js";
2
-
3
- export class Wire {
4
-
5
- // Should have some net info too
6
-
7
- path: WireSegment[]
8
-
9
- constructor(path: WireSegment[]) {
10
- this.path = path;
11
- }
12
- }
13
-
14
- export type WireSegment = {
15
- direction: 'up' | 'down' | 'left' | 'right' | 'auto' | 'auto_';
16
- value: number,
17
- valueXY?: [x: number, y: number],
18
- until?: [instance: ClassComponent, pin: number],
19
- }
@@ -1,66 +0,0 @@
1
- import { ExecutionContext } from '../execute.js';
2
- import { ClassComponent } from './ClassComponent.js';
3
- import { Net } from './Net.js';
4
- import { NumericValue, PercentageValue, PinBlankValue } from './ParamDefinition.js';
5
-
6
- export type CFunction = (args: CallableParameter[],
7
- options?: CFunctionOptions) => CFunctionResult;
8
-
9
- export type CFunctionOptions = {
10
- netNamespace?: string
11
- }
12
-
13
- export type CFunctionResult = [
14
- executionContext: ExecutionContext,
15
- result: ValueType | ClassComponent | null
16
- ];
17
-
18
- // export type NetMap = Map<ComponentPin, Net>;
19
-
20
- export type ComponentPinNet = [
21
- netName: string, instanceName: string, pin: number];
22
-
23
- // Need to improve name...
24
- export type ComponentPinNetPair = [
25
- component: ClassComponent,
26
- pin: number,
27
- net: Net
28
- ];
29
-
30
- export type ComponentPin = [
31
- component: ClassComponent,
32
- pinId: number|string
33
- ];
34
-
35
- export type ComplexType = ValueType
36
- | ClassComponent
37
- | UndeclaredReference
38
- | null;
39
-
40
- export type ValueType = boolean | number | string |
41
- NumericValue | PercentageValue | PinBlankValue;
42
-
43
- export type CallableParameter =
44
- ['keyword', key: string, value: ValueType] |
45
- ['position', key: number, value: ValueType];
46
-
47
- export type FunctionDefinedParameter = [name: string, defaultValue: ValueType]
48
- | [name: string];
49
-
50
-
51
- export class UndeclaredReference {
52
- reference: ReferenceType;
53
-
54
- constructor(reference: ReferenceType) {
55
- this.reference = reference;
56
- }
57
- }
58
-
59
- export type ReferenceType =
60
- {
61
- found: boolean,
62
- name?: string,
63
- trailers?: string[],
64
- type?: string,
65
- value?: any
66
- };
package/src/parser.ts DELETED
@@ -1,106 +0,0 @@
1
- import { CharStream, CommonTokenStream, ErrorListener, Token } from 'antlr4';
2
-
3
- import CircuitScriptLexer from './antlr/CircuitScriptLexer.js';
4
- import CircuitScriptParser from './antlr/CircuitScriptParser.js';
5
-
6
- import { MainVisitor } from './visitor.js';
7
- import { MainLexer } from './lexer.js';
8
- import { SimpleStopwatch } from './utils.js';
9
-
10
- export function parseFileWithVisitor(visitor: MainVisitor, data: string) {
11
- const chars = new CharStream(data);
12
- const lexer = new MainLexer(chars);
13
-
14
- const lexerTimer = new SimpleStopwatch();
15
-
16
- const tokens = new CommonTokenStream(lexer);
17
- tokens.fill();
18
-
19
- const lexerTimeTaken = lexerTimer.lap();
20
-
21
- const parserTimer = new SimpleStopwatch();
22
- const parser = new CircuitScriptParser(tokens);
23
- // Clear any existing error listeners and use the custom one only
24
- parser.removeErrorListeners();
25
-
26
- const errorListener = new CircuitscriptParserErrorListener();
27
- parser.addErrorListener(errorListener);
28
-
29
- const tree = parser.script();
30
-
31
- let hasError = false;
32
-
33
- try {
34
- visitor.visit(tree);
35
- } catch (err){
36
- // Error should be internally handled in visitor
37
- err.print(data);
38
- hasError = true;
39
- }
40
-
41
- const parserTimeTaken = parserTimer.lap();
42
-
43
- // dumpTokens(tokens.tokens, lexer, data);
44
-
45
- return {
46
- tree, parser,
47
- hasParseError: errorListener.hasParseErrors(),
48
- hasError,
49
- parserTimeTaken,
50
- lexerTimeTaken,
51
- };
52
- }
53
-
54
- function dumpTokens(tokens:Token[], lexer: CircuitScriptLexer, scriptData: string): void {
55
- tokens.forEach(item => {
56
- if (item.type !== -1) {
57
- let stringValue = "";
58
- let textPart = "";
59
-
60
- if (lexer.symbolicNames[item.type] !== null && lexer.symbolicNames[item.type] !== undefined) {
61
- stringValue = lexer.symbolicNames[item.type];
62
- if (stringValue !== "NEWLINE") {
63
- textPart = scriptData.substring(item.start, item.stop + 1);
64
- } else {
65
- textPart = item.text.length-1;
66
- }
67
- } else if (lexer.literalNames[item.type] !== null && lexer.literalNames[item.type] !== undefined) {
68
- stringValue = lexer.literalNames[item.type];
69
- textPart = scriptData.substring(item.start, item.stop + 1);
70
- } else {
71
- stringValue = item._text;
72
- }
73
-
74
- console.log('line', item.line + ':' + item.column, `\t${stringValue} (${item.type})`.padEnd(30), textPart);
75
- }
76
- });
77
- }
78
-
79
- export class CircuitscriptParserErrorListener extends ErrorListener {
80
-
81
- syntaxErrorCounter = 0;
82
-
83
- syntaxError(recognizer: Recognizer<TSymbol>,
84
- offendingSymbol: TSymbol,
85
- line: number,
86
- column: number,
87
- msg: string,
88
- e: RecognitionException | undefined) {
89
- console.log("Syntax error at line", line, ':', column, ' - ', msg);
90
-
91
- this.syntaxErrorCounter++;
92
- }
93
-
94
- // reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
95
- // }
96
-
97
- // reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
98
- // }
99
-
100
- // reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) {
101
- // }
102
-
103
- hasParseErrors(): boolean {
104
- return (this.syntaxErrorCounter > 0);
105
- }
106
- }
@@ -1,25 +0,0 @@
1
- import fs from 'fs';
2
- import { renderScript } from './helpers.js';
3
-
4
- const mainDir = './__tests__/renderData/';
5
-
6
- const cstFiles = [];
7
-
8
- const files = fs.readdirSync(mainDir);
9
- files.forEach(file => {
10
- if (file.endsWith('.cst')){
11
- cstFiles.push(file);
12
- }
13
- });
14
-
15
- const useCurrentDir = './examples/';
16
-
17
- cstFiles.forEach(file => {
18
- const inputPath = mainDir + file;
19
- const scriptData = fs.readFileSync(inputPath, { encoding: 'utf-8' });
20
-
21
- const outputPath = inputPath + '.svg';
22
- renderScript(scriptData, outputPath, { currentDirectory: useCurrentDir });
23
-
24
- console.log('generated ', outputPath);
25
- });
package/src/render.ts DELETED
@@ -1,260 +0,0 @@
1
- import { createSVGWindow } from 'svgdom';
2
- import { SVG, SVGTypeMapping, registerWindow } from '@svgdotjs/svg.js';
3
-
4
- import { BoundBox, MergedWire, RenderComponent, RenderFrame,
5
- RenderFrameType, RenderJunction, RenderText, RenderWire, getBounds } from "./layout.js";
6
- import { applyFontsToSVG } from './sizing.js';
7
- import { ParamKeys, bodyColor, junctionColor, junctionSize, wireColor } from './globals.js';
8
- import { NumericValue } from './objects/ParamDefinition.js';
9
- import { getBoundsSize } from './utils.js';
10
-
11
- export function generateSVG2(graph: {
12
- components: RenderComponent[],
13
- wires: RenderWire[], junctions: RenderJunction[],
14
- mergedWires: MergedWire[], debugRects: BoundBox[],
15
- frameObjects: RenderFrame[],
16
- textObjects: RenderText[],
17
- }): string {
18
-
19
- const window = createSVGWindow();
20
- const document = window.document;
21
-
22
- registerWindow(window, document);
23
-
24
- const canvas = SVG(document.documentElement);
25
- applyFontsToSVG(canvas);
26
-
27
- generateSVGChild(canvas,
28
- graph.components, graph.wires, graph.junctions, graph.mergedWires,
29
- graph.frameObjects, graph.textObjects,
30
- );
31
- const {x, y, width, height} = canvas.bbox();
32
-
33
- const margin = 5;
34
- const widthAndMargin = width + margin * 2;
35
- const heightAndMargin = height + margin * 2;
36
-
37
- const scale = 1;
38
-
39
- canvas.size(widthAndMargin * scale, heightAndMargin * scale);
40
- canvas.viewbox(x - margin, y - margin, widthAndMargin, heightAndMargin);
41
-
42
- return canvas.svg();
43
- }
44
-
45
- function generateSVGChild(canvas: SVGTypeMapping<SVGAElement>,
46
- components: RenderComponent[], wires: RenderWire[],
47
- junctions: RenderJunction[], mergedWires:MergedWire[],
48
- frameObjects:RenderFrame[], textObjects: RenderText[] ): void {
49
-
50
- const displayWireId = false;
51
-
52
- // Draw the display grid
53
- const bounds = getBounds(components, wires, junctions, frameObjects);
54
-
55
- drawGrid(
56
- canvas.group().translate(0, 0),
57
- {
58
- x: bounds.xmin,
59
- y: bounds.ymin,
60
- x2: bounds.xmax,
61
- y2: bounds.ymax
62
- });
63
-
64
- components.forEach(item => {
65
- const { x, y, width, height } = item;
66
- const symbolGroup = canvas.group();
67
- symbolGroup.translate(x, y);
68
-
69
- const { symbol = null } = item;
70
-
71
- if (symbol !== null && symbol) {
72
- let extra = {};
73
- if (item.component.parameters.has('__is_net')) {
74
- extra.net_name = item.component.parameters.get(ParamKeys.net_name);
75
-
76
- } else if (item.component.parameters.has('value')) {
77
- let tmpValue = item.component.parameters.get('value');
78
- if (tmpValue instanceof NumericValue){
79
- // Prepare value for display
80
- tmpValue = (tmpValue as NumericValue).value;
81
- }
82
-
83
- extra.value = tmpValue;
84
- }
85
-
86
- extra.instance_name = item.component.instanceName;
87
-
88
- if (item.component.parameters.has('place')){
89
- extra.place = item.component.parameters.get('place');
90
- } else {
91
- extra.place = true; // Default is to place the item
92
- }
93
-
94
- symbol.draw(symbolGroup, extra);
95
-
96
- } else {
97
- // draw default shape
98
- symbolGroup.rect(width, height)
99
- .fill(bodyColor)
100
- .stroke({ width: 1, color: '#333' });
101
- }
102
- });
103
-
104
- if (displayWireId){
105
- // Debugging method to draw the wire id next to the wires.
106
- const wiresGroup = canvas.group().translate(0, 0);
107
-
108
- wires.forEach(wire => {
109
- // Draw the wire id at the start of the wire
110
- wiresGroup.text(wire.id.toString())
111
- .font({
112
- family: 'Inter',
113
- size: 10,
114
- })
115
- .translate(wire.x+5, wire.y+5)
116
- });
117
- }
118
-
119
- const mergedWireGroup = canvas.group();
120
-
121
- // draw the merged wires
122
- mergedWires.forEach(tmpItem => {
123
- const { segments, intersectPoints } = tmpItem;
124
-
125
- segments.forEach(segment => {
126
- const pt1 = segment[0];
127
- const pt2 = segment[1];
128
- mergedWireGroup.line([pt1, pt2])
129
- .stroke({ width: 1, color: wireColor, linecap: 'square' })
130
- .fill('none');
131
- });
132
-
133
- intersectPoints.forEach(point => {
134
- const [x, y, count] = point;
135
- mergedWireGroup.circle(junctionSize)
136
- .translate(x - junctionSize/2, y - junctionSize/2)
137
- .fill(junctionColor)
138
- .stroke('none');
139
-
140
- // mergedWireGroup.text(count.toString())
141
- // .translate(x + 2, y + 2)
142
- // .font({
143
- // family: 'Inter',
144
- // size: 10,
145
- // })
146
- });
147
- });
148
-
149
- // const debugRectsGroup = canvas.group();
150
- // debugRects.forEach(box => {
151
- // // Draw a rect
152
- // const width = box.xmax - box.xmin;
153
- // const height = box.ymax - box.ymin;
154
- // const tmpRect = debugRectsGroup.rect(width, height)
155
- // .fill('none')
156
- // .stroke({ width: 1, color: '#000'});
157
- // tmpRect.translate(box.xmin, box.ymin);
158
- // });
159
-
160
- const frameGroup = canvas.group();
161
- const showElementFrames = false;
162
-
163
- frameObjects.forEach(item => {
164
- const { bounds, borderWidth } = item;
165
- if (borderWidth > 0){
166
- const { width, height } = getBoundsSize(bounds);
167
-
168
- let strokeColor = '#111';
169
- if (item.type === RenderFrameType.Container) {
170
- strokeColor = '#111';
171
- } else if (item.type === RenderFrameType.Elements){
172
- strokeColor = '#aaa';
173
- if (!showElementFrames){
174
- return;
175
- }
176
- }
177
-
178
- const tmpRect = frameGroup.rect(width, height)
179
- .fill('none')
180
- .stroke({ width: borderWidth, color: strokeColor });
181
-
182
- tmpRect.translate(item.x, item.y);
183
- }
184
- });
185
-
186
- textObjects.forEach(item => {
187
- const {x, y, symbol} = item;
188
- const innerGroup = canvas.group();
189
- innerGroup.translate(x, y);
190
- symbol.draw(innerGroup);
191
- });
192
-
193
- const drawOrigin = false;
194
-
195
- // Draw origin
196
- drawOrigin && canvas.group().translate(0,0)
197
- .circle(5)
198
- .translate(-5/2, -5/2)
199
- .stroke('none').fill('red');
200
- }
201
-
202
- function drawGrid(group: G, canvasSize: { x: number, y: number, x2: number, y2: number }): void {
203
- const gridSize = 20;
204
- const { x, y, x2, y2 } = canvasSize;
205
-
206
- const gridStartX = (Math.floor(x / gridSize) - 1) * gridSize;
207
- const gridStartY = (Math.floor(y / gridSize) - 1) * gridSize;
208
-
209
- const gridEndX = (Math.ceil(x2 / gridSize) + 1) * gridSize;
210
- const gridEndY = (Math.ceil(y2 / gridSize) + 1) * gridSize;
211
-
212
- const numCols = Math.ceil((gridEndX - gridStartX) / gridSize);
213
- // const numRows = Math.ceil((gridEndY - gridStartY) / gridSize);
214
-
215
- // Draws (0, 0) point
216
- // group.circle(5)
217
- // .translate(-5 / 2, -5 / 2)
218
- // .fill('red')
219
- // .stroke('none');
220
-
221
- const lines = [];
222
-
223
- for (let i = 0; i <= numCols; i++) {
224
- const startX = gridStartX + i * gridSize;
225
- const startY = gridStartY-0.5;
226
- const endY = gridEndY;
227
- lines.push(`M ${startX} ${startY} L ${startX} ${endY}`);
228
- }
229
-
230
- group.path(lines.join(" "))
231
- .fill('none')
232
- .attr({
233
- 'stroke-dasharray': '1,' + (gridSize-1),
234
- })
235
- .stroke({
236
- width: 1,
237
- color: '#aaa'
238
- })
239
- }
240
-
241
- function calculateBoundingBox(components: RenderComponent[]): { width: number, height: number } {
242
- let maxX = Number.NEGATIVE_INFINITY;
243
- let minX = Number.POSITIVE_INFINITY;
244
-
245
- let maxY = Number.NEGATIVE_INFINITY;
246
- let minY = Number.POSITIVE_INFINITY;
247
-
248
- components.forEach(item => {
249
- minX = Math.min(item.x, minX);
250
- maxX = Math.max(item.x + item.width, maxX);
251
-
252
- minY = Math.min(item.y, minY);
253
- maxY = Math.max(item.y + item.height, maxY);
254
- });
255
-
256
- return {
257
- width: (maxX - minX),
258
- height: (maxY - minY)
259
- }
260
- }
package/src/sizing.ts DELETED
@@ -1,96 +0,0 @@
1
- import { Box, SVG, SVGTypeMapping, registerWindow } from '@svgdotjs/svg.js';
2
- import { config, createSVGWindow } from 'svgdom';
3
- import { HorizontalAlign, VerticalAlign } from './geometry.js';
4
- import { defaultFont } from './globals.js';
5
-
6
- let MainCanvas = null;
7
-
8
- const supportedFonts = {
9
- // 'Roboto': 'Roboto-Regular.ttf',
10
- // 'Inter': 'Inter-Regular.ttf',
11
- // 'Inter-Bold': 'Inter-Bold.ttf',
12
- }
13
-
14
- export async function prepareSizing(fontsPath): Promise<void> {
15
- await config.setFontDir(fontsPath)
16
- .setFontFamilyMappings(supportedFonts)
17
- .preloadFonts()
18
- }
19
-
20
- export function applyFontsToSVG(canvas: SVGTypeMapping): void {
21
- // for (const fontName in supportedFonts) {
22
- // canvas.fontface(fontName, "url('" + InterFontEncoded + "')");
23
- // }
24
- }
25
-
26
- export async function measureTextSize(text: string, fontFamily: string, fontSize: number): Promise<{ width: number, height: number }> {
27
- // Async version, in case measuring text sizes need more time
28
- return measureTextSize2(text, fontFamily, fontSize);
29
- }
30
-
31
- // Cache measurements to avoid recalculations
32
- const measureTextSizeCache: {
33
- [key: string]: {
34
- width: number,
35
- height: number, box: Box
36
- }
37
- } = {};
38
- const measureTextSizeCacheHits: { [key: string]: number } = {};
39
-
40
- export function measureTextSize2(text: string, fontFamily: string,
41
- fontSize: number, fontWeight = 'regular',
42
- anchor = HorizontalAlign.Left,
43
- vanchor = VerticalAlign.Bottom): { width: number, height: number, box: Box } {
44
-
45
- // Reuse the canvas, so no need to keep creating
46
- if (MainCanvas === null) {
47
- const window = createSVGWindow();
48
- const { document } = window;
49
- registerWindow(window, document);
50
- MainCanvas = SVG(document.documentElement);
51
- }
52
-
53
- // Check if entry already exists in the cache
54
- const key = `${text}-${fontFamily}-${fontSize}-${fontWeight}-${anchor}-${vanchor}`;
55
-
56
- if (measureTextSizeCache[key] === undefined) {
57
- let dominantBaseline = 'hanging';
58
- switch(vanchor){
59
- case VerticalAlign.Top:
60
- dominantBaseline = 'hanging';
61
- break;
62
-
63
- case VerticalAlign.Middle:
64
- dominantBaseline = 'middle';
65
- break;
66
-
67
- case VerticalAlign.Bottom:
68
- dominantBaseline = 'text-top';
69
- break;
70
- }
71
-
72
- fontFamily = defaultFont;
73
-
74
- const tmpTextElement = MainCanvas.text(text).font({
75
- family: fontFamily,
76
- size: fontSize,
77
- anchor: anchor,
78
- 'dominant-baseline': dominantBaseline,
79
- weight: fontWeight,
80
- }).fill('#333');
81
-
82
- const textbox = tmpTextElement.bbox();
83
- const { width, height } = textbox;
84
- tmpTextElement.remove();
85
-
86
- measureTextSizeCache[key] = {
87
- width: Math.round(width * 100) / 100,
88
- height: Math.round(height * 100) / 100,
89
- box: textbox,
90
- }
91
- measureTextSizeCacheHits[key] = 0;
92
- }
93
-
94
- measureTextSizeCacheHits[key]++;
95
- return measureTextSizeCache[key];
96
- }