@pithyjs/core 0.1.0-beta.13 → 0.1.0-beta.14

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 (39) hide show
  1. package/README.md +3 -1
  2. package/dist/a11y/focus-trap.d.ts +11 -3
  3. package/dist/a11y/focus-trap.d.ts.map +1 -1
  4. package/dist/a11y/focus-trap.js +53 -10
  5. package/dist/a11y/focus-trap.js.map +1 -1
  6. package/dist/compile/bindSwitchCases.d.ts.map +1 -1
  7. package/dist/compile/bindSwitchCases.js +15 -1
  8. package/dist/compile/bindSwitchCases.js.map +1 -1
  9. package/dist/compile/binds/bindAfterProjection.d.ts +7 -0
  10. package/dist/compile/binds/bindAfterProjection.d.ts.map +1 -0
  11. package/dist/compile/binds/bindAfterProjection.js +32 -0
  12. package/dist/compile/binds/bindAfterProjection.js.map +1 -0
  13. package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
  14. package/dist/compile/binds/bindComponentsTags.js +9 -1
  15. package/dist/compile/binds/bindComponentsTags.js.map +1 -1
  16. package/dist/compile/compileTemplate.d.ts.map +1 -1
  17. package/dist/compile/compileTemplate.js +3 -24
  18. package/dist/compile/compileTemplate.js.map +1 -1
  19. package/dist/compile/contentProjection.d.ts +9 -0
  20. package/dist/compile/contentProjection.d.ts.map +1 -1
  21. package/dist/compile/contentProjection.js +34 -0
  22. package/dist/compile/contentProjection.js.map +1 -1
  23. package/dist/compile/renderBranch.js +1 -1
  24. package/dist/compile/renderBranch.js.map +1 -1
  25. package/dist/compile/renderChildren.d.ts +3 -1
  26. package/dist/compile/renderChildren.d.ts.map +1 -1
  27. package/dist/compile/renderChildren.js +6 -0
  28. package/dist/compile/renderChildren.js.map +1 -1
  29. package/dist/runtime/applyBindings.d.ts +6 -2
  30. package/dist/runtime/applyBindings.d.ts.map +1 -1
  31. package/dist/runtime/applyBindings.js +41 -22
  32. package/dist/runtime/applyBindings.js.map +1 -1
  33. package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
  34. package/dist/runtime/bindings/applyComponent.js +2 -0
  35. package/dist/runtime/bindings/applyComponent.js.map +1 -1
  36. package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
  37. package/dist/runtime/bindings/applySimple.js +3 -2
  38. package/dist/runtime/bindings/applySimple.js.map +1 -1
  39. package/package.json +3 -3
package/README.md CHANGED
@@ -352,7 +352,8 @@ The `@for` directive provides keyed, reactive list rendering with:
352
352
  | --- | --- | --- | --- | --- |
353
353
  | FocusTrap | focus-trap | `class FocusTrap` | stable | Focus Trap Instance Manages focus containment within an element for accessible modals/dialogs |
354
354
  | activate | focus-trap | `activate(): void` | stable | - |
355
- | deactivate | focus-trap | `deactivate(): void` | stable | - |
355
+ | deactivate | focus-trap | `deactivate(options?: { holdScrollLock?: boolean }): void` | stable | - |
356
+ | releaseScrollLock | focus-trap | `releaseScrollLock(): void` | stable | - |
356
357
  | updateFocusableElements | focus-trap | `updateFocusableElements(): void` | stable | - |
357
358
  | isActivated | focus-trap | `isActivated(): boolean` | stable | - |
358
359
  | destroy | focus-trap | `destroy(): void` | stable | - |
@@ -499,6 +500,7 @@ pnpm test -- --watch # Watch mode
499
500
  | FocusTrap | ✓ | - | - | Missing integration |
500
501
  | activate | ✓ | - | - | Missing integration |
501
502
  | deactivate | ✓ | - | - | Missing integration |
503
+ | releaseScrollLock | ✓ | - | - | Missing integration |
502
504
  | updateFocusableElements | ✓ | - | - | Missing integration |
503
505
  | isActivated | ✓ | - | - | Missing integration |
504
506
  | destroy | ✓ | - | - | Missing integration |
@@ -37,6 +37,7 @@ export declare class FocusTrap {
37
37
  private focusableElements;
38
38
  private keydownHandler;
39
39
  private clickHandler;
40
+ private holdsScrollLock;
40
41
  /**
41
42
  * Selector for focusable elements
42
43
  * Based on what browsers consider naturally focusable
@@ -49,12 +50,19 @@ export declare class FocusTrap {
49
50
  * Traps keyboard focus within the element
50
51
  */
51
52
  activate(): void;
52
- /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"deactivate","stability":"stable","signature":"deactivate(): void"} */
53
+ /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"deactivate","stability":"stable","signature":"deactivate(options?: { holdScrollLock?: boolean }): void"} */
53
54
  /**
54
55
  * Deactivate the focus trap
55
- * Returns focus to the previously focused element
56
+ * Returns focus to the previously focused element. With `holdScrollLock`,
57
+ * the page stays locked until `releaseScrollLock()`, e.g. while a dialog
58
+ * animates out after giving focus back.
56
59
  */
57
- deactivate(): void;
60
+ deactivate(options?: {
61
+ holdScrollLock?: boolean;
62
+ }): void;
63
+ /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"releaseScrollLock","stability":"stable","signature":"releaseScrollLock(): void"} */
64
+ /** Release a scroll lock kept by `deactivate({ holdScrollLock: true })`. */
65
+ releaseScrollLock(): void;
58
66
  /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"updateFocusableElements","stability":"stable","signature":"updateFocusableElements(): void"} */
59
67
  /**
60
68
  * Update the list of focusable elements
@@ -1 +1 @@
1
- {"version":3,"file":"focus-trap.d.ts","sourceRoot":"","sources":["../../src/a11y/focus-trap.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4FAA4F;IAC5F,YAAY,CAAC,EAAE,WAAW,GAAG,MAAM,CAAC;IACpC,iGAAiG;IACjG,WAAW,CAAC,EAAE,WAAW,GAAG,MAAM,CAAC;IACnC,4DAA4D;IAC5D,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,qDAAqD;IACrD,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,sCAAsC;IACtC,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,wCAAwC;IACxC,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAC1B,4EAA4E;IAC5E,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,yHAAyH;AACzH;;;GAGG;AACH,qBAAa,SAAS;IACpB,OAAO,CA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AO,CAAC,aAAa;IAerB;;OAEG;IACH,OAAO,CAAC,YAAY;IA2BpB;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAM1B,kIAAkI;IAClI;;OAEG;IACH,WAAW,IAAI,OAAO;IAItB,uHAAuH;IACvH;;OAEG;IACH,OAAO,IAAI,IAAI;CAMhB;AAED,+KAA+K;AAC/K;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,gBAAgB,GACzB,SAAS,CAEX"}
@@ -5,6 +5,38 @@
5
5
  "category": "feature"
6
6
  }
7
7
  */
8
+ // One lock shared by every trap: traps overlap when a dialog exits while the
9
+ // next one opens, and only the last release may restore the body.
10
+ let scrollLocks = 0;
11
+ let savedBody = null;
12
+ function lockScroll() {
13
+ if (scrollLocks++ > 0)
14
+ return;
15
+ const body = document.body;
16
+ const root = document.documentElement;
17
+ savedBody = {
18
+ overflow: body.style.overflow,
19
+ paddingRight: body.style.paddingRight,
20
+ };
21
+ const width = () => root.getBoundingClientRect().width;
22
+ const before = width();
23
+ const padding = getComputedStyle(body).paddingRight || '0px';
24
+ body.style.overflow = 'hidden';
25
+ // Pad by the width the hidden scrollbar gave back, so the page stays put. A
26
+ // `scrollbar-gutter: stable` gutter stays reserved and gives back nothing;
27
+ // the root's box shows that, where Chromium's clientWidth does not.
28
+ const released = width() - before;
29
+ if (before > 0 && released > 0) {
30
+ body.style.paddingRight = `calc(${padding} + ${released}px)`;
31
+ }
32
+ }
33
+ function unlockScroll() {
34
+ if (scrollLocks === 0 || --scrollLocks > 0 || !savedBody)
35
+ return;
36
+ document.body.style.overflow = savedBody.overflow;
37
+ document.body.style.paddingRight = savedBody.paddingRight;
38
+ savedBody = null;
39
+ }
8
40
  /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"FocusTrap","stability":"stable","signature":"class FocusTrap"} */
9
41
  /**
10
42
  * Focus Trap Instance
@@ -18,6 +50,7 @@ export class FocusTrap {
18
50
  // Event handlers stored for cleanup
19
51
  this.keydownHandler = null;
20
52
  this.clickHandler = null;
53
+ this.holdsScrollLock = false;
21
54
  this.element = element;
22
55
  this.options = {
23
56
  initialFocus: options.initialFocus ?? undefined,
@@ -49,21 +82,24 @@ export class FocusTrap {
49
82
  this.clickHandler = (e) => this.handleClickOutside(e);
50
83
  document.addEventListener('click', this.clickHandler, true);
51
84
  }
52
- // Prevent body scroll if enabled
53
- if (this.options.preventScroll) {
54
- document.body.style.overflow = 'hidden';
85
+ // A lock held over from `deactivate({ holdScrollLock: true })` is reused.
86
+ if (this.options.preventScroll && !this.holdsScrollLock) {
87
+ lockScroll();
88
+ this.holdsScrollLock = true;
55
89
  }
56
90
  // Focus initial element
57
91
  this.focusInitialElement();
58
92
  this.isActive = true;
59
93
  this.options.onActivate();
60
94
  }
61
- /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"deactivate","stability":"stable","signature":"deactivate(): void"} */
95
+ /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"deactivate","stability":"stable","signature":"deactivate(options?: { holdScrollLock?: boolean }): void"} */
62
96
  /**
63
97
  * Deactivate the focus trap
64
- * Returns focus to the previously focused element
98
+ * Returns focus to the previously focused element. With `holdScrollLock`,
99
+ * the page stays locked until `releaseScrollLock()`, e.g. while a dialog
100
+ * animates out after giving focus back.
65
101
  */
66
- deactivate() {
102
+ deactivate(options = {}) {
67
103
  if (!this.isActive)
68
104
  return;
69
105
  // Remove event listeners
@@ -75,10 +111,8 @@ export class FocusTrap {
75
111
  document.removeEventListener('click', this.clickHandler, true);
76
112
  this.clickHandler = null;
77
113
  }
78
- // Restore body scroll
79
- if (this.options.preventScroll) {
80
- document.body.style.overflow = '';
81
- }
114
+ if (!options.holdScrollLock)
115
+ this.releaseScrollLock();
82
116
  // Return focus to previously focused element
83
117
  const returnTarget = this.getReturnFocusTarget();
84
118
  if (returnTarget && returnTarget.focus) {
@@ -87,6 +121,14 @@ export class FocusTrap {
87
121
  this.isActive = false;
88
122
  this.options.onDeactivate();
89
123
  }
124
+ /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"releaseScrollLock","stability":"stable","signature":"releaseScrollLock(): void"} */
125
+ /** Release a scroll lock kept by `deactivate({ holdScrollLock: true })`. */
126
+ releaseScrollLock() {
127
+ if (!this.holdsScrollLock)
128
+ return;
129
+ unlockScroll();
130
+ this.holdsScrollLock = false;
131
+ }
90
132
  /** @codexApi {"parent":"pithy.a11y.focus-trap","name":"updateFocusableElements","stability":"stable","signature":"updateFocusableElements(): void"} */
91
133
  /**
92
134
  * Update the list of focusable elements
@@ -216,6 +258,7 @@ export class FocusTrap {
216
258
  */
217
259
  destroy() {
218
260
  this.deactivate();
261
+ this.releaseScrollLock();
219
262
  this.focusableElements = [];
220
263
  this.previouslyFocusedElement = null;
221
264
  }
@@ -1 +1 @@
1
- {"version":3,"file":"focus-trap.js","sourceRoot":"","sources":["../../src/a11y/focus-trap.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAsBF,yHAAyH;AACzH;;;GAGG;AACH,MAAM,OAAO,SAAS;IA6BpB,YAAY,OAAoB,EAAE,UAA4B,EAAE;QA1BxD,aAAQ,GAAY,KAAK,CAAC;QAC1B,6BAAwB,GAAuB,IAAI,CAAC;QACpD,sBAAiB,GAAkB,EAAE,CAAC;QAE9C,oCAAoC;QAC5B,mBAAc,GAAwC,IAAI,CAAC;QAC3D,iBAAY,GAAqC,IAAI,CAAC;QAqB5D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG;YACb,YAAY,EAAE,OAAO,CAAC,YAAY,IAAI,SAAS;YAC/C,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,SAAS;YAC7C,uBAAuB,EAAE,OAAO,CAAC,uBAAuB,IAAI,KAAK;YACjE,iBAAiB,EAAE,OAAO,CAAC,iBAAiB,IAAI,IAAI;YACpD,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,CAAC,GAAG,EAAE,GAAE,CAAC,CA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AC,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,KAAK,WAAW,EAAE,CAAC;YAC1D,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,YAAY,CAAC,KAAK,EAAE,CAAC;YACrB,OAAO;QACT,CAAC;IACH,CAAC;IAED;;OAEG;IACK,kBAAkB,CAAC,CAAa;QACtC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAc,CAAC,EAAE,CAAC;YAC7C,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,CAAC;IACH,CAAC;IAED,kIAAkI;IAClI;;OAEG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,uHAAuH;IACvH;;OAEG;IACH,OAAO;QACL,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,IAAI,CAAC,iBAAiB,GAAG,EAAE,CAAC;QAC5B,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC;IACvC,CAAC;;AA9PD;;;GAGG;AACqB,4BAAkB,GAAG;IAC3C,SAAS;IACT,YAAY;IACZ,uBAAuB;IACvB,wBAAwB;IACxB,0BAA0B;IAC1B,wBAAwB;IACxB,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,iCAAiC;IACjC,0BAA0B;CAC3B,CAAC,IAAI,CAAC,GAAG,CAAC,AAZ+B,CAY9B;AAiPd,+KAA+K;AAC/K;;;GAGG;AACH,MAAM,UAAU,eAAe,CAC7B,OAAoB,EACpB,OAA0B;IAE1B,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AACzC,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.a11y.focus-trap\",\n \"title\": \"Focus Trap Utility - Accessible Modal/Dialog Support\",\n \"category\": \"feature\"\n}\n*/\n\n/**\n * Focus Trap Configuration\n */\nexport interface FocusTrapOptions {\n /** Element to receive focus when trap is activated (defaults to first focusable element) */\n initialFocus?: HTMLElement | string;\n /** Element to receive focus when trap is deactivated (defaults to previously focused element) */\n returnFocus?: HTMLElement | string;\n /** Allow clicking outside to deactivate (default: false) */\n clickOutsideDeactivates?: boolean;\n /** Allow escape key to deactivate (default: true) */\n escapeDeactivates?: boolean;\n /** Callback when trap is activated */\n onActivate?: () => void;\n /** Callback when trap is deactivated */\n onDeactivate?: () => void;\n /** Whether to prevent scroll on body when trap is active (default: true) */\n preventScroll?: boolean;\n}\n\n/** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"FocusTrap\",\"stability\":\"stable\",\"signature\":\"class FocusTrap\"} */\n/**\n * Focus Trap Instance\n * Manages focus containment within an element for accessible modals/dialogs\n */\nexport class FocusTrap {\n private element: HTMLElement;\n private options: Required<FocusTrapOptions>;\n private isActive: boolean = false;\n private previouslyFocusedElement: HTMLElement | null = null;\n private focusableElements: HTMLElement[] = [];\n\n // Event handlers stored for cleanup\n private keydownHandler: ((e: KeyboardEvent) => void) | null = null;\n private clickHandler: ((e: MouseEvent) => void) | null = null;\n\n /**\n * Selector for focusable elements\n * Based on what browsers consider naturally focusable\n */\n private static readonly FOCUSABLE_SELECTOR = [\n 'a[href]',\n 'area[href]',\n 'input:not([disabled])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n 'button:not([disabled])',\n 'iframe',\n 'object',\n 'embed',\n '[tabindex]:not([tabindex=\"-1\"])',\n '[contenteditable=\"true\"]',\n ].join(',');\n\n constructor(element: HTMLElement, options: FocusTrapOptions = {}) {\n this.element = element;\n this.options = {\n initialFocus: options.initialFocus ?? undefined,\n returnFocus: options.returnFocus ?? undefined,\n clickOutsideDeactivates: options.clickOutsideDeactivates ?? false,\n escapeDeactivates: options.escapeDeactivates ?? true,\n onActivate: options.onActivate ?? (() => {}),\n onDeactivate: options.onDeactivate ?? (() => {}),\n preventScroll: options.preventScroll ?? true,\n } as Required<FocusTrapOptions>;\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"activate\",\"stability\":\"stable\",\"signature\":\"activate(): void\"} */\n /**\n * Activate the focus trap\n * Traps keyboard focus within the element\n */\n activate(): void {\n if (this.isActive) return;\n\n // Store currently focused element to return to later\n this.previouslyFocusedElement = document.activeElement as HTMLElement;\n\n // Update focusable elements list\n this.updateFocusableElements();\n\n // Set up keyboard navigation\n this.keydownHandler = (e: KeyboardEvent) => this.handleKeydown(e);\n document.addEventListener('keydown', this.keydownHandler);\n\n // Set up click outside handler if enabled\n if (this.options.clickOutsideDeactivates) {\n this.clickHandler = (e: MouseEvent) => this.handleClickOutside(e);\n document.addEventListener('click', this.clickHandler, true);\n }\n\n // Prevent body scroll if enabled\n if (this.options.preventScroll) {\n document.body.style.overflow = 'hidden';\n }\n\n // Focus initial element\n this.focusInitialElement();\n\n this.isActive = true;\n this.options.onActivate();\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"deactivate\",\"stability\":\"stable\",\"signature\":\"deactivate(): void\"} */\n /**\n * Deactivate the focus trap\n * Returns focus to the previously focused element\n */\n deactivate(): void {\n if (!this.isActive) return;\n\n // Remove event listeners\n if (this.keydownHandler) {\n document.removeEventListener('keydown', this.keydownHandler);\n this.keydownHandler = null;\n }\n if (this.clickHandler) {\n document.removeEventListener('click', this.clickHandler, true);\n this.clickHandler = null;\n }\n\n // Restore body scroll\n if (this.options.preventScroll) {\n document.body.style.overflow = '';\n }\n\n // Return focus to previously focused element\n const returnTarget = this.getReturnFocusTarget();\n if (returnTarget && returnTarget.focus) {\n returnTarget.focus();\n }\n\n this.isActive = false;\n this.options.onDeactivate();\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"updateFocusableElements\",\"stability\":\"stable\",\"signature\":\"updateFocusableElements(): void\"} */\n /**\n * Update the list of focusable elements\n * Call this if the DOM within the trap changes\n */\n updateFocusableElements(): void {\n const elements = Array.from(\n this.element.querySelectorAll(FocusTrap.FOCUSABLE_SELECTOR)\n ) as HTMLElement[];\n\n // Filter out hidden or disabled elements\n this.focusableElements = elements.filter(el => {\n return (\n el.offsetWidth > 0 &&\n el.offsetHeight > 0 &&\n !el.hasAttribute('disabled') &&\n window.getComputedStyle(el).visibility !== 'hidden'\n );\n });\n }\n\n /**\n * Get the first focusable element in the trap\n */\n private getFirstFocusableElement(): HTMLElement | null {\n return this.focusableElements[0] || null;\n }\n\n /**\n * Get the last focusable element in the trap\n */\n private getLastFocusableElement(): HTMLElement | null {\n return this.focusableElements[this.focusableElements.length - 1] || null;\n }\n\n /**\n * Focus the initial element based on options\n */\n private focusInitialElement(): void {\n let target: HTMLElement | null = null;\n\n // Check if initialFocus is specified\n if (this.options.initialFocus) {\n if (typeof this.options.initialFocus === 'string') {\n target = this.element.querySelector(\n this.options.initialFocus\n ) as HTMLElement;\n } else {\n target = this.options.initialFocus;\n }\n }\n\n // Fallback to first focusable element\n if (!target) {\n target = this.getFirstFocusableElement();\n }\n\n // Fallback to the container itself\n if (!target) {\n target = this.element;\n target.setAttribute('tabindex', '-1');\n }\n\n if (target && target.focus) {\n target.focus();\n }\n }\n\n /**\n * Get the element to return focus to\n */\n private getReturnFocusTarget(): HTMLElement | null {\n if (this.options.returnFocus) {\n if (typeof this.options.returnFocus === 'string') {\n return document.querySelector(this.options.returnFocus) as HTMLElement;\n }\n return this.options.returnFocus;\n }\n return this.previouslyFocusedElement;\n }\n\n /**\n * Handle keydown events for focus trapping\n */\n private handleKeydown(e: KeyboardEvent): void {\n // Handle Escape key\n if (e.key === 'Escape' && this.options.escapeDeactivates) {\n e.preventDefault();\n e.stopPropagation();\n this.deactivate();\n return;\n }\n\n // Handle Tab key\n if (e.key === 'Tab') {\n this.handleTabKey(e);\n }\n }\n\n /**\n * Handle Tab key for focus cycling\n */\n private handleTabKey(e: KeyboardEvent): void {\n // Re-read: content swapped since activation would leave detached ends.\n this.updateFocusableElements();\n const firstElement = this.getFirstFocusableElement();\n const lastElement = this.getLastFocusableElement();\n\n if (!firstElement || !lastElement) {\n // No focusable elements, prevent tabbing out\n e.preventDefault();\n return;\n }\n\n // Shift+Tab on first element -> focus last\n if (e.shiftKey && document.activeElement === firstElement) {\n e.preventDefault();\n lastElement.focus();\n return;\n }\n\n // Tab on last element -> focus first\n if (!e.shiftKey && document.activeElement === lastElement) {\n e.preventDefault();\n firstElement.focus();\n return;\n }\n }\n\n /**\n * Handle clicks outside the trapped element\n */\n private handleClickOutside(e: MouseEvent): void {\n if (!this.element.contains(e.target as Node)) {\n this.deactivate();\n }\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"isActivated\",\"stability\":\"stable\",\"signature\":\"isActivated(): boolean\"} */\n /**\n * Check if the trap is currently active\n */\n isActivated(): boolean {\n return this.isActive;\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"destroy\",\"stability\":\"stable\",\"signature\":\"destroy(): void\"} */\n /**\n * Destroy the focus trap and clean up resources\n */\n destroy(): void {\n this.deactivate();\n this.focusableElements = [];\n this.previouslyFocusedElement = null;\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"createFocusTrap\",\"stability\":\"stable\",\"signature\":\"(element: HTMLElement, options?: FocusTrapOptions) => FocusTrap\"} */\n/**\n * Create a focus trap for an element\n * Convenience function for creating and activating a focus trap\n */\nexport function createFocusTrap(\n element: HTMLElement,\n options?: FocusTrapOptions\n): FocusTrap {\n return new FocusTrap(element, options);\n}\n"]}
1
+ {"version":3,"file":"focus-trap.js","sourceRoot":"","sources":["../../src/a11y/focus-trap.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAsBF,6EAA6E;AAC7E,kEAAkE;AAClE,IAAI,WAAW,GAAG,CAAC,CAAC;AACpB,IAAI,SAAS,GAAsD,IAAI,CAAC;AAExE,SAAS,UAAU;IACjB,IAAI,WAAW,EAAE,GAAG,CAAC;QAAE,OAAO;IAC9B,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;IAC3B,MAAM,IAA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AI,CAAC;IACvC,CAAC;;AAvQD;;;GAGG;AACqB,4BAAkB,GAAG;IAC3C,SAAS;IACT,YAAY;IACZ,uBAAuB;IACvB,wBAAwB;IACxB,0BAA0B;IAC1B,wBAAwB;IACxB,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,iCAAiC;IACjC,0BAA0B;CAC3B,CAAC,IAAI,CAAC,GAAG,CAAC,AAZ+B,CAY9B;AA0Pd,+KAA+K;AAC/K;;;GAGG;AACH,MAAM,UAAU,eAAe,CAC7B,OAAoB,EACpB,OAA0B;IAE1B,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AACzC,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.a11y.focus-trap\",\n \"title\": \"Focus Trap Utility - Accessible Modal/Dialog Support\",\n \"category\": \"feature\"\n}\n*/\n\n/**\n * Focus Trap Configuration\n */\nexport interface FocusTrapOptions {\n /** Element to receive focus when trap is activated (defaults to first focusable element) */\n initialFocus?: HTMLElement | string;\n /** Element to receive focus when trap is deactivated (defaults to previously focused element) */\n returnFocus?: HTMLElement | string;\n /** Allow clicking outside to deactivate (default: false) */\n clickOutsideDeactivates?: boolean;\n /** Allow escape key to deactivate (default: true) */\n escapeDeactivates?: boolean;\n /** Callback when trap is activated */\n onActivate?: () => void;\n /** Callback when trap is deactivated */\n onDeactivate?: () => void;\n /** Whether to prevent scroll on body when trap is active (default: true) */\n preventScroll?: boolean;\n}\n\n// One lock shared by every trap: traps overlap when a dialog exits while the\n// next one opens, and only the last release may restore the body.\nlet scrollLocks = 0;\nlet savedBody: { overflow: string; paddingRight: string } | null = null;\n\nfunction lockScroll(): void {\n if (scrollLocks++ > 0) return;\n const body = document.body;\n const root = document.documentElement;\n savedBody = {\n overflow: body.style.overflow,\n paddingRight: body.style.paddingRight,\n };\n const width = () => root.getBoundingClientRect().width;\n const before = width();\n const padding = getComputedStyle(body).paddingRight || '0px';\n body.style.overflow = 'hidden';\n // Pad by the width the hidden scrollbar gave back, so the page stays put. A\n // `scrollbar-gutter: stable` gutter stays reserved and gives back nothing;\n // the root's box shows that, where Chromium's clientWidth does not.\n const released = width() - before;\n if (before > 0 && released > 0) {\n body.style.paddingRight = `calc(${padding} + ${released}px)`;\n }\n}\n\nfunction unlockScroll(): void {\n if (scrollLocks === 0 || --scrollLocks > 0 || !savedBody) return;\n document.body.style.overflow = savedBody.overflow;\n document.body.style.paddingRight = savedBody.paddingRight;\n savedBody = null;\n}\n\n/** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"FocusTrap\",\"stability\":\"stable\",\"signature\":\"class FocusTrap\"} */\n/**\n * Focus Trap Instance\n * Manages focus containment within an element for accessible modals/dialogs\n */\nexport class FocusTrap {\n private element: HTMLElement;\n private options: Required<FocusTrapOptions>;\n private isActive: boolean = false;\n private previouslyFocusedElement: HTMLElement | null = null;\n private focusableElements: HTMLElement[] = [];\n\n // Event handlers stored for cleanup\n private keydownHandler: ((e: KeyboardEvent) => void) | null = null;\n private clickHandler: ((e: MouseEvent) => void) | null = null;\n private holdsScrollLock = false;\n\n /**\n * Selector for focusable elements\n * Based on what browsers consider naturally focusable\n */\n private static readonly FOCUSABLE_SELECTOR = [\n 'a[href]',\n 'area[href]',\n 'input:not([disabled])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n 'button:not([disabled])',\n 'iframe',\n 'object',\n 'embed',\n '[tabindex]:not([tabindex=\"-1\"])',\n '[contenteditable=\"true\"]',\n ].join(',');\n\n constructor(element: HTMLElement, options: FocusTrapOptions = {}) {\n this.element = element;\n this.options = {\n initialFocus: options.initialFocus ?? undefined,\n returnFocus: options.returnFocus ?? undefined,\n clickOutsideDeactivates: options.clickOutsideDeactivates ?? false,\n escapeDeactivates: options.escapeDeactivates ?? true,\n onActivate: options.onActivate ?? (() => {}),\n onDeactivate: options.onDeactivate ?? (() => {}),\n preventScroll: options.preventScroll ?? true,\n } as Required<FocusTrapOptions>;\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"activate\",\"stability\":\"stable\",\"signature\":\"activate(): void\"} */\n /**\n * Activate the focus trap\n * Traps keyboard focus within the element\n */\n activate(): void {\n if (this.isActive) return;\n\n // Store currently focused element to return to later\n this.previouslyFocusedElement = document.activeElement as HTMLElement;\n\n // Update focusable elements list\n this.updateFocusableElements();\n\n // Set up keyboard navigation\n this.keydownHandler = (e: KeyboardEvent) => this.handleKeydown(e);\n document.addEventListener('keydown', this.keydownHandler);\n\n // Set up click outside handler if enabled\n if (this.options.clickOutsideDeactivates) {\n this.clickHandler = (e: MouseEvent) => this.handleClickOutside(e);\n document.addEventListener('click', this.clickHandler, true);\n }\n\n // A lock held over from `deactivate({ holdScrollLock: true })` is reused.\n if (this.options.preventScroll && !this.holdsScrollLock) {\n lockScroll();\n this.holdsScrollLock = true;\n }\n\n // Focus initial element\n this.focusInitialElement();\n\n this.isActive = true;\n this.options.onActivate();\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"deactivate\",\"stability\":\"stable\",\"signature\":\"deactivate(options?: { holdScrollLock?: boolean }): void\"} */\n /**\n * Deactivate the focus trap\n * Returns focus to the previously focused element. With `holdScrollLock`,\n * the page stays locked until `releaseScrollLock()`, e.g. while a dialog\n * animates out after giving focus back.\n */\n deactivate(options: { holdScrollLock?: boolean } = {}): void {\n if (!this.isActive) return;\n\n // Remove event listeners\n if (this.keydownHandler) {\n document.removeEventListener('keydown', this.keydownHandler);\n this.keydownHandler = null;\n }\n if (this.clickHandler) {\n document.removeEventListener('click', this.clickHandler, true);\n this.clickHandler = null;\n }\n\n if (!options.holdScrollLock) this.releaseScrollLock();\n\n // Return focus to previously focused element\n const returnTarget = this.getReturnFocusTarget();\n if (returnTarget && returnTarget.focus) {\n returnTarget.focus();\n }\n\n this.isActive = false;\n this.options.onDeactivate();\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"releaseScrollLock\",\"stability\":\"stable\",\"signature\":\"releaseScrollLock(): void\"} */\n /** Release a scroll lock kept by `deactivate({ holdScrollLock: true })`. */\n releaseScrollLock(): void {\n if (!this.holdsScrollLock) return;\n unlockScroll();\n this.holdsScrollLock = false;\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"updateFocusableElements\",\"stability\":\"stable\",\"signature\":\"updateFocusableElements(): void\"} */\n /**\n * Update the list of focusable elements\n * Call this if the DOM within the trap changes\n */\n updateFocusableElements(): void {\n const elements = Array.from(\n this.element.querySelectorAll(FocusTrap.FOCUSABLE_SELECTOR)\n ) as HTMLElement[];\n\n // Filter out hidden or disabled elements\n this.focusableElements = elements.filter(el => {\n return (\n el.offsetWidth > 0 &&\n el.offsetHeight > 0 &&\n !el.hasAttribute('disabled') &&\n window.getComputedStyle(el).visibility !== 'hidden'\n );\n });\n }\n\n /**\n * Get the first focusable element in the trap\n */\n private getFirstFocusableElement(): HTMLElement | null {\n return this.focusableElements[0] || null;\n }\n\n /**\n * Get the last focusable element in the trap\n */\n private getLastFocusableElement(): HTMLElement | null {\n return this.focusableElements[this.focusableElements.length - 1] || null;\n }\n\n /**\n * Focus the initial element based on options\n */\n private focusInitialElement(): void {\n let target: HTMLElement | null = null;\n\n // Check if initialFocus is specified\n if (this.options.initialFocus) {\n if (typeof this.options.initialFocus === 'string') {\n target = this.element.querySelector(\n this.options.initialFocus\n ) as HTMLElement;\n } else {\n target = this.options.initialFocus;\n }\n }\n\n // Fallback to first focusable element\n if (!target) {\n target = this.getFirstFocusableElement();\n }\n\n // Fallback to the container itself\n if (!target) {\n target = this.element;\n target.setAttribute('tabindex', '-1');\n }\n\n if (target && target.focus) {\n target.focus();\n }\n }\n\n /**\n * Get the element to return focus to\n */\n private getReturnFocusTarget(): HTMLElement | null {\n if (this.options.returnFocus) {\n if (typeof this.options.returnFocus === 'string') {\n return document.querySelector(this.options.returnFocus) as HTMLElement;\n }\n return this.options.returnFocus;\n }\n return this.previouslyFocusedElement;\n }\n\n /**\n * Handle keydown events for focus trapping\n */\n private handleKeydown(e: KeyboardEvent): void {\n // Handle Escape key\n if (e.key === 'Escape' && this.options.escapeDeactivates) {\n e.preventDefault();\n e.stopPropagation();\n this.deactivate();\n return;\n }\n\n // Handle Tab key\n if (e.key === 'Tab') {\n this.handleTabKey(e);\n }\n }\n\n /**\n * Handle Tab key for focus cycling\n */\n private handleTabKey(e: KeyboardEvent): void {\n // Re-read: content swapped since activation would leave detached ends.\n this.updateFocusableElements();\n const firstElement = this.getFirstFocusableElement();\n const lastElement = this.getLastFocusableElement();\n\n if (!firstElement || !lastElement) {\n // No focusable elements, prevent tabbing out\n e.preventDefault();\n return;\n }\n\n // Shift+Tab on first element -> focus last\n if (e.shiftKey && document.activeElement === firstElement) {\n e.preventDefault();\n lastElement.focus();\n return;\n }\n\n // Tab on last element -> focus first\n if (!e.shiftKey && document.activeElement === lastElement) {\n e.preventDefault();\n firstElement.focus();\n return;\n }\n }\n\n /**\n * Handle clicks outside the trapped element\n */\n private handleClickOutside(e: MouseEvent): void {\n if (!this.element.contains(e.target as Node)) {\n this.deactivate();\n }\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"isActivated\",\"stability\":\"stable\",\"signature\":\"isActivated(): boolean\"} */\n /**\n * Check if the trap is currently active\n */\n isActivated(): boolean {\n return this.isActive;\n }\n\n /** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"destroy\",\"stability\":\"stable\",\"signature\":\"destroy(): void\"} */\n /**\n * Destroy the focus trap and clean up resources\n */\n destroy(): void {\n this.deactivate();\n this.releaseScrollLock();\n this.focusableElements = [];\n this.previouslyFocusedElement = null;\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.a11y.focus-trap\",\"name\":\"createFocusTrap\",\"stability\":\"stable\",\"signature\":\"(element: HTMLElement, options?: FocusTrapOptions) => FocusTrap\"} */\n/**\n * Create a focus trap for an element\n * Convenience function for creating and activating a focus trap\n */\nexport function createFocusTrap(\n element: HTMLElement,\n options?: FocusTrapOptions\n): FocusTrap {\n return new FocusTrap(element, options);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindSwitchCases.d.ts","sourceRoot":"","sources":["../../src/compile/bindSwitchCases.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAQlE;;;GAGG;AACH,kRAAkR;AAClR,wBAAgB,eAAe,CAC7B,KAAK,EAAE,SAAS,EAAE,EAClB,MAAM,EAAE,OAAO,GAAG,gBAAgB,EAClC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,GAAE,GAAG,CAAC,MAAM,CAAa,EAAE,gCAAgC;AAC3E,SAAS,GAAE,CAAC,MAAM,IAAI,CAAC,EAAO,GAC7B,GAAG,CAAC,MAAM,CAAC,CA0Db;AAUD;;GAEG;AACH,yQAAyQ;AACzQ,wBAAgB,eAAe,CAC7B,UAAU,EAAE,SAAS,EACrB,aAAa,EAAE,OAAO,EACtB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,EAAE,GAAG,CAAC,MAAM,CAAC,EAC7B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,OAAO,CAwCT"}
1
+ {"version":3,"file":"bindSwitchCases.d.ts","sourceRoot":"","sources":["../../src/compile/bindSwitchCases.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAQlE;;;GAGG;AACH,kRAAkR;AAClR,wBAAgB,eAAe,CAC7B,KAAK,EAAE,SAAS,EAAE,EAClB,MAAM,EAAE,OAAO,GAAG,gBAAgB,EAClC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,GAAE,GAAG,CAAC,MAAM,CAAa,EAAE,gCAAgC;AAC3E,SAAS,GAAE,CAAC,MAAM,IAAI,CAAC,EAAO,GAC7B,GAAG,CAAC,MAAM,CAAC,CAyEb;AAUD;;GAEG;AACH,yQAAyQ;AACzQ,wBAAgB,eAAe,CAC7B,UAAU,EAAE,SAAS,EACrB,aAAa,EAAE,OAAO,EACtB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,EAAE,GAAG,CAAC,MAAM,CAAC,EAC7B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,OAAO,CAwCT"}
@@ -34,9 +34,22 @@ disposers = [] // Collect disposers for cleanup
34
34
  }
35
35
  const switchIds = new Set();
36
36
  for (const node of nodes) {
37
- if (node.type !== 'element' || node.directives?.switch === undefined) {
37
+ if (node.type !== 'element')
38
+ continue;
39
+ if ((node.directives?.case !== undefined || isDefaultCase(node)) &&
40
+ node.nodeId &&
41
+ !processedNodeIds.has(node.nodeId) &&
42
+ !isConditionalBranch(node)) {
43
+ processedNodeIds.add(node.nodeId);
44
+ elMap.get(node.nodeId)?.remove();
45
+ if (import.meta.env?.DEV && !warnedOrphans.has(node)) {
46
+ warnedOrphans.add(node);
47
+ console.warn(`[bindSwitchCases] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element (BUG-070); <${node.originalTagName ?? node.tagName}> is dropped, as in a build`);
48
+ }
38
49
  continue;
39
50
  }
51
+ if (node.directives?.switch === undefined)
52
+ continue;
40
53
  if (isConditionalBranch(node))
41
54
  continue;
42
55
  const parentElement = node.nodeId ? elMap.get(node.nodeId) : null;
@@ -106,6 +119,7 @@ export function bindSwitchBlock(switchNode, parentElement, ctx, processedNodeIds
106
119
  return true;
107
120
  }
108
121
  const warnedSwitches = new WeakSet();
122
+ const warnedOrphans = new WeakSet();
109
123
  function removeNonCaseChildren(parentElement, caseElements, switchNode) {
110
124
  const cases = new Set(caseElements);
111
125
  let dropped;
@@ -1 +1 @@
1
- {"version":3,"file":"b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QAEH,2EAA2E;QAC3E,SAAS,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACrC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.switch\",\n \"title\": \"@switch directive\",\n \"category\": \"directive\"\n}\n*/\n\nimport { isDefaultCase, type PithyNode } from '@pithyjs/compiler';\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from './compileExpression';\nimport { findAllNestedLoopNodes } from './forLoops/loopTraversal';\nimport { nodeExpando } from './nodeExpando';\nimport { clearBranch, renderBranch, type Branch } from './renderBranch';\nimport { isSSRMode } from './ssrMode';\n\n/**\n * Processes switch case directives (@switch, @case, @default) in the template.\n * Identifies switch blocks and delegates their handling to handleSwitchBlock.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchCases\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], rootEl: Element | DocumentFragment, ctx: Record<string, unknown>, processedNodeIds?: Set<string>, disposers?: (() => void)[]) => Set<string>\"} */\nexport function bindSwitchCases(\n nodes: PithyNode[],\n rootEl: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string> = new Set(), // Track already processed nodes\n disposers: (() => void)[] = [] // Collect disposers for cleanup\n): Set<string> {\n // Performance optimization: Create a Map of all elements by data-pid\n // This makes element lookups O(1) instead of O(n) with querySelector\n const elMap = new Map<string, Element>();\n if (rootEl instanceof Element || rootEl instanceof DocumentFragment) {\n const elements = rootEl.querySelectorAll('[data-pid]');\n elements.forEach(el => {\n const pid = el.getAttribute('data-pid');\n if (pid) {\n elMap.set(pid, el as Element);\n }\n });\n }\n\n const switchIds = new Set<string>();\n\n for (const node of nodes) {\n if (node.type !== 'element' || node.directives?.switch === undefined) {\n continue;\n }\n if (isConditionalBranch(node)) continue;\n\n const parentElement = node.nodeId ? elMap.get(node.nodeId) : null;\n if (!parentElement) {\n console.error(\n '[bindSwitchCases] Could not find parent element for switch block'\n );\n continue;\n }\n if (\n bindSwitchBlock(node, parentElement, ctx, processedNodeIds, disposers) &&\n node.nodeId\n )\n switchIds.add(node.nodeId);\n }\n\n for (const node of nodes) {\n if (node.nodeId && switchIds.has(node.nodeId)) continue;\n if (node.nodeId && processedNodeIds.has(node.nodeId)) continue;\n if (isConditionalBranch(node)) continue;\n if (node.isComponent) continue;\n\n if (node.type === 'element' && node.children?.length) {\n const element = node.nodeId ? elMap.get(node.nodeId) : null;\n\n if (element instanceof Element) {\n bindSwitchCases(\n node.children,\n element,\n ctx,\n processedNodeIds,\n disposers\n );\n }\n }\n }\n\n return processedNodeIds;\n}\n\nfunction isConditionalBranch(node: PithyNode): boolean {\n return (\n node.directives?.if !== undefined ||\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n );\n}\n\n/**\n * Binds one @switch element whose DOM is already built.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchBlock\",\"stability\":\"experimental\",\"signature\":\"(switchNode: PithyNode, parentElement: Element, ctx: Record<string, unknown>, processedNodeIds: Set<string>, disposers: (() => void)[]) => boolean\"} */\nexport function bindSwitchBlock(\n switchNode: PithyNode,\n parentElement: Element,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string>,\n disposers: (() => void)[]\n): boolean {\n const caseNodes = (switchNode.children || []).filter(\n child =>\n child.type === 'element' &&\n (child.directives?.case !== undefined || isDefaultCase(child))\n );\n if (caseNodes.length === 0) return false;\n\n for (const node of caseNodes) {\n if (node.nodeId) processedNodeIds.add(node.nodeId);\n for (const loopNode of findAllNestedLoopNodes(node)) {\n if (loopNode.nodeId) processedNodeIds.add(loopNode.nodeId);\n }\n }\n\n const childByPid = new Map<string, Element>();\n for (const child of Array.from(parentElement.children)) {\n const pid = child.getAttribute('data-pid');\n if (pid) childByPid.set(pid, child as Element);\n }\n const caseElements = caseNodes\n .map(node => (node.nodeId ? childByPid.get(node.nodeId) : undefined))\n .filter((el): el is Element => el !== undefined);\n\n if (caseElements.length !== caseNodes.length) {\n console.error('[bindSwitchCases] Could not find all case elements');\n return true;\n }\n\n removeNonCaseChildren(parentElement, caseElements, switchNode);\n\n handleSwitchBlock(\n parentElement,\n caseElements,\n switchNode,\n caseNodes,\n ctx,\n disposers\n );\n return true;\n}\n\nconst warnedSwitches = new WeakSet<PithyNode>();\n\nfunction removeNonCaseChildren(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode\n): void {\n const cases = new Set<Node>(caseElements);\n let dropped: string | undefined;\n for (const child of Array.from(parentElement.childNodes)) {\n if (cases.has(child)) continue;\n if (child.nodeType === Node.TEXT_NODE && !child.textContent?.trim()) {\n child.remove();\n continue;\n }\n const node = nodeExpando(child).__pithyNode;\n if (child.nodeType === Node.TEXT_NODE)\n dropped ??= JSON.stringify(child.textContent?.trim());\n else if (node?.type === 'slot') dropped ??= '<slot>';\n else if (node) dropped ??= `<${node.originalTagName ?? node.tagName}>`;\n else if (child.nodeType === Node.ELEMENT_NODE)\n dropped ??= `<${(child as Element).localName}>`;\n child.remove();\n }\n if (dropped && import.meta.env?.DEV && !warnedSwitches.has(switchNode)) {\n warnedSwitches.add(switchNode);\n console.warn(\n `[bindSwitchCases] @switch renders only its @case/@default children; ${dropped} is dropped, as in a build`\n );\n }\n}\n\n/**\n * Handles rendering and reactivity for an @switch/@case/@default block.\n */\nfunction handleSwitchBlock(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode,\n caseNodes: PithyNode[],\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n) {\n // Generate a unique ID for this switch block for debugging\n const switchId = Math.random().toString(36).substring(2, 8);\n\n // Create a placeholder comment to mark where our switch content should go\n const placeholder = document.createComment(`switch-block-${switchId}`);\n\n // Insert the placeholder at the beginning of the parent element\n parentElement.insertBefore(placeholder, parentElement.firstChild);\n\n // Remove all case elements from the DOM immediately\n for (const el of caseElements) {\n el.remove();\n }\n\n let current: Branch | null = null;\n\n // Cache for compiled expressions to avoid recompiling on each change\n const compiledExpressions = new Map<string, () => unknown>();\n\n // Helper function to compile and cache expressions\n function getCompiledExpression(expr: string, kind: string): () => unknown {\n if (!expr || expr.trim() === '') {\n return () => undefined;\n }\n\n // Check if we already compiled this expression\n const cacheKey = `${kind}:${expr}`;\n if (compiledExpressions.has(cacheKey)) {\n return compiledExpressions.get(cacheKey)!;\n }\n\n try {\n const fn = compileExpression(expr, ctx, undefined);\n compiledExpressions.set(cacheKey, fn);\n return fn;\n } catch (err) {\n console.error(`[Switch-${switchId}] Error compiling ${kind}:`, err);\n const fallbackFn = () => undefined;\n compiledExpressions.set(cacheKey, fallbackFn);\n return fallbackFn;\n }\n }\n\n // Helper function to safely evaluate expressions\n function safeEvaluate(expr: string, kind: string): unknown {\n const fn = getCompiledExpression(expr, kind);\n try {\n return fn();\n } catch (err) {\n console.error(`[Switch-${switchId}] Error evaluating ${kind}:`, err);\n return undefined;\n }\n }\n\n function cleanupCurrentBranch() {\n if (current) clearBranch(current);\n current = null;\n }\n\n // Shared logic for finding the matching case\n function findMatchingCase(): number {\n // Evaluate the switch expression\n const switchValue = safeEvaluate(switchNode.directives!.switch!, '@switch');\n\n // Find the matching case\n let matchIndex = -1;\n let defaultIndex = -1;\n\n for (let i = 0; i < caseNodes.length; i++) {\n const node = caseNodes[i];\n\n if (node.directives?.case !== undefined) {\n // This is a @case node\n const caseValue = safeEvaluate(node.directives.case, '@case');\n\n // Check if the case value matches the switch value\n if (caseValue === switchValue) {\n matchIndex = i;\n break;\n }\n } else if (isDefaultCase(node)) {\n // This is a @default node, remember its index but continue checking other cases\n if (defaultIndex === -1) defaultIndex = i;\n }\n }\n\n // If no case matched but we have a default, use that\n if (matchIndex === -1 && defaultIndex !== -1) {\n matchIndex = defaultIndex;\n }\n\n return matchIndex;\n }\n\n function renderMatchedCase(matchIndex: number): Branch | null {\n if (matchIndex < 0 || !placeholder.parentNode) return null;\n return renderBranch(caseNodes[matchIndex], ctx, placeholder);\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n const matchIndex = findMatchingCase();\n const branch = renderMatchedCase(matchIndex);\n // Ensure nested directive disposers created during SSR are added\n // to the parent disposers array for proper cleanup on destroy()\n if (branch) disposers.push(...branch.disposers);\n } else {\n // Client mode: reactive effect for dynamic updates\n // Track the previous match index to avoid unnecessary DOM operations\n let previousMatchIndex = -1;\n\n // Set up the reactive effect and capture the stop function\n const stopEffect = effect(() => {\n const matchIndex = findMatchingCase();\n\n // Skip re-insertion if match hasn't changed\n if (matchIndex === previousMatchIndex) {\n return;\n }\n\n // Clean up the current branch before showing a new one\n cleanupCurrentBranch();\n // Update the previous match index\n previousMatchIndex = matchIndex;\n current = renderMatchedCase(matchIndex);\n\n // Don't return cleanup here - we handle cleanup explicitly:\n // 1. When match changes: cleanupCurrentBranch() is called above\n // 2. When effect stops: cleanupCurrentBranch is in disposers array\n });\n\n // Add cleanup and effect stop to disposers for proper cleanup on destroy()\n disposers.push(cleanupCurrentBranch);\n disposers.push(stopEffect);\n }\n}\n"]}
1
+ {"version":3,"file":"bindSwitchCases.js","sourceRoot":"","sources":["../../src/compile/bindSwitchCases.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,aAAa,EAAkB,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAe,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC;;;GAGG;AACH,kRAAkR;AAClR,MAAM,UAAU,eAAe,CAC7B,KAAkB,EAClB,MAAkC,EAClC,GAA4B,E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IAAI,UAAU,KAAK,kBAAkB,EAAE,CAAC;gBACtC,OAAO;YACT,CAAC;YAED,uDAAuD;YACvD,oBAAoB,EAAE,CAAC;YACvB,kCAAkC;YAClC,kBAAkB,GAAG,UAAU,CAAC;YAChC,OAAO,GAAG,iBAAiB,CAAC,UAAU,CAAC,CAAC;YAExC,4DAA4D;YAC5D,gEAAgE;YAChE,mEAAmE;QACrE,CAAC,CAAC,CAAC;QAEH,2EAA2E;QAC3E,SAAS,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACrC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.switch\",\n \"title\": \"@switch directive\",\n \"category\": \"directive\"\n}\n*/\n\nimport { isDefaultCase, type PithyNode } from '@pithyjs/compiler';\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from './compileExpression';\nimport { findAllNestedLoopNodes } from './forLoops/loopTraversal';\nimport { nodeExpando } from './nodeExpando';\nimport { clearBranch, renderBranch, type Branch } from './renderBranch';\nimport { isSSRMode } from './ssrMode';\n\n/**\n * Processes switch case directives (@switch, @case, @default) in the template.\n * Identifies switch blocks and delegates their handling to handleSwitchBlock.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchCases\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], rootEl: Element | DocumentFragment, ctx: Record<string, unknown>, processedNodeIds?: Set<string>, disposers?: (() => void)[]) => Set<string>\"} */\nexport function bindSwitchCases(\n nodes: PithyNode[],\n rootEl: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string> = new Set(), // Track already processed nodes\n disposers: (() => void)[] = [] // Collect disposers for cleanup\n): Set<string> {\n // Performance optimization: Create a Map of all elements by data-pid\n // This makes element lookups O(1) instead of O(n) with querySelector\n const elMap = new Map<string, Element>();\n if (rootEl instanceof Element || rootEl instanceof DocumentFragment) {\n const elements = rootEl.querySelectorAll('[data-pid]');\n elements.forEach(el => {\n const pid = el.getAttribute('data-pid');\n if (pid) {\n elMap.set(pid, el as Element);\n }\n });\n }\n\n const switchIds = new Set<string>();\n\n for (const node of nodes) {\n if (node.type !== 'element') continue;\n if (\n (node.directives?.case !== undefined || isDefaultCase(node)) &&\n node.nodeId &&\n !processedNodeIds.has(node.nodeId) &&\n !isConditionalBranch(node)\n ) {\n processedNodeIds.add(node.nodeId);\n elMap.get(node.nodeId)?.remove();\n if (import.meta.env?.DEV && !warnedOrphans.has(node)) {\n warnedOrphans.add(node);\n console.warn(\n `[bindSwitchCases] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element (BUG-070); <${node.originalTagName ?? node.tagName}> is dropped, as in a build`\n );\n }\n continue;\n }\n if (node.directives?.switch === undefined) continue;\n if (isConditionalBranch(node)) continue;\n\n const parentElement = node.nodeId ? elMap.get(node.nodeId) : null;\n if (!parentElement) {\n console.error(\n '[bindSwitchCases] Could not find parent element for switch block'\n );\n continue;\n }\n if (\n bindSwitchBlock(node, parentElement, ctx, processedNodeIds, disposers) &&\n node.nodeId\n )\n switchIds.add(node.nodeId);\n }\n\n for (const node of nodes) {\n if (node.nodeId && switchIds.has(node.nodeId)) continue;\n if (node.nodeId && processedNodeIds.has(node.nodeId)) continue;\n if (isConditionalBranch(node)) continue;\n if (node.isComponent) continue;\n\n if (node.type === 'element' && node.children?.length) {\n const element = node.nodeId ? elMap.get(node.nodeId) : null;\n\n if (element instanceof Element) {\n bindSwitchCases(\n node.children,\n element,\n ctx,\n processedNodeIds,\n disposers\n );\n }\n }\n }\n\n return processedNodeIds;\n}\n\nfunction isConditionalBranch(node: PithyNode): boolean {\n return (\n node.directives?.if !== undefined ||\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n );\n}\n\n/**\n * Binds one @switch element whose DOM is already built.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchBlock\",\"stability\":\"experimental\",\"signature\":\"(switchNode: PithyNode, parentElement: Element, ctx: Record<string, unknown>, processedNodeIds: Set<string>, disposers: (() => void)[]) => boolean\"} */\nexport function bindSwitchBlock(\n switchNode: PithyNode,\n parentElement: Element,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string>,\n disposers: (() => void)[]\n): boolean {\n const caseNodes = (switchNode.children || []).filter(\n child =>\n child.type === 'element' &&\n (child.directives?.case !== undefined || isDefaultCase(child))\n );\n if (caseNodes.length === 0) return false;\n\n for (const node of caseNodes) {\n if (node.nodeId) processedNodeIds.add(node.nodeId);\n for (const loopNode of findAllNestedLoopNodes(node)) {\n if (loopNode.nodeId) processedNodeIds.add(loopNode.nodeId);\n }\n }\n\n const childByPid = new Map<string, Element>();\n for (const child of Array.from(parentElement.children)) {\n const pid = child.getAttribute('data-pid');\n if (pid) childByPid.set(pid, child as Element);\n }\n const caseElements = caseNodes\n .map(node => (node.nodeId ? childByPid.get(node.nodeId) : undefined))\n .filter((el): el is Element => el !== undefined);\n\n if (caseElements.length !== caseNodes.length) {\n console.error('[bindSwitchCases] Could not find all case elements');\n return true;\n }\n\n removeNonCaseChildren(parentElement, caseElements, switchNode);\n\n handleSwitchBlock(\n parentElement,\n caseElements,\n switchNode,\n caseNodes,\n ctx,\n disposers\n );\n return true;\n}\n\nconst warnedSwitches = new WeakSet<PithyNode>();\nconst warnedOrphans = new WeakSet<PithyNode>();\n\nfunction removeNonCaseChildren(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode\n): void {\n const cases = new Set<Node>(caseElements);\n let dropped: string | undefined;\n for (const child of Array.from(parentElement.childNodes)) {\n if (cases.has(child)) continue;\n if (child.nodeType === Node.TEXT_NODE && !child.textContent?.trim()) {\n child.remove();\n continue;\n }\n const node = nodeExpando(child).__pithyNode;\n if (child.nodeType === Node.TEXT_NODE)\n dropped ??= JSON.stringify(child.textContent?.trim());\n else if (node?.type === 'slot') dropped ??= '<slot>';\n else if (node) dropped ??= `<${node.originalTagName ?? node.tagName}>`;\n else if (child.nodeType === Node.ELEMENT_NODE)\n dropped ??= `<${(child as Element).localName}>`;\n child.remove();\n }\n if (dropped && import.meta.env?.DEV && !warnedSwitches.has(switchNode)) {\n warnedSwitches.add(switchNode);\n console.warn(\n `[bindSwitchCases] @switch renders only its @case/@default children; ${dropped} is dropped, as in a build`\n );\n }\n}\n\n/**\n * Handles rendering and reactivity for an @switch/@case/@default block.\n */\nfunction handleSwitchBlock(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode,\n caseNodes: PithyNode[],\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n) {\n // Generate a unique ID for this switch block for debugging\n const switchId = Math.random().toString(36).substring(2, 8);\n\n // Create a placeholder comment to mark where our switch content should go\n const placeholder = document.createComment(`switch-block-${switchId}`);\n\n // Insert the placeholder at the beginning of the parent element\n parentElement.insertBefore(placeholder, parentElement.firstChild);\n\n // Remove all case elements from the DOM immediately\n for (const el of caseElements) {\n el.remove();\n }\n\n let current: Branch | null = null;\n\n // Cache for compiled expressions to avoid recompiling on each change\n const compiledExpressions = new Map<string, () => unknown>();\n\n // Helper function to compile and cache expressions\n function getCompiledExpression(expr: string, kind: string): () => unknown {\n if (!expr || expr.trim() === '') {\n return () => undefined;\n }\n\n // Check if we already compiled this expression\n const cacheKey = `${kind}:${expr}`;\n if (compiledExpressions.has(cacheKey)) {\n return compiledExpressions.get(cacheKey)!;\n }\n\n try {\n const fn = compileExpression(expr, ctx, undefined);\n compiledExpressions.set(cacheKey, fn);\n return fn;\n } catch (err) {\n console.error(`[Switch-${switchId}] Error compiling ${kind}:`, err);\n const fallbackFn = () => undefined;\n compiledExpressions.set(cacheKey, fallbackFn);\n return fallbackFn;\n }\n }\n\n // Helper function to safely evaluate expressions\n function safeEvaluate(expr: string, kind: string): unknown {\n const fn = getCompiledExpression(expr, kind);\n try {\n return fn();\n } catch (err) {\n console.error(`[Switch-${switchId}] Error evaluating ${kind}:`, err);\n return undefined;\n }\n }\n\n function cleanupCurrentBranch() {\n if (current) clearBranch(current);\n current = null;\n }\n\n // Shared logic for finding the matching case\n function findMatchingCase(): number {\n // Evaluate the switch expression\n const switchValue = safeEvaluate(switchNode.directives!.switch!, '@switch');\n\n // Find the matching case\n let matchIndex = -1;\n let defaultIndex = -1;\n\n for (let i = 0; i < caseNodes.length; i++) {\n const node = caseNodes[i];\n\n if (node.directives?.case !== undefined) {\n // This is a @case node\n const caseValue = safeEvaluate(node.directives.case, '@case');\n\n // Check if the case value matches the switch value\n if (caseValue === switchValue) {\n matchIndex = i;\n break;\n }\n } else if (isDefaultCase(node)) {\n // This is a @default node, remember its index but continue checking other cases\n if (defaultIndex === -1) defaultIndex = i;\n }\n }\n\n // If no case matched but we have a default, use that\n if (matchIndex === -1 && defaultIndex !== -1) {\n matchIndex = defaultIndex;\n }\n\n return matchIndex;\n }\n\n function renderMatchedCase(matchIndex: number): Branch | null {\n if (matchIndex < 0 || !placeholder.parentNode) return null;\n return renderBranch(caseNodes[matchIndex], ctx, placeholder);\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n const matchIndex = findMatchingCase();\n const branch = renderMatchedCase(matchIndex);\n // Ensure nested directive disposers created during SSR are added\n // to the parent disposers array for proper cleanup on destroy()\n if (branch) disposers.push(...branch.disposers);\n } else {\n // Client mode: reactive effect for dynamic updates\n // Track the previous match index to avoid unnecessary DOM operations\n let previousMatchIndex = -1;\n\n // Set up the reactive effect and capture the stop function\n const stopEffect = effect(() => {\n const matchIndex = findMatchingCase();\n\n // Skip re-insertion if match hasn't changed\n if (matchIndex === previousMatchIndex) {\n return;\n }\n\n // Clean up the current branch before showing a new one\n cleanupCurrentBranch();\n // Update the previous match index\n previousMatchIndex = matchIndex;\n current = renderMatchedCase(matchIndex);\n\n // Don't return cleanup here - we handle cleanup explicitly:\n // 1. When match changes: cleanupCurrentBranch() is called above\n // 2. When effect stops: cleanupCurrentBranch is in disposers array\n });\n\n // Add cleanup and effect stop to disposers for proper cleanup on destroy()\n disposers.push(cleanupCurrentBranch);\n disposers.push(stopEffect);\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The non-structural passes that follow content projection, in order. Each
3
+ * consumes what it binds, so a second run over the same nodes binds nothing.
4
+ */
5
+ /** @codexApi {"parent":"pithy.runtime.renderer","name":"bindAfterProjection","stability":"internal","signature":"(fragment: DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void"} */
6
+ export declare function bindAfterProjection(fragment: DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]): void;
7
+ //# sourceMappingURL=bindAfterProjection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bindAfterProjection.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindAfterProjection.ts"],"names":[],"mappings":"AASA;;;GAGG;AACH,wNAAwN;AACxN,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAwBN"}
@@ -0,0 +1,32 @@
1
+ import { bindComponentTags } from './bindComponentsTags.js';
2
+ import { bindDefaultTwoWay } from './bindDefaultTwoWay.js';
3
+ import { bindTextInterpolations } from './bindTextInterpolations.js';
4
+ import { bindEventHandlers } from './bindEventHandlers.js';
5
+ import { bindClassDirectives } from './bindClassDirectives.js';
6
+ import { bindBoundAttributes } from './bindBoundAttributes.js';
7
+ import { executeCustomDirectiveBinders } from './directiveRegistry.js';
8
+ import { bindDeferDirectives } from './bindDeferDirectives.js';
9
+ /**
10
+ * The non-structural passes that follow content projection, in order. Each
11
+ * consumes what it binds, so a second run over the same nodes binds nothing.
12
+ */
13
+ /** @codexApi {"parent":"pithy.runtime.renderer","name":"bindAfterProjection","stability":"internal","signature":"(fragment: DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void"} */
14
+ export function bindAfterProjection(fragment, context, disposers) {
15
+ // components — materialize custom tags, including those in projected content
16
+ bindComponentTags(fragment, context, disposers);
17
+ // two-way model bindings for native controls at this level
18
+ bindDefaultTwoWay(fragment, context, disposers);
19
+ // text interpolations — our binder already skips nested loops & component roots
20
+ bindTextInterpolations(fragment, context, disposers);
21
+ // events (idempotent; supports modifiers; nearest ctx; $event/$el)
22
+ bindEventHandlers(fragment, context, disposers);
23
+ // classes and style properties
24
+ bindClassDirectives(fragment, context, disposers);
25
+ // bound attributes
26
+ bindBoundAttributes(fragment, context, disposers);
27
+ // custom directives — allows external packages (router, etc.) to register binders
28
+ executeCustomDirectiveBinders(fragment, context, disposers);
29
+ // defer directives — lazy loading with @defer, @load, @placeholder
30
+ bindDeferDirectives(fragment, context, disposers);
31
+ }
32
+ //# sourceMappingURL=bindAfterProjection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bindAfterProjection.js","sourceRoot":"","sources":["../../../src/compile/binds/bindAfterProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D;;;GAGG;AACH,wNAAwN;AACxN,MAAM,UAAU,mBAAmB,CACjC,QAA0B,EAC1B,OAAgC,EAChC,SAAyB;IAEzB,6EAA6E;IAC7E,iBAAiB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAEhD,2DAA2D;IAC3D,iBAAiB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAEhD,gFAAgF;IAChF,sBAAsB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAErD,mEAAmE;IACnE,iBAAiB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAEhD,+BAA+B;IAC/B,mBAAmB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAElD,mBAAmB;IACnB,mBAAmB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAElD,kFAAkF;IAClF,6BAA6B,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAE5D,mEAAmE;IACnE,mBAAmB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import { bindComponentTags } from './bindComponentsTags';\nimport { bindDefaultTwoWay } from './bindDefaultTwoWay';\nimport { bindTextInterpolations } from './bindTextInterpolations';\nimport { bindEventHandlers } from './bindEventHandlers';\nimport { bindClassDirectives } from './bindClassDirectives';\nimport { bindBoundAttributes } from './bindBoundAttributes';\nimport { executeCustomDirectiveBinders } from './directiveRegistry';\nimport { bindDeferDirectives } from './bindDeferDirectives';\n\n/**\n * The non-structural passes that follow content projection, in order. Each\n * consumes what it binds, so a second run over the same nodes binds nothing.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.renderer\",\"name\":\"bindAfterProjection\",\"stability\":\"internal\",\"signature\":\"(fragment: DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindAfterProjection(\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // components — materialize custom tags, including those in projected content\n bindComponentTags(fragment, context, disposers);\n\n // two-way model bindings for native controls at this level\n bindDefaultTwoWay(fragment, context, disposers);\n\n // text interpolations — our binder already skips nested loops & component roots\n bindTextInterpolations(fragment, context, disposers);\n\n // events (idempotent; supports modifiers; nearest ctx; $event/$el)\n bindEventHandlers(fragment, context, disposers);\n\n // classes and style properties\n bindClassDirectives(fragment, context, disposers);\n\n // bound attributes\n bindBoundAttributes(fragment, context, disposers);\n\n // custom directives — allows external packages (router, etc.) to register binders\n executeCustomDirectiveBinders(fragment, context, disposers);\n\n // defer directives — lazy loading with @defer, @load, @placeholder\n bindDeferDirectives(fragment, context, disposers);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA+BF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AA6JD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAwWN"}
1
+ {"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAqCF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AA6JD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAoXN"}
@@ -8,7 +8,7 @@
8
8
  import { compileExpression } from '../compileExpression.js';
9
9
  import { boundaryForElement, runWithBoundary } from './bindErrorBoundary.js';
10
10
  import { collectSlotMap } from '../contentProjection.js';
11
- import { nativeTags } from '@pithyjs/compiler';
11
+ import { componentChildDirectiveMessage, componentChildDirectives, nativeTags, } from '@pithyjs/compiler';
12
12
  import { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs.js';
13
13
  import { createRoot, untrack } from '@pithyjs/signals';
14
14
  import { nodeExpando } from '../nodeExpando.js';
@@ -25,6 +25,7 @@ import { parsePropNames } from './propNames.js';
25
25
  // (e.g. a panel importing Button while using a native <button>), and
26
26
  // repeating the warning drowns out real ones.
27
27
  const warnedComponentTags = new Set();
28
+ const warnedChildDirectives = new WeakSet();
28
29
  /** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */
29
30
  export function __resetComponentTagWarnings() {
30
31
  warnedComponentTags.clear();
@@ -237,6 +238,13 @@ export function bindComponentTags(root, rootCtx, disposers) {
237
238
  if (inComponentDom(el))
238
239
  continue;
239
240
  }
241
+ if (import.meta.env?.DEV &&
242
+ pithyNode &&
243
+ !warnedChildDirectives.has(pithyNode)) {
244
+ warnedChildDirectives.add(pithyNode);
245
+ for (const name of componentChildDirectives(pithyNode))
246
+ console.warn(`[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`);
247
+ }
240
248
  let candidate = tagMap.get(tag);
241
249
  if (!candidate)
242
250
  continue;