@10x-media/fields 0.1.0-beta.5 → 0.1.0-beta.7

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 (97) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -2
  4. package/dist/exports/client.d.ts +4 -1
  5. package/dist/exports/client.js +4 -1
  6. package/dist/exports/measurement-utils.d.ts +9 -0
  7. package/dist/exports/measurement-utils.js +8 -0
  8. package/dist/exports/measurement.d.ts +11 -0
  9. package/dist/exports/measurement.js +10 -0
  10. package/dist/exports/rsc.d.ts +3 -1
  11. package/dist/exports/rsc.js +3 -1
  12. package/dist/fields/icon/client/icon-field.css +4 -2
  13. package/dist/fields/measurement/client/MeasurementCell.d.ts +18 -0
  14. package/dist/fields/measurement/client/MeasurementCell.js +47 -0
  15. package/dist/fields/measurement/client/MeasurementCell.js.map +1 -0
  16. package/dist/fields/measurement/client/MeasurementField.d.ts +11 -0
  17. package/dist/fields/measurement/client/MeasurementField.js +386 -0
  18. package/dist/fields/measurement/client/MeasurementField.js.map +1 -0
  19. package/dist/fields/measurement/client/MeasurementUnitsProvider.d.ts +24 -0
  20. package/dist/fields/measurement/client/MeasurementUnitsProvider.js +61 -0
  21. package/dist/fields/measurement/client/MeasurementUnitsProvider.js.map +1 -0
  22. package/dist/fields/measurement/client/editModel.js +115 -0
  23. package/dist/fields/measurement/client/editModel.js.map +1 -0
  24. package/dist/fields/measurement/client/measurementCell.css +4 -0
  25. package/dist/fields/measurement/client/measurementField.css +215 -0
  26. package/dist/fields/measurement/engine/convert.d.ts +8 -0
  27. package/dist/fields/measurement/engine/convert.js +21 -0
  28. package/dist/fields/measurement/engine/convert.js.map +1 -0
  29. package/dist/fields/measurement/engine/format.d.ts +37 -0
  30. package/dist/fields/measurement/engine/format.js +156 -0
  31. package/dist/fields/measurement/engine/format.js.map +1 -0
  32. package/dist/fields/measurement/engine/locale.d.ts +25 -0
  33. package/dist/fields/measurement/engine/locale.js +79 -0
  34. package/dist/fields/measurement/engine/locale.js.map +1 -0
  35. package/dist/fields/measurement/engine/precision.d.ts +34 -0
  36. package/dist/fields/measurement/engine/precision.js +63 -0
  37. package/dist/fields/measurement/engine/precision.js.map +1 -0
  38. package/dist/fields/measurement/engine/registry.d.ts +55 -0
  39. package/dist/fields/measurement/engine/registry.js +117 -0
  40. package/dist/fields/measurement/engine/registry.js.map +1 -0
  41. package/dist/fields/measurement/engine/units.d.ts +178 -0
  42. package/dist/fields/measurement/engine/units.js +198 -0
  43. package/dist/fields/measurement/engine/units.js.map +1 -0
  44. package/dist/fields/measurement/measurementField.d.ts +17 -0
  45. package/dist/fields/measurement/measurementField.js +139 -0
  46. package/dist/fields/measurement/measurementField.js.map +1 -0
  47. package/dist/fields/measurement/options.d.ts +76 -0
  48. package/dist/fields/measurement/options.js +9 -0
  49. package/dist/fields/measurement/options.js.map +1 -0
  50. package/dist/fields/measurement/presets.d.ts +117 -0
  51. package/dist/fields/measurement/presets.js +136 -0
  52. package/dist/fields/measurement/presets.js.map +1 -0
  53. package/dist/fields/measurement/server/MeasurementCellServer.d.ts +21 -0
  54. package/dist/fields/measurement/server/MeasurementCellServer.js +53 -0
  55. package/dist/fields/measurement/server/MeasurementCellServer.js.map +1 -0
  56. package/dist/fields/measurement/server/MeasurementFieldServer.d.ts +16 -0
  57. package/dist/fields/measurement/server/MeasurementFieldServer.js +45 -0
  58. package/dist/fields/measurement/server/MeasurementFieldServer.js.map +1 -0
  59. package/dist/fields/measurement/server/getUserUnits.js +39 -0
  60. package/dist/fields/measurement/server/getUserUnits.js.map +1 -0
  61. package/dist/fields/measurement/server/resolvePrecisionSafe.js +24 -0
  62. package/dist/fields/measurement/server/resolvePrecisionSafe.js.map +1 -0
  63. package/dist/fields/measurement/server/resolveRegistryDefault.js +26 -0
  64. package/dist/fields/measurement/server/resolveRegistryDefault.js.map +1 -0
  65. package/dist/index.d.ts +4 -3
  66. package/dist/index.js +16 -0
  67. package/dist/index.js.map +1 -1
  68. package/dist/translations/ar.js +54 -0
  69. package/dist/translations/ar.js.map +1 -0
  70. package/dist/translations/de.js +4 -1
  71. package/dist/translations/de.js.map +1 -1
  72. package/dist/translations/en.js +4 -1
  73. package/dist/translations/en.js.map +1 -1
  74. package/dist/translations/es.js +54 -0
  75. package/dist/translations/es.js.map +1 -0
  76. package/dist/translations/fr.js +54 -0
  77. package/dist/translations/fr.js.map +1 -0
  78. package/dist/translations/id.js +54 -0
  79. package/dist/translations/id.js.map +1 -0
  80. package/dist/translations/index.d.ts +10 -1
  81. package/dist/translations/index.js +19 -1
  82. package/dist/translations/index.js.map +1 -1
  83. package/dist/translations/keys.d.ts +4 -1
  84. package/dist/translations/keys.js +5 -2
  85. package/dist/translations/keys.js.map +1 -1
  86. package/dist/translations/ko.js +54 -0
  87. package/dist/translations/ko.js.map +1 -0
  88. package/dist/translations/pt.js +54 -0
  89. package/dist/translations/pt.js.map +1 -0
  90. package/dist/translations/ru.js +54 -0
  91. package/dist/translations/ru.js.map +1 -0
  92. package/dist/translations/uk.js +54 -0
  93. package/dist/translations/uk.js.map +1 -0
  94. package/dist/translations/zh.js +54 -0
  95. package/dist/translations/zh.js.map +1 -0
  96. package/dist/types.d.ts +20 -1
  97. package/package.json +12 -2
@@ -0,0 +1,386 @@
1
+ "use client";
2
+ import { COMPOUNDS } from "../engine/units.js";
3
+ import { exactModePrecisionOverride, resolvePrecision } from "../engine/precision.js";
4
+ import { keys } from "../../../translations/keys.js";
5
+ import { useTranslation as useTranslation$1 } from "../../../translations/useTranslation.js";
6
+ import { resolveDisplayUnit, systemForLocale } from "../engine/locale.js";
7
+ import { createEngine, defaultEngine } from "../engine/registry.js";
8
+ import { commitDrafts, draftsFor } from "./editModel.js";
9
+ import { useMeasurementUnits } from "./MeasurementUnitsProvider.js";
10
+ import { number } from "payload/shared";
11
+ import { FieldDescription, FieldError, FieldLabel, Popup, RenderCustomComponent, fieldBaseClass, useField } from "@payloadcms/ui";
12
+ import { mergeFieldStyles } from "@payloadcms/ui/shared";
13
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
14
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
15
+ import "./measurementField.css";
16
+ //#region src/fields/measurement/client/MeasurementField.tsx
17
+ const baseClass = "fields-measurement";
18
+ /** MeasurementFieldServer always resolves and threads precision; this only covers a hand-authored Field with no server wrapper. */
19
+ const DEFAULT_PRECISION = resolvePrecision([]);
20
+ const CLEAN = {
21
+ minor: false,
22
+ primary: false
23
+ };
24
+ /**
25
+ * Every value input sizes to its content so "5 ft 11 in" (or a lone scalar)
26
+ * reads as one left-aligned phrase. The half-ch keeps the caret off the edge;
27
+ * the clamp keeps an empty input clickable and a runaway draft from pushing
28
+ * the row into overflow.
29
+ */
30
+ const draftWidth = (draft) => ({ width: `${Math.min(Math.max(draft.length, 2), 12) + .5}ch` });
31
+ const unitKebab = /* @__PURE__ */ jsxs("svg", {
32
+ "aria-hidden": "true",
33
+ className: `${baseClass}__kebab`,
34
+ focusable: "false",
35
+ viewBox: "0 0 4 16",
36
+ xmlns: "http://www.w3.org/2000/svg",
37
+ children: [
38
+ /* @__PURE__ */ jsx("circle", {
39
+ cx: "2",
40
+ cy: "2",
41
+ fill: "currentColor",
42
+ r: "1.6"
43
+ }),
44
+ /* @__PURE__ */ jsx("circle", {
45
+ cx: "2",
46
+ cy: "8",
47
+ fill: "currentColor",
48
+ r: "1.6"
49
+ }),
50
+ /* @__PURE__ */ jsx("circle", {
51
+ cx: "2",
52
+ cy: "14",
53
+ fill: "currentColor",
54
+ r: "1.6"
55
+ })
56
+ ]
57
+ });
58
+ const MeasurementField = (props) => {
59
+ const { field, field: { admin: { className, description, placeholder, readOnly: readOnlyFromAdmin } = {}, label, localized, max, min, name, required }, measurementOptions, path: pathFromProps, readOnly: readOnlyFromProps } = props;
60
+ const { custom, dimension, fallbackUnit, initialUnit, localeDefaults, precision, preferenceKey, registryDefault, storageUnit, units } = measurementOptions;
61
+ const { i18n, t } = useTranslation$1();
62
+ const locale = i18n.language;
63
+ const engine = useMemo(() => custom ? createEngine(custom) : defaultEngine, [custom]);
64
+ const context = useMeasurementUnits();
65
+ const [localUnit, setLocalUnit] = useState(initialUnit ?? null);
66
+ const [system, setSystem] = useState(null);
67
+ useEffect(() => {
68
+ setSystem(systemForLocale(navigator.language));
69
+ }, []);
70
+ const displayUnit = resolveDisplayUnit({
71
+ dimension,
72
+ fallbackUnit,
73
+ localeDefaults,
74
+ preferenceUnit: context ? context.units[preferenceKey] ?? (context.ready ? null : initialUnit ?? null) : localUnit,
75
+ registryDefault,
76
+ system,
77
+ units
78
+ });
79
+ const resolvedPrecision = precision ?? DEFAULT_PRECISION;
80
+ const displayPrecision = useMemo(() => exactModePrecisionOverride(resolvedPrecision, displayUnit), [resolvedPrecision, displayUnit]);
81
+ const fmtBound = useCallback((bound) => {
82
+ try {
83
+ return engine.formatMeasurement(bound, {
84
+ displayUnit,
85
+ locale: `${locale}-u-nu-latn`,
86
+ precision: displayPrecision,
87
+ storageUnit
88
+ });
89
+ } catch {
90
+ return engine.formatMeasurement(bound, {
91
+ displayUnit,
92
+ locale,
93
+ precision: displayPrecision,
94
+ storageUnit
95
+ });
96
+ }
97
+ }, [
98
+ displayUnit,
99
+ engine,
100
+ locale,
101
+ displayPrecision,
102
+ storageUnit
103
+ ]);
104
+ const { customComponents: { AfterInput, BeforeInput, Description, Error: ErrorComponent, Label } = {}, disabled, path, setValue, showError, value } = useField({
105
+ potentiallyStalePath: pathFromProps,
106
+ validate: useCallback((value, options) => {
107
+ if (typeof value === "number" && !Number.isNaN(value)) {
108
+ if (typeof min === "number" && value < min) return t(keys.measurementBelowMin, { min: fmtBound(min) });
109
+ if (typeof max === "number" && value > max) return t(keys.measurementAboveMax, { max: fmtBound(max) });
110
+ }
111
+ return number(value, {
112
+ ...options,
113
+ max: void 0,
114
+ min: void 0,
115
+ name,
116
+ required,
117
+ type: "number"
118
+ });
119
+ }, [
120
+ fmtBound,
121
+ max,
122
+ min,
123
+ name,
124
+ required,
125
+ t
126
+ ])
127
+ });
128
+ const isReadOnly = Boolean(readOnlyFromProps || disabled || readOnlyFromAdmin);
129
+ const numericValue = typeof value === "number" && !Number.isNaN(value) ? value : null;
130
+ const draftOpts = useMemo(() => ({
131
+ displayUnit,
132
+ draft: resolvedPrecision.draft,
133
+ engine,
134
+ precision: displayPrecision,
135
+ storageDigits: resolvedPrecision.storage,
136
+ storageUnit
137
+ }), [
138
+ displayUnit,
139
+ engine,
140
+ displayPrecision,
141
+ resolvedPrecision,
142
+ storageUnit
143
+ ]);
144
+ const boundsMessage = useMemo(() => {
145
+ if (numericValue === null) return void 0;
146
+ if (typeof min === "number" && numericValue < min) return t(keys.measurementBelowMin, { min: fmtBound(min) });
147
+ if (typeof max === "number" && numericValue > max) return t(keys.measurementAboveMax, { max: fmtBound(max) });
148
+ }, [
149
+ numericValue,
150
+ min,
151
+ max,
152
+ fmtBound,
153
+ t
154
+ ]);
155
+ const editingRef = useRef(false);
156
+ const [drafts, setDrafts] = useState(() => draftsFor(numericValue, draftOpts));
157
+ const paintedDraftsRef = useRef(drafts);
158
+ const paintedStoredRef = useRef(numericValue);
159
+ const [dirty, setDirty] = useState(CLEAN);
160
+ useEffect(() => {
161
+ if (!editingRef.current) {
162
+ const resynced = draftsFor(numericValue, draftOpts);
163
+ setDrafts(resynced);
164
+ paintedDraftsRef.current = resynced;
165
+ paintedStoredRef.current = numericValue;
166
+ setDirty(CLEAN);
167
+ }
168
+ }, [numericValue, draftOpts]);
169
+ const onDraftChange = useCallback((part) => (event) => {
170
+ editingRef.current = true;
171
+ const next = {
172
+ ...drafts,
173
+ [part]: event.target.value
174
+ };
175
+ const nextDirty = {
176
+ ...dirty,
177
+ [part]: true
178
+ };
179
+ setDrafts(next);
180
+ setDirty(nextDirty);
181
+ setValue(commitDrafts(next, {
182
+ ...draftOpts,
183
+ dirty: nextDirty,
184
+ entry: resolvedPrecision.entry,
185
+ paintedDrafts: paintedDraftsRef.current,
186
+ storedValue: paintedStoredRef.current
187
+ }));
188
+ }, [
189
+ dirty,
190
+ drafts,
191
+ draftOpts,
192
+ resolvedPrecision.entry,
193
+ setValue
194
+ ]);
195
+ const onBlur = useCallback(() => {
196
+ editingRef.current = false;
197
+ const resynced = draftsFor(numericValue, draftOpts);
198
+ setDrafts(resynced);
199
+ paintedDraftsRef.current = resynced;
200
+ paintedStoredRef.current = numericValue;
201
+ setDirty(CLEAN);
202
+ }, [numericValue, draftOpts]);
203
+ const selectUnit = useCallback((unit) => {
204
+ editingRef.current = false;
205
+ setDirty(CLEAN);
206
+ if (context) context.setUnit(preferenceKey, unit);
207
+ else setLocalUnit(unit);
208
+ }, [context, preferenceKey]);
209
+ const isCompound = engine.isCompoundUnit(displayUnit);
210
+ const compoundDef = isCompound ? COMPOUNDS[displayUnit] : null;
211
+ const inputId = `field-${path?.replace(/\./g, "__")}`;
212
+ const styles = useMemo(() => mergeFieldStyles(field), [field]);
213
+ const primaryInputRef = useRef(null);
214
+ const minorInputRef = useRef(null);
215
+ const focusNearestInput = useCallback((event) => {
216
+ const target = event.target;
217
+ const isUnitSuffix = target.closest(`.${baseClass}__unit-static`) !== null;
218
+ if (target !== event.currentTarget && !isUnitSuffix) return;
219
+ event.preventDefault();
220
+ const active = document.activeElement;
221
+ if (active === primaryInputRef.current || active === minorInputRef.current) return;
222
+ const [first, ...rest] = [primaryInputRef.current, minorInputRef.current].filter((input) => input !== null);
223
+ if (!first) return;
224
+ const distanceFrom = (input) => {
225
+ const rect = input.getBoundingClientRect();
226
+ return Math.abs(event.clientX - (rect.left + rect.width / 2));
227
+ };
228
+ let nearest = first;
229
+ let nearestDistance = distanceFrom(first);
230
+ for (const input of rest) {
231
+ const distance = distanceFrom(input);
232
+ if (distance < nearestDistance) {
233
+ nearestDistance = distance;
234
+ nearest = input;
235
+ }
236
+ }
237
+ nearest.focus();
238
+ }, []);
239
+ const isUnitInteractive = units.length > 1 && !isReadOnly;
240
+ const placeholderText = typeof placeholder === "string" ? placeholder : void 0;
241
+ const renderUnitPanel = ({ close }) => /* @__PURE__ */ jsx("div", {
242
+ "aria-label": t(keys.selectUnit),
243
+ className: `${baseClass}__unit-panel`,
244
+ role: "listbox",
245
+ children: units.map((unit) => /* @__PURE__ */ jsxs("button", {
246
+ "aria-selected": unit === displayUnit,
247
+ className: `${baseClass}__unit-option`,
248
+ onClick: () => {
249
+ selectUnit(unit);
250
+ close();
251
+ },
252
+ role: "option",
253
+ type: "button",
254
+ children: [/* @__PURE__ */ jsx("span", { children: engine.unitLabel(unit, locale, "long") }), /* @__PURE__ */ jsx("span", {
255
+ className: `${baseClass}__unit-symbol`,
256
+ children: engine.unitLabel(unit, locale, "short")
257
+ })]
258
+ }, unit))
259
+ });
260
+ const renderUnitSuffix = (unit) => /* @__PURE__ */ jsx("span", {
261
+ className: `${baseClass}__unit-static`,
262
+ children: engine.unitLabel(unit, locale, "short")
263
+ });
264
+ const renderMenuTrigger = () => {
265
+ if (!isUnitInteractive) return null;
266
+ const shortLabel = engine.unitLabel(displayUnit, locale, "short");
267
+ return /* @__PURE__ */ jsx(Popup, {
268
+ button: /* @__PURE__ */ jsxs(Fragment$1, { children: [unitKebab, /* @__PURE__ */ jsxs("span", {
269
+ className: `${baseClass}__sr-only`,
270
+ children: [
271
+ t(keys.selectUnit),
272
+ ": ",
273
+ shortLabel
274
+ ]
275
+ })] }),
276
+ buttonClassName: `${baseClass}__unit-trigger`,
277
+ buttonType: "default",
278
+ caret: false,
279
+ className: `${baseClass}__popup`,
280
+ horizontalAlign: "right",
281
+ render: renderUnitPanel,
282
+ size: "fit-content",
283
+ verticalAlign: "bottom"
284
+ });
285
+ };
286
+ return /* @__PURE__ */ jsxs("div", {
287
+ className: [
288
+ fieldBaseClass,
289
+ baseClass,
290
+ className,
291
+ showError && "error",
292
+ isReadOnly && "read-only"
293
+ ].filter(Boolean).join(" "),
294
+ style: styles,
295
+ children: [/* @__PURE__ */ jsx(RenderCustomComponent, {
296
+ CustomComponent: Label,
297
+ Fallback: /* @__PURE__ */ jsx(FieldLabel, {
298
+ label,
299
+ localized,
300
+ path,
301
+ required
302
+ })
303
+ }), /* @__PURE__ */ jsxs("div", {
304
+ className: `${fieldBaseClass}__wrap`,
305
+ children: [
306
+ /* @__PURE__ */ jsx(RenderCustomComponent, {
307
+ CustomComponent: ErrorComponent,
308
+ Fallback: /* @__PURE__ */ jsx(FieldError, {
309
+ message: boundsMessage,
310
+ path,
311
+ showError
312
+ })
313
+ }),
314
+ BeforeInput,
315
+ /* @__PURE__ */ jsxs("div", {
316
+ className: `${baseClass}__container`,
317
+ onMouseDown: focusNearestInput,
318
+ children: [isCompound && compoundDef ? /* @__PURE__ */ jsxs("span", {
319
+ className: `${baseClass}__compound`,
320
+ onMouseDown: focusNearestInput,
321
+ children: [/* @__PURE__ */ jsxs("span", {
322
+ className: `${baseClass}__part`,
323
+ children: [/* @__PURE__ */ jsx("input", {
324
+ className: `${baseClass}__input`,
325
+ id: inputId,
326
+ inputMode: "decimal",
327
+ name: path,
328
+ onBlur,
329
+ onChange: onDraftChange("primary"),
330
+ readOnly: isReadOnly,
331
+ ref: primaryInputRef,
332
+ step: "any",
333
+ style: draftWidth(drafts.primary),
334
+ type: "number",
335
+ value: drafts.primary
336
+ }), renderUnitSuffix(compoundDef.major)]
337
+ }), /* @__PURE__ */ jsxs("span", {
338
+ className: `${baseClass}__part`,
339
+ children: [/* @__PURE__ */ jsx("input", {
340
+ "aria-label": engine.unitLabel(compoundDef.minor, locale, "long"),
341
+ className: `${baseClass}__input`,
342
+ inputMode: "decimal",
343
+ max: compoundDef.ratio - .001,
344
+ min: 0,
345
+ onBlur,
346
+ onChange: onDraftChange("minor"),
347
+ readOnly: isReadOnly,
348
+ ref: minorInputRef,
349
+ step: "any",
350
+ style: draftWidth(drafts.minor),
351
+ type: "number",
352
+ value: drafts.minor
353
+ }), renderUnitSuffix(compoundDef.minor)]
354
+ })]
355
+ }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("input", {
356
+ className: `${baseClass}__input`,
357
+ id: inputId,
358
+ inputMode: "decimal",
359
+ name: path,
360
+ onBlur,
361
+ onChange: onDraftChange("primary"),
362
+ placeholder: placeholderText,
363
+ readOnly: isReadOnly,
364
+ ref: primaryInputRef,
365
+ step: "any",
366
+ style: draftWidth(drafts.primary || placeholderText || ""),
367
+ type: "number",
368
+ value: drafts.primary
369
+ }), renderUnitSuffix(displayUnit)] }), renderMenuTrigger()]
370
+ }),
371
+ AfterInput,
372
+ /* @__PURE__ */ jsx(RenderCustomComponent, {
373
+ CustomComponent: Description,
374
+ Fallback: /* @__PURE__ */ jsx(FieldDescription, {
375
+ description,
376
+ path
377
+ })
378
+ })
379
+ ]
380
+ })]
381
+ });
382
+ };
383
+ //#endregion
384
+ export { MeasurementField };
385
+
386
+ //# sourceMappingURL=MeasurementField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MeasurementField.js","names":["useTranslation"],"sources":["../../../../src/fields/measurement/client/MeasurementField.tsx"],"sourcesContent":["'use client'\nimport {\n\tFieldDescription,\n\tFieldError,\n\tFieldLabel,\n\tfieldBaseClass,\n\tPopup,\n\tRenderCustomComponent,\n\tuseField,\n} from '@payloadcms/ui'\nimport { mergeFieldStyles } from '@payloadcms/ui/shared'\nimport type { NumberFieldClientProps, Validate } from 'payload'\nimport { number } from 'payload/shared'\nimport type React from 'react'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { keys } from '../../../translations/keys'\nimport { useTranslation } from '../../../translations/useTranslation'\nimport { type MeasurementSystem, systemForLocale } from '../engine/locale'\nimport { exactModePrecisionOverride, resolvePrecision } from '../engine/precision'\nimport { createEngine, defaultEngine } from '../engine/registry'\nimport { COMPOUNDS, type MeasurementUnitId } from '../engine/units'\nimport type { MeasurementResolvedClientOptions } from '../options'\nimport {\n\tcommitDrafts,\n\ttype DirtyDrafts,\n\tdraftsFor,\n\ttype MeasurementDrafts,\n\tresolveDisplayUnit,\n} from './editModel'\nimport { useMeasurementUnits } from './MeasurementUnitsProvider'\nimport './measurementField.css'\n\nconst baseClass = 'fields-measurement'\n\n/** MeasurementFieldServer always resolves and threads precision; this only covers a hand-authored Field with no server wrapper. */\nconst DEFAULT_PRECISION = resolvePrecision([])\n\nconst CLEAN: DirtyDrafts = { minor: false, primary: false }\n\n/**\n * Every value input sizes to its content so \"5 ft 11 in\" (or a lone scalar)\n * reads as one left-aligned phrase. The half-ch keeps the caret off the edge;\n * the clamp keeps an empty input clickable and a runaway draft from pushing\n * the row into overflow.\n */\nconst draftWidth = (draft: string): React.CSSProperties => ({\n\twidth: `${Math.min(Math.max(draft.length, 2), 12) + 0.5}ch`,\n})\n\nconst unitKebab = (\n\t<svg\n\t\taria-hidden=\"true\"\n\t\tclassName={`${baseClass}__kebab`}\n\t\tfocusable=\"false\"\n\t\tviewBox=\"0 0 4 16\"\n\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t>\n\t\t<circle cx=\"2\" cy=\"2\" fill=\"currentColor\" r=\"1.6\" />\n\t\t<circle cx=\"2\" cy=\"8\" fill=\"currentColor\" r=\"1.6\" />\n\t\t<circle cx=\"2\" cy=\"14\" fill=\"currentColor\" r=\"1.6\" />\n\t</svg>\n)\n\nexport type MeasurementFieldProps = {\n\tmeasurementOptions: MeasurementResolvedClientOptions\n} & NumberFieldClientProps\n\nexport const MeasurementField: React.FC<MeasurementFieldProps> = (props) => {\n\tconst {\n\t\tfield,\n\t\tfield: {\n\t\t\tadmin: { className, description, placeholder, readOnly: readOnlyFromAdmin } = {},\n\t\t\tlabel,\n\t\t\tlocalized,\n\t\t\tmax,\n\t\t\tmin,\n\t\t\tname,\n\t\t\trequired,\n\t\t},\n\t\tmeasurementOptions,\n\t\tpath: pathFromProps,\n\t\treadOnly: readOnlyFromProps,\n\t} = props\n\tconst {\n\t\tcustom,\n\t\tdimension,\n\t\tfallbackUnit,\n\t\tinitialUnit,\n\t\tlocaleDefaults,\n\t\tprecision,\n\t\tpreferenceKey,\n\t\tregistryDefault,\n\t\tstorageUnit,\n\t\tunits,\n\t} = measurementOptions\n\tconst { i18n, t } = useTranslation()\n\tconst locale = i18n.language\n\n\t// Every conversion, label and precision lookup runs through this, so the\n\t// field's custom units behave exactly like the built-in ones.\n\tconst engine = useMemo(() => (custom ? createEngine(custom) : defaultEngine), [custom])\n\n\tconst context = useMeasurementUnits()\n\t// Standalone fallback when the plugin (and so the provider) is absent\n\tconst [localUnit, setLocalUnit] = useState<MeasurementUnitId | null>(initialUnit ?? null)\n\t// navigator is read post-hydration only, or SSR markup would mismatch\n\tconst [system, setSystem] = useState<MeasurementSystem | null>(null)\n\tuseEffect(() => {\n\t\tsetSystem(systemForLocale(navigator.language))\n\t}, [])\n\n\tconst preferenceUnit = context\n\t\t? (context.units[preferenceKey] ?? (context.ready ? null : (initialUnit ?? null)))\n\t\t: localUnit\n\tconst displayUnit = resolveDisplayUnit({\n\t\tdimension,\n\t\tfallbackUnit,\n\t\tlocaleDefaults,\n\t\tpreferenceUnit,\n\t\tregistryDefault,\n\t\tsystem,\n\t\tunits,\n\t})\n\n\tconst resolvedPrecision = precision ?? DEFAULT_PRECISION\n\t// Bound messages sit next to a type=number input, which always renders Latin\n\t// digits; force the same numerals here so \"min 5\" and \"5\" agree in RTL/native-digit\n\t// locales (Arabic, Persian). The input itself stays native-digit for display. Exact\n\t// mode uses the same storage-digit override as the cell, so error text and cell\n\t// text always agree. Memoized: exact mode builds a fresh object every call, and an\n\t// unmemoized value here fed draftOpts -> the resync effect -> setDrafts in a loop\n\t// that never settled.\n\tconst displayPrecision = useMemo(\n\t\t() => exactModePrecisionOverride(resolvedPrecision, displayUnit),\n\t\t[resolvedPrecision, displayUnit]\n\t)\n\tconst fmtBound = useCallback(\n\t\t(bound: number) => {\n\t\t\ttry {\n\t\t\t\treturn engine.formatMeasurement(bound, {\n\t\t\t\t\tdisplayUnit,\n\t\t\t\t\tlocale: `${locale}-u-nu-latn`,\n\t\t\t\t\tprecision: displayPrecision,\n\t\t\t\t\tstorageUnit,\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\treturn engine.formatMeasurement(bound, {\n\t\t\t\t\tdisplayUnit,\n\t\t\t\t\tlocale,\n\t\t\t\t\tprecision: displayPrecision,\n\t\t\t\t\tstorageUnit,\n\t\t\t\t})\n\t\t\t}\n\t\t},\n\t\t[displayUnit, engine, locale, displayPrecision, storageUnit]\n\t)\n\n\tconst memoizedValidate = useCallback<Validate<number | null | undefined>>(\n\t\t(value, options) => {\n\t\t\tif (typeof value === 'number' && !Number.isNaN(value)) {\n\t\t\t\tif (typeof min === 'number' && value < min) {\n\t\t\t\t\treturn t(keys.measurementBelowMin, { min: fmtBound(min) })\n\t\t\t\t}\n\t\t\t\tif (typeof max === 'number' && value > max) {\n\t\t\t\t\treturn t(keys.measurementAboveMax, { max: fmtBound(max) })\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn number(value, {\n\t\t\t\t...options,\n\t\t\t\tmax: undefined,\n\t\t\t\tmin: undefined,\n\t\t\t\tname,\n\t\t\t\trequired,\n\t\t\t\ttype: 'number',\n\t\t\t} as Parameters<typeof number>[1])\n\t\t},\n\t\t[fmtBound, max, min, name, required, t]\n\t)\n\n\tconst {\n\t\tcustomComponents: { AfterInput, BeforeInput, Description, Error: ErrorComponent, Label } = {},\n\t\tdisabled,\n\t\tpath,\n\t\tsetValue,\n\t\tshowError,\n\t\tvalue,\n\t} = useField<number | null>({ potentiallyStalePath: pathFromProps, validate: memoizedValidate })\n\n\t// renderField only maps permissions into the readOnly clientProp; admin.readOnly\n\t// reaches custom Field components solely via clientField.admin\n\tconst isReadOnly = Boolean(readOnlyFromProps || disabled || readOnlyFromAdmin)\n\n\tconst numericValue = typeof value === 'number' && !Number.isNaN(value) ? value : null\n\tconst draftOpts = useMemo(\n\t\t() => ({\n\t\t\tdisplayUnit,\n\t\t\tdraft: resolvedPrecision.draft,\n\t\t\tengine,\n\t\t\tprecision: displayPrecision,\n\t\t\tstorageDigits: resolvedPrecision.storage,\n\t\t\tstorageUnit,\n\t\t}),\n\t\t[displayUnit, engine, displayPrecision, resolvedPrecision, storageUnit]\n\t)\n\n\t// Payload's server-driven form-state refresh (conditional-logic revalidation on\n\t// every change) can replace this field's errorMessage with the server's raw,\n\t// storage-unit message before our own throttled client validate lands. Compute\n\t// the unit-aware bound message independently and pass it straight to FieldError\n\t// so display never depends on winning that race.\n\tconst boundsMessage = useMemo(() => {\n\t\tif (numericValue === null) return undefined\n\t\tif (typeof min === 'number' && numericValue < min) {\n\t\t\treturn t(keys.measurementBelowMin, { min: fmtBound(min) })\n\t\t}\n\t\tif (typeof max === 'number' && numericValue > max) {\n\t\t\treturn t(keys.measurementAboveMax, { max: fmtBound(max) })\n\t\t}\n\t\treturn undefined\n\t}, [numericValue, min, max, fmtBound, t])\n\n\tconst editingRef = useRef(false)\n\tconst [drafts, setDrafts] = useState<MeasurementDrafts>(() => draftsFor(numericValue, draftOpts))\n\t// The drafts as painted on screen immediately before the current edit, refreshed\n\t// only at a resync (mount, external value, blur, unit switch) and never per\n\t// keystroke. A carry-rounded display (182.5 cm storage paints as 6 ft 0 in even\n\t// though the exact split is 5 ft 11.850394 in) must never be mistaken for the\n\t// exact stored value, so commits diff the typed value against this baseline\n\t// rather than against the exact decompose.\n\tconst paintedDraftsRef = useRef<MeasurementDrafts>(drafts)\n\t// The stored value the painted drafts were derived from, frozen at the same\n\t// resync points as paintedDraftsRef. A mid-edit setValue call updates Payload's\n\t// live form value (and so `numericValue`) before the viewer blurs; diffing the\n\t// next keystroke's delta against that advanced value, instead of this frozen\n\t// snapshot, would re-apply an already-committed delta on top of itself.\n\tconst paintedStoredRef = useRef<number | null>(numericValue)\n\t// Which part the viewer has actually typed into since the last resync: an\n\t// untouched part must commit the value it already holds, never whatever the\n\t// display-policy draft happens to show for it.\n\tconst [dirty, setDirty] = useState<DirtyDrafts>(CLEAN)\n\tuseEffect(() => {\n\t\tif (!editingRef.current) {\n\t\t\tconst resynced = draftsFor(numericValue, draftOpts)\n\t\t\tsetDrafts(resynced)\n\t\t\tpaintedDraftsRef.current = resynced\n\t\t\tpaintedStoredRef.current = numericValue\n\t\t\tsetDirty(CLEAN)\n\t\t}\n\t}, [numericValue, draftOpts])\n\n\tconst onDraftChange = useCallback(\n\t\t(part: keyof MeasurementDrafts) => (event: React.ChangeEvent<HTMLInputElement>) => {\n\t\t\teditingRef.current = true\n\t\t\tconst next = { ...drafts, [part]: event.target.value }\n\t\t\tconst nextDirty = { ...dirty, [part]: true }\n\t\t\tsetDrafts(next)\n\t\t\tsetDirty(nextDirty)\n\t\t\tsetValue(\n\t\t\t\tcommitDrafts(next, {\n\t\t\t\t\t...draftOpts,\n\t\t\t\t\tdirty: nextDirty,\n\t\t\t\t\tentry: resolvedPrecision.entry,\n\t\t\t\t\tpaintedDrafts: paintedDraftsRef.current,\n\t\t\t\t\tstoredValue: paintedStoredRef.current,\n\t\t\t\t})\n\t\t\t)\n\t\t},\n\t\t[dirty, drafts, draftOpts, resolvedPrecision.entry, setValue]\n\t)\n\n\tconst onBlur = useCallback(() => {\n\t\teditingRef.current = false\n\t\tconst resynced = draftsFor(numericValue, draftOpts)\n\t\tsetDrafts(resynced)\n\t\tpaintedDraftsRef.current = resynced\n\t\tpaintedStoredRef.current = numericValue\n\t\tsetDirty(CLEAN)\n\t}, [numericValue, draftOpts])\n\n\tconst selectUnit = useCallback(\n\t\t(unit: MeasurementUnitId) => {\n\t\t\teditingRef.current = false\n\t\t\tsetDirty(CLEAN)\n\t\t\tif (context) context.setUnit(preferenceKey, unit)\n\t\t\telse setLocalUnit(unit)\n\t\t},\n\t\t[context, preferenceKey]\n\t)\n\n\tconst isCompound = engine.isCompoundUnit(displayUnit)\n\tconst compoundDef = isCompound ? COMPOUNDS[displayUnit] : null\n\tconst inputId = `field-${path?.replace(/\\./g, '__')}`\n\tconst styles = useMemo(() => mergeFieldStyles(field), [field])\n\n\tconst primaryInputRef = useRef<HTMLInputElement>(null)\n\tconst minorInputRef = useRef<HTMLInputElement>(null)\n\n\t// Dead-space (or the passive unit suffix, e.g. \"in\") mousedown focuses the nearest\n\t// input like a native control; preventDefault stops an already-focused input from\n\t// blurring, so we never steal focus from it. The suffix is never inside the unit\n\t// trigger button, so this never intercepts opening the unit popup.\n\tconst focusNearestInput = useCallback((event: React.MouseEvent<HTMLElement>) => {\n\t\tconst target = event.target as HTMLElement\n\t\tconst isUnitSuffix = target.closest(`.${baseClass}__unit-static`) !== null\n\t\tif (target !== event.currentTarget && !isUnitSuffix) return\n\t\tevent.preventDefault()\n\t\tconst active = document.activeElement\n\t\tif (active === primaryInputRef.current || active === minorInputRef.current) return\n\t\tconst inputs = [primaryInputRef.current, minorInputRef.current].filter(\n\t\t\t(input): input is HTMLInputElement => input !== null\n\t\t)\n\t\tconst [first, ...rest] = inputs\n\t\tif (!first) return\n\t\tconst distanceFrom = (input: HTMLInputElement) => {\n\t\t\tconst rect = input.getBoundingClientRect()\n\t\t\treturn Math.abs(event.clientX - (rect.left + rect.width / 2))\n\t\t}\n\t\tlet nearest = first\n\t\tlet nearestDistance = distanceFrom(first)\n\t\tfor (const input of rest) {\n\t\t\tconst distance = distanceFrom(input)\n\t\t\tif (distance < nearestDistance) {\n\t\t\t\tnearestDistance = distance\n\t\t\t\tnearest = input\n\t\t\t}\n\t\t}\n\t\tnearest.focus()\n\t}, [])\n\n\tconst isUnitInteractive = units.length > 1 && !isReadOnly\n\tconst placeholderText = typeof placeholder === 'string' ? placeholder : undefined\n\n\tconst renderUnitPanel = ({ close }: { close: () => void }) => (\n\t\t<div aria-label={t(keys.selectUnit)} className={`${baseClass}__unit-panel`} role=\"listbox\">\n\t\t\t{units.map((unit) => (\n\t\t\t\t<button\n\t\t\t\t\taria-selected={unit === displayUnit}\n\t\t\t\t\tclassName={`${baseClass}__unit-option`}\n\t\t\t\t\tkey={unit}\n\t\t\t\t\tonClick={() => {\n\t\t\t\t\t\tselectUnit(unit)\n\t\t\t\t\t\tclose()\n\t\t\t\t\t}}\n\t\t\t\t\trole=\"option\"\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t>\n\t\t\t\t\t<span>{engine.unitLabel(unit, locale, 'long')}</span>\n\t\t\t\t\t<span className={`${baseClass}__unit-symbol`}>\n\t\t\t\t\t\t{engine.unitLabel(unit, locale, 'short')}\n\t\t\t\t\t</span>\n\t\t\t\t</button>\n\t\t\t))}\n\t\t</div>\n\t)\n\n\tconst renderUnitSuffix = (unit: MeasurementUnitId) => (\n\t\t<span className={`${baseClass}__unit-static`}>{engine.unitLabel(unit, locale, 'short')}</span>\n\t)\n\n\t// One kebab per field, pinned to the row's right edge; the unit text itself\n\t// stays a passive suffix so value and unit read as a single phrase.\n\tconst renderMenuTrigger = () => {\n\t\tif (!isUnitInteractive) return null\n\t\tconst shortLabel = engine.unitLabel(displayUnit, locale, 'short')\n\t\treturn (\n\t\t\t<Popup\n\t\t\t\tbutton={\n\t\t\t\t\t<>\n\t\t\t\t\t\t{unitKebab}\n\t\t\t\t\t\t<span className={`${baseClass}__sr-only`}>\n\t\t\t\t\t\t\t{t(keys.selectUnit)}: {shortLabel}\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</>\n\t\t\t\t}\n\t\t\t\tbuttonClassName={`${baseClass}__unit-trigger`}\n\t\t\t\tbuttonType=\"default\"\n\t\t\t\tcaret={false}\n\t\t\t\tclassName={`${baseClass}__popup`}\n\t\t\t\thorizontalAlign=\"right\"\n\t\t\t\trender={renderUnitPanel}\n\t\t\t\tsize=\"fit-content\"\n\t\t\t\tverticalAlign=\"bottom\"\n\t\t\t/>\n\t\t)\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tclassName={[\n\t\t\t\tfieldBaseClass,\n\t\t\t\tbaseClass,\n\t\t\t\tclassName,\n\t\t\t\tshowError && 'error',\n\t\t\t\tisReadOnly && 'read-only',\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' ')}\n\t\t\tstyle={styles}\n\t\t>\n\t\t\t<RenderCustomComponent\n\t\t\t\tCustomComponent={Label}\n\t\t\t\tFallback={\n\t\t\t\t\t<FieldLabel label={label} localized={localized} path={path} required={required} />\n\t\t\t\t}\n\t\t\t/>\n\t\t\t<div className={`${fieldBaseClass}__wrap`}>\n\t\t\t\t<RenderCustomComponent\n\t\t\t\t\tCustomComponent={ErrorComponent}\n\t\t\t\t\tFallback={<FieldError message={boundsMessage} path={path} showError={showError} />}\n\t\t\t\t/>\n\t\t\t\t{BeforeInput}\n\t\t\t\t{/* biome-ignore lint/a11y/noStaticElementInteractions: mousedown only refocuses an inner input, it adds no control and changes no semantics */}\n\t\t\t\t<div className={`${baseClass}__container`} onMouseDown={focusNearestInput}>\n\t\t\t\t\t{isCompound && compoundDef ? (\n\t\t\t\t\t\t// biome-ignore lint/a11y/noStaticElementInteractions: same as the container, refocuses whichever inner input is nearest\n\t\t\t\t\t\t<span className={`${baseClass}__compound`} onMouseDown={focusNearestInput}>\n\t\t\t\t\t\t\t<span className={`${baseClass}__part`}>\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tclassName={`${baseClass}__input`}\n\t\t\t\t\t\t\t\t\tid={inputId}\n\t\t\t\t\t\t\t\t\tinputMode=\"decimal\"\n\t\t\t\t\t\t\t\t\tname={path}\n\t\t\t\t\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\t\t\t\t\tonChange={onDraftChange('primary')}\n\t\t\t\t\t\t\t\t\treadOnly={isReadOnly}\n\t\t\t\t\t\t\t\t\tref={primaryInputRef}\n\t\t\t\t\t\t\t\t\tstep=\"any\"\n\t\t\t\t\t\t\t\t\tstyle={draftWidth(drafts.primary)}\n\t\t\t\t\t\t\t\t\ttype=\"number\"\n\t\t\t\t\t\t\t\t\tvalue={drafts.primary}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t{renderUnitSuffix(compoundDef.major)}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t<span className={`${baseClass}__part`}>\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\taria-label={engine.unitLabel(compoundDef.minor, locale, 'long')}\n\t\t\t\t\t\t\t\t\tclassName={`${baseClass}__input`}\n\t\t\t\t\t\t\t\t\tinputMode=\"decimal\"\n\t\t\t\t\t\t\t\t\tmax={compoundDef.ratio - 0.001}\n\t\t\t\t\t\t\t\t\tmin={0}\n\t\t\t\t\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\t\t\t\t\tonChange={onDraftChange('minor')}\n\t\t\t\t\t\t\t\t\treadOnly={isReadOnly}\n\t\t\t\t\t\t\t\t\tref={minorInputRef}\n\t\t\t\t\t\t\t\t\tstep=\"any\"\n\t\t\t\t\t\t\t\t\tstyle={draftWidth(drafts.minor)}\n\t\t\t\t\t\t\t\t\ttype=\"number\"\n\t\t\t\t\t\t\t\t\tvalue={drafts.minor}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t{renderUnitSuffix(compoundDef.minor)}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<>\n\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\tclassName={`${baseClass}__input`}\n\t\t\t\t\t\t\t\tid={inputId}\n\t\t\t\t\t\t\t\tinputMode=\"decimal\"\n\t\t\t\t\t\t\t\tname={path}\n\t\t\t\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\t\t\t\tonChange={onDraftChange('primary')}\n\t\t\t\t\t\t\t\tplaceholder={placeholderText}\n\t\t\t\t\t\t\t\treadOnly={isReadOnly}\n\t\t\t\t\t\t\t\tref={primaryInputRef}\n\t\t\t\t\t\t\t\tstep=\"any\"\n\t\t\t\t\t\t\t\tstyle={draftWidth(drafts.primary || placeholderText || '')}\n\t\t\t\t\t\t\t\ttype=\"number\"\n\t\t\t\t\t\t\t\tvalue={drafts.primary}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{renderUnitSuffix(displayUnit)}\n\t\t\t\t\t\t</>\n\t\t\t\t\t)}\n\t\t\t\t\t{renderMenuTrigger()}\n\t\t\t\t</div>\n\t\t\t\t{AfterInput}\n\t\t\t\t<RenderCustomComponent\n\t\t\t\t\tCustomComponent={Description}\n\t\t\t\t\tFallback={<FieldDescription description={description} path={path} />}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAM,YAAY;;AAGlB,MAAM,oBAAoB,iBAAiB,CAAC,CAAC;AAE7C,MAAM,QAAqB;CAAE,OAAO;CAAO,SAAS;AAAM;;;;;;;AAQ1D,MAAM,cAAc,WAAwC,EAC3D,OAAO,GAAG,KAAK,IAAI,KAAK,IAAI,MAAM,QAAQ,CAAC,GAAG,EAAE,IAAI,GAAI,IACzD;AAEA,MAAM,YACL,qBAAC,OAAD;CACC,eAAY;CACZ,WAAW,GAAG,UAAU;CACxB,WAAU;CACV,SAAQ;CACR,OAAM;WALP;EAOC,oBAAC,UAAD;GAAQ,IAAG;GAAI,IAAG;GAAI,MAAK;GAAe,GAAE;EAAO,CAAA;EACnD,oBAAC,UAAD;GAAQ,IAAG;GAAI,IAAG;GAAI,MAAK;GAAe,GAAE;EAAO,CAAA;EACnD,oBAAC,UAAD;GAAQ,IAAG;GAAI,IAAG;GAAK,MAAK;GAAe,GAAE;EAAO,CAAA;CAChD;;AAON,MAAa,oBAAqD,UAAU;CAC3E,MAAM,EACL,OACA,OAAO,EACN,OAAO,EAAE,WAAW,aAAa,aAAa,UAAU,sBAAsB,CAAC,GAC/E,OACA,WACA,KACA,KACA,MACA,YAED,oBACA,MAAM,eACN,UAAU,sBACP;CACJ,MAAM,EACL,QACA,WACA,cACA,aACA,gBACA,WACA,eACA,iBACA,aACA,UACG;CACJ,MAAM,EAAE,MAAM,MAAMA,iBAAe;CACnC,MAAM,SAAS,KAAK;CAIpB,MAAM,SAAS,cAAe,SAAS,aAAa,MAAM,IAAI,eAAgB,CAAC,MAAM,CAAC;CAE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B,WAAU;QACV,KAAK,YAAY,QAAQ;QACzB,KAAK;QACG;QACR,UAAU,cAAc,OAAO;QAC/B,UAAU;QACV,KAAK;QACL,MAAK;QACL,OAAO,WAAW,OAAO,KAAK;QAC9B,MAAK;QACL,OAAO,OAAO;OACd,CAAA,GACA,iBAAiB,YAAY,KAAK,CAC9B;QACD;UAEN,qBAAA,YAAA,EAAA,UAAA,CACC,oBAAC,SAAD;MACC,WAAW,GAAG,UAAU;MACxB,IAAI;MACJ,WAAU;MACV,MAAM;MACE;MACR,UAAU,cAAc,SAAS;MACjC,aAAa;MACb,UAAU;MACV,KAAK;MACL,MAAK;MACL,OAAO,WAAW,OAAO,WAAW,mBAAmB,EAAE;MACzD,MAAK;MACL,OAAO,OAAO;KACd,CAAA,GACA,iBAAiB,WAAW,CAC5B,EAAA,CAAA,GAEF,kBAAkB,CACf;;IACJ;IACD,oBAAC,uBAAD;KACC,iBAAiB;KACjB,UAAU,oBAAC,kBAAD;MAA+B;MAAmB;KAAO,CAAA;IACnE,CAAA;GACG;IACD;;AAEP"}
@@ -0,0 +1,24 @@
1
+ import { MeasurementUnitId } from "../engine/units.js";
2
+ import { MeasurementUnitsPreference } from "../options.js";
3
+ import React from "react";
4
+
5
+ //#region src/fields/measurement/client/MeasurementUnitsProvider.d.ts
6
+ type MeasurementUnitsContextValue = {
7
+ ready: boolean;
8
+ units: MeasurementUnitsPreference;
9
+ setUnit: (preferenceKey: string, unit: MeasurementUnitId) => void;
10
+ };
11
+ /**
12
+ * Reactive layer over payload-preferences for the per-bucket display units.
13
+ * Payload's own usePreferences is ref-backed and never re-renders consumers,
14
+ * so this provider holds the map in state: one toggle re-renders every
15
+ * measurement field and cell on the page, then persists with merge mode.
16
+ */
17
+ declare const MeasurementUnitsProvider: React.FC<{
18
+ children: React.ReactNode; /** Kiosk/shared-account mode: skips both the preference fetch and writes, state stays session-only. Defaults to true. */
19
+ persist?: boolean;
20
+ }>;
21
+ declare const useMeasurementUnits: () => MeasurementUnitsContextValue | null;
22
+ //#endregion
23
+ export { MeasurementUnitsProvider, useMeasurementUnits };
24
+ //# sourceMappingURL=MeasurementUnitsProvider.d.ts.map
@@ -0,0 +1,61 @@
1
+ "use client";
2
+ import { MEASUREMENT_PREFERENCE_KEY } from "../options.js";
3
+ import { usePreferences } from "@payloadcms/ui";
4
+ import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
5
+ import { jsx } from "react/jsx-runtime";
6
+ //#region src/fields/measurement/client/MeasurementUnitsProvider.tsx
7
+ const Context = createContext(null);
8
+ const isPreference = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
+ /**
10
+ * Reactive layer over payload-preferences for the per-bucket display units.
11
+ * Payload's own usePreferences is ref-backed and never re-renders consumers,
12
+ * so this provider holds the map in state: one toggle re-renders every
13
+ * measurement field and cell on the page, then persists with merge mode.
14
+ */
15
+ const MeasurementUnitsProvider = ({ children, persist = true }) => {
16
+ const { getPreference, setPreference } = usePreferences();
17
+ const [units, setUnits] = useState({});
18
+ const [ready, setReady] = useState(() => !persist);
19
+ useEffect(() => {
20
+ if (!persist) return;
21
+ let cancelled = false;
22
+ getPreference(MEASUREMENT_PREFERENCE_KEY).then((stored) => {
23
+ if (cancelled) return;
24
+ if (isPreference(stored)) setUnits((current) => ({
25
+ ...stored,
26
+ ...current
27
+ }));
28
+ setReady(true);
29
+ }).catch(() => {
30
+ if (!cancelled) setReady(true);
31
+ });
32
+ return () => {
33
+ cancelled = true;
34
+ };
35
+ }, [getPreference, persist]);
36
+ const setUnit = useCallback((preferenceKey, unit) => {
37
+ setUnits((current) => ({
38
+ ...current,
39
+ [preferenceKey]: unit
40
+ }));
41
+ if (persist) setPreference(MEASUREMENT_PREFERENCE_KEY, { [preferenceKey]: unit }, true);
42
+ }, [persist, setPreference]);
43
+ const value = useMemo(() => ({
44
+ ready,
45
+ setUnit,
46
+ units
47
+ }), [
48
+ ready,
49
+ setUnit,
50
+ units
51
+ ]);
52
+ return /* @__PURE__ */ jsx(Context.Provider, {
53
+ value,
54
+ children
55
+ });
56
+ };
57
+ const useMeasurementUnits = () => useContext(Context);
58
+ //#endregion
59
+ export { MeasurementUnitsProvider, useMeasurementUnits };
60
+
61
+ //# sourceMappingURL=MeasurementUnitsProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MeasurementUnitsProvider.js","names":[],"sources":["../../../../src/fields/measurement/client/MeasurementUnitsProvider.tsx"],"sourcesContent":["'use client'\nimport { usePreferences } from '@payloadcms/ui'\nimport type React from 'react'\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'\nimport type { MeasurementUnitId } from '../engine/units'\nimport { MEASUREMENT_PREFERENCE_KEY, type MeasurementUnitsPreference } from '../options'\n\nexport type MeasurementUnitsContextValue = {\n\tready: boolean\n\tunits: MeasurementUnitsPreference\n\tsetUnit: (preferenceKey: string, unit: MeasurementUnitId) => void\n}\n\nconst Context = createContext<MeasurementUnitsContextValue | null>(null)\n\nconst isPreference = (value: unknown): value is MeasurementUnitsPreference =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Reactive layer over payload-preferences for the per-bucket display units.\n * Payload's own usePreferences is ref-backed and never re-renders consumers,\n * so this provider holds the map in state: one toggle re-renders every\n * measurement field and cell on the page, then persists with merge mode.\n */\nexport const MeasurementUnitsProvider: React.FC<{\n\tchildren: React.ReactNode\n\t/** Kiosk/shared-account mode: skips both the preference fetch and writes, state stays session-only. Defaults to true. */\n\tpersist?: boolean\n}> = ({ children, persist = true }) => {\n\tconst { getPreference, setPreference } = usePreferences()\n\tconst [units, setUnits] = useState<MeasurementUnitsPreference>({})\n\t// No fetch to wait for when session-only, so first paint is already the final state.\n\tconst [ready, setReady] = useState(() => !persist)\n\n\tuseEffect(() => {\n\t\tif (!persist) return\n\t\tlet cancelled = false\n\t\tgetPreference<MeasurementUnitsPreference | null>(MEASUREMENT_PREFERENCE_KEY)\n\t\t\t.then((stored) => {\n\t\t\t\tif (cancelled) return\n\t\t\t\t// Toggles made before the fetch resolves win over the stored snapshot\n\t\t\t\tif (isPreference(stored)) setUnits((current) => ({ ...stored, ...current }))\n\t\t\t\tsetReady(true)\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tif (!cancelled) setReady(true)\n\t\t\t})\n\t\treturn () => {\n\t\t\tcancelled = true\n\t\t}\n\t}, [getPreference, persist])\n\n\tconst setUnit = useCallback(\n\t\t(preferenceKey: string, unit: MeasurementUnitId) => {\n\t\t\tsetUnits((current) => ({ ...current, [preferenceKey]: unit }))\n\t\t\tif (persist) void setPreference(MEASUREMENT_PREFERENCE_KEY, { [preferenceKey]: unit }, true)\n\t\t},\n\t\t[persist, setPreference]\n\t)\n\n\tconst value = useMemo(() => ({ ready, setUnit, units }), [ready, setUnit, units])\n\treturn <Context.Provider value={value}>{children}</Context.Provider>\n}\n\nexport const useMeasurementUnits = (): MeasurementUnitsContextValue | null => useContext(Context)\n"],"mappings":";;;;;;AAaA,MAAM,UAAU,cAAmD,IAAI;AAEvE,MAAM,gBAAgB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;;;AAQpE,MAAa,4BAIP,EAAE,UAAU,UAAU,WAAW;CACtC,MAAM,EAAE,eAAe,kBAAkB,eAAe;CACxD,MAAM,CAAC,OAAO,YAAY,SAAqC,CAAC,CAAC;CAEjE,MAAM,CAAC,OAAO,YAAY,eAAe,CAAC,OAAO;CAEjD,gBAAgB;EACf,IAAI,CAAC,SAAS;EACd,IAAI,YAAY;EAChB,cAAiD,0BAA0B,EACzE,MAAM,WAAW;GACjB,IAAI,WAAW;GAEf,IAAI,aAAa,MAAM,GAAG,UAAU,aAAa;IAAE,GAAG;IAAQ,GAAG;GAAQ,EAAE;GAC3E,SAAS,IAAI;EACd,CAAC,EACA,YAAY;GACZ,IAAI,CAAC,WAAW,SAAS,IAAI;EAC9B,CAAC;EACF,aAAa;GACZ,YAAY;EACb;CACD,GAAG,CAAC,eAAe,OAAO,CAAC;CAE3B,MAAM,UAAU,aACd,eAAuB,SAA4B;EACnD,UAAU,aAAa;GAAE,GAAG;IAAU,gBAAgB;EAAK,EAAE;EAC7D,IAAI,SAAS,cAAmB,4BAA4B,GAAG,gBAAgB,KAAK,GAAG,IAAI;CAC5F,GACA,CAAC,SAAS,aAAa,CACxB;CAEA,MAAM,QAAQ,eAAe;EAAE;EAAO;EAAS;CAAM,IAAI;EAAC;EAAO;EAAS;CAAK,CAAC;CAChF,OAAO,oBAAC,QAAQ,UAAT;EAAyB;EAAQ;CAA2B,CAAA;AACpE;AAEA,MAAa,4BAAiE,WAAW,OAAO"}
@@ -0,0 +1,115 @@
1
+ import { COMPOUNDS } from "../engine/units.js";
2
+ import "../engine/locale.js";
3
+ import { roundTo } from "../engine/convert.js";
4
+ //#region src/fields/measurement/client/editModel.ts
5
+ const numberToDraft = (value) => String(value);
6
+ const parseDraft = (raw) => {
7
+ if (raw.trim() === "") return null;
8
+ const parsed = Number(raw);
9
+ return Number.isFinite(parsed) ? parsed : null;
10
+ };
11
+ const ALL_DIRTY = {
12
+ primary: true,
13
+ minor: true
14
+ };
15
+ const commitDrafts = (drafts, opts) => {
16
+ const { displayUnit, dirty = ALL_DIRTY, engine, entry = "free", paintedDrafts, precision, storageDigits = 6, storageUnit, storedValue = null } = opts;
17
+ if (engine.isCompoundUnit(displayUnit)) {
18
+ const compound = COMPOUNDS[displayUnit];
19
+ const hasStored = typeof storedValue === "number";
20
+ const dirtyCount = (dirty.primary ? 1 : 0) + (dirty.minor ? 1 : 0);
21
+ if (hasStored && dirtyCount === 1 && paintedDrafts) {
22
+ const exact = engine.decompose(storedValue, storageUnit, displayUnit, storageDigits);
23
+ const exactTotal = exact.major * compound.ratio + exact.minor;
24
+ if (dirty.primary) {
25
+ let typedMajor = parseDraft(drafts.primary);
26
+ if (typedMajor === null) return null;
27
+ if (entry === "quantize") typedMajor = roundTo(typedMajor, engine.precisionFor(compound.major, precision));
28
+ const paintedMajor = parseDraft(paintedDrafts.primary) ?? exact.major;
29
+ const newTotal = exactTotal + (typedMajor - paintedMajor) * compound.ratio;
30
+ return roundTo(engine.compose({
31
+ major: 0,
32
+ minor: newTotal
33
+ }, displayUnit, storageUnit), storageDigits);
34
+ }
35
+ const rawMinor = parseDraft(drafts.minor) ?? 0;
36
+ const newTotal = exactTotal + ((entry === "quantize" ? roundTo(rawMinor, engine.precisionFor(displayUnit, precision)) : rawMinor) - (parseDraft(paintedDrafts.minor) ?? 0));
37
+ return roundTo(engine.compose({
38
+ major: 0,
39
+ minor: newTotal
40
+ }, displayUnit, storageUnit), storageDigits);
41
+ }
42
+ const stored = hasStored ? engine.decompose(storedValue, storageUnit, displayUnit, storageDigits) : null;
43
+ let major;
44
+ if (dirty.primary) {
45
+ major = parseDraft(drafts.primary);
46
+ if (major !== null && entry === "quantize") major = roundTo(major, engine.precisionFor(compound.major, precision));
47
+ } else major = stored ? stored.major : parseDraft(drafts.primary);
48
+ if (major === null) return null;
49
+ let minor;
50
+ if (dirty.minor) {
51
+ const rawMinor = parseDraft(drafts.minor) ?? 0;
52
+ const maxMinor = compound.ratio - .001;
53
+ const clampedRaw = Math.sign(rawMinor) * Math.min(Math.abs(rawMinor), maxMinor);
54
+ minor = entry === "quantize" ? roundTo(clampedRaw, engine.precisionFor(displayUnit, precision)) : clampedRaw;
55
+ } else minor = stored ? stored.minor : parseDraft(paintedDrafts?.minor ?? "") ?? 0;
56
+ return roundTo(engine.compose({
57
+ major,
58
+ minor
59
+ }, displayUnit, storageUnit), storageDigits);
60
+ }
61
+ if (!dirty.primary) return storedValue;
62
+ const parsed = parseDraft(drafts.primary);
63
+ if (parsed === null) return null;
64
+ const value = entry === "quantize" ? roundTo(parsed, engine.precisionFor(displayUnit, precision)) : parsed;
65
+ return roundTo(engine.convert(value, displayUnit, storageUnit), storageDigits);
66
+ };
67
+ /**
68
+ * Drafts for repainting from a stored value. 'faithful' (default) is the shortest
69
+ * draft that commits back to the stored value: display precision first, then one
70
+ * more fraction digit at a time up to storage precision, since a draft that
71
+ * silently truncates the stored value would write the truncation back on the next
72
+ * save. 'display' skips escalation and renders straight at display digits
73
+ * (compound parts each at their own digits), trading faithfulness for a value that
74
+ * always matches what the unit picker promises.
75
+ */
76
+ const draftsFor = (value, opts) => {
77
+ if (typeof value !== "number" || Number.isNaN(value)) return {
78
+ minor: "",
79
+ primary: ""
80
+ };
81
+ const { displayUnit, draft = "faithful", engine, precision, storageDigits = 6, storageUnit } = opts;
82
+ const draftAt = (digits) => {
83
+ if (engine.isCompoundUnit(displayUnit)) {
84
+ const parts = engine.decompose(value, storageUnit, displayUnit, digits);
85
+ return {
86
+ minor: numberToDraft(parts.minor),
87
+ primary: numberToDraft(parts.major)
88
+ };
89
+ }
90
+ return {
91
+ minor: "",
92
+ primary: numberToDraft(roundTo(engine.convert(value, storageUnit, displayUnit), digits))
93
+ };
94
+ };
95
+ const displayDigits = engine.precisionFor(displayUnit, precision);
96
+ if (draft === "display") return draftAt(displayDigits);
97
+ const maxDigits = Math.max(displayDigits, storageDigits);
98
+ const target = roundTo(value, storageDigits);
99
+ const probeOpts = {
100
+ displayUnit,
101
+ engine,
102
+ precision,
103
+ storageDigits,
104
+ storageUnit
105
+ };
106
+ for (let digits = displayDigits; digits < maxDigits; digits++) {
107
+ const candidate = draftAt(digits);
108
+ if (commitDrafts(candidate, probeOpts) === target) return candidate;
109
+ }
110
+ return draftAt(maxDigits);
111
+ };
112
+ //#endregion
113
+ export { commitDrafts, draftsFor };
114
+
115
+ //# sourceMappingURL=editModel.js.map