@masterteam/components 0.0.206 → 0.0.208

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.
@@ -149,7 +149,7 @@ function createOperatorToken(symbol, depth = 0, functionId, argIndex) {
149
149
  /**
150
150
  * Create a literal token
151
151
  */
152
- function createLiteralToken(value, depth = 0, functionId, argIndex) {
152
+ function createLiteralToken(value, depth = 0, functionId, argIndex, display) {
153
153
  let displayValue = String(value);
154
154
  let literalType = 'string';
155
155
  if (typeof value === 'number') {
@@ -165,6 +165,10 @@ function createLiteralToken(value, depth = 0, functionId, argIndex) {
165
165
  id: generateTokenId(),
166
166
  type: 'literal',
167
167
  value: displayValue,
168
+ // Friendly label rendered on the chip while `value` stays the executable
169
+ // (serialized) form — e.g. a lookup value shows "Completed" but serializes
170
+ // as "completed". Cosmetic only; serialization never reads `display`.
171
+ display: display?.trim() ? display : undefined,
168
172
  literalType,
169
173
  depth,
170
174
  functionId,
@@ -247,7 +251,9 @@ function isValidDropPosition(tokens, dropIndex, draggedTokens) {
247
251
  return true;
248
252
  }
249
253
  /**
250
- * Serialize tokens to formula string
254
+ * Serialize tokens to the canonical, executable formula string.
255
+ * Uses each token's `value` (e.g. `@Current::startdate`) — never `display` —
256
+ * so the produced expression is stable and engine/back-end compatible.
251
257
  */
252
258
  function serializeTokens(tokens) {
253
259
  const parts = [];
@@ -263,6 +269,29 @@ function serializeTokens(tokens) {
263
269
  }
264
270
  return parts.join('');
265
271
  }
272
+ /**
273
+ * Serialize tokens to a human-readable preview string using each token's
274
+ * `display` label (the friendly property name) when present, falling back to
275
+ * its `value`. Spacing is computed from the canonical `value`/`type` so that a
276
+ * friendly name containing spaces (e.g. "Start Date") does not corrupt
277
+ * function/paren/separator spacing. This output is for display/preview ONLY
278
+ * (e.g. `formulaText`) — never feed it to the validator or persist it as the
279
+ * executable expression.
280
+ */
281
+ function serializeTokensForDisplay(tokens) {
282
+ const parts = [];
283
+ let lastType = null;
284
+ let lastValue = '';
285
+ for (const token of tokens) {
286
+ if (shouldInsertSpace(lastType, lastValue, token)) {
287
+ parts.push(' ');
288
+ }
289
+ parts.push(token.display ?? token.value);
290
+ lastType = token.type;
291
+ lastValue = token.value;
292
+ }
293
+ return parts.join('');
294
+ }
266
295
  function shouldInsertSpace(previousType, previousValue, current) {
267
296
  if (!previousType)
268
297
  return false;
@@ -632,11 +661,12 @@ function createOperatorBlock(symbol) {
632
661
  };
633
662
  }
634
663
  /** Create a literal block */
635
- function createLiteralBlock(value) {
664
+ function createLiteralBlock(value, display) {
636
665
  return {
637
666
  id: generateSmartBlockId(),
638
667
  type: 'literal',
639
668
  value: String(value),
669
+ display,
640
670
  literalValue: value,
641
671
  };
642
672
  }
@@ -977,7 +1007,9 @@ class FormulaEditor {
977
1007
  case 'operator':
978
1008
  return [createOperatorToken(block.operatorSymbol || block.value)];
979
1009
  case 'literal':
980
- return [createLiteralToken(block.literalValue ?? block.value)];
1010
+ return [
1011
+ createLiteralToken(block.literalValue ?? block.value, 0, undefined, undefined, block.display),
1012
+ ];
981
1013
  default:
982
1014
  return [createLiteralToken(block.value)];
983
1015
  }
@@ -1100,6 +1132,103 @@ function getReferenceCompletionBounds(lineContent, column, suggestion) {
1100
1132
  };
1101
1133
  }
1102
1134
 
1135
+ /** Path (relative to the document base) where the host copies monaco `min/vs`. */
1136
+ const MONACO_ASSET_DIR = 'assets/monaco/vs';
1137
+ /**
1138
+ * Shared, lazily-resolved Monaco loader promise (module scope so every editor
1139
+ * instance reuses a single load).
1140
+ */
1141
+ let monacoLoadPromise = null;
1142
+ /** Absolute URL to the copied Monaco `vs` folder, with no trailing slash. */
1143
+ function resolveMonacoAssetBase(doc) {
1144
+ return new URL(`${MONACO_ASSET_DIR}/`, doc.baseURI)
1145
+ .toString()
1146
+ .replace(/\/$/, '');
1147
+ }
1148
+ /**
1149
+ * Point Monaco's web workers at the copied assets via a tiny same-origin proxy
1150
+ * worker. Loading workers from `/assets/monaco/vs` (instead of node_modules)
1151
+ * avoids the Vite `@fs` serving-allow-list 403 and the "define
1152
+ * MonacoEnvironment.getWorkerUrl" warning. Set once; respects a host-provided
1153
+ * MonacoEnvironment if one already exists.
1154
+ */
1155
+ function configureMonacoWorker(base) {
1156
+ const globalScope = self;
1157
+ if (globalScope.MonacoEnvironment) {
1158
+ return;
1159
+ }
1160
+ globalScope.MonacoEnvironment = {
1161
+ getWorkerUrl: () => {
1162
+ const proxy = `self.MonacoEnvironment={baseUrl:'${base}/'};` +
1163
+ `importScripts('${base}/base/worker/workerMain.js');`;
1164
+ return `data:text/javascript;charset=utf-8,${encodeURIComponent(proxy)}`;
1165
+ },
1166
+ };
1167
+ }
1168
+ /**
1169
+ * Load Monaco via its own AMD loader from `/assets/monaco/vs`. This is fully
1170
+ * self-contained: `editor.main` injects its CSS and the codicon font from the
1171
+ * same folder, and workers resolve from there too — so no editor CSS/font is
1172
+ * pulled into the app bundle and there is no node_modules/`@fs` access at all.
1173
+ */
1174
+ function loadMonacoFromAssets(doc, base) {
1175
+ return new Promise((resolve, reject) => {
1176
+ const globalScope = window;
1177
+ if (globalScope.monaco) {
1178
+ resolve({ monaco: globalScope.monaco, fromAssets: true });
1179
+ return;
1180
+ }
1181
+ const startRequire = () => {
1182
+ const amdRequire = globalScope.require;
1183
+ if (!amdRequire?.config) {
1184
+ reject(new Error('Monaco AMD loader is unavailable'));
1185
+ return;
1186
+ }
1187
+ configureMonacoWorker(base);
1188
+ amdRequire.config({ paths: { vs: base } });
1189
+ amdRequire(['vs/editor/editor.main'], () => globalScope.monaco
1190
+ ? resolve({ monaco: globalScope.monaco, fromAssets: true })
1191
+ : reject(new Error('Monaco did not initialize')), (error) => reject(error));
1192
+ };
1193
+ if (globalScope.require?.config) {
1194
+ startRequire();
1195
+ return;
1196
+ }
1197
+ const existing = doc.querySelector('script[data-mt-monaco-loader]');
1198
+ if (existing) {
1199
+ existing.addEventListener('load', startRequire, { once: true });
1200
+ existing.addEventListener('error', () => reject(new Error('Monaco loader failed to load')), { once: true });
1201
+ return;
1202
+ }
1203
+ const script = doc.createElement('script');
1204
+ script.src = `${base}/loader.js`;
1205
+ script.async = true;
1206
+ script.dataset['mtMonacoLoader'] = 'true';
1207
+ script.addEventListener('load', startRequire, { once: true });
1208
+ script.addEventListener('error', () => reject(new Error('Monaco loader failed to load')), { once: true });
1209
+ doc.head.appendChild(script);
1210
+ });
1211
+ }
1212
+ /**
1213
+ * Resolve Monaco once, preferring the self-contained assets loader and falling
1214
+ * back to the bundled ESM build if `/assets/monaco/vs` is unavailable (so hosts
1215
+ * that do not copy `min/vs` keep working, just without the asset-served CSS).
1216
+ */
1217
+ function loadMonaco(doc) {
1218
+ if (monacoLoadPromise) {
1219
+ return monacoLoadPromise;
1220
+ }
1221
+ const base = resolveMonacoAssetBase(doc);
1222
+ monacoLoadPromise = loadMonacoFromAssets(doc, base).catch(async (error) => {
1223
+ console.warn(`[mt-formula-editor-code] Could not load Monaco from ${base}; falling back ` +
1224
+ `to the bundled monaco-editor. Copy "node_modules/monaco-editor/min/vs/" ` +
1225
+ `to "/assets/monaco/vs/" in the host app's angular.json for the ` +
1226
+ `self-contained loader (CSS, codicon font, and workers from assets).`, error);
1227
+ const monaco = (await import('monaco-editor'));
1228
+ return { monaco, fromAssets: false };
1229
+ });
1230
+ return monacoLoadPromise;
1231
+ }
1103
1232
  class FormulaEditorCode {
1104
1233
  placeholder = input('Enter formula...', ...(ngDevMode ? [{ debugName: "placeholder" }] : /* istanbul ignore next */ []));
1105
1234
  initialFormula = input('', ...(ngDevMode ? [{ debugName: "initialFormula" }] : /* istanbul ignore next */ []));
@@ -1251,15 +1380,20 @@ class FormulaEditorCode {
1251
1380
  const host = this.editorHost()?.nativeElement;
1252
1381
  if (!host)
1253
1382
  return;
1254
- this.ensureMonacoStylesLoaded();
1255
- let monaco;
1383
+ let loaded;
1256
1384
  try {
1257
- monaco = await import('monaco-editor');
1385
+ loaded = await loadMonaco(this.document);
1258
1386
  }
1259
1387
  catch (error) {
1260
1388
  console.warn('Failed to load Monaco editor:', error);
1261
1389
  return;
1262
1390
  }
1391
+ const monaco = loaded.monaco;
1392
+ // The assets (AMD) path injects its own CSS + codicon font from
1393
+ // /assets/monaco/vs. Only the bundled ESM fallback needs the manual link.
1394
+ if (!loaded.fromAssets) {
1395
+ this.ensureMonacoStylesLoaded();
1396
+ }
1263
1397
  this.monaco = monaco;
1264
1398
  this.ensureFormulaAssets(monaco);
1265
1399
  const model = monaco.editor.createModel(this.value(), this.language());
@@ -3351,17 +3485,29 @@ class FormulaRuntimeEngine {
3351
3485
  return compiled;
3352
3486
  }
3353
3487
  deserializeFormulaTokens(formulaTokens) {
3354
- let parsed;
3355
- try {
3356
- parsed = JSON.parse(formulaTokens);
3357
- }
3358
- catch {
3359
- throw new Error('Formula tokens JSON is invalid');
3360
- }
3361
- if (!Array.isArray(parsed)) {
3362
- throw new Error('Formula tokens must be an array');
3488
+ const trimmed = formulaTokens.trim();
3489
+ // `formulaTokens` may be persisted in two equivalent encodings:
3490
+ // - the canonical executable EXPRESSION string (e.g.
3491
+ // "OR(ISNULL(@Current::x), ...)") — what the back-end stores; or
3492
+ // - a JSON token array (legacy / inline-form snapshots).
3493
+ // Accept both: a value that parses to an array of token objects is used
3494
+ // directly; anything else is tokenized from the expression string.
3495
+ if (trimmed.startsWith('[')) {
3496
+ try {
3497
+ const parsed = JSON.parse(trimmed);
3498
+ if (Array.isArray(parsed) &&
3499
+ (parsed.length === 0 ||
3500
+ (typeof parsed[0] === 'object' &&
3501
+ parsed[0] !== null &&
3502
+ 'type' in parsed[0]))) {
3503
+ return parsed;
3504
+ }
3505
+ }
3506
+ catch {
3507
+ // Not valid JSON — fall through and treat it as an expression string.
3508
+ }
3363
3509
  }
3364
- return parsed;
3510
+ return tokenizeFormulaTemplate(trimmed);
3365
3511
  }
3366
3512
  toLexTokens(tokens) {
3367
3513
  if (!tokens.length) {
@@ -3664,5 +3810,5 @@ function createRuntimeError(code, error) {
3664
3810
  * Generated bundle index. Do not edit.
3665
3811
  */
3666
3812
 
3667
- 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 };
3813
+ 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, serializeTokensForDisplay, shouldInsertSpace, tokenizeFormulaTemplate };
3668
3814
  //# sourceMappingURL=masterteam-components-formula.mjs.map