@delmaredigital/payload-experiments 0.4.0-rc.10 → 0.4.0-rc.11

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 (140) hide show
  1. package/dist/admin/MetricSourceSelect.js +10 -3
  2. package/dist/admin/copy/blocks.js +3 -3
  3. package/dist/admin/copy/goals.d.ts +15 -8
  4. package/dist/admin/copy/goals.js +18 -8
  5. package/dist/admin/copy/newTest.d.ts +3 -2
  6. package/dist/admin/copy/newTest.js +3 -2
  7. package/dist/admin/surface/SurfaceShell.d.ts +4 -2
  8. package/dist/admin/surface/SurfaceShell.js +25 -3
  9. package/dist/admin/surface/TestRowMenu.d.ts +7 -0
  10. package/dist/admin/surface/TestRowMenu.js +9 -2
  11. package/dist/admin/surface/TestsHome.js +8 -1
  12. package/dist/admin/surface/goals/DeleteGoalDialog.d.ts +7 -0
  13. package/dist/admin/surface/goals/DeleteGoalDialog.js +42 -0
  14. package/dist/admin/surface/goals/GoalForm.d.ts +1 -0
  15. package/dist/admin/surface/goals/GoalForm.js +280 -191
  16. package/dist/admin/surface/goals/GoalsList.js +102 -33
  17. package/dist/admin/surface/goals/data.d.ts +2 -0
  18. package/dist/admin/surface/goals/data.js +9 -0
  19. package/dist/admin/surface/goals/goals.css +3 -2
  20. package/dist/admin/surface/goals/goals.model.d.ts +2 -2
  21. package/dist/admin/surface/goals/goals.model.js +7 -12
  22. package/dist/admin/surface/home.model.d.ts +1 -0
  23. package/dist/admin/surface/home.model.js +5 -1
  24. package/dist/admin/surface/newTest/NewTest.js +56 -29
  25. package/dist/admin/surface/newTest/PageWizard.d.ts +3 -1
  26. package/dist/admin/surface/newTest/PageWizard.js +14 -14
  27. package/dist/admin/surface/newTest/newTest.css +3 -3
  28. package/dist/admin/surface/results/ResultsHeader.d.ts +1 -1
  29. package/dist/admin/surface/results/ResultsHeader.js +69 -41
  30. package/dist/admin/surface/surface.css +20 -1
  31. package/dist/admin/surface/test/TestPage.js +46 -34
  32. package/dist/admin/surface/useXpStepNav.d.ts +11 -0
  33. package/dist/admin/surface/useXpStepNav.js +14 -0
  34. package/dist/admin/views/TestsSurfaceClient.js +27 -3
  35. package/dist/blocks/createExperimentBlock.js +1 -1
  36. package/dist/blocks/formState.js +1 -1
  37. package/dist/collections/metrics.js +12 -5
  38. package/dist/collections/serialize.js +3 -2
  39. package/dist/db/snapshots.d.ts +1 -0
  40. package/dist/goals/sourceLabel.d.ts +2 -0
  41. package/dist/goals/sourceLabel.js +4 -0
  42. package/dist/plugin.js +51 -1
  43. package/dist/puck/editor/ExperimentSlotEditor.d.ts +2 -1
  44. package/dist/puck/editor/ExperimentSlotEditor.js +96 -43
  45. package/dist/puck/editor/QuickTestActions.d.ts +2 -2
  46. package/dist/puck/editor/QuickTestActions.js +42 -27
  47. package/dist/puck/editor/ResultsReadout.d.ts +3 -1
  48. package/dist/puck/editor/ResultsReadout.js +28 -16
  49. package/dist/puck/editor/VersionBuilder.d.ts +2 -1
  50. package/dist/puck/editor/VersionBuilder.js +14 -8
  51. package/dist/puck/editor/copy.d.ts +3 -3
  52. package/dist/puck/editor/copy.js +4 -4
  53. package/dist/puck/editor/editor.chrome.css +9 -1
  54. package/dist/puck/editor/editor.css +10 -1
  55. package/dist/puck/nestedTestCopy.js +1 -1
  56. package/dist/puck/slotConfig.d.ts +1 -1
  57. package/dist/puck/slotConfig.js +1 -1
  58. package/dist/results/analyse.d.ts +2 -0
  59. package/dist/results/analyse.js +2 -2
  60. package/dist/results/verdict.d.ts +1 -1
  61. package/dist/results/verdict.js +7 -6
  62. package/dist/server/runResults.js +2 -1
  63. package/dist/testSurface/PreviewLinks.d.ts +2 -1
  64. package/dist/testSurface/PreviewLinks.js +3 -3
  65. package/dist/testSurface/actions/DecideDialog.d.ts +3 -2
  66. package/dist/testSurface/actions/DecideDialog.js +21 -12
  67. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  68. package/dist/testSurface/actions/LifecycleAction.js +3 -1
  69. package/dist/testSurface/actions/actions.model.js +6 -5
  70. package/dist/testSurface/actions/decide.model.d.ts +1 -0
  71. package/dist/testSurface/actions/decide.model.js +1 -0
  72. package/dist/testSurface/allocation.model.js +6 -3
  73. package/dist/testSurface/copy/actions.d.ts +12 -9
  74. package/dist/testSurface/copy/actions.js +12 -9
  75. package/dist/testSurface/copy/advanced.d.ts +10 -0
  76. package/dist/testSurface/copy/advanced.js +10 -0
  77. package/dist/testSurface/copy/arms.d.ts +1 -1
  78. package/dist/testSurface/copy/arms.js +1 -1
  79. package/dist/testSurface/copy/audience.d.ts +4 -3
  80. package/dist/testSurface/copy/audience.js +5 -4
  81. package/dist/testSurface/copy/common.d.ts +2 -2
  82. package/dist/testSurface/copy/common.js +2 -2
  83. package/dist/testSurface/copy/metrics.d.ts +6 -0
  84. package/dist/testSurface/copy/metrics.js +8 -0
  85. package/dist/testSurface/copy/readiness.d.ts +3 -3
  86. package/dist/testSurface/copy/readiness.js +5 -5
  87. package/dist/testSurface/copy/recommendation.d.ts +4 -4
  88. package/dist/testSurface/copy/recommendation.js +4 -4
  89. package/dist/testSurface/copy/results.d.ts +13 -9
  90. package/dist/testSurface/copy/results.js +15 -9
  91. package/dist/testSurface/copy/review.d.ts +12 -9
  92. package/dist/testSurface/copy/review.js +13 -9
  93. package/dist/testSurface/copy/setting.d.ts +1 -2
  94. package/dist/testSurface/copy/setting.js +1 -2
  95. package/dist/testSurface/copy/surface.js +1 -1
  96. package/dist/testSurface/copy/testPage.d.ts +13 -9
  97. package/dist/testSurface/copy/testPage.js +16 -13
  98. package/dist/testSurface/format/date.d.ts +1 -0
  99. package/dist/testSurface/format/date.js +11 -0
  100. package/dist/testSurface/labels.d.ts +1 -2
  101. package/dist/testSurface/labels.js +2 -3
  102. package/dist/testSurface/lockedNotice.model.d.ts +2 -0
  103. package/dist/testSurface/lockedNotice.model.js +31 -0
  104. package/dist/testSurface/results/results.model.d.ts +3 -2
  105. package/dist/testSurface/results/results.model.js +10 -9
  106. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +1 -1
  107. package/dist/testSurface/surface/pageBlock/parts.js +17 -7
  108. package/dist/testSurface/surface/pagePicker/PageCombobox.js +0 -5
  109. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +1 -1
  110. package/dist/testSurface/surface/readiness/ActionDialogs.js +54 -33
  111. package/dist/testSurface/surface/readiness/Banner.d.ts +3 -1
  112. package/dist/testSurface/surface/readiness/Banner.js +86 -75
  113. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +5 -2
  114. package/dist/testSurface/surface/readiness/SaveStatus.js +8 -7
  115. package/dist/testSurface/surface/readiness/readiness.model.js +1 -1
  116. package/dist/testSurface/surface/results/ResultsBody.d.ts +4 -1
  117. package/dist/testSurface/surface/results/ResultsBody.js +119 -80
  118. package/dist/testSurface/surface/results/recommendation.model.js +3 -3
  119. package/dist/testSurface/surface/setting/parts.js +31 -28
  120. package/dist/testSurface/surface/setting/setting.css +2 -1
  121. package/dist/testSurface/surface/test/AdvancedSection.js +10 -4
  122. package/dist/testSurface/surface/test/GoalSection.js +11 -11
  123. package/dist/testSurface/surface/test/LengthSection.js +20 -13
  124. package/dist/testSurface/surface/test/PageHoldout.d.ts +1 -1
  125. package/dist/testSurface/surface/test/PageHoldout.js +7 -7
  126. package/dist/testSurface/surface/test/ReadinessBar.d.ts +1 -1
  127. package/dist/testSurface/surface/test/ReadinessBar.js +4 -10
  128. package/dist/testSurface/surface/test/Section.js +8 -0
  129. package/dist/testSurface/surface/test/TargetingSection.js +7 -2
  130. package/dist/testSurface/surface/test/VersionsSection.js +88 -68
  131. package/dist/testSurface/surface/test/fields.d.ts +4 -3
  132. package/dist/testSurface/surface/test/fields.js +10 -16
  133. package/dist/testSurface/surface/test/pageParts.js +3 -1
  134. package/dist/testSurface/surface/test/testPage.css +9 -1
  135. package/dist/testSurface/surfaceUrls.d.ts +1 -0
  136. package/dist/testSurface/surfaceUrls.js +4 -0
  137. package/dist/ui/Dialog.js +25 -0
  138. package/dist/ui/Inputs.js +0 -1
  139. package/dist/ui/ui.css +1 -0
  140. package/package.json +1 -1
@@ -1,24 +1,28 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import { surfaceUrls } from '../../../testSurface/surfaceUrls.js';
4
- import { useEffect, useRef, useState } from 'react';
4
+ import { useCallback, useEffect, useRef, useState } from 'react';
5
5
  import { useRouter } from 'next/navigation.js';
6
6
  import { formatAdminURL } from 'payload/shared';
7
- import { GOALS_COPY as C, goalDeleteLockedStart, goalInUse, goalShowAll } from '../../copy/goals.js';
8
- import { metricSourceHint, metricSourceOptions, sourceFor } from '../../../testSurface/metricSource.model.js';
7
+ import { GOALS_COPY as C, goalDeleteLockedStart, goalInUse, goalShowAll, largestValues } from '../../copy/goals.js';
8
+ import { metricSourceOptions, sourceFor } from '../../../testSurface/metricSource.model.js';
9
9
  import { validateCappingType, validateCappingValue } from '../../../collections/metricValidation.js';
10
10
  import { CLICK_KEY } from '../../../goals/key.js';
11
- import { clickGoalSlug } from '../../../goals/picker/clickGoalPicker.model.js';
11
+ import { goalSourceLabel } from '../../../goals/sourceLabel.js';
12
12
  import { goalSlug, goalUsage, goalUsageRows, visibleGoalUsage } from './goals.model.js';
13
13
  import { GoalResponseError, goalPages, goalResponse } from './data.js';
14
14
  import { SURFACE_COPY } from '../../../testSurface/copy/surface.js';
15
15
  import { SurfaceShell } from '../SurfaceShell.js';
16
+ import { useXpStepNav } from '../useXpStepNav.js';
16
17
  import { Button } from '../../../ui/Button.js';
17
- import { TextInput, NumberInput, Select } from '../../../ui/Inputs.js';
18
+ import { TextInput, NumberInput } from '../../../ui/Inputs.js';
19
+ import { Select } from '../../../ui/Select.js';
18
20
  import { Card } from '../../../ui/Card.js';
19
- import { Banner } from '../../../ui/Feedback.js';
20
- import { ConfirmDialog } from '../../../ui/Dialog.js';
21
- import { actionTitle } from '../../../testSurface/copy/actions.js';
21
+ import { Banner, StatusChip } from '../../../ui/Feedback.js';
22
+ import { SaveStatus } from '../../../testSurface/surface/readiness/SaveStatus.js';
23
+ import { sameTestValue } from '../../../testSurface/surface/testDocument.model.js';
24
+ import { DeleteGoalDialog } from './DeleteGoalDialog.js';
25
+ import '../../../ui/ui.css';
22
26
  import './goals.css';
23
27
  const fieldNames = {
24
28
  name: 'name',
@@ -42,11 +46,43 @@ const empty = ()=>({
42
46
  capValue: '',
43
47
  warningPercent: '5'
44
48
  });
49
+ const HOURS_PER_DAY = 24;
50
+ function awaitingFixedAmount(draft) {
51
+ return draft.capType === 'absolute' && !draft.capValue.trim() && !draft.capValueEdited;
52
+ }
53
+ function goalBody(draft, lockedGoal) {
54
+ const click = draft.source.startsWith('click:');
55
+ const slug = lockedGoal?.slug ?? draft.slug;
56
+ return {
57
+ name: draft.name,
58
+ slug,
59
+ source: lockedGoal?.source ?? (click ? `click:${slug}` : draft.source),
60
+ direction: click ? 'increase' : draft.direction,
61
+ attributionWindowHours: draft.windowDays === undefined ? draft.attributionWindowHours : Number(draft.windowDays) * HOURS_PER_DAY,
62
+ minSampleSize: draft.minSampleSize,
63
+ capping: {
64
+ type: click ? null : draft.capType || null,
65
+ value: click || !draft.capValue.trim() ? null : Number(draft.capValue)
66
+ },
67
+ guardrailThreshold: (draft.warningPercent.trim() === '' ? 5 : Number(draft.warningPercent)) / 100
68
+ };
69
+ }
45
70
  export function GoalForm({ surface, id, returnToTest }) {
46
71
  const router = useRouter();
47
72
  const base = surface.apiRoute.replace(/\/$/, '');
48
73
  const [draft, setDraft] = useState(empty);
49
74
  const [goal, setGoal] = useState();
75
+ useXpStepNav([
76
+ {
77
+ label: SURFACE_COPY.goals,
78
+ url: surfaceUrls.goals(surface.adminRoute, returnToTest ? {
79
+ return: returnToTest
80
+ } : undefined)
81
+ },
82
+ {
83
+ label: goal?.name ?? (id === undefined ? C.newGoal : C.goal)
84
+ }
85
+ ]);
50
86
  const [usageTests, setUsageTests] = useState([]);
51
87
  const [showAllUsage, setShowAllUsage] = useState(false);
52
88
  const [usedBy, setUsedBy] = useState(0);
@@ -56,12 +92,14 @@ export function GoalForm({ surface, id, returnToTest }) {
56
92
  const [fieldErrors, setFieldErrors] = useState({});
57
93
  const [seenFieldErrors, setSeenFieldErrors] = useState(fieldErrors);
58
94
  const [advancedOpen, setAdvancedOpen] = useState(false);
59
- const [pending, setPending] = useState(null);
95
+ const [saving, setSaving] = useState('idle');
60
96
  const [slugEdited, setSlugEdited] = useState(false);
61
97
  const [attempt, setAttempt] = useState(0);
62
98
  const inFlight = useRef(false);
99
+ const persisted = useRef(undefined);
100
+ const queued = useRef(undefined);
63
101
  const [confirmDelete, setConfirmDelete] = useState(false);
64
- const [deleteError, setDeleteError] = useState();
102
+ const existing = id !== undefined;
65
103
  const listUrl = surfaceUrls.goals(surface.adminRoute, returnToTest ? {
66
104
  return: returnToTest
67
105
  } : undefined);
@@ -88,14 +126,15 @@ export function GoalForm({ surface, id, returnToTest }) {
88
126
  setUsageTests(tests);
89
127
  setShowAllUsage(false);
90
128
  setUsedBy(goalUsage(tests).get(loaded.id) ?? 0);
91
- setDraft({
129
+ const loadedDraft = {
92
130
  ...empty(),
93
131
  ...loaded,
94
132
  capType: loaded.capping?.type ?? (defaultCap ? 'percentile' : ''),
95
133
  capValue: loaded.capping?.value == null ? defaultCap ? '0.99' : '' : String(loaded.capping.value),
96
134
  warningPercent: String(Number(((loaded.guardrailThreshold ?? 0.05) * 100).toPrecision(12)))
97
- });
98
- setSlugEdited(true);
135
+ };
136
+ persisted.current = loadedDraft;
137
+ setDraft(loadedDraft);
99
138
  }
100
139
  if (!controller.signal.aborted) setReady(true);
101
140
  } catch (cause) {
@@ -106,7 +145,8 @@ export function GoalForm({ surface, id, returnToTest }) {
106
145
  }, [
107
146
  base,
108
147
  id,
109
- attempt
148
+ attempt,
149
+ surface.metricSources
110
150
  ]);
111
151
  const source = sourceFor(draft.source, surface.metricSources);
112
152
  const click = draft.source.startsWith('click:');
@@ -115,70 +155,130 @@ export function GoalForm({ surface, id, returnToTest }) {
115
155
  setSeenFieldErrors(fieldErrors);
116
156
  if (click && fieldErrors.slug || fieldErrors.capType || fieldErrors.capValue || fieldErrors.warningPercent) setAdvancedOpen(true);
117
157
  }
118
- const hint = metricSourceHint(source);
119
- const options = metricSourceOptions(surface.metricSources);
158
+ const selectedSource = click ? 'click:' : draft.source;
159
+ const options = [
160
+ {
161
+ value: '',
162
+ label: C.chooseSource
163
+ },
164
+ ...metricSourceOptions(surface.metricSources)
165
+ ];
166
+ if (selectedSource && !source) options.push({
167
+ value: selectedSource,
168
+ label: goalSourceLabel(selectedSource)
169
+ });
170
+ const capChoice = draft.capType === 'percentile' ? draft.capValue : draft.capType;
171
+ const capOptions = source?.kind === 'revenue' ? [] : [
172
+ {
173
+ value: '',
174
+ label: C.noCap
175
+ }
176
+ ];
177
+ capOptions.push(...[
178
+ '0.99',
179
+ '0.95'
180
+ ].map((value)=>({
181
+ value,
182
+ label: largestValues(value)
183
+ })));
184
+ if (draft.capType === 'percentile' && capChoice && !capOptions.some((option)=>option.value === capChoice)) {
185
+ capOptions.push({
186
+ value: capChoice,
187
+ label: largestValues(capChoice)
188
+ });
189
+ }
190
+ capOptions.push({
191
+ value: 'absolute',
192
+ label: C.absolute
193
+ });
194
+ const hasUnsaved = !persisted.current || !sameTestValue(goalBody(persisted.current), goalBody(draft));
120
195
  const set = (key, value)=>setDraft((current)=>({
121
196
  ...current,
122
197
  [key]: value
123
198
  }));
124
- async function submit() {
125
- if (inFlight.current || !ready || !surface.canManage) return;
126
- const capValue = click || draft.capValue.trim() === '' ? null : Number(draft.capValue);
127
- const typeError = validateCappingType(click ? null : draft.capType || null, capValue, source?.kind);
128
- const valueError = validateCappingValue(capValue, click ? null : draft.capType || null);
129
- const warningPercent = draft.warningPercent.trim() === '' ? 5 : Number(draft.warningPercent);
199
+ const submit = useCallback(async function save(draft) {
200
+ if (!ready || !surface.canManage || confirmDelete || existing && persisted.current === draft) return;
201
+ if (existing && awaitingFixedAmount(draft)) return;
202
+ if (inFlight.current) {
203
+ if (existing) queued.current = draft;
204
+ return;
205
+ }
206
+ const lockedGoal = usedBy ? goal : undefined;
207
+ const click = draft.source.startsWith('click:');
208
+ const body = goalBody(draft, lockedGoal);
209
+ const kind = sourceFor(draft.source, surface.metricSources)?.kind;
210
+ const typeError = validateCappingType(body.capping.type, body.capping.value, kind);
211
+ const valueError = validateCappingValue(body.capping.value, body.capping.type);
212
+ const days = draft.windowDays === undefined ? undefined : Number(draft.windowDays);
130
213
  const errors = {
131
- ...click && !CLICK_KEY.test(draft.slug) ? {
214
+ ...!draft.name.trim() ? {
215
+ name: C.nameRequired
216
+ } : {},
217
+ ...!draft.slug || (!existing || click) && !CLICK_KEY.test(draft.slug) ? {
132
218
  slug: C.slugRule
133
219
  } : {},
220
+ ...!draft.source ? {
221
+ source: C.chooseSource
222
+ } : {},
223
+ ...days !== undefined && (!Number.isInteger(days) || days < 1 || !Number.isFinite(days * HOURS_PER_DAY)) ? {
224
+ attributionWindowHours: C.windowError
225
+ } : {},
226
+ ...draft.minSampleSize == null || !Number.isFinite(draft.minSampleSize) || draft.minSampleSize < 1 ? {
227
+ minSampleSize: C.minimumError
228
+ } : {},
134
229
  ...typeError !== true ? {
135
230
  capType: typeError
136
231
  } : {},
137
- ...valueError !== true ? {
138
- capValue: valueError
232
+ ...valueError !== true ? draft.capType === 'absolute' ? {
233
+ capValue: C.fixedAmountError
234
+ } : {
235
+ capType: valueError
139
236
  } : {},
140
- ...!Number.isFinite(warningPercent) || warningPercent < 0 ? {
237
+ ...!Number.isFinite(body.guardrailThreshold) || body.guardrailThreshold < 0 ? {
141
238
  warningPercent: C.thresholdError
142
239
  } : {}
143
240
  };
144
241
  setFieldErrors(errors);
145
- if (Object.keys(errors).length) return;
146
- inFlight.current = true;
147
- setPending('save');
148
242
  setError('');
243
+ if (Object.keys(errors).length) {
244
+ setSaving('error');
245
+ return;
246
+ }
247
+ // Send only this editor's changes. Groups such as capping stay atomic.
248
+ const baseline = existing && persisted.current ? goalBody(persisted.current, lockedGoal) : undefined;
249
+ const patch = baseline ? Object.fromEntries(Object.entries(body).filter(([key, value])=>!sameTestValue(value, baseline[key]))) : body;
250
+ if (!Object.keys(patch).length) {
251
+ persisted.current = draft;
252
+ setSaving('saved');
253
+ return;
254
+ }
255
+ inFlight.current = true;
256
+ setSaving('saving');
149
257
  try {
150
- // Use an explicit body: loaded metadata and presentation fields never go back to Payload.
151
- const body = {
152
- name: draft.name,
153
- slug: usedBy && goal ? goal.slug : draft.slug,
154
- source: usedBy && goal ? goal.source : click ? `click:${draft.slug}` : draft.source,
155
- direction: click ? 'increase' : draft.direction,
156
- attributionWindowHours: draft.attributionWindowHours,
157
- minSampleSize: draft.minSampleSize,
158
- capping: {
159
- type: click ? null : draft.capType || null,
160
- value: capValue
161
- },
162
- guardrailThreshold: warningPercent / 100
163
- };
164
258
  const response = await fetch(`${base}/xp-metrics${id === undefined ? '' : `/${encodeURIComponent(id)}`}`, {
165
- method: id === undefined ? 'POST' : 'PATCH',
259
+ method: existing ? 'PATCH' : 'POST',
166
260
  credentials: 'include',
167
261
  headers: {
168
262
  'Content-Type': 'application/json'
169
263
  },
170
- body: JSON.stringify(body)
264
+ body: JSON.stringify(patch)
171
265
  });
172
266
  const saved = await goalResponse(response, C.saveError, {
173
267
  notFound: C.notFound
174
268
  });
175
269
  if (saved.doc?.id == null) throw new Error(C.saveError);
176
- router.push(id === undefined && returnToTest ? formatAdminURL({
177
- adminRoute: surface.adminRoute,
178
- path: `/experiments/${encodeURIComponent(returnToTest)}?${new URLSearchParams({
179
- goal: String(saved.doc.id)
180
- })}`
181
- }) : listUrl);
270
+ if (existing) {
271
+ persisted.current = draft;
272
+ setGoal(saved.doc);
273
+ setSaving('saved');
274
+ } else {
275
+ router.push(returnToTest ? formatAdminURL({
276
+ adminRoute: surface.adminRoute,
277
+ path: `/experiments/${encodeURIComponent(returnToTest)}?${new URLSearchParams({
278
+ goal: String(saved.doc.id)
279
+ })}`
280
+ }) : listUrl);
281
+ }
182
282
  } catch (cause) {
183
283
  setError(cause instanceof GoalResponseError ? cause.message : C.saveError);
184
284
  if (cause instanceof GoalResponseError) setFieldErrors(Object.fromEntries(Object.entries(cause.fields).flatMap(([path, message])=>fieldNames[path] ? [
@@ -187,29 +287,32 @@ export function GoalForm({ surface, id, returnToTest }) {
187
287
  path === 'slug' ? click ? C.duplicateSlug : C.duplicateSlugMain : message
188
288
  ]
189
289
  ] : [])));
290
+ setSaving('error');
291
+ } finally{
190
292
  inFlight.current = false;
191
- setPending(null);
192
- }
193
- }
194
- async function remove() {
195
- if (inFlight.current || !confirmDelete || !ready || !surface.canManage || usedBy || id === undefined) return;
196
- inFlight.current = true;
197
- setPending('delete');
198
- setDeleteError(undefined);
199
- try {
200
- const response = await fetch(`${base}/xp-metrics/${encodeURIComponent(id)}`, {
201
- method: 'DELETE',
202
- credentials: 'include'
203
- });
204
- await goalResponse(response, C.deleteError, {
205
- notFound: C.notFound
206
- });
207
- router.push(listUrl);
208
- } catch (cause) {
209
- setDeleteError(cause instanceof Error ? cause.message : C.deleteError);
210
- inFlight.current = false;
211
- setPending(null);
293
+ // Blur commits can outlive this screen, including edits made during a PATCH.
294
+ const next = queued.current;
295
+ queued.current = undefined;
296
+ if (next) await save(next);
212
297
  }
298
+ }, [
299
+ base,
300
+ confirmDelete,
301
+ existing,
302
+ goal,
303
+ id,
304
+ listUrl,
305
+ ready,
306
+ returnToTest,
307
+ router,
308
+ surface.adminRoute,
309
+ surface.canManage,
310
+ surface.metricSources,
311
+ usedBy
312
+ ]);
313
+ function select(next) {
314
+ setDraft(next);
315
+ if (existing) void submit(next);
213
316
  }
214
317
  const usage = goal ? goalUsageRows(usageTests, goal.id) : [];
215
318
  const title = goal?.name ?? (id === undefined ? C.newGoal : C.goal);
@@ -249,9 +352,13 @@ export function GoalForm({ surface, id, returnToTest }) {
249
352
  children: C.loading
250
353
  }) : /*#__PURE__*/ _jsxs("form", {
251
354
  className: "xp-goal-form",
355
+ noValidate: true,
356
+ onBlur: (event)=>{
357
+ if (existing && event.target instanceof HTMLInputElement) void submit(draft);
358
+ },
252
359
  onSubmit: (event)=>{
253
360
  event.preventDefault();
254
- void submit();
361
+ void submit(draft);
255
362
  },
256
363
  children: [
257
364
  usage.length ? /*#__PURE__*/ _jsxs(Card, {
@@ -271,12 +378,13 @@ export function GoalForm({ surface, id, returnToTest }) {
271
378
  }),
272
379
  children: test.name
273
380
  }),
274
- /*#__PURE__*/ _jsxs("span", {
275
- children: [
276
- test.roles.join(' · '),
277
- test.status ? ` · ${test.status}` : ''
278
- ]
279
- })
381
+ /*#__PURE__*/ _jsx("span", {
382
+ className: "xp-goal-usage-roles",
383
+ children: test.roles.join(' · ')
384
+ }),
385
+ test.status ? /*#__PURE__*/ _jsx(StatusChip, {
386
+ status: test.status
387
+ }) : null
280
388
  ]
281
389
  }, test.id))
282
390
  }),
@@ -292,6 +400,11 @@ export function GoalForm({ surface, id, returnToTest }) {
292
400
  }) : null,
293
401
  error ? /*#__PURE__*/ _jsx(Banner, {
294
402
  tone: "error",
403
+ action: existing && !Object.keys(fieldErrors).length ? /*#__PURE__*/ _jsx(Button, {
404
+ size: "sm",
405
+ onClick: ()=>void submit(draft),
406
+ children: C.retry
407
+ }) : undefined,
295
408
  children: error
296
409
  }) : null,
297
410
  /*#__PURE__*/ _jsxs(Card, {
@@ -301,7 +414,7 @@ export function GoalForm({ surface, id, returnToTest }) {
301
414
  children: C.fields
302
415
  }),
303
416
  /*#__PURE__*/ _jsxs("fieldset", {
304
- disabled: pending !== null || !surface.canManage,
417
+ disabled: !existing && saving === 'saving' || !surface.canManage,
305
418
  children: [
306
419
  /*#__PURE__*/ _jsx(TextInput, {
307
420
  id: "xp-goal-name",
@@ -314,13 +427,13 @@ export function GoalForm({ surface, id, returnToTest }) {
314
427
  setDraft((current)=>({
315
428
  ...current,
316
429
  name,
317
- ...!slugEdited && !usedBy ? {
318
- slug: click ? clickGoalSlug(name) : goalSlug(name)
430
+ ...!existing && !slugEdited ? {
431
+ slug: goalSlug(name)
319
432
  } : {}
320
433
  }));
321
- if (click && !slugEdited && !usedBy) setFieldErrors((current)=>({
434
+ if (click && !existing && !slugEdited) setFieldErrors((current)=>({
322
435
  ...current,
323
- slug: clickGoalSlug(name) ? undefined : C.slugRule
436
+ slug: goalSlug(name) ? undefined : C.slugRule
324
437
  }));
325
438
  }
326
439
  }),
@@ -339,56 +452,43 @@ export function GoalForm({ surface, id, returnToTest }) {
339
452
  }
340
453
  })
341
454
  }) : null,
342
- /*#__PURE__*/ _jsxs(Select, {
455
+ /*#__PURE__*/ _jsx(Select, {
343
456
  id: "xp-goal-source",
344
457
  label: C.source,
345
458
  required: true,
346
- value: click ? 'click:' : draft.source,
459
+ value: selectedSource,
460
+ options: options,
347
461
  disabled: usedBy > 0,
348
- help: usedBy ? C.sourceLocked : hint || undefined,
462
+ help: usedBy ? C.sourceLocked : undefined,
349
463
  error: fieldErrors.source,
350
464
  onChange: (event)=>{
351
465
  const sourceId = event.currentTarget.value;
352
466
  const revenue = sourceFor(sourceId, surface.metricSources)?.kind === 'revenue';
353
- setDraft((current)=>({
354
- ...current,
355
- source: sourceId,
356
- ...!slugEdited && !usedBy ? {
357
- slug: sourceId === 'click:' ? clickGoalSlug(current.name) : goalSlug(current.name)
358
- } : {},
359
- capType: revenue ? 'percentile' : '',
360
- capValue: revenue ? '0.99' : ''
361
- }));
362
- if (sourceId === 'click:' && !slugEdited && !usedBy) setFieldErrors((current)=>({
467
+ select({
468
+ ...draft,
469
+ source: sourceId,
470
+ capType: revenue ? 'percentile' : '',
471
+ capValue: revenue ? '0.99' : ''
472
+ });
473
+ if (sourceId === 'click:' && !existing && !slugEdited) setFieldErrors((current)=>({
363
474
  ...current,
364
- slug: clickGoalSlug(draft.name) ? undefined : C.slugRule
475
+ slug: goalSlug(draft.name) ? undefined : C.slugRule
365
476
  }));
366
477
  else if (sourceId === 'click:' !== click) setFieldErrors((current)=>({
367
478
  ...current,
368
479
  slug: undefined
369
480
  }));
370
- },
371
- children: [
372
- /*#__PURE__*/ _jsx("option", {
373
- value: "",
374
- children: C.chooseSource
375
- }),
376
- options.map((option)=>/*#__PURE__*/ _jsx("option", {
377
- value: option.value,
378
- children: option.value === 'click:' ? sourceFor(option.value, surface.metricSources)?.label : option.label
379
- }, option.value)),
380
- !click && draft.source && !options.some((option)=>option.value === draft.source) ? /*#__PURE__*/ _jsx("option", {
381
- value: draft.source,
382
- children: draft.source
383
- }) : null
384
- ]
481
+ }
385
482
  }),
386
483
  !click ? /*#__PURE__*/ _jsxs(Select, {
387
484
  id: "xp-goal-direction",
388
485
  label: C.direction,
389
486
  value: draft.direction,
390
487
  error: fieldErrors.direction,
391
- onChange: (event)=>set('direction', event.currentTarget.value),
488
+ onChange: (event)=>select({
489
+ ...draft,
490
+ direction: event.currentTarget.value === 'decrease' ? 'decrease' : 'increase'
491
+ }),
392
492
  children: [
393
493
  /*#__PURE__*/ _jsx("option", {
394
494
  value: "increase",
@@ -405,10 +505,10 @@ export function GoalForm({ surface, id, returnToTest }) {
405
505
  label: C.window,
406
506
  required: true,
407
507
  min: "1",
408
- step: "any",
409
- value: draft.attributionWindowHours ?? '',
508
+ step: "1",
509
+ value: draft.windowDays ?? (draft.attributionWindowHours == null ? '' : draft.attributionWindowHours % HOURS_PER_DAY === 0 ? draft.attributionWindowHours / HOURS_PER_DAY : (draft.attributionWindowHours / HOURS_PER_DAY).toFixed(1)),
410
510
  error: fieldErrors.attributionWindowHours,
411
- onChange: (event)=>set('attributionWindowHours', event.currentTarget.value === '' ? null : Number(event.currentTarget.value))
511
+ onChange: (event)=>set('windowDays', event.currentTarget.value)
412
512
  }),
413
513
  /*#__PURE__*/ _jsx(NumberInput, {
414
514
  id: "xp-goal-minimum",
@@ -446,50 +546,47 @@ export function GoalForm({ surface, id, returnToTest }) {
446
546
  }
447
547
  })
448
548
  }) : /*#__PURE__*/ _jsxs("fieldset", {
549
+ "aria-labelledby": "xp-goal-capping-heading",
449
550
  children: [
450
- /*#__PURE__*/ _jsx("legend", {
551
+ /*#__PURE__*/ _jsx("h3", {
552
+ id: "xp-goal-capping-heading",
451
553
  children: C.capping
452
554
  }),
453
- /*#__PURE__*/ _jsxs(Select, {
555
+ /*#__PURE__*/ _jsx(Select, {
454
556
  id: "xp-goal-cap-type",
455
557
  label: C.capType,
456
- required: source?.kind === 'revenue',
457
- value: draft.capType,
458
- error: fieldErrors.capType,
558
+ value: capChoice,
559
+ options: capOptions,
560
+ disabled: !!source && source.kind !== 'revenue',
561
+ error: fieldErrors.capType ?? (draft.capType !== 'absolute' ? fieldErrors.capValue : undefined),
459
562
  onChange: (event)=>{
460
- const capType = event.currentTarget.value;
461
- setDraft((current)=>({
462
- ...current,
463
- capType,
464
- capValue: capType ? current.capValue : ''
465
- }));
466
- },
467
- children: [
468
- source?.kind !== 'revenue' ? /*#__PURE__*/ _jsx("option", {
469
- value: "",
470
- children: C.noCap
471
- }) : null,
472
- /*#__PURE__*/ _jsx("option", {
473
- value: "percentile",
474
- children: C.percentile
475
- }),
476
- /*#__PURE__*/ _jsx("option", {
477
- value: "absolute",
478
- children: C.absolute
479
- })
480
- ]
563
+ const value = event.currentTarget.value;
564
+ const next = {
565
+ ...draft,
566
+ capType: value === '' || value === 'absolute' ? value : 'percentile',
567
+ capValue: value === 'absolute' ? '' : value,
568
+ capValueEdited: false
569
+ };
570
+ if (value === 'absolute') setDraft(next);
571
+ else select(next);
572
+ }
481
573
  }),
482
- /*#__PURE__*/ _jsx(NumberInput, {
574
+ draft.capType === 'absolute' ? /*#__PURE__*/ _jsx(NumberInput, {
483
575
  id: "xp-goal-cap-value",
484
576
  label: C.capValue,
485
577
  step: "any",
486
578
  min: "0",
487
- disabled: !draft.capType,
488
579
  value: draft.capValue,
489
- error: fieldErrors.capValue,
490
- help: C.capHelp,
491
- onChange: (event)=>set('capValue', event.currentTarget.value)
492
- })
580
+ error: existing && awaitingFixedAmount(draft) ? undefined : fieldErrors.capValue,
581
+ onChange: (event)=>{
582
+ const capValue = event.currentTarget.value;
583
+ setDraft((current)=>({
584
+ ...current,
585
+ capValue,
586
+ capValueEdited: true
587
+ }));
588
+ }
589
+ }) : null
493
590
  ]
494
591
  }),
495
592
  /*#__PURE__*/ _jsx(NumberInput, {
@@ -511,33 +608,24 @@ export function GoalForm({ surface, id, returnToTest }) {
511
608
  })
512
609
  ]
513
610
  }),
514
- /*#__PURE__*/ _jsxs("div", {
611
+ /*#__PURE__*/ _jsx("div", {
515
612
  className: "xp-ui-button-group",
516
- children: [
517
- /*#__PURE__*/ _jsx(Button, {
518
- variant: "primary",
519
- type: "submit",
520
- disabled: pending !== null || !surface.canManage,
521
- busy: pending === 'save',
522
- children: pending === 'save' ? C.saving : C.save
523
- }),
524
- /*#__PURE__*/ _jsx(Button, {
525
- variant: "quiet",
526
- href: listUrl,
527
- children: C.cancel
528
- }),
529
- id === undefined ? null : /*#__PURE__*/ _jsx(Button, {
530
- variant: "danger",
531
- disabled: pending !== null || usedBy > 0 || !surface.canManage,
532
- "aria-describedby": usedBy ? 'xp-goal-used' : undefined,
533
- onClick: (event)=>{
534
- event.currentTarget.focus();
535
- setDeleteError(undefined);
536
- setConfirmDelete(true);
537
- },
538
- children: pending === 'delete' ? C.deleting : C.remove
539
- })
540
- ]
613
+ children: existing ? /*#__PURE__*/ _jsx(Button, {
614
+ variant: "danger",
615
+ disabled: saving === 'saving' || usedBy > 0 || !surface.canManage,
616
+ "aria-describedby": usedBy ? 'xp-goal-used' : undefined,
617
+ onClick: (event)=>{
618
+ event.currentTarget.focus();
619
+ setConfirmDelete(true);
620
+ },
621
+ children: C.remove
622
+ }) : /*#__PURE__*/ _jsx(Button, {
623
+ variant: "primary",
624
+ type: "submit",
625
+ disabled: saving === 'saving' || !surface.canManage,
626
+ busy: saving === 'saving',
627
+ children: saving === 'saving' ? C.saving : C.createGoal
628
+ })
541
629
  }),
542
630
  id !== undefined && usedBy ? /*#__PURE__*/ _jsxs("p", {
543
631
  className: "xp-ui-help",
@@ -552,25 +640,26 @@ export function GoalForm({ surface, id, returnToTest }) {
552
640
  ]
553
641
  }) : null
554
642
  ]
555
- })
643
+ }),
644
+ existing && surface.canManage ? /*#__PURE__*/ _jsx("div", {
645
+ className: "xp-goal-save",
646
+ children: /*#__PURE__*/ _jsx(SaveStatus, {
647
+ save: {
648
+ saving,
649
+ hasUnsaved,
650
+ stale: false,
651
+ errors: {}
652
+ }
653
+ })
654
+ }) : null
556
655
  ]
557
656
  }),
558
- /*#__PURE__*/ _jsx(ConfirmDialog, {
559
- open: confirmDelete,
560
- title: goal ? actionTitle(C.confirmDelete, goal.name) : C.deleteTitle,
657
+ confirmDelete && goal ? /*#__PURE__*/ _jsx(DeleteGoalDialog, {
658
+ goal: goal,
659
+ apiRoute: base,
561
660
  onClose: ()=>setConfirmDelete(false),
562
- cancelLabel: C.cancel,
563
- busy: pending === 'delete',
564
- busyLabel: C.deleting,
565
- description: C.deleteBody,
566
- error: deleteError,
567
- confirm: {
568
- label: C.confirmDelete,
569
- destructive: true,
570
- disabled: pending !== null,
571
- onClick: remove
572
- }
573
- })
661
+ onDeleted: ()=>router.push(listUrl)
662
+ }) : null
574
663
  ]
575
664
  })
576
665
  });