@fw-components/formula-editor 2.0.3-formula-editor.1 → 2.0.7-formula-editor.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.
@@ -1,141 +0,0 @@
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
- }
@@ -1,99 +0,0 @@
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
- }
@@ -1,236 +0,0 @@
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
- }
@@ -1,20 +0,0 @@
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
- }
package/src/helpers.ts DELETED
@@ -1,62 +0,0 @@
1
- export class Stack<Type> {
2
- private _elements: Type[] = [];
3
-
4
- push(item: Type): void {
5
- this._elements.push(item);
6
- }
7
-
8
- pop(): Type | undefined {
9
- return this._elements.pop();
10
- }
11
-
12
- top(): Type | undefined {
13
- return this._elements.at(-1);
14
- }
15
-
16
- isEmpty(): boolean {
17
- return this._elements.length == 0;
18
- }
19
-
20
- print(): void {
21
- console.log(this._elements);
22
- }
23
- }
24
-
25
- export class Queue<Type> {
26
- private _elements: { [key: number]: Type } = {};
27
- private _head: number = 0;
28
- private _tail: number = 0;
29
-
30
- enqueue(item: Type): void {
31
- this._elements[this._tail] = item;
32
- this._tail++;
33
- }
34
-
35
- dequeue(): Type | undefined {
36
- if (this._tail === this._head) return undefined;
37
-
38
- const element = this._elements[this._head];
39
- delete this._elements[this._head];
40
- this._head++;
41
-
42
- return element;
43
- }
44
-
45
- peek(): Type {
46
- return this._elements[this._head];
47
- }
48
-
49
- isEmpty(): boolean {
50
- return this._head == this._tail;
51
- }
52
-
53
- print(): void {
54
- console.log(this._elements);
55
- }
56
- }
57
-
58
- export enum Expectation {
59
- VARIABLE,
60
- OPERATOR,
61
- UNDEFINED,
62
- }