@selfhelp/shared 1.3.0 → 1.3.2

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 (58) hide show
  1. package/CHANGELOG.md +349 -341
  2. package/LICENSE +381 -381
  3. package/README.md +57 -57
  4. package/package.json +102 -102
  5. package/src/api/__tests__/endpoints.test.ts +45 -45
  6. package/src/api/index.ts +5 -5
  7. package/src/assets/__tests__/resolveAssetUrl.test.ts +61 -61
  8. package/src/assets/index.ts +5 -5
  9. package/src/assets/resolveAssetUrl.ts +44 -44
  10. package/src/cms-classes/__tests__/classify.test.ts +63 -63
  11. package/src/cms-classes/allow-list.ts +158 -158
  12. package/src/cms-classes/classify.ts +90 -90
  13. package/src/cms-classes/index.ts +7 -7
  14. package/src/cms-classes/remap.ts +44 -44
  15. package/src/condition/__tests__/evaluate.test.ts +54 -54
  16. package/src/condition/evaluate.ts +121 -121
  17. package/src/condition/index.ts +5 -5
  18. package/src/index.ts +25 -25
  19. package/src/interpolation/__tests__/replaceCalcedValues.test.ts +41 -41
  20. package/src/interpolation/index.ts +5 -5
  21. package/src/interpolation/replaceCalcedValues.ts +27 -27
  22. package/src/plugin-sdk/define.ts +89 -89
  23. package/src/plugin-sdk/index.ts +103 -103
  24. package/src/plugin-sdk/lock.ts +124 -124
  25. package/src/plugin-sdk/manifest.ts +307 -307
  26. package/src/plugin-sdk/realtime.ts +277 -277
  27. package/src/plugin-sdk/registry.ts +105 -105
  28. package/src/plugin-sdk/runtime-shim.ts +140 -140
  29. package/src/plugin-sdk/types.ts +315 -315
  30. package/src/plugin-sdk/version.ts +209 -209
  31. package/src/registry/__tests__/registry.test.ts +135 -135
  32. package/src/registry/index.ts +94 -94
  33. package/src/registry/styles.registry.ts +295 -295
  34. package/src/testing/__tests__/testing-kit.test.ts +228 -228
  35. package/src/testing/index.ts +483 -483
  36. package/src/theme/index.ts +6 -6
  37. package/src/theme/tailwind.ts +73 -73
  38. package/src/theme/tokens.ts +177 -177
  39. package/src/types/api/envelope.ts +34 -34
  40. package/src/types/api/forms.ts +76 -76
  41. package/src/types/api/index.ts +9 -9
  42. package/src/types/api/language.ts +12 -12
  43. package/src/types/api/page.ts +9 -9
  44. package/src/types/index.ts +17 -17
  45. package/src/types/mantine/common.ts +142 -142
  46. package/src/types/pages.ts +107 -107
  47. package/src/types/styles/auth.ts +184 -184
  48. package/src/types/styles/base.ts +72 -72
  49. package/src/types/styles/composite.ts +131 -131
  50. package/src/types/styles/forms.ts +439 -439
  51. package/src/types/styles/interactive.ts +165 -165
  52. package/src/types/styles/layout.ts +184 -184
  53. package/src/types/styles/media.ts +68 -68
  54. package/src/types/styles/typography.ts +118 -118
  55. package/src/types/styles/unknown.ts +220 -220
  56. package/src/utils/__tests__/transformPageData.test.ts +69 -69
  57. package/src/utils/spacing.ts +64 -64
  58. package/src/utils/transformPageData.ts +99 -99
@@ -1,44 +1,44 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- /**
6
- * Web -> mobile class remap. Some Tailwind classes are valid on web but
7
- * have no mobile equivalent (or have a different name in Uniwind). This
8
- * table runs BEFORE the allow-list check.
9
- *
10
- * Rules of thumb:
11
- * - drop classes that don't make sense on mobile (`select-text` is a no-op on RN, `cursor-*`, `hover:*`).
12
- * - rewrite logical pairs (e.g. mobile prefers `text-center` over `text-left` defaults — leave alone).
13
- * - alias common Mantine-flavored utility names users may type.
14
- */
15
-
16
- export interface IClassRemap {
17
- /** Class to rewrite. */
18
- from: string;
19
- /** Replacement class, or null to drop the class entirely. */
20
- to: string | null;
21
- /** Optional reason surfaced via dev warning. */
22
- reason?: string;
23
- }
24
-
25
- export const CLASS_REMAP: readonly IClassRemap[] = [
26
- // hover/focus on mobile only fires for keyboard nav; safe to drop.
27
- { from: 'hover:bg-gray-100', to: null, reason: 'hover not applicable on mobile' },
28
- { from: 'hover:underline', to: null, reason: 'hover not applicable on mobile' },
29
- // cursor classes are no-ops on RN.
30
- { from: 'cursor-pointer', to: null, reason: 'no cursor on RN' },
31
- { from: 'cursor-default', to: null, reason: 'no cursor on RN' },
32
- { from: 'cursor-not-allowed', to: null, reason: 'no cursor on RN' },
33
- // select-text behaves slightly differently on RN; keep but as a soft no-op.
34
- { from: 'select-text', to: null, reason: 'unsupported on RN' },
35
- // legacy aliases
36
- { from: 'mantine-fw', to: 'w-full' },
37
- { from: 'mantine-h-full', to: 'h-full' },
38
- ];
39
-
40
- const REMAP_MAP = new Map<string, IClassRemap>(CLASS_REMAP.map((r) => [r.from, r]));
41
-
42
- export function findRemap(className: string): IClassRemap | undefined {
43
- return REMAP_MAP.get(className);
44
- }
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Web -> mobile class remap. Some Tailwind classes are valid on web but
7
+ * have no mobile equivalent (or have a different name in Uniwind). This
8
+ * table runs BEFORE the allow-list check.
9
+ *
10
+ * Rules of thumb:
11
+ * - drop classes that don't make sense on mobile (`select-text` is a no-op on RN, `cursor-*`, `hover:*`).
12
+ * - rewrite logical pairs (e.g. mobile prefers `text-center` over `text-left` defaults — leave alone).
13
+ * - alias common Mantine-flavored utility names users may type.
14
+ */
15
+
16
+ export interface IClassRemap {
17
+ /** Class to rewrite. */
18
+ from: string;
19
+ /** Replacement class, or null to drop the class entirely. */
20
+ to: string | null;
21
+ /** Optional reason surfaced via dev warning. */
22
+ reason?: string;
23
+ }
24
+
25
+ export const CLASS_REMAP: readonly IClassRemap[] = [
26
+ // hover/focus on mobile only fires for keyboard nav; safe to drop.
27
+ { from: 'hover:bg-gray-100', to: null, reason: 'hover not applicable on mobile' },
28
+ { from: 'hover:underline', to: null, reason: 'hover not applicable on mobile' },
29
+ // cursor classes are no-ops on RN.
30
+ { from: 'cursor-pointer', to: null, reason: 'no cursor on RN' },
31
+ { from: 'cursor-default', to: null, reason: 'no cursor on RN' },
32
+ { from: 'cursor-not-allowed', to: null, reason: 'no cursor on RN' },
33
+ // select-text behaves slightly differently on RN; keep but as a soft no-op.
34
+ { from: 'select-text', to: null, reason: 'unsupported on RN' },
35
+ // legacy aliases
36
+ { from: 'mantine-fw', to: 'w-full' },
37
+ { from: 'mantine-h-full', to: 'h-full' },
38
+ ];
39
+
40
+ const REMAP_MAP = new Map<string, IClassRemap>(CLASS_REMAP.map((r) => [r.from, r]));
41
+
42
+ export function findRemap(className: string): IClassRemap | undefined {
43
+ return REMAP_MAP.get(className);
44
+ }
@@ -1,54 +1,54 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- import { describe, it, expect } from 'vitest';
6
- import { buildConditionContext, evaluateCondition } from '../evaluate';
7
-
8
- describe('evaluateCondition', () => {
9
- const ctx = buildConditionContext('web');
10
-
11
- it('treats a null/empty/whitespace condition as visible (no condition)', () => {
12
- expect(evaluateCondition(null, ctx).visible).toBe(true);
13
- expect(evaluateCondition('', ctx).visible).toBe(true);
14
- expect(evaluateCondition(' ', ctx).visible).toBe(true);
15
- });
16
-
17
- it('evaluates a true JSON-Logic rule to visible', () => {
18
- expect(evaluateCondition('{"==":[1,1]}', ctx).visible).toBe(true);
19
- });
20
-
21
- it('evaluates a false JSON-Logic rule to not visible', () => {
22
- expect(evaluateCondition('{"==":[1,2]}', ctx).visible).toBe(false);
23
- });
24
-
25
- it('resolves context variables (platform) from the condition context', () => {
26
- const rule = '{"==":[{"var":"platform"},"web"]}';
27
- expect(evaluateCondition(rule, buildConditionContext('web')).visible).toBe(true);
28
- expect(evaluateCondition(rule, buildConditionContext('mobile')).visible).toBe(false);
29
- });
30
-
31
- it('treats invalid JSON as not visible (fail closed, never throws)', () => {
32
- expect(evaluateCondition('{not json', ctx).visible).toBe(false);
33
- });
34
-
35
- it('exposes a debug payload with the error when withDebug is set', () => {
36
- const result = evaluateCondition('{not json', ctx, { withDebug: true });
37
- expect(result.visible).toBe(false);
38
- expect(result.debug?.error).toContain('Invalid JSON');
39
- expect(result.debug?.condition).toBe('{not json');
40
- });
41
- });
42
-
43
- describe('buildConditionContext', () => {
44
- it('builds deterministic date/time vars from a fixed "now" and includes the platform', () => {
45
- const now = new Date(2026, 4, 22, 9, 5, 3); // 2026-05-22 09:05:03 (month is 0-based)
46
- const ctx = buildConditionContext('mobile', { custom: 'x' }, now);
47
-
48
- expect(ctx.platform).toBe('mobile');
49
- expect(ctx.current_date).toBe('2026-05-22');
50
- expect(ctx.current_time).toBe('09:05:03');
51
- expect(ctx.current_datetime).toBe('2026-05-22 09:05:03');
52
- expect(ctx.custom).toBe('x');
53
- });
54
- });
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { describe, it, expect } from 'vitest';
6
+ import { buildConditionContext, evaluateCondition } from '../evaluate';
7
+
8
+ describe('evaluateCondition', () => {
9
+ const ctx = buildConditionContext('web');
10
+
11
+ it('treats a null/empty/whitespace condition as visible (no condition)', () => {
12
+ expect(evaluateCondition(null, ctx).visible).toBe(true);
13
+ expect(evaluateCondition('', ctx).visible).toBe(true);
14
+ expect(evaluateCondition(' ', ctx).visible).toBe(true);
15
+ });
16
+
17
+ it('evaluates a true JSON-Logic rule to visible', () => {
18
+ expect(evaluateCondition('{"==":[1,1]}', ctx).visible).toBe(true);
19
+ });
20
+
21
+ it('evaluates a false JSON-Logic rule to not visible', () => {
22
+ expect(evaluateCondition('{"==":[1,2]}', ctx).visible).toBe(false);
23
+ });
24
+
25
+ it('resolves context variables (platform) from the condition context', () => {
26
+ const rule = '{"==":[{"var":"platform"},"web"]}';
27
+ expect(evaluateCondition(rule, buildConditionContext('web')).visible).toBe(true);
28
+ expect(evaluateCondition(rule, buildConditionContext('mobile')).visible).toBe(false);
29
+ });
30
+
31
+ it('treats invalid JSON as not visible (fail closed, never throws)', () => {
32
+ expect(evaluateCondition('{not json', ctx).visible).toBe(false);
33
+ });
34
+
35
+ it('exposes a debug payload with the error when withDebug is set', () => {
36
+ const result = evaluateCondition('{not json', ctx, { withDebug: true });
37
+ expect(result.visible).toBe(false);
38
+ expect(result.debug?.error).toContain('Invalid JSON');
39
+ expect(result.debug?.condition).toBe('{not json');
40
+ });
41
+ });
42
+
43
+ describe('buildConditionContext', () => {
44
+ it('builds deterministic date/time vars from a fixed "now" and includes the platform', () => {
45
+ const now = new Date(2026, 4, 22, 9, 5, 3); // 2026-05-22 09:05:03 (month is 0-based)
46
+ const ctx = buildConditionContext('mobile', { custom: 'x' }, now);
47
+
48
+ expect(ctx.platform).toBe('mobile');
49
+ expect(ctx.current_date).toBe('2026-05-22');
50
+ expect(ctx.current_time).toBe('09:05:03');
51
+ expect(ctx.current_datetime).toBe('2026-05-22 09:05:03');
52
+ expect(ctx.custom).toBe('x');
53
+ });
54
+ });
@@ -1,121 +1,121 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- /**
6
- * Client-side mirror of the backend `ConditionService::evaluateCondition`.
7
- * Uses `json-logic-js` so the same JSON-Logic expressions evaluated on
8
- * the server are evaluated identically here.
9
- *
10
- * Backend system variables (see ConditionService docblock):
11
- * - language: ISO locale code, e.g. 'de-CH'
12
- * - current_date / current_datetime / current_time
13
- * - page_keyword
14
- * - platform: 'web' | 'mobile'
15
- *
16
- * Anything else passed in `extraVars` is merged on top.
17
- */
18
-
19
- import jsonLogic from 'json-logic-js';
20
-
21
- export type TPlatform = 'web' | 'mobile';
22
-
23
- export interface IConditionContext {
24
- platform: TPlatform;
25
- language?: string;
26
- page_keyword?: string;
27
- current_date?: string;
28
- current_datetime?: string;
29
- current_time?: string;
30
- [extraKey: string]: unknown;
31
- }
32
-
33
- export interface IEvaluatedCondition {
34
- /** Whether the condition allowed the section to render. */
35
- visible: boolean;
36
- /** Optional debug payload (only set when `withDebug` is true). */
37
- debug?: {
38
- condition: string | null;
39
- result: boolean;
40
- variables: Record<string, unknown>;
41
- error?: string;
42
- };
43
- }
44
-
45
- /**
46
- * Build a default context with current date/time + the platform
47
- * variable. Pass any extra vars (data-bound section variables, etc).
48
- */
49
- export function buildConditionContext(
50
- platform: TPlatform,
51
- extraVars: Record<string, unknown> = {},
52
- now: Date = new Date()
53
- ): IConditionContext {
54
- const pad = (n: number): string => String(n).padStart(2, '0');
55
- const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
56
- const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
57
- return {
58
- platform,
59
- current_date: date,
60
- current_time: time,
61
- current_datetime: `${date} ${time}`,
62
- ...extraVars,
63
- };
64
- }
65
-
66
- /**
67
- * Evaluate a JSON-Logic condition string. A null/empty/whitespace
68
- * condition is treated as `visible: true` (no condition).
69
- */
70
- export function evaluateCondition(
71
- condition: string | null | undefined,
72
- context: IConditionContext,
73
- options: { withDebug?: boolean } = {}
74
- ): IEvaluatedCondition {
75
- const trimmed = (condition ?? '').toString().trim();
76
- if (!trimmed) {
77
- return options.withDebug
78
- ? { visible: true, debug: { condition: null, result: true, variables: { ...context } } }
79
- : { visible: true };
80
- }
81
-
82
- let parsed: unknown;
83
- try {
84
- parsed = JSON.parse(trimmed);
85
- } catch (err) {
86
- return options.withDebug
87
- ? {
88
- visible: false,
89
- debug: {
90
- condition: trimmed,
91
- result: false,
92
- variables: { ...context },
93
- error: `Invalid JSON: ${(err as Error).message}`,
94
- },
95
- }
96
- : { visible: false };
97
- }
98
-
99
- try {
100
- // jsonLogic typings are loose; the result of any boolean rule is
101
- // a boolean, but rules like {var: 'x'} can return raw values, so
102
- // we coerce.
103
- const raw = jsonLogic.apply(parsed as jsonLogic.RulesLogic, context as Record<string, unknown>);
104
- const visible = Boolean(raw);
105
- return options.withDebug
106
- ? { visible, debug: { condition: trimmed, result: visible, variables: { ...context } } }
107
- : { visible };
108
- } catch (err) {
109
- return options.withDebug
110
- ? {
111
- visible: false,
112
- debug: {
113
- condition: trimmed,
114
- result: false,
115
- variables: { ...context },
116
- error: (err as Error).message,
117
- },
118
- }
119
- : { visible: false };
120
- }
121
- }
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Client-side mirror of the backend `ConditionService::evaluateCondition`.
7
+ * Uses `json-logic-js` so the same JSON-Logic expressions evaluated on
8
+ * the server are evaluated identically here.
9
+ *
10
+ * Backend system variables (see ConditionService docblock):
11
+ * - language: ISO locale code, e.g. 'de-CH'
12
+ * - current_date / current_datetime / current_time
13
+ * - page_keyword
14
+ * - platform: 'web' | 'mobile'
15
+ *
16
+ * Anything else passed in `extraVars` is merged on top.
17
+ */
18
+
19
+ import jsonLogic from 'json-logic-js';
20
+
21
+ export type TPlatform = 'web' | 'mobile';
22
+
23
+ export interface IConditionContext {
24
+ platform: TPlatform;
25
+ language?: string;
26
+ page_keyword?: string;
27
+ current_date?: string;
28
+ current_datetime?: string;
29
+ current_time?: string;
30
+ [extraKey: string]: unknown;
31
+ }
32
+
33
+ export interface IEvaluatedCondition {
34
+ /** Whether the condition allowed the section to render. */
35
+ visible: boolean;
36
+ /** Optional debug payload (only set when `withDebug` is true). */
37
+ debug?: {
38
+ condition: string | null;
39
+ result: boolean;
40
+ variables: Record<string, unknown>;
41
+ error?: string;
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Build a default context with current date/time + the platform
47
+ * variable. Pass any extra vars (data-bound section variables, etc).
48
+ */
49
+ export function buildConditionContext(
50
+ platform: TPlatform,
51
+ extraVars: Record<string, unknown> = {},
52
+ now: Date = new Date()
53
+ ): IConditionContext {
54
+ const pad = (n: number): string => String(n).padStart(2, '0');
55
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
56
+ const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
57
+ return {
58
+ platform,
59
+ current_date: date,
60
+ current_time: time,
61
+ current_datetime: `${date} ${time}`,
62
+ ...extraVars,
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Evaluate a JSON-Logic condition string. A null/empty/whitespace
68
+ * condition is treated as `visible: true` (no condition).
69
+ */
70
+ export function evaluateCondition(
71
+ condition: string | null | undefined,
72
+ context: IConditionContext,
73
+ options: { withDebug?: boolean } = {}
74
+ ): IEvaluatedCondition {
75
+ const trimmed = (condition ?? '').toString().trim();
76
+ if (!trimmed) {
77
+ return options.withDebug
78
+ ? { visible: true, debug: { condition: null, result: true, variables: { ...context } } }
79
+ : { visible: true };
80
+ }
81
+
82
+ let parsed: unknown;
83
+ try {
84
+ parsed = JSON.parse(trimmed);
85
+ } catch (err) {
86
+ return options.withDebug
87
+ ? {
88
+ visible: false,
89
+ debug: {
90
+ condition: trimmed,
91
+ result: false,
92
+ variables: { ...context },
93
+ error: `Invalid JSON: ${(err as Error).message}`,
94
+ },
95
+ }
96
+ : { visible: false };
97
+ }
98
+
99
+ try {
100
+ // jsonLogic typings are loose; the result of any boolean rule is
101
+ // a boolean, but rules like {var: 'x'} can return raw values, so
102
+ // we coerce.
103
+ const raw = jsonLogic.apply(parsed as jsonLogic.RulesLogic, context as Record<string, unknown>);
104
+ const visible = Boolean(raw);
105
+ return options.withDebug
106
+ ? { visible, debug: { condition: trimmed, result: visible, variables: { ...context } } }
107
+ : { visible };
108
+ } catch (err) {
109
+ return options.withDebug
110
+ ? {
111
+ visible: false,
112
+ debug: {
113
+ condition: trimmed,
114
+ result: false,
115
+ variables: { ...context },
116
+ error: (err as Error).message,
117
+ },
118
+ }
119
+ : { visible: false };
120
+ }
121
+ }
@@ -1,5 +1,5 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- export * from './evaluate';
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ export * from './evaluate';
package/src/index.ts CHANGED
@@ -1,25 +1,25 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- /**
6
- * @selfhelp/shared — public surface.
7
- *
8
- * Each subpath also has its own export:
9
- * - `@selfhelp/shared/registry`
10
- * - `@selfhelp/shared/theme`
11
- * - `@selfhelp/shared/tailwind`
12
- *
13
- * The default export aggregates everything so consumers can do:
14
- * import { STYLE_REGISTRY, replaceCalcedValues, ENDPOINTS } from '@selfhelp/shared';
15
- */
16
-
17
- export * from './types';
18
- export * from './registry';
19
- export * from './api';
20
- export * from './theme';
21
- export * from './interpolation';
22
- export * from './condition';
23
- export * from './cms-classes';
24
- export * from './assets';
25
- export * from './utils';
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * @selfhelp/shared — public surface.
7
+ *
8
+ * Each subpath also has its own export:
9
+ * - `@selfhelp/shared/registry`
10
+ * - `@selfhelp/shared/theme`
11
+ * - `@selfhelp/shared/tailwind`
12
+ *
13
+ * The default export aggregates everything so consumers can do:
14
+ * import { STYLE_REGISTRY, replaceCalcedValues, ENDPOINTS } from '@selfhelp/shared';
15
+ */
16
+
17
+ export * from './types';
18
+ export * from './registry';
19
+ export * from './api';
20
+ export * from './theme';
21
+ export * from './interpolation';
22
+ export * from './condition';
23
+ export * from './cms-classes';
24
+ export * from './assets';
25
+ export * from './utils';
@@ -1,41 +1,41 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- import { describe, it, expect } from 'vitest';
6
- import { replaceCalcedValues } from '../replaceCalcedValues';
7
-
8
- describe('replaceCalcedValues', () => {
9
- it('replaces a single {{name}} placeholder with its value', () => {
10
- expect(replaceCalcedValues('Hello {{name}}!', { name: 'Ada' })).toBe('Hello Ada!');
11
- });
12
-
13
- it('replaces the double-brace {{{{name}}}} form (backend regex parity)', () => {
14
- expect(replaceCalcedValues('{{{{score}}}}', { score: 42 })).toBe('42');
15
- });
16
-
17
- it('coerces number and boolean values to strings', () => {
18
- expect(replaceCalcedValues('{{count}}/{{active}}', { count: 3, active: true })).toBe('3/true');
19
- });
20
-
21
- it('leaves unknown placeholders intact so editors notice them', () => {
22
- expect(replaceCalcedValues('Hi {{missing}}', { name: 'Ada' })).toBe('Hi {{missing}}');
23
- });
24
-
25
- it('leaves the placeholder intact when the value is null or undefined', () => {
26
- expect(replaceCalcedValues('{{a}}{{b}}', { a: null, b: undefined })).toBe('{{a}}{{b}}');
27
- });
28
-
29
- it('returns an empty string for null/undefined input (never renders "undefined")', () => {
30
- expect(replaceCalcedValues(null, {})).toBe('');
31
- expect(replaceCalcedValues(undefined, {})).toBe('');
32
- });
33
-
34
- it('trims whitespace inside the braces before lookup', () => {
35
- expect(replaceCalcedValues('{{ name }}', { name: 'Ada' })).toBe('Ada');
36
- });
37
-
38
- it('replaces multiple placeholders in one pass', () => {
39
- expect(replaceCalcedValues('{{a}} and {{b}}', { a: 'x', b: 'y' })).toBe('x and y');
40
- });
41
- });
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { describe, it, expect } from 'vitest';
6
+ import { replaceCalcedValues } from '../replaceCalcedValues';
7
+
8
+ describe('replaceCalcedValues', () => {
9
+ it('replaces a single {{name}} placeholder with its value', () => {
10
+ expect(replaceCalcedValues('Hello {{name}}!', { name: 'Ada' })).toBe('Hello Ada!');
11
+ });
12
+
13
+ it('replaces the double-brace {{{{name}}}} form (backend regex parity)', () => {
14
+ expect(replaceCalcedValues('{{{{score}}}}', { score: 42 })).toBe('42');
15
+ });
16
+
17
+ it('coerces number and boolean values to strings', () => {
18
+ expect(replaceCalcedValues('{{count}}/{{active}}', { count: 3, active: true })).toBe('3/true');
19
+ });
20
+
21
+ it('leaves unknown placeholders intact so editors notice them', () => {
22
+ expect(replaceCalcedValues('Hi {{missing}}', { name: 'Ada' })).toBe('Hi {{missing}}');
23
+ });
24
+
25
+ it('leaves the placeholder intact when the value is null or undefined', () => {
26
+ expect(replaceCalcedValues('{{a}}{{b}}', { a: null, b: undefined })).toBe('{{a}}{{b}}');
27
+ });
28
+
29
+ it('returns an empty string for null/undefined input (never renders "undefined")', () => {
30
+ expect(replaceCalcedValues(null, {})).toBe('');
31
+ expect(replaceCalcedValues(undefined, {})).toBe('');
32
+ });
33
+
34
+ it('trims whitespace inside the braces before lookup', () => {
35
+ expect(replaceCalcedValues('{{ name }}', { name: 'Ada' })).toBe('Ada');
36
+ });
37
+
38
+ it('replaces multiple placeholders in one pass', () => {
39
+ expect(replaceCalcedValues('{{a}} and {{b}}', { a: 'x', b: 'y' })).toBe('x and y');
40
+ });
41
+ });
@@ -1,5 +1,5 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- export * from './replaceCalcedValues';
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ export * from './replaceCalcedValues';
@@ -1,27 +1,27 @@
1
- /*
2
- SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
- SPDX-License-Identifier: MPL-2.0
4
- */
5
- /**
6
- * Mirrors the backend `PageDb::replace_calced_values()` regex:
7
- *
8
- * ~{{({{)?(.*?)(}})?}}~s
9
- *
10
- * Replaces every `{{name}}` or `{{{{name}}}}` occurrence in the input
11
- * string with `values[name]`. Unknown placeholders are left intact so
12
- * editors notice them and so we never accidentally render `undefined`.
13
- */
14
-
15
- const PLACEHOLDER_RE = /{{({{)?([^{}]+?)(}})?}}/g;
16
-
17
- export type TCalcedValues = Record<string, string | number | boolean | null | undefined>;
18
-
19
- export function replaceCalcedValues(input: string | null | undefined, values: TCalcedValues): string {
20
- if (input === null || input === undefined) return '';
21
- return String(input).replace(PLACEHOLDER_RE, (full, _open, key) => {
22
- const trimmed = String(key).trim();
23
- const value = values[trimmed];
24
- if (value === undefined || value === null) return full;
25
- return String(value);
26
- });
27
- }
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Mirrors the backend `PageDb::replace_calced_values()` regex:
7
+ *
8
+ * ~{{({{)?(.*?)(}})?}}~s
9
+ *
10
+ * Replaces every `{{name}}` or `{{{{name}}}}` occurrence in the input
11
+ * string with `values[name]`. Unknown placeholders are left intact so
12
+ * editors notice them and so we never accidentally render `undefined`.
13
+ */
14
+
15
+ const PLACEHOLDER_RE = /{{({{)?([^{}]+?)(}})?}}/g;
16
+
17
+ export type TCalcedValues = Record<string, string | number | boolean | null | undefined>;
18
+
19
+ export function replaceCalcedValues(input: string | null | undefined, values: TCalcedValues): string {
20
+ if (input === null || input === undefined) return '';
21
+ return String(input).replace(PLACEHOLDER_RE, (full, _open, key) => {
22
+ const trimmed = String(key).trim();
23
+ const value = values[trimmed];
24
+ if (value === undefined || value === null) return full;
25
+ return String(value);
26
+ });
27
+ }