@masterteam/components 0.0.185 → 0.0.186

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 (82) hide show
  1. package/README.md +70 -63
  2. package/assets/common.css +243 -2
  3. package/fesm2022/masterteam-components-table.mjs +1 -0
  4. package/fesm2022/masterteam-components-table.mjs.map +1 -1
  5. package/fesm2022/masterteam-components-text-field.mjs +8 -3
  6. package/fesm2022/masterteam-components-text-field.mjs.map +1 -1
  7. package/fesm2022/masterteam-components-user-search-field.mjs +27 -6
  8. package/fesm2022/masterteam-components-user-search-field.mjs.map +1 -1
  9. package/package.json +2 -2
  10. package/types/masterteam-components-user-search-field.d.ts +3 -0
  11. package/fesm2022/masterteam-components-color-picker-field.mjs +0 -102
  12. package/fesm2022/masterteam-components-color-picker-field.mjs.map +0 -1
  13. package/fesm2022/masterteam-components-drawer.mjs +0 -261
  14. package/fesm2022/masterteam-components-drawer.mjs.map +0 -1
  15. package/fesm2022/masterteam-components-editor-field.mjs +0 -99
  16. package/fesm2022/masterteam-components-editor-field.mjs.map +0 -1
  17. package/fesm2022/masterteam-components-formula.mjs +0 -3618
  18. package/fesm2022/masterteam-components-formula.mjs.map +0 -1
  19. package/fesm2022/masterteam-components-icon-field.mjs +0 -161
  20. package/fesm2022/masterteam-components-icon-field.mjs.map +0 -1
  21. package/fesm2022/masterteam-components-list.mjs +0 -31
  22. package/fesm2022/masterteam-components-list.mjs.map +0 -1
  23. package/fesm2022/masterteam-components-location-field.mjs +0 -315
  24. package/fesm2022/masterteam-components-location-field.mjs.map +0 -1
  25. package/fesm2022/masterteam-components-menu.mjs +0 -135
  26. package/fesm2022/masterteam-components-menu.mjs.map +0 -1
  27. package/fesm2022/masterteam-components-module-summary-card.mjs +0 -34
  28. package/fesm2022/masterteam-components-module-summary-card.mjs.map +0 -1
  29. package/fesm2022/masterteam-components-page-header.mjs +0 -42
  30. package/fesm2022/masterteam-components-page-header.mjs.map +0 -1
  31. package/fesm2022/masterteam-components-page.mjs +0 -35
  32. package/fesm2022/masterteam-components-page.mjs.map +0 -1
  33. package/fesm2022/masterteam-components-pick-list-field.mjs +0 -206
  34. package/fesm2022/masterteam-components-pick-list-field.mjs.map +0 -1
  35. package/fesm2022/masterteam-components-property-filter-builder.mjs +0 -386
  36. package/fesm2022/masterteam-components-property-filter-builder.mjs.map +0 -1
  37. package/fesm2022/masterteam-components-radio-button-field.mjs +0 -85
  38. package/fesm2022/masterteam-components-radio-button-field.mjs.map +0 -1
  39. package/fesm2022/masterteam-components-radio-cards-field.mjs +0 -126
  40. package/fesm2022/masterteam-components-radio-cards-field.mjs.map +0 -1
  41. package/fesm2022/masterteam-components-radio-cards.mjs +0 -74
  42. package/fesm2022/masterteam-components-radio-cards.mjs.map +0 -1
  43. package/fesm2022/masterteam-components-runtime-action.mjs +0 -406
  44. package/fesm2022/masterteam-components-runtime-action.mjs.map +0 -1
  45. package/fesm2022/masterteam-components-sidebar.mjs +0 -37
  46. package/fesm2022/masterteam-components-sidebar.mjs.map +0 -1
  47. package/fesm2022/masterteam-components-slider-field.mjs +0 -115
  48. package/fesm2022/masterteam-components-slider-field.mjs.map +0 -1
  49. package/fesm2022/masterteam-components-statistic-card.mjs +0 -22
  50. package/fesm2022/masterteam-components-statistic-card.mjs.map +0 -1
  51. package/fesm2022/masterteam-components-textarea-field.mjs +0 -122
  52. package/fesm2022/masterteam-components-textarea-field.mjs.map +0 -1
  53. package/fesm2022/masterteam-components-toast.mjs +0 -80
  54. package/fesm2022/masterteam-components-toast.mjs.map +0 -1
  55. package/fesm2022/masterteam-components-topbar.mjs +0 -32
  56. package/fesm2022/masterteam-components-topbar.mjs.map +0 -1
  57. package/fesm2022/masterteam-components-tree.mjs +0 -260
  58. package/fesm2022/masterteam-components-tree.mjs.map +0 -1
  59. package/types/masterteam-components-color-picker-field.d.ts +0 -35
  60. package/types/masterteam-components-drawer.d.ts +0 -61
  61. package/types/masterteam-components-editor-field.d.ts +0 -35
  62. package/types/masterteam-components-formula.d.ts +0 -734
  63. package/types/masterteam-components-icon-field.d.ts +0 -40
  64. package/types/masterteam-components-list.d.ts +0 -18
  65. package/types/masterteam-components-location-field.d.ts +0 -95
  66. package/types/masterteam-components-menu.d.ts +0 -55
  67. package/types/masterteam-components-module-summary-card.d.ts +0 -18
  68. package/types/masterteam-components-page-header.d.ts +0 -30
  69. package/types/masterteam-components-page.d.ts +0 -26
  70. package/types/masterteam-components-pick-list-field.d.ts +0 -61
  71. package/types/masterteam-components-property-filter-builder.d.ts +0 -90
  72. package/types/masterteam-components-radio-button-field.d.ts +0 -41
  73. package/types/masterteam-components-radio-cards-field.d.ts +0 -35
  74. package/types/masterteam-components-radio-cards.d.ts +0 -33
  75. package/types/masterteam-components-runtime-action.d.ts +0 -105
  76. package/types/masterteam-components-sidebar.d.ts +0 -28
  77. package/types/masterteam-components-slider-field.d.ts +0 -38
  78. package/types/masterteam-components-statistic-card.d.ts +0 -18
  79. package/types/masterteam-components-textarea-field.d.ts +0 -41
  80. package/types/masterteam-components-toast.d.ts +0 -27
  81. package/types/masterteam-components-topbar.d.ts +0 -20
  82. package/types/masterteam-components-tree.d.ts +0 -106
@@ -1,3618 +0,0 @@
1
- import * as i0 from '@angular/core';
2
- import { input, output, signal, computed, effect, forwardRef, Component, viewChild, inject, NgZone, ViewEncapsulation, ChangeDetectionStrategy, contentChild, TemplateRef } from '@angular/core';
3
- import * as i1$2 from '@angular/common';
4
- import { CommonModule, DOCUMENT } from '@angular/common';
5
- import * as i2 from '@angular/forms';
6
- import { FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms';
7
- import * as i1 from '@angular/cdk/drag-drop';
8
- import { moveItemInArray, DragDropModule } from '@angular/cdk/drag-drop';
9
- import * as i3 from '@jsverse/transloco';
10
- import { TranslocoPipe, TranslocoService, TranslocoModule } from '@jsverse/transloco';
11
- import { Subject, isObservable, from, firstValueFrom, of } from 'rxjs';
12
- import { debounceTime, filter, takeUntil, catchError } from 'rxjs/operators';
13
- import * as i1$1 from 'primeng/tooltip';
14
- import { TooltipModule } from 'primeng/tooltip';
15
-
16
- /**
17
- * Flat Formula Token Model
18
- *
19
- * The formula is represented as a FLAT array of tokens.
20
- * This approach provides:
21
- * - Better performance (no deep component nesting)
22
- * - Solid drag-drop behavior (functions move as complete units)
23
- * - Simple serialization (just join token values)
24
- *
25
- * STRUCTURE RULES:
26
- * - fn-open: "IF(" - function name + opening paren as ONE token
27
- * - fn-close: ")" - closing paren, belongs to a function
28
- * - fn-separator: "," - argument separator, belongs to a function
29
- * - Dragging any structural token moves the ENTIRE function
30
- * - Content tokens (property, operator, literal) can move individually
31
- */
32
- // ============ UTILITY FUNCTIONS ============
33
- /** Generate unique token ID */
34
- function generateTokenId() {
35
- return `tok_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
36
- }
37
- /** Generate unique function ID */
38
- function generateFunctionId() {
39
- return `fn_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
40
- }
41
- /** Parse function signature like "SUM(values)" or "IF(cond, a, b)" */
42
- function parseSignature(signature) {
43
- const match = signature.match(/^(\w+)\((.*)\)$/);
44
- if (!match)
45
- return { name: signature, args: [] };
46
- const name = match[1];
47
- const argsStr = match[2].trim();
48
- if (!argsStr)
49
- return { name, args: [] };
50
- const args = [];
51
- let current = '';
52
- let depth = 0;
53
- for (const char of argsStr) {
54
- if (char === '(')
55
- depth++;
56
- else if (char === ')')
57
- depth--;
58
- else if (char === ',' && depth === 0) {
59
- args.push(current.trim());
60
- current = '';
61
- continue;
62
- }
63
- current += char;
64
- }
65
- if (current.trim())
66
- args.push(current.trim());
67
- return { name, args };
68
- }
69
- /**
70
- * Create a function's tokens from signature
71
- * e.g., "IF(condition, trueVal, falseVal)" creates:
72
- * - fn-open: "IF("
73
- * - fn-separator: "," (x2)
74
- * - fn-close: ")"
75
- */
76
- function createFunctionTokens(signature, depth = 0) {
77
- const parsed = parseSignature(signature);
78
- const functionId = generateFunctionId();
79
- const tokens = [];
80
- // Opening token: "NAME("
81
- tokens.push({
82
- id: generateTokenId(),
83
- type: 'fn-open',
84
- value: `${parsed.name}(`,
85
- functionId,
86
- functionName: parsed.name,
87
- depth,
88
- dragBehavior: 'function',
89
- });
90
- // Separators for arguments (one less than arg count)
91
- for (let i = 0; i < parsed.args.length - 1; i++) {
92
- tokens.push({
93
- id: generateTokenId(),
94
- type: 'fn-separator',
95
- value: ',',
96
- functionId,
97
- depth,
98
- argIndex: i, // Separator AFTER this argument
99
- dragBehavior: 'function',
100
- });
101
- }
102
- // Closing token: ")"
103
- tokens.push({
104
- id: generateTokenId(),
105
- type: 'fn-close',
106
- value: ')',
107
- functionId,
108
- depth,
109
- dragBehavior: 'function',
110
- });
111
- return tokens;
112
- }
113
- /**
114
- * Create a property token
115
- */
116
- function createPropertyToken(propertyKey, propertyType = 'current', depth = 0, functionId, argIndex, display) {
117
- const usesFullPath = propertyKey.startsWith('@');
118
- const prefix = propertyType === 'current'
119
- ? '@'
120
- : propertyType === 'children'
121
- ? '*.'
122
- : '$.';
123
- return {
124
- id: generateTokenId(),
125
- type: 'property',
126
- value: usesFullPath ? propertyKey : `${prefix}${propertyKey}`,
127
- display,
128
- propertyType,
129
- depth,
130
- functionId,
131
- argIndex,
132
- dragBehavior: 'single',
133
- };
134
- }
135
- /**
136
- * Create an operator token
137
- */
138
- function createOperatorToken(symbol, depth = 0, functionId, argIndex) {
139
- return {
140
- id: generateTokenId(),
141
- type: 'operator',
142
- value: symbol,
143
- depth,
144
- functionId,
145
- argIndex,
146
- dragBehavior: 'single',
147
- };
148
- }
149
- /**
150
- * Create a literal token
151
- */
152
- function createLiteralToken(value, depth = 0, functionId, argIndex) {
153
- let displayValue = String(value);
154
- let literalType = 'string';
155
- if (typeof value === 'number') {
156
- literalType = 'number';
157
- }
158
- else if (typeof value === 'boolean') {
159
- literalType = 'boolean';
160
- }
161
- else if (typeof value === 'string' && !value.startsWith('"')) {
162
- displayValue = `"${value}"`;
163
- }
164
- return {
165
- id: generateTokenId(),
166
- type: 'literal',
167
- value: displayValue,
168
- literalType,
169
- depth,
170
- functionId,
171
- argIndex,
172
- dragBehavior: 'single',
173
- };
174
- }
175
- /**
176
- * Create a raw text token for identifiers or syntax fragments that are not
177
- * properties, literals, or operators.
178
- */
179
- function createTextToken(value, depth = 0, functionId, argIndex) {
180
- return {
181
- id: generateTokenId(),
182
- type: 'text',
183
- value,
184
- depth,
185
- functionId,
186
- argIndex,
187
- dragBehavior: 'single',
188
- };
189
- }
190
- // ============ TOKEN ARRAY OPERATIONS ============
191
- /**
192
- * Find the complete range of a function in the token array
193
- * This includes ALL tokens between fn-open and fn-close (including nested content)
194
- * Returns [startIndex, endIndex] inclusive
195
- */
196
- function findFunctionRange(tokens, functionId) {
197
- // Find the fn-open token with this functionId
198
- const openIndex = tokens.findIndex((t) => t.functionId === functionId && t.type === 'fn-open');
199
- if (openIndex === -1)
200
- return null;
201
- // Now find the matching fn-close by counting depth
202
- // Start from fn-open and find matching close paren
203
- let depth = 1;
204
- for (let i = openIndex + 1; i < tokens.length; i++) {
205
- const token = tokens[i];
206
- if (token.type === 'fn-open') {
207
- depth++;
208
- }
209
- else if (token.type === 'fn-close') {
210
- depth--;
211
- if (depth === 0) {
212
- // Found the matching close
213
- return [openIndex, i];
214
- }
215
- }
216
- }
217
- // Fallback: find fn-close with same functionId
218
- const closeIndex = tokens.findIndex((t) => t.functionId === functionId && t.type === 'fn-close');
219
- if (closeIndex === -1)
220
- return null;
221
- return [openIndex, closeIndex];
222
- }
223
- /**
224
- * Get all tokens belonging to a function (including nested content)
225
- */
226
- function getFunctionTokens(tokens, functionId) {
227
- const range = findFunctionRange(tokens, functionId);
228
- if (!range)
229
- return [];
230
- return tokens.slice(range[0], range[1] + 1);
231
- }
232
- /**
233
- * Validate if a drop position is allowed
234
- */
235
- function isValidDropPosition(tokens, dropIndex, draggedTokens) {
236
- // Can always drop at start or end
237
- if (dropIndex === 0 || dropIndex === tokens.length)
238
- return true;
239
- const _prevToken = tokens[dropIndex - 1];
240
- const _nextToken = tokens[dropIndex];
241
- // If dragging a function, check if it would create invalid nesting
242
- const isDraggingFunction = draggedTokens.some((t) => t.type === 'fn-open' || t.type === 'fn-close');
243
- if (isDraggingFunction) {
244
- // Don't allow dropping a function that would break structure
245
- // For now, allow all - we can refine later
246
- }
247
- return true;
248
- }
249
- /**
250
- * Serialize tokens to formula string
251
- */
252
- function serializeTokens(tokens) {
253
- const parts = [];
254
- let lastType = null;
255
- let lastValue = '';
256
- for (const token of tokens) {
257
- if (shouldInsertSpace(lastType, lastValue, token)) {
258
- parts.push(' ');
259
- }
260
- parts.push(token.value);
261
- lastType = token.type;
262
- lastValue = token.value;
263
- }
264
- return parts.join('');
265
- }
266
- function shouldInsertSpace(previousType, previousValue, current) {
267
- if (!previousType)
268
- return false;
269
- if (previousType === 'fn-open')
270
- return false;
271
- if (current.type === 'fn-close')
272
- return false;
273
- if (current.type === 'fn-separator')
274
- return false;
275
- if (previousType === 'fn-separator')
276
- return true;
277
- if (current.value === ':')
278
- return false;
279
- if (previousValue === ':')
280
- return true;
281
- return true;
282
- }
283
- /**
284
- * Clone a token with new ID
285
- */
286
- function cloneToken(token) {
287
- return {
288
- ...token,
289
- id: generateTokenId(),
290
- };
291
- }
292
- /**
293
- * Clone multiple tokens with new IDs and new function IDs
294
- */
295
- function cloneTokens(tokens) {
296
- // Map old function IDs to new ones
297
- const functionIdMap = new Map();
298
- return tokens.map((token) => {
299
- const newToken = cloneToken(token);
300
- // Remap function IDs
301
- if (token.functionId) {
302
- if (!functionIdMap.has(token.functionId)) {
303
- functionIdMap.set(token.functionId, generateFunctionId());
304
- }
305
- newToken.functionId = functionIdMap.get(token.functionId);
306
- }
307
- return newToken;
308
- });
309
- }
310
- /**
311
- * Update depth for all tokens (after move)
312
- */
313
- function recalculateDepths(tokens) {
314
- let currentDepth = 0;
315
- const result = [];
316
- for (const token of tokens) {
317
- if (token.type === 'fn-open') {
318
- result.push({ ...token, depth: currentDepth });
319
- currentDepth++;
320
- }
321
- else if (token.type === 'fn-close') {
322
- currentDepth--;
323
- result.push({ ...token, depth: currentDepth });
324
- }
325
- else {
326
- result.push({ ...token, depth: currentDepth });
327
- }
328
- }
329
- return result;
330
- }
331
- /**
332
- * Convert a backend template or insertText into builder tokens while
333
- * preserving the authored syntax as closely as the flat token model allows.
334
- */
335
- function tokenizeFormulaTemplate(template) {
336
- const source = template.trim();
337
- if (!source)
338
- return [];
339
- let index = 0;
340
- const parseExpression = (context) => {
341
- const tokens = [];
342
- while (index < source.length) {
343
- skipWhitespace();
344
- if (index >= source.length)
345
- break;
346
- const char = source[index];
347
- if (char === ',' || char === ')') {
348
- break;
349
- }
350
- if (char === '@') {
351
- tokens.push(createPropertyToken(readPropertyPath(), 'current', context.depth, context.functionId, context.argIndex));
352
- continue;
353
- }
354
- if (char === '"' || char === "'") {
355
- tokens.push(createLiteralToken(readQuotedString(), context.depth, context.functionId, context.argIndex));
356
- continue;
357
- }
358
- if (isDigit(char)) {
359
- tokens.push(createLiteralToken(Number(readNumber()), context.depth, context.functionId, context.argIndex));
360
- continue;
361
- }
362
- if (char === '-' &&
363
- isDigit(source[index + 1] ?? '') &&
364
- shouldReadNegativeNumber(tokens)) {
365
- tokens.push(createLiteralToken(Number(readNumber()), context.depth, context.functionId, context.argIndex));
366
- continue;
367
- }
368
- if (isIdentifierStart(char)) {
369
- const identifier = readIdentifier();
370
- skipWhitespace();
371
- if (source[index] === '(') {
372
- tokens.push(...parseFunction(identifier, context.depth));
373
- continue;
374
- }
375
- if (identifier === 'true' || identifier === 'false') {
376
- tokens.push(createLiteralToken(identifier === 'true', context.depth, context.functionId, context.argIndex));
377
- continue;
378
- }
379
- if (identifier === 'null') {
380
- tokens.push(createTextToken(identifier, context.depth, context.functionId, context.argIndex));
381
- continue;
382
- }
383
- tokens.push(createTextToken(identifier, context.depth, context.functionId, context.argIndex));
384
- continue;
385
- }
386
- const operator = readOperator();
387
- if (operator) {
388
- tokens.push(createOperatorToken(operator, context.depth, context.functionId, context.argIndex));
389
- continue;
390
- }
391
- tokens.push(createTextToken(char, context.depth, context.functionId, context.argIndex));
392
- index += 1;
393
- }
394
- return tokens;
395
- };
396
- const parseFunction = (name, depth) => {
397
- const functionId = generateFunctionId();
398
- const tokens = [
399
- {
400
- id: generateTokenId(),
401
- type: 'fn-open',
402
- value: `${name}(`,
403
- functionId,
404
- functionName: name,
405
- depth,
406
- dragBehavior: 'function',
407
- },
408
- ];
409
- index += 1; // consume '('
410
- let argIndex = 0;
411
- while (index < source.length) {
412
- skipWhitespace();
413
- if (source[index] === ')') {
414
- index += 1;
415
- break;
416
- }
417
- tokens.push(...parseExpression({
418
- depth: depth + 1,
419
- functionId,
420
- argIndex,
421
- }));
422
- skipWhitespace();
423
- if (source[index] === ',') {
424
- tokens.push({
425
- id: generateTokenId(),
426
- type: 'fn-separator',
427
- value: ',',
428
- functionId,
429
- depth,
430
- argIndex,
431
- dragBehavior: 'function',
432
- });
433
- argIndex += 1;
434
- index += 1;
435
- continue;
436
- }
437
- if (source[index] === ')') {
438
- index += 1;
439
- break;
440
- }
441
- }
442
- tokens.push({
443
- id: generateTokenId(),
444
- type: 'fn-close',
445
- value: ')',
446
- functionId,
447
- depth,
448
- dragBehavior: 'function',
449
- });
450
- return tokens;
451
- };
452
- const skipWhitespace = () => {
453
- while (index < source.length && /\s/.test(source[index])) {
454
- index += 1;
455
- }
456
- };
457
- const readQuotedString = () => {
458
- const quote = source[index];
459
- let value = quote;
460
- index += 1;
461
- while (index < source.length) {
462
- const char = source[index];
463
- value += char;
464
- index += 1;
465
- if (char === '\\' && index < source.length) {
466
- value += source[index];
467
- index += 1;
468
- continue;
469
- }
470
- if (char === quote) {
471
- break;
472
- }
473
- }
474
- return value;
475
- };
476
- const readNumber = () => {
477
- const start = index;
478
- if (source[index] === '-') {
479
- index += 1;
480
- }
481
- while (index < source.length && /[0-9.]/.test(source[index])) {
482
- index += 1;
483
- }
484
- return source.slice(start, index);
485
- };
486
- const readIdentifier = () => {
487
- const start = index;
488
- index += 1;
489
- while (index < source.length && /[\w]/.test(source[index])) {
490
- index += 1;
491
- }
492
- return source.slice(start, index);
493
- };
494
- const readPropertyPath = () => {
495
- const start = index;
496
- index += 1;
497
- while (index < source.length) {
498
- const char = source[index];
499
- const next = source[index + 1] ?? '';
500
- if (/\s/.test(char) || char === ',' || char === ')' || char === '(') {
501
- break;
502
- }
503
- if (/[+\-*/%<>=!&|?:]/.test(char) && !(char === ':' && next === ':')) {
504
- break;
505
- }
506
- index += 1;
507
- }
508
- return source.slice(start, index);
509
- };
510
- const readOperator = () => {
511
- const operators = [
512
- '==',
513
- '!=',
514
- '>=',
515
- '<=',
516
- '&&',
517
- '||',
518
- ':',
519
- '+',
520
- '-',
521
- '*',
522
- '/',
523
- '%',
524
- '>',
525
- '<',
526
- '!',
527
- '?',
528
- ];
529
- for (const operator of operators) {
530
- if (source.startsWith(operator, index)) {
531
- index += operator.length;
532
- return operator;
533
- }
534
- }
535
- return null;
536
- };
537
- return recalculateDepths(parseExpression({ depth: 0 }));
538
- }
539
- function isDigit(value) {
540
- return /[0-9]/.test(value);
541
- }
542
- function isIdentifierStart(value) {
543
- return /[A-Za-z_]/.test(value);
544
- }
545
- function shouldReadNegativeNumber(tokens) {
546
- const previous = tokens[tokens.length - 1];
547
- if (!previous)
548
- return true;
549
- return previous.type === 'operator' || previous.type === 'fn-open';
550
- }
551
- /**
552
- * Find which argument index a position belongs to within a function
553
- */
554
- function getArgumentIndexAtPosition(tokens, functionId, position) {
555
- const range = findFunctionRange(tokens, functionId);
556
- if (!range)
557
- return 0;
558
- let argIndex = 0;
559
- for (let i = range[0] + 1; i < position && i <= range[1]; i++) {
560
- if (tokens[i].type === 'fn-separator' &&
561
- tokens[i].functionId === functionId) {
562
- argIndex++;
563
- }
564
- }
565
- return argIndex;
566
- }
567
-
568
- /**
569
- * Smart Formula Block - Types and Factory Functions
570
- * Defines the block structure and creation helpers
571
- */
572
- /** Generate unique block ID */
573
- function generateSmartBlockId() {
574
- return `sb_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
575
- }
576
- /** Create a function block from signature */
577
- function createFunctionBlock(signature, name, insertText, cursorOffset) {
578
- const parsed = parseSignature(signature);
579
- return {
580
- id: generateSmartBlockId(),
581
- type: 'function',
582
- value: parsed.name,
583
- functionName: name || parsed.name,
584
- signature,
585
- insertText,
586
- cursorOffset,
587
- arguments: parsed.args.map((arg) => ({
588
- id: generateSmartBlockId(),
589
- name: arg,
590
- blocks: [],
591
- placeholder: arg,
592
- })),
593
- };
594
- }
595
- /** Create a property block */
596
- function createPropertyBlock(propertyKey, propertyType = 'current', display) {
597
- const usesFullPath = propertyKey.startsWith('@');
598
- const prefix = propertyType === 'current'
599
- ? '@'
600
- : propertyType === 'children'
601
- ? '*.'
602
- : '$.';
603
- return {
604
- id: generateSmartBlockId(),
605
- type: 'property',
606
- value: usesFullPath ? propertyKey : `${prefix}${propertyKey}`,
607
- display,
608
- propertyType,
609
- propertyKey,
610
- };
611
- }
612
- /** Create an operator block */
613
- function createOperatorBlock(symbol) {
614
- return {
615
- id: generateSmartBlockId(),
616
- type: 'operator',
617
- value: symbol,
618
- operatorSymbol: symbol,
619
- };
620
- }
621
- /** Create a literal block */
622
- function createLiteralBlock(value) {
623
- return {
624
- id: generateSmartBlockId(),
625
- type: 'literal',
626
- value: String(value),
627
- literalValue: value,
628
- };
629
- }
630
- /** Deep clone a block with new IDs */
631
- function cloneBlock(block) {
632
- const newBlock = { ...block, id: generateSmartBlockId() };
633
- if (block.arguments) {
634
- newBlock.arguments = block.arguments.map((arg) => ({
635
- ...arg,
636
- id: generateSmartBlockId(),
637
- blocks: arg.blocks.map((b) => cloneBlock(b)),
638
- }));
639
- }
640
- return newBlock;
641
- }
642
-
643
- /**
644
- * Validation Result Models
645
- * API response types for formula validation
646
- */
647
-
648
- /**
649
- * Formula Block Model - Types for formula functions and operators
650
- */
651
-
652
- // Models index
653
-
654
- class FormulaEditor {
655
- // ============ INPUTS ============
656
- placeholder = input('Click toolbar items to build formula...', ...(ngDevMode ? [{ debugName: "placeholder" }] : /* istanbul ignore next */ []));
657
- initialTokens = input([], ...(ngDevMode ? [{ debugName: "initialTokens" }] : /* istanbul ignore next */ []));
658
- disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
659
- borderless = input(false, ...(ngDevMode ? [{ debugName: "borderless" }] : /* istanbul ignore next */ []));
660
- // ============ OUTPUTS ============
661
- formulaChange = output();
662
- tokensChange = output();
663
- onBlur = output();
664
- onFocus = output();
665
- // ============ STATE ============
666
- tokens = signal([], ...(ngDevMode ? [{ debugName: "tokens" }] : /* istanbul ignore next */ []));
667
- /** Index range being dragged [start, end] inclusive */
668
- draggedRange = null;
669
- /** Is currently dragging */
670
- isDragging = signal(false, ...(ngDevMode ? [{ debugName: "isDragging" }] : /* istanbul ignore next */ []));
671
- /** Hovered function ID for highlighting */
672
- hoveredFunctionId = signal(null, ...(ngDevMode ? [{ debugName: "hoveredFunctionId" }] : /* istanbul ignore next */ []));
673
- /** Is focused */
674
- isFocused = signal(false, ...(ngDevMode ? [{ debugName: "isFocused" }] : /* istanbul ignore next */ []));
675
- // ============ CVA ============
676
- onChange = () => { };
677
- onTouched = () => { };
678
- // ============ COMPUTED ============
679
- containerClasses = computed(() => {
680
- const base = 'flex min-h-20 font-mono text-sm bg-white dark:bg-surface-800';
681
- if (this.borderless()) {
682
- return base;
683
- }
684
- return `${base} border border-surface-200 dark:border-surface-700 rounded-md focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/10`;
685
- }, ...(ngDevMode ? [{ debugName: "containerClasses" }] : /* istanbul ignore next */ []));
686
- lineNumberClasses = computed(() => {
687
- const base = 'flex flex-col px-1.5 py-2 bg-surface-50 dark:bg-surface-900 border-r border-surface-200 dark:border-surface-700 select-none min-w-6 text-right';
688
- if (this.borderless()) {
689
- return base;
690
- }
691
- return `${base} rounded-l-md`;
692
- }, ...(ngDevMode ? [{ debugName: "lineNumberClasses" }] : /* istanbul ignore next */ []));
693
- /** Line numbers based on token count */
694
- lines = computed(() => {
695
- const count = Math.max(1, Math.ceil(this.tokens().length / 8));
696
- return Array(count).fill(0);
697
- }, ...(ngDevMode ? [{ debugName: "lines" }] : /* istanbul ignore next */ []));
698
- /** Serialized formula string */
699
- formulaString = computed(() => serializeTokens(this.tokens()), ...(ngDevMode ? [{ debugName: "formulaString" }] : /* istanbul ignore next */ []));
700
- constructor() {
701
- // Initialize from input
702
- effect(() => {
703
- const initial = this.initialTokens();
704
- if (initial.length > 0) {
705
- this.tokens.set(initial);
706
- }
707
- });
708
- }
709
- // ============ CONTROL VALUE ACCESSOR ============
710
- writeValue(value) {
711
- if (value === null || value === undefined) {
712
- this.tokens.set([]);
713
- return;
714
- }
715
- // Value should be tokens array
716
- if (Array.isArray(value)) {
717
- this.tokens.set(value);
718
- }
719
- }
720
- registerOnChange(fn) {
721
- this.onChange = fn;
722
- }
723
- registerOnTouched(fn) {
724
- this.onTouched = fn;
725
- }
726
- // ============ PUBLIC API ============
727
- /**
728
- * Add a block from toolbar (converts SmartBlock to tokens)
729
- */
730
- addBlock(block) {
731
- if (this.disabled())
732
- return;
733
- const newTokens = this.smartBlockToTokens(block);
734
- this.tokens.update((tokens) => [...tokens, ...cloneTokens(newTokens)]);
735
- this.emit();
736
- }
737
- /**
738
- * Add tokens directly
739
- */
740
- addTokens(newTokens) {
741
- if (this.disabled())
742
- return;
743
- this.tokens.update((tokens) => [...tokens, ...cloneTokens(newTokens)]);
744
- this.emit();
745
- }
746
- /**
747
- * Clear all tokens
748
- */
749
- clear() {
750
- if (this.disabled())
751
- return;
752
- this.tokens.set([]);
753
- this.emit();
754
- }
755
- /**
756
- * Get current formula string
757
- */
758
- serialize() {
759
- return this.formulaString();
760
- }
761
- /**
762
- * Get current tokens
763
- */
764
- getTokens() {
765
- return this.tokens();
766
- }
767
- // ============ FOCUS HANDLERS ============
768
- handleFocus() {
769
- this.isFocused.set(true);
770
- this.onFocus.emit();
771
- }
772
- handleBlur() {
773
- this.isFocused.set(false);
774
- this.onTouched();
775
- this.onBlur.emit();
776
- }
777
- // ============ DRAG HANDLERS ============
778
- /**
779
- * Handle drag start - determine what tokens to drag
780
- */
781
- onDragStart(event, token, index) {
782
- if (this.disabled())
783
- return;
784
- this.isDragging.set(true);
785
- if (token.dragBehavior === 'function' && token.functionId) {
786
- // Drag entire function (all tokens from fn-open to fn-close)
787
- const range = findFunctionRange(this.tokens(), token.functionId);
788
- if (range) {
789
- this.draggedRange = range;
790
- }
791
- else {
792
- // Fallback to single token if range not found
793
- this.draggedRange = [index, index];
794
- }
795
- }
796
- else {
797
- // Drag single token
798
- this.draggedRange = [index, index];
799
- }
800
- }
801
- /**
802
- * Handle drop - reorder tokens in the formula
803
- */
804
- onDrop(event) {
805
- if (this.disabled())
806
- return;
807
- this.isDragging.set(false);
808
- const { previousIndex, currentIndex } = event;
809
- // No movement
810
- if (previousIndex === currentIndex) {
811
- this.resetDragState();
812
- return;
813
- }
814
- // No drag data (shouldn't happen but be safe)
815
- if (!this.draggedRange) {
816
- this.resetDragState();
817
- return;
818
- }
819
- const [start, end] = this.draggedRange;
820
- const count = end - start + 1;
821
- const isSingleToken = start === end;
822
- // Block dropping inside own range (only for multi-token drag)
823
- if (!isSingleToken && currentIndex > start && currentIndex <= end) {
824
- this.resetDragState();
825
- return;
826
- }
827
- const tokens = [...this.tokens()];
828
- if (isSingleToken) {
829
- // Simple single-token move using CDK utility
830
- moveItemInArray(tokens, previousIndex, currentIndex);
831
- }
832
- else {
833
- // Multi-token move (function with all content)
834
- // 1. Extract the tokens we're moving
835
- const moving = tokens.splice(start, count);
836
- // 2. Calculate insert position
837
- let insertAt;
838
- if (currentIndex <= start) {
839
- // Moving left/backward - insert at drop position
840
- insertAt = currentIndex;
841
- }
842
- else {
843
- // Moving right/forward
844
- // After removal, adjust for removed count and insert AFTER drop target
845
- insertAt = currentIndex - count + 1;
846
- }
847
- // 3. Clamp and insert
848
- insertAt = Math.max(0, Math.min(insertAt, tokens.length));
849
- tokens.splice(insertAt, 0, ...moving);
850
- }
851
- // Update state with recalculated depths
852
- this.tokens.set(recalculateDepths(tokens));
853
- this.resetDragState();
854
- this.emit();
855
- }
856
- /**
857
- * Reset drag state
858
- */
859
- resetDragState() {
860
- this.draggedRange = null;
861
- }
862
- /**
863
- * Handle drag end
864
- * NOTE: CDK fires cdkDragEnded BEFORE cdkDropListDropped
865
- * So we don't reset draggedRange here - onDrop handles it
866
- */
867
- onDragEnd() {
868
- this.isDragging.set(false);
869
- }
870
- // ============ DELETE ============
871
- /**
872
- * Remove a token or function
873
- */
874
- removeToken(token, index) {
875
- if (this.disabled())
876
- return;
877
- if (token.dragBehavior === 'function' && token.functionId) {
878
- // Remove entire function
879
- const range = findFunctionRange(this.tokens(), token.functionId);
880
- if (range) {
881
- this.tokens.update((tokens) => {
882
- const newTokens = [...tokens];
883
- newTokens.splice(range[0], range[1] - range[0] + 1);
884
- return recalculateDepths(newTokens);
885
- });
886
- }
887
- }
888
- else {
889
- // Remove single token
890
- this.tokens.update((tokens) => tokens.filter((_, i) => i !== index));
891
- }
892
- this.emit();
893
- }
894
- // ============ HOVER EFFECTS ============
895
- onTokenHover(token) {
896
- if (token.functionId && token.dragBehavior === 'function') {
897
- this.hoveredFunctionId.set(token.functionId);
898
- }
899
- }
900
- onTokenLeave() {
901
- this.hoveredFunctionId.set(null);
902
- }
903
- /**
904
- * Check if token should be highlighted
905
- * Only structural tokens (fn-open, fn-close, fn-separator) get highlighted
906
- * Content tokens (property, operator, literal) inside function are NOT highlighted
907
- */
908
- isHighlighted(token) {
909
- const hoveredId = this.hoveredFunctionId();
910
- if (!hoveredId)
911
- return false;
912
- // Only highlight structural tokens of the function, not content inside
913
- const isStructural = token.type === 'fn-open' ||
914
- token.type === 'fn-close' ||
915
- token.type === 'fn-separator';
916
- return isStructural && token.functionId === hoveredId;
917
- }
918
- // ============ STYLING ============
919
- /** Base token classes */
920
- baseTokenClasses = 'inline-flex items-center px-2 py-1 rounded text-sm font-medium cursor-grab select-none whitespace-nowrap active:cursor-grabbing';
921
- /**
922
- * Get Tailwind classes for a token
923
- */
924
- getTokenClasses(token) {
925
- const base = this.baseTokenClasses;
926
- // Type-based styling using Tailwind
927
- switch (token.type) {
928
- case 'fn-open':
929
- // Function opening: "IF(" - rounded left only
930
- return `${base} bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 font-semibold hover:bg-slate-300 dark:hover:bg-slate-600 rounded-r-none pr-0.5`;
931
- case 'fn-close':
932
- // Function closing: ")" - rounded right only
933
- return `${base} bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 font-semibold hover:bg-slate-300 dark:hover:bg-slate-600 rounded-l-none pl-0.5`;
934
- case 'fn-separator':
935
- // Function separator: ","
936
- return `${base} bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 font-semibold hover:bg-slate-300 dark:hover:bg-slate-600 rounded-sm px-1`;
937
- case 'property':
938
- // Property tokens - amber colors
939
- return `${base} bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 font-semibold hover:bg-amber-200 dark:hover:bg-amber-900/50`;
940
- case 'operator':
941
- // Operator tokens - sky colors
942
- return `${base} bg-sky-100 dark:bg-sky-900/30 text-sky-700 dark:text-sky-300 font-bold hover:bg-sky-200 dark:hover:bg-sky-900/50 px-2`;
943
- case 'literal':
944
- // Literal tokens - emerald colors
945
- return `${base} bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-200 dark:hover:bg-emerald-900/50`;
946
- case 'text':
947
- return `${base} bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700`;
948
- default:
949
- return base;
950
- }
951
- }
952
- // ============ CONVERSION ============
953
- /**
954
- * Convert SmartBlock to FormulaTokens
955
- */
956
- smartBlockToTokens(block) {
957
- switch (block.type) {
958
- case 'function':
959
- return tokenizeFormulaTemplate(block.insertText || block.signature || `${block.functionName}()`);
960
- case 'property':
961
- return [
962
- createPropertyToken(block.propertyKey || block.value, block.propertyType, 0, undefined, undefined, block.display),
963
- ];
964
- case 'operator':
965
- return [createOperatorToken(block.operatorSymbol || block.value)];
966
- case 'literal':
967
- return [createLiteralToken(block.literalValue ?? block.value)];
968
- default:
969
- return [createLiteralToken(block.value)];
970
- }
971
- }
972
- // ============ EMIT ============
973
- emit() {
974
- const formula = this.formulaString();
975
- const tokens = this.tokens();
976
- this.tokensChange.emit(tokens);
977
- this.formulaChange.emit(formula);
978
- this.onChange(tokens);
979
- }
980
- // ============ CDK HELPERS ============
981
- /**
982
- * Track function for ngFor
983
- */
984
- trackByToken(_index, token) {
985
- return token.id;
986
- }
987
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaEditor, deps: [], target: i0.ɵɵFactoryTarget.Component });
988
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: FormulaEditor, isStandalone: true, selector: "mt-formula-editor", inputs: { placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, initialTokens: { classPropertyName: "initialTokens", publicName: "initialTokens", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, borderless: { classPropertyName: "borderless", publicName: "borderless", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { formulaChange: "formulaChange", tokensChange: "tokensChange", onBlur: "onBlur", onFocus: "onFocus" }, providers: [
989
- {
990
- provide: NG_VALUE_ACCESSOR,
991
- useExisting: forwardRef(() => FormulaEditor),
992
- multi: true,
993
- },
994
- ], ngImport: i0, template: "<div\r\n [class]=\"containerClasses()\"\r\n [class.opacity-60]=\"disabled()\"\r\n [class.pointer-events-none]=\"disabled()\"\r\n (focus)=\"handleFocus()\"\r\n (blur)=\"handleBlur()\"\r\n tabindex=\"0\"\r\n>\r\n <!-- Line Numbers -->\r\n <div [class]=\"lineNumberClasses()\">\r\n @for (line of lines(); track $index) {\r\n <div class=\"text-surface-400 dark:text-surface-500 text-sm leading-6\">\r\n {{ $index + 1 }}\r\n </div>\r\n }\r\n </div>\r\n\r\n <!-- Editor Content - Single Drop Zone -->\r\n <div\r\n class=\"flex-1 p-2 flex flex-wrap gap-0.5 items-start content-start min-h-14 cursor-text\"\r\n cdkDropList\r\n cdkDropListOrientation=\"mixed\"\r\n [cdkDropListData]=\"tokens()\"\r\n [cdkDropListDisabled]=\"disabled()\"\r\n (cdkDropListDropped)=\"onDrop($event)\"\r\n >\r\n @if (tokens().length === 0) {\r\n <div class=\"text-surface-400 dark:text-surface-500 text-sm italic\">\r\n {{ placeholder() }}\r\n </div>\r\n } @else {\r\n @for (token of tokens(); track token.id; let i = $index) {\r\n <div\r\n class=\"relative inline-flex items-center group\"\r\n cdkDrag\r\n [cdkDragData]=\"token\"\r\n [cdkDragDisabled]=\"disabled()\"\r\n (cdkDragStarted)=\"onDragStart($event, token, i)\"\r\n (cdkDragEnded)=\"onDragEnd()\"\r\n >\r\n <!-- Drag Placeholder (thin cursor line) -->\r\n <div\r\n *cdkDragPlaceholder\r\n class=\"w-2 min-w-2 h-5 bg-primary rounded-sm opacity-80\"\r\n ></div>\r\n\r\n <!-- Token -->\r\n <span\r\n [class]=\"getTokenClasses(token)\"\r\n [class.border-b-2]=\"!isDragging() && isHighlighted(token)\"\r\n [class.border-primary]=\"!isDragging() && isHighlighted(token)\"\r\n (mouseenter)=\"onTokenHover(token)\"\r\n (mouseleave)=\"onTokenLeave()\"\r\n >\r\n {{ token.display ?? token.value }}\r\n </span>\r\n\r\n <!-- Delete Button (shows on hover, hidden during drag) -->\r\n @if (!isDragging() && !disabled()) {\r\n <button\r\n type=\"button\"\r\n class=\"absolute -top-1.5 -right-1.5 w-3.5 h-3.5 flex items-center justify-center bg-red-500 hover:bg-red-600 text-white rounded-full cursor-pointer scale-75 hover:scale-100 opacity-0 group-hover:opacity-100 pointer-events-none group-hover:pointer-events-auto z-10\"\r\n (click)=\"removeToken(token, i); $event.stopPropagation()\"\r\n [title]=\"\r\n token.dragBehavior === 'function'\r\n ? ('components.formulaEditor.removeFunction' | transloco)\r\n : ('components.formulaEditor.remove' | transloco)\r\n \"\r\n >\r\n <svg\r\n class=\"h-2.5 w-2.5\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"3\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 18L18 6M6 6l12 12\"\r\n />\r\n </svg>\r\n </button>\r\n }\r\n </div>\r\n }\r\n }\r\n </div>\r\n</div>\r\n", styles: [".cdk-drag-preview{width:20px!important;height:20px!important;min-width:20px!important;min-height:20px!important;max-width:20px!important;max-height:20px!important;border-radius:4px;opacity:.9;overflow:hidden!important;cursor:grabbing}.cdk-drag-animating{transition:none!important}.cdk-drag-dragging{opacity:1}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: DragDropModule }, { kind: "directive", type: i1.CdkDropList, selector: "[cdkDropList], cdk-drop-list", inputs: ["cdkDropListConnectedTo", "cdkDropListData", "cdkDropListOrientation", "id", "cdkDropListLockAxis", "cdkDropListDisabled", "cdkDropListSortingDisabled", "cdkDropListEnterPredicate", "cdkDropListSortPredicate", "cdkDropListAutoScrollDisabled", "cdkDropListAutoScrollStep", "cdkDropListElementContainer", "cdkDropListHasAnchor"], outputs: ["cdkDropListDropped", "cdkDropListEntered", "cdkDropListExited", "cdkDropListSorted"], exportAs: ["cdkDropList"] }, { kind: "directive", type: i1.CdkDrag, selector: "[cdkDrag]", inputs: ["cdkDragData", "cdkDragLockAxis", "cdkDragRootElement", "cdkDragBoundary", "cdkDragStartDelay", "cdkDragFreeDragPosition", "cdkDragDisabled", "cdkDragConstrainPosition", "cdkDragPreviewClass", "cdkDragPreviewContainer", "cdkDragScale"], outputs: ["cdkDragStarted", "cdkDragReleased", "cdkDragEnded", "cdkDragEntered", "cdkDragExited", "cdkDragDropped", "cdkDragMoved"], exportAs: ["cdkDrag"] }, { kind: "directive", type: i1.CdkDragPlaceholder, selector: "ng-template[cdkDragPlaceholder]", inputs: ["data"] }, { kind: "ngmodule", type: FormsModule }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }] });
995
- }
996
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaEditor, decorators: [{
997
- type: Component,
998
- args: [{ selector: 'mt-formula-editor', standalone: true, imports: [CommonModule, DragDropModule, FormsModule, TranslocoPipe], providers: [
999
- {
1000
- provide: NG_VALUE_ACCESSOR,
1001
- useExisting: forwardRef(() => FormulaEditor),
1002
- multi: true,
1003
- },
1004
- ], template: "<div\r\n [class]=\"containerClasses()\"\r\n [class.opacity-60]=\"disabled()\"\r\n [class.pointer-events-none]=\"disabled()\"\r\n (focus)=\"handleFocus()\"\r\n (blur)=\"handleBlur()\"\r\n tabindex=\"0\"\r\n>\r\n <!-- Line Numbers -->\r\n <div [class]=\"lineNumberClasses()\">\r\n @for (line of lines(); track $index) {\r\n <div class=\"text-surface-400 dark:text-surface-500 text-sm leading-6\">\r\n {{ $index + 1 }}\r\n </div>\r\n }\r\n </div>\r\n\r\n <!-- Editor Content - Single Drop Zone -->\r\n <div\r\n class=\"flex-1 p-2 flex flex-wrap gap-0.5 items-start content-start min-h-14 cursor-text\"\r\n cdkDropList\r\n cdkDropListOrientation=\"mixed\"\r\n [cdkDropListData]=\"tokens()\"\r\n [cdkDropListDisabled]=\"disabled()\"\r\n (cdkDropListDropped)=\"onDrop($event)\"\r\n >\r\n @if (tokens().length === 0) {\r\n <div class=\"text-surface-400 dark:text-surface-500 text-sm italic\">\r\n {{ placeholder() }}\r\n </div>\r\n } @else {\r\n @for (token of tokens(); track token.id; let i = $index) {\r\n <div\r\n class=\"relative inline-flex items-center group\"\r\n cdkDrag\r\n [cdkDragData]=\"token\"\r\n [cdkDragDisabled]=\"disabled()\"\r\n (cdkDragStarted)=\"onDragStart($event, token, i)\"\r\n (cdkDragEnded)=\"onDragEnd()\"\r\n >\r\n <!-- Drag Placeholder (thin cursor line) -->\r\n <div\r\n *cdkDragPlaceholder\r\n class=\"w-2 min-w-2 h-5 bg-primary rounded-sm opacity-80\"\r\n ></div>\r\n\r\n <!-- Token -->\r\n <span\r\n [class]=\"getTokenClasses(token)\"\r\n [class.border-b-2]=\"!isDragging() && isHighlighted(token)\"\r\n [class.border-primary]=\"!isDragging() && isHighlighted(token)\"\r\n (mouseenter)=\"onTokenHover(token)\"\r\n (mouseleave)=\"onTokenLeave()\"\r\n >\r\n {{ token.display ?? token.value }}\r\n </span>\r\n\r\n <!-- Delete Button (shows on hover, hidden during drag) -->\r\n @if (!isDragging() && !disabled()) {\r\n <button\r\n type=\"button\"\r\n class=\"absolute -top-1.5 -right-1.5 w-3.5 h-3.5 flex items-center justify-center bg-red-500 hover:bg-red-600 text-white rounded-full cursor-pointer scale-75 hover:scale-100 opacity-0 group-hover:opacity-100 pointer-events-none group-hover:pointer-events-auto z-10\"\r\n (click)=\"removeToken(token, i); $event.stopPropagation()\"\r\n [title]=\"\r\n token.dragBehavior === 'function'\r\n ? ('components.formulaEditor.removeFunction' | transloco)\r\n : ('components.formulaEditor.remove' | transloco)\r\n \"\r\n >\r\n <svg\r\n class=\"h-2.5 w-2.5\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"3\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 18L18 6M6 6l12 12\"\r\n />\r\n </svg>\r\n </button>\r\n }\r\n </div>\r\n }\r\n }\r\n </div>\r\n</div>\r\n", styles: [".cdk-drag-preview{width:20px!important;height:20px!important;min-width:20px!important;min-height:20px!important;max-width:20px!important;max-height:20px!important;border-radius:4px;opacity:.9;overflow:hidden!important;cursor:grabbing}.cdk-drag-animating{transition:none!important}.cdk-drag-dragging{opacity:1}\n"] }]
1005
- }], ctorParameters: () => [], propDecorators: { placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], initialTokens: [{ type: i0.Input, args: [{ isSignal: true, alias: "initialTokens", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], borderless: [{ type: i0.Input, args: [{ isSignal: true, alias: "borderless", required: false }] }], formulaChange: [{ type: i0.Output, args: ["formulaChange"] }], tokensChange: [{ type: i0.Output, args: ["tokensChange"] }], onBlur: [{ type: i0.Output, args: ["onBlur"] }], onFocus: [{ type: i0.Output, args: ["onFocus"] }] } });
1006
-
1007
- function buildCompletionFilterText(suggestion) {
1008
- const candidates = [
1009
- suggestion.displayText,
1010
- suggestion.insertText,
1011
- suggestion.text,
1012
- ]
1013
- .map((value) => value?.trim() ?? '')
1014
- .filter((value) => value.length > 0);
1015
- return Array.from(new Set(candidates)).join(' ');
1016
- }
1017
-
1018
- function normalizeAutocompleteSuggestion(suggestion, context) {
1019
- const insertText = resolveScopedInsertText(suggestion, context);
1020
- if (insertText === (suggestion.insertText ?? suggestion.text)) {
1021
- return suggestion;
1022
- }
1023
- return {
1024
- ...suggestion,
1025
- insertText,
1026
- };
1027
- }
1028
- function resolveScopedInsertText(suggestion, context) {
1029
- const insertText = suggestion.insertText ?? suggestion.text;
1030
- if (suggestion.type !== 'Property' ||
1031
- !insertText ||
1032
- insertText.startsWith('@')) {
1033
- return insertText;
1034
- }
1035
- const tablePath = resolveTablePath(context);
1036
- if (!tablePath) {
1037
- return insertText;
1038
- }
1039
- return `@${tablePath}::${insertText}`;
1040
- }
1041
- function resolveTablePath(context) {
1042
- const tablePath = context?.tablePath?.trim();
1043
- if (tablePath) {
1044
- return tablePath;
1045
- }
1046
- const scopeToken = context?.scopeToken?.trim();
1047
- if (scopeToken) {
1048
- const scopeParameter = context?.scopeParameter?.trim();
1049
- return scopeParameter ? `${scopeToken}.${scopeParameter}` : scopeToken;
1050
- }
1051
- const scope = context?.scope?.trim();
1052
- if (!scope) {
1053
- return '';
1054
- }
1055
- return scope.replace(/^@/, '').replace(/::$/, '');
1056
- }
1057
-
1058
- const FORMULA_REFERENCE_CHARACTER = /[@\w.:]/;
1059
- function resolveCompletionRangeBounds(lineContent, column, wordStartColumn, wordEndColumn, suggestion) {
1060
- const referenceBounds = getReferenceCompletionBounds(lineContent, column, suggestion);
1061
- return (referenceBounds ?? {
1062
- startColumn: wordStartColumn,
1063
- endColumn: wordEndColumn,
1064
- });
1065
- }
1066
- function getReferenceCompletionBounds(lineContent, column, suggestion) {
1067
- const insertText = suggestion.insertText ?? suggestion.text;
1068
- if (suggestion.type !== 'Property' &&
1069
- suggestion.type !== 'Context' &&
1070
- !insertText.startsWith('@')) {
1071
- return null;
1072
- }
1073
- const cursorIndex = Math.max(0, Math.min(column - 1, lineContent.length));
1074
- let startIndex = cursorIndex;
1075
- while (startIndex > 0 &&
1076
- FORMULA_REFERENCE_CHARACTER.test(lineContent[startIndex - 1] ?? '')) {
1077
- startIndex--;
1078
- }
1079
- let endIndex = cursorIndex;
1080
- while (endIndex < lineContent.length &&
1081
- FORMULA_REFERENCE_CHARACTER.test(lineContent[endIndex] ?? '')) {
1082
- endIndex++;
1083
- }
1084
- return {
1085
- startColumn: startIndex + 1,
1086
- endColumn: endIndex + 1,
1087
- };
1088
- }
1089
-
1090
- class FormulaEditorCode {
1091
- placeholder = input('Enter formula...', ...(ngDevMode ? [{ debugName: "placeholder" }] : /* istanbul ignore next */ []));
1092
- initialFormula = input('', ...(ngDevMode ? [{ debugName: "initialFormula" }] : /* istanbul ignore next */ []));
1093
- disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
1094
- language = input('formula', ...(ngDevMode ? [{ debugName: "language" }] : /* istanbul ignore next */ []));
1095
- theme = input('formula-light', ...(ngDevMode ? [{ debugName: "theme" }] : /* istanbul ignore next */ []));
1096
- borderless = input(false, ...(ngDevMode ? [{ debugName: "borderless" }] : /* istanbul ignore next */ []));
1097
- autocompleteProvider = input(null, ...(ngDevMode ? [{ debugName: "autocompleteProvider" }] : /* istanbul ignore next */ []));
1098
- autocompleteDebounceMs = input(150, ...(ngDevMode ? [{ debugName: "autocompleteDebounceMs" }] : /* istanbul ignore next */ []));
1099
- formulaChange = output();
1100
- onBlur = output();
1101
- onFocus = output();
1102
- editorHost = viewChild('editorHost', ...(ngDevMode ? [{ debugName: "editorHost" }] : /* istanbul ignore next */ []));
1103
- zone = inject(NgZone);
1104
- document = inject(DOCUMENT);
1105
- monaco = null;
1106
- editor = null;
1107
- model = null;
1108
- disposables = [];
1109
- resizeObserver = null;
1110
- completionProvider = null;
1111
- // Autocomplete state - using RxJS for proper debounce and cancellation
1112
- autocompleteSubject = new Subject();
1113
- autocompleteSubscription = null;
1114
- cancelAutocomplete$ = new Subject();
1115
- currentAutocompleteRequestId = 0;
1116
- static formulaAssetsReady = false;
1117
- static monacoStylesReady = false;
1118
- value = signal('', ...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
1119
- isFocused = signal(false, ...(ngDevMode ? [{ debugName: "isFocused" }] : /* istanbul ignore next */ []));
1120
- showPlaceholder = computed(() => this.value().length === 0 && !this.isFocused(), ...(ngDevMode ? [{ debugName: "showPlaceholder" }] : /* istanbul ignore next */ []));
1121
- containerClasses = computed(() => {
1122
- const base = 'relative flex min-h-20 flex-col bg-white dark:bg-surface-800 font-mono text-sm';
1123
- if (this.borderless()) {
1124
- return base;
1125
- }
1126
- return `${base} rounded-md border border-surface-200 dark:border-surface-700 focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/10`;
1127
- }, ...(ngDevMode ? [{ debugName: "containerClasses" }] : /* istanbul ignore next */ []));
1128
- hasWrittenValue = false;
1129
- isApplyingExternalValue = false;
1130
- onChange = () => { };
1131
- onTouched = () => { };
1132
- constructor() {
1133
- effect(() => {
1134
- const initial = this.initialFormula();
1135
- if (!this.hasWrittenValue && this.value().length === 0 && initial) {
1136
- this.value.set(initial);
1137
- }
1138
- });
1139
- effect(() => {
1140
- const readOnly = this.disabled();
1141
- if (this.editor) {
1142
- this.editor.updateOptions({ readOnly });
1143
- }
1144
- });
1145
- effect(() => {
1146
- const theme = this.theme();
1147
- if (this.monaco) {
1148
- this.monaco.editor.setTheme(theme);
1149
- }
1150
- });
1151
- effect(() => {
1152
- const language = this.language();
1153
- if (this.monaco && this.model) {
1154
- this.ensureFormulaAssets(this.monaco);
1155
- this.monaco.editor.setModelLanguage(this.model, language);
1156
- // Completion provider is registered in the autocompleteProvider effect
1157
- }
1158
- });
1159
- effect(() => {
1160
- // Track both language and provider changes - reading signals to subscribe
1161
- const _provider = this.autocompleteProvider();
1162
- const language = this.language();
1163
- if (this.monaco && language) {
1164
- this.registerCompletionProvider();
1165
- }
1166
- });
1167
- }
1168
- ngAfterViewInit() {
1169
- this.zone.runOutsideAngular(() => {
1170
- void this.initEditor();
1171
- });
1172
- }
1173
- ngOnDestroy() {
1174
- this.resizeObserver?.disconnect();
1175
- // Cancel any pending autocomplete
1176
- this.cancelAutocomplete$.next();
1177
- this.cancelAutocomplete$.complete();
1178
- this.autocompleteSubject.complete();
1179
- this.autocompleteSubscription?.unsubscribe();
1180
- if (this.completionProvider) {
1181
- this.completionProvider.dispose();
1182
- this.completionProvider = null;
1183
- }
1184
- this.disposables.forEach((disposable) => disposable.dispose());
1185
- this.editor?.dispose();
1186
- this.model?.dispose();
1187
- }
1188
- writeValue(value) {
1189
- this.hasWrittenValue = true;
1190
- const next = value ?? '';
1191
- this.value.set(next);
1192
- this.syncEditorValue(next);
1193
- }
1194
- registerOnChange(fn) {
1195
- this.onChange = fn;
1196
- }
1197
- registerOnTouched(fn) {
1198
- this.onTouched = fn;
1199
- }
1200
- addBlock(block) {
1201
- if (this.disabled())
1202
- return;
1203
- const { text, cursorOffset } = this.smartBlockToText(block);
1204
- this.insertText(text, cursorOffset);
1205
- }
1206
- insertText(text, cursorOffset = 0) {
1207
- if (this.disabled())
1208
- return;
1209
- if (!this.editor || !this.model || !this.monaco) {
1210
- const next = `${this.value()}${text}`;
1211
- this.emitValue(next);
1212
- return;
1213
- }
1214
- const selection = this.editor.getSelection() ?? new this.monaco.Selection(1, 1, 1, 1);
1215
- this.editor.executeEdits('formula-editor-code', [
1216
- { range: selection, text, forceMoveMarkers: true },
1217
- ]);
1218
- const startOffset = this.model.getOffsetAt(selection.getStartPosition());
1219
- const nextOffset = Math.max(0, Math.min(startOffset + text.length + cursorOffset, this.model.getValueLength()));
1220
- const nextPos = this.model.getPositionAt(nextOffset);
1221
- this.editor.setSelection(new this.monaco.Selection(nextPos.lineNumber, nextPos.column, nextPos.lineNumber, nextPos.column));
1222
- this.editor.focus();
1223
- }
1224
- clear() {
1225
- if (this.disabled())
1226
- return;
1227
- if (this.model) {
1228
- this.isApplyingExternalValue = true;
1229
- this.model.setValue('');
1230
- this.isApplyingExternalValue = false;
1231
- }
1232
- this.emitValue('');
1233
- }
1234
- getValue() {
1235
- return this.value();
1236
- }
1237
- async initEditor() {
1238
- const host = this.editorHost()?.nativeElement;
1239
- if (!host)
1240
- return;
1241
- this.ensureMonacoStylesLoaded();
1242
- let monaco;
1243
- try {
1244
- monaco = await import('monaco-editor');
1245
- }
1246
- catch (error) {
1247
- console.warn('Failed to load Monaco editor:', error);
1248
- return;
1249
- }
1250
- this.monaco = monaco;
1251
- this.ensureFormulaAssets(monaco);
1252
- const model = monaco.editor.createModel(this.value(), this.language());
1253
- this.model = model;
1254
- const editor = monaco.editor.create(host, {
1255
- model,
1256
- theme: this.theme(),
1257
- readOnly: this.disabled(),
1258
- minimap: { enabled: false },
1259
- scrollBeyondLastLine: false,
1260
- wordWrap: 'on',
1261
- fontSize: 14,
1262
- lineHeight: 21,
1263
- lineNumbers: 'on',
1264
- lineNumbersMinChars: 3,
1265
- lineDecorationsWidth: 10,
1266
- glyphMargin: false,
1267
- automaticLayout: true,
1268
- fixedOverflowWidgets: true,
1269
- suggestOnTriggerCharacters: true,
1270
- quickSuggestions: { other: true, comments: false, strings: true },
1271
- renderLineHighlight: 'line',
1272
- matchBrackets: 'always',
1273
- bracketPairColorization: { enabled: true },
1274
- padding: { top: 4, bottom: 4 },
1275
- fontFamily: "Consolas, 'Courier New', monospace",
1276
- fontLigatures: false,
1277
- cursorBlinking: 'blink',
1278
- cursorStyle: 'line',
1279
- cursorWidth: 2,
1280
- renderWhitespace: 'selection',
1281
- folding: false,
1282
- occurrencesHighlight: 'singleFile',
1283
- selectionHighlight: true,
1284
- roundedSelection: true,
1285
- smoothScrolling: true,
1286
- mouseWheelZoom: false,
1287
- contextmenu: true,
1288
- scrollbar: {
1289
- vertical: 'auto',
1290
- horizontal: 'auto',
1291
- verticalScrollbarSize: 14,
1292
- horizontalScrollbarSize: 10,
1293
- useShadows: false,
1294
- },
1295
- });
1296
- this.editor = editor;
1297
- this.attachEditorListeners(editor, model);
1298
- this.setupResizeObserver(host, editor);
1299
- this.registerCompletionProvider();
1300
- }
1301
- ensureMonacoStylesLoaded() {
1302
- if (FormulaEditorCode.monacoStylesReady) {
1303
- return;
1304
- }
1305
- const doc = this.document;
1306
- if (!doc?.head) {
1307
- return;
1308
- }
1309
- const existing = doc.head.querySelector('link[data-mt-monaco-style="editor-main"]');
1310
- if (existing) {
1311
- FormulaEditorCode.monacoStylesReady = true;
1312
- return;
1313
- }
1314
- // Monaco assets are copied by the app to /assets/monaco/vs/.
1315
- const stylesheetHref = new URL('assets/monaco/vs/editor/editor.main.css', doc.baseURI).toString();
1316
- const link = doc.createElement('link');
1317
- link.rel = 'stylesheet';
1318
- link.href = stylesheetHref;
1319
- link.dataset['mtMonacoStyle'] = 'editor-main';
1320
- link.onerror = () => {
1321
- console.warn(`[mt-formula-editor-code] Failed to load Monaco stylesheet at ${stylesheetHref}. ` +
1322
- `The editor will render without styles. Ensure the host app installs "monaco-editor" ` +
1323
- `and copies "node_modules/monaco-editor/min/vs/" to "/assets/monaco/vs/" in angular.json.`);
1324
- };
1325
- doc.head.appendChild(link);
1326
- FormulaEditorCode.monacoStylesReady = true;
1327
- }
1328
- ensureFormulaAssets(monaco) {
1329
- if (FormulaEditorCode.formulaAssetsReady)
1330
- return;
1331
- monaco.languages.register({ id: 'formula' });
1332
- monaco.languages.setMonarchTokensProvider('formula', {
1333
- keywords: ['true', 'false', 'null'],
1334
- operators: [
1335
- '==',
1336
- '!=',
1337
- '>=',
1338
- '<=',
1339
- '>',
1340
- '<',
1341
- '+',
1342
- '-',
1343
- '*',
1344
- '/',
1345
- '%',
1346
- '^',
1347
- '&&',
1348
- '||',
1349
- '!',
1350
- ],
1351
- symbols: /[=><!~?:&|+\-*/^%]+/,
1352
- tokenizer: {
1353
- root: [
1354
- [/@[a-zA-Z_][\w.]*::[\w_]+/, 'type.identifier'],
1355
- [/@[a-zA-Z_][\w.]*/, 'type.identifier'],
1356
- [/\b[A-Z_][A-Z0-9_]*\b/, 'function'],
1357
- [
1358
- /[a-zA-Z_][\w_]*/,
1359
- {
1360
- cases: {
1361
- '@keywords': 'keyword',
1362
- '@default': 'identifier',
1363
- },
1364
- },
1365
- ],
1366
- [/[0-9]+(\.[0-9]+)?/, 'number'],
1367
- [/"/, { token: 'string.quote', bracket: '@open', next: '@string' }],
1368
- [/'[^'\\]*(?:\\.[^'\\]*)*'/, 'string'],
1369
- [/@symbols/, { cases: { '@operators': 'operator', '@default': '' } }],
1370
- [/[()[\]{}]/, '@brackets'],
1371
- [/[;,.]/, 'delimiter'],
1372
- { include: '@whitespace' },
1373
- ],
1374
- whitespace: [
1375
- [/\s+/, 'white'],
1376
- [/\/\/.*$/, 'comment'],
1377
- [/\/\*/, 'comment', '@comment'],
1378
- ],
1379
- comment: [
1380
- [/[^/*]+/, 'comment'],
1381
- [/\*\//, 'comment', '@pop'],
1382
- [/[/*]/, 'comment'],
1383
- ],
1384
- string: [
1385
- [/[^\\"]+/, 'string'],
1386
- [/\\./, 'string.escape'],
1387
- [/"/, { token: 'string.quote', bracket: '@close', next: '@pop' }],
1388
- ],
1389
- },
1390
- });
1391
- monaco.languages.setLanguageConfiguration('formula', {
1392
- brackets: [
1393
- ['{', '}'],
1394
- ['[', ']'],
1395
- ['(', ')'],
1396
- ],
1397
- autoClosingPairs: [
1398
- { open: '{', close: '}' },
1399
- { open: '[', close: ']' },
1400
- { open: '(', close: ')' },
1401
- { open: '"', close: '"' },
1402
- { open: "'", close: "'" },
1403
- ],
1404
- surroundingPairs: [
1405
- { open: '{', close: '}' },
1406
- { open: '[', close: ']' },
1407
- { open: '(', close: ')' },
1408
- { open: '"', close: '"' },
1409
- { open: "'", close: "'" },
1410
- ],
1411
- });
1412
- monaco.editor.defineTheme('formula-light', {
1413
- base: 'vs',
1414
- inherit: true,
1415
- rules: [
1416
- // VS Code Light+ token colors
1417
- { token: 'function', foreground: '795E26', fontStyle: 'bold' },
1418
- { token: 'type.identifier', foreground: '267F99' },
1419
- { token: 'keyword', foreground: '0000FF', fontStyle: 'bold' },
1420
- { token: 'number', foreground: '098658' },
1421
- { token: 'string', foreground: 'A31515' },
1422
- { token: 'string.escape', foreground: 'EE0000' },
1423
- { token: 'operator', foreground: '000000' },
1424
- { token: 'delimiter', foreground: '000000' },
1425
- { token: 'comment', foreground: '008000', fontStyle: 'italic' },
1426
- { token: 'identifier', foreground: '001080' },
1427
- { token: 'variable', foreground: '001080' },
1428
- ],
1429
- colors: {
1430
- // Editor core
1431
- 'editor.background': '#FFFFFF',
1432
- 'editor.foreground': '#000000',
1433
- 'editorCursor.foreground': '#000000',
1434
- // Line numbers
1435
- 'editorLineNumber.foreground': '#237893',
1436
- 'editorLineNumber.activeForeground': '#0B216F',
1437
- // Line highlight
1438
- 'editorLineHighlight.background': '#00000000',
1439
- 'editorLineHighlight.border': '#EEF0F1',
1440
- // Selection
1441
- 'editor.selectionBackground': '#ADD6FF',
1442
- 'editor.inactiveSelectionBackground': '#E5EBF1',
1443
- 'editor.selectionHighlightBackground': '#ADD6FF80',
1444
- // Word highlight (when cursor is on a word/function)
1445
- 'editor.wordHighlightBackground': '#57575740',
1446
- 'editor.wordHighlightStrongBackground': '#0E639C40',
1447
- 'editor.wordHighlightBorder': '#595959',
1448
- 'editor.wordHighlightStrongBorder': '#0E639C',
1449
- // Find match
1450
- 'editor.findMatchBackground': '#A8AC94',
1451
- 'editor.findMatchHighlightBackground': '#EA5C0055',
1452
- // Bracket matching
1453
- 'editorBracketMatch.background': '#0064001A',
1454
- 'editorBracketMatch.border': '#B9B9B9',
1455
- // Indent guides
1456
- 'editorIndentGuide.background': '#D3D3D3',
1457
- 'editorIndentGuide.activeBackground': '#939393',
1458
- // Gutter
1459
- 'editorGutter.background': '#FFFFFF',
1460
- // Suggest widget
1461
- 'editorSuggestWidget.background': '#F3F3F3',
1462
- 'editorSuggestWidget.border': '#C8C8C8',
1463
- 'editorSuggestWidget.foreground': '#000000',
1464
- 'editorSuggestWidget.selectedBackground': '#0060C0',
1465
- 'editorSuggestWidget.selectedForeground': '#FFFFFF',
1466
- 'editorSuggestWidget.highlightForeground': '#0066BF',
1467
- 'editorSuggestWidget.focusHighlightForeground': '#FFFFFF',
1468
- // Hover widget
1469
- 'editorHoverWidget.background': '#F3F3F3',
1470
- 'editorHoverWidget.border': '#C8C8C8',
1471
- 'editorHoverWidget.foreground': '#000000',
1472
- // Generic widget
1473
- 'editorWidget.background': '#F3F3F3',
1474
- 'editorWidget.border': '#C8C8C8',
1475
- // Scrollbar
1476
- 'scrollbarSlider.background': '#64646433',
1477
- 'scrollbarSlider.hoverBackground': '#646464B3',
1478
- 'scrollbarSlider.activeBackground': '#646464B3',
1479
- },
1480
- });
1481
- monaco.editor.defineTheme('formula-dark', {
1482
- base: 'vs-dark',
1483
- inherit: true,
1484
- rules: [
1485
- // VS Code Dark+ token colors
1486
- { token: 'function', foreground: 'DCDCAA', fontStyle: 'bold' },
1487
- { token: 'type.identifier', foreground: '4EC9B0' },
1488
- { token: 'keyword', foreground: '569CD6', fontStyle: 'bold' },
1489
- { token: 'number', foreground: 'B5CEA8' },
1490
- { token: 'string', foreground: 'CE9178' },
1491
- { token: 'string.escape', foreground: 'D7BA7D' },
1492
- { token: 'operator', foreground: 'D4D4D4' },
1493
- { token: 'delimiter', foreground: 'D4D4D4' },
1494
- { token: 'comment', foreground: '6A9955', fontStyle: 'italic' },
1495
- { token: 'identifier', foreground: '9CDCFE' },
1496
- { token: 'variable', foreground: '9CDCFE' },
1497
- ],
1498
- colors: {
1499
- // Editor core
1500
- 'editor.background': '#1E1E1E',
1501
- 'editor.foreground': '#D4D4D4',
1502
- 'editorCursor.foreground': '#AEAFAD',
1503
- // Line numbers
1504
- 'editorLineNumber.foreground': '#858585',
1505
- 'editorLineNumber.activeForeground': '#C6C6C6',
1506
- // Line highlight
1507
- 'editorLineHighlight.background': '#2A2D2E',
1508
- 'editorLineHighlight.border': '#282828',
1509
- // Selection
1510
- 'editor.selectionBackground': '#264F78',
1511
- 'editor.inactiveSelectionBackground': '#3A3D41',
1512
- 'editor.selectionHighlightBackground': '#ADD6FF26',
1513
- // Word highlight (when cursor is on a word/function)
1514
- 'editor.wordHighlightBackground': '#575757B3',
1515
- 'editor.wordHighlightStrongBackground': '#004972B3',
1516
- 'editor.wordHighlightBorder': '#858585',
1517
- 'editor.wordHighlightStrongBorder': '#007ACC',
1518
- // Find match
1519
- 'editor.findMatchBackground': '#515C6A',
1520
- 'editor.findMatchHighlightBackground': '#EA5C0055',
1521
- // Bracket matching
1522
- 'editorBracketMatch.background': '#0064001A',
1523
- 'editorBracketMatch.border': '#888888',
1524
- // Indent guides
1525
- 'editorIndentGuide.background': '#404040',
1526
- 'editorIndentGuide.activeBackground': '#707070',
1527
- // Gutter
1528
- 'editorGutter.background': '#1E1E1E',
1529
- // Suggest widget
1530
- 'editorSuggestWidget.background': '#252526',
1531
- 'editorSuggestWidget.border': '#454545',
1532
- 'editorSuggestWidget.foreground': '#D4D4D4',
1533
- 'editorSuggestWidget.selectedBackground': '#04395E',
1534
- 'editorSuggestWidget.selectedForeground': '#FFFFFF',
1535
- 'editorSuggestWidget.highlightForeground': '#18A3FF',
1536
- 'editorSuggestWidget.focusHighlightForeground': '#18A3FF',
1537
- // Hover widget
1538
- 'editorHoverWidget.background': '#252526',
1539
- 'editorHoverWidget.border': '#454545',
1540
- 'editorHoverWidget.foreground': '#D4D4D4',
1541
- // Generic widget
1542
- 'editorWidget.background': '#252526',
1543
- 'editorWidget.border': '#454545',
1544
- // Scrollbar
1545
- 'scrollbarSlider.background': '#79797966',
1546
- 'scrollbarSlider.hoverBackground': '#646464B3',
1547
- 'scrollbarSlider.activeBackground': '#BFBFBF66',
1548
- },
1549
- });
1550
- FormulaEditorCode.formulaAssetsReady = true;
1551
- }
1552
- attachEditorListeners(editor, model) {
1553
- this.disposables.push(model.onDidChangeContent(() => {
1554
- if (this.isApplyingExternalValue)
1555
- return;
1556
- const next = model.getValue();
1557
- this.emitValue(next);
1558
- this.scheduleAutocomplete();
1559
- }), editor.onDidFocusEditorText(() => {
1560
- this.zone.run(() => {
1561
- this.isFocused.set(true);
1562
- this.onFocus.emit();
1563
- });
1564
- }), editor.onDidBlurEditorText(() => {
1565
- this.zone.run(() => {
1566
- this.isFocused.set(false);
1567
- this.onTouched();
1568
- this.onBlur.emit();
1569
- });
1570
- }));
1571
- }
1572
- setupResizeObserver(host, editor) {
1573
- if (typeof ResizeObserver === 'undefined')
1574
- return;
1575
- this.resizeObserver = new ResizeObserver(() => {
1576
- editor.layout();
1577
- });
1578
- this.resizeObserver.observe(host);
1579
- }
1580
- scheduleAutocomplete() {
1581
- if (!this.editor || !this.autocompleteProvider())
1582
- return;
1583
- // Emit to subject - debouncing is handled in setupAutocompleteStream
1584
- this.autocompleteSubject.next();
1585
- }
1586
- setupAutocompleteStream() {
1587
- // Clean up previous subscription
1588
- this.autocompleteSubscription?.unsubscribe();
1589
- const debounceMs = Math.max(0, this.autocompleteDebounceMs());
1590
- this.autocompleteSubscription = this.autocompleteSubject
1591
- .pipe(debounceTime(debounceMs), filter(() => !!this.editor && !!this.autocompleteProvider()))
1592
- .subscribe(() => {
1593
- // Trigger Monaco's suggest widget - this will call provideCompletionItems
1594
- this.editor?.trigger('formula-editor-code', 'editor.action.triggerSuggest', {});
1595
- });
1596
- }
1597
- registerCompletionProvider() {
1598
- if (!this.monaco)
1599
- return;
1600
- // Clean up previous provider
1601
- if (this.completionProvider) {
1602
- this.completionProvider.dispose();
1603
- this.completionProvider = null;
1604
- }
1605
- const provider = this.autocompleteProvider();
1606
- if (!provider)
1607
- return;
1608
- const language = this.language();
1609
- // Setup the autocomplete stream for debouncing
1610
- this.setupAutocompleteStream();
1611
- this.completionProvider =
1612
- this.monaco.languages.registerCompletionItemProvider(language, {
1613
- triggerCharacters: ['@', '.', ':', '(', ',', ' '],
1614
- provideCompletionItems: async (model, position) => {
1615
- // Cancel any previous in-flight request
1616
- this.cancelAutocomplete$.next();
1617
- // Generate unique request ID
1618
- const requestId = ++this.currentAutocompleteRequestId;
1619
- const cursorPosition = model.getOffsetAt(position);
1620
- const formula = model.getValue();
1621
- try {
1622
- const response = await this.resolveAutocompleteResponse(provider, { formula, cursorPosition }, requestId);
1623
- // Check if this request is still the current one
1624
- if (!response || requestId !== this.currentAutocompleteRequestId) {
1625
- return { suggestions: [] };
1626
- }
1627
- return {
1628
- suggestions: (response.suggestions ?? []).map((suggestion, index) => {
1629
- const normalizedSuggestion = normalizeAutocompleteSuggestion(suggestion, response.context);
1630
- const label = normalizedSuggestion.displayText?.trim() ||
1631
- normalizedSuggestion.text;
1632
- const description = normalizedSuggestion.description?.trim() || '';
1633
- const detail = description || normalizedSuggestion.category || '';
1634
- const insertText = normalizedSuggestion.insertText ??
1635
- normalizedSuggestion.text;
1636
- const { text, rule } = this.applyCursorOffset(insertText, normalizedSuggestion.cursorOffset ?? 0);
1637
- return {
1638
- label,
1639
- kind: this.mapSuggestionKind(normalizedSuggestion.type),
1640
- insertText: text,
1641
- insertTextRules: rule,
1642
- detail,
1643
- documentation: description
1644
- ? { value: description }
1645
- : undefined,
1646
- range: this.getCompletionRanges(model, position, normalizedSuggestion),
1647
- sortText: String(index).padStart(4, '0'),
1648
- filterText: buildCompletionFilterText(normalizedSuggestion),
1649
- };
1650
- }),
1651
- };
1652
- }
1653
- catch (error) {
1654
- // Request was cancelled or failed - return empty
1655
- console.debug('Autocomplete request cancelled or failed:', error);
1656
- return { suggestions: [] };
1657
- }
1658
- },
1659
- });
1660
- }
1661
- async resolveAutocompleteResponse(provider, request, _requestId) {
1662
- const result = provider(request);
1663
- if (!result)
1664
- return null;
1665
- // Convert to Observable for unified handling with cancellation
1666
- let source$;
1667
- if (isObservable(result)) {
1668
- source$ = result;
1669
- }
1670
- else if (result instanceof Promise) {
1671
- source$ = from(result);
1672
- }
1673
- else {
1674
- // Synchronous result
1675
- return result;
1676
- }
1677
- // Use takeUntil for cancellation
1678
- return await firstValueFrom(source$.pipe(takeUntil(this.cancelAutocomplete$), catchError(() => of(null)))).catch(() => null);
1679
- }
1680
- applyCursorOffset(insertText, cursorOffset) {
1681
- if (!cursorOffset) {
1682
- return { text: insertText };
1683
- }
1684
- const cursorIndex = Math.max(0, Math.min(insertText.length + cursorOffset, insertText.length));
1685
- const snippet = insertText.slice(0, cursorIndex) + '$0' + insertText.slice(cursorIndex);
1686
- return {
1687
- text: snippet,
1688
- rule: this.monaco?.languages.CompletionItemInsertTextRule.InsertAsSnippet,
1689
- };
1690
- }
1691
- getCompletionRanges(model, position, suggestion) {
1692
- const word = model.getWordUntilPosition(position);
1693
- const { startColumn, endColumn } = resolveCompletionRangeBounds(model.getLineContent(position.lineNumber), position.column, word.startColumn, Math.max(word.endColumn, position.column), suggestion);
1694
- return {
1695
- insert: new this.monaco.Range(position.lineNumber, startColumn, position.lineNumber, position.column),
1696
- replace: new this.monaco.Range(position.lineNumber, startColumn, position.lineNumber, endColumn),
1697
- };
1698
- }
1699
- mapSuggestionKind(type) {
1700
- if (!this.monaco) {
1701
- return 17;
1702
- }
1703
- switch (type) {
1704
- case 'Function':
1705
- return this.monaco.languages.CompletionItemKind.Function;
1706
- case 'Operator':
1707
- return this.monaco.languages.CompletionItemKind.Operator;
1708
- case 'Property':
1709
- return this.monaco.languages.CompletionItemKind.Field;
1710
- case 'Context':
1711
- return this.monaco.languages.CompletionItemKind.Module;
1712
- case 'Keyword':
1713
- return this.monaco.languages.CompletionItemKind.Keyword;
1714
- default:
1715
- return this.monaco.languages.CompletionItemKind.Text;
1716
- }
1717
- }
1718
- syncEditorValue(value) {
1719
- if (!this.model)
1720
- return;
1721
- if (this.model.getValue() === value)
1722
- return;
1723
- this.isApplyingExternalValue = true;
1724
- this.model.setValue(value);
1725
- this.isApplyingExternalValue = false;
1726
- }
1727
- smartBlockToText(block) {
1728
- switch (block.type) {
1729
- case 'function': {
1730
- const text = block.insertText ??
1731
- block.signature ??
1732
- `${block.functionName ?? block.value}()`;
1733
- const cursorOffset = block.cursorOffset ?? (text.endsWith(')') ? -1 : 0);
1734
- return { text, cursorOffset };
1735
- }
1736
- case 'property':
1737
- return { text: block.value ?? '', cursorOffset: 0 };
1738
- case 'operator':
1739
- return {
1740
- text: block.operatorSymbol ?? block.value ?? '',
1741
- cursorOffset: 0,
1742
- };
1743
- case 'literal':
1744
- return {
1745
- text: this.formatLiteral(block.literalValue ?? block.value ?? ''),
1746
- cursorOffset: 0,
1747
- };
1748
- default:
1749
- return { text: block.value ?? '', cursorOffset: 0 };
1750
- }
1751
- }
1752
- formatLiteral(value) {
1753
- if (typeof value === 'string') {
1754
- if (value.startsWith('"') && value.endsWith('"')) {
1755
- return value;
1756
- }
1757
- return `"${value}"`;
1758
- }
1759
- return String(value);
1760
- }
1761
- emitValue(value) {
1762
- this.zone.run(() => {
1763
- this.value.set(value);
1764
- this.formulaChange.emit(value);
1765
- this.onChange(value);
1766
- });
1767
- }
1768
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaEditorCode, deps: [], target: i0.ɵɵFactoryTarget.Component });
1769
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: FormulaEditorCode, isStandalone: true, selector: "mt-formula-editor-code", inputs: { placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, initialFormula: { classPropertyName: "initialFormula", publicName: "initialFormula", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, language: { classPropertyName: "language", publicName: "language", isSignal: true, isRequired: false, transformFunction: null }, theme: { classPropertyName: "theme", publicName: "theme", isSignal: true, isRequired: false, transformFunction: null }, borderless: { classPropertyName: "borderless", publicName: "borderless", isSignal: true, isRequired: false, transformFunction: null }, autocompleteProvider: { classPropertyName: "autocompleteProvider", publicName: "autocompleteProvider", isSignal: true, isRequired: false, transformFunction: null }, autocompleteDebounceMs: { classPropertyName: "autocompleteDebounceMs", publicName: "autocompleteDebounceMs", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { formulaChange: "formulaChange", onBlur: "onBlur", onFocus: "onFocus" }, host: { classAttribute: "block mt-formula-editor-code" }, providers: [
1770
- {
1771
- provide: NG_VALUE_ACCESSOR,
1772
- useExisting: forwardRef(() => FormulaEditorCode),
1773
- multi: true,
1774
- },
1775
- ], viewQueries: [{ propertyName: "editorHost", first: true, predicate: ["editorHost"], descendants: true, isSignal: true }], ngImport: i0, template: "<div\r\n [class]=\"containerClasses()\"\r\n [class.opacity-60]=\"disabled()\"\r\n [class.pointer-events-none]=\"disabled()\"\r\n>\r\n <div #editorHost class=\"min-h-20 flex-1\"></div>\r\n\r\n @if (showPlaceholder()) {\r\n <div\r\n class=\"mt-formula-editor-code__placeholder text-sm italic text-surface-400 dark:text-surface-500\"\r\n >\r\n {{ placeholder() }}\r\n </div>\r\n }\r\n</div>\r\n", styles: [".mt-formula-editor-code{position:relative;--mt-formula-editor-code-gutter: 3.25rem;--mt-formula-editor-code-placeholder-top: .25rem}.mt-formula-editor-code__placeholder{position:absolute;top:var(--mt-formula-editor-code-placeholder-top);left:var(--mt-formula-editor-code-gutter);pointer-events:none;z-index:2;white-space:nowrap}.mt-formula-editor-code .monaco-editor .overflow-guard{overflow:visible}.mt-formula-editor-code .monaco-editor .suggest-widget{z-index:2000}.mt-formula-editor-code .monaco-editor .cursor{transition:opacity .1s ease-in-out}.mt-formula-editor-code .monaco-editor .selected-text{border-radius:0}.mt-formula-editor-code .monaco-editor .bracket-match{border-radius:2px}.mt-formula-editor-code .monaco-editor .view-overlays .current-line{border:none}.mt-formula-editor-code .monaco-editor .monaco-scrollable-element>.scrollbar>.slider{border-radius:0}.mt-formula-editor-code .monaco-editor .suggest-widget{border-radius:3px;box-shadow:0 2px 8px #00000029,0 0 0 1px #0000000a}.mt-formula-editor-code .monaco-editor .suggest-widget .monaco-list-row{padding:0 4px}.mt-formula-editor-code .monaco-editor .suggest-widget .monaco-list-row.focused{border-radius:3px}.mt-formula-editor-code .monaco-editor .monaco-hover{border-radius:3px;box-shadow:0 2px 8px #00000029}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
1776
- }
1777
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaEditorCode, decorators: [{
1778
- type: Component,
1779
- args: [{ selector: 'mt-formula-editor-code', standalone: true, imports: [CommonModule], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, host: {
1780
- class: 'block mt-formula-editor-code',
1781
- }, providers: [
1782
- {
1783
- provide: NG_VALUE_ACCESSOR,
1784
- useExisting: forwardRef(() => FormulaEditorCode),
1785
- multi: true,
1786
- },
1787
- ], template: "<div\r\n [class]=\"containerClasses()\"\r\n [class.opacity-60]=\"disabled()\"\r\n [class.pointer-events-none]=\"disabled()\"\r\n>\r\n <div #editorHost class=\"min-h-20 flex-1\"></div>\r\n\r\n @if (showPlaceholder()) {\r\n <div\r\n class=\"mt-formula-editor-code__placeholder text-sm italic text-surface-400 dark:text-surface-500\"\r\n >\r\n {{ placeholder() }}\r\n </div>\r\n }\r\n</div>\r\n", styles: [".mt-formula-editor-code{position:relative;--mt-formula-editor-code-gutter: 3.25rem;--mt-formula-editor-code-placeholder-top: .25rem}.mt-formula-editor-code__placeholder{position:absolute;top:var(--mt-formula-editor-code-placeholder-top);left:var(--mt-formula-editor-code-gutter);pointer-events:none;z-index:2;white-space:nowrap}.mt-formula-editor-code .monaco-editor .overflow-guard{overflow:visible}.mt-formula-editor-code .monaco-editor .suggest-widget{z-index:2000}.mt-formula-editor-code .monaco-editor .cursor{transition:opacity .1s ease-in-out}.mt-formula-editor-code .monaco-editor .selected-text{border-radius:0}.mt-formula-editor-code .monaco-editor .bracket-match{border-radius:2px}.mt-formula-editor-code .monaco-editor .view-overlays .current-line{border:none}.mt-formula-editor-code .monaco-editor .monaco-scrollable-element>.scrollbar>.slider{border-radius:0}.mt-formula-editor-code .monaco-editor .suggest-widget{border-radius:3px;box-shadow:0 2px 8px #00000029,0 0 0 1px #0000000a}.mt-formula-editor-code .monaco-editor .suggest-widget .monaco-list-row{padding:0 4px}.mt-formula-editor-code .monaco-editor .suggest-widget .monaco-list-row.focused{border-radius:3px}.mt-formula-editor-code .monaco-editor .monaco-hover{border-radius:3px;box-shadow:0 2px 8px #00000029}\n"] }]
1788
- }], ctorParameters: () => [], propDecorators: { placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], initialFormula: [{ type: i0.Input, args: [{ isSignal: true, alias: "initialFormula", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], language: [{ type: i0.Input, args: [{ isSignal: true, alias: "language", required: false }] }], theme: [{ type: i0.Input, args: [{ isSignal: true, alias: "theme", required: false }] }], borderless: [{ type: i0.Input, args: [{ isSignal: true, alias: "borderless", required: false }] }], autocompleteProvider: [{ type: i0.Input, args: [{ isSignal: true, alias: "autocompleteProvider", required: false }] }], autocompleteDebounceMs: [{ type: i0.Input, args: [{ isSignal: true, alias: "autocompleteDebounceMs", required: false }] }], formulaChange: [{ type: i0.Output, args: ["formulaChange"] }], onBlur: [{ type: i0.Output, args: ["onBlur"] }], onFocus: [{ type: i0.Output, args: ["onFocus"] }], editorHost: [{ type: i0.ViewChild, args: ['editorHost', { isSignal: true }] }] } });
1789
-
1790
- /**
1791
- * Toolbar Item Component
1792
- * Clickable item in the toolbar (function, property, operator)
1793
- * Items are clicked to insert - no drag from toolbar
1794
- *
1795
- * This is a pure input/output component with no service dependencies.
1796
- */
1797
- class FormulaToolbarItem {
1798
- /** Item type */
1799
- type = input.required(...(ngDevMode ? [{ debugName: "type" }] : /* istanbul ignore next */ []));
1800
- /** Item value (function name, property key, operator symbol) */
1801
- value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
1802
- /** Display value (optional, defaults to value) */
1803
- display = input(...(ngDevMode ? [undefined, { debugName: "display" }] : /* istanbul ignore next */ []));
1804
- /** Description for tooltip */
1805
- description = input('', ...(ngDevMode ? [{ debugName: "description" }] : /* istanbul ignore next */ []));
1806
- /** Function signature (for functions only, e.g., "SUM(values)") */
1807
- signature = input(...(ngDevMode ? [undefined, { debugName: "signature" }] : /* istanbul ignore next */ []));
1808
- /** Function examples (for functions only) - can be strings or objects with code/description */
1809
- examples = input([], ...(ngDevMode ? [{ debugName: "examples" }] : /* istanbul ignore next */ []));
1810
- /** Backend template to insert (preferred over signature) */
1811
- template = input(...(ngDevMode ? [undefined, { debugName: "template" }] : /* istanbul ignore next */ []));
1812
- /** Cursor offset relative to inserted template */
1813
- templateCursorOffset = input(...(ngDevMode ? [undefined, { debugName: "templateCursorOffset" }] : /* istanbul ignore next */ []));
1814
- /** Function hints from backend documentation */
1815
- hints = input([], ...(ngDevMode ? [{ debugName: "hints" }] : /* istanbul ignore next */ []));
1816
- /** Function return type */
1817
- returnType = input(...(ngDevMode ? [undefined, { debugName: "returnType" }] : /* istanbul ignore next */ []));
1818
- /** Function parameters */
1819
- parameters = input([], ...(ngDevMode ? [{ debugName: "parameters" }] : /* istanbul ignore next */ []));
1820
- /** Normalized description */
1821
- normalizedDescription = computed(() => this.description().trim(), ...(ngDevMode ? [{ debugName: "normalizedDescription" }] : /* istanbul ignore next */ []));
1822
- /** Normalized signature */
1823
- normalizedSignature = computed(() => this.signature()?.trim() ?? '', ...(ngDevMode ? [{ debugName: "normalizedSignature" }] : /* istanbul ignore next */ []));
1824
- /** Normalized template */
1825
- normalizedTemplate = computed(() => this.template()?.trim() ?? '', ...(ngDevMode ? [{ debugName: "normalizedTemplate" }] : /* istanbul ignore next */ []));
1826
- /** Normalized return type */
1827
- normalizedReturnType = computed(() => this.returnType()?.trim() ?? '', ...(ngDevMode ? [{ debugName: "normalizedReturnType" }] : /* istanbul ignore next */ []));
1828
- /** Normalized examples as ExampleItem[] */
1829
- normalizedExamples = computed(() => {
1830
- return this.examples()
1831
- .map((example) => {
1832
- const normalized = typeof example === 'string' ? { code: example } : example;
1833
- return {
1834
- code: normalized.code.trim(),
1835
- description: normalized.description?.trim() || undefined,
1836
- };
1837
- })
1838
- .filter((example) => example.code.length > 0);
1839
- }, ...(ngDevMode ? [{ debugName: "normalizedExamples" }] : /* istanbul ignore next */ []));
1840
- /** Normalized hints */
1841
- normalizedHints = computed(() => this.hints()
1842
- .map((hint) => hint.trim())
1843
- .filter((hint) => hint.length > 0), ...(ngDevMode ? [{ debugName: "normalizedHints" }] : /* istanbul ignore next */ []));
1844
- /** Normalized parameters */
1845
- normalizedParameters = computed(() => this.parameters()
1846
- .map((parameter) => ({
1847
- ...parameter,
1848
- name: parameter.name.trim(),
1849
- type: parameter.type.trim(),
1850
- description: parameter.description.trim(),
1851
- }))
1852
- .filter((parameter) => parameter.name.length > 0 ||
1853
- parameter.type.length > 0 ||
1854
- parameter.description.length > 0), ...(ngDevMode ? [{ debugName: "normalizedParameters" }] : /* istanbul ignore next */ []));
1855
- /** Property type for properties */
1856
- propertyType = input('current', ...(ngDevMode ? [{ debugName: "propertyType" }] : /* istanbul ignore next */ []));
1857
- /** Insert event - emits SmartBlock */
1858
- onInsert = output();
1859
- /** Computed display value */
1860
- displayValue = computed(() => this.display() ?? this.value(), ...(ngDevMode ? [{ debugName: "displayValue" }] : /* istanbul ignore next */ []));
1861
- /** Whether function metadata should use the rich tooltip template */
1862
- hasRichTooltip = computed(() => this.type() === 'function' &&
1863
- Boolean(this.normalizedSignature() ||
1864
- this.shouldShowTemplate() ||
1865
- this.normalizedDescription() ||
1866
- this.normalizedReturnType() ||
1867
- this.normalizedParameters().length > 0 ||
1868
- this.normalizedExamples().length > 0 ||
1869
- this.normalizedHints().length > 0), ...(ngDevMode ? [{ debugName: "hasRichTooltip" }] : /* istanbul ignore next */ []));
1870
- /** Keep lightweight tooltip behavior only for small descriptions */
1871
- simpleTooltip = computed(() => this.hasRichTooltip() ? '' : this.normalizedDescription(), ...(ngDevMode ? [{ debugName: "simpleTooltip" }] : /* istanbul ignore next */ []));
1872
- /** Show insert template when it adds useful information beyond the signature */
1873
- shouldShowTemplate = computed(() => {
1874
- const template = this.normalizedTemplate();
1875
- return template.length > 0 && template !== this.normalizedSignature();
1876
- }, ...(ngDevMode ? [{ debugName: "shouldShowTemplate" }] : /* istanbul ignore next */ []));
1877
- /** PrimeNG tooltip class to widen rich tooltip content */
1878
- tooltipStyleClass = computed(() => this.hasRichTooltip()
1879
- ? 'mt-formula-toolbar-item-tooltip mt-formula-toolbar-item-tooltip-rich'
1880
- : 'mt-formula-toolbar-item-tooltip', ...(ngDevMode ? [{ debugName: "tooltipStyleClass" }] : /* istanbul ignore next */ []));
1881
- /** Build SmartBlock from item data */
1882
- smartBlock = computed(() => {
1883
- switch (this.type()) {
1884
- case 'function':
1885
- return createFunctionBlock(this.normalizedSignature() || `${this.value()}()`, this.value(), this.normalizedTemplate() ||
1886
- this.normalizedSignature() ||
1887
- `${this.value()}()`, this.templateCursorOffset());
1888
- case 'property':
1889
- return createPropertyBlock(this.value(), this.propertyType(), this.display());
1890
- case 'operator':
1891
- return createOperatorBlock(this.value());
1892
- default:
1893
- return createOperatorBlock(this.value());
1894
- }
1895
- }, ...(ngDevMode ? [{ debugName: "smartBlock" }] : /* istanbul ignore next */ []));
1896
- /** Item CSS class based on type */
1897
- itemClass = computed(() => {
1898
- switch (this.type()) {
1899
- case 'function':
1900
- return 'bg-slate-200 text-slate-700 hover:bg-slate-300 dark:bg-slate-700 dark:text-slate-300 dark:hover:bg-slate-600';
1901
- case 'property':
1902
- return 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-300 dark:hover:bg-amber-900/50';
1903
- case 'operator':
1904
- return 'bg-sky-100 text-sky-700 hover:bg-sky-200 dark:bg-sky-900/30 dark:text-sky-300 dark:hover:bg-sky-900/50';
1905
- default:
1906
- return 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300';
1907
- }
1908
- }, ...(ngDevMode ? [{ debugName: "itemClass" }] : /* istanbul ignore next */ []));
1909
- /** Handle click - emit the SmartBlock */
1910
- handleClick() {
1911
- this.onInsert.emit(this.smartBlock());
1912
- }
1913
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaToolbarItem, deps: [], target: i0.ɵɵFactoryTarget.Component });
1914
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: FormulaToolbarItem, isStandalone: true, selector: "mt-formula-toolbar-item", inputs: { type: { classPropertyName: "type", publicName: "type", isSignal: true, isRequired: true, transformFunction: null }, value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: true, transformFunction: null }, display: { classPropertyName: "display", publicName: "display", isSignal: true, isRequired: false, transformFunction: null }, description: { classPropertyName: "description", publicName: "description", isSignal: true, isRequired: false, transformFunction: null }, signature: { classPropertyName: "signature", publicName: "signature", isSignal: true, isRequired: false, transformFunction: null }, examples: { classPropertyName: "examples", publicName: "examples", isSignal: true, isRequired: false, transformFunction: null }, template: { classPropertyName: "template", publicName: "template", isSignal: true, isRequired: false, transformFunction: null }, templateCursorOffset: { classPropertyName: "templateCursorOffset", publicName: "templateCursorOffset", isSignal: true, isRequired: false, transformFunction: null }, hints: { classPropertyName: "hints", publicName: "hints", isSignal: true, isRequired: false, transformFunction: null }, returnType: { classPropertyName: "returnType", publicName: "returnType", isSignal: true, isRequired: false, transformFunction: null }, parameters: { classPropertyName: "parameters", publicName: "parameters", isSignal: true, isRequired: false, transformFunction: null }, propertyType: { classPropertyName: "propertyType", publicName: "propertyType", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { onInsert: "onInsert" }, host: { classAttribute: "inline-block max-w-full" }, ngImport: i0, template: "<button\r\n type=\"button\"\r\n class=\"inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded px-2 py-1 text-sm font-medium transition-colors hover:shadow-sm active:scale-95\"\r\n [class]=\"itemClass()\"\r\n [pTooltip]=\"hasRichTooltip() ? richTooltip : simpleTooltip()\"\r\n [tooltipDisabled]=\"!hasRichTooltip() && !simpleTooltip()\"\r\n [tooltipStyleClass]=\"tooltipStyleClass()\"\r\n [tooltipPosition]=\"'bottom'\"\r\n [showDelay]=\"300\"\r\n [hideDelay]=\"100\"\r\n [autoHide]=\"!hasRichTooltip()\"\r\n (click)=\"handleClick()\"\r\n>\r\n @if (type() === \"function\") {\r\n <span class=\"text-sm opacity-60\">f</span>\r\n }\r\n <span class=\"truncate\">{{ displayValue() }}</span>\r\n</button>\r\n\r\n<ng-template #richTooltip>\r\n <div class=\"space-y-3\">\r\n @if (normalizedSignature()) {\r\n <div class=\"rounded bg-slate-700 px-3 py-2\">\r\n <code\r\n class=\"block whitespace-pre-wrap break-words font-mono text-sm text-emerald-400\"\r\n >{{ normalizedSignature() }}</code\r\n >\r\n </div>\r\n }\r\n\r\n @if (shouldShowTemplate()) {\r\n <div class=\"space-y-1\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Insert</span\r\n >\r\n <div class=\"rounded bg-slate-800 px-3 py-2\">\r\n <code\r\n class=\"block whitespace-pre-wrap break-words font-mono text-xs text-amber-300\"\r\n >{{ normalizedTemplate() }}</code\r\n >\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (normalizedDescription()) {\r\n <p class=\"text-sm leading-relaxed text-slate-200\">\r\n {{ normalizedDescription() }}\r\n </p>\r\n }\r\n\r\n @if (normalizedReturnType()) {\r\n <div class=\"flex items-center gap-2 text-xs text-slate-300\">\r\n <span class=\"font-semibold uppercase tracking-wider text-slate-400\"\r\n >Returns</span\r\n >\r\n <code class=\"rounded bg-slate-800 px-2 py-0.5 text-sky-300\">{{\r\n normalizedReturnType()\r\n }}</code>\r\n </div>\r\n }\r\n\r\n @if (normalizedParameters().length > 0) {\r\n <div class=\"space-y-2 border-t border-slate-600 pt-3\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Parameters</span\r\n >\r\n <div class=\"space-y-2\">\r\n @for (\r\n parameter of normalizedParameters();\r\n track parameter.name + parameter.type\r\n ) {\r\n <div class=\"rounded bg-slate-800/70 px-3 py-2\">\r\n <div class=\"flex flex-wrap items-center gap-2 text-xs\">\r\n @if (parameter.name) {\r\n <code class=\"font-mono text-emerald-300\">{{\r\n parameter.name\r\n }}</code>\r\n }\r\n @if (parameter.type) {\r\n <code class=\"text-sky-300\">{{ parameter.type }}</code>\r\n }\r\n </div>\r\n @if (parameter.description) {\r\n <p class=\"mt-1 text-xs leading-relaxed text-slate-400\">\r\n {{ parameter.description }}\r\n </p>\r\n }\r\n </div>\r\n }\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (normalizedExamples().length > 0) {\r\n <div class=\"space-y-2 border-t border-slate-600 pt-3\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Examples</span\r\n >\r\n <div class=\"space-y-2\">\r\n @for (example of normalizedExamples(); track example.code + $index) {\r\n <div class=\"space-y-1\">\r\n <div class=\"rounded bg-slate-800 px-3 py-2\">\r\n <code\r\n class=\"block whitespace-pre-wrap break-words font-mono text-xs text-amber-300\"\r\n >{{ example.code }}</code\r\n >\r\n </div>\r\n @if (example.description) {\r\n <p class=\"px-1 text-xs leading-relaxed text-slate-400\">\r\n {{ example.description }}\r\n </p>\r\n }\r\n </div>\r\n }\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (normalizedHints().length > 0) {\r\n <div class=\"space-y-2 border-t border-slate-600 pt-3\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Hints</span\r\n >\r\n <div class=\"space-y-1.5\">\r\n @for (hint of normalizedHints(); track hint) {\r\n <p\r\n class=\"rounded bg-slate-800/70 px-3 py-2 text-xs leading-relaxed text-slate-300\"\r\n >\r\n {{ hint }}\r\n </p>\r\n }\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n</ng-template>\r\n", styles: [".mt-formula-toolbar-item-tooltip.p-tooltip,.mt-formula-toolbar-item-tooltip .p-tooltip-text{max-width:min(32rem,92vw)}.mt-formula-toolbar-item-tooltip-rich .p-tooltip-text{width:min(32rem,92vw);max-height:min(70vh,36rem);overflow-y:auto;padding:.75rem}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: TooltipModule }, { kind: "directive", type: i1$1.Tooltip, selector: "[pTooltip]", inputs: ["tooltipPosition", "tooltipEvent", "positionStyle", "tooltipStyleClass", "tooltipZIndex", "escape", "showDelay", "hideDelay", "life", "positionTop", "positionLeft", "autoHide", "fitContent", "hideOnEscape", "showOnEllipsis", "pTooltip", "tooltipDisabled", "tooltipOptions", "appendTo", "ptTooltip", "pTooltipPT", "pTooltipUnstyled"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
1915
- }
1916
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaToolbarItem, decorators: [{
1917
- type: Component,
1918
- args: [{ selector: 'mt-formula-toolbar-item', standalone: true, imports: [CommonModule, TooltipModule], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, host: {
1919
- class: 'inline-block max-w-full',
1920
- }, template: "<button\r\n type=\"button\"\r\n class=\"inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded px-2 py-1 text-sm font-medium transition-colors hover:shadow-sm active:scale-95\"\r\n [class]=\"itemClass()\"\r\n [pTooltip]=\"hasRichTooltip() ? richTooltip : simpleTooltip()\"\r\n [tooltipDisabled]=\"!hasRichTooltip() && !simpleTooltip()\"\r\n [tooltipStyleClass]=\"tooltipStyleClass()\"\r\n [tooltipPosition]=\"'bottom'\"\r\n [showDelay]=\"300\"\r\n [hideDelay]=\"100\"\r\n [autoHide]=\"!hasRichTooltip()\"\r\n (click)=\"handleClick()\"\r\n>\r\n @if (type() === \"function\") {\r\n <span class=\"text-sm opacity-60\">f</span>\r\n }\r\n <span class=\"truncate\">{{ displayValue() }}</span>\r\n</button>\r\n\r\n<ng-template #richTooltip>\r\n <div class=\"space-y-3\">\r\n @if (normalizedSignature()) {\r\n <div class=\"rounded bg-slate-700 px-3 py-2\">\r\n <code\r\n class=\"block whitespace-pre-wrap break-words font-mono text-sm text-emerald-400\"\r\n >{{ normalizedSignature() }}</code\r\n >\r\n </div>\r\n }\r\n\r\n @if (shouldShowTemplate()) {\r\n <div class=\"space-y-1\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Insert</span\r\n >\r\n <div class=\"rounded bg-slate-800 px-3 py-2\">\r\n <code\r\n class=\"block whitespace-pre-wrap break-words font-mono text-xs text-amber-300\"\r\n >{{ normalizedTemplate() }}</code\r\n >\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (normalizedDescription()) {\r\n <p class=\"text-sm leading-relaxed text-slate-200\">\r\n {{ normalizedDescription() }}\r\n </p>\r\n }\r\n\r\n @if (normalizedReturnType()) {\r\n <div class=\"flex items-center gap-2 text-xs text-slate-300\">\r\n <span class=\"font-semibold uppercase tracking-wider text-slate-400\"\r\n >Returns</span\r\n >\r\n <code class=\"rounded bg-slate-800 px-2 py-0.5 text-sky-300\">{{\r\n normalizedReturnType()\r\n }}</code>\r\n </div>\r\n }\r\n\r\n @if (normalizedParameters().length > 0) {\r\n <div class=\"space-y-2 border-t border-slate-600 pt-3\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Parameters</span\r\n >\r\n <div class=\"space-y-2\">\r\n @for (\r\n parameter of normalizedParameters();\r\n track parameter.name + parameter.type\r\n ) {\r\n <div class=\"rounded bg-slate-800/70 px-3 py-2\">\r\n <div class=\"flex flex-wrap items-center gap-2 text-xs\">\r\n @if (parameter.name) {\r\n <code class=\"font-mono text-emerald-300\">{{\r\n parameter.name\r\n }}</code>\r\n }\r\n @if (parameter.type) {\r\n <code class=\"text-sky-300\">{{ parameter.type }}</code>\r\n }\r\n </div>\r\n @if (parameter.description) {\r\n <p class=\"mt-1 text-xs leading-relaxed text-slate-400\">\r\n {{ parameter.description }}\r\n </p>\r\n }\r\n </div>\r\n }\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (normalizedExamples().length > 0) {\r\n <div class=\"space-y-2 border-t border-slate-600 pt-3\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Examples</span\r\n >\r\n <div class=\"space-y-2\">\r\n @for (example of normalizedExamples(); track example.code + $index) {\r\n <div class=\"space-y-1\">\r\n <div class=\"rounded bg-slate-800 px-3 py-2\">\r\n <code\r\n class=\"block whitespace-pre-wrap break-words font-mono text-xs text-amber-300\"\r\n >{{ example.code }}</code\r\n >\r\n </div>\r\n @if (example.description) {\r\n <p class=\"px-1 text-xs leading-relaxed text-slate-400\">\r\n {{ example.description }}\r\n </p>\r\n }\r\n </div>\r\n }\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (normalizedHints().length > 0) {\r\n <div class=\"space-y-2 border-t border-slate-600 pt-3\">\r\n <span\r\n class=\"text-xs font-semibold uppercase tracking-wider text-slate-400\"\r\n >Hints</span\r\n >\r\n <div class=\"space-y-1.5\">\r\n @for (hint of normalizedHints(); track hint) {\r\n <p\r\n class=\"rounded bg-slate-800/70 px-3 py-2 text-xs leading-relaxed text-slate-300\"\r\n >\r\n {{ hint }}\r\n </p>\r\n }\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n</ng-template>\r\n", styles: [".mt-formula-toolbar-item-tooltip.p-tooltip,.mt-formula-toolbar-item-tooltip .p-tooltip-text{max-width:min(32rem,92vw)}.mt-formula-toolbar-item-tooltip-rich .p-tooltip-text{width:min(32rem,92vw);max-height:min(70vh,36rem);overflow-y:auto;padding:.75rem}\n"] }]
1921
- }], propDecorators: { type: [{ type: i0.Input, args: [{ isSignal: true, alias: "type", required: true }] }], value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: true }] }], display: [{ type: i0.Input, args: [{ isSignal: true, alias: "display", required: false }] }], description: [{ type: i0.Input, args: [{ isSignal: true, alias: "description", required: false }] }], signature: [{ type: i0.Input, args: [{ isSignal: true, alias: "signature", required: false }] }], examples: [{ type: i0.Input, args: [{ isSignal: true, alias: "examples", required: false }] }], template: [{ type: i0.Input, args: [{ isSignal: true, alias: "template", required: false }] }], templateCursorOffset: [{ type: i0.Input, args: [{ isSignal: true, alias: "templateCursorOffset", required: false }] }], hints: [{ type: i0.Input, args: [{ isSignal: true, alias: "hints", required: false }] }], returnType: [{ type: i0.Input, args: [{ isSignal: true, alias: "returnType", required: false }] }], parameters: [{ type: i0.Input, args: [{ isSignal: true, alias: "parameters", required: false }] }], propertyType: [{ type: i0.Input, args: [{ isSignal: true, alias: "propertyType", required: false }] }], onInsert: [{ type: i0.Output, args: ["onInsert"] }] } });
1922
-
1923
- const OPERATOR_SYMBOL_TO_TRANSLATION_KEY = {
1924
- '+': 'add',
1925
- '-': 'subtract',
1926
- '*': 'multiply',
1927
- '/': 'divide',
1928
- '%': 'modulo',
1929
- '==': 'equal',
1930
- '!=': 'notEqual',
1931
- '>': 'greater',
1932
- '<': 'less',
1933
- '>=': 'greaterOrEqual',
1934
- '<=': 'lessOrEqual',
1935
- '&&': 'and',
1936
- '||': 'or',
1937
- '!': 'not',
1938
- };
1939
- const DEFAULT_OPERATORS = [
1940
- // Arithmetic
1941
- {
1942
- symbol: '+',
1943
- name: 'Add',
1944
- type: 'arithmetic',
1945
- description: 'Addition',
1946
- precedence: 4,
1947
- },
1948
- {
1949
- symbol: '-',
1950
- name: 'Subtract',
1951
- type: 'arithmetic',
1952
- description: 'Subtraction',
1953
- precedence: 4,
1954
- },
1955
- {
1956
- symbol: '*',
1957
- name: 'Multiply',
1958
- type: 'arithmetic',
1959
- description: 'Multiplication',
1960
- precedence: 5,
1961
- },
1962
- {
1963
- symbol: '/',
1964
- name: 'Divide',
1965
- type: 'arithmetic',
1966
- description: 'Division',
1967
- precedence: 5,
1968
- },
1969
- {
1970
- symbol: '%',
1971
- name: 'Modulo',
1972
- type: 'arithmetic',
1973
- description: 'Modulo',
1974
- precedence: 5,
1975
- },
1976
- // Comparison
1977
- {
1978
- symbol: '==',
1979
- name: 'Equal',
1980
- type: 'comparison',
1981
- description: 'Equal to',
1982
- precedence: 3,
1983
- },
1984
- {
1985
- symbol: '!=',
1986
- name: 'Not Equal',
1987
- type: 'comparison',
1988
- description: 'Not equal to',
1989
- precedence: 3,
1990
- },
1991
- {
1992
- symbol: '>',
1993
- name: 'Greater',
1994
- type: 'comparison',
1995
- description: 'Greater than',
1996
- precedence: 3,
1997
- },
1998
- {
1999
- symbol: '<',
2000
- name: 'Less',
2001
- type: 'comparison',
2002
- description: 'Less than',
2003
- precedence: 3,
2004
- },
2005
- {
2006
- symbol: '>=',
2007
- name: 'Greater or Equal',
2008
- type: 'comparison',
2009
- description: 'Greater than or equal',
2010
- precedence: 3,
2011
- },
2012
- {
2013
- symbol: '<=',
2014
- name: 'Less or Equal',
2015
- type: 'comparison',
2016
- description: 'Less than or equal',
2017
- precedence: 3,
2018
- },
2019
- // Logical
2020
- {
2021
- symbol: '&&',
2022
- name: 'And',
2023
- type: 'logical',
2024
- description: 'Logical AND',
2025
- precedence: 2,
2026
- },
2027
- {
2028
- symbol: '||',
2029
- name: 'Or',
2030
- type: 'logical',
2031
- description: 'Logical OR',
2032
- precedence: 1,
2033
- },
2034
- {
2035
- symbol: '!',
2036
- name: 'Not',
2037
- type: 'logical',
2038
- description: 'Logical NOT',
2039
- precedence: 6,
2040
- },
2041
- ];
2042
-
2043
- /**
2044
- * Formula Toolbar Component
2045
- * Vertical tabs toolbar with functions, properties, and operators
2046
- *
2047
- * This is a PURE input/output component with NO service dependencies.
2048
- * All data (functions, operators, properties) must be passed via inputs.
2049
- */
2050
- class FormulaToolbar {
2051
- transloco = inject(TranslocoService);
2052
- // ============ INPUTS ============
2053
- /** Known properties to show in properties tab */
2054
- knownProperties = input([], ...(ngDevMode ? [{ debugName: "knownProperties" }] : /* istanbul ignore next */ []));
2055
- /** Custom properties template */
2056
- propertiesTemplate = input(null, ...(ngDevMode ? [{ debugName: "propertiesTemplate" }] : /* istanbul ignore next */ []));
2057
- /** Projected properties template */
2058
- projectedPropertiesTemplate = contentChild('properties', { ...(ngDevMode ? { debugName: "projectedPropertiesTemplate" } : /* istanbul ignore next */ {}), read: TemplateRef });
2059
- /** Function categories (from API or static data) */
2060
- functionCategories = input([], ...(ngDevMode ? [{ debugName: "functionCategories" }] : /* istanbul ignore next */ []));
2061
- /** Operators list (overridable) */
2062
- operators = input(DEFAULT_OPERATORS, ...(ngDevMode ? [{ debugName: "operators" }] : /* istanbul ignore next */ []));
2063
- /** Initial active tab */
2064
- initialTab = input('functions', ...(ngDevMode ? [{ debugName: "initialTab" }] : /* istanbul ignore next */ []));
2065
- /** Tabs visible in the toolbar */
2066
- visibleTabs = input([
2067
- 'functions',
2068
- 'properties',
2069
- 'operators',
2070
- ], ...(ngDevMode ? [{ debugName: "visibleTabs" }] : /* istanbul ignore next */ []));
2071
- /** Placeholder for search input */
2072
- searchPlaceholder = input('', ...(ngDevMode ? [{ debugName: "searchPlaceholder" }] : /* istanbul ignore next */ []));
2073
- /** Labels */
2074
- labels = input({}, ...(ngDevMode ? [{ debugName: "labels" }] : /* istanbul ignore next */ []));
2075
- // ============ OUTPUTS ============
2076
- /** Insert event - emits SmartBlock for the editor */
2077
- onBlockInsert = output();
2078
- /** Tab change event */
2079
- onTabChange = output();
2080
- // ============ STATE ============
2081
- /** Active tab */
2082
- activeTab = signal('functions', ...(ngDevMode ? [{ debugName: "activeTab" }] : /* istanbul ignore next */ []));
2083
- /** Tab options */
2084
- tabOptions = computed(() => [
2085
- {
2086
- label: this.transloco.translate('components.formula.toolbar.functions'),
2087
- value: 'functions',
2088
- },
2089
- {
2090
- label: this.transloco.translate('components.formula.toolbar.properties'),
2091
- value: 'properties',
2092
- },
2093
- {
2094
- label: this.transloco.translate('components.formula.toolbar.operators'),
2095
- value: 'operators',
2096
- },
2097
- ], ...(ngDevMode ? [{ debugName: "tabOptions" }] : /* istanbul ignore next */ []));
2098
- /** Tabs actually rendered */
2099
- resolvedTabOptions = computed(() => {
2100
- const visibleTabs = this.visibleTabs();
2101
- const allTabs = this.tabOptions();
2102
- const tabs = allTabs.filter((tab) => visibleTabs.includes(tab.value));
2103
- return tabs.length > 0 ? tabs : [allTabs[0]];
2104
- }, ...(ngDevMode ? [{ debugName: "resolvedTabOptions" }] : /* istanbul ignore next */ []));
2105
- /** Context for custom properties template */
2106
- propertiesTemplateContext = {
2107
- insertBlock: (block) => this.insertBlock(block),
2108
- };
2109
- /** Resolve properties template (projected first, input fallback) */
2110
- resolvedPropertiesTemplate = computed(() => this.projectedPropertiesTemplate() ?? this.propertiesTemplate(), ...(ngDevMode ? [{ debugName: "resolvedPropertiesTemplate" }] : /* istanbul ignore next */ []));
2111
- /** Search query */
2112
- searchQuery = signal('', ...(ngDevMode ? [{ debugName: "searchQuery" }] : /* istanbul ignore next */ []));
2113
- /** Custom value input */
2114
- customValue = signal('', ...(ngDevMode ? [{ debugName: "customValue" }] : /* istanbul ignore next */ []));
2115
- /** Detected type of custom value */
2116
- customValueType = computed(() => {
2117
- const val = this.customValue().trim();
2118
- if (!val)
2119
- return 'text';
2120
- // Check if it's a number
2121
- if (/^-?\d+(\.\d+)?$/.test(val)) {
2122
- return 'number';
2123
- }
2124
- // Check if it's a quoted string
2125
- if ((val.startsWith('"') && val.endsWith('"')) ||
2126
- (val.startsWith("'") && val.endsWith("'"))) {
2127
- return 'string';
2128
- }
2129
- return 'text';
2130
- }, ...(ngDevMode ? [{ debugName: "customValueType" }] : /* istanbul ignore next */ []));
2131
- /** Preview of custom value */
2132
- customValuePreview = computed(() => {
2133
- const val = this.customValue().trim();
2134
- if (!val)
2135
- return '';
2136
- const type = this.customValueType();
2137
- if (type === 'string') {
2138
- // Show the quoted string as-is
2139
- return val;
2140
- }
2141
- if (type === 'number') {
2142
- return val;
2143
- }
2144
- // For unquoted text, show as string preview
2145
- return `"${val}"`;
2146
- }, ...(ngDevMode ? [{ debugName: "customValuePreview" }] : /* istanbul ignore next */ []));
2147
- /** CSS class for custom value type */
2148
- customValueTypeClass = computed(() => {
2149
- switch (this.customValueType()) {
2150
- case 'number':
2151
- return 'bg-rose-100 text-rose-700 hover:bg-rose-200 dark:bg-rose-900/30 dark:text-rose-300 dark:hover:bg-rose-900/50';
2152
- case 'string':
2153
- return 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-300 dark:hover:bg-emerald-900/50';
2154
- default:
2155
- return 'bg-slate-100 text-slate-700 hover:bg-slate-200 dark:bg-slate-700 dark:text-slate-300 dark:hover:bg-slate-600';
2156
- }
2157
- }, ...(ngDevMode ? [{ debugName: "customValueTypeClass" }] : /* istanbul ignore next */ []));
2158
- constructor() {
2159
- // Initialize active tab from input
2160
- effect(() => {
2161
- const initial = this.initialTab();
2162
- const availableTabs = this.resolvedTabOptions();
2163
- const nextTab = availableTabs.some((tab) => tab.value === initial)
2164
- ? initial
2165
- : availableTabs[0]?.value;
2166
- if (nextTab) {
2167
- this.activeTab.set(nextTab);
2168
- }
2169
- });
2170
- }
2171
- // ============ COMPUTED ============
2172
- /** Filtered categories based on search */
2173
- filteredCategories = computed(() => {
2174
- const query = this.searchQuery().trim().toLowerCase();
2175
- return this.functionCategories()
2176
- .map((cat) => ({
2177
- ...cat,
2178
- functions: cat.functions.filter((fn) => {
2179
- if (!query) {
2180
- return true;
2181
- }
2182
- const functionName = fn.name.toLowerCase();
2183
- const description = fn.description.toLowerCase();
2184
- const categoryName = String(cat.displayName ?? cat.name).toLowerCase();
2185
- return (functionName.includes(query) ||
2186
- description.includes(query) ||
2187
- categoryName.includes(query));
2188
- }),
2189
- }))
2190
- .filter((cat) => cat.functions.length > 0);
2191
- }, ...(ngDevMode ? [{ debugName: "filteredCategories" }] : /* istanbul ignore next */ []));
2192
- /** Filtered properties based on search */
2193
- filteredProperties = computed(() => {
2194
- const query = this.searchQuery().toLowerCase();
2195
- const props = this.knownProperties();
2196
- if (!query)
2197
- return props;
2198
- return props.filter((p) => p.toLowerCase().includes(query));
2199
- }, ...(ngDevMode ? [{ debugName: "filteredProperties" }] : /* istanbul ignore next */ []));
2200
- /** Operators translated through the active locale */
2201
- translatedOperators = computed(() => this.operators().map((op) => {
2202
- const key = OPERATOR_SYMBOL_TO_TRANSLATION_KEY[op.symbol];
2203
- if (!key)
2204
- return op;
2205
- return {
2206
- ...op,
2207
- name: this.transloco.translate(`components.formulaOperators.${key}.name`),
2208
- description: this.transloco.translate(`components.formulaOperators.${key}.description`),
2209
- };
2210
- }), ...(ngDevMode ? [{ debugName: "translatedOperators" }] : /* istanbul ignore next */ []));
2211
- /** Filtered operators based on search */
2212
- filteredOperators = computed(() => {
2213
- const query = this.searchQuery().toLowerCase();
2214
- const ops = this.translatedOperators();
2215
- if (!query)
2216
- return ops;
2217
- return ops.filter((op) => op.symbol.toLowerCase().includes(query) ||
2218
- op.name.toLowerCase().includes(query) ||
2219
- op.description.toLowerCase().includes(query));
2220
- }, ...(ngDevMode ? [{ debugName: "filteredOperators" }] : /* istanbul ignore next */ []));
2221
- /** Count of filtered items per tab */
2222
- filteredFunctionsCount = computed(() => this.filteredCategories().reduce((sum, cat) => sum + cat.functions.length, 0), ...(ngDevMode ? [{ debugName: "filteredFunctionsCount" }] : /* istanbul ignore next */ []));
2223
- filteredPropertiesCount = computed(() => this.filteredProperties().length, ...(ngDevMode ? [{ debugName: "filteredPropertiesCount" }] : /* istanbul ignore next */ []));
2224
- filteredOperatorsCount = computed(() => this.filteredOperators().length, ...(ngDevMode ? [{ debugName: "filteredOperatorsCount" }] : /* istanbul ignore next */ []));
2225
- /** Smart search effect - switches to tab with results */
2226
- smartSearchEffect = effect(() => {
2227
- const query = this.searchQuery();
2228
- if (!query || query.length < 2)
2229
- return;
2230
- const currentTab = this.activeTab();
2231
- const availableTabs = this.resolvedTabOptions().map((tab) => tab.value);
2232
- const functionsCount = this.filteredFunctionsCount();
2233
- const propertiesCount = this.filteredPropertiesCount();
2234
- const operatorsCount = this.filteredOperatorsCount();
2235
- // Check if current tab has results
2236
- const currentHasResults = (currentTab === 'functions' && functionsCount > 0) ||
2237
- (currentTab === 'properties' && propertiesCount > 0) ||
2238
- (currentTab === 'operators' && operatorsCount > 0);
2239
- // If current tab has no results, switch to first tab with results
2240
- if (!currentHasResults) {
2241
- if (availableTabs.includes('functions') && functionsCount > 0) {
2242
- this.activeTab.set('functions');
2243
- }
2244
- else if (availableTabs.includes('properties') && propertiesCount > 0) {
2245
- this.activeTab.set('properties');
2246
- }
2247
- else if (availableTabs.includes('operators') && operatorsCount > 0) {
2248
- this.activeTab.set('operators');
2249
- }
2250
- }
2251
- }, ...(ngDevMode ? [{ debugName: "smartSearchEffect" }] : /* istanbul ignore next */ []));
2252
- /** Group operators by type */
2253
- operatorGroups = computed(() => {
2254
- const ops = this.filteredOperators();
2255
- const groups = new Map();
2256
- ops.forEach((op) => {
2257
- const type = op.type || 'other';
2258
- if (!groups.has(type)) {
2259
- groups.set(type, []);
2260
- }
2261
- groups.get(type).push(op);
2262
- });
2263
- return Array.from(groups.entries()).map(([type, operators]) => ({
2264
- type,
2265
- operators,
2266
- }));
2267
- }, ...(ngDevMode ? [{ debugName: "operatorGroups" }] : /* istanbul ignore next */ []));
2268
- /** Translate an operator group header, falling back to a capitalized label */
2269
- operatorTypeLabel(type) {
2270
- const key = `components.formula.toolbar.operatorTypes.${type}`;
2271
- const translated = this.transloco.translate(key);
2272
- return translated && translated !== key
2273
- ? translated
2274
- : type.charAt(0).toUpperCase() + type.slice(1);
2275
- }
2276
- /** Translate a function category header, falling back to its display name */
2277
- categoryLabel(category) {
2278
- const display = category.displayName || String(category.name ?? '');
2279
- // Normalize to a slug so "Phase Gate", "PhaseGate" and "phase-gate" all match.
2280
- const slug = display.toLowerCase().replace(/[^a-z0-9]/g, '');
2281
- const key = `components.formula.toolbar.categories.${slug}`;
2282
- const translated = this.transloco.translate(key);
2283
- return translated && translated !== key ? translated : display;
2284
- }
2285
- /** Total item count for current tab */
2286
- itemCount = computed(() => {
2287
- switch (this.activeTab()) {
2288
- case 'functions':
2289
- return this.filteredCategories().reduce((sum, cat) => sum + cat.functions.length, 0);
2290
- case 'properties':
2291
- return this.filteredProperties().length;
2292
- case 'operators':
2293
- return this.filteredOperators().length;
2294
- default:
2295
- return 0;
2296
- }
2297
- }, ...(ngDevMode ? [{ debugName: "itemCount" }] : /* istanbul ignore next */ []));
2298
- // ============ COMPUTED LABELS ============
2299
- labelFunctions = computed(() => this.labels()?.functions ?? 'Functions', ...(ngDevMode ? [{ debugName: "labelFunctions" }] : /* istanbul ignore next */ []));
2300
- labelProperties = computed(() => this.labels()?.properties ?? 'Properties', ...(ngDevMode ? [{ debugName: "labelProperties" }] : /* istanbul ignore next */ []));
2301
- labelOperators = computed(() => this.labels()?.operators ?? 'Operators', ...(ngDevMode ? [{ debugName: "labelOperators" }] : /* istanbul ignore next */ []));
2302
- labelNoFunctions = computed(() => this.labels()?.noFunctionsFound ?? 'No functions found', ...(ngDevMode ? [{ debugName: "labelNoFunctions" }] : /* istanbul ignore next */ []));
2303
- labelNoProperties = computed(() => this.labels()?.noPropertiesAvailable ?? 'No properties available', ...(ngDevMode ? [{ debugName: "labelNoProperties" }] : /* istanbul ignore next */ []));
2304
- labelNoOperators = computed(() => this.labels()?.noOperatorsFound ?? 'No operators found', ...(ngDevMode ? [{ debugName: "labelNoOperators" }] : /* istanbul ignore next */ []));
2305
- // ============ METHODS ============
2306
- /** Get count for a specific tab (filtered when searching) */
2307
- getTabCount(tab) {
2308
- const query = this.searchQuery();
2309
- if (query) {
2310
- // When searching, show filtered count
2311
- switch (tab) {
2312
- case 'functions':
2313
- return this.filteredFunctionsCount();
2314
- case 'properties':
2315
- return this.filteredPropertiesCount();
2316
- case 'operators':
2317
- return this.filteredOperatorsCount();
2318
- default:
2319
- return 0;
2320
- }
2321
- }
2322
- else {
2323
- // When not searching, show total count
2324
- switch (tab) {
2325
- case 'functions':
2326
- return this.functionCategories().reduce((sum, cat) => sum + cat.functions.length, 0);
2327
- case 'properties':
2328
- return this.knownProperties().length;
2329
- case 'operators':
2330
- return this.operators().length;
2331
- default:
2332
- return 0;
2333
- }
2334
- }
2335
- }
2336
- /** Check if a tab has results when searching */
2337
- tabHasResults(tab) {
2338
- return this.getTabCount(tab) > 0;
2339
- }
2340
- /** Set active tab */
2341
- setActiveTab(tab) {
2342
- this.activeTab.set(tab);
2343
- this.onTabChange.emit(tab);
2344
- }
2345
- /** Emit block insert event */
2346
- insertBlock(block) {
2347
- this.onBlockInsert.emit(block);
2348
- }
2349
- /** Clear search */
2350
- clearSearch() {
2351
- this.searchQuery.set('');
2352
- }
2353
- /** Insert custom value */
2354
- insertCustomValue() {
2355
- const val = this.customValue().trim();
2356
- if (!val)
2357
- return;
2358
- const type = this.customValueType();
2359
- let literalValue;
2360
- if (type === 'number') {
2361
- literalValue = parseFloat(val);
2362
- }
2363
- else if (type === 'string') {
2364
- // Remove quotes for storage, keep the content
2365
- literalValue = val.slice(1, -1);
2366
- }
2367
- else {
2368
- // Treat as string, add quotes
2369
- literalValue = val;
2370
- }
2371
- const block = createLiteralBlock(literalValue);
2372
- // For strings, ensure the value includes quotes for display
2373
- if (type === 'string' || type === 'text') {
2374
- block.value = type === 'string' ? val : `"${val}"`;
2375
- }
2376
- this.onBlockInsert.emit(block);
2377
- this.clearCustomValue();
2378
- }
2379
- /** Clear custom value input */
2380
- clearCustomValue() {
2381
- this.customValue.set('');
2382
- }
2383
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaToolbar, deps: [], target: i0.ɵɵFactoryTarget.Component });
2384
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: FormulaToolbar, isStandalone: true, selector: "mt-formula-toolbar", inputs: { knownProperties: { classPropertyName: "knownProperties", publicName: "knownProperties", isSignal: true, isRequired: false, transformFunction: null }, propertiesTemplate: { classPropertyName: "propertiesTemplate", publicName: "propertiesTemplate", isSignal: true, isRequired: false, transformFunction: null }, functionCategories: { classPropertyName: "functionCategories", publicName: "functionCategories", isSignal: true, isRequired: false, transformFunction: null }, operators: { classPropertyName: "operators", publicName: "operators", isSignal: true, isRequired: false, transformFunction: null }, initialTab: { classPropertyName: "initialTab", publicName: "initialTab", isSignal: true, isRequired: false, transformFunction: null }, visibleTabs: { classPropertyName: "visibleTabs", publicName: "visibleTabs", isSignal: true, isRequired: false, transformFunction: null }, searchPlaceholder: { classPropertyName: "searchPlaceholder", publicName: "searchPlaceholder", isSignal: true, isRequired: false, transformFunction: null }, labels: { classPropertyName: "labels", publicName: "labels", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { onBlockInsert: "onBlockInsert", onTabChange: "onTabChange" }, queries: [{ propertyName: "projectedPropertiesTemplate", first: true, predicate: ["properties"], descendants: true, read: TemplateRef, isSignal: true }], ngImport: i0, template: "<div\r\n *transloco=\"let t; prefix: 'components.formula.toolbar'\"\r\n class=\"flex flex-col border-b border-slate-200 dark:border-slate-700\"\r\n [class.h-52]=\"activeTab() !== 'properties' || !resolvedPropertiesTemplate()\"\r\n>\r\n <!-- Top Bar: Search + Quick Insert -->\r\n <div\r\n class=\"flex items-center gap-2 border-b border-slate-200 px-3 py-2 dark:border-slate-700\"\r\n >\r\n <!-- Search Field -->\r\n <div class=\"relative flex-1\">\r\n <svg\r\n class=\"absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z\"\r\n />\r\n </svg>\r\n <input\r\n type=\"text\"\r\n class=\"w-full rounded-lg border border-slate-300 bg-white py-1.5 ps-9 pe-8 text-sm text-slate-700 placeholder:text-slate-400 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all duration-200 dark:border-slate-600 dark:bg-slate-900 dark:text-slate-200 dark:placeholder:text-slate-500\"\r\n [placeholder]=\"searchPlaceholder() || t('search')\"\r\n [(ngModel)]=\"searchQuery\"\r\n />\r\n @if (searchQuery()) {\r\n <button\r\n type=\"button\"\r\n class=\"absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-slate-400 hover:bg-slate-200 hover:text-slate-600 transition-all duration-200 dark:hover:bg-slate-700\"\r\n (click)=\"clearSearch()\"\r\n >\r\n <svg\r\n class=\"h-4 w-4\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 18L18 6M6 6l12 12\"\r\n />\r\n </svg>\r\n </button>\r\n }\r\n </div>\r\n\r\n <!-- Separator -->\r\n <div class=\"h-6 w-px bg-slate-200 dark:bg-slate-600\"></div>\r\n\r\n <!-- Quick Insert Input -->\r\n <div class=\"relative flex items-center gap-2\">\r\n <span\r\n class=\"text-sm font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide\"\r\n >{{ t(\"insertLabel\") }}:</span\r\n >\r\n <div class=\"relative\">\r\n <input\r\n #customValueInput\r\n type=\"text\"\r\n class=\"w-32 rounded-md border border-dashed border-slate-300 bg-slate-50 px-3 py-1.5 text-sm font-mono text-slate-700 placeholder:text-slate-400 focus:border-primary focus:bg-white focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all duration-200 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200 dark:placeholder:text-slate-500 dark:focus:bg-slate-900\"\r\n [placeholder]=\"t('customValuePlaceholder')\"\r\n [(ngModel)]=\"customValue\"\r\n (keydown.enter)=\"insertCustomValue()\"\r\n (keydown.escape)=\"clearCustomValue()\"\r\n />\r\n </div>\r\n\r\n <!-- Insert Button with Type Preview -->\r\n @if (customValue()) {\r\n <button\r\n type=\"button\"\r\n class=\"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-all duration-200 hover:shadow-sm active:scale-95\"\r\n [class]=\"customValueTypeClass()\"\r\n (click)=\"insertCustomValue()\"\r\n [title]=\"t('insertType', { type: customValueType() })\"\r\n >\r\n @switch (customValueType()) {\r\n @case (\"number\") {\r\n <svg\r\n class=\"h-3 w-3\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M7 20l4-16m2 16l4-16M6 9h14M4 15h14\"\r\n />\r\n </svg>\r\n }\r\n @case (\"string\") {\r\n <svg\r\n class=\"h-3 w-3\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z\"\r\n />\r\n </svg>\r\n }\r\n @default {\r\n <svg\r\n class=\"h-3 w-3\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M12 4.5v15m7.5-7.5h-15\"\r\n />\r\n </svg>\r\n }\r\n }\r\n <span class=\"max-w-16 truncate\">{{ customValuePreview() }}</span>\r\n </button>\r\n }\r\n </div>\r\n </div>\r\n\r\n <!-- Main Content Row -->\r\n <div class=\"flex flex-1 overflow-hidden\">\r\n <!-- Vertical Tabs -->\r\n <div\r\n class=\"flex w-44 flex-col border-e border-slate-200 dark:border-slate-700\"\r\n >\r\n @for (tab of resolvedTabOptions(); track tab.value) {\r\n <button\r\n type=\"button\"\r\n class=\"flex cursor-pointer items-center gap-2 px-3 py-2.5 text-start text-sm font-medium transition-all duration-200\"\r\n [class]=\"\r\n activeTab() === tab.value\r\n ? 'bg-white border-e-2 border-primary text-primary dark:bg-slate-900'\r\n : searchQuery() && !tabHasResults(tab.value)\r\n ? 'text-slate-300 dark:text-slate-600'\r\n : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800 dark:text-slate-300 dark:hover:bg-slate-700'\r\n \"\r\n (click)=\"setActiveTab(tab.value)\"\r\n >\r\n <!-- Tab Icons -->\r\n @switch (tab.value) {\r\n @case (\"functions\") {\r\n <svg\r\n class=\"h-5 w-5 shrink-0\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5\"\r\n />\r\n </svg>\r\n }\r\n @case (\"properties\") {\r\n <svg\r\n class=\"h-5 w-5 shrink-0\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z\"\r\n />\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 6h.008v.008H6V6z\"\r\n />\r\n </svg>\r\n }\r\n @case (\"operators\") {\r\n <svg\r\n class=\"h-5 w-5 shrink-0\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M15.75 15.75V18m-7.5-6.75h.008v.008H8.25v-.008zm0 2.25h.008v.008H8.25V13.5zm0 2.25h.008v.008H8.25v-.008zm0 2.25h.008v.008H8.25V18zm2.498-6.75h.007v.008h-.007v-.008zm0 2.25h.007v.008h-.007V13.5zm0 2.25h.007v.008h-.007v-.008zm0 2.25h.007v.008h-.007V18zm2.504-6.75h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V13.5zm0 2.25h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V18zm2.498-6.75h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V13.5zM8.25 6h7.5v2.25h-7.5V6zM12 2.25c-1.892 0-3.758.11-5.593.322C5.307 2.7 4.5 3.65 4.5 4.757V19.5a2.25 2.25 0 002.25 2.25h10.5a2.25 2.25 0 002.25-2.25V4.757c0-1.108-.806-2.057-1.907-2.185A48.507 48.507 0 0012 2.25z\"\r\n />\r\n </svg>\r\n }\r\n }\r\n <!-- Label (always visible) -->\r\n <span class=\"truncate whitespace-nowrap text-sm\">{{\r\n t(tab.value)\r\n }}</span>\r\n <!-- Count Badge -->\r\n @if (tab.value !== \"properties\" || !resolvedPropertiesTemplate()) {\r\n <span\r\n class=\"ms-auto rounded-full px-1.5 py-0.5 text-xs font-semibold\"\r\n [class]=\"\r\n activeTab() === tab.value\r\n ? 'bg-primary/10 text-primary'\r\n : 'bg-slate-200 text-slate-600 dark:bg-slate-600 dark:text-slate-300'\r\n \"\r\n >\r\n {{ getTabCount(tab.value) }}\r\n </span>\r\n }\r\n </button>\r\n }\r\n </div>\r\n\r\n <!-- Content Area -->\r\n <div class=\"flex flex-1 flex-col overflow-hidden\">\r\n <!-- Items Grid -->\r\n <div\r\n class=\"flex-1 p-2.5\"\r\n [class.overflow-y-auto]=\"\r\n activeTab() !== 'properties' || !resolvedPropertiesTemplate()\r\n \"\r\n >\r\n @switch (activeTab()) {\r\n @case (\"functions\") {\r\n @if (filteredCategories().length === 0) {\r\n <div\r\n class=\"flex h-full items-center justify-center text-sm text-slate-400 dark:text-slate-500\"\r\n >\r\n {{ labels()?.noFunctionsFound ?? t(\"noFunctionsFound\") }}\r\n </div>\r\n } @else {\r\n <div class=\"space-y-3\">\r\n @for (category of filteredCategories(); track category.name) {\r\n <div>\r\n <div class=\"mb-2 flex items-center gap-2\">\r\n <span\r\n class=\"text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400\"\r\n >\r\n {{ categoryLabel(category) }}\r\n </span>\r\n <span\r\n class=\"h-px flex-1 bg-slate-200/60 dark:bg-slate-700/60\"\r\n ></span>\r\n <span\r\n class=\"text-sm text-slate-400 dark:text-slate-500\"\r\n >{{ category.functions.length }}</span\r\n >\r\n </div>\r\n <div class=\"flex flex-wrap gap-1.5\">\r\n @for (fn of category.functions; track fn.name) {\r\n <mt-formula-toolbar-item\r\n type=\"function\"\r\n [value]=\"fn.name\"\r\n [description]=\"fn.description\"\r\n [signature]=\"fn.signature\"\r\n [template]=\"fn.template\"\r\n [templateCursorOffset]=\"fn.templateCursorOffset\"\r\n [returnType]=\"fn.returnType\"\r\n [parameters]=\"fn.parameters ?? []\"\r\n [examples]=\"fn.examples ?? []\"\r\n [hints]=\"fn.hints ?? []\"\r\n (onInsert)=\"insertBlock($event)\"\r\n />\r\n }\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n }\r\n }\r\n @case (\"properties\") {\r\n @if (resolvedPropertiesTemplate(); as template) {\r\n <ng-container\r\n [ngTemplateOutlet]=\"template\"\r\n [ngTemplateOutletContext]=\"propertiesTemplateContext\"\r\n />\r\n } @else {\r\n @if (filteredProperties().length === 0) {\r\n <div\r\n class=\"flex h-full items-center justify-center text-sm text-slate-400 dark:text-slate-500\"\r\n >\r\n {{\r\n labels()?.noPropertiesAvailable ??\r\n t(\"noPropertiesAvailable\")\r\n }}\r\n </div>\r\n } @else {\r\n <div class=\"flex flex-wrap gap-1.5\">\r\n @for (prop of filteredProperties(); track prop) {\r\n <mt-formula-toolbar-item\r\n type=\"property\"\r\n [value]=\"prop\"\r\n [description]=\"t('property') + ': ' + prop\"\r\n propertyType=\"current\"\r\n (onInsert)=\"insertBlock($event)\"\r\n />\r\n }\r\n </div>\r\n }\r\n }\r\n }\r\n @case (\"operators\") {\r\n @if (filteredOperators().length === 0) {\r\n <div\r\n class=\"flex h-full items-center justify-center text-sm text-slate-400 dark:text-slate-500\"\r\n >\r\n {{ labels()?.noOperatorsFound ?? t(\"noOperatorsFound\") }}\r\n </div>\r\n } @else {\r\n <div class=\"space-y-3\">\r\n @for (group of operatorGroups(); track group.type) {\r\n <div>\r\n <div class=\"mb-2 flex items-center gap-2\">\r\n <span\r\n class=\"text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400\"\r\n >\r\n {{ operatorTypeLabel(group.type) }}\r\n </span>\r\n <span\r\n class=\"h-px flex-1 bg-slate-200/60 dark:bg-slate-700/60\"\r\n ></span>\r\n </div>\r\n <div class=\"flex flex-wrap gap-1.5\">\r\n @for (op of group.operators; track op.symbol) {\r\n <mt-formula-toolbar-item\r\n type=\"operator\"\r\n [value]=\"op.symbol\"\r\n [description]=\"op.description\"\r\n (onInsert)=\"insertBlock($event)\"\r\n />\r\n }\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n }\r\n }\r\n }\r\n </div>\r\n </div>\r\n </div>\r\n</div>\r\n", dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1$2.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i2.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "ngmodule", type: TranslocoModule }, { kind: "directive", type: i3.TranslocoDirective, selector: "[transloco]", inputs: ["transloco", "translocoParams", "translocoScope", "translocoRead", "translocoPrefix", "translocoLang", "translocoLoadingTpl"] }, { kind: "component", type: FormulaToolbarItem, selector: "mt-formula-toolbar-item", inputs: ["type", "value", "display", "description", "signature", "examples", "template", "templateCursorOffset", "hints", "returnType", "parameters", "propertyType"], outputs: ["onInsert"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2385
- }
2386
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaToolbar, decorators: [{
2387
- type: Component,
2388
- args: [{ selector: 'mt-formula-toolbar', standalone: true, imports: [CommonModule, FormsModule, TranslocoModule, FormulaToolbarItem], changeDetection: ChangeDetectionStrategy.OnPush, template: "<div\r\n *transloco=\"let t; prefix: 'components.formula.toolbar'\"\r\n class=\"flex flex-col border-b border-slate-200 dark:border-slate-700\"\r\n [class.h-52]=\"activeTab() !== 'properties' || !resolvedPropertiesTemplate()\"\r\n>\r\n <!-- Top Bar: Search + Quick Insert -->\r\n <div\r\n class=\"flex items-center gap-2 border-b border-slate-200 px-3 py-2 dark:border-slate-700\"\r\n >\r\n <!-- Search Field -->\r\n <div class=\"relative flex-1\">\r\n <svg\r\n class=\"absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z\"\r\n />\r\n </svg>\r\n <input\r\n type=\"text\"\r\n class=\"w-full rounded-lg border border-slate-300 bg-white py-1.5 ps-9 pe-8 text-sm text-slate-700 placeholder:text-slate-400 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all duration-200 dark:border-slate-600 dark:bg-slate-900 dark:text-slate-200 dark:placeholder:text-slate-500\"\r\n [placeholder]=\"searchPlaceholder() || t('search')\"\r\n [(ngModel)]=\"searchQuery\"\r\n />\r\n @if (searchQuery()) {\r\n <button\r\n type=\"button\"\r\n class=\"absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-slate-400 hover:bg-slate-200 hover:text-slate-600 transition-all duration-200 dark:hover:bg-slate-700\"\r\n (click)=\"clearSearch()\"\r\n >\r\n <svg\r\n class=\"h-4 w-4\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 18L18 6M6 6l12 12\"\r\n />\r\n </svg>\r\n </button>\r\n }\r\n </div>\r\n\r\n <!-- Separator -->\r\n <div class=\"h-6 w-px bg-slate-200 dark:bg-slate-600\"></div>\r\n\r\n <!-- Quick Insert Input -->\r\n <div class=\"relative flex items-center gap-2\">\r\n <span\r\n class=\"text-sm font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide\"\r\n >{{ t(\"insertLabel\") }}:</span\r\n >\r\n <div class=\"relative\">\r\n <input\r\n #customValueInput\r\n type=\"text\"\r\n class=\"w-32 rounded-md border border-dashed border-slate-300 bg-slate-50 px-3 py-1.5 text-sm font-mono text-slate-700 placeholder:text-slate-400 focus:border-primary focus:bg-white focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all duration-200 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200 dark:placeholder:text-slate-500 dark:focus:bg-slate-900\"\r\n [placeholder]=\"t('customValuePlaceholder')\"\r\n [(ngModel)]=\"customValue\"\r\n (keydown.enter)=\"insertCustomValue()\"\r\n (keydown.escape)=\"clearCustomValue()\"\r\n />\r\n </div>\r\n\r\n <!-- Insert Button with Type Preview -->\r\n @if (customValue()) {\r\n <button\r\n type=\"button\"\r\n class=\"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-all duration-200 hover:shadow-sm active:scale-95\"\r\n [class]=\"customValueTypeClass()\"\r\n (click)=\"insertCustomValue()\"\r\n [title]=\"t('insertType', { type: customValueType() })\"\r\n >\r\n @switch (customValueType()) {\r\n @case (\"number\") {\r\n <svg\r\n class=\"h-3 w-3\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M7 20l4-16m2 16l4-16M6 9h14M4 15h14\"\r\n />\r\n </svg>\r\n }\r\n @case (\"string\") {\r\n <svg\r\n class=\"h-3 w-3\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z\"\r\n />\r\n </svg>\r\n }\r\n @default {\r\n <svg\r\n class=\"h-3 w-3\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M12 4.5v15m7.5-7.5h-15\"\r\n />\r\n </svg>\r\n }\r\n }\r\n <span class=\"max-w-16 truncate\">{{ customValuePreview() }}</span>\r\n </button>\r\n }\r\n </div>\r\n </div>\r\n\r\n <!-- Main Content Row -->\r\n <div class=\"flex flex-1 overflow-hidden\">\r\n <!-- Vertical Tabs -->\r\n <div\r\n class=\"flex w-44 flex-col border-e border-slate-200 dark:border-slate-700\"\r\n >\r\n @for (tab of resolvedTabOptions(); track tab.value) {\r\n <button\r\n type=\"button\"\r\n class=\"flex cursor-pointer items-center gap-2 px-3 py-2.5 text-start text-sm font-medium transition-all duration-200\"\r\n [class]=\"\r\n activeTab() === tab.value\r\n ? 'bg-white border-e-2 border-primary text-primary dark:bg-slate-900'\r\n : searchQuery() && !tabHasResults(tab.value)\r\n ? 'text-slate-300 dark:text-slate-600'\r\n : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800 dark:text-slate-300 dark:hover:bg-slate-700'\r\n \"\r\n (click)=\"setActiveTab(tab.value)\"\r\n >\r\n <!-- Tab Icons -->\r\n @switch (tab.value) {\r\n @case (\"functions\") {\r\n <svg\r\n class=\"h-5 w-5 shrink-0\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5\"\r\n />\r\n </svg>\r\n }\r\n @case (\"properties\") {\r\n <svg\r\n class=\"h-5 w-5 shrink-0\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z\"\r\n />\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 6h.008v.008H6V6z\"\r\n />\r\n </svg>\r\n }\r\n @case (\"operators\") {\r\n <svg\r\n class=\"h-5 w-5 shrink-0\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M15.75 15.75V18m-7.5-6.75h.008v.008H8.25v-.008zm0 2.25h.008v.008H8.25V13.5zm0 2.25h.008v.008H8.25v-.008zm0 2.25h.008v.008H8.25V18zm2.498-6.75h.007v.008h-.007v-.008zm0 2.25h.007v.008h-.007V13.5zm0 2.25h.007v.008h-.007v-.008zm0 2.25h.007v.008h-.007V18zm2.504-6.75h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V13.5zm0 2.25h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V18zm2.498-6.75h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V13.5zM8.25 6h7.5v2.25h-7.5V6zM12 2.25c-1.892 0-3.758.11-5.593.322C5.307 2.7 4.5 3.65 4.5 4.757V19.5a2.25 2.25 0 002.25 2.25h10.5a2.25 2.25 0 002.25-2.25V4.757c0-1.108-.806-2.057-1.907-2.185A48.507 48.507 0 0012 2.25z\"\r\n />\r\n </svg>\r\n }\r\n }\r\n <!-- Label (always visible) -->\r\n <span class=\"truncate whitespace-nowrap text-sm\">{{\r\n t(tab.value)\r\n }}</span>\r\n <!-- Count Badge -->\r\n @if (tab.value !== \"properties\" || !resolvedPropertiesTemplate()) {\r\n <span\r\n class=\"ms-auto rounded-full px-1.5 py-0.5 text-xs font-semibold\"\r\n [class]=\"\r\n activeTab() === tab.value\r\n ? 'bg-primary/10 text-primary'\r\n : 'bg-slate-200 text-slate-600 dark:bg-slate-600 dark:text-slate-300'\r\n \"\r\n >\r\n {{ getTabCount(tab.value) }}\r\n </span>\r\n }\r\n </button>\r\n }\r\n </div>\r\n\r\n <!-- Content Area -->\r\n <div class=\"flex flex-1 flex-col overflow-hidden\">\r\n <!-- Items Grid -->\r\n <div\r\n class=\"flex-1 p-2.5\"\r\n [class.overflow-y-auto]=\"\r\n activeTab() !== 'properties' || !resolvedPropertiesTemplate()\r\n \"\r\n >\r\n @switch (activeTab()) {\r\n @case (\"functions\") {\r\n @if (filteredCategories().length === 0) {\r\n <div\r\n class=\"flex h-full items-center justify-center text-sm text-slate-400 dark:text-slate-500\"\r\n >\r\n {{ labels()?.noFunctionsFound ?? t(\"noFunctionsFound\") }}\r\n </div>\r\n } @else {\r\n <div class=\"space-y-3\">\r\n @for (category of filteredCategories(); track category.name) {\r\n <div>\r\n <div class=\"mb-2 flex items-center gap-2\">\r\n <span\r\n class=\"text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400\"\r\n >\r\n {{ categoryLabel(category) }}\r\n </span>\r\n <span\r\n class=\"h-px flex-1 bg-slate-200/60 dark:bg-slate-700/60\"\r\n ></span>\r\n <span\r\n class=\"text-sm text-slate-400 dark:text-slate-500\"\r\n >{{ category.functions.length }}</span\r\n >\r\n </div>\r\n <div class=\"flex flex-wrap gap-1.5\">\r\n @for (fn of category.functions; track fn.name) {\r\n <mt-formula-toolbar-item\r\n type=\"function\"\r\n [value]=\"fn.name\"\r\n [description]=\"fn.description\"\r\n [signature]=\"fn.signature\"\r\n [template]=\"fn.template\"\r\n [templateCursorOffset]=\"fn.templateCursorOffset\"\r\n [returnType]=\"fn.returnType\"\r\n [parameters]=\"fn.parameters ?? []\"\r\n [examples]=\"fn.examples ?? []\"\r\n [hints]=\"fn.hints ?? []\"\r\n (onInsert)=\"insertBlock($event)\"\r\n />\r\n }\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n }\r\n }\r\n @case (\"properties\") {\r\n @if (resolvedPropertiesTemplate(); as template) {\r\n <ng-container\r\n [ngTemplateOutlet]=\"template\"\r\n [ngTemplateOutletContext]=\"propertiesTemplateContext\"\r\n />\r\n } @else {\r\n @if (filteredProperties().length === 0) {\r\n <div\r\n class=\"flex h-full items-center justify-center text-sm text-slate-400 dark:text-slate-500\"\r\n >\r\n {{\r\n labels()?.noPropertiesAvailable ??\r\n t(\"noPropertiesAvailable\")\r\n }}\r\n </div>\r\n } @else {\r\n <div class=\"flex flex-wrap gap-1.5\">\r\n @for (prop of filteredProperties(); track prop) {\r\n <mt-formula-toolbar-item\r\n type=\"property\"\r\n [value]=\"prop\"\r\n [description]=\"t('property') + ': ' + prop\"\r\n propertyType=\"current\"\r\n (onInsert)=\"insertBlock($event)\"\r\n />\r\n }\r\n </div>\r\n }\r\n }\r\n }\r\n @case (\"operators\") {\r\n @if (filteredOperators().length === 0) {\r\n <div\r\n class=\"flex h-full items-center justify-center text-sm text-slate-400 dark:text-slate-500\"\r\n >\r\n {{ labels()?.noOperatorsFound ?? t(\"noOperatorsFound\") }}\r\n </div>\r\n } @else {\r\n <div class=\"space-y-3\">\r\n @for (group of operatorGroups(); track group.type) {\r\n <div>\r\n <div class=\"mb-2 flex items-center gap-2\">\r\n <span\r\n class=\"text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400\"\r\n >\r\n {{ operatorTypeLabel(group.type) }}\r\n </span>\r\n <span\r\n class=\"h-px flex-1 bg-slate-200/60 dark:bg-slate-700/60\"\r\n ></span>\r\n </div>\r\n <div class=\"flex flex-wrap gap-1.5\">\r\n @for (op of group.operators; track op.symbol) {\r\n <mt-formula-toolbar-item\r\n type=\"operator\"\r\n [value]=\"op.symbol\"\r\n [description]=\"op.description\"\r\n (onInsert)=\"insertBlock($event)\"\r\n />\r\n }\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n }\r\n }\r\n }\r\n </div>\r\n </div>\r\n </div>\r\n</div>\r\n" }]
2389
- }], ctorParameters: () => [], propDecorators: { knownProperties: [{ type: i0.Input, args: [{ isSignal: true, alias: "knownProperties", required: false }] }], propertiesTemplate: [{ type: i0.Input, args: [{ isSignal: true, alias: "propertiesTemplate", required: false }] }], projectedPropertiesTemplate: [{ type: i0.ContentChild, args: ['properties', { ...{
2390
- read: TemplateRef,
2391
- }, isSignal: true }] }], functionCategories: [{ type: i0.Input, args: [{ isSignal: true, alias: "functionCategories", required: false }] }], operators: [{ type: i0.Input, args: [{ isSignal: true, alias: "operators", required: false }] }], initialTab: [{ type: i0.Input, args: [{ isSignal: true, alias: "initialTab", required: false }] }], visibleTabs: [{ type: i0.Input, args: [{ isSignal: true, alias: "visibleTabs", required: false }] }], searchPlaceholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "searchPlaceholder", required: false }] }], labels: [{ type: i0.Input, args: [{ isSignal: true, alias: "labels", required: false }] }], onBlockInsert: [{ type: i0.Output, args: ["onBlockInsert"] }], onTabChange: [{ type: i0.Output, args: ["onTabChange"] }] } });
2392
-
2393
- /**
2394
- * Formula Status Bar Component
2395
- * Displays validation status, complexity, and dependencies
2396
- *
2397
- * This is a PURE input/output component with NO service dependencies.
2398
- */
2399
- class FormulaStatusBar {
2400
- // ============ INPUTS ============
2401
- /** Validation result */
2402
- validation = input(null, ...(ngDevMode ? [{ debugName: "validation" }] : /* istanbul ignore next */ []));
2403
- /** Labels for i18n support */
2404
- labels = input({}, ...(ngDevMode ? [{ debugName: "labels" }] : /* istanbul ignore next */ []));
2405
- // ============ COMPUTED ============
2406
- /** Is formula valid */
2407
- isValid = computed(() => this.validation()?.isValid ?? true, ...(ngDevMode ? [{ debugName: "isValid" }] : /* istanbul ignore next */ []));
2408
- /** Complexity score */
2409
- complexity = computed(() => this.validation()?.complexity ?? 0, ...(ngDevMode ? [{ debugName: "complexity" }] : /* istanbul ignore next */ []));
2410
- /** Dependencies list */
2411
- dependencies = computed(() => this.validation()?.dependencies ?? [], ...(ngDevMode ? [{ debugName: "dependencies" }] : /* istanbul ignore next */ []));
2412
- /** Dependencies as text */
2413
- dependenciesText = computed(() => {
2414
- const deps = this.dependencies();
2415
- if (deps.length <= 3) {
2416
- return deps.join(', ');
2417
- }
2418
- return `${deps.slice(0, 3).join(', ')} +${deps.length - 3}`;
2419
- }, ...(ngDevMode ? [{ debugName: "dependenciesText" }] : /* istanbul ignore next */ []));
2420
- /** First error */
2421
- firstError = computed(() => this.validation()?.errors?.[0] ?? null, ...(ngDevMode ? [{ debugName: "firstError" }] : /* istanbul ignore next */ []));
2422
- /** Complexity CSS class */
2423
- complexityClass = computed(() => {
2424
- const c = this.complexity();
2425
- if (c <= 10)
2426
- return 'text-emerald-600 dark:text-emerald-400';
2427
- if (c <= 25)
2428
- return 'text-amber-600 dark:text-amber-400';
2429
- return 'text-rose-600 dark:text-rose-400';
2430
- }, ...(ngDevMode ? [{ debugName: "complexityClass" }] : /* istanbul ignore next */ []));
2431
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaStatusBar, deps: [], target: i0.ɵɵFactoryTarget.Component });
2432
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: FormulaStatusBar, isStandalone: true, selector: "mt-formula-status-bar", inputs: { validation: { classPropertyName: "validation", publicName: "validation", isSignal: true, isRequired: false, transformFunction: null }, labels: { classPropertyName: "labels", publicName: "labels", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: "<div\r\n *transloco=\"let t; prefix: 'components.formula.statusBar'\"\r\n class=\"flex items-center gap-4 border-t border-slate-200 px-4 py-2 text-sm dark:border-slate-700\"\r\n>\r\n <!-- Validation Status -->\r\n <div class=\"flex items-center gap-1.5\">\r\n @if (isValid()) {\r\n <span\r\n class=\"flex h-5 w-5 items-center justify-center rounded-full bg-emerald-100 text-emerald-600 dark:bg-emerald-900 dark:text-emerald-400\"\r\n >\r\n <svg\r\n class=\"h-3.5 w-3.5\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2.5\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M5 13l4 4L19 7\"\r\n />\r\n </svg>\r\n </span>\r\n <span class=\"font-medium text-emerald-600 dark:text-emerald-400\">\r\n {{ labels()?.valid ?? t(\"valid\") }}\r\n </span>\r\n } @else {\r\n <span\r\n class=\"flex h-5 w-5 items-center justify-center rounded-full bg-rose-100 text-rose-600 dark:bg-rose-900 dark:text-rose-400\"\r\n >\r\n <svg\r\n class=\"h-3.5 w-3.5\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2.5\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 18L18 6M6 6l12 12\"\r\n />\r\n </svg>\r\n </span>\r\n <span class=\"font-medium text-rose-600 dark:text-rose-400\">\r\n {{ labels()?.invalid ?? t(\"invalid\") }}\r\n </span>\r\n }\r\n </div>\r\n\r\n <!-- Separator -->\r\n <div class=\"h-4 w-px bg-slate-300 dark:bg-slate-600\"></div>\r\n\r\n <!-- Complexity -->\r\n <div class=\"flex items-center gap-1.5 text-slate-500 dark:text-slate-400\">\r\n <svg class=\"h-4 w-4\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n stroke-width=\"2\"\r\n d=\"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z\"\r\n />\r\n </svg>\r\n <span>{{ labels()?.complexity ?? t(\"complexity\") }}:</span>\r\n <span class=\"font-medium\" [class]=\"complexityClass()\">\r\n {{ complexity() }}\r\n </span>\r\n </div>\r\n\r\n <!-- Dependencies -->\r\n @if (dependencies().length > 0) {\r\n <div class=\"h-4 w-px bg-slate-300 dark:bg-slate-600\"></div>\r\n <div class=\"flex items-center gap-1.5 text-slate-500 dark:text-slate-400\">\r\n <svg\r\n class=\"h-4 w-4\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n stroke-width=\"2\"\r\n d=\"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1\"\r\n />\r\n </svg>\r\n <span>{{ labels()?.dependencies ?? t(\"dependencies\") }}:</span>\r\n <span class=\"font-medium text-slate-700 dark:text-slate-300\">\r\n {{ dependenciesText() }}\r\n </span>\r\n </div>\r\n }\r\n\r\n <!-- Error message (if any) -->\r\n @if (firstError(); as error) {\r\n <div\r\n class=\"ms-auto flex items-center gap-1.5 text-rose-600 dark:text-rose-400\"\r\n >\r\n <svg\r\n class=\"h-4 w-4\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n stroke-width=\"2\"\r\n d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z\"\r\n />\r\n </svg>\r\n <span class=\"text-xs\">{{ error.message }}</span>\r\n <span class=\"text-xs opacity-60\"\r\n >({{ error.line }}:{{ error.column }})</span\r\n >\r\n </div>\r\n }\r\n</div>\r\n", dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: TranslocoModule }, { kind: "directive", type: i3.TranslocoDirective, selector: "[transloco]", inputs: ["transloco", "translocoParams", "translocoScope", "translocoRead", "translocoPrefix", "translocoLang", "translocoLoadingTpl"] }] });
2433
- }
2434
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FormulaStatusBar, decorators: [{
2435
- type: Component,
2436
- args: [{ selector: 'mt-formula-status-bar', standalone: true, imports: [CommonModule, TranslocoModule], template: "<div\r\n *transloco=\"let t; prefix: 'components.formula.statusBar'\"\r\n class=\"flex items-center gap-4 border-t border-slate-200 px-4 py-2 text-sm dark:border-slate-700\"\r\n>\r\n <!-- Validation Status -->\r\n <div class=\"flex items-center gap-1.5\">\r\n @if (isValid()) {\r\n <span\r\n class=\"flex h-5 w-5 items-center justify-center rounded-full bg-emerald-100 text-emerald-600 dark:bg-emerald-900 dark:text-emerald-400\"\r\n >\r\n <svg\r\n class=\"h-3.5 w-3.5\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2.5\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M5 13l4 4L19 7\"\r\n />\r\n </svg>\r\n </span>\r\n <span class=\"font-medium text-emerald-600 dark:text-emerald-400\">\r\n {{ labels()?.valid ?? t(\"valid\") }}\r\n </span>\r\n } @else {\r\n <span\r\n class=\"flex h-5 w-5 items-center justify-center rounded-full bg-rose-100 text-rose-600 dark:bg-rose-900 dark:text-rose-400\"\r\n >\r\n <svg\r\n class=\"h-3.5 w-3.5\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n stroke-width=\"2.5\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n d=\"M6 18L18 6M6 6l12 12\"\r\n />\r\n </svg>\r\n </span>\r\n <span class=\"font-medium text-rose-600 dark:text-rose-400\">\r\n {{ labels()?.invalid ?? t(\"invalid\") }}\r\n </span>\r\n }\r\n </div>\r\n\r\n <!-- Separator -->\r\n <div class=\"h-4 w-px bg-slate-300 dark:bg-slate-600\"></div>\r\n\r\n <!-- Complexity -->\r\n <div class=\"flex items-center gap-1.5 text-slate-500 dark:text-slate-400\">\r\n <svg class=\"h-4 w-4\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n stroke-width=\"2\"\r\n d=\"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z\"\r\n />\r\n </svg>\r\n <span>{{ labels()?.complexity ?? t(\"complexity\") }}:</span>\r\n <span class=\"font-medium\" [class]=\"complexityClass()\">\r\n {{ complexity() }}\r\n </span>\r\n </div>\r\n\r\n <!-- Dependencies -->\r\n @if (dependencies().length > 0) {\r\n <div class=\"h-4 w-px bg-slate-300 dark:bg-slate-600\"></div>\r\n <div class=\"flex items-center gap-1.5 text-slate-500 dark:text-slate-400\">\r\n <svg\r\n class=\"h-4 w-4\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n stroke-width=\"2\"\r\n d=\"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1\"\r\n />\r\n </svg>\r\n <span>{{ labels()?.dependencies ?? t(\"dependencies\") }}:</span>\r\n <span class=\"font-medium text-slate-700 dark:text-slate-300\">\r\n {{ dependenciesText() }}\r\n </span>\r\n </div>\r\n }\r\n\r\n <!-- Error message (if any) -->\r\n @if (firstError(); as error) {\r\n <div\r\n class=\"ms-auto flex items-center gap-1.5 text-rose-600 dark:text-rose-400\"\r\n >\r\n <svg\r\n class=\"h-4 w-4\"\r\n fill=\"none\"\r\n viewBox=\"0 0 24 24\"\r\n stroke=\"currentColor\"\r\n >\r\n <path\r\n stroke-linecap=\"round\"\r\n stroke-linejoin=\"round\"\r\n stroke-width=\"2\"\r\n d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z\"\r\n />\r\n </svg>\r\n <span class=\"text-xs\">{{ error.message }}</span>\r\n <span class=\"text-xs opacity-60\"\r\n >({{ error.line }}:{{ error.column }})</span\r\n >\r\n </div>\r\n }\r\n</div>\r\n" }]
2437
- }], propDecorators: { validation: [{ type: i0.Input, args: [{ isSignal: true, alias: "validation", required: false }] }], labels: [{ type: i0.Input, args: [{ isSignal: true, alias: "labels", required: false }] }] } });
2438
-
2439
- const CONDITION_FUNCTION_CATEGORIES = [
2440
- {
2441
- name: 'Logic',
2442
- displayName: 'Field Visibility',
2443
- functions: [
2444
- {
2445
- name: 'SHOW_IF',
2446
- category: 'Logic',
2447
- description: 'Show this field when condition is true',
2448
- signature: 'SHOW_IF(condition)',
2449
- parameters: [
2450
- {
2451
- name: 'condition',
2452
- type: 'boolean',
2453
- description: 'When true, field is visible',
2454
- required: true,
2455
- },
2456
- ],
2457
- returnType: 'boolean',
2458
- examples: ['SHOW_IF(@Status == "Active")'],
2459
- },
2460
- {
2461
- name: 'HIDE_IF',
2462
- category: 'Logic',
2463
- description: 'Hide this field when condition is true',
2464
- signature: 'HIDE_IF(condition)',
2465
- parameters: [
2466
- {
2467
- name: 'condition',
2468
- type: 'boolean',
2469
- description: 'When true, field is hidden',
2470
- required: true,
2471
- },
2472
- ],
2473
- returnType: 'boolean',
2474
- examples: ['HIDE_IF(@Status == "Closed")'],
2475
- },
2476
- {
2477
- name: 'DISABLE_IF',
2478
- category: 'Logic',
2479
- description: 'Disable this field when condition is true',
2480
- signature: 'DISABLE_IF(condition)',
2481
- parameters: [
2482
- {
2483
- name: 'condition',
2484
- type: 'boolean',
2485
- description: 'When true, field is disabled',
2486
- required: true,
2487
- },
2488
- ],
2489
- returnType: 'boolean',
2490
- examples: ['DISABLE_IF(@Status == "Approved")'],
2491
- },
2492
- {
2493
- name: 'ENABLE_IF',
2494
- category: 'Logic',
2495
- description: 'Enable this field when condition is true',
2496
- signature: 'ENABLE_IF(condition)',
2497
- parameters: [
2498
- {
2499
- name: 'condition',
2500
- type: 'boolean',
2501
- description: 'When true, field is enabled',
2502
- required: true,
2503
- },
2504
- ],
2505
- returnType: 'boolean',
2506
- examples: ['ENABLE_IF(@Status == "Draft")'],
2507
- },
2508
- ],
2509
- },
2510
- {
2511
- name: 'Aggregation',
2512
- displayName: 'Logic Helpers',
2513
- functions: [
2514
- {
2515
- name: 'AND',
2516
- category: 'Aggregation',
2517
- description: 'Returns true if all conditions are true',
2518
- signature: 'AND(condition1, condition2)',
2519
- parameters: [
2520
- {
2521
- name: 'condition1',
2522
- type: 'boolean',
2523
- description: 'First condition',
2524
- required: true,
2525
- },
2526
- {
2527
- name: 'condition2',
2528
- type: 'boolean',
2529
- description: 'Second condition',
2530
- required: true,
2531
- },
2532
- ],
2533
- returnType: 'boolean',
2534
- examples: ['AND(@Status == "Active", @Priority > 0)'],
2535
- },
2536
- {
2537
- name: 'OR',
2538
- category: 'Aggregation',
2539
- description: 'Returns true if any condition is true',
2540
- signature: 'OR(condition1, condition2)',
2541
- parameters: [
2542
- {
2543
- name: 'condition1',
2544
- type: 'boolean',
2545
- description: 'First condition',
2546
- required: true,
2547
- },
2548
- {
2549
- name: 'condition2',
2550
- type: 'boolean',
2551
- description: 'Second condition',
2552
- required: true,
2553
- },
2554
- ],
2555
- returnType: 'boolean',
2556
- examples: ['OR(@Status == "Active", @Status == "Pending")'],
2557
- },
2558
- {
2559
- name: 'NOT',
2560
- category: 'Aggregation',
2561
- description: 'Returns the opposite of the condition',
2562
- signature: 'NOT(condition)',
2563
- parameters: [
2564
- {
2565
- name: 'condition',
2566
- type: 'boolean',
2567
- description: 'Condition to negate',
2568
- required: true,
2569
- },
2570
- ],
2571
- returnType: 'boolean',
2572
- examples: ['NOT(@IsCompleted)'],
2573
- },
2574
- {
2575
- name: 'ISNULL',
2576
- category: 'Aggregation',
2577
- description: 'Returns true if value is null or empty',
2578
- signature: 'ISNULL(value)',
2579
- parameters: [
2580
- {
2581
- name: 'value',
2582
- type: 'any',
2583
- description: 'Value to check',
2584
- required: true,
2585
- },
2586
- ],
2587
- returnType: 'boolean',
2588
- examples: ['ISNULL(@Description)'],
2589
- },
2590
- {
2591
- name: 'CONTAINS',
2592
- category: 'Aggregation',
2593
- description: 'Returns true if text contains the search string',
2594
- signature: 'CONTAINS(text, search)',
2595
- parameters: [
2596
- {
2597
- name: 'text',
2598
- type: 'string',
2599
- description: 'Text to search in',
2600
- required: true,
2601
- },
2602
- {
2603
- name: 'search',
2604
- type: 'string',
2605
- description: 'String to search for',
2606
- required: true,
2607
- },
2608
- ],
2609
- returnType: 'boolean',
2610
- examples: ['CONTAINS(@Name, "Project")'],
2611
- },
2612
- ],
2613
- },
2614
- ];
2615
- const CONDITION_OPERATORS = [
2616
- {
2617
- symbol: '==',
2618
- name: 'Equal',
2619
- type: 'comparison',
2620
- description: 'Equal to',
2621
- precedence: 3,
2622
- },
2623
- {
2624
- symbol: '!=',
2625
- name: 'Not Equal',
2626
- type: 'comparison',
2627
- description: 'Not equal to',
2628
- precedence: 3,
2629
- },
2630
- {
2631
- symbol: '>',
2632
- name: 'Greater Than',
2633
- type: 'comparison',
2634
- description: 'Greater than',
2635
- precedence: 4,
2636
- },
2637
- {
2638
- symbol: '<',
2639
- name: 'Less Than',
2640
- type: 'comparison',
2641
- description: 'Less than',
2642
- precedence: 4,
2643
- },
2644
- {
2645
- symbol: '>=',
2646
- name: 'Greater or Equal',
2647
- type: 'comparison',
2648
- description: 'Greater than or equal',
2649
- precedence: 4,
2650
- },
2651
- {
2652
- symbol: '<=',
2653
- name: 'Less or Equal',
2654
- type: 'comparison',
2655
- description: 'Less than or equal',
2656
- precedence: 4,
2657
- },
2658
- {
2659
- symbol: '&&',
2660
- name: 'And',
2661
- type: 'logical',
2662
- description: 'Logical AND',
2663
- precedence: 2,
2664
- },
2665
- {
2666
- symbol: '||',
2667
- name: 'Or',
2668
- type: 'logical',
2669
- description: 'Logical OR',
2670
- precedence: 1,
2671
- },
2672
- ];
2673
- const VALIDATION_FUNCTION_CATEGORIES = [
2674
- {
2675
- name: 'Validation',
2676
- displayName: 'Validation',
2677
- functions: [
2678
- {
2679
- name: 'REQUIRED',
2680
- category: 'Validation',
2681
- description: 'Returns true when value is not empty',
2682
- signature: 'REQUIRED(value)',
2683
- parameters: [
2684
- {
2685
- name: 'value',
2686
- type: 'any',
2687
- description: 'Value to check',
2688
- required: true,
2689
- },
2690
- ],
2691
- returnType: 'boolean',
2692
- examples: ['REQUIRED(@Email)'],
2693
- },
2694
- {
2695
- name: 'ISNULL',
2696
- category: 'Validation',
2697
- description: 'Returns true if value is null or empty',
2698
- signature: 'ISNULL(value)',
2699
- parameters: [
2700
- {
2701
- name: 'value',
2702
- type: 'any',
2703
- description: 'Value to check',
2704
- required: true,
2705
- },
2706
- ],
2707
- returnType: 'boolean',
2708
- examples: ['ISNULL(@Phone)'],
2709
- },
2710
- {
2711
- name: 'MIN_LENGTH',
2712
- category: 'Validation',
2713
- description: 'Returns true if value length is at least min',
2714
- signature: 'MIN_LENGTH(value, min)',
2715
- parameters: [
2716
- {
2717
- name: 'value',
2718
- type: 'string',
2719
- description: 'Value to check',
2720
- required: true,
2721
- },
2722
- {
2723
- name: 'min',
2724
- type: 'number',
2725
- description: 'Minimum length',
2726
- required: true,
2727
- },
2728
- ],
2729
- returnType: 'boolean',
2730
- examples: ['MIN_LENGTH(@Password, 8)'],
2731
- },
2732
- {
2733
- name: 'MAX_LENGTH',
2734
- category: 'Validation',
2735
- description: 'Returns true if value length is at most max',
2736
- signature: 'MAX_LENGTH(value, max)',
2737
- parameters: [
2738
- {
2739
- name: 'value',
2740
- type: 'string',
2741
- description: 'Value to check',
2742
- required: true,
2743
- },
2744
- {
2745
- name: 'max',
2746
- type: 'number',
2747
- description: 'Maximum length',
2748
- required: true,
2749
- },
2750
- ],
2751
- returnType: 'boolean',
2752
- examples: ['MAX_LENGTH(@Title, 120)'],
2753
- },
2754
- {
2755
- name: 'REGEX',
2756
- category: 'Validation',
2757
- description: 'Returns true if value matches regex pattern',
2758
- signature: 'REGEX(value, pattern)',
2759
- parameters: [
2760
- {
2761
- name: 'value',
2762
- type: 'string',
2763
- description: 'Value to check',
2764
- required: true,
2765
- },
2766
- {
2767
- name: 'pattern',
2768
- type: 'string',
2769
- description: 'Regex pattern',
2770
- required: true,
2771
- },
2772
- ],
2773
- returnType: 'boolean',
2774
- examples: ['REGEX(@Email, "^[^@]+@[^@]+\\.[^@]+$")'],
2775
- },
2776
- {
2777
- name: 'BEFORE',
2778
- category: 'Validation',
2779
- description: 'Returns true if date is before reference date',
2780
- signature: 'BEFORE(date, reference)',
2781
- parameters: [
2782
- {
2783
- name: 'date',
2784
- type: 'date',
2785
- description: 'Date to check',
2786
- required: true,
2787
- },
2788
- {
2789
- name: 'reference',
2790
- type: 'date',
2791
- description: 'Reference date',
2792
- required: true,
2793
- },
2794
- ],
2795
- returnType: 'boolean',
2796
- examples: ['BEFORE(@EndDate, @StartDate)'],
2797
- },
2798
- {
2799
- name: 'AFTER',
2800
- category: 'Validation',
2801
- description: 'Returns true if date is after reference date',
2802
- signature: 'AFTER(date, reference)',
2803
- parameters: [
2804
- {
2805
- name: 'date',
2806
- type: 'date',
2807
- description: 'Date to check',
2808
- required: true,
2809
- },
2810
- {
2811
- name: 'reference',
2812
- type: 'date',
2813
- description: 'Reference date',
2814
- required: true,
2815
- },
2816
- ],
2817
- returnType: 'boolean',
2818
- examples: ['AFTER(@StartDate, @EndDate)'],
2819
- },
2820
- ],
2821
- },
2822
- {
2823
- name: 'Logic',
2824
- displayName: 'Logic Helpers',
2825
- functions: [
2826
- {
2827
- name: 'AND',
2828
- category: 'Logic',
2829
- description: 'Returns true if all conditions are true',
2830
- signature: 'AND(condition1, condition2)',
2831
- parameters: [
2832
- {
2833
- name: 'condition1',
2834
- type: 'boolean',
2835
- description: 'First condition',
2836
- required: true,
2837
- },
2838
- {
2839
- name: 'condition2',
2840
- type: 'boolean',
2841
- description: 'Second condition',
2842
- required: true,
2843
- },
2844
- ],
2845
- returnType: 'boolean',
2846
- examples: ['AND(REQUIRED(@Email), REGEX(@Email, "^.+@.+$"))'],
2847
- },
2848
- {
2849
- name: 'OR',
2850
- category: 'Logic',
2851
- description: 'Returns true if any condition is true',
2852
- signature: 'OR(condition1, condition2)',
2853
- parameters: [
2854
- {
2855
- name: 'condition1',
2856
- type: 'boolean',
2857
- description: 'First condition',
2858
- required: true,
2859
- },
2860
- {
2861
- name: 'condition2',
2862
- type: 'boolean',
2863
- description: 'Second condition',
2864
- required: true,
2865
- },
2866
- ],
2867
- returnType: 'boolean',
2868
- examples: ['OR(ISNULL(@Phone), REGEX(@Phone, "^\\+?[0-9]+$"))'],
2869
- },
2870
- {
2871
- name: 'NOT',
2872
- category: 'Logic',
2873
- description: 'Returns the opposite of a condition',
2874
- signature: 'NOT(condition)',
2875
- parameters: [
2876
- {
2877
- name: 'condition',
2878
- type: 'boolean',
2879
- description: 'Condition to negate',
2880
- required: true,
2881
- },
2882
- ],
2883
- returnType: 'boolean',
2884
- examples: ['NOT(ISNULL(@Password))'],
2885
- },
2886
- ],
2887
- },
2888
- ];
2889
- const VALIDATION_OPERATORS = [
2890
- {
2891
- symbol: '+',
2892
- name: 'Add',
2893
- type: 'arithmetic',
2894
- description: 'Addition',
2895
- precedence: 4,
2896
- },
2897
- {
2898
- symbol: '-',
2899
- name: 'Subtract',
2900
- type: 'arithmetic',
2901
- description: 'Subtraction',
2902
- precedence: 4,
2903
- },
2904
- {
2905
- symbol: '*',
2906
- name: 'Multiply',
2907
- type: 'arithmetic',
2908
- description: 'Multiplication',
2909
- precedence: 5,
2910
- },
2911
- {
2912
- symbol: '/',
2913
- name: 'Divide',
2914
- type: 'arithmetic',
2915
- description: 'Division',
2916
- precedence: 5,
2917
- },
2918
- {
2919
- symbol: '==',
2920
- name: 'Equal',
2921
- type: 'comparison',
2922
- description: 'Equal to',
2923
- precedence: 3,
2924
- },
2925
- {
2926
- symbol: '!=',
2927
- name: 'Not Equal',
2928
- type: 'comparison',
2929
- description: 'Not equal to',
2930
- precedence: 3,
2931
- },
2932
- {
2933
- symbol: '>',
2934
- name: 'Greater Than',
2935
- type: 'comparison',
2936
- description: 'Greater than',
2937
- precedence: 3,
2938
- },
2939
- {
2940
- symbol: '<',
2941
- name: 'Less Than',
2942
- type: 'comparison',
2943
- description: 'Less than',
2944
- precedence: 3,
2945
- },
2946
- {
2947
- symbol: '>=',
2948
- name: 'Greater or Equal',
2949
- type: 'comparison',
2950
- description: 'Greater than or equal',
2951
- precedence: 3,
2952
- },
2953
- {
2954
- symbol: '<=',
2955
- name: 'Less or Equal',
2956
- type: 'comparison',
2957
- description: 'Less than or equal',
2958
- precedence: 3,
2959
- },
2960
- {
2961
- symbol: '&&',
2962
- name: 'And',
2963
- type: 'logical',
2964
- description: 'Logical AND',
2965
- precedence: 2,
2966
- },
2967
- {
2968
- symbol: '||',
2969
- name: 'Or',
2970
- type: 'logical',
2971
- description: 'Logical OR',
2972
- precedence: 1,
2973
- },
2974
- ];
2975
- const CONDITION_RUNTIME_CATALOG = {
2976
- domain: 'condition',
2977
- functions: CONDITION_FUNCTION_CATEGORIES,
2978
- operators: CONDITION_OPERATORS,
2979
- };
2980
- const VALIDATION_RUNTIME_CATALOG = {
2981
- domain: 'validation',
2982
- functions: VALIDATION_FUNCTION_CATEGORIES,
2983
- operators: VALIDATION_OPERATORS,
2984
- };
2985
-
2986
- const CONDITION_WRAPPER_NAMES = new Set([
2987
- 'show',
2988
- 'hide',
2989
- 'enable',
2990
- 'disable',
2991
- ]);
2992
- const PROPERTY_PREFIXES = ['@', '*.', '$.'];
2993
- class FormulaParser {
2994
- tokens;
2995
- current = 0;
2996
- dependencies = new Set();
2997
- constructor(tokens) {
2998
- this.tokens = tokens;
2999
- }
3000
- parse() {
3001
- const ast = this.expression();
3002
- this.consume('eof', 'Unexpected tokens after formula end');
3003
- const topLevelWrapper = ast.type === 'call' ? normalizeWrapperAction(ast.name) : null;
3004
- return {
3005
- ast,
3006
- dependencies: Array.from(this.dependencies),
3007
- topLevelWrapper,
3008
- };
3009
- }
3010
- expression() {
3011
- return this.logicalOr();
3012
- }
3013
- logicalOr() {
3014
- let expr = this.logicalAnd();
3015
- while (this.matchOperator('||')) {
3016
- const operator = this.previousOperator();
3017
- const right = this.logicalAnd();
3018
- expr = { type: 'binary', operator, left: expr, right };
3019
- }
3020
- return expr;
3021
- }
3022
- logicalAnd() {
3023
- let expr = this.equality();
3024
- while (this.matchOperator('&&')) {
3025
- const operator = this.previousOperator();
3026
- const right = this.equality();
3027
- expr = { type: 'binary', operator, left: expr, right };
3028
- }
3029
- return expr;
3030
- }
3031
- equality() {
3032
- let expr = this.comparison();
3033
- while (this.matchOperator('==', '!=')) {
3034
- const operator = this.previousOperator();
3035
- const right = this.comparison();
3036
- expr = { type: 'binary', operator, left: expr, right };
3037
- }
3038
- return expr;
3039
- }
3040
- comparison() {
3041
- let expr = this.addition();
3042
- while (this.matchOperator('>', '>=', '<', '<=')) {
3043
- const operator = this.previousOperator();
3044
- const right = this.addition();
3045
- expr = { type: 'binary', operator, left: expr, right };
3046
- }
3047
- return expr;
3048
- }
3049
- addition() {
3050
- let expr = this.multiplication();
3051
- while (this.matchOperator('+', '-')) {
3052
- const operator = this.previousOperator();
3053
- const right = this.multiplication();
3054
- expr = { type: 'binary', operator, left: expr, right };
3055
- }
3056
- return expr;
3057
- }
3058
- multiplication() {
3059
- let expr = this.unary();
3060
- while (this.matchOperator('*', '/')) {
3061
- const operator = this.previousOperator();
3062
- const right = this.unary();
3063
- expr = { type: 'binary', operator, left: expr, right };
3064
- }
3065
- return expr;
3066
- }
3067
- unary() {
3068
- if (this.matchOperator('!', '-')) {
3069
- const operator = this.previousOperator();
3070
- const right = this.unary();
3071
- return { type: 'unary', operator, right };
3072
- }
3073
- return this.primary();
3074
- }
3075
- primary() {
3076
- if (this.match('literal')) {
3077
- return { type: 'literal', value: this.previous().value };
3078
- }
3079
- if (this.match('property')) {
3080
- const token = this.previousProperty();
3081
- this.dependencies.add(token.value);
3082
- return { type: 'property', key: token.value, raw: token.raw };
3083
- }
3084
- if (this.match('identifier')) {
3085
- const name = this.previous().value;
3086
- if (!this.match('lparen')) {
3087
- throw new Error(`Expected "(" after function "${name}"`);
3088
- }
3089
- const args = [];
3090
- if (!this.check('rparen')) {
3091
- do {
3092
- args.push(this.expression());
3093
- } while (this.match('comma'));
3094
- }
3095
- this.consume('rparen', `Expected ")" after function "${name}"`);
3096
- return { type: 'call', name, args };
3097
- }
3098
- if (this.match('lparen')) {
3099
- const expr = this.expression();
3100
- this.consume('rparen', 'Expected ")" after expression');
3101
- return expr;
3102
- }
3103
- throw new Error('Unexpected token while parsing formula');
3104
- }
3105
- previous() {
3106
- return this.tokens[this.current - 1];
3107
- }
3108
- previousProperty() {
3109
- return this.tokens[this.current - 1];
3110
- }
3111
- previousOperator() {
3112
- return this.tokens[this.current - 1].value;
3113
- }
3114
- consume(type, message) {
3115
- if (this.check(type)) {
3116
- this.advance();
3117
- return;
3118
- }
3119
- throw new Error(message);
3120
- }
3121
- match(type) {
3122
- if (!this.check(type))
3123
- return false;
3124
- this.advance();
3125
- return true;
3126
- }
3127
- matchOperator(...operators) {
3128
- if (!this.check('operator'))
3129
- return false;
3130
- const token = this.peek();
3131
- if (!operators.includes(token.value))
3132
- return false;
3133
- this.advance();
3134
- return true;
3135
- }
3136
- check(type) {
3137
- if (this.isAtEnd())
3138
- return type === 'eof';
3139
- return this.peek().type === type;
3140
- }
3141
- advance() {
3142
- if (!this.isAtEnd())
3143
- this.current++;
3144
- return this.tokens[this.current - 1];
3145
- }
3146
- isAtEnd() {
3147
- return this.peek().type === 'eof';
3148
- }
3149
- peek() {
3150
- return this.tokens[this.current];
3151
- }
3152
- }
3153
- class FormulaRuntimeEngine {
3154
- compiledCache = new Map();
3155
- functionRegistry;
3156
- constructor(customFunctions) {
3157
- this.functionRegistry = {
3158
- ...buildDefaultFunctionRegistry(),
3159
- ...(customFunctions ?? {}),
3160
- };
3161
- }
3162
- evaluateCondition(config, context) {
3163
- let compiled;
3164
- try {
3165
- compiled = this.getCompiledFormula(config.formulaTokens);
3166
- }
3167
- catch (error) {
3168
- return {
3169
- dependencies: [],
3170
- errors: [createRuntimeError('FORMULA_PARSE_ERROR', error)],
3171
- };
3172
- }
3173
- let rawValue;
3174
- try {
3175
- rawValue = this.evaluateAst(compiled.ast, context.values);
3176
- }
3177
- catch (error) {
3178
- return {
3179
- dependencies: compiled.dependencies,
3180
- errors: [createRuntimeError('FORMULA_EVALUATION_ERROR', error)],
3181
- };
3182
- }
3183
- const action = this.resolveConditionAction(config.mode, compiled);
3184
- const conditionValue = toBoolean(rawValue);
3185
- switch (action) {
3186
- case 'show':
3187
- return {
3188
- hidden: !conditionValue,
3189
- dependencies: compiled.dependencies,
3190
- errors: [],
3191
- };
3192
- case 'hide':
3193
- return {
3194
- hidden: conditionValue,
3195
- dependencies: compiled.dependencies,
3196
- errors: [],
3197
- };
3198
- case 'enable':
3199
- return {
3200
- disabled: !conditionValue,
3201
- dependencies: compiled.dependencies,
3202
- errors: [],
3203
- };
3204
- case 'disable':
3205
- return {
3206
- disabled: conditionValue,
3207
- dependencies: compiled.dependencies,
3208
- errors: [],
3209
- };
3210
- default:
3211
- return {
3212
- dependencies: compiled.dependencies,
3213
- errors: [],
3214
- };
3215
- }
3216
- }
3217
- evaluateValidation(rule, context) {
3218
- let compiled;
3219
- try {
3220
- compiled = this.getCompiledFormula(rule.formulaTokens);
3221
- }
3222
- catch (error) {
3223
- return {
3224
- valid: false,
3225
- dependencies: [],
3226
- errors: [createRuntimeError('FORMULA_PARSE_ERROR', error)],
3227
- };
3228
- }
3229
- try {
3230
- const value = this.evaluateAst(compiled.ast, context.values);
3231
- return {
3232
- valid: toBoolean(value),
3233
- dependencies: compiled.dependencies,
3234
- errors: [],
3235
- };
3236
- }
3237
- catch (error) {
3238
- return {
3239
- valid: false,
3240
- dependencies: compiled.dependencies,
3241
- errors: [createRuntimeError('FORMULA_EVALUATION_ERROR', error)],
3242
- };
3243
- }
3244
- }
3245
- evaluateValidationRules(rules, context, options) {
3246
- const errors = [];
3247
- const warnings = [];
3248
- const isDependencyActive = options?.isDependencyActive ?? (() => true);
3249
- rules.forEach((rule) => {
3250
- if (!rule.enabled)
3251
- return;
3252
- const result = this.evaluateValidation(rule, context);
3253
- const hasInactiveDependency = result.dependencies.some((dependency) => !isDependencyActive(dependency));
3254
- if (hasInactiveDependency)
3255
- return;
3256
- if (result.errors.length > 0) {
3257
- const firstError = result.errors[0];
3258
- const message = {
3259
- code: firstError.code,
3260
- severity: rule.severity,
3261
- message: firstError.message,
3262
- formulaText: rule.formulaText,
3263
- ruleId: rule.id,
3264
- };
3265
- if (rule.severity === 'error')
3266
- errors.push(message);
3267
- else
3268
- warnings.push(message);
3269
- return;
3270
- }
3271
- if (!result.valid) {
3272
- const message = {
3273
- code: 'FORMULA_FALSE',
3274
- severity: rule.severity,
3275
- message: rule.message || 'Validation rule failed',
3276
- formulaText: rule.formulaText,
3277
- ruleId: rule.id,
3278
- };
3279
- if (rule.severity === 'error')
3280
- errors.push(message);
3281
- else
3282
- warnings.push(message);
3283
- }
3284
- });
3285
- return { errors, warnings };
3286
- }
3287
- extractDependencies(formulaTokens) {
3288
- try {
3289
- return this.getCompiledFormula(formulaTokens).dependencies;
3290
- }
3291
- catch {
3292
- return [];
3293
- }
3294
- }
3295
- resolveConditionAction(mode, compiled) {
3296
- if (mode && mode !== 'auto')
3297
- return mode;
3298
- return compiled.topLevelWrapper ?? 'show';
3299
- }
3300
- getCompiledFormula(formulaTokens) {
3301
- const key = formulaTokens?.trim();
3302
- if (!key) {
3303
- throw new Error('Formula tokens are empty');
3304
- }
3305
- const cached = this.compiledCache.get(key);
3306
- if (cached)
3307
- return cached;
3308
- const tokens = this.deserializeFormulaTokens(key);
3309
- const lexTokens = this.toLexTokens(tokens);
3310
- const compiled = new FormulaParser(lexTokens).parse();
3311
- this.compiledCache.set(key, compiled);
3312
- return compiled;
3313
- }
3314
- deserializeFormulaTokens(formulaTokens) {
3315
- let parsed;
3316
- try {
3317
- parsed = JSON.parse(formulaTokens);
3318
- }
3319
- catch {
3320
- throw new Error('Formula tokens JSON is invalid');
3321
- }
3322
- if (!Array.isArray(parsed)) {
3323
- throw new Error('Formula tokens must be an array');
3324
- }
3325
- return parsed;
3326
- }
3327
- toLexTokens(tokens) {
3328
- if (!tokens.length) {
3329
- throw new Error('Formula token array is empty');
3330
- }
3331
- const lex = [];
3332
- for (const token of tokens) {
3333
- switch (token.type) {
3334
- case 'fn-open': {
3335
- const functionName = (token.functionName ?? token.value.replace(/\($/, '')).trim();
3336
- if (!functionName) {
3337
- throw new Error('Formula contains function token without a name');
3338
- }
3339
- lex.push({ type: 'identifier', value: functionName });
3340
- lex.push({ type: 'lparen' });
3341
- break;
3342
- }
3343
- case 'fn-close':
3344
- lex.push({ type: 'rparen' });
3345
- break;
3346
- case 'fn-separator':
3347
- lex.push({ type: 'comma' });
3348
- break;
3349
- case 'operator':
3350
- lex.push({ type: 'operator', value: token.value });
3351
- break;
3352
- case 'property':
3353
- lex.push({
3354
- type: 'property',
3355
- value: normalizePropertyToken(token.value),
3356
- raw: token.value,
3357
- });
3358
- break;
3359
- case 'literal':
3360
- lex.push({ type: 'literal', value: parseLiteralTokenValue(token) });
3361
- break;
3362
- default:
3363
- throw new Error(`Unsupported formula token type: ${token.type}`);
3364
- }
3365
- }
3366
- lex.push({ type: 'eof' });
3367
- return lex;
3368
- }
3369
- evaluateAst(ast, values) {
3370
- switch (ast.type) {
3371
- case 'literal':
3372
- return ast.value;
3373
- case 'property':
3374
- return resolvePropertyValue(values, ast.key, ast.raw);
3375
- case 'unary': {
3376
- const right = this.evaluateAst(ast.right, values);
3377
- if (ast.operator === '!')
3378
- return !toBoolean(right);
3379
- if (ast.operator === '-')
3380
- return -toNumber(right);
3381
- throw new Error(`Unsupported unary operator: ${ast.operator}`);
3382
- }
3383
- case 'binary': {
3384
- const left = this.evaluateAst(ast.left, values);
3385
- const right = this.evaluateAst(ast.right, values);
3386
- return evaluateBinary(ast.operator, left, right);
3387
- }
3388
- case 'call': {
3389
- const fn = this.functionRegistry[ast.name.toUpperCase()];
3390
- if (!fn) {
3391
- throw new Error(`Unsupported function: ${ast.name}`);
3392
- }
3393
- const args = ast.args.map((arg) => this.evaluateAst(arg, values));
3394
- return fn(...args);
3395
- }
3396
- default:
3397
- throw new Error('Unsupported formula AST node');
3398
- }
3399
- }
3400
- }
3401
- function evaluateBinary(operator, left, right) {
3402
- switch (operator) {
3403
- case '||':
3404
- return toBoolean(left) || toBoolean(right);
3405
- case '&&':
3406
- return toBoolean(left) && toBoolean(right);
3407
- case '==':
3408
- return looseEqual(left, right);
3409
- case '!=':
3410
- return !looseEqual(left, right);
3411
- case '>':
3412
- return compareValues(left, right) > 0;
3413
- case '>=':
3414
- return compareValues(left, right) >= 0;
3415
- case '<':
3416
- return compareValues(left, right) < 0;
3417
- case '<=':
3418
- return compareValues(left, right) <= 0;
3419
- case '+':
3420
- return typeof left === 'string' || typeof right === 'string'
3421
- ? `${left ?? ''}${right ?? ''}`
3422
- : toNumber(left) + toNumber(right);
3423
- case '-':
3424
- return toNumber(left) - toNumber(right);
3425
- case '*':
3426
- return toNumber(left) * toNumber(right);
3427
- case '/':
3428
- return toNumber(left) / toNumber(right);
3429
- default:
3430
- throw new Error(`Unsupported operator: ${operator}`);
3431
- }
3432
- }
3433
- function looseEqual(left, right) {
3434
- if (Array.isArray(left) && Array.isArray(right)) {
3435
- return right.every((item) => left.includes(item));
3436
- }
3437
- if (Array.isArray(left))
3438
- return left.includes(right);
3439
- if (Array.isArray(right))
3440
- return right.includes(left);
3441
- const leftDate = toDate(left);
3442
- const rightDate = toDate(right);
3443
- if (leftDate && rightDate) {
3444
- return leftDate.getTime() === rightDate.getTime();
3445
- }
3446
- const leftNumber = maybeNumber(left);
3447
- const rightNumber = maybeNumber(right);
3448
- if (leftNumber !== null && rightNumber !== null) {
3449
- return leftNumber === rightNumber;
3450
- }
3451
- return left === right;
3452
- }
3453
- function compareValues(left, right) {
3454
- const leftDate = toDate(left);
3455
- const rightDate = toDate(right);
3456
- if (leftDate && rightDate) {
3457
- return leftDate.getTime() - rightDate.getTime();
3458
- }
3459
- const leftNumber = toNumber(left);
3460
- const rightNumber = toNumber(right);
3461
- return leftNumber - rightNumber;
3462
- }
3463
- function buildDefaultFunctionRegistry() {
3464
- const isNull = (value) => value === null ||
3465
- value === undefined ||
3466
- value === '' ||
3467
- (Array.isArray(value) && value.length === 0);
3468
- return {
3469
- SHOW_IF: (condition) => toBoolean(condition),
3470
- HIDE_IF: (condition) => toBoolean(condition),
3471
- ENABLE_IF: (condition) => toBoolean(condition),
3472
- DISABLE_IF: (condition) => toBoolean(condition),
3473
- AND: (...args) => args.every((arg) => toBoolean(arg)),
3474
- OR: (...args) => args.some((arg) => toBoolean(arg)),
3475
- NOT: (condition) => !toBoolean(condition),
3476
- ISNULL: (value) => isNull(value),
3477
- CONTAINS: (text, search) => String(text ?? '')
3478
- .toLowerCase()
3479
- .includes(String(search ?? '').toLowerCase()),
3480
- REQUIRED: (value) => !isNull(value),
3481
- MIN_LENGTH: (value, min) => String(value ?? '').length >= toNumber(min),
3482
- MAX_LENGTH: (value, max) => String(value ?? '').length <= toNumber(max),
3483
- REGEX: (value, pattern) => {
3484
- try {
3485
- return new RegExp(String(pattern ?? '')).test(String(value ?? ''));
3486
- }
3487
- catch {
3488
- return false;
3489
- }
3490
- },
3491
- BEFORE: (date, reference) => {
3492
- const left = toDate(date);
3493
- const right = toDate(reference);
3494
- if (!left || !right)
3495
- return false;
3496
- return left.getTime() < right.getTime();
3497
- },
3498
- AFTER: (date, reference) => {
3499
- const left = toDate(date);
3500
- const right = toDate(reference);
3501
- if (!left || !right)
3502
- return false;
3503
- return left.getTime() > right.getTime();
3504
- },
3505
- };
3506
- }
3507
- function normalizeWrapperAction(name) {
3508
- const normalized = name.trim().toLowerCase();
3509
- return CONDITION_WRAPPER_NAMES.has(normalized)
3510
- ? normalized
3511
- : null;
3512
- }
3513
- function normalizePropertyToken(raw) {
3514
- const value = String(raw ?? '').trim();
3515
- const prefix = PROPERTY_PREFIXES.find((p) => value.startsWith(p));
3516
- return prefix ? value.slice(prefix.length) : value;
3517
- }
3518
- function parseLiteralTokenValue(token) {
3519
- if (token.literalType === 'number') {
3520
- return toNumber(token.value);
3521
- }
3522
- if (token.literalType === 'boolean') {
3523
- return toBoolean(token.value);
3524
- }
3525
- const value = String(token.value ?? '').trim();
3526
- if ((value.startsWith('"') && value.endsWith('"')) ||
3527
- (value.startsWith("'") && value.endsWith("'"))) {
3528
- return value.slice(1, -1);
3529
- }
3530
- if (value.toLowerCase() === 'true')
3531
- return true;
3532
- if (value.toLowerCase() === 'false')
3533
- return false;
3534
- const asNumber = maybeNumber(value);
3535
- if (asNumber !== null)
3536
- return asNumber;
3537
- return value;
3538
- }
3539
- function resolvePropertyValue(values, key, raw) {
3540
- if (Object.prototype.hasOwnProperty.call(values, key)) {
3541
- return values[key];
3542
- }
3543
- if (Object.prototype.hasOwnProperty.call(values, raw)) {
3544
- return values[raw];
3545
- }
3546
- if (!key.includes('.')) {
3547
- return undefined;
3548
- }
3549
- const parts = key.split('.');
3550
- let current = values;
3551
- for (const part of parts) {
3552
- if (current === null || current === undefined) {
3553
- return undefined;
3554
- }
3555
- current = current[part];
3556
- }
3557
- return current;
3558
- }
3559
- function toBoolean(value) {
3560
- if (typeof value === 'boolean')
3561
- return value;
3562
- if (typeof value === 'number')
3563
- return !Number.isNaN(value) && value !== 0;
3564
- if (typeof value === 'string') {
3565
- const normalized = value.trim().toLowerCase();
3566
- if (normalized === '' ||
3567
- normalized === 'false' ||
3568
- normalized === '0' ||
3569
- normalized === 'null' ||
3570
- normalized === 'undefined') {
3571
- return false;
3572
- }
3573
- return true;
3574
- }
3575
- if (Array.isArray(value))
3576
- return value.length > 0;
3577
- return Boolean(value);
3578
- }
3579
- function toNumber(value) {
3580
- const num = Number(value);
3581
- return Number.isFinite(num) ? num : 0;
3582
- }
3583
- function maybeNumber(value) {
3584
- if (value === '' || value === null || value === undefined)
3585
- return null;
3586
- const num = Number(value);
3587
- return Number.isFinite(num) ? num : null;
3588
- }
3589
- function toDate(value) {
3590
- if (value instanceof Date) {
3591
- return Number.isNaN(value.getTime()) ? null : value;
3592
- }
3593
- if (typeof value === 'string' || typeof value === 'number') {
3594
- const date = new Date(value);
3595
- return Number.isNaN(date.getTime()) ? null : date;
3596
- }
3597
- return null;
3598
- }
3599
- function toErrorMessage(error) {
3600
- if (error instanceof Error && error.message)
3601
- return error.message;
3602
- return 'Formula evaluation failed';
3603
- }
3604
- function createRuntimeError(code, error) {
3605
- return {
3606
- code,
3607
- message: toErrorMessage(error),
3608
- };
3609
- }
3610
-
3611
- // Formula components public API
3612
-
3613
- /**
3614
- * Generated bundle index. Do not edit.
3615
- */
3616
-
3617
- export { CONDITION_FUNCTION_CATEGORIES, CONDITION_OPERATORS, CONDITION_RUNTIME_CATALOG, DEFAULT_OPERATORS, FormulaEditor, FormulaEditorCode, FormulaRuntimeEngine, FormulaStatusBar, FormulaToolbar, FormulaToolbarItem, OPERATOR_SYMBOL_TO_TRANSLATION_KEY, VALIDATION_FUNCTION_CATEGORIES, VALIDATION_OPERATORS, VALIDATION_RUNTIME_CATALOG, cloneBlock, cloneToken, cloneTokens, createFunctionBlock, createFunctionTokens, createLiteralBlock, createLiteralToken, createOperatorBlock, createOperatorToken, createPropertyBlock, createPropertyToken, createTextToken, findFunctionRange, generateFunctionId, generateSmartBlockId, generateTokenId, getArgumentIndexAtPosition, getFunctionTokens, isValidDropPosition, parseSignature, recalculateDepths, serializeTokens, tokenizeFormulaTemplate };
3618
- //# sourceMappingURL=masterteam-components-formula.mjs.map