@10x-media/fields 0.1.0-beta.9 → 4.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +9 -4
- package/dist/fields/color/client/ColorInput.js +17 -6
- package/dist/fields/color/client/ColorInput.js.map +1 -1
- package/dist/fields/color/client/ColorPickerPanel.js +18 -12
- package/dist/fields/color/client/ColorPickerPanel.js.map +1 -1
- package/dist/fields/color/client/colorField.css +131 -178
- package/dist/fields/color/client/icons.js +17 -24
- package/dist/fields/color/client/icons.js.map +1 -1
- package/dist/fields/color/colorField.js +5 -3
- package/dist/fields/color/colorField.js.map +1 -1
- package/dist/fields/color/server/colorCell.css +8 -9
- package/dist/fields/encrypted/components/EncryptedInput.js +44 -26
- package/dist/fields/encrypted/components/EncryptedInput.js.map +1 -1
- package/dist/fields/encrypted/components/EncryptedTextarea.js +29 -29
- package/dist/fields/encrypted/components/EncryptedTextarea.js.map +1 -1
- package/dist/fields/encrypted/components/EyeToggle.js +14 -35
- package/dist/fields/encrypted/components/EyeToggle.js.map +1 -1
- package/dist/fields/encrypted/components/ProtectedField.css +107 -159
- package/dist/fields/encrypted/components/ProtectedField.js +6 -2
- package/dist/fields/encrypted/components/ProtectedField.js.map +1 -1
- package/dist/fields/encrypted/components/RichTextRevealGate.js +3 -3
- package/dist/fields/encrypted/components/RichTextRevealGate.js.map +1 -1
- package/dist/fields/encrypted/components/WriteOnlyActions.js +58 -53
- package/dist/fields/encrypted/components/WriteOnlyActions.js.map +1 -1
- package/dist/fields/encrypted/components/WriteOnlyField.js +39 -21
- package/dist/fields/encrypted/components/WriteOnlyField.js.map +1 -1
- package/dist/fields/encrypted/components/facsimiles.js +70 -79
- package/dist/fields/encrypted/components/facsimiles.js.map +1 -1
- package/dist/fields/encrypted/components/placement.js.map +1 -1
- package/dist/fields/encrypted/encryptedField.js +25 -12
- package/dist/fields/encrypted/encryptedField.js.map +1 -1
- package/dist/fields/encrypted/{typescriptSchema.js → jsonSchema.js} +4 -4
- package/dist/fields/encrypted/jsonSchema.js.map +1 -0
- package/dist/fields/encrypted/queryRewrite.js +20 -0
- package/dist/fields/encrypted/queryRewrite.js.map +1 -1
- package/dist/fields/encrypted/validators.js +1 -1
- package/dist/fields/encrypted/validators.js.map +1 -1
- package/dist/fields/icon/adapters/tabler/generated/nodes.js +1 -1
- package/dist/fields/icon/adapters/tabler/generated/nodes.js.map +1 -1
- package/dist/fields/icon/client/IconDrawerContent.js +8 -6
- package/dist/fields/icon/client/IconDrawerContent.js.map +1 -1
- package/dist/fields/icon/client/IconFieldClient.js +15 -37
- package/dist/fields/icon/client/IconFieldClient.js.map +1 -1
- package/dist/fields/icon/client/icon-field.css +137 -233
- package/dist/fields/icon/codegen/sources/tabler.js +25 -6
- package/dist/fields/icon/codegen/sources/tabler.js.map +1 -1
- package/dist/fields/icon/layers/upload.js +3 -0
- package/dist/fields/icon/layers/upload.js.map +1 -1
- package/dist/fields/icon/react/createIcon.js +4 -4
- package/dist/fields/icon/react/createIcon.js.map +1 -1
- package/dist/fields/measurement/client/MeasurementInput.js +18 -32
- package/dist/fields/measurement/client/MeasurementInput.js.map +1 -1
- package/dist/fields/measurement/client/editModel.js +12 -3
- package/dist/fields/measurement/client/editModel.js.map +1 -1
- package/dist/fields/measurement/client/measurementField.css +58 -105
- package/dist/fields/measurement/server/getUserUnits.js +2 -1
- package/dist/fields/measurement/server/getUserUnits.js.map +1 -1
- package/dist/fields/phoneNumber/client/CountryPicker.js +14 -9
- package/dist/fields/phoneNumber/client/CountryPicker.js.map +1 -1
- package/dist/fields/phoneNumber/client/PhoneNumberField.d.ts +1 -1
- package/dist/fields/phoneNumber/client/PhoneNumberField.js +22 -4
- package/dist/fields/phoneNumber/client/PhoneNumberField.js.map +1 -1
- package/dist/fields/phoneNumber/client/phoneNumberField.css +109 -142
- package/dist/fields/phoneNumber/phoneNumberField.js +1 -1
- package/dist/fields/phoneNumber/phoneNumberField.js.map +1 -1
- package/dist/fields/phoneNumber/server/PhoneNumberCellServer.js +2 -1
- package/dist/fields/phoneNumber/server/PhoneNumberCellServer.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +5 -4
- package/dist/index.js.map +1 -1
- package/dist/plugin/companionSelect.d.ts +12 -0
- package/dist/plugin/companionSelect.js +107 -0
- package/dist/plugin/companionSelect.js.map +1 -0
- package/package.json +15 -15
- package/dist/fields/encrypted/typescriptSchema.js.map +0 -1
|
@@ -27,6 +27,7 @@ const findDocs = async (args) => {
|
|
|
27
27
|
collection: args.collection,
|
|
28
28
|
depth: 0,
|
|
29
29
|
limit: 0,
|
|
30
|
+
overrideAccess: true,
|
|
30
31
|
pagination: false,
|
|
31
32
|
...args.ctx.req ? { req: args.ctx.req } : {},
|
|
32
33
|
...args.where ? { where: args.where } : {}
|
|
@@ -85,6 +86,7 @@ const uploadIconLayer = (options) => {
|
|
|
85
86
|
collection: options.collection,
|
|
86
87
|
depth: 0,
|
|
87
88
|
limit: 1,
|
|
89
|
+
overrideAccess: true,
|
|
88
90
|
...ctx.req ? { req: ctx.req } : {},
|
|
89
91
|
where
|
|
90
92
|
})).docs.map(asUploadDoc)[0];
|
|
@@ -97,6 +99,7 @@ const uploadIconLayer = (options) => {
|
|
|
97
99
|
collection: options.collection,
|
|
98
100
|
depth: 0,
|
|
99
101
|
limit: 0,
|
|
102
|
+
overrideAccess: true,
|
|
100
103
|
pagination: false,
|
|
101
104
|
...ctx.req ? { req: ctx.req } : {},
|
|
102
105
|
where
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload.js","names":[],"sources":["../../../../src/fields/icon/layers/upload.ts"],"sourcesContent":["import type { CollectionSlug, Payload, Where } from 'payload'\nimport type { IconLayer, IconLayerCache, IconLayerContext, IconMeta } from '../../../types'\n\n/** Document shape the layer reads, after the configurable field names are applied. */\ntype UploadDoc = Record<string, unknown>\n\n/**\n * Widens one document to a bag of fields.\n *\n * Payload types `find` as the document union of the host app's collections, and a generated\n * document type has no index signature, so asserting the array directly is rejected wherever\n * types have been generated. That is the dev app and every real consumer, and it is why this\n * only shows up outside the package's own typecheck. Taking `unknown` keeps it one legal\n * assertion rather than a double cast.\n */\nconst asUploadDoc = (doc: unknown): UploadDoc => doc as UploadDoc\n\nexport type UploadIconLayerOptions = {\n\t/** Upload collection holding the icons. */\n\tcollection: CollectionSlug\n\t/** Layer id, unique within the adapter. Defaults to the collection slug. */\n\tid?: string\n\t/** Field holding the icon name that becomes part of the stored value. Defaults to `name`. */\n\tnameField?: string\n\t/** Field holding the human-readable label. Defaults to `label`. */\n\tlabelField?: string\n\t/** Field holding search tags, a string array. Defaults to `tags`. */\n\ttagsField?: string\n\t/** Field holding categories, a string array. Defaults to `categories`. */\n\tcategoriesField?: string\n\t/**\n\t * Extra constraint, typically tenant scoping. Receives the request so it can read the\n\t * caller. Supply `cacheKey` alongside it, or one caller's listing is served to another.\n\t */\n\twhere?: (ctx: IconLayerContext) => Where | undefined\n\t/**\n\t * Cache-key segment for a scoped layer. Required whenever `where` varies by request:\n\t * the listing cache is otherwise keyed by adapter slug and layer id alone.\n\t */\n\tcacheKey?: (ctx: IconLayerContext) => string\n\t/** Listing cache policy. Defaults to a 30 second TTL, since uploads change at runtime. */\n\tcache?: IconLayerCache\n\t/**\n\t * How glyphs paint. `'url'` is the default and renders each icon through an `<img>`,\n\t * which is inert by construction: an SVG loaded that way cannot execute script.\n\t *\n\t * `'svg'` inlines the markup instead, which allows `currentColor` recolouring but means\n\t * rendering editor-uploaded markup inside the admin. On a multi-tenant install the\n\t * uploader may be a customer rather than an operator, so that is a deliberate choice\n\t * with a real blast radius. The markup is sanitised either way; `'url'` simply removes\n\t * the question.\n\t */\n\trender?: 'url' | 'svg'\n\t/** importMap path resolving `(name: string) => null | string` for the `url` strategy. */\n\tresolveUrl?: string\n\t/** importMap path resolving `() => Promise<Record<string, string>>` for the `svg` strategy. */\n\tloadSvgs?: string\n}\n\nconst DEFAULT_TTL = 30_000\n\nconst asStrings = (value: unknown): string[] =>\n\tArray.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n\nconst toMeta = (doc: UploadDoc, options: Required<FieldNames>): IconMeta | null => {\n\tconst name = doc[options.nameField]\n\tif (typeof name !== 'string' || name === '') return null\n\tconst label = doc[options.labelField]\n\treturn {\n\t\tcategories: asStrings(doc[options.categoriesField]),\n\t\tname,\n\t\ttags: asStrings(doc[options.tagsField]),\n\t\t...(typeof label === 'string' && label !== '' ? { label } : {}),\n\t}\n}\n\ntype FieldNames = {\n\tcategoriesField: string\n\tlabelField: string\n\tnameField: string\n\ttagsField: string\n}\n\nconst findDocs = async (args: {\n\tctx: IconLayerContext\n\tcollection: CollectionSlug\n\tpayload: Payload\n\twhere: Where | undefined\n}): Promise<UploadDoc[]> => {\n\tconst result = await args.payload.find({\n\t\tcollection: args.collection,\n\t\tdepth: 0,\n\t\tlimit: 0,\n\t\tpagination: false,\n\t\t...(args.ctx.req ? { req: args.ctx.req } : {}),\n\t\t...(args.where ? { where: args.where } : {}),\n\t})\n\treturn result.docs.map(asUploadDoc)\n}\n\n/**\n * An icon layer backed by a Payload upload collection, so editors can add icons without a\n * deploy.\n *\n * This is the preset that proves the layer contract holds: if a real upload-backed library\n * needs anything expressible only here and not through `IconLayer`, that is a gap in the\n * contract rather than in this file.\n *\n * Validation never reads the listing cache. `resolveMetaMany` answers from one indexed\n * query, so an icon uploaded a moment ago is valid immediately, on every instance, rather\n * than after a cache expiry or a restart.\n */\nexport const uploadIconLayer = (options: UploadIconLayerOptions): IconLayer => {\n\tconst fields: Required<FieldNames> = {\n\t\tcategoriesField: options.categoriesField ?? 'categories',\n\t\tlabelField: options.labelField ?? 'label',\n\t\tnameField: options.nameField ?? 'name',\n\t\ttagsField: options.tagsField ?? 'tags',\n\t}\n\tconst strategy = options.render ?? 'url'\n\tif (strategy === 'url' && !options.resolveUrl) {\n\t\tthrow new Error('[fields] uploadIconLayer: the url strategy needs a resolveUrl import path')\n\t}\n\tif (strategy === 'svg' && !options.loadSvgs) {\n\t\tthrow new Error('[fields] uploadIconLayer: the svg strategy needs a loadSvgs import path')\n\t}\n\n\tconst scopedWhere = (ctx: IconLayerContext): Where | undefined => options.where?.(ctx)\n\n\treturn {\n\t\tcache: options.cache ?? { ttl: DEFAULT_TTL },\n\t\t...(options.cacheKey ? { cacheKey: options.cacheKey } : {}),\n\t\tid: options.id ?? String(options.collection),\n\t\tloadManifest: async (ctx) => {\n\t\t\tconst docs = await findDocs({\n\t\t\t\tcollection: options.collection,\n\t\t\t\tctx,\n\t\t\t\tpayload: ctx.payload,\n\t\t\t\twhere: scopedWhere(ctx),\n\t\t\t})\n\t\t\tconst icons = docs\n\t\t\t\t.map((doc) => toMeta(doc, fields))\n\t\t\t\t.filter((icon): icon is IconMeta => icon !== null)\n\t\t\tconst categories = [...new Set(icons.flatMap((icon) => icon.categories))].sort()\n\t\t\treturn { categories, icons }\n\t\t},\n\t\trender:\n\t\t\tstrategy === 'url'\n\t\t\t\t? { resolve: options.resolveUrl ?? '', type: 'url' }\n\t\t\t\t: { load: options.loadSvgs ?? '', type: 'svg' },\n\t\tresolveMeta: async (name, ctx) => {\n\t\t\tconst scoped = scopedWhere(ctx)\n\t\t\tconst where: Where = scoped\n\t\t\t\t? { and: [scoped, { [fields.nameField]: { equals: name } }] }\n\t\t\t\t: { [fields.nameField]: { equals: name } }\n\t\t\tconst result = await ctx.payload.find({\n\t\t\t\tcollection: options.collection,\n\t\t\t\tdepth: 0,\n\t\t\t\tlimit: 1,\n\t\t\t\t...(ctx.req ? { req: ctx.req } : {}),\n\t\t\t\twhere,\n\t\t\t})\n\t\t\tconst doc = result.docs.map(asUploadDoc)[0]\n\t\t\treturn doc ? toMeta(doc, fields) : null\n\t\t},\n\t\t// One `in` query for every name looked up in the tick. A document holding eight icon\n\t\t// fields, or a fifty-row list, costs one query rather than eight or fifty.\n\t\tresolveMetaMany: async (names, ctx) => {\n\t\t\tconst scoped = scopedWhere(ctx)\n\t\t\tconst where: Where = scoped\n\t\t\t\t? { and: [scoped, { [fields.nameField]: { in: names } }] }\n\t\t\t\t: { [fields.nameField]: { in: names } }\n\t\t\tconst result = await ctx.payload.find({\n\t\t\t\tcollection: options.collection,\n\t\t\t\tdepth: 0,\n\t\t\t\tlimit: 0,\n\t\t\t\tpagination: false,\n\t\t\t\t...(ctx.req ? { req: ctx.req } : {}),\n\t\t\t\twhere,\n\t\t\t})\n\t\t\tconst found = new Map<string, IconMeta>()\n\t\t\tfor (const doc of result.docs.map(asUploadDoc)) {\n\t\t\t\tconst meta = toMeta(doc, fields)\n\t\t\t\tif (meta) found.set(meta.name, meta)\n\t\t\t}\n\t\t\treturn found\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAeA,MAAM,eAAe,QAA4B;AA4CjD,MAAM,cAAc;AAEpB,MAAM,aAAa,UAClB,MAAM,QAAQ,KAAK,IAAI,MAAM,QAAQ,UAA2B,OAAO,UAAU,QAAQ,IAAI,CAAC;AAE/F,MAAM,UAAU,KAAgB,YAAmD;CAClF,MAAM,OAAO,IAAI,QAAQ;CACzB,IAAI,OAAO,SAAS,YAAY,SAAS,IAAI,OAAO;CACpD,MAAM,QAAQ,IAAI,QAAQ;CAC1B,OAAO;EACN,YAAY,UAAU,IAAI,QAAQ,gBAAgB;EAClD;EACA,MAAM,UAAU,IAAI,QAAQ,UAAU;EACtC,GAAI,OAAO,UAAU,YAAY,UAAU,KAAK,EAAE,MAAM,IAAI,CAAC;CAC9D;AACD;AASA,MAAM,WAAW,OAAO,SAKI;CAS3B,QAAO,MARc,KAAK,QAAQ,KAAK;EACtC,YAAY,KAAK;EACjB,OAAO;EACP,OAAO;EACP,YAAY;EACZ,GAAI,KAAK,IAAI,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,IAAI,CAAC;EAC5C,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC3C,CAAC,GACa,KAAK,IAAI,WAAW;AAC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AAM,OAAM,MAPS,IAAI,QAAQ,KAAK;IACrC,YAAY,QAAQ;IACpB,OAAO;IACP,OAAO;IACP,GAAI,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC;IAClC;GACD,CAAC,GACkB,KAAK,IAAI,WAAW,EAAE;GACzC,OAAO,MAAM,OAAO,KAAK,MAAM,IAAI;EACpC;EAGA,iBAAiB,OAAO,OAAO,QAAQ;GACtC,MAAM,SAAS,YAAY,GAAG;GAC9B,MAAM,QAAe,SAClB,EAAE,KAAK,CAAC,QAAQ,GAAG,OAAO,YAAY,EAAE,IAAI,MAAM,EAAE,CAAC,EAAE,IACvD,GAAG,OAAO,YAAY,EAAE,IAAI,MAAM,EAAE;GACvC,MAAM,SAAS,MAAM,IAAI,QAAQ,KAAK;IACrC,YAAY,QAAQ;IACpB,OAAO;IACP,OAAO;IACP,YAAY;IACZ,GAAI,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC;IAClC;GACD,CAAC;GACD,MAAM,wBAAQ,IAAI,IAAsB;GACxC,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,WAAW,GAAG;IAC/C,MAAM,OAAO,OAAO,KAAK,MAAM;IAC/B,IAAI,MAAM,MAAM,IAAI,KAAK,MAAM,IAAI;GACpC;GACA,OAAO;EACR;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"upload.js","names":[],"sources":["../../../../src/fields/icon/layers/upload.ts"],"sourcesContent":["import type { CollectionSlug, Payload, Where } from 'payload'\nimport type { IconLayer, IconLayerCache, IconLayerContext, IconMeta } from '../../../types'\n\n/** Document shape the layer reads, after the configurable field names are applied. */\ntype UploadDoc = Record<string, unknown>\n\n/**\n * Widens one document to a bag of fields.\n *\n * Payload types `find` as the document union of the host app's collections, and a generated\n * document type has no index signature, so asserting the array directly is rejected wherever\n * types have been generated. That is the dev app and every real consumer, and it is why this\n * only shows up outside the package's own typecheck. Taking `unknown` keeps it one legal\n * assertion rather than a double cast.\n */\nconst asUploadDoc = (doc: unknown): UploadDoc => doc as UploadDoc\n\nexport type UploadIconLayerOptions = {\n\t/** Upload collection holding the icons. */\n\tcollection: CollectionSlug\n\t/** Layer id, unique within the adapter. Defaults to the collection slug. */\n\tid?: string\n\t/** Field holding the icon name that becomes part of the stored value. Defaults to `name`. */\n\tnameField?: string\n\t/** Field holding the human-readable label. Defaults to `label`. */\n\tlabelField?: string\n\t/** Field holding search tags, a string array. Defaults to `tags`. */\n\ttagsField?: string\n\t/** Field holding categories, a string array. Defaults to `categories`. */\n\tcategoriesField?: string\n\t/**\n\t * Extra constraint, typically tenant scoping. Receives the request so it can read the\n\t * caller. Supply `cacheKey` alongside it, or one caller's listing is served to another.\n\t */\n\twhere?: (ctx: IconLayerContext) => Where | undefined\n\t/**\n\t * Cache-key segment for a scoped layer. Required whenever `where` varies by request:\n\t * the listing cache is otherwise keyed by adapter slug and layer id alone.\n\t */\n\tcacheKey?: (ctx: IconLayerContext) => string\n\t/** Listing cache policy. Defaults to a 30 second TTL, since uploads change at runtime. */\n\tcache?: IconLayerCache\n\t/**\n\t * How glyphs paint. `'url'` is the default and renders each icon through an `<img>`,\n\t * which is inert by construction: an SVG loaded that way cannot execute script.\n\t *\n\t * `'svg'` inlines the markup instead, which allows `currentColor` recolouring but means\n\t * rendering editor-uploaded markup inside the admin. On a multi-tenant install the\n\t * uploader may be a customer rather than an operator, so that is a deliberate choice\n\t * with a real blast radius. The markup is sanitised either way; `'url'` simply removes\n\t * the question.\n\t */\n\trender?: 'url' | 'svg'\n\t/** importMap path resolving `(name: string) => null | string` for the `url` strategy. */\n\tresolveUrl?: string\n\t/** importMap path resolving `() => Promise<Record<string, string>>` for the `svg` strategy. */\n\tloadSvgs?: string\n}\n\nconst DEFAULT_TTL = 30_000\n\nconst asStrings = (value: unknown): string[] =>\n\tArray.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n\nconst toMeta = (doc: UploadDoc, options: Required<FieldNames>): IconMeta | null => {\n\tconst name = doc[options.nameField]\n\tif (typeof name !== 'string' || name === '') return null\n\tconst label = doc[options.labelField]\n\treturn {\n\t\tcategories: asStrings(doc[options.categoriesField]),\n\t\tname,\n\t\ttags: asStrings(doc[options.tagsField]),\n\t\t...(typeof label === 'string' && label !== '' ? { label } : {}),\n\t}\n}\n\ntype FieldNames = {\n\tcategoriesField: string\n\tlabelField: string\n\tnameField: string\n\ttagsField: string\n}\n\nconst findDocs = async (args: {\n\tctx: IconLayerContext\n\tcollection: CollectionSlug\n\tpayload: Payload\n\twhere: Where | undefined\n}): Promise<UploadDoc[]> => {\n\tconst result = await args.payload.find({\n\t\tcollection: args.collection,\n\t\tdepth: 0,\n\t\tlimit: 0,\n\t\t// Icon metadata is library data, not the viewer's: lookups ran unrestricted on\n\t\t// Payload 3, and validation depends on them for any editor.\n\t\toverrideAccess: true,\n\t\tpagination: false,\n\t\t...(args.ctx.req ? { req: args.ctx.req } : {}),\n\t\t...(args.where ? { where: args.where } : {}),\n\t})\n\treturn result.docs.map(asUploadDoc)\n}\n\n/**\n * An icon layer backed by a Payload upload collection, so editors can add icons without a\n * deploy.\n *\n * This is the preset that proves the layer contract holds: if a real upload-backed library\n * needs anything expressible only here and not through `IconLayer`, that is a gap in the\n * contract rather than in this file.\n *\n * Validation never reads the listing cache. `resolveMetaMany` answers from one indexed\n * query, so an icon uploaded a moment ago is valid immediately, on every instance, rather\n * than after a cache expiry or a restart.\n */\nexport const uploadIconLayer = (options: UploadIconLayerOptions): IconLayer => {\n\tconst fields: Required<FieldNames> = {\n\t\tcategoriesField: options.categoriesField ?? 'categories',\n\t\tlabelField: options.labelField ?? 'label',\n\t\tnameField: options.nameField ?? 'name',\n\t\ttagsField: options.tagsField ?? 'tags',\n\t}\n\tconst strategy = options.render ?? 'url'\n\tif (strategy === 'url' && !options.resolveUrl) {\n\t\tthrow new Error('[fields] uploadIconLayer: the url strategy needs a resolveUrl import path')\n\t}\n\tif (strategy === 'svg' && !options.loadSvgs) {\n\t\tthrow new Error('[fields] uploadIconLayer: the svg strategy needs a loadSvgs import path')\n\t}\n\n\tconst scopedWhere = (ctx: IconLayerContext): Where | undefined => options.where?.(ctx)\n\n\treturn {\n\t\tcache: options.cache ?? { ttl: DEFAULT_TTL },\n\t\t...(options.cacheKey ? { cacheKey: options.cacheKey } : {}),\n\t\tid: options.id ?? String(options.collection),\n\t\tloadManifest: async (ctx) => {\n\t\t\tconst docs = await findDocs({\n\t\t\t\tcollection: options.collection,\n\t\t\t\tctx,\n\t\t\t\tpayload: ctx.payload,\n\t\t\t\twhere: scopedWhere(ctx),\n\t\t\t})\n\t\t\tconst icons = docs\n\t\t\t\t.map((doc) => toMeta(doc, fields))\n\t\t\t\t.filter((icon): icon is IconMeta => icon !== null)\n\t\t\tconst categories = [...new Set(icons.flatMap((icon) => icon.categories))].sort()\n\t\t\treturn { categories, icons }\n\t\t},\n\t\trender:\n\t\t\tstrategy === 'url'\n\t\t\t\t? { resolve: options.resolveUrl ?? '', type: 'url' }\n\t\t\t\t: { load: options.loadSvgs ?? '', type: 'svg' },\n\t\tresolveMeta: async (name, ctx) => {\n\t\t\tconst scoped = scopedWhere(ctx)\n\t\t\tconst where: Where = scoped\n\t\t\t\t? { and: [scoped, { [fields.nameField]: { equals: name } }] }\n\t\t\t\t: { [fields.nameField]: { equals: name } }\n\t\t\tconst result = await ctx.payload.find({\n\t\t\t\tcollection: options.collection,\n\t\t\t\tdepth: 0,\n\t\t\t\tlimit: 1,\n\t\t\t\toverrideAccess: true,\n\t\t\t\t...(ctx.req ? { req: ctx.req } : {}),\n\t\t\t\twhere,\n\t\t\t})\n\t\t\tconst doc = result.docs.map(asUploadDoc)[0]\n\t\t\treturn doc ? toMeta(doc, fields) : null\n\t\t},\n\t\t// One `in` query for every name looked up in the tick. A document holding eight icon\n\t\t// fields, or a fifty-row list, costs one query rather than eight or fifty.\n\t\tresolveMetaMany: async (names, ctx) => {\n\t\t\tconst scoped = scopedWhere(ctx)\n\t\t\tconst where: Where = scoped\n\t\t\t\t? { and: [scoped, { [fields.nameField]: { in: names } }] }\n\t\t\t\t: { [fields.nameField]: { in: names } }\n\t\t\tconst result = await ctx.payload.find({\n\t\t\t\tcollection: options.collection,\n\t\t\t\tdepth: 0,\n\t\t\t\tlimit: 0,\n\t\t\t\toverrideAccess: true,\n\t\t\t\tpagination: false,\n\t\t\t\t...(ctx.req ? { req: ctx.req } : {}),\n\t\t\t\twhere,\n\t\t\t})\n\t\t\tconst found = new Map<string, IconMeta>()\n\t\t\tfor (const doc of result.docs.map(asUploadDoc)) {\n\t\t\t\tconst meta = toMeta(doc, fields)\n\t\t\t\tif (meta) found.set(meta.name, meta)\n\t\t\t}\n\t\t\treturn found\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAeA,MAAM,eAAe,QAA4B;AA4CjD,MAAM,cAAc;AAEpB,MAAM,aAAa,UAClB,MAAM,QAAQ,KAAK,IAAI,MAAM,QAAQ,UAA2B,OAAO,UAAU,QAAQ,IAAI,CAAC;AAE/F,MAAM,UAAU,KAAgB,YAAmD;CAClF,MAAM,OAAO,IAAI,QAAQ;CACzB,IAAI,OAAO,SAAS,YAAY,SAAS,IAAI,OAAO;CACpD,MAAM,QAAQ,IAAI,QAAQ;CAC1B,OAAO;EACN,YAAY,UAAU,IAAI,QAAQ,gBAAgB;EAClD;EACA,MAAM,UAAU,IAAI,QAAQ,UAAU;EACtC,GAAI,OAAO,UAAU,YAAY,UAAU,KAAK,EAAE,MAAM,IAAI,CAAC;CAC9D;AACD;AASA,MAAM,WAAW,OAAO,SAKI;CAY3B,QAAO,MAXc,KAAK,QAAQ,KAAK;EACtC,YAAY,KAAK;EACjB,OAAO;EACP,OAAO;EAGP,gBAAgB;EAChB,YAAY;EACZ,GAAI,KAAK,IAAI,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,IAAI,CAAC;EAC5C,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC3C,CAAC,GACa,KAAK,IAAI,WAAW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,MAAM,OAAM,MARS,IAAI,QAAQ,KAAK;IACrC,YAAY,QAAQ;IACpB,OAAO;IACP,OAAO;IACP,gBAAgB;IAChB,GAAI,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC;IAClC;GACD,CAAC,GACkB,KAAK,IAAI,WAAW,EAAE;GACzC,OAAO,MAAM,OAAO,KAAK,MAAM,IAAI;EACpC;EAGA,iBAAiB,OAAO,OAAO,QAAQ;GACtC,MAAM,SAAS,YAAY,GAAG;GAC9B,MAAM,QAAe,SAClB,EAAE,KAAK,CAAC,QAAQ,GAAG,OAAO,YAAY,EAAE,IAAI,MAAM,EAAE,CAAC,EAAE,IACvD,GAAG,OAAO,YAAY,EAAE,IAAI,MAAM,EAAE;GACvC,MAAM,SAAS,MAAM,IAAI,QAAQ,KAAK;IACrC,YAAY,QAAQ;IACpB,OAAO;IACP,OAAO;IACP,gBAAgB;IAChB,YAAY;IACZ,GAAI,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC;IAClC;GACD,CAAC;GACD,MAAM,wBAAQ,IAAI,IAAsB;GACxC,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,WAAW,GAAG;IAC/C,MAAM,OAAO,OAAO,KAAK,MAAM;IAC/B,IAAI,MAAM,MAAM,IAAI,KAAK,MAAM,IAAI;GACpC;GACA,OAAO;EACR;CACD;AACD"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { resolveIconValue } from "../shared/value.js";
|
|
3
3
|
import { resolveRenderedIcon } from "./resolveRendered.js";
|
|
4
4
|
import React, { Suspense, createContext, useContext } from "react";
|
|
5
|
-
import { Fragment
|
|
5
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
6
6
|
//#region src/fields/icon/react/createIcon.tsx
|
|
7
7
|
/**
|
|
8
8
|
* Carries the caller's `fallback` down to the cached lazy component. The lazy is
|
|
@@ -12,7 +12,7 @@ import { Fragment as Fragment$1, jsx } from "react/jsx-runtime";
|
|
|
12
12
|
*/
|
|
13
13
|
const FallbackContext = createContext(null);
|
|
14
14
|
/** Stands in for an icon the adapter resolved to null, so a miss renders the caller's fallback. */
|
|
15
|
-
const MissingIcon = () => /* @__PURE__ */ jsx(Fragment
|
|
15
|
+
const MissingIcon = () => /* @__PURE__ */ jsx(Fragment, { children: useContext(FallbackContext) });
|
|
16
16
|
/**
|
|
17
17
|
* Client dispatcher: per-value React.lazy components cached module-wide so a
|
|
18
18
|
* value renders one stable lazy component (per-icon chunks, loaded once).
|
|
@@ -38,10 +38,10 @@ const createIcon = (args) => {
|
|
|
38
38
|
return component;
|
|
39
39
|
};
|
|
40
40
|
const Icon = ({ className, fallback = null, icon, label, size = 20 }) => {
|
|
41
|
-
if (!icon) return /* @__PURE__ */ jsx(Fragment
|
|
41
|
+
if (!icon) return /* @__PURE__ */ jsx(Fragment, { children: fallback });
|
|
42
42
|
const { library, name } = resolveIconValue(icon, defaultLibrary);
|
|
43
43
|
const Component = lazyFor(library, name);
|
|
44
|
-
if (!Component) return /* @__PURE__ */ jsx(Fragment
|
|
44
|
+
if (!Component) return /* @__PURE__ */ jsx(Fragment, { children: fallback });
|
|
45
45
|
const tree = /* @__PURE__ */ jsx(Suspense, {
|
|
46
46
|
fallback,
|
|
47
47
|
children: /* @__PURE__ */ jsx(Component, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createIcon.js","names":[],"sources":["../../../../src/fields/icon/react/createIcon.tsx"],"sourcesContent":["'use client'\n\nimport type { ComponentType, ReactNode } from 'react'\nimport React, { createContext, Suspense, useContext } from 'react'\nimport { resolveIconValue } from '../shared/value'\nimport { resolveRenderedIcon } from './resolveRendered'\nimport type { IconProps, IconRendererAdapter, IconRenderProps } from './types'\n\n/**\n * Carries the caller's `fallback` down to the cached lazy component. The lazy is\n * cached module-wide on `library:name` so a repeated value loads its chunk once,\n * which means it cannot close over any one caller's prop. Context is how a shared\n * component reads a per-subtree value without giving up that cache.\n */\nconst FallbackContext = createContext<ReactNode>(null)\n\n/** Stands in for an icon the adapter resolved to null, so a miss renders the caller's fallback. */\nconst MissingIcon: ComponentType<IconRenderProps> = () => <>{useContext(FallbackContext)}</>\n\n/**\n * Client dispatcher: per-value React.lazy components cached module-wide so a\n * value renders one stable lazy component (per-icon chunks, loaded once).\n *\n * A rejected load stays cached, because React.lazy caches its own rejection.\n * That is deliberate: retrying would re-request a failing icon on every render\n * against an endpoint already struggling. `createRscIcon` evicts instead, because\n * a server render has no equivalent re-render pressure.\n */\nexport const createIcon = (args: {\n\tadapters: IconRendererAdapter[]\n\tdefaultLibrary?: string\n}): React.FC<IconProps> => {\n\tconst bySlug = new Map(args.adapters.map((adapter) => [adapter.slug, adapter]))\n\tconst defaultLibrary = args.defaultLibrary ?? args.adapters[0]?.slug ?? ''\n\tconst cache = new Map<string, ComponentType<IconRenderProps>>()\n\n\tconst lazyFor = (library: string, name: string): ComponentType<IconRenderProps> | null => {\n\t\tconst adapter = bySlug.get(library)\n\t\tif (!adapter) return null\n\t\tconst key = `${library}:${name}`\n\t\tlet component = cache.get(key)\n\t\tif (!component) {\n\t\t\tcomponent = React.lazy(async () => ({\n\t\t\t\tdefault: (await resolveRenderedIcon(adapter, name)) ?? MissingIcon,\n\t\t\t})) as unknown as ComponentType<IconRenderProps>\n\t\t\tcache.set(key, component)\n\t\t}\n\t\treturn component\n\t}\n\n\tconst Icon: React.FC<IconProps> = ({ className, fallback = null, icon, label, size = 20 }) => {\n\t\tif (!icon) return <>{fallback}</>\n\t\tconst { library, name } = resolveIconValue(icon, defaultLibrary)\n\t\tconst Component = lazyFor(library, name)\n\t\tif (!Component) return <>{fallback}</>\n\t\tconst tree = (\n\t\t\t<Suspense fallback={fallback}>\n\t\t\t\t<Component\n\t\t\t\t\taria-hidden={label ? undefined : true}\n\t\t\t\t\taria-label={label}\n\t\t\t\t\tclassName={className}\n\t\t\t\t\trole={label ? 'img' : undefined}\n\t\t\t\t\tsize={size}\n\t\t\t\t/>\n\t\t\t</Suspense>\n\t\t)\n\t\t// Provider only where there is something to carry, so the common decorative\n\t\t// call renders exactly the tree it always did.\n\t\treturn fallback == null ? (\n\t\t\ttree\n\t\t) : (\n\t\t\t<FallbackContext.Provider value={fallback}>{tree}</FallbackContext.Provider>\n\t\t)\n\t}\n\treturn Icon\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,kBAAkB,cAAyB,IAAI;;AAGrD,MAAM,oBAAoD,oBAAA,
|
|
1
|
+
{"version":3,"file":"createIcon.js","names":[],"sources":["../../../../src/fields/icon/react/createIcon.tsx"],"sourcesContent":["'use client'\n\nimport type { ComponentType, ReactNode } from 'react'\nimport React, { createContext, Suspense, useContext } from 'react'\nimport { resolveIconValue } from '../shared/value'\nimport { resolveRenderedIcon } from './resolveRendered'\nimport type { IconProps, IconRendererAdapter, IconRenderProps } from './types'\n\n/**\n * Carries the caller's `fallback` down to the cached lazy component. The lazy is\n * cached module-wide on `library:name` so a repeated value loads its chunk once,\n * which means it cannot close over any one caller's prop. Context is how a shared\n * component reads a per-subtree value without giving up that cache.\n */\nconst FallbackContext = createContext<ReactNode>(null)\n\n/** Stands in for an icon the adapter resolved to null, so a miss renders the caller's fallback. */\nconst MissingIcon: ComponentType<IconRenderProps> = () => <>{useContext(FallbackContext)}</>\n\n/**\n * Client dispatcher: per-value React.lazy components cached module-wide so a\n * value renders one stable lazy component (per-icon chunks, loaded once).\n *\n * A rejected load stays cached, because React.lazy caches its own rejection.\n * That is deliberate: retrying would re-request a failing icon on every render\n * against an endpoint already struggling. `createRscIcon` evicts instead, because\n * a server render has no equivalent re-render pressure.\n */\nexport const createIcon = (args: {\n\tadapters: IconRendererAdapter[]\n\tdefaultLibrary?: string\n}): React.FC<IconProps> => {\n\tconst bySlug = new Map(args.adapters.map((adapter) => [adapter.slug, adapter]))\n\tconst defaultLibrary = args.defaultLibrary ?? args.adapters[0]?.slug ?? ''\n\tconst cache = new Map<string, ComponentType<IconRenderProps>>()\n\n\tconst lazyFor = (library: string, name: string): ComponentType<IconRenderProps> | null => {\n\t\tconst adapter = bySlug.get(library)\n\t\tif (!adapter) return null\n\t\tconst key = `${library}:${name}`\n\t\tlet component = cache.get(key)\n\t\tif (!component) {\n\t\t\tcomponent = React.lazy(async () => ({\n\t\t\t\tdefault: (await resolveRenderedIcon(adapter, name)) ?? MissingIcon,\n\t\t\t})) as unknown as ComponentType<IconRenderProps>\n\t\t\tcache.set(key, component)\n\t\t}\n\t\treturn component\n\t}\n\n\tconst Icon: React.FC<IconProps> = ({ className, fallback = null, icon, label, size = 20 }) => {\n\t\tif (!icon) return <>{fallback}</>\n\t\tconst { library, name } = resolveIconValue(icon, defaultLibrary)\n\t\tconst Component = lazyFor(library, name)\n\t\tif (!Component) return <>{fallback}</>\n\t\tconst tree = (\n\t\t\t<Suspense fallback={fallback}>\n\t\t\t\t<Component\n\t\t\t\t\taria-hidden={label ? undefined : true}\n\t\t\t\t\taria-label={label}\n\t\t\t\t\tclassName={className}\n\t\t\t\t\trole={label ? 'img' : undefined}\n\t\t\t\t\tsize={size}\n\t\t\t\t/>\n\t\t\t</Suspense>\n\t\t)\n\t\t// Provider only where there is something to carry, so the common decorative\n\t\t// call renders exactly the tree it always did.\n\t\treturn fallback == null ? (\n\t\t\ttree\n\t\t) : (\n\t\t\t<FallbackContext.Provider value={fallback}>{tree}</FallbackContext.Provider>\n\t\t)\n\t}\n\treturn Icon\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,kBAAkB,cAAyB,IAAI;;AAGrD,MAAM,oBAAoD,oBAAA,UAAA,EAAA,UAAG,WAAW,eAAe,EAAI,CAAA;;;;;;;;;;AAW3F,MAAa,cAAc,SAGA;CAC1B,MAAM,SAAS,IAAI,IAAI,KAAK,SAAS,KAAK,YAAY,CAAC,QAAQ,MAAM,OAAO,CAAC,CAAC;CAC9E,MAAM,iBAAiB,KAAK,kBAAkB,KAAK,SAAS,IAAI,QAAQ;CACxE,MAAM,wBAAQ,IAAI,IAA4C;CAE9D,MAAM,WAAW,SAAiB,SAAwD;EACzF,MAAM,UAAU,OAAO,IAAI,OAAO;EAClC,IAAI,CAAC,SAAS,OAAO;EACrB,MAAM,MAAM,GAAG,QAAQ,GAAG;EAC1B,IAAI,YAAY,MAAM,IAAI,GAAG;EAC7B,IAAI,CAAC,WAAW;GACf,YAAY,MAAM,KAAK,aAAa,EACnC,SAAU,MAAM,oBAAoB,SAAS,IAAI,KAAM,YACxD,EAAE;GACF,MAAM,IAAI,KAAK,SAAS;EACzB;EACA,OAAO;CACR;CAEA,MAAM,QAA6B,EAAE,WAAW,WAAW,MAAM,MAAM,OAAO,OAAO,SAAS;EAC7F,IAAI,CAAC,MAAM,OAAO,oBAAA,UAAA,EAAA,UAAG,SAAW,CAAA;EAChC,MAAM,EAAE,SAAS,SAAS,iBAAiB,MAAM,cAAc;EAC/D,MAAM,YAAY,QAAQ,SAAS,IAAI;EACvC,IAAI,CAAC,WAAW,OAAO,oBAAA,UAAA,EAAA,UAAG,SAAW,CAAA;EACrC,MAAM,OACL,oBAAC,UAAD;GAAoB;aACnB,oBAAC,WAAD;IACC,eAAa,QAAQ,KAAA,IAAY;IACjC,cAAY;IACD;IACX,MAAM,QAAQ,QAAQ,KAAA;IAChB;GACN,CAAA;EACQ,CAAA;EAIX,OAAO,YAAY,OAClB,OAEA,oBAAC,gBAAgB,UAAjB;GAA0B,OAAO;aAAW;EAA+B,CAAA;CAE7E;CACA,OAAO;AACR"}
|
|
@@ -4,9 +4,9 @@ import { keys } from "../../../translations/keys.js";
|
|
|
4
4
|
import { useTranslation as useTranslation$1 } from "../../../translations/useTranslation.js";
|
|
5
5
|
import { commitDrafts, draftsFor } from "./editModel.js";
|
|
6
6
|
import { useMeasurementModel } from "./useMeasurementModel.js";
|
|
7
|
-
import { FieldDescription, FieldError, FieldLabel, Popup, RenderCustomComponent, fieldBaseClass } from "@payloadcms/ui";
|
|
7
|
+
import { FieldDescription, FieldError, FieldLabel, MoreIcon, Popup, RenderCustomComponent, fieldBaseClass } from "@payloadcms/ui";
|
|
8
8
|
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
|
9
|
-
import { Fragment
|
|
9
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
10
10
|
import "./measurementField.css";
|
|
11
11
|
//#region src/fields/measurement/client/MeasurementInput.tsx
|
|
12
12
|
const baseClass = "fields-measurement";
|
|
@@ -21,32 +21,10 @@ const CLEAN = {
|
|
|
21
21
|
* the row into overflow.
|
|
22
22
|
*/
|
|
23
23
|
const draftWidth = (draft) => ({ width: `${Math.min(Math.max(draft.length, 2), 12) + .5}ch` });
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
/** Payload's own "more" glyph, turned upright: a vertical kebab reads as the row's menu. */
|
|
25
|
+
const unitKebab = /* @__PURE__ */ jsx(MoreIcon, {
|
|
26
26
|
className: `${baseClass}__kebab`,
|
|
27
|
-
|
|
28
|
-
viewBox: "0 0 4 16",
|
|
29
|
-
xmlns: "http://www.w3.org/2000/svg",
|
|
30
|
-
children: [
|
|
31
|
-
/* @__PURE__ */ jsx("circle", {
|
|
32
|
-
cx: "2",
|
|
33
|
-
cy: "2",
|
|
34
|
-
fill: "currentColor",
|
|
35
|
-
r: "1.6"
|
|
36
|
-
}),
|
|
37
|
-
/* @__PURE__ */ jsx("circle", {
|
|
38
|
-
cx: "2",
|
|
39
|
-
cy: "8",
|
|
40
|
-
fill: "currentColor",
|
|
41
|
-
r: "1.6"
|
|
42
|
-
}),
|
|
43
|
-
/* @__PURE__ */ jsx("circle", {
|
|
44
|
-
cx: "2",
|
|
45
|
-
cy: "14",
|
|
46
|
-
fill: "currentColor",
|
|
47
|
-
r: "1.6"
|
|
48
|
-
})
|
|
49
|
-
]
|
|
27
|
+
size: 24
|
|
50
28
|
});
|
|
51
29
|
/** The row itself, shared by `MeasurementInput` and the form-bound `MeasurementField`. */
|
|
52
30
|
const MeasurementInputView = (props) => {
|
|
@@ -168,11 +146,15 @@ const MeasurementInputView = (props) => {
|
|
|
168
146
|
const isUnitInteractive = units.length > 1 && !isReadOnly;
|
|
169
147
|
const renderUnitPanel = ({ close }) => /* @__PURE__ */ jsx("div", {
|
|
170
148
|
"aria-label": t(keys.selectUnit),
|
|
171
|
-
className: `${baseClass}__unit-panel`,
|
|
149
|
+
className: `${baseClass}__unit-panel popup-button-list`,
|
|
172
150
|
role: "listbox",
|
|
173
151
|
children: units.map((unit) => /* @__PURE__ */ jsxs("button", {
|
|
174
152
|
"aria-selected": unit === displayUnit,
|
|
175
|
-
className:
|
|
153
|
+
className: [
|
|
154
|
+
`${baseClass}__unit-option`,
|
|
155
|
+
"popup-button-list__button",
|
|
156
|
+
unit === displayUnit && "popup-button-list__button--selected"
|
|
157
|
+
].filter(Boolean).join(" "),
|
|
176
158
|
onClick: () => {
|
|
177
159
|
selectUnit(unit);
|
|
178
160
|
close();
|
|
@@ -193,7 +175,7 @@ const MeasurementInputView = (props) => {
|
|
|
193
175
|
if (!isUnitInteractive) return null;
|
|
194
176
|
const shortLabel = engine.unitLabel(displayUnit, locale, "short");
|
|
195
177
|
return /* @__PURE__ */ jsx(Popup, {
|
|
196
|
-
button: /* @__PURE__ */ jsxs(Fragment
|
|
178
|
+
button: /* @__PURE__ */ jsxs(Fragment, { children: [unitKebab, /* @__PURE__ */ jsxs("span", {
|
|
197
179
|
className: `${baseClass}__sr-only`,
|
|
198
180
|
children: [
|
|
199
181
|
t(keys.selectUnit),
|
|
@@ -242,7 +224,11 @@ const MeasurementInputView = (props) => {
|
|
|
242
224
|
}),
|
|
243
225
|
BeforeInput,
|
|
244
226
|
/* @__PURE__ */ jsxs("div", {
|
|
245
|
-
className:
|
|
227
|
+
className: [
|
|
228
|
+
`${baseClass}__container`,
|
|
229
|
+
"form-input-group",
|
|
230
|
+
showError && "form-input-group-error"
|
|
231
|
+
].filter(Boolean).join(" "),
|
|
246
232
|
onMouseDown: focusNearestInput,
|
|
247
233
|
children: [isCompound && compoundDef ? /* @__PURE__ */ jsxs("span", {
|
|
248
234
|
className: `${baseClass}__compound`,
|
|
@@ -281,7 +267,7 @@ const MeasurementInputView = (props) => {
|
|
|
281
267
|
value: drafts.minor
|
|
282
268
|
}), renderUnitSuffix(compoundDef.minor)]
|
|
283
269
|
})]
|
|
284
|
-
}) : /* @__PURE__ */ jsxs(Fragment
|
|
270
|
+
}) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("input", {
|
|
285
271
|
className: `${baseClass}__input`,
|
|
286
272
|
id: inputId,
|
|
287
273
|
inputMode: "decimal",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MeasurementInput.js","names":["useTranslation"],"sources":["../../../../src/fields/measurement/client/MeasurementInput.tsx"],"sourcesContent":["'use client'\nimport {\n\tFieldDescription,\n\tFieldError,\n\tFieldLabel,\n\tfieldBaseClass,\n\tPopup,\n\tRenderCustomComponent,\n} from '@payloadcms/ui'\nimport type { StaticDescription, StaticLabel } from 'payload'\nimport type React from 'react'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport { keys } from '../../../translations/keys'\nimport { useTranslation } from '../../../translations/useTranslation'\nimport { COMPOUNDS, type MeasurementUnitId } from '../engine/units'\nimport { commitDrafts, type DirtyDrafts, draftsFor, type MeasurementDrafts } from './editModel'\nimport {\n\ttype MeasurementInputOptions,\n\ttype MeasurementModel,\n\tuseMeasurementModel,\n} from './useMeasurementModel'\nimport './measurementField.css'\n\nconst baseClass = 'fields-measurement'\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\n/**\n * Props for the form-free measurement input. `value` is the number in\n * `options.storageUnit`, exactly as `measurementField` stores it; the viewer reads and\n * types in their display unit.\n */\nexport type MeasurementInputProps = {\n\tvalue: null | number | undefined\n\t/** Fires on every edit with the value converted back to the storage unit. */\n\tonChange: (value: null | number) => void\n\toptions: MeasurementInputOptions\n\t/** Bounds in the storage unit; a value outside them shows a message in the display unit. */\n\tmin?: number\n\tmax?: number\n\t/** Names the input (`id`, `name`, label `htmlFor`), as on a native field. */\n\tpath?: string\n\tlabel?: StaticLabel\n\tdescription?: StaticDescription\n\tplaceholder?: string\n\trequired?: boolean\n\tlocalized?: boolean\n\treadOnly?: boolean\n\t/** Message shown in the error tooltip. Left unset, the input reports its own bound errors. */\n\terror?: string\n\t/** Forces the error state on or off. Left unset, it follows `error` and the bound check. */\n\tshowError?: boolean\n\tclassName?: string\n\tstyle?: React.CSSProperties\n\tLabel?: React.ReactNode\n\tError?: React.ReactNode\n\tDescription?: React.ReactNode\n\tBeforeInput?: React.ReactNode\n\tAfterInput?: React.ReactNode\n}\n\ntype MeasurementInputViewProps = { model: MeasurementModel } & Omit<\n\tMeasurementInputProps,\n\t'options'\n>\n\n/** The row itself, shared by `MeasurementInput` and the form-bound `MeasurementField`. */\nexport const MeasurementInputView: React.FC<MeasurementInputViewProps> = (props) => {\n\tconst {\n\t\tAfterInput,\n\t\tBeforeInput,\n\t\tclassName,\n\t\tDescription,\n\t\tdescription,\n\t\tError: ErrorComponent,\n\t\terror,\n\t\tLabel,\n\t\tlabel,\n\t\tlocalized,\n\t\tmax,\n\t\tmin,\n\t\tmodel,\n\t\tonChange,\n\t\tpath,\n\t\tplaceholder,\n\t\treadOnly,\n\t\trequired,\n\t\tshowError: showErrorFromProps,\n\t\tstyle,\n\t\tvalue,\n\t} = props\n\tconst {\n\t\tdisplayPrecision,\n\t\tdisplayUnit,\n\t\tengine,\n\t\tfmtBound,\n\t\tlocale,\n\t\tresolvedPrecision,\n\t\tselectUnit: selectModelUnit,\n\t\tstorageUnit,\n\t\tunits,\n\t} = model\n\tconst { t } = useTranslation()\n\tconst isReadOnly = Boolean(readOnly)\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\tconst errorMessage = error ?? boundsMessage\n\tconst showError = showErrorFromProps ?? errorMessage !== undefined\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 commit updates the live value\n\t// (and so `numericValue`) before the viewer blurs; diffing the next keystroke's\n\t// delta against that advanced value, instead of this frozen snapshot, would\n\t// 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\tonChange(\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, onChange, resolvedPrecision.entry]\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\tselectModelUnit(unit)\n\t\t},\n\t\t[selectModelUnit]\n\t)\n\n\tconst isCompound = engine.isCompoundUnit(displayUnit)\n\tconst compoundDef = isCompound ? COMPOUNDS[displayUnit] : null\n\t// Without a path there is no field id to derive, so the label pairs with a generated one\n\tconst generatedId = useId()\n\tconst inputId = path ? `field-${path.replace(/\\./g, '__')}` : generatedId\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\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={style}\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\n\t\t\t\t\t\thtmlFor={path ? undefined : inputId}\n\t\t\t\t\t\tlabel={label}\n\t\t\t\t\t\tlocalized={localized}\n\t\t\t\t\t\tpath={path}\n\t\t\t\t\t\trequired={required}\n\t\t\t\t\t/>\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={errorMessage} 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={placeholder}\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 || placeholder || '')}\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\n/**\n * The measurement field's row, unit menu and conversion pipeline with no form behind\n * it, for custom admin views and components. Inside the admin the display unit is the\n * viewer's saved preference for `preferenceKey`, shared with every measurement field\n * on that key; `MeasurementField` is this plus `useField`.\n */\nexport const MeasurementInput: React.FC<MeasurementInputProps> = ({ options, ...props }) => {\n\tconst model = useMeasurementModel(options)\n\treturn <MeasurementInputView model={model} {...props} />\n}\n"],"mappings":";;;;;;;;;;;AAuBA,MAAM,YAAY;AAElB,MAAM,QAAqB;CAAE,OAAO;CAAO,SAAS;AAAM;;;;;;;AAQ1D,M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,oBAAqD,EAAE,SAAS,GAAG,YAAY;CAE3F,OAAO,oBAAC,sBAAD;EAAsB,OADf,oBAAoB,OACM;EAAG,GAAI;CAAQ,CAAA;AACxD"}
|
|
1
|
+
{"version":3,"file":"MeasurementInput.js","names":["useTranslation"],"sources":["../../../../src/fields/measurement/client/MeasurementInput.tsx"],"sourcesContent":["'use client'\nimport {\n\tFieldDescription,\n\tFieldError,\n\tFieldLabel,\n\tfieldBaseClass,\n\tMoreIcon,\n\tPopup,\n\tRenderCustomComponent,\n} from '@payloadcms/ui'\nimport type { StaticDescription, StaticLabel } from 'payload'\nimport type React from 'react'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport { keys } from '../../../translations/keys'\nimport { useTranslation } from '../../../translations/useTranslation'\nimport { COMPOUNDS, type MeasurementUnitId } from '../engine/units'\nimport { commitDrafts, type DirtyDrafts, draftsFor, type MeasurementDrafts } from './editModel'\nimport {\n\ttype MeasurementInputOptions,\n\ttype MeasurementModel,\n\tuseMeasurementModel,\n} from './useMeasurementModel'\nimport './measurementField.css'\n\nconst baseClass = 'fields-measurement'\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\n/** Payload's own \"more\" glyph, turned upright: a vertical kebab reads as the row's menu. */\nconst unitKebab = <MoreIcon className={`${baseClass}__kebab`} size={24} />\n\n/**\n * Props for the form-free measurement input. `value` is the number in\n * `options.storageUnit`, exactly as `measurementField` stores it; the viewer reads and\n * types in their display unit.\n */\nexport type MeasurementInputProps = {\n\tvalue: null | number | undefined\n\t/** Fires on every edit with the value converted back to the storage unit. */\n\tonChange: (value: null | number) => void\n\toptions: MeasurementInputOptions\n\t/** Bounds in the storage unit; a value outside them shows a message in the display unit. */\n\tmin?: number\n\tmax?: number\n\t/** Names the input (`id`, `name`, label `htmlFor`), as on a native field. */\n\tpath?: string\n\tlabel?: StaticLabel\n\tdescription?: StaticDescription\n\tplaceholder?: string\n\trequired?: boolean\n\tlocalized?: boolean\n\treadOnly?: boolean\n\t/** Message shown in the error tooltip. Left unset, the input reports its own bound errors. */\n\terror?: string\n\t/** Forces the error state on or off. Left unset, it follows `error` and the bound check. */\n\tshowError?: boolean\n\tclassName?: string\n\tstyle?: React.CSSProperties\n\tLabel?: React.ReactNode\n\tError?: React.ReactNode\n\tDescription?: React.ReactNode\n\tBeforeInput?: React.ReactNode\n\tAfterInput?: React.ReactNode\n}\n\ntype MeasurementInputViewProps = { model: MeasurementModel } & Omit<\n\tMeasurementInputProps,\n\t'options'\n>\n\n/** The row itself, shared by `MeasurementInput` and the form-bound `MeasurementField`. */\nexport const MeasurementInputView: React.FC<MeasurementInputViewProps> = (props) => {\n\tconst {\n\t\tAfterInput,\n\t\tBeforeInput,\n\t\tclassName,\n\t\tDescription,\n\t\tdescription,\n\t\tError: ErrorComponent,\n\t\terror,\n\t\tLabel,\n\t\tlabel,\n\t\tlocalized,\n\t\tmax,\n\t\tmin,\n\t\tmodel,\n\t\tonChange,\n\t\tpath,\n\t\tplaceholder,\n\t\treadOnly,\n\t\trequired,\n\t\tshowError: showErrorFromProps,\n\t\tstyle,\n\t\tvalue,\n\t} = props\n\tconst {\n\t\tdisplayPrecision,\n\t\tdisplayUnit,\n\t\tengine,\n\t\tfmtBound,\n\t\tlocale,\n\t\tresolvedPrecision,\n\t\tselectUnit: selectModelUnit,\n\t\tstorageUnit,\n\t\tunits,\n\t} = model\n\tconst { t } = useTranslation()\n\tconst isReadOnly = Boolean(readOnly)\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\tconst errorMessage = error ?? boundsMessage\n\tconst showError = showErrorFromProps ?? errorMessage !== undefined\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 commit updates the live value\n\t// (and so `numericValue`) before the viewer blurs; diffing the next keystroke's\n\t// delta against that advanced value, instead of this frozen snapshot, would\n\t// 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\tonChange(\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, onChange, resolvedPrecision.entry]\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\tselectModelUnit(unit)\n\t\t},\n\t\t[selectModelUnit]\n\t)\n\n\tconst isCompound = engine.isCompoundUnit(displayUnit)\n\tconst compoundDef = isCompound ? COMPOUNDS[displayUnit] : null\n\t// Without a path there is no field id to derive, so the label pairs with a generated one\n\tconst generatedId = useId()\n\tconst inputId = path ? `field-${path.replace(/\\./g, '__')}` : generatedId\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\n\tconst renderUnitPanel = ({ close }: { close: () => void }) => (\n\t\t<div\n\t\t\taria-label={t(keys.selectUnit)}\n\t\t\tclassName={`${baseClass}__unit-panel popup-button-list`}\n\t\t\trole=\"listbox\"\n\t\t>\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={[\n\t\t\t\t\t\t`${baseClass}__unit-option`,\n\t\t\t\t\t\t'popup-button-list__button',\n\t\t\t\t\t\tunit === displayUnit && 'popup-button-list__button--selected',\n\t\t\t\t\t]\n\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t.join(' ')}\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// @todo Payload 4's Popup pins its panel to the viewport edge once the field scrolls out of\n\t\t\t// view (v3 let it scroll away with the field). Adopt the option if Payload adds one.\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={style}\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\n\t\t\t\t\t\thtmlFor={path ? undefined : inputId}\n\t\t\t\t\t\tlabel={label}\n\t\t\t\t\t\tlocalized={localized}\n\t\t\t\t\t\tpath={path}\n\t\t\t\t\t\trequired={required}\n\t\t\t\t\t/>\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={errorMessage} 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\n\t\t\t\t\tclassName={[\n\t\t\t\t\t\t`${baseClass}__container`,\n\t\t\t\t\t\t'form-input-group',\n\t\t\t\t\t\tshowError && 'form-input-group-error',\n\t\t\t\t\t]\n\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t.join(' ')}\n\t\t\t\t\tonMouseDown={focusNearestInput}\n\t\t\t\t>\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={placeholder}\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 || placeholder || '')}\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\n/**\n * The measurement field's row, unit menu and conversion pipeline with no form behind\n * it, for custom admin views and components. Inside the admin the display unit is the\n * viewer's saved preference for `preferenceKey`, shared with every measurement field\n * on that key; `MeasurementField` is this plus `useField`.\n */\nexport const MeasurementInput: React.FC<MeasurementInputProps> = ({ options, ...props }) => {\n\tconst model = useMeasurementModel(options)\n\treturn <MeasurementInputView model={model} {...props} />\n}\n"],"mappings":";;;;;;;;;;;AAwBA,MAAM,YAAY;AAElB,MAAM,QAAqB;CAAE,OAAO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;AACxD"}
|
|
@@ -8,6 +8,15 @@ const parseDraft = (raw) => {
|
|
|
8
8
|
const parsed = Number(raw);
|
|
9
9
|
return Number.isFinite(parsed) ? parsed : null;
|
|
10
10
|
};
|
|
11
|
+
/**
|
|
12
|
+
* The major part of a compound draft. An empty major beside a minor that holds a number
|
|
13
|
+
* reads as zero (`'' ft 5 in` is 5 in), so typing only the minor part commits; with both
|
|
14
|
+
* parts empty, or an unparseable major, there is nothing to commit.
|
|
15
|
+
*/
|
|
16
|
+
const parseMajorDraft = (drafts) => {
|
|
17
|
+
if (drafts.primary.trim() === "" && parseDraft(drafts.minor) !== null) return 0;
|
|
18
|
+
return parseDraft(drafts.primary);
|
|
19
|
+
};
|
|
11
20
|
const ALL_DIRTY = {
|
|
12
21
|
primary: true,
|
|
13
22
|
minor: true
|
|
@@ -22,7 +31,7 @@ const commitDrafts = (drafts, opts) => {
|
|
|
22
31
|
const exact = engine.decompose(storedValue, storageUnit, displayUnit, storageDigits);
|
|
23
32
|
const exactTotal = exact.major * compound.ratio + exact.minor;
|
|
24
33
|
if (dirty.primary) {
|
|
25
|
-
let typedMajor =
|
|
34
|
+
let typedMajor = parseMajorDraft(drafts);
|
|
26
35
|
if (typedMajor === null) return null;
|
|
27
36
|
if (entry === "quantize") typedMajor = roundTo(typedMajor, engine.precisionFor(compound.major, precision));
|
|
28
37
|
const paintedMajor = parseDraft(paintedDrafts.primary) ?? exact.major;
|
|
@@ -42,9 +51,9 @@ const commitDrafts = (drafts, opts) => {
|
|
|
42
51
|
const stored = hasStored ? engine.decompose(storedValue, storageUnit, displayUnit, storageDigits) : null;
|
|
43
52
|
let major;
|
|
44
53
|
if (dirty.primary) {
|
|
45
|
-
major =
|
|
54
|
+
major = parseMajorDraft(drafts);
|
|
46
55
|
if (major !== null && entry === "quantize") major = roundTo(major, engine.precisionFor(compound.major, precision));
|
|
47
|
-
} else major = stored ? stored.major :
|
|
56
|
+
} else major = stored ? stored.major : parseMajorDraft(drafts);
|
|
48
57
|
if (major === null) return null;
|
|
49
58
|
let minor;
|
|
50
59
|
if (dirty.minor) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editModel.js","names":[],"sources":["../../../../src/fields/measurement/client/editModel.ts"],"sourcesContent":["import { roundTo } from '../engine/convert'\nimport type { MeasurementEngine } from '../engine/registry'\nimport { COMPOUNDS, type MeasurementUnitId, STORAGE_FRACTION_DIGITS } from '../engine/units'\n\n/** Re-exported so MeasurementField/MeasurementCell keep one import site for the edit model. */\nexport { resolveDisplayUnit } from '../engine/locale'\n\nexport type MeasurementDrafts = { primary: string; minor: string }\n\n/** Which inputs the viewer has actually typed into since the last resync. */\nexport type DirtyDrafts = { primary: boolean; minor: boolean }\n\ntype UnitContext = {\n\t/** Bound over the field's custom units, so custom ids convert and format like built-ins. */\n\tengine: MeasurementEngine\n\tstorageUnit: MeasurementUnitId\n\tdisplayUnit: MeasurementUnitId\n\tprecision?: Partial<Record<MeasurementUnitId, number>>\n\t/**\n\t * Draft-repaint policy: 'faithful' (default) escalates fraction digits until the\n\t * draft round-trips to the stored value; 'display' renders straight at display\n\t * digits, so a stored value can print shorter than it is stored.\n\t */\n\tdraft?: 'display' | 'faithful'\n\t/** Fraction digits kept in the storage unit. Defaults to STORAGE_FRACTION_DIGITS. */\n\tstorageDigits?: number\n}\n\ntype CommitOptions = UnitContext & {\n\t/**\n\t * Entry-unit typing behavior: 'quantize' rounds a dirty part at its own display\n\t * digits, in the unit it was typed in, before converting; 'free' (default) keeps\n\t * the typed value exact.\n\t */\n\tentry?: 'quantize' | 'free'\n\t/** An untouched part never commits its displayed string; only a dirty one does. */\n\tdirty?: DirtyDrafts\n\t/** Current stored value, used to derive an untouched part's exact contribution. */\n\tstoredValue?: number | null\n\t/**\n\t * The compound drafts as painted on screen immediately before this edit (not the\n\t * post-keystroke `drafts`). A display-digit repaint can carry (182.5 cm storage\n\t * splits exactly to 5 ft 11.850394 in but paints as 6 ft 0 in), so when exactly\n\t * one part is dirty, the edited part's contribution is computed as a delta off\n\t * this baseline rather than a full replace, which would otherwise bake the\n\t * painted carry into storage.\n\t */\n\tpaintedDrafts?: MeasurementDrafts\n}\n\nconst numberToDraft = (value: number): string => String(value)\n\nconst parseDraft = (raw: string): number | null => {\n\tif (raw.trim() === '') return null\n\tconst parsed = Number(raw)\n\treturn Number.isFinite(parsed) ? parsed : null\n}\n\n// draftsFor/commitDrafts default to 'faithful'/'free'/ALL_DIRTY when a caller omits\n// them, i.e. the shape of 'exact' mode, not the engine's own 'readable' default: the\n// component always threads its resolved precision explicitly, so these bare defaults\n// exist only for a caller invoking editModel directly (tests, or an embedder outside\n// the component), and preserve the single behavior this module had before precision\n// modes existed.\nconst ALL_DIRTY: DirtyDrafts = { primary: true, minor: true }\n\nexport const commitDrafts = (drafts: MeasurementDrafts, opts: CommitOptions): number | null => {\n\tconst {\n\t\tdisplayUnit,\n\t\tdirty = ALL_DIRTY,\n\t\tengine,\n\t\tentry = 'free',\n\t\tpaintedDrafts,\n\t\tprecision,\n\t\tstorageDigits = STORAGE_FRACTION_DIGITS,\n\t\tstorageUnit,\n\t\tstoredValue = null,\n\t} = opts\n\n\tif (engine.isCompoundUnit(displayUnit)) {\n\t\tconst compound = COMPOUNDS[displayUnit]\n\t\tconst hasStored = typeof storedValue === 'number'\n\t\tconst dirtyCount = (dirty.primary ? 1 : 0) + (dirty.minor ? 1 : 0)\n\n\t\t// Delta path: exactly one part was touched and a painted baseline exists, so\n\t\t// the untouched part's contribution comes entirely from the exact stored\n\t\t// total (never its carried, display-precision draft), and the touched part\n\t\t// contributes only the change the viewer actually typed, in minor units.\n\t\tif (hasStored && dirtyCount === 1 && paintedDrafts) {\n\t\t\tconst exact = engine.decompose(storedValue as number, storageUnit, displayUnit, storageDigits)\n\t\t\tconst exactTotal = exact.major * compound.ratio + exact.minor\n\n\t\t\tif (dirty.primary) {\n\t\t\t\tlet typedMajor = parseDraft(drafts.primary)\n\t\t\t\tif (typedMajor === null) return null\n\t\t\t\tif (entry === 'quantize') {\n\t\t\t\t\ttypedMajor = roundTo(typedMajor, engine.precisionFor(compound.major, precision))\n\t\t\t\t}\n\t\t\t\tconst paintedMajor = parseDraft(paintedDrafts.primary) ?? exact.major\n\t\t\t\tconst newTotal = exactTotal + (typedMajor - paintedMajor) * compound.ratio\n\t\t\t\treturn roundTo(\n\t\t\t\t\tengine.compose({ major: 0, minor: newTotal }, displayUnit, storageUnit),\n\t\t\t\t\tstorageDigits\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst rawMinor = parseDraft(drafts.minor) ?? 0\n\t\t\tconst typedMinor =\n\t\t\t\tentry === 'quantize'\n\t\t\t\t\t? roundTo(rawMinor, engine.precisionFor(displayUnit, precision))\n\t\t\t\t\t: rawMinor\n\t\t\tconst paintedMinor = parseDraft(paintedDrafts.minor) ?? 0\n\t\t\tconst newTotal = exactTotal + (typedMinor - paintedMinor)\n\t\t\treturn roundTo(\n\t\t\t\tengine.compose({ major: 0, minor: newTotal }, displayUnit, storageUnit),\n\t\t\t\tstorageDigits\n\t\t\t)\n\t\t}\n\n\t\t// Both parts dirty (an explicit full replace) or no baseline to diff\n\t\t// against: compose the two parts directly, as before.\n\t\tconst stored = hasStored\n\t\t\t? engine.decompose(storedValue as number, storageUnit, displayUnit, storageDigits)\n\t\t\t: null\n\n\t\tlet major: number | null\n\t\tif (dirty.primary) {\n\t\t\tmajor = parseDraft(drafts.primary)\n\t\t\tif (major !== null && entry === 'quantize') {\n\t\t\t\tmajor = roundTo(major, engine.precisionFor(compound.major, precision))\n\t\t\t}\n\t\t} else {\n\t\t\tmajor = stored ? stored.major : parseDraft(drafts.primary)\n\t\t}\n\t\tif (major === null) return null\n\n\t\tlet minor: number\n\t\tif (dirty.minor) {\n\t\t\tconst rawMinor = parseDraft(drafts.minor) ?? 0\n\t\t\tconst maxMinor = compound.ratio - 0.001\n\t\t\t// Clamp the raw typed magnitude (bounds a literal 24) before quantizing:\n\t\t\t// a quantized value landing exactly on the ratio (11.96 -> 12) must be\n\t\t\t// free to carry into the major via compose, matching decompose's own\n\t\t\t// carry contract, so nothing clamps it back down afterward.\n\t\t\tconst clampedRaw = Math.sign(rawMinor) * Math.min(Math.abs(rawMinor), maxMinor)\n\t\t\tminor =\n\t\t\t\tentry === 'quantize'\n\t\t\t\t\t? roundTo(clampedRaw, engine.precisionFor(displayUnit, precision))\n\t\t\t\t\t: clampedRaw\n\t\t} else {\n\t\t\t// No stored value to derive an exact minor from (a brand new, never-saved\n\t\t\t// field): fall back to the painted baseline, matching major's own fallback,\n\t\t\t// never a bare 0 (a cleared-then-retyped major would otherwise commit with\n\t\t\t// its minor silently zeroed).\n\t\t\tminor = stored ? stored.minor : (parseDraft(paintedDrafts?.minor ?? '') ?? 0)\n\t\t}\n\n\t\treturn roundTo(engine.compose({ major, minor }, displayUnit, storageUnit), storageDigits)\n\t}\n\n\tif (!dirty.primary) return storedValue\n\tconst parsed = parseDraft(drafts.primary)\n\tif (parsed === null) return null\n\tconst value =\n\t\tentry === 'quantize' ? roundTo(parsed, engine.precisionFor(displayUnit, precision)) : parsed\n\treturn roundTo(engine.convert(value, displayUnit, storageUnit), storageDigits)\n}\n\n/**\n * Drafts for repainting from a stored value. 'faithful' (default) is the shortest\n * draft that commits back to the stored value: display precision first, then one\n * more fraction digit at a time up to storage precision, since a draft that\n * silently truncates the stored value would write the truncation back on the next\n * save. 'display' skips escalation and renders straight at display digits\n * (compound parts each at their own digits), trading faithfulness for a value that\n * always matches what the unit picker promises.\n */\nexport const draftsFor = (value: number | null, opts: UnitContext): MeasurementDrafts => {\n\tif (typeof value !== 'number' || Number.isNaN(value)) return { minor: '', primary: '' }\n\tconst {\n\t\tdisplayUnit,\n\t\tdraft = 'faithful',\n\t\tengine,\n\t\tprecision,\n\t\tstorageDigits = STORAGE_FRACTION_DIGITS,\n\t\tstorageUnit,\n\t} = opts\n\tconst draftAt = (digits: number): MeasurementDrafts => {\n\t\tif (engine.isCompoundUnit(displayUnit)) {\n\t\t\tconst parts = engine.decompose(value, storageUnit, displayUnit, digits)\n\t\t\treturn { minor: numberToDraft(parts.minor), primary: numberToDraft(parts.major) }\n\t\t}\n\t\tconst converted = roundTo(engine.convert(value, storageUnit, displayUnit), digits)\n\t\treturn { minor: '', primary: numberToDraft(converted) }\n\t}\n\n\tconst displayDigits = engine.precisionFor(displayUnit, precision)\n\tif (draft === 'display') return draftAt(displayDigits)\n\n\t// Digits past storage precision never survive a save, so that is where escalation stops.\n\tconst maxDigits = Math.max(displayDigits, storageDigits)\n\tconst target = roundTo(value, storageDigits)\n\t// A bare probe: never forward `opts` itself, so an entry/dirty/storedValue field\n\t// a future CommitOptions caller happens to carry can never poison this check.\n\tconst probeOpts: UnitContext = { displayUnit, engine, precision, storageDigits, storageUnit }\n\tfor (let digits = displayDigits; digits < maxDigits; digits++) {\n\t\tconst candidate = draftAt(digits)\n\t\tif (commitDrafts(candidate, probeOpts) === target) return candidate\n\t}\n\treturn draftAt(maxDigits)\n}\n"],"mappings":";;;;AAkDA,MAAM,iBAAiB,UAA0B,OAAO,KAAK;AAE7D,MAAM,cAAc,QAA+B;CAClD,IAAI,IAAI,KAAK,MAAM,IAAI,OAAO;CAC9B,MAAM,SAAS,OAAO,GAAG;CACzB,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC3C;AAQA,MAAM,YAAyB;CAAE,SAAS;CAAM,OAAO;AAAK;AAE5D,MAAa,gBAAgB,QAA2B,SAAuC;CAC9F,MAAM,EACL,aACA,QAAQ,WACR,QACA,QAAQ,QACR,eACA,WACA,gBAAA,GACA,aACA,cAAc,SACX;CAEJ,IAAI,OAAO,eAAe,WAAW,GAAG;EACvC,MAAM,WAAW,UAAU;EAC3B,MAAM,YAAY,OAAO,gBAAgB;EACzC,MAAM,cAAc,MAAM,UAAU,IAAI,MAAM,MAAM,QAAQ,IAAI;EAMhE,IAAI,aAAa,eAAe,KAAK,eAAe;GACnD,MAAM,QAAQ,OAAO,UAAU,aAAuB,aAAa,aAAa,aAAa;GAC7F,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MAAM;EAChC,IAAI,aAAa,WAAW,SAAS,MAAM,QAAQ,OAAO;CAC3D;CACA,OAAO,QAAQ,SAAS;AACzB"}
|
|
1
|
+
{"version":3,"file":"editModel.js","names":[],"sources":["../../../../src/fields/measurement/client/editModel.ts"],"sourcesContent":["import { roundTo } from '../engine/convert'\nimport type { MeasurementEngine } from '../engine/registry'\nimport { COMPOUNDS, type MeasurementUnitId, STORAGE_FRACTION_DIGITS } from '../engine/units'\n\n/** Re-exported so MeasurementField/MeasurementCell keep one import site for the edit model. */\nexport { resolveDisplayUnit } from '../engine/locale'\n\nexport type MeasurementDrafts = { primary: string; minor: string }\n\n/** Which inputs the viewer has actually typed into since the last resync. */\nexport type DirtyDrafts = { primary: boolean; minor: boolean }\n\ntype UnitContext = {\n\t/** Bound over the field's custom units, so custom ids convert and format like built-ins. */\n\tengine: MeasurementEngine\n\tstorageUnit: MeasurementUnitId\n\tdisplayUnit: MeasurementUnitId\n\tprecision?: Partial<Record<MeasurementUnitId, number>>\n\t/**\n\t * Draft-repaint policy: 'faithful' (default) escalates fraction digits until the\n\t * draft round-trips to the stored value; 'display' renders straight at display\n\t * digits, so a stored value can print shorter than it is stored.\n\t */\n\tdraft?: 'display' | 'faithful'\n\t/** Fraction digits kept in the storage unit. Defaults to STORAGE_FRACTION_DIGITS. */\n\tstorageDigits?: number\n}\n\ntype CommitOptions = UnitContext & {\n\t/**\n\t * Entry-unit typing behavior: 'quantize' rounds a dirty part at its own display\n\t * digits, in the unit it was typed in, before converting; 'free' (default) keeps\n\t * the typed value exact.\n\t */\n\tentry?: 'quantize' | 'free'\n\t/** An untouched part never commits its displayed string; only a dirty one does. */\n\tdirty?: DirtyDrafts\n\t/** Current stored value, used to derive an untouched part's exact contribution. */\n\tstoredValue?: number | null\n\t/**\n\t * The compound drafts as painted on screen immediately before this edit (not the\n\t * post-keystroke `drafts`). A display-digit repaint can carry (182.5 cm storage\n\t * splits exactly to 5 ft 11.850394 in but paints as 6 ft 0 in), so when exactly\n\t * one part is dirty, the edited part's contribution is computed as a delta off\n\t * this baseline rather than a full replace, which would otherwise bake the\n\t * painted carry into storage.\n\t */\n\tpaintedDrafts?: MeasurementDrafts\n}\n\nconst numberToDraft = (value: number): string => String(value)\n\nconst parseDraft = (raw: string): number | null => {\n\tif (raw.trim() === '') return null\n\tconst parsed = Number(raw)\n\treturn Number.isFinite(parsed) ? parsed : null\n}\n\n/**\n * The major part of a compound draft. An empty major beside a minor that holds a number\n * reads as zero (`'' ft 5 in` is 5 in), so typing only the minor part commits; with both\n * parts empty, or an unparseable major, there is nothing to commit.\n */\nconst parseMajorDraft = (drafts: MeasurementDrafts): number | null => {\n\tif (drafts.primary.trim() === '' && parseDraft(drafts.minor) !== null) return 0\n\treturn parseDraft(drafts.primary)\n}\n\n// draftsFor/commitDrafts default to 'faithful'/'free'/ALL_DIRTY when a caller omits\n// them, i.e. the shape of 'exact' mode, not the engine's own 'readable' default: the\n// component always threads its resolved precision explicitly, so these bare defaults\n// exist only for a caller invoking editModel directly (tests, or an embedder outside\n// the component), and preserve the single behavior this module had before precision\n// modes existed.\nconst ALL_DIRTY: DirtyDrafts = { primary: true, minor: true }\n\nexport const commitDrafts = (drafts: MeasurementDrafts, opts: CommitOptions): number | null => {\n\tconst {\n\t\tdisplayUnit,\n\t\tdirty = ALL_DIRTY,\n\t\tengine,\n\t\tentry = 'free',\n\t\tpaintedDrafts,\n\t\tprecision,\n\t\tstorageDigits = STORAGE_FRACTION_DIGITS,\n\t\tstorageUnit,\n\t\tstoredValue = null,\n\t} = opts\n\n\tif (engine.isCompoundUnit(displayUnit)) {\n\t\tconst compound = COMPOUNDS[displayUnit]\n\t\tconst hasStored = typeof storedValue === 'number'\n\t\tconst dirtyCount = (dirty.primary ? 1 : 0) + (dirty.minor ? 1 : 0)\n\n\t\t// Delta path: exactly one part was touched and a painted baseline exists, so\n\t\t// the untouched part's contribution comes entirely from the exact stored\n\t\t// total (never its carried, display-precision draft), and the touched part\n\t\t// contributes only the change the viewer actually typed, in minor units.\n\t\tif (hasStored && dirtyCount === 1 && paintedDrafts) {\n\t\t\tconst exact = engine.decompose(storedValue as number, storageUnit, displayUnit, storageDigits)\n\t\t\tconst exactTotal = exact.major * compound.ratio + exact.minor\n\n\t\t\tif (dirty.primary) {\n\t\t\t\tlet typedMajor = parseMajorDraft(drafts)\n\t\t\t\tif (typedMajor === null) return null\n\t\t\t\tif (entry === 'quantize') {\n\t\t\t\t\ttypedMajor = roundTo(typedMajor, engine.precisionFor(compound.major, precision))\n\t\t\t\t}\n\t\t\t\tconst paintedMajor = parseDraft(paintedDrafts.primary) ?? exact.major\n\t\t\t\tconst newTotal = exactTotal + (typedMajor - paintedMajor) * compound.ratio\n\t\t\t\treturn roundTo(\n\t\t\t\t\tengine.compose({ major: 0, minor: newTotal }, displayUnit, storageUnit),\n\t\t\t\t\tstorageDigits\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst rawMinor = parseDraft(drafts.minor) ?? 0\n\t\t\tconst typedMinor =\n\t\t\t\tentry === 'quantize'\n\t\t\t\t\t? roundTo(rawMinor, engine.precisionFor(displayUnit, precision))\n\t\t\t\t\t: rawMinor\n\t\t\tconst paintedMinor = parseDraft(paintedDrafts.minor) ?? 0\n\t\t\tconst newTotal = exactTotal + (typedMinor - paintedMinor)\n\t\t\treturn roundTo(\n\t\t\t\tengine.compose({ major: 0, minor: newTotal }, displayUnit, storageUnit),\n\t\t\t\tstorageDigits\n\t\t\t)\n\t\t}\n\n\t\t// Both parts dirty (an explicit full replace) or no baseline to diff\n\t\t// against: compose the two parts directly, as before.\n\t\tconst stored = hasStored\n\t\t\t? engine.decompose(storedValue as number, storageUnit, displayUnit, storageDigits)\n\t\t\t: null\n\n\t\tlet major: number | null\n\t\tif (dirty.primary) {\n\t\t\tmajor = parseMajorDraft(drafts)\n\t\t\tif (major !== null && entry === 'quantize') {\n\t\t\t\tmajor = roundTo(major, engine.precisionFor(compound.major, precision))\n\t\t\t}\n\t\t} else {\n\t\t\tmajor = stored ? stored.major : parseMajorDraft(drafts)\n\t\t}\n\t\tif (major === null) return null\n\n\t\tlet minor: number\n\t\tif (dirty.minor) {\n\t\t\tconst rawMinor = parseDraft(drafts.minor) ?? 0\n\t\t\tconst maxMinor = compound.ratio - 0.001\n\t\t\t// Clamp the raw typed magnitude (bounds a literal 24) before quantizing:\n\t\t\t// a quantized value landing exactly on the ratio (11.96 -> 12) must be\n\t\t\t// free to carry into the major via compose, matching decompose's own\n\t\t\t// carry contract, so nothing clamps it back down afterward.\n\t\t\tconst clampedRaw = Math.sign(rawMinor) * Math.min(Math.abs(rawMinor), maxMinor)\n\t\t\tminor =\n\t\t\t\tentry === 'quantize'\n\t\t\t\t\t? roundTo(clampedRaw, engine.precisionFor(displayUnit, precision))\n\t\t\t\t\t: clampedRaw\n\t\t} else {\n\t\t\t// No stored value to derive an exact minor from (a brand new, never-saved\n\t\t\t// field): fall back to the painted baseline, matching major's own fallback,\n\t\t\t// never a bare 0 (a cleared-then-retyped major would otherwise commit with\n\t\t\t// its minor silently zeroed).\n\t\t\tminor = stored ? stored.minor : (parseDraft(paintedDrafts?.minor ?? '') ?? 0)\n\t\t}\n\n\t\treturn roundTo(engine.compose({ major, minor }, displayUnit, storageUnit), storageDigits)\n\t}\n\n\tif (!dirty.primary) return storedValue\n\tconst parsed = parseDraft(drafts.primary)\n\tif (parsed === null) return null\n\tconst value =\n\t\tentry === 'quantize' ? roundTo(parsed, engine.precisionFor(displayUnit, precision)) : parsed\n\treturn roundTo(engine.convert(value, displayUnit, storageUnit), storageDigits)\n}\n\n/**\n * Drafts for repainting from a stored value. 'faithful' (default) is the shortest\n * draft that commits back to the stored value: display precision first, then one\n * more fraction digit at a time up to storage precision, since a draft that\n * silently truncates the stored value would write the truncation back on the next\n * save. 'display' skips escalation and renders straight at display digits\n * (compound parts each at their own digits), trading faithfulness for a value that\n * always matches what the unit picker promises.\n */\nexport const draftsFor = (value: number | null, opts: UnitContext): MeasurementDrafts => {\n\tif (typeof value !== 'number' || Number.isNaN(value)) return { minor: '', primary: '' }\n\tconst {\n\t\tdisplayUnit,\n\t\tdraft = 'faithful',\n\t\tengine,\n\t\tprecision,\n\t\tstorageDigits = STORAGE_FRACTION_DIGITS,\n\t\tstorageUnit,\n\t} = opts\n\tconst draftAt = (digits: number): MeasurementDrafts => {\n\t\tif (engine.isCompoundUnit(displayUnit)) {\n\t\t\tconst parts = engine.decompose(value, storageUnit, displayUnit, digits)\n\t\t\treturn { minor: numberToDraft(parts.minor), primary: numberToDraft(parts.major) }\n\t\t}\n\t\tconst converted = roundTo(engine.convert(value, storageUnit, displayUnit), digits)\n\t\treturn { minor: '', primary: numberToDraft(converted) }\n\t}\n\n\tconst displayDigits = engine.precisionFor(displayUnit, precision)\n\tif (draft === 'display') return draftAt(displayDigits)\n\n\t// Digits past storage precision never survive a save, so that is where escalation stops.\n\tconst maxDigits = Math.max(displayDigits, storageDigits)\n\tconst target = roundTo(value, storageDigits)\n\t// A bare probe: never forward `opts` itself, so an entry/dirty/storedValue field\n\t// a future CommitOptions caller happens to carry can never poison this check.\n\tconst probeOpts: UnitContext = { displayUnit, engine, precision, storageDigits, storageUnit }\n\tfor (let digits = displayDigits; digits < maxDigits; digits++) {\n\t\tconst candidate = draftAt(digits)\n\t\tif (commitDrafts(candidate, probeOpts) === target) return candidate\n\t}\n\treturn draftAt(maxDigits)\n}\n"],"mappings":";;;;AAkDA,MAAM,iBAAiB,UAA0B,OAAO,KAAK;AAE7D,MAAM,cAAc,QAA+B;CAClD,IAAI,IAAI,KAAK,MAAM,IAAI,OAAO;CAC9B,MAAM,SAAS,OAAO,GAAG;CACzB,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC3C;;;;;;AAOA,MAAM,mBAAmB,WAA6C;CACrE,IAAI,OAAO,QAAQ,KAAK,MAAM,MAAM,WAAW,OAAO,KAAK,MAAM,MAAM,OAAO;CAC9E,OAAO,WAAW,OAAO,OAAO;AACjC;AAQA,MAAM,YAAyB;CAAE,SAAS;CA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