@fw-components/formula-editor 2.0.3-formula-editor.2 → 2.0.7-cline-formulaeditor.0

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.
@@ -0,0 +1,367 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { html, LitElement } from "lit";
8
+ import { customElement, property, state, query } from "lit/decorators.js";
9
+ import { FormulaEditorStyles } from "./styles/formula-editor-styles.js";
10
+ import { Parser } from "./parser.js";
11
+ import { Cursor } from "./cursor.js";
12
+ import "./suggestion-menu.js";
13
+ let FormulaEditor = class FormulaEditor extends LitElement {
14
+ constructor() {
15
+ super();
16
+ this._undoStack = [];
17
+ this._redoStack = [];
18
+ this._isCalculating = false;
19
+ this._inputDebounceTimer = null;
20
+ /**
21
+ * These `states` and `properties` can't be defined as `static get properties`,
22
+ * because TS doesn't support that.
23
+ * @see https://github.com/lit/lit-element/issues/414
24
+ */
25
+ this._formattedContent = null;
26
+ this._recommendations = null;
27
+ this._calculatedResult = undefined;
28
+ /**
29
+ * If `parseInput` is called to add a recommendation, say by clicking,
30
+ * browser removes focus from the input box. In that case, we have no way
31
+ * of knowing where the cursor previously was, other than storing it somewhere.
32
+ */
33
+ this.currentCursorPosition = null;
34
+ this.currentCursorRect = undefined;
35
+ this.lastInputType = "undef";
36
+ this.isFocus = false;
37
+ this.content = "";
38
+ this.placeholder = "Type your formula...";
39
+ this.variables = new Map();
40
+ this.minSuggestionLen = 2;
41
+ this.errorString = null;
42
+ this._parser = new Parser(this.variables, this.minSuggestionLen);
43
+ }
44
+ firstUpdated(_changedProperties) {
45
+ this._parser = new Parser(this.variables, this.minSuggestionLen);
46
+ this.parseInput(null, false);
47
+ }
48
+ handleChange(event) {
49
+ event.preventDefault();
50
+ this.lastInputType = event.inputType;
51
+ const newContent = event.target.innerText;
52
+ // Save state for undo/redo if content actually changed
53
+ if (newContent !== this.content) {
54
+ this._undoStack.push(this.content);
55
+ this._redoStack = []; // Clear redo stack on new changes
56
+ if (this._undoStack.length > 50)
57
+ this._undoStack.shift(); // Limit stack size
58
+ }
59
+ this.content = newContent;
60
+ // Debounce input parsing
61
+ if (this._inputDebounceTimer) {
62
+ window.clearTimeout(this._inputDebounceTimer);
63
+ }
64
+ this._inputDebounceTimer = window.setTimeout(() => {
65
+ this.parseInput();
66
+ this._inputDebounceTimer = null;
67
+ }, 150);
68
+ event.target.focus();
69
+ }
70
+ handlePaste(event) {
71
+ event.preventDefault();
72
+ const text = event.clipboardData?.getData('text/plain') || '';
73
+ // Clean and sanitize pasted content
74
+ const sanitizedText = text
75
+ .replace(/[\u200B-\u200D\uFEFF]/g, '') // Remove zero-width spaces
76
+ .replace(/\r\n/g, ' ') // Convert Windows line endings
77
+ .replace(/\n/g, ' ') // Convert remaining line endings
78
+ .trim();
79
+ document.execCommand('insertText', false, sanitizedText);
80
+ }
81
+ undo() {
82
+ if (this._undoStack.length > 0) {
83
+ this._redoStack.push(this.content);
84
+ this.content = this._undoStack.pop();
85
+ this.parseInput();
86
+ }
87
+ }
88
+ redo() {
89
+ if (this._redoStack.length > 0) {
90
+ this._undoStack.push(this.content);
91
+ this.content = this._redoStack.pop();
92
+ this.parseInput();
93
+ }
94
+ }
95
+ navigateRecommendations(direction) {
96
+ if (!this._recommendations)
97
+ return;
98
+ const currentIndex = this._recommendations.indexOf(this._selectedRecommendation);
99
+ const newIndex = direction === "ArrowDown"
100
+ ? (currentIndex + 1) % this._recommendations.length
101
+ : direction === "ArrowUp"
102
+ ? (currentIndex - 1 + this._recommendations.length) % this._recommendations.length
103
+ : currentIndex;
104
+ this._selectedRecommendation = this._recommendations[newIndex];
105
+ this.scrollToSelectedRecommendation(newIndex);
106
+ }
107
+ scrollToSelectedRecommendation(index) {
108
+ const suggestionMenu = this.shadowRoot?.querySelector("suggestion-menu");
109
+ if (suggestionMenu) {
110
+ const listItem = suggestionMenu.shadowRoot?.querySelectorAll("li")[index];
111
+ if (listItem) {
112
+ listItem.scrollIntoView({
113
+ block: "nearest",
114
+ inline: "nearest",
115
+ });
116
+ }
117
+ }
118
+ }
119
+ handleKeyboardEvents(event) {
120
+ if (event.code === "Tab" && this._recommendations?.length == 1) {
121
+ this._selectedRecommendation = null;
122
+ event.preventDefault();
123
+ this.parseInput(this._recommendations[0]);
124
+ }
125
+ else if (event.code === "ArrowDown" || event.code === "ArrowUp") {
126
+ event.preventDefault();
127
+ this.navigateRecommendations(event.code);
128
+ this.requestUpdate();
129
+ }
130
+ else if (event.code === "Enter" && this._selectedRecommendation) {
131
+ event.preventDefault();
132
+ this.parseInput(this._selectedRecommendation);
133
+ this._selectedRecommendation = null;
134
+ }
135
+ else if ((event.metaKey || event.ctrlKey) && event.code === "KeyZ") {
136
+ event.preventDefault();
137
+ if (event.shiftKey) {
138
+ this.redo();
139
+ }
140
+ else {
141
+ this.undo();
142
+ }
143
+ }
144
+ }
145
+ onClickRecommendation(recommendation) {
146
+ let editor = this.shadowRoot?.getElementById("wysiwyg-editor");
147
+ if (!editor)
148
+ return;
149
+ this.parseInput(recommendation);
150
+ this.currentCursorPosition = null;
151
+ }
152
+ /**
153
+ *
154
+ * @param recommendation The recommendation which needs to be inserted
155
+ * at the current cursor position
156
+ * @param manageCursor Whether or not cursor management is needed. Not
157
+ * needed when manual insertion of text is required (eg: during initialization)
158
+ * @returns void
159
+ */
160
+ parseInput(recommendation = null, manageCursor = true) {
161
+ let editor = this.shadowRoot?.getElementById("wysiwyg-editor");
162
+ if (!editor)
163
+ return;
164
+ /**
165
+ * @see https://github.com/WICG/webcomponents/issues/79
166
+ */
167
+ if (manageCursor)
168
+ this.currentCursorPosition = recommendation
169
+ ? this.currentCursorPosition
170
+ : Cursor.getCaretPosition(this.shadowRoot, editor);
171
+ const parseOutput = this._parser.parseInput(this.content, this.currentCursorPosition, recommendation);
172
+ this._recommendations = parseOutput.recommendations;
173
+ this._formattedContent = parseOutput.formattedContent;
174
+ this.errorString = parseOutput.errorString;
175
+ /**
176
+ * Don't modify the text stream manually if the text is being composed,
177
+ * unless the user manually chooses to do so by selecting a suggestion.
178
+ * @see https://github.com/w3c/input-events/issues/86
179
+ * @see https://github.com/w3c/input-events/pull/122
180
+ * @see https://bugs.chromium.org/p/chromium/issues/detail?id=689541
181
+ * */
182
+ if (this.lastInputType != "insertCompositionText" || recommendation) {
183
+ editor.innerHTML = parseOutput.formattedString;
184
+ }
185
+ this.content = editor.innerText;
186
+ if (recommendation) {
187
+ this._recommendations = null;
188
+ this.currentCursorPosition = parseOutput.newCursorPosition;
189
+ }
190
+ if (manageCursor)
191
+ Cursor.setCaretPosition(this.currentCursorPosition, editor);
192
+ editor?.focus();
193
+ if (manageCursor)
194
+ this.currentCursorRect = Cursor.getCursorRect(this.shadowRoot);
195
+ this.requestUpdate();
196
+ this.dispatchEvent(new CustomEvent("fw-formula-content-changed", {
197
+ detail: {
198
+ formulaString: this.content,
199
+ error: this.errorString,
200
+ recommendations: this._recommendations
201
+ },
202
+ bubbles: true,
203
+ }));
204
+ }
205
+ async requestCalculate() {
206
+ if (this._parser.parseInput(this.content).errorString) {
207
+ return;
208
+ }
209
+ this._isCalculating = true;
210
+ this.requestUpdate();
211
+ try {
212
+ const calculatedResult = this._parser.calculate(this.content);
213
+ this.content = this._parser.addParentheses(this.content) ?? this.content;
214
+ this.parseInput();
215
+ this._calculatedResult = calculatedResult.result;
216
+ this.errorString = calculatedResult.errorString;
217
+ }
218
+ finally {
219
+ this._isCalculating = false;
220
+ this._recommendations = null;
221
+ this.requestUpdate();
222
+ }
223
+ }
224
+ requestFormat() {
225
+ if (!Boolean(this.content)) {
226
+ return;
227
+ }
228
+ this.content = this._parser.addParentheses(this.content) ?? this.content;
229
+ this.parseInput();
230
+ this._recommendations = null;
231
+ this.requestUpdate();
232
+ }
233
+ async updated(_changedProperties) {
234
+ if (_changedProperties.has("content")) {
235
+ if (!this.content.trim()) {
236
+ this._recommendations = Array.from(this.variables.keys());
237
+ }
238
+ }
239
+ if (_changedProperties.has("variables")) {
240
+ this._parser = new Parser(this.variables, this.minSuggestionLen);
241
+ this.parseInput(null, false);
242
+ }
243
+ }
244
+ handleFocusOut(e) {
245
+ this.isFocus = false;
246
+ this._recommendations = null;
247
+ this.requestUpdate();
248
+ }
249
+ handleFocus(e) {
250
+ this.isFocus = true;
251
+ if (!this.content.trim()) {
252
+ this._recommendations = Array.from(this.variables.keys());
253
+ }
254
+ }
255
+ render() {
256
+ return html `
257
+ <style>
258
+ ${FormulaEditorStyles}
259
+ </style>
260
+
261
+ ${this.label
262
+ ? html `<label for="wysiwyg-editor" class="formula-editor-label">
263
+ ${this.label}
264
+ </label>`
265
+ : ""}
266
+
267
+ <div
268
+ contenteditable
269
+ placeholder=${this.placeholder}
270
+ id="wysiwyg-editor"
271
+ spellcheck="false"
272
+ autocomplete="off"
273
+ role="textbox"
274
+ class=${this._isCalculating ? 'loading' : ''}
275
+ aria-label="Formula editor"
276
+ aria-placeholder=${this.placeholder}
277
+ aria-invalid=${Boolean(this.errorString)}
278
+ aria-describedby=${this.errorString ? "error-message" : null}
279
+ @input=${this.handleChange}
280
+ @keydown=${this.handleKeyboardEvents}
281
+ @blur=${this.handleFocusOut}
282
+ @focus=${this.handleFocus}
283
+ @paste=${this.handlePaste}
284
+ ></div>
285
+ ${this.errorString ? html `
286
+ <div id="error-message" class="error-message" role="alert">
287
+ ${this.errorString}
288
+ </div>
289
+ ` : null}
290
+ ${this.isFocus ? html `
291
+ <suggestion-menu
292
+ .recommendations=${this._recommendations ?? []}
293
+ .currentSelection=${this._selectedRecommendation}
294
+ .onClickRecommendation=${(e) => this.onClickRecommendation(e)}
295
+ .variables=${this.variables}
296
+ .constants=${this._parser.constants}
297
+ .isLoading=${this._inputDebounceTimer !== null}
298
+ @mousedown=${(e) => e.preventDefault()}
299
+ ></suggestion-menu>
300
+ ` : html ``}
301
+ ${this._calculatedResult !== undefined ? html `
302
+ <p role="status" aria-live="polite">Result: ${this._calculatedResult}</p>
303
+ ` : null}
304
+ `;
305
+ }
306
+ };
307
+ __decorate([
308
+ state()
309
+ ], FormulaEditor.prototype, "_formattedContent", void 0);
310
+ __decorate([
311
+ state()
312
+ ], FormulaEditor.prototype, "_recommendations", void 0);
313
+ __decorate([
314
+ state()
315
+ ], FormulaEditor.prototype, "_calculatedResult", void 0);
316
+ __decorate([
317
+ state()
318
+ ], FormulaEditor.prototype, "currentCursorPosition", void 0);
319
+ __decorate([
320
+ state()
321
+ ], FormulaEditor.prototype, "currentCursorRect", void 0);
322
+ __decorate([
323
+ state()
324
+ ], FormulaEditor.prototype, "lastInputType", void 0);
325
+ __decorate([
326
+ state()
327
+ ], FormulaEditor.prototype, "_selectedRecommendation", void 0);
328
+ __decorate([
329
+ state()
330
+ ], FormulaEditor.prototype, "isFocus", void 0);
331
+ __decorate([
332
+ property()
333
+ ], FormulaEditor.prototype, "content", void 0);
334
+ __decorate([
335
+ property()
336
+ ], FormulaEditor.prototype, "placeholder", void 0);
337
+ __decorate([
338
+ property()
339
+ ], FormulaEditor.prototype, "label", void 0);
340
+ __decorate([
341
+ property({
342
+ type: (Map),
343
+ converter: {
344
+ fromAttribute: (value) => {
345
+ if (value) {
346
+ return new Map(JSON.parse(value));
347
+ }
348
+ },
349
+ toAttribute: (value) => {
350
+ return JSON.stringify(Array.from(value.entries()));
351
+ },
352
+ },
353
+ })
354
+ ], FormulaEditor.prototype, "variables", void 0);
355
+ __decorate([
356
+ property()
357
+ ], FormulaEditor.prototype, "minSuggestionLen", void 0);
358
+ __decorate([
359
+ property()
360
+ ], FormulaEditor.prototype, "errorString", void 0);
361
+ __decorate([
362
+ query("wysiwyg-editor")
363
+ ], FormulaEditor.prototype, "editor", void 0);
364
+ FormulaEditor = __decorate([
365
+ customElement("formula-editor")
366
+ ], FormulaEditor);
367
+ export { FormulaEditor };
@@ -0,0 +1,16 @@
1
+ export var Operator;
2
+ (function (Operator) {
3
+ Operator["PLUS"] = "+";
4
+ Operator["MINUS"] = "-";
5
+ Operator["MUL"] = "*";
6
+ Operator["DIV"] = "/";
7
+ Operator["NONE"] = "";
8
+ })(Operator || (Operator = {}));
9
+ export class Formula {
10
+ constructor(name, formulaString, precision = -1) {
11
+ this.error = null;
12
+ this.name = name || "";
13
+ this.formulaString = formulaString || "";
14
+ this.precision = precision;
15
+ }
16
+ }
@@ -0,0 +1,72 @@
1
+ export class Stack {
2
+ constructor() {
3
+ this._elements = [];
4
+ }
5
+ push(item) {
6
+ this._elements.push(item);
7
+ }
8
+ pop() {
9
+ return this._elements.pop();
10
+ }
11
+ top() {
12
+ return this._elements.at(-1);
13
+ }
14
+ isEmpty() {
15
+ return this._elements.length == 0;
16
+ }
17
+ print() {
18
+ console.log(this._elements);
19
+ }
20
+ }
21
+ export class Queue {
22
+ constructor() {
23
+ this._elements = {};
24
+ this._head = 0;
25
+ this._tail = 0;
26
+ }
27
+ enqueue(item) {
28
+ this._elements[this._tail] = item;
29
+ this._tail++;
30
+ }
31
+ dequeue() {
32
+ if (this._tail === this._head)
33
+ return undefined;
34
+ const element = this._elements[this._head];
35
+ delete this._elements[this._head];
36
+ this._head++;
37
+ return element;
38
+ }
39
+ peek() {
40
+ return this._elements[this._head];
41
+ }
42
+ isEmpty() {
43
+ return this._head == this._tail;
44
+ }
45
+ print() {
46
+ console.log(this._elements);
47
+ }
48
+ toArray() {
49
+ const result = [];
50
+ for (let i = this._head; i < this._tail; i++) {
51
+ if (this._elements[i] !== undefined) {
52
+ result.push(this._elements[i]);
53
+ }
54
+ }
55
+ return result;
56
+ }
57
+ clone() {
58
+ const newQueue = new Queue();
59
+ Object.entries(this._elements).forEach(([key, value]) => {
60
+ newQueue._elements[parseInt(key)] = value;
61
+ });
62
+ newQueue._head = this._head;
63
+ newQueue._tail = this._tail;
64
+ return newQueue;
65
+ }
66
+ }
67
+ export var Expectation;
68
+ (function (Expectation) {
69
+ Expectation[Expectation["VARIABLE"] = 0] = "VARIABLE";
70
+ Expectation[Expectation["OPERATOR"] = 1] = "OPERATOR";
71
+ Expectation[Expectation["UNDEFINED"] = 2] = "UNDEFINED";
72
+ })(Expectation || (Expectation = {}));