@fw-components/formula-editor 2.0.3-formula-editor.1

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.
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@fw-components/formula-editor",
3
+ "version": "2.0.3-formula-editor.1",
4
+ "type": "module",
5
+ "description": "A WYSIWYG type formula editor",
6
+ "main": "dist/src/formula-builder.js",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "scripts": {
11
+ "start": "es-dev-server --app-index ../../index.html --node-resolve --watch --open"
12
+ },
13
+ "dependencies": {
14
+ "@fw-components/styles": "^2.0.3-formula-editor.1",
15
+ "big.js": "^6.2.1",
16
+ "lit": "^2.1.2",
17
+ "typescript": "^5.0.4"
18
+ },
19
+ "author": "The Fundwave Authors",
20
+ "license": "ISC",
21
+ "devDependencies": {
22
+ "@types/big.js": "^6.1.6",
23
+ "es-dev-server": "^2.1.0"
24
+ },
25
+ "gitHead": "f0c8eaf674cdbc6d104fcedb36ddbb6036af40db"
26
+ }
package/src/cursor.ts ADDED
@@ -0,0 +1,134 @@
1
+ export class Cursor {
2
+ /**
3
+ * The functions `getCurrentCursorPosition`, `setCurrentCursorPosition` and their
4
+ * helpers `_createRange` and `_isChildOf` are not used for caret manipulation,
5
+ * but are still in the code for future reference, if the functionality breaks
6
+ * somehow in some obsolete browser.
7
+ */
8
+ static getCurrentCursorPosition(parentElement: any): number {
9
+ let selection = window.getSelection(),
10
+ charCount = -1,
11
+ node;
12
+
13
+ if (selection?.focusNode) {
14
+ if (Cursor._isChildOf(selection.focusNode, parentElement)) {
15
+ node = selection.focusNode;
16
+ charCount = selection.focusOffset;
17
+
18
+ while (node) {
19
+ if (node === parentElement) {
20
+ break;
21
+ }
22
+
23
+ if (node.previousSibling) {
24
+ node = node.previousSibling;
25
+ charCount += node.textContent?.length ?? 0;
26
+ } else {
27
+ node = node.parentNode;
28
+ if (node === null) {
29
+ break;
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
35
+
36
+ return charCount;
37
+ }
38
+
39
+ static setCurrentCursorPosition(chars: number, element: any) {
40
+ if (chars >= 0) {
41
+ var selection = window.getSelection();
42
+ let range = Cursor._createRange(element, { count: chars }, undefined);
43
+
44
+ if (range) {
45
+ range.collapse(false);
46
+ selection?.removeAllRanges();
47
+ selection?.addRange(range);
48
+ }
49
+ }
50
+ }
51
+
52
+ static _createRange(node: any, chars: any, range: any) {
53
+ if (!range) {
54
+ range = document.createRange();
55
+ range.selectNode(node);
56
+ range.setStart(node, 0);
57
+ }
58
+
59
+ if (chars.count === 0) {
60
+ range.setEnd(node, chars.count);
61
+ } else if (node && chars.count > 0) {
62
+ if (node.nodeType === Node.TEXT_NODE) {
63
+ if (node.textContent.length < chars.count) {
64
+ chars.count -= node.textContent.length;
65
+ } else {
66
+ range.setEnd(node, chars.count);
67
+ chars.count = 0;
68
+ }
69
+ } else {
70
+ for (var lp = 0; lp < node.childNodes.length; lp++) {
71
+ range = Cursor._createRange(node.childNodes[lp], chars, range);
72
+
73
+ if (chars.count === 0) {
74
+ break;
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ return range;
81
+ }
82
+
83
+ static _isChildOf(node: any, parentElement: any) {
84
+ while (node !== null) {
85
+ if (node === parentElement) {
86
+ return true;
87
+ }
88
+ node = node.parentNode;
89
+ }
90
+
91
+ return false;
92
+ }
93
+
94
+ static getCaretPosition(shadowRoot: ShadowRoot, element: HTMLElement) {
95
+ // `getSelection` is not defined for the type ShadowRoot in TS,
96
+ // but it does exist.
97
+ const range = (shadowRoot as any).getSelection()!.getRangeAt(0);
98
+ const prefix = range.cloneRange();
99
+ prefix.selectNodeContents(element);
100
+ prefix.setEnd(range.endContainer, range.endOffset);
101
+ return prefix.toString().length;
102
+ }
103
+
104
+ static setCaretPosition = (pos: any, parent: any) => {
105
+ for (const node of parent.childNodes) {
106
+ if (node.nodeType == Node.TEXT_NODE) {
107
+ if (node.length >= pos) {
108
+ const range = document.createRange();
109
+ const sel = window.getSelection()!;
110
+ range.setStart(node, pos);
111
+ range.collapse(true);
112
+ sel.removeAllRanges();
113
+ sel.addRange(range);
114
+ return -1;
115
+ } else {
116
+ pos = pos - node.length;
117
+ }
118
+ } else {
119
+ pos = this.setCaretPosition(pos, node);
120
+ if (pos < 0) {
121
+ return pos;
122
+ }
123
+ }
124
+ }
125
+ return pos;
126
+ };
127
+
128
+ static getCursorRect(shadowRoot: ShadowRoot) {
129
+ return (shadowRoot as any)
130
+ .getSelection()
131
+ ?.getRangeAt(0)
132
+ ?.getClientRects()[0];
133
+ }
134
+ }
@@ -0,0 +1,141 @@
1
+ import { LitElement, css, html } from "lit";
2
+ import { customElement, property, query } from "lit/decorators.js";
3
+ import { Formula } from "./helpers/types.js";
4
+
5
+ import { TextButtonStyles } from "../../styles/src/button-styles.js";
6
+ import { FormulaEditor } from "./formula-editor";
7
+
8
+ @customElement("formula-builder")
9
+ class FormulaBuilder extends LitElement {
10
+ static styles = css`
11
+ #wysiwyg-err {
12
+ width: 100%;
13
+ border-radius: 0px 0px var(--fe-err-border-radius, 4px)
14
+ var(--fe-err-border-radius, 4px);
15
+ color: var(--fe-err-text-color, #fc514f);
16
+ border: var(--fe-err-border-width, 2px) solid black;
17
+ /* border-top: 0px; */
18
+ background-color: var(--fe-background-color, #222222);
19
+ padding: 4px;
20
+ margin: 0px 0px 8px 0px;
21
+ }
22
+
23
+ .wysiwyg-no-err {
24
+ color: #098668 !important;
25
+ }
26
+ `;
27
+
28
+ @property({
29
+ type: Map<string, number>,
30
+ converter: {
31
+ fromAttribute: (value) => {
32
+ if (value) {
33
+ return new Map<string, number>(JSON.parse(value));
34
+ }
35
+ },
36
+ toAttribute: (value: Map<string, number>) => {
37
+ return JSON.stringify(Array.from(value.entries()));
38
+ },
39
+ },
40
+ })
41
+ variables = new Map([
42
+ ["sales_expense", 2],
43
+ ["sales_in_quarter", 3],
44
+ ["sales_cummulative", 3],
45
+ ["cummulative_sum", 4],
46
+ ["mayank", 10],
47
+ ]);
48
+
49
+ @property({
50
+ type: Formula,
51
+ converter: {
52
+ fromAttribute: (value) => {
53
+ if (value) {
54
+ const formulaJSON = JSON.parse(value);
55
+ return new Formula(
56
+ formulaJSON.name,
57
+ formulaJSON.formulaString,
58
+ formulaJSON.precision
59
+ );
60
+ }
61
+ },
62
+ toAttribute: (value) => {
63
+ return JSON.stringify(value);
64
+ },
65
+ },
66
+ })
67
+ formula = new Formula("", "");
68
+
69
+ @property()
70
+ handleCalculate = () => {
71
+ this.formulaEditor?.requestCalculate();
72
+ };
73
+
74
+ @property()
75
+ handleFormat = () => {
76
+ this.formulaEditor?.requestFormat();
77
+ };
78
+
79
+ @query("#metric-name-input")
80
+ nameInput: HTMLInputElement | undefined;
81
+
82
+ @query("formula-editor")
83
+ formulaEditor: FormulaEditor | undefined;
84
+
85
+ handleChange() {
86
+ this.dispatchEvent(
87
+ new CustomEvent("fw-formula-changed", {
88
+ detail: {
89
+ name: this.nameInput?.value,
90
+ rawFormula: this.formula.formulaString,
91
+ error: this.formula.error,
92
+ precision: this.formula.precision,
93
+ },
94
+ bubbles: true,
95
+ })
96
+ );
97
+
98
+ this.requestUpdate();
99
+ }
100
+
101
+ render() {
102
+ return html`
103
+ ${TextButtonStyles}
104
+
105
+ <div>
106
+ <label for="metric-name-input">Metric Name</label>
107
+ <input
108
+ id="metric-name-input"
109
+ .value=${this.formula.name}
110
+ @input=${(e: any) => {
111
+ this.handleChange();
112
+ }}
113
+ />
114
+ </div>
115
+ <label>Formula</label>
116
+ <formula-editor
117
+ class="fe"
118
+ minSuggestionLen="0"
119
+ @fw-formula-content-changed=${(e: any) => {
120
+ this.formula.formulaString = e.detail.formulaString;
121
+ this.formula.error = e.detail.error;
122
+ this.handleChange();
123
+ }}
124
+ .variables=${this.variables}
125
+ .content=${this.formula.formulaString}
126
+ .errorString=${this.formula.error}
127
+ >
128
+ </formula-editor>
129
+ <div id="wysiwyg-err" class="${this.formula.error ?? "wysiwyg-no-err"}">
130
+ ${this.formula.error ??
131
+ `${this.formula.name} = ${this.formula.formulaString}`}
132
+ </div>
133
+ <button class="primary-text-button" @click=${this.handleCalculate}>
134
+ Calculate
135
+ </button>
136
+ <button class="primary-text-button" @click=${this.handleFormat}>
137
+ Format
138
+ </button>
139
+ `;
140
+ }
141
+ }
@@ -0,0 +1,99 @@
1
+ import { LitElement, html } from "lit";
2
+ import { customElement, state } from "lit/decorators.js";
3
+ import { repeat } from "lit/directives/repeat.js";
4
+ import { ifDefined } from "lit/directives/if-defined.js";
5
+ import { Operator } from "./helpers/types";
6
+
7
+ enum FormulaEntityType {
8
+ Operator,
9
+ Entity,
10
+ }
11
+
12
+ class FormulaEntity {
13
+ constructor(
14
+ type: FormulaEntityType,
15
+ metric: string | null,
16
+ operator: Operator = Operator.NONE
17
+ ) {
18
+ this.type = type;
19
+ this.metric = metric;
20
+ this.operator = operator;
21
+ }
22
+
23
+ type: FormulaEntityType;
24
+ metric: string | null;
25
+ operator: Operator;
26
+ }
27
+
28
+ class FormulaRow {
29
+ constructor(
30
+ type: FormulaEntityType,
31
+ metrices: FormulaEntity[] | null = null,
32
+ operator: Operator = Operator.NONE
33
+ ) {
34
+ this.type = type;
35
+ this.metrices = metrices;
36
+ this.operator = operator;
37
+ }
38
+
39
+ type: FormulaEntityType;
40
+ operator: Operator = Operator.NONE;
41
+ metrices: FormulaEntity[] | null;
42
+ }
43
+
44
+ @customElement("formula-creator")
45
+ class FormulaCreator extends LitElement {
46
+ @state()
47
+ formulaState: FormulaRow[] = [
48
+ new FormulaRow(FormulaEntityType.Entity, [
49
+ new FormulaEntity(FormulaEntityType.Entity, "Sales Expense"),
50
+ new FormulaEntity(FormulaEntityType.Operator, null, Operator.MINUS),
51
+ new FormulaEntity(FormulaEntityType.Entity, "Marketing Expense"),
52
+ ]),
53
+ new FormulaRow(FormulaEntityType.Operator, null, Operator.DIV),
54
+ new FormulaRow(FormulaEntityType.Entity, [
55
+ new FormulaEntity(FormulaEntityType.Entity, "Sales Expense"),
56
+ new FormulaEntity(FormulaEntityType.Operator, null, Operator.PLUS),
57
+ new FormulaEntity(FormulaEntityType.Entity, "Marketing Expense"),
58
+ ]),
59
+ new FormulaRow(FormulaEntityType.Operator, null, Operator.DIV),
60
+ new FormulaRow(FormulaEntityType.Entity, [
61
+ new FormulaEntity(FormulaEntityType.Entity, "Sales Expense"),
62
+ new FormulaEntity(FormulaEntityType.Operator, null, Operator.DIV),
63
+ new FormulaEntity(FormulaEntityType.Entity, "Marketing Expense"),
64
+ ]),
65
+ ];
66
+
67
+ render() {
68
+ return html`
69
+ <label>Formula</label>
70
+ ${repeat(
71
+ this.formulaState,
72
+ (_, rowIndex) => `row-${rowIndex}`,
73
+ (formulaRow, rowIndex) => {
74
+ return formulaRow.type == FormulaEntityType.Entity
75
+ ? html` <div>
76
+ ${repeat(
77
+ formulaRow.metrices!,
78
+ (_, columnIndex) => `col-(${rowIndex},${columnIndex})`,
79
+ (formulaEntity, columnIndex) => {
80
+ return formulaEntity.type == FormulaEntityType.Entity
81
+ ? html`<input
82
+ value=${ifDefined(
83
+ formulaEntity.metric === null
84
+ ? undefined
85
+ : formulaEntity.metric
86
+ )}
87
+ />`
88
+ : html`<operator-input
89
+ .operator=${formulaEntity.operator}
90
+ ></operator-input>`;
91
+ }
92
+ )}
93
+ </div>`
94
+ : html`<div>${formulaRow.operator}</div>`;
95
+ }
96
+ )}
97
+ `;
98
+ }
99
+ }
@@ -0,0 +1,236 @@
1
+ import { html, LitElement, PropertyValueMap } from "lit";
2
+ import { customElement, property, state, query } from "lit/decorators.js";
3
+ import { FormulaEditorStyles } from "./styles/formula-editor-styles.js";
4
+ import { Parser } from "./parser.js";
5
+ import { Cursor } from "./cursor.js";
6
+ import "./suggestion-menu.js";
7
+
8
+ @customElement("formula-editor")
9
+ export class FormulaEditor extends LitElement {
10
+ private _parser: Parser;
11
+
12
+ constructor() {
13
+ super();
14
+
15
+ this._parser = new Parser(this.variables, this.minSuggestionLen);
16
+ }
17
+
18
+ protected firstUpdated(
19
+ _changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>
20
+ ): void {
21
+ this._parser = new Parser(this.variables, this.minSuggestionLen);
22
+ this.parseInput(null, false);
23
+ }
24
+
25
+ /**
26
+ * These `states` and `properties` can't be defined as `static get properties`,
27
+ * because TS doesn't support that.
28
+ * @see https://github.com/lit/lit-element/issues/414
29
+ */
30
+
31
+ @state()
32
+ _formattedContent: Element | null = null;
33
+
34
+ @state()
35
+ _recommendations: string[] | null = null;
36
+
37
+ @state()
38
+ _calculatedResult: number | undefined = undefined;
39
+
40
+ /**
41
+ * If `parseInput` is called to add a recommendation, say by clicking,
42
+ * browser removes focus from the input box. In that case, we have no way
43
+ * of knowing where the cursor previously was, other than storing it somewhere.
44
+ */
45
+
46
+ @state()
47
+ currentCursorPosition: number | null = null;
48
+
49
+ @state()
50
+ currentCursorRect: DOMRect | undefined = undefined;
51
+
52
+ @state()
53
+ lastInputType: string = "undef";
54
+
55
+ @property()
56
+ content: string = "";
57
+
58
+ @property({
59
+ type: Map<string, number>,
60
+ converter: {
61
+ fromAttribute: (value) => {
62
+ if (value) {
63
+ return new Map<string, number>(JSON.parse(value));
64
+ }
65
+ },
66
+ toAttribute: (value: Map<string, number>) => {
67
+ return JSON.stringify(Array.from(value.entries()));
68
+ },
69
+ },
70
+ })
71
+ variables = new Map();
72
+
73
+ @property()
74
+ minSuggestionLen: number = 2;
75
+
76
+ @property()
77
+ errorString: string | null = null;
78
+
79
+ @query("wysiwyg-editor")
80
+ editor: any;
81
+
82
+ handleChange(event: InputEvent) {
83
+ event.preventDefault();
84
+
85
+ this.lastInputType = event.inputType;
86
+ this.content = (event.target as HTMLDivElement).innerText;
87
+ this.parseInput();
88
+
89
+ (event.target as HTMLDivElement).focus();
90
+ }
91
+
92
+ handleTab(event: KeyboardEvent) {
93
+ if (event.code == "Tab" && this._recommendations?.length == 1) {
94
+ event.preventDefault();
95
+ this.parseInput(this._recommendations[0]);
96
+ }
97
+ }
98
+
99
+ onClickRecommendation(recommendation: string) {
100
+ let editor = this.shadowRoot?.getElementById("wysiwyg-editor");
101
+ if (!editor) return;
102
+
103
+ this.parseInput(recommendation);
104
+ this.currentCursorPosition = null;
105
+ }
106
+
107
+ /**
108
+ *
109
+ * @param recommendation The recommendation which needs to be inserted
110
+ * at the current cursor position
111
+ * @param manageCursor Whether or not cursor management is needed. Not
112
+ * needed when manual insertion of text is required (eg: during initialization)
113
+ * @returns void
114
+ */
115
+ parseInput(
116
+ recommendation: string | null = null,
117
+ manageCursor: boolean = true
118
+ ) {
119
+ let editor = this.shadowRoot?.getElementById("wysiwyg-editor");
120
+ if (!editor) return;
121
+
122
+ /**
123
+ * @see https://github.com/WICG/webcomponents/issues/79
124
+ */
125
+
126
+ if (manageCursor)
127
+ this.currentCursorPosition = recommendation
128
+ ? this.currentCursorPosition
129
+ : Cursor.getCaretPosition(this.shadowRoot!, editor);
130
+
131
+ const parseOutput = this._parser.parseInput(
132
+ this.content,
133
+ this.currentCursorPosition,
134
+ recommendation
135
+ );
136
+
137
+ this._recommendations = parseOutput.recommendations;
138
+ this._formattedContent = parseOutput.formattedContent;
139
+ this.errorString = parseOutput.errorString;
140
+
141
+ /**
142
+ * Don't modify the text stream manually if the text is being composed,
143
+ * unless the user manually chooses to do so by selecting a suggestion.
144
+ * @see https://github.com/w3c/input-events/issues/86
145
+ * @see https://github.com/w3c/input-events/pull/122
146
+ * @see https://bugs.chromium.org/p/chromium/issues/detail?id=689541
147
+ * */
148
+
149
+ if (this.lastInputType != "insertCompositionText" || recommendation) {
150
+ editor.innerHTML = parseOutput.formattedString!;
151
+ }
152
+
153
+ this.content = (editor as HTMLDivElement).innerText;
154
+
155
+ if (recommendation) {
156
+ this._recommendations = null;
157
+ this.currentCursorPosition = parseOutput.newCursorPosition;
158
+ }
159
+
160
+ if (manageCursor)
161
+ Cursor.setCaretPosition(this.currentCursorPosition!, editor);
162
+ editor?.focus();
163
+
164
+ if (manageCursor)
165
+ this.currentCursorRect = Cursor.getCursorRect(this.shadowRoot!);
166
+
167
+ this.requestUpdate();
168
+
169
+ this.dispatchEvent(
170
+ new CustomEvent("fw-formula-content-changed", {
171
+ detail: {
172
+ formulaString: this.content,
173
+ error: this.errorString,
174
+ },
175
+ bubbles: true,
176
+ })
177
+ );
178
+ }
179
+
180
+ requestCalculate() {
181
+ if (this._parser.parseInput(this.content).errorString) {
182
+ return;
183
+ }
184
+
185
+ const calculatedResult = this._parser.calculate(this.content);
186
+
187
+ this.content = this._parser.addParentheses(this.content) ?? this.content;
188
+ this.parseInput();
189
+
190
+ this._calculatedResult = calculatedResult.result;
191
+ this.errorString = calculatedResult.errorString;
192
+
193
+ this._recommendations = null;
194
+ this.requestUpdate();
195
+ }
196
+
197
+ requestFormat() {
198
+ this.content = this._parser.addParentheses(this.content) ?? this.content;
199
+ this.parseInput();
200
+ this._recommendations = null;
201
+ this.requestUpdate();
202
+ }
203
+
204
+ render() {
205
+ return html`
206
+ <style>
207
+ ${FormulaEditorStyles}
208
+ </style>
209
+ <div
210
+ contenteditable
211
+ id="wysiwyg-editor"
212
+ spellcheck="false"
213
+ autocomplete="off"
214
+ @input=${this.handleChange}
215
+ @keydown=${this.handleTab}
216
+ ></div>
217
+ ${this._recommendations
218
+ ? html` <suggestion-menu
219
+ style="
220
+ position: absolute;
221
+ left: ${(this.currentCursorRect?.left ?? 0) -
222
+ (this.editor?.getClientRect()[0]?.left ?? 0) +
223
+ "px"};
224
+ top: ${(this.currentCursorRect?.top ??
225
+ 0 - (this.editor?.getClientRect()[0]?.top ?? 0)) +
226
+ window.scrollY +
227
+ "px"};
228
+ "
229
+ .recommendations=${this._recommendations}
230
+ .onClickRecommendation=${(e: any) => this.onClickRecommendation(e)}
231
+ ></suggestion-menu>`
232
+ : html``}
233
+ <p>${this._calculatedResult}</p>
234
+ `;
235
+ }
236
+ }
@@ -0,0 +1,20 @@
1
+ export enum Operator {
2
+ PLUS = "+",
3
+ MINUS = "-",
4
+ MUL = "*",
5
+ DIV = "/",
6
+ NONE = "",
7
+ }
8
+
9
+ export class Formula {
10
+ constructor(name: string, formulaString: string, precision: number = -1) {
11
+ this.name = name;
12
+ this.formulaString = formulaString;
13
+ this.precision = precision;
14
+ }
15
+
16
+ name: string;
17
+ formulaString: string;
18
+ precision: number;
19
+ error: string | null = null;
20
+ }