@delmaredigital/payload-experiments 0.4.0-rc.4 → 0.4.0-rc.6

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 (123) hide show
  1. package/dist/admin/copy/newTest.d.ts +1 -1
  2. package/dist/admin/copy/newTest.js +1 -1
  3. package/dist/admin/surface/ResultsRoute.js +2 -10
  4. package/dist/admin/surface/newTest/NewTest.js +16 -18
  5. package/dist/admin/surface/newTest/PageWizard.js +10 -12
  6. package/dist/admin/surface/newTest/newTest.css +3 -1
  7. package/dist/admin/surface/results/ResultsHeader.js +15 -8
  8. package/dist/blocks/bindings.js +6 -13
  9. package/dist/blocks/placementLocale.d.ts +2 -0
  10. package/dist/blocks/placementLocale.js +16 -12
  11. package/dist/goals/fairness.d.ts +1 -1
  12. package/dist/goals/fairness.js +9 -7
  13. package/dist/hooks/blockRemovalRule.d.ts +2 -1
  14. package/dist/hooks/blockRemovalRule.js +27 -5
  15. package/dist/hooks/pageGuard.js +2 -2
  16. package/dist/puck/ExperimentPicker.d.ts +2 -1
  17. package/dist/puck/ExperimentPicker.js +34 -30
  18. package/dist/puck/ExperimentSlot.js +3 -1
  19. package/dist/puck/copy.d.ts +1 -0
  20. package/dist/puck/copy.js +1 -0
  21. package/dist/puck/editor/ConfigureTestDrawer.js +2 -2
  22. package/dist/puck/editor/CreateExperimentDrawer.d.ts +2 -1
  23. package/dist/puck/editor/CreateExperimentDrawer.js +24 -16
  24. package/dist/puck/editor/EditorControls.d.ts +1 -1
  25. package/dist/puck/editor/EditorControls.js +1 -1
  26. package/dist/puck/editor/ExperimentSlotEditor.js +624 -299
  27. package/dist/puck/editor/LeftoverVersions.d.ts +15 -0
  28. package/dist/puck/editor/LeftoverVersions.js +97 -0
  29. package/dist/puck/editor/PlacementNotice.d.ts +8 -0
  30. package/dist/puck/editor/PlacementNotice.js +22 -0
  31. package/dist/puck/editor/QuickTestActions.d.ts +3 -0
  32. package/dist/puck/editor/QuickTestActions.js +50 -0
  33. package/dist/puck/editor/ResultsReadout.js +5 -0
  34. package/dist/puck/editor/VersionBuilder.d.ts +37 -12
  35. package/dist/puck/editor/VersionBuilder.js +273 -184
  36. package/dist/puck/editor/armWrites.d.ts +11 -2
  37. package/dist/puck/editor/armWrites.js +42 -3
  38. package/dist/puck/editor/armsCache.d.ts +1 -1
  39. package/dist/puck/editor/armsCache.js +2 -1
  40. package/dist/puck/editor/cloneSlot.d.ts +2 -0
  41. package/dist/puck/editor/cloneSlot.js +7 -0
  42. package/dist/puck/editor/copy.d.ts +35 -20
  43. package/dist/puck/editor/copy.js +35 -20
  44. package/dist/puck/editor/createTest.d.ts +3 -0
  45. package/dist/puck/editor/createTest.js +33 -0
  46. package/dist/puck/editor/editor.chrome.css +32 -14
  47. package/dist/puck/editor/editor.css +58 -17
  48. package/dist/puck/editor/editor.model.d.ts +1 -1
  49. package/dist/puck/editor/editor.model.js +2 -2
  50. package/dist/puck/editor/experimentOutlinePlugin.js +96 -28
  51. package/dist/puck/editor/localPlacements.d.ts +4 -2
  52. package/dist/puck/editor/localPlacements.js +20 -18
  53. package/dist/puck/editor/outlineVersion.d.ts +5 -0
  54. package/dist/puck/editor/outlineVersion.js +36 -0
  55. package/dist/puck/editor/placementsCache.d.ts +33 -2
  56. package/dist/puck/editor/placementsCache.js +208 -33
  57. package/dist/puck/editor/sidebar.d.ts +8 -0
  58. package/dist/puck/editor/sidebar.js +74 -0
  59. package/dist/puck/editor/usePlacementNotice.d.ts +3 -0
  60. package/dist/puck/editor/usePlacementNotice.js +14 -0
  61. package/dist/puck/visibility.d.ts +21 -0
  62. package/dist/puck/visibility.js +77 -0
  63. package/dist/server/recordContentChange.js +3 -1
  64. package/dist/server/resolveExperimentData.js +4 -1
  65. package/dist/testSurface/api.js +1 -1
  66. package/dist/testSurface/copy/common.d.ts +1 -1
  67. package/dist/testSurface/copy/common.js +3 -1
  68. package/dist/testSurface/copy/readiness.d.ts +18 -1
  69. package/dist/testSurface/copy/readiness.js +23 -1
  70. package/dist/testSurface/copy/testPage.d.ts +8 -6
  71. package/dist/testSurface/copy/testPage.js +8 -6
  72. package/dist/testSurface/readPreflight.d.ts +9 -0
  73. package/dist/testSurface/readPreflight.js +38 -0
  74. package/dist/testSurface/readinessRead.d.ts +50 -0
  75. package/dist/testSurface/readinessRead.js +46 -0
  76. package/dist/testSurface/results/results.css +1 -1
  77. package/dist/testSurface/results/results.model.d.ts +1 -1
  78. package/dist/testSurface/surface/contracts.d.ts +6 -2
  79. package/dist/testSurface/surface/editorPlacement.d.ts +21 -0
  80. package/dist/testSurface/surface/editorPlacement.js +60 -0
  81. package/dist/testSurface/surface/pageBlock/parts.js +13 -3
  82. package/dist/testSurface/surface/readiness/ActionDialogs.js +65 -41
  83. package/dist/testSurface/surface/readiness/Banner.d.ts +1 -4
  84. package/dist/testSurface/surface/readiness/Banner.js +106 -68
  85. package/dist/testSurface/surface/readiness/BlockerList.d.ts +11 -0
  86. package/dist/testSurface/surface/readiness/BlockerList.js +31 -0
  87. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +6 -2
  88. package/dist/testSurface/surface/readiness/SaveStatus.js +35 -22
  89. package/dist/testSurface/surface/readiness/parts.js +0 -2
  90. package/dist/testSurface/surface/readiness/readiness.model.d.ts +13 -0
  91. package/dist/testSurface/surface/readiness/readiness.model.js +51 -36
  92. package/dist/testSurface/surface/readiness/useTransition.d.ts +5 -2
  93. package/dist/testSurface/surface/readiness/useTransition.js +69 -7
  94. package/dist/testSurface/surface/test/AdvancedSection.js +1 -0
  95. package/dist/testSurface/surface/test/GoalSection.js +102 -74
  96. package/dist/testSurface/surface/test/LengthSection.d.ts +1 -1
  97. package/dist/testSurface/surface/test/LengthSection.js +2 -1
  98. package/dist/testSurface/surface/test/Rail.js +7 -4
  99. package/dist/testSurface/surface/test/ReadinessBar.js +1 -2
  100. package/dist/testSurface/surface/test/Section.d.ts +3 -1
  101. package/dist/testSurface/surface/test/Section.js +38 -6
  102. package/dist/testSurface/surface/test/TargetingSection.js +5 -0
  103. package/dist/testSurface/surface/test/TestSurface.d.ts +2 -1
  104. package/dist/testSurface/surface/test/TestSurface.js +68 -7
  105. package/dist/testSurface/surface/test/VersionsSection.js +1 -0
  106. package/dist/testSurface/surface/test/fields.d.ts +1 -3
  107. package/dist/testSurface/surface/test/fields.js +5 -35
  108. package/dist/testSurface/surface/test/testPage.css +12 -0
  109. package/dist/testSurface/surface/useTestDocument.d.ts +5 -2
  110. package/dist/testSurface/surface/useTestDocument.js +61 -46
  111. package/dist/testSurface/useReadinessPolling.d.ts +3 -0
  112. package/dist/testSurface/useReadinessPolling.js +24 -0
  113. package/dist/transitions/makeContent.js +24 -5
  114. package/dist/transitions/placements.js +23 -34
  115. package/dist/transitions/preflightData.js +1 -1
  116. package/dist/types/puck.d.ts +1 -0
  117. package/dist/ui/Card.d.ts +2 -1
  118. package/dist/ui/Card.js +4 -4
  119. package/dist/ui/Inputs.js +8 -5
  120. package/dist/ui/Tabs.d.ts +2 -2
  121. package/dist/ui/Tabs.js +33 -32
  122. package/dist/ui/ui.css +26 -3
  123. package/package.json +1 -1
@@ -1,8 +1,10 @@
1
1
  'use client';
2
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { createUsePuck, walkTree } from '@puckeditor/core';
4
- import { useEffect, useMemo, useState } from 'react';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { createUsePuck, useGetPuck, walkTree } from '@puckeditor/core';
4
+ import { useId, useLayoutEffect, useMemo, useRef } from 'react';
5
5
  import { EXPERIMENT_SLOT_TYPE } from '../../types/puck.js';
6
+ import { slotLabels } from '../copy.js';
7
+ import { useOutlineVersion } from './outlineVersion.js';
6
8
  import { useArms } from './armsCache.js';
7
9
  const usePuckSelector = createUsePuck();
8
10
  const slots = [
@@ -11,35 +13,93 @@ const slots = [
11
13
  'variantB',
12
14
  'variantC'
13
15
  ];
14
- // Puck 0.24.0 dist/chunk-DQXMVPVM.mjs:8040 (item attribute), 8126–8135
15
- // (direct zone containers). Zones have no stable attribute; avoid the CSS-module hash.
16
+ // Puck 0.24.0: defaultSlots prepends in field order (chunk-H65MT2JK:15–18),
17
+ // getZonesByParent/buildLayerNode preserve zone order (chunk-DQXMVPVM:8577–8622),
18
+ // and Layer maps it to direct wrappers (8126–8135). Never rely on a module hash.
16
19
  const zone = 'div[class*="Layer-zones"]';
17
20
  const chain = (count)=>Array(count).fill(zone).join(' ~ ');
18
- function SlotRules({ item: [id, testId, emptySlots] }) {
21
+ /** Read Puck's DOM only; the plugin owns the wrapper and the emitted style. */ function SlotRules({ item: [id, testId, emptySlots], root, scope }) {
19
22
  const known = useArms(testId ?? undefined);
20
- const [mounted, setMounted] = useState(false);
21
- useEffect(()=>{
22
- setMounted(true);
23
- }, []);
24
- // CSS.escape is a browser API: SSR and the first hydration render emit no rules.
25
- if (!mounted) return null;
26
- const rules = slots.flatMap((slot, index)=>{
27
- // Original always remains available. Unknown bound tests must reveal every zone.
28
- if (slot === 'control' || testId !== null && (!known || known.arms.includes(slot))) return [];
29
- if (!emptySlots[index]) return [];
30
- // Exactly the nth zone sibling: the positive chain matches n onward and the
31
- // negated chain excludes n+1 onward. Unlike nth-child, DropLine siblings do not count.
32
- const selector = `li[data-puck-layer-tree-id="${CSS.escape(id)}"] > ${chain(index + 1)}:not(${chain(index + 2)})`;
33
- return [
34
- `${selector} { display: none; }`
35
- ];
36
- }).join('\n');
23
+ const active = useOutlineVersion(useGetPuck(), id);
24
+ const dragging = usePuckSelector((state)=>state.appState.ui?.isDragging ?? false);
25
+ const fixedHidden = useRef([]);
26
+ const style = useRef(null);
27
+ useLayoutEffect(()=>{
28
+ const ownedStyle = style.current;
29
+ const host = root.current ?? ownedStyle?.parentElement;
30
+ if (!host || !ownedStyle || typeof CSS === 'undefined' || typeof CSS.escape !== 'function') return;
31
+ const rowSelector = `[data-xp-outline-scope="${CSS.escape(scope)}"] li[data-puck-layer-tree-id="${CSS.escape(id)}"]`;
32
+ const update = ()=>{
33
+ const rows = [
34
+ ...host.querySelectorAll(`li[data-puck-layer-tree-id="${CSS.escape(id)}"]`)
35
+ ];
36
+ const row = rows.length === 1 ? rows[0] : undefined;
37
+ const zones = row ? [
38
+ ...row.children
39
+ ].filter((child)=>child.matches(zone)) : [];
40
+ // Exact count and static field labels guard sibling position, including after
41
+ // a Puck upgrade, a host override, collapse/expand, reorder or virtualization.
42
+ const valid = !!row && zones.length === slots.length && [
43
+ ...row.children
44
+ ].filter((child)=>child.matches('div[class*="Layer-inner"]')).length === 1 && [
45
+ ...row.children
46
+ ].every((child)=>child.matches(`${zone}, div[class*="Layer-inner"], div[class*="DropLine"]`)) && zones.every((child, index)=>{
47
+ const label = child.firstElementChild;
48
+ const list = label?.nextElementSibling;
49
+ return label?.matches('div[class*="LayerTree-zoneTitle"]') && label.textContent?.trim() === slotLabels[slots[index]] && list?.matches('ul[class*="LayerTree"]') && !list.nextElementSibling;
50
+ });
51
+ const unknown = testId !== null && !known;
52
+ // A drag's collision shapes were measured before it began. Never hide a
53
+ // previously visible target mid-drag; apply the new tab after it finishes.
54
+ if (!valid || unknown) fixedHidden.current = [];
55
+ else if (!dragging) fixedHidden.current = slots.filter((slot, index)=>active ? slot !== active : slot !== active && slot !== 'control' && !known?.arms.includes(slot) && emptySlots[index]);
56
+ const rules = !valid || unknown ? '' : slots.flatMap((slot, index)=>{
57
+ // No canvas tab is mounted: retain the existing empty-unused-slot behavior.
58
+ if (!fixedHidden.current.includes(slot)) return [];
59
+ // The count guard also disables the rule synchronously if wrappers change.
60
+ const guard = `:has(> ${chain(slots.length)}):not(:has(> ${chain(slots.length + 1)}))`;
61
+ const selector = `${rowSelector}${guard} > ${chain(index + 1)}:not(${chain(index + 2)})`;
62
+ // Hidden descendants have no pointer hit area, including zone drop targets.
63
+ return [
64
+ `${selector} { display: none; pointer-events: none; }`
65
+ ];
66
+ }).join('\n');
67
+ if (ownedStyle.textContent !== rules) ownedStyle.textContent = rules;
68
+ };
69
+ update();
70
+ const observer = new MutationObserver(update);
71
+ observer.observe(host, {
72
+ childList: true,
73
+ subtree: true,
74
+ characterData: true,
75
+ attributes: true,
76
+ attributeFilter: [
77
+ 'class',
78
+ 'data-puck-layer-tree-id'
79
+ ]
80
+ });
81
+ return ()=>{
82
+ observer.disconnect();
83
+ ownedStyle.textContent = '';
84
+ };
85
+ }, [
86
+ id,
87
+ testId,
88
+ emptySlots,
89
+ known,
90
+ active,
91
+ dragging,
92
+ root,
93
+ scope
94
+ ]);
37
95
  return /*#__PURE__*/ _jsx("style", {
38
- "data-xp-outline": id,
39
- children: rules
96
+ ref: style,
97
+ "data-xp-outline": id
40
98
  });
41
99
  }
42
100
  function ExperimentOutline({ children }) {
101
+ const root = useRef(null);
102
+ const scope = useId();
43
103
  // Public selector API in Puck 0.24, rather than the deprecated usePuck hook.
44
104
  const key = usePuckSelector((state)=>{
45
105
  const { data } = state.appState;
@@ -68,11 +128,19 @@ function ExperimentOutline({ children }) {
68
128
  });
69
129
  // Only binding/emptiness changes rebuild the rules, not edits to other page fields.
70
130
  const rules = useMemo(()=>JSON.parse(key).map((item)=>/*#__PURE__*/ _jsx(SlotRules, {
71
- item: item
131
+ item: item,
132
+ root: root,
133
+ scope: scope
72
134
  }, item[0])), [
73
- key
135
+ key,
136
+ scope
74
137
  ]);
75
- return /*#__PURE__*/ _jsxs(_Fragment, {
138
+ return /*#__PURE__*/ _jsxs("div", {
139
+ ref: root,
140
+ "data-xp-outline-scope": scope,
141
+ style: {
142
+ display: 'contents'
143
+ },
76
144
  children: [
77
145
  children,
78
146
  rules
@@ -1,2 +1,4 @@
1
- import { type Config, type Data } from '@puckeditor/core';
2
- export declare function localPlacements(data: Data, config: Config): Map<string, Set<string>>;
1
+ import { type BlockVisibility } from '../visibility.js';
2
+ import type { Data } from '@puckeditor/core';
3
+ export declare function localPlacements(data: Data): Map<string, Set<string>>;
4
+ export declare function localBlockVisibility(data: Data, id: string): BlockVisibility | undefined;
@@ -1,29 +1,31 @@
1
- import { walkTree } from '@puckeditor/core';
2
- // Puck data/config are immutable. Selection, hover and drag state reuse this
1
+ import { walkVisiblePuck } from '../visibility.js';
2
+ // Puck data is immutable. Selection, hover and drag state reuse this
3
3
  // result, and every block on the page shares a single traversal per data change.
4
4
  const pages = new WeakMap();
5
- export function localPlacements(data, config) {
6
- let configs = pages.get(data);
7
- if (!configs) {
8
- configs = new WeakMap();
9
- pages.set(data, configs);
10
- }
11
- let placements = configs.get(config);
5
+ export function localPlacements(data) {
6
+ let placements = pages.get(data);
12
7
  if (!placements) {
13
8
  placements = new Map();
14
- const collect = (content)=>{
15
- for (const item of content)if (item.type === 'ExperimentSlot' && item.props.experiment?.id !== undefined) {
16
- const key = String(item.props.experiment.id);
9
+ walkVisiblePuck(data, (item, visibility)=>{
10
+ const ref = item.props.experiment;
11
+ if (!visibility.hidden && item.type === 'ExperimentSlot' && ref && ref.id !== undefined) {
12
+ const key = String(ref.id);
17
13
  const ids = placements.get(key) ?? new Set();
18
- ids.add(item.props.id);
14
+ ids.add(String(item.props.id));
19
15
  placements.set(key, ids);
20
16
  }
21
- };
22
- walkTree(data, config, (content)=>{
23
- collect(content);
24
17
  });
25
- for (const content of Object.values(data.zones ?? {}))collect(content);
26
- configs.set(config, placements);
18
+ pages.set(data, placements);
27
19
  }
28
20
  return placements;
29
21
  }
22
+ const visibilityPages = new WeakMap();
23
+ export function localBlockVisibility(data, id) {
24
+ let blocks = visibilityPages.get(data);
25
+ if (!blocks) {
26
+ blocks = new Map();
27
+ walkVisiblePuck(data, (block, visibility)=>blocks.set(String(block.props.id), visibility));
28
+ visibilityPages.set(data, blocks);
29
+ }
30
+ return blocks.get(id);
31
+ }
@@ -0,0 +1,5 @@
1
+ import type { ArmSlot } from '../../types/puck.js';
2
+ type Editor = object;
3
+ export declare function publishOutlineVersion(editor: Editor, id: string, slot?: ArmSlot): void;
4
+ export declare function useOutlineVersion(editor: Editor, id: string): ArmSlot | undefined;
5
+ export {};
@@ -0,0 +1,36 @@
1
+ import { useSyncExternalStore } from 'react';
2
+ const editors = new WeakMap();
3
+ function entryFor(editor, id) {
4
+ let entries = editors.get(editor);
5
+ if (!entries) {
6
+ entries = new Map();
7
+ editors.set(editor, entries);
8
+ }
9
+ let entry = entries.get(id);
10
+ if (!entry) {
11
+ const listeners = new Set();
12
+ entry = {
13
+ listeners,
14
+ removeListener: (notify)=>{
15
+ listeners.delete(notify);
16
+ }
17
+ };
18
+ entries.set(id, entry);
19
+ }
20
+ return entry;
21
+ }
22
+ export function publishOutlineVersion(editor, id, slot) {
23
+ const entry = entryFor(editor, id);
24
+ if (entry.slot === slot) return;
25
+ entry.slot = slot;
26
+ for (const notify of entry.listeners)notify();
27
+ }
28
+ export function useOutlineVersion(editor, id) {
29
+ const entry = entryFor(editor, id);
30
+ return useSyncExternalStore((notify)=>{
31
+ entry.listeners.add(notify);
32
+ return ()=>{
33
+ entry.removeListener(notify);
34
+ };
35
+ }, ()=>entry.slot, ()=>undefined);
36
+ }
@@ -12,8 +12,39 @@ export declare function refreshPlacements(api: string, id: DocId): Promise<{
12
12
  ok: boolean;
13
13
  detail?: string;
14
14
  }[] | undefined>;
15
- /** Reuse the surface's successful preflight, without another editor request. */
16
- export declare function publishPlacements(api: string, id: DocId, placements: Placements | undefined): void;
15
+ /** Focus storms share the last attempt (including polling), at most once per ten seconds. */
16
+ export declare function focusPlacements(api: string, id: DocId): Promise<{
17
+ collection: string;
18
+ id: DocId;
19
+ title: string;
20
+ url?: string;
21
+ editorUrl?: string;
22
+ slots?: Record<import("../../types/puck.js").ArmSlot, number>;
23
+ ok: boolean;
24
+ detail?: string;
25
+ }[] | undefined>;
17
26
  export declare function invalidatePlacements(api: string, id: DocId): void;
27
+ /** Listen without starting a request; the drawer already owns its initial preflight. */
28
+ export declare function subscribePlacements(api: string, id: DocId, notify: (placements: Placements | undefined) => void): () => void;
18
29
  export declare function acquirePlacements(api: string, id: DocId, notify: (placements: Placements | undefined) => void, fresh?: boolean): () => void;
30
+ /** Drawer preflight uses this same producer and follows a superseding post-write read. */
31
+ export declare function readEditorPreflight(api: string, id: DocId, signal: AbortSignal, supersede?: boolean): Promise<Response>;
32
+ /** Current readiness shares the same request and lifetime as placements. */
33
+ export declare function cachedPreflight(api: string, id: DocId): PreflightResult | undefined;
34
+ /** Mandatory post-write/refusal reads guard Start in every shared consumer. */
35
+ export declare function placementsBlocking(api: string, id: DocId): boolean;
36
+ export declare function placementsPending(api: string, id: DocId): boolean;
37
+ /** Pending reads retain the complete settled classification, including terminal outcomes. */
38
+ export declare function cachedReadinessRead(api: string, id: DocId): {
39
+ status: number;
40
+ loadState: "forbidden" | "error" | "missing" | "ready";
41
+ kind: string;
42
+ answer: PreflightResult | undefined;
43
+ message: "Couldn't check where this test is used. Try again." | "You don't have permission to check where this test is used." | "A page used by this test no longer exists. Choose another page." | "This test's setup couldn't be checked." | "Couldn't check readiness. Try again." | "This test no longer exists." | "This isn't available yet." | "Your session has expired. Sign in again." | "Couldn't load this test. Try selecting it again." | "You don't have access to this test." | "Couldn't load this test." | "You don't have access to this test. You can still edit its content." | "This test isn't available to you. You can still edit its content." | "You can view this test's results." | undefined;
44
+ failed: boolean;
45
+ retry: boolean;
46
+ pollDelay: number | null;
47
+ } | undefined;
48
+ export declare function placementReadError(api: string, id: DocId): string | undefined;
49
+ export declare function watchPlacementNotice(api: string, id: DocId, doc: Document): () => void;
19
50
  export {};
@@ -1,39 +1,66 @@
1
+ import { isPreflightResult, readPreflight } from '../../testSurface/readPreflight.js';
2
+ import { classifyReadinessRead } from '../../testSurface/readinessRead.js';
1
3
  const cache = new Map();
4
+ const latest = new Map();
2
5
  const consumers = new Map();
3
6
  const keyFor = (api, id)=>JSON.stringify([
4
7
  api,
5
8
  String(id)
6
9
  ]);
7
- function read(api, id, fresh) {
10
+ function read(api, id, fresh, blocking = false) {
8
11
  const key = keyFor(api, id);
9
12
  const cached = cache.get(key);
10
13
  if (cached && (!fresh || cached.pending)) return cached;
11
14
  const controller = new AbortController();
15
+ const previous = latest.get(key);
12
16
  const entry = {
13
17
  controller,
14
18
  pending: true,
19
+ blocking,
20
+ startedAt: Date.now(),
21
+ failures: previous?.failures ?? 0,
22
+ value: previous?.value,
23
+ previousPreflight: previous?.preflight ?? (previous?.pending ? previous.previousPreflight : undefined),
24
+ previousRead: previous?.read ?? previous?.previousRead,
15
25
  promise: undefined
16
26
  };
17
27
  cache.set(key, entry);
18
- for (const notify of consumers.get(key) ?? [])notify(undefined);
28
+ latest.set(key, entry);
29
+ for (const notify of consumers.get(key)?.listeners ?? [])notify(entry.value);
19
30
  entry.promise = (async ()=>{
20
31
  try {
21
- const response = await fetch(`${api}/xp/experiments/${encodeURIComponent(id)}/preflight`, {
22
- credentials: 'include',
23
- cache: 'no-store',
24
- signal: controller.signal
32
+ const { response, body: data } = await readPreflight((signal)=>fetch(`${api}/xp/experiments/${encodeURIComponent(id)}/preflight`, {
33
+ credentials: 'include',
34
+ cache: 'no-store',
35
+ signal
36
+ }), controller.signal);
37
+ entry.read = classifyReadinessRead(response.status, data, entry.failures + 1, {
38
+ kind: 'where-used'
25
39
  });
26
- if (!response.ok) return;
27
- const data = await response.json();
40
+ if (!response.ok) {
41
+ entry.response = new Response(JSON.stringify(data), {
42
+ status: response.status,
43
+ headers: response.headers
44
+ });
45
+ return;
46
+ }
47
+ if (!isPreflightResult(data)) return;
48
+ entry.preflight = data;
49
+ if (data.checks?.some((check)=>!check.ok && check.code === 'no-placements' && check.detail !== undefined)) return;
28
50
  return Array.isArray(data.placements) ? data.placements : undefined;
29
51
  } catch {
30
52
  return undefined;
31
53
  }
32
54
  })().then((placements)=>{
33
55
  entry.pending = false;
56
+ entry.read ??= classifyReadinessRead(0, undefined, entry.failures + 1, {
57
+ kind: 'where-used'
58
+ });
59
+ entry.failures = entry.read.failed ? entry.failures + 1 : 0;
60
+ entry.value = placements;
34
61
  if (cache.get(key) === entry) {
35
- if (placements === undefined) cache.delete(key);
36
- for (const notify of consumers.get(key) ?? [])notify(placements);
62
+ if (!entry.preflight) cache.delete(key);
63
+ for (const notify of consumers.get(key)?.listeners ?? [])notify(placements);
37
64
  }
38
65
  return placements;
39
66
  });
@@ -42,42 +69,190 @@ function read(api, id, fresh) {
42
69
  /** Share mounted reads, but destructive actions always bypass settled cached knowledge. */ export function refreshPlacements(api, id) {
43
70
  return read(api, id, true).promise;
44
71
  }
45
- /** Reuse the surface's successful preflight, without another editor request. */ export function publishPlacements(api, id, placements) {
46
- const key = keyFor(api, id);
47
- cache.get(key)?.controller.abort();
48
- if (placements === undefined) cache.delete(key);
49
- else cache.set(key, {
50
- controller: new AbortController(),
51
- promise: Promise.resolve(placements),
52
- pending: false
53
- });
54
- for (const notify of consumers.get(key) ?? [])notify(placements);
72
+ /** Focus storms share the last attempt (including polling), at most once per ten seconds. */ export function focusPlacements(api, id) {
73
+ const previous = latest.get(keyFor(api, id));
74
+ if (previous && Date.now() - previous.startedAt < 10_000) return previous.promise;
75
+ return read(api, id, true).promise;
55
76
  }
56
77
  export function invalidatePlacements(api, id) {
57
78
  const key = keyFor(api, id);
58
79
  cache.get(key)?.controller.abort();
59
80
  cache.delete(key);
60
- for (const notify of consumers.get(key) ?? [])notify(undefined);
61
- if (consumers.get(key)?.size) void read(api, id, true).promise;
81
+ if (consumers.get(key)?.listeners.size) void read(api, id, true, true).promise;
82
+ else latest.delete(key);
83
+ }
84
+ /** Listen without starting a request; the drawer already owns its initial preflight. */ export function subscribePlacements(api, id, notify) {
85
+ const key = keyFor(api, id);
86
+ let group = consumers.get(key);
87
+ if (!group) {
88
+ const listeners = new Set();
89
+ group = {
90
+ listeners,
91
+ removeListener: (notify)=>{
92
+ listeners.delete(notify);
93
+ }
94
+ };
95
+ consumers.set(key, group);
96
+ }
97
+ const current = group;
98
+ current.listeners.add(notify);
99
+ let listening = true;
100
+ return ()=>{
101
+ if (!listening) return;
102
+ listening = false;
103
+ current.removeListener(notify);
104
+ if (!current.listeners.size && consumers.get(key) === current) {
105
+ consumers.delete(key);
106
+ latest.delete(key);
107
+ cache.get(key)?.controller.abort();
108
+ cache.delete(key);
109
+ }
110
+ };
62
111
  }
63
112
  export function acquirePlacements(api, id, notify, fresh = false) {
113
+ const release = subscribePlacements(api, id, notify);
64
114
  const key = keyFor(api, id);
65
- let listeners = new Set();
66
- listeners = consumers.get(key) ?? listeners;
67
- consumers.set(key, listeners);
68
- listeners.add(notify);
69
115
  const entry = read(api, id, fresh);
116
+ if (entry.value !== undefined) notify(entry.value);
70
117
  let active = true;
71
- void entry.promise.then((value)=>{
72
- if (active && cache.get(key) === entry) notify(value);
118
+ void entry.promise.then(()=>{
119
+ if (active && cache.get(key) === entry) notify(entry.value);
73
120
  });
74
121
  return ()=>{
75
122
  active = false;
76
- listeners.delete(notify);
77
- if (!listeners.size) {
78
- consumers.delete(key);
79
- cache.get(key)?.controller.abort();
80
- cache.delete(key);
123
+ release();
124
+ };
125
+ }
126
+ /** Drawer preflight uses this same producer and follows a superseding post-write read. */ export async function readEditorPreflight(api, id, signal, supersede = false) {
127
+ if (signal.aborted) return new Response(null, {
128
+ status: 503
129
+ });
130
+ const release = subscribePlacements(api, id, ()=>{});
131
+ signal.addEventListener('abort', release, {
132
+ once: true
133
+ });
134
+ try {
135
+ if (supersede) invalidatePlacements(api, id);
136
+ const previous = latest.get(keyFor(api, id));
137
+ let entry = previous && Date.now() - previous.startedAt < 10_000 ? previous : read(api, id, true);
138
+ while(!signal.aborted){
139
+ await entry.promise;
140
+ if (signal.aborted) return new Response(null, {
141
+ status: 503
142
+ });
143
+ const current = latest.get(keyFor(api, id));
144
+ if (current && current !== entry) {
145
+ entry = current;
146
+ continue;
147
+ }
148
+ return entry.preflight ? Response.json(entry.preflight) : entry.response?.clone() ?? new Response(null, {
149
+ status: 503
150
+ });
151
+ }
152
+ return new Response(null, {
153
+ status: 503
154
+ });
155
+ } finally{
156
+ signal.removeEventListener('abort', release);
157
+ release();
158
+ }
159
+ }
160
+ /** Current readiness shares the same request and lifetime as placements. */ export function cachedPreflight(api, id) {
161
+ const entry = latest.get(keyFor(api, id));
162
+ return entry?.preflight ?? (entry?.pending ? entry.previousPreflight : undefined);
163
+ }
164
+ /** Mandatory post-write/refusal reads guard Start in every shared consumer. */ export function placementsBlocking(api, id) {
165
+ const entry = cache.get(keyFor(api, id));
166
+ return entry?.pending === true && entry.blocking;
167
+ }
168
+ export function placementsPending(api, id) {
169
+ return cache.get(keyFor(api, id))?.pending === true;
170
+ }
171
+ /** Pending reads retain the complete settled classification, including terminal outcomes. */ export function cachedReadinessRead(api, id) {
172
+ const entry = latest.get(keyFor(api, id));
173
+ return entry?.pending ? entry.previousRead : entry?.read;
174
+ }
175
+ export function placementReadError(api, id) {
176
+ return cachedReadinessRead(api, id)?.message;
177
+ }
178
+ const notices = new WeakMap();
179
+ const noticeDelay = (api, id)=>cachedReadinessRead(api, id)?.pollDelay ?? null;
180
+ export function watchPlacementNotice(api, id, doc) {
181
+ let session = notices.get(doc);
182
+ if (!session) {
183
+ const requests = new Map();
184
+ const created = {
185
+ requests,
186
+ removeRequest: (key)=>{
187
+ requests.delete(key);
188
+ },
189
+ visibility: ()=>{},
190
+ schedule: ()=>{}
191
+ };
192
+ created.schedule = ()=>{
193
+ if (created.timer !== undefined) {
194
+ clearTimeout(created.timer);
195
+ created.timer = undefined;
196
+ }
197
+ const eligible = [
198
+ ...created.requests.values()
199
+ ].filter((request)=>!request.pending && noticeDelay(request.api, request.id) !== null);
200
+ if (doc.visibilityState !== 'visible' || !eligible.length) return;
201
+ created.timer = setTimeout(()=>{
202
+ created.timer = undefined;
203
+ if (doc.visibilityState !== 'visible') return;
204
+ const due = eligible.filter((request)=>created.requests.get(keyFor(request.api, request.id)) === request && request.nextAt <= Date.now());
205
+ for (const request of due){
206
+ request.pending = true;
207
+ void refreshPlacements(request.api, request.id).then(()=>{
208
+ request.pending = false;
209
+ request.nextAt = Date.now() + (noticeDelay(request.api, request.id) ?? 0);
210
+ if (notices.get(doc) === created) created.schedule();
211
+ });
212
+ }
213
+ created.schedule();
214
+ }, Math.max(0, Math.min(...eligible.map((request)=>request.nextAt)) - Date.now()));
215
+ };
216
+ created.visibility = ()=>{
217
+ for (const request of created.requests.values())request.nextAt = Date.now() + (noticeDelay(request.api, request.id) ?? 0);
218
+ created.schedule();
219
+ };
220
+ session = created;
221
+ notices.set(doc, session);
222
+ doc.addEventListener('visibilitychange', created.visibility);
223
+ }
224
+ const current = session;
225
+ const key = keyFor(api, id);
226
+ const existing = current.requests.get(key);
227
+ const request = existing ?? {
228
+ api,
229
+ id,
230
+ subscribers: 0,
231
+ nextAt: Date.now() + (noticeDelay(api, id) ?? 0),
232
+ pending: false,
233
+ release: ()=>{}
234
+ };
235
+ request.subscribers++;
236
+ current.requests.set(key, request);
237
+ if (!existing) request.release = subscribePlacements(api, id, ()=>{
238
+ if (placementsPending(api, id)) return;
239
+ // Manual/focus retries also reset the backoff after recovery.
240
+ request.nextAt = Date.now() + (noticeDelay(api, id) ?? 0);
241
+ current.schedule();
242
+ });
243
+ if (!existing || current.timer === undefined) current.schedule();
244
+ let active = true;
245
+ return ()=>{
246
+ if (!active) return;
247
+ active = false;
248
+ if (--request.subscribers === 0) {
249
+ current.removeRequest(key);
250
+ request.release();
251
+ }
252
+ if (!current.requests.size) {
253
+ if (current.timer !== undefined) clearTimeout(current.timer);
254
+ doc.removeEventListener('visibilitychange', current.visibility);
255
+ notices.delete(doc);
81
256
  }
82
257
  };
83
258
  }
@@ -0,0 +1,8 @@
1
+ type Targets = {
2
+ test: HTMLElement;
3
+ controls: HTMLElement;
4
+ };
5
+ export declare function useSidebarTargets(id: string): Targets | undefined;
6
+ /** The custom field owns only its portal destinations never another data reader. */
7
+ export declare function TestSidebarField(): import("react").JSX.Element;
8
+ export {};