@cutticat/payload-field-ms 0.0.0-stage → 1.0.0

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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maksim Victorovich Fomin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,156 @@
1
- # Temporary Holding Version
1
+ # @cutticat/payload-field-ms
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Payload CMS](https://payloadcms.com/) 3 `number` field edited as a duration. Editors type `10d`
4
+ or `1h 30m`, the database stores milliseconds, and the list view shows `1w 3d` instead of
5
+ `864000000`. The syntax is [`@cutticat/ms`](https://www.npmjs.com/package/@cutticat/ms).
6
+
7
+ ## Contents
8
+
9
+ - [Overview](#overview)
10
+ - [Installation](#installation)
11
+ - [Quick start](#quick-start)
12
+ - [Negative durations](#negative-durations)
13
+ - [Validation](#validation)
14
+ - [What is stored](#what-is-stored)
15
+ - [API](#api)
16
+ - [Documentation](#documentation)
17
+ - [Requirements](#requirements)
18
+
19
+ ## Overview
20
+
21
+ A timeout, a reminder offset, or a retention period is a number of milliseconds in code. A plain
22
+ Payload `number` field makes editors type `604800000` for a week. `durationField` keeps the
23
+ number column and changes only the admin:
24
+
25
+ - one value is a text input that reads `1w`, `90m`, `-2h`
26
+ - `hasMany` is a list of chips in the same syntax, like Payload's own `hasMany` number field
27
+ - the list view formats the stored numbers the same way
28
+
29
+ The input and the chips are Payload's own text input, so the field looks and behaves like the
30
+ rest of the admin. Messages come from Payload's translations, in every language it supports. No
31
+ plugin and no extra config.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pnpm add @cutticat/payload-field-ms
37
+ ```
38
+
39
+ `payload`, `@payloadcms/ui`, `react`, and `react-dom` are peer dependencies.
40
+
41
+ ## Quick start
42
+
43
+ ```typescript
44
+ import type { GlobalConfig } from "payload"
45
+ import { durationField } from "@cutticat/payload-field-ms"
46
+
47
+ export const Settings: GlobalConfig = {
48
+ slug: "settings",
49
+ fields: [
50
+ durationField({ name: "sessionTimeoutMs", label: "Session timeout", required: true }),
51
+ durationField({ name: "remindersMs", label: "Reminders", hasMany: true, maxRows: 3 }),
52
+ ],
53
+ }
54
+ ```
55
+
56
+ The options are those of a `number` field without `type`. `admin.components.Field` and `Cell` are
57
+ the duration ones; `admin.step` and `autoComplete` do not apply to a text input. Then run
58
+ `payload generate:importmap`: it picks up `@cutticat/payload-field-ms/client#DurationField` and
59
+ `#DurationCell`.
60
+
61
+ ## Negative durations
62
+
63
+ `min` defaults to `0`, so a negative duration is rejected in the admin and by the API. An offset
64
+ that may point back in time removes the bound with `null`:
65
+
66
+ ```typescript
67
+ durationField({ name: "offsetMs", min: null })
68
+ ```
69
+
70
+ Any other `min` or `max` works as on a number field, in milliseconds.
71
+
72
+ ## Validation
73
+
74
+ The field's `validate` runs on the server, for saves from the admin and the API:
75
+
76
+ - text the syntax does not cover, such as `5 мин`, is rejected with Payload's "This field has an
77
+ invalid input" and stays in the input to fix; so is any other item that is not a finite number,
78
+ such as a string in a `hasMany` value sent to the API
79
+ - `min` and `max` use Payload's messages with the numbers shown as durations: "-2h is less than
80
+ the min allowed Value of 0ms."
81
+ - then Payload's number validation checks `required`, `minRows`, and `maxRows`, or your own
82
+ `validate`, if you pass one
83
+
84
+ Payload does not validate a draft save unless `versions.drafts.validate` is on. Without it the
85
+ field drops text that did not parse, and a single value keeps what was saved before.
86
+
87
+ Until validation rejects it, unparsed text is in the value as `{ text: "5 мин" }`, and your own
88
+ `beforeValidate` and `beforeChange` hooks on the field see it there.
89
+
90
+ The API takes milliseconds. Payload itself turns a string sent to a single number field into a
91
+ number with `parseFloat`, so `"10d"` from a REST client becomes `10`. In the input a bare number
92
+ is milliseconds too: `30` is `30ms`.
93
+
94
+ A number field built by hand can use the same checks with `createDurationValidation` and
95
+ `dropUnparsedFromDraft`; both are needed with the duration input. The validation reads `min` and
96
+ `max` from the field config:
97
+
98
+ ```typescript
99
+ import type { NumberField } from "payload"
100
+ import { createDurationValidation, dropUnparsedFromDraft } from "@cutticat/payload-field-ms"
101
+
102
+ const timeout: NumberField = {
103
+ name: "timeoutMs",
104
+ type: "number",
105
+ min: 0,
106
+ max: 86_400_000,
107
+ validate: createDurationValidation(),
108
+ hooks: { beforeChange: [dropUnparsedFromDraft] },
109
+ admin: { components: { Field: "@cutticat/payload-field-ms/client#DurationField" } },
110
+ }
111
+ ```
112
+
113
+ ## What is stored
114
+
115
+ - One value: milliseconds, or `null` when the input is empty.
116
+ - `hasMany`: an ordered `number[]`, `[]` when there are no chips.
117
+
118
+ The input rounds to whole milliseconds, the smallest unit it shows: `0.4ms` is saved as `0`.
119
+
120
+ The input shows what was typed until the value changes elsewhere. After a reload it shows the
121
+ short form: `10d` comes back as `1w 3d`.
122
+
123
+ This is a duration, not a point in time. A timestamp shown in this syntax reads as a span of
124
+ years.
125
+
126
+ ## API
127
+
128
+ ### Root entry
129
+
130
+ - `durationField(options)` — a Payload `number` field config with the duration input, list cell,
131
+ and validation. `options` is a number field config without `type`; `min` defaults to `0`,
132
+ `null` removes a bound
133
+ - `DurationFieldOptions` — type of `options`
134
+ - `createDurationValidation(options?)` — the field's validation for a number field built by hand,
135
+ with the bounds from its config; `CreateDurationValidationOptions`: `validate`, run after the
136
+ duration checks instead of Payload's number validation
137
+ - `dropUnparsedFromDraft` — `beforeChange` hook that keeps unparsed text out of a draft save
138
+
139
+ ### `./client`
140
+
141
+ - `DurationField` — the admin input. Payload loads it through the import map
142
+ - `DurationCell` — the list-view cell
143
+
144
+ ## Documentation
145
+
146
+ - [Project structure](<https://gitflic.ru/project/cutticat-npm/payload-field-ms/blob?branch=main&file=packages/field/documents/STRUCTURE.md>)
147
+ - [Scripts](<https://gitflic.ru/project/cutticat-npm/payload-field-ms/blob?branch=main&file=packages/field/documents/SCRIPTS.md>)
148
+ - [Style guide](<https://gitflic.ru/project/cutticat-npm/payload-field-ms/blob?branch=main&file=documents/STYLE_GUIDE.md>)
149
+ - [Contributing](<https://gitflic.ru/project/cutticat-npm/payload-field-ms/blob?branch=main&file=documents/CONTRIBUTING.md>)
150
+
151
+ ## Requirements
152
+
153
+ - Node.js >= 22.18.0
154
+ - pnpm >= 10.17.0 for development
155
+ - Payload >= 3.80 and < 4
156
+ - React >= 19
@@ -0,0 +1,14 @@
1
+ import { FC } from "react";
2
+ import { DefaultCellComponentProps, NumberFieldClient } from "payload";
3
+ //#region lib/client/DurationCell.d.ts
4
+ /**
5
+ * List-view cell of {@link durationField}: Payload's default cell with the stored durations in
6
+ * the input's format, joined with a comma. Links, row selection, and the empty state stay
7
+ * Payload's.
8
+ *
9
+ * @param props - Payload cell props.
10
+ * @returns The cell.
11
+ */
12
+ export declare const DurationCell: FC<DefaultCellComponentProps<NumberFieldClient>>;
13
+ //#endregion
14
+ //# sourceMappingURL=DurationCell.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DurationCell.d.ts","names":[],"sources":["../../lib/client/DurationCell.tsx"],"mappings":";;;;;;;;;;;qBAea,cAAc,GAAG,0BAA0B"}
@@ -0,0 +1,21 @@
1
+ "use client";
2
+ import { textsOf } from "./internal/durations.js";
3
+ import { DefaultCell } from "@payloadcms/ui";
4
+ import { jsx } from "react/jsx-runtime";
5
+ //#region lib/client/DurationCell.tsx
6
+ /**
7
+ * List-view cell of {@link durationField}: Payload's default cell with the stored durations in
8
+ * the input's format, joined with a comma. Links, row selection, and the empty state stay
9
+ * Payload's.
10
+ *
11
+ * @param props - Payload cell props.
12
+ * @returns The cell.
13
+ */
14
+ const DurationCell = (props) => /* @__PURE__ */ jsx(DefaultCell, {
15
+ ...props,
16
+ cellData: textsOf(props.cellData).join(", ")
17
+ });
18
+ //#endregion
19
+ export { DurationCell };
20
+
21
+ //# sourceMappingURL=DurationCell.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DurationCell.js","names":[],"sources":["../../lib/client/DurationCell.tsx"],"sourcesContent":["\"use client\"\n\nimport { DefaultCell } from \"@payloadcms/ui\"\nimport type { DefaultCellComponentProps, NumberFieldClient } from \"payload\"\nimport type { FC } from \"react\"\nimport { textsOf } from \"../internal/durations.js\"\n\n/**\n * List-view cell of {@link durationField}: Payload's default cell with the stored durations in\n * the input's format, joined with a comma. Links, row selection, and the empty state stay\n * Payload's.\n *\n * @param props - Payload cell props.\n * @returns The cell.\n */\nexport const DurationCell: FC<DefaultCellComponentProps<NumberFieldClient>> = props => (\n <DefaultCell {...props} cellData={textsOf(props.cellData).join(\", \")} />\n)\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAa,gBAAiE,UAC5E,oBAAC,aAAD;CAAa,GAAI;CAAO,UAAU,QAAQ,MAAM,QAAQ,CAAC,CAAC,KAAK,IAAI;AAAI,CAAA"}
@@ -0,0 +1,14 @@
1
+ import { NumberFieldClientComponent } from "payload";
2
+ //#region lib/client/DurationField.d.ts
3
+ /**
4
+ * Admin input of {@link durationField}: Payload's text input over a number field.
5
+ *
6
+ * One value is a text box, `hasMany` is a list of chips. Text that does not parse stays in
7
+ * the input and in the form value, and the field's server validation rejects it.
8
+ *
9
+ * @param props - Payload number field client props.
10
+ * @returns The field.
11
+ */
12
+ export declare const DurationField: NumberFieldClientComponent;
13
+ //#endregion
14
+ //# sourceMappingURL=DurationField.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DurationField.d.ts","names":[],"sources":["../../lib/client/DurationField.tsx"],"mappings":";;;;;;;;;;;qBA0Ba,eAAe"}
@@ -0,0 +1,75 @@
1
+ "use client";
2
+ import { textsMatch, textsOf, valueOfText } from "./internal/durations.js";
3
+ import { chipOf, textOfChip } from "./internal/chips.js";
4
+ import { TextInput, useField } from "@payloadcms/ui";
5
+ import { jsx } from "react/jsx-runtime";
6
+ import { mergeFieldStyles } from "@payloadcms/ui/shared";
7
+ import { useCallback, useEffect, useMemo, useState } from "react";
8
+ import { omitUndefined } from "@cutticat/objects";
9
+ //#region lib/client/DurationField.tsx
10
+ /**
11
+ * Admin input of {@link durationField}: Payload's text input over a number field.
12
+ *
13
+ * One value is a text box, `hasMany` is a list of chips. Text that does not parse stays in
14
+ * the input and in the form value, and the field's server validation rejects it.
15
+ *
16
+ * @param props - Payload number field client props.
17
+ * @returns The field.
18
+ */
19
+ const DurationField = ({ field, onChange: onChangeFromProps, path: pathFromProps, readOnly }) => {
20
+ const { admin: { className, description, placeholder, readOnly: readOnlyFromConfig } = {}, hasMany = false, label, localized, required } = field;
21
+ const maxRows = "maxRows" in field ? field.maxRows : void 0;
22
+ const { customComponents: { AfterInput, BeforeInput, Description, Error: ErrorComponent, Label } = {}, disabled, path, setValue, showError, value } = useField({ potentiallyStalePath: pathFromProps });
23
+ const isReadOnly = readOnly || disabled || readOnlyFromConfig === true;
24
+ const [texts, setTexts] = useState(() => textsOf(value));
25
+ const style = useMemo(() => mergeFieldStyles(field), [field]);
26
+ useEffect(() => {
27
+ setTexts((current) => textsMatch(current, value) ? current : textsOf(value));
28
+ }, [value]);
29
+ const handleChange = useCallback((event) => {
30
+ const next = valueOfText(event.target.value);
31
+ setTexts([event.target.value]);
32
+ setValue(next);
33
+ if (typeof next === "number") onChangeFromProps?.(next);
34
+ }, [onChangeFromProps, setValue]);
35
+ const handleManyChange = useCallback((selected) => {
36
+ if (isReadOnly) return;
37
+ const nextTexts = (Array.isArray(selected) ? selected : selected == null ? [] : [selected]).map(textOfChip).filter((text) => text.trim() !== "");
38
+ setTexts(nextTexts);
39
+ setValue(nextTexts.flatMap((text) => valueOfText(text) ?? []));
40
+ }, [isReadOnly, setValue]);
41
+ const shared = omitUndefined({
42
+ AfterInput,
43
+ BeforeInput,
44
+ className,
45
+ Description,
46
+ description,
47
+ Error: ErrorComponent,
48
+ Label,
49
+ label,
50
+ localized,
51
+ path,
52
+ placeholder,
53
+ readOnly: isReadOnly,
54
+ required,
55
+ showError,
56
+ style
57
+ });
58
+ if (!hasMany) return /* @__PURE__ */ jsx(TextInput, {
59
+ ...shared,
60
+ onChange: handleChange,
61
+ value: texts[0] ?? ""
62
+ });
63
+ return /* @__PURE__ */ jsx(TextInput, {
64
+ ...shared,
65
+ hasMany: true,
66
+ ...omitUndefined({ maxRows }),
67
+ onChange: handleManyChange,
68
+ value: texts,
69
+ valueToRender: texts.map(chipOf)
70
+ });
71
+ };
72
+ //#endregion
73
+ export { DurationField };
74
+
75
+ //# sourceMappingURL=DurationField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DurationField.js","names":[],"sources":["../../lib/client/DurationField.tsx"],"sourcesContent":["\"use client\"\n\nimport { TextInput, type TextInputProps, useField } from \"@payloadcms/ui\"\nimport type { Option } from \"@payloadcms/ui/elements/ReactSelect\"\nimport { mergeFieldStyles } from \"@payloadcms/ui/shared\"\nimport type { NumberFieldClientComponent } from \"payload\"\nimport { type ChangeEvent, useCallback, useEffect, useMemo, useState } from \"react\"\nimport { omitUndefined } from \"@cutticat/objects\"\nimport { chipOf, textOfChip } from \"../internal/chips.js\"\nimport { type DurationItem, textsMatch, textsOf, valueOfText } from \"../internal/durations.js\"\n\n/**\n * Form value: milliseconds, an array of them with `hasMany`, or `null` when empty. Text that\n * does not parse stays in it as `{ text }` until the server rejects it.\n */\ntype DurationValue = DurationItem | DurationItem[] | null\n\n/**\n * Admin input of {@link durationField}: Payload's text input over a number field.\n *\n * One value is a text box, `hasMany` is a list of chips. Text that does not parse stays in\n * the input and in the form value, and the field's server validation rejects it.\n *\n * @param props - Payload number field client props.\n * @returns The field.\n */\nexport const DurationField: NumberFieldClientComponent = ({\n field,\n onChange: onChangeFromProps,\n path: pathFromProps,\n readOnly,\n}) => {\n // State\n\n const {\n admin: { className, description, placeholder, readOnly: readOnlyFromConfig } = {},\n hasMany = false,\n label,\n localized,\n required,\n } = field\n const maxRows = \"maxRows\" in field ? field.maxRows : undefined\n\n const {\n customComponents: { AfterInput, BeforeInput, Description, Error: ErrorComponent, Label } = {},\n disabled,\n path,\n setValue,\n showError,\n value,\n } = useField<DurationValue>({ potentiallyStalePath: pathFromProps })\n\n // Payload hands a custom input only the parent's and the access read-only, not `admin.readOnly`\n const isReadOnly = readOnly || disabled || readOnlyFromConfig === true\n\n // What the user sees\n const [texts, setTexts] = useState(() => textsOf(value))\n const style = useMemo(() => mergeFieldStyles(field), [field])\n\n // Effects\n\n // Show a value set elsewhere (load, reset, another tab), but keep what the user is typing\n useEffect(() => {\n setTexts(current => (textsMatch(current, value) ? current : textsOf(value)))\n }, [value])\n\n // Handlers\n\n const handleChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n const next = valueOfText(event.target.value)\n\n setTexts([event.target.value])\n setValue(next)\n\n // Payload types `onChange` for a number only, so empty and unparsed text do not call it\n if (typeof next === \"number\") onChangeFromProps?.(next)\n },\n [onChangeFromProps, setValue]\n )\n\n // Payload's `hasMany` number input does not call `onChange` either\n const handleManyChange = useCallback(\n (selected: Option | Option[] | null) => {\n if (isReadOnly) return\n\n const nextTexts = (Array.isArray(selected) ? selected : selected == null ? [] : [selected])\n .map(textOfChip)\n .filter(text => text.trim() !== \"\")\n\n setTexts(nextTexts)\n setValue(nextTexts.flatMap(text => valueOfText(text) ?? []))\n },\n [isReadOnly, setValue]\n )\n\n // Render\n\n const shared = omitUndefined({\n AfterInput,\n BeforeInput,\n className,\n Description,\n description,\n Error: ErrorComponent,\n Label,\n label,\n localized,\n path,\n // Payload types the number field placeholder loosely; it is a string or a locale map\n placeholder: placeholder as TextInputProps[\"placeholder\"],\n readOnly: isReadOnly,\n required,\n showError,\n style,\n })\n\n if (!hasMany) return <TextInput {...shared} onChange={handleChange} value={texts[0] ?? \"\"} />\n\n return (\n <TextInput\n {...shared}\n hasMany\n {...omitUndefined({ maxRows })}\n onChange={handleManyChange}\n // Payload's input counts `value` against `maxRows`; its type is for a single text\n value={texts as unknown as string}\n valueToRender={texts.map(chipOf)}\n />\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,MAAa,iBAA6C,EACxD,OACA,UAAU,mBACV,MAAM,eACN,eACI;CAGJ,MAAM,EACJ,OAAO,EAAE,WAAW,aAAa,aAAa,UAAU,uBAAuB,CAAC,GAChF,UAAU,OACV,OACA,WACA,aACE;CACJ,MAAM,UAAU,aAAa,QAAQ,MAAM,UAAU,KAAA;CAErD,MAAM,EACJ,kBAAkB,EAAE,YAAY,aAAa,aAAa,OAAO,gBAAgB,UAAU,CAAC,GAC5F,UACA,MACA,UACA,WACA,UACE,SAAwB,EAAE,sBAAsB,cAAc,CAAC;CAGnE,MAAM,aAAa,YAAY,YAAY,uBAAuB;CAGlE,MAAM,CAAC,OAAO,YAAY,eAAe,QAAQ,KAAK,CAAC;CACvD,MAAM,QAAQ,cAAc,iBAAiB,KAAK,GAAG,CAAC,KAAK,CAAC;CAK5D,gBAAgB;EACd,UAAS,YAAY,WAAW,SAAS,KAAK,IAAI,UAAU,QAAQ,KAAK,CAAE;CAC7E,GAAG,CAAC,KAAK,CAAC;CAIV,MAAM,eAAe,aAClB,UAAyC;EACxC,MAAM,OAAO,YAAY,MAAM,OAAO,KAAK;EAE3C,SAAS,CAAC,MAAM,OAAO,KAAK,CAAC;EAC7B,SAAS,IAAI;EAGb,IAAI,OAAO,SAAS,UAAU,oBAAoB,IAAI;CACxD,GACA,CAAC,mBAAmB,QAAQ,CAC9B;CAGA,MAAM,mBAAmB,aACtB,aAAuC;EACtC,IAAI,YAAY;EAEhB,MAAM,aAAa,MAAM,QAAQ,QAAQ,IAAI,WAAW,YAAY,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAA,CACtF,IAAI,UAAU,CAAC,CACf,QAAO,SAAQ,KAAK,KAAK,MAAM,EAAE;EAEpC,SAAS,SAAS;EAClB,SAAS,UAAU,SAAQ,SAAQ,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC;CAC7D,GACA,CAAC,YAAY,QAAQ,CACvB;CAIA,MAAM,SAAS,cAAc;EAC3B;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;EACA;EACA;EACA;EAEa;EACb,UAAU;EACV;EACA;EACA;CACF,CAAC;CAED,IAAI,CAAC,SAAS,OAAO,oBAAC,WAAD;EAAW,GAAI;EAAQ,UAAU;EAAc,OAAO,MAAM,MAAM;CAAK,CAAA;CAE5F,OACE,oBAAC,WAAD;EACE,GAAI;EACJ,SAAA;EACA,GAAI,cAAc,EAAE,QAAQ,CAAC;EAC7B,UAAU;EAEV,OAAO;EACP,eAAe,MAAM,IAAI,MAAM;CAChC,CAAA;AAEL"}
@@ -0,0 +1,3 @@
1
+ import { DurationCell } from "./DurationCell.js";
2
+ import { DurationField } from "./DurationField.js";
3
+ export { DurationCell, DurationField };
@@ -0,0 +1,4 @@
1
+ "use client";
2
+ import { DurationCell } from "./DurationCell.js";
3
+ import { DurationField } from "./DurationField.js";
4
+ export { DurationCell, DurationField };
@@ -0,0 +1,36 @@
1
+ //#region lib/internal/chips.ts
2
+ /**
3
+ * A chip for one text in the shape Payload's text input renders. The index keeps keys unique
4
+ * when two chips read the same.
5
+ *
6
+ * @param text - Chip text.
7
+ * @param index - Position in the list.
8
+ * @returns A react-select option.
9
+ */
10
+ function chipOf(text, index) {
11
+ const key = `${index}:${text}`;
12
+ return {
13
+ id: key,
14
+ label: text,
15
+ value: {
16
+ toString: () => key,
17
+ value: text
18
+ }
19
+ };
20
+ }
21
+ /**
22
+ * Text of a chip. Payload's input hands back chips it rendered as `{ value }` objects, and new
23
+ * or edited chips as plain strings.
24
+ *
25
+ * @param option - Option from the input.
26
+ * @returns The chip text.
27
+ */
28
+ function textOfChip(option) {
29
+ const { value } = option;
30
+ const isWrapped = value != null && typeof value === "object" && "value" in value;
31
+ return String(isWrapped ? value.value : value);
32
+ }
33
+ //#endregion
34
+ export { chipOf, textOfChip };
35
+
36
+ //# sourceMappingURL=chips.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chips.js","names":[],"sources":["../../../lib/internal/chips.ts"],"sourcesContent":["import type { Option } from \"@payloadcms/ui/elements/ReactSelect\"\n\n/**\n * A chip for one text in the shape Payload's text input renders. The index keeps keys unique\n * when two chips read the same.\n *\n * @param text - Chip text.\n * @param index - Position in the list.\n * @returns A react-select option.\n */\nexport function chipOf(text: string, index: number): Option {\n const key = `${index}:${text}`\n return { id: key, label: text, value: { toString: () => key, value: text } }\n}\n\n/**\n * Text of a chip. Payload's input hands back chips it rendered as `{ value }` objects, and new\n * or edited chips as plain strings.\n *\n * @param option - Option from the input.\n * @returns The chip text.\n */\nexport function textOfChip(option: Option): string {\n const { value } = option\n const isWrapped = value != null && typeof value === \"object\" && \"value\" in value\n\n return String(isWrapped ? value.value : value)\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,OAAO,MAAc,OAAuB;CAC1D,MAAM,MAAM,GAAG,MAAM,GAAG;CACxB,OAAO;EAAE,IAAI;EAAK,OAAO;EAAM,OAAO;GAAE,gBAAgB;GAAK,OAAO;EAAK;CAAE;AAC7E;;;;;;;;AASA,SAAgB,WAAW,QAAwB;CACjD,MAAM,EAAE,UAAU;CAClB,MAAM,YAAY,SAAS,QAAQ,OAAO,UAAU,YAAY,WAAW;CAE3E,OAAO,OAAO,YAAY,MAAM,QAAQ,KAAK;AAC/C"}
@@ -0,0 +1,81 @@
1
+ import { ms } from "@cutticat/ms";
2
+ //#region lib/internal/durations.ts
3
+ /**
4
+ * Field value for typed text.
5
+ *
6
+ * @param text - Input text, such as `10d` or `1h 30m`.
7
+ * @returns Whole milliseconds; `null` for empty text; `{ text }` when `@cutticat/ms` cannot
8
+ * parse it.
9
+ */
10
+ function valueOfText(text) {
11
+ if (text.trim() === "") return null;
12
+ try {
13
+ const value = Math.round(ms(text)) || 0;
14
+ return Number.isFinite(value) ? value : { text };
15
+ } catch {
16
+ return { text };
17
+ }
18
+ }
19
+ /**
20
+ * Whether an item is a duration that can be saved and shown.
21
+ *
22
+ * @param item - Any value.
23
+ * @returns `true` for a finite number.
24
+ */
25
+ function isDuration(item) {
26
+ return typeof item === "number" && Number.isFinite(item);
27
+ }
28
+ /**
29
+ * Whether an item is unparsed text.
30
+ *
31
+ * @param item - Any value.
32
+ * @returns `true` for `{ text: string }`.
33
+ */
34
+ function isUnparsed(item) {
35
+ return item != null && typeof item === "object" && "text" in item && typeof item.text === "string";
36
+ }
37
+ /**
38
+ * Items of a field value as a list.
39
+ *
40
+ * @param value - A single value, an array of them with `hasMany`, or empty.
41
+ * @returns Durations and unparsed texts in order; anything else, `NaN` included, is skipped.
42
+ */
43
+ function itemsOf(value) {
44
+ return (Array.isArray(value) ? value : [value]).filter((item) => isDuration(item) || isUnparsed(item));
45
+ }
46
+ /**
47
+ * Texts the input and the list show for a field value.
48
+ *
49
+ * @param value - Field value.
50
+ * @returns Durations in the `@cutticat/ms` short form, and unparsed texts as typed.
51
+ */
52
+ function textsOf(value) {
53
+ return itemsOf(value).map((item) => typeof item === "number" ? ms(item) : item.text);
54
+ }
55
+ /**
56
+ * Whether texts on screen already give a field value, so a re-render does not replace what
57
+ * the user is typing.
58
+ *
59
+ * @param texts - Texts on screen; empty ones are skipped.
60
+ * @param value - Field value.
61
+ * @returns `true` when the texts parse to the same items in the same order.
62
+ */
63
+ function textsMatch(texts, value) {
64
+ const typed = texts.flatMap((text) => valueOfText(text) ?? []);
65
+ const items = itemsOf(value);
66
+ return typed.length === items.length && typed.every((item, index) => sameItem(item, items[index]));
67
+ /**
68
+ * Whether two items are equal: the same number, or the same unparsed text.
69
+ *
70
+ * @param a - First item.
71
+ * @param b - Second item.
72
+ * @returns `true` when equal.
73
+ */
74
+ function sameItem(a, b) {
75
+ return typeof a === "number" ? a === b : isUnparsed(b) && a.text === b.text;
76
+ }
77
+ }
78
+ //#endregion
79
+ export { isDuration, isUnparsed, itemsOf, textsMatch, textsOf, valueOfText };
80
+
81
+ //# sourceMappingURL=durations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"durations.js","names":[],"sources":["../../../lib/internal/durations.ts"],"sourcesContent":["import { ms } from \"@cutticat/ms\"\n\n/**\n * Text the user typed that does not parse. It stays in the form value so the server rejects\n * the save. An object, not a string: Payload turns a string in a single number field into a\n * number with `parseFloat` before validation, so `5 мин` would be saved as `5`.\n */\nexport type UnparsedDuration = { text: string }\n\n/** One item of a duration field value: milliseconds, or unparsed text. */\nexport type DurationItem = number | UnparsedDuration\n\n/**\n * Field value for typed text.\n *\n * @param text - Input text, such as `10d` or `1h 30m`.\n * @returns Whole milliseconds; `null` for empty text; `{ text }` when `@cutticat/ms` cannot\n * parse it.\n */\nexport function valueOfText(text: string): DurationItem | null {\n // `ms` reads blank text as `0`; here it is no value\n if (text.trim() === \"\") return null\n\n try {\n // `ms` keeps a fraction such as `0.5ms`, but formats only whole milliseconds, so the input\n // would show another number after a reload. `|| 0` turns `-0` into `0`\n const value = Math.round(ms(text)) || 0\n\n // Such as `1e400`, which reads as `Infinity`\n return Number.isFinite(value) ? value : { text }\n } catch {\n return { text }\n }\n}\n\n/**\n * Whether an item is a duration that can be saved and shown.\n *\n * @param item - Any value.\n * @returns `true` for a finite number.\n */\nexport function isDuration(item: unknown): item is number {\n return typeof item === \"number\" && Number.isFinite(item)\n}\n\n/**\n * Whether an item is unparsed text.\n *\n * @param item - Any value.\n * @returns `true` for `{ text: string }`.\n */\nexport function isUnparsed(item: unknown): item is UnparsedDuration {\n return item != null && typeof item === \"object\" && \"text\" in item && typeof item.text === \"string\"\n}\n\n/**\n * Items of a field value as a list.\n *\n * @param value - A single value, an array of them with `hasMany`, or empty.\n * @returns Durations and unparsed texts in order; anything else, `NaN` included, is skipped.\n */\nexport function itemsOf(value: unknown): DurationItem[] {\n return (Array.isArray(value) ? value : [value]).filter(\n item => isDuration(item) || isUnparsed(item)\n )\n}\n\n/**\n * Texts the input and the list show for a field value.\n *\n * @param value - Field value.\n * @returns Durations in the `@cutticat/ms` short form, and unparsed texts as typed.\n */\nexport function textsOf(value: unknown): string[] {\n return itemsOf(value).map(item => (typeof item === \"number\" ? ms(item) : item.text))\n}\n\n/**\n * Whether texts on screen already give a field value, so a re-render does not replace what\n * the user is typing.\n *\n * @param texts - Texts on screen; empty ones are skipped.\n * @param value - Field value.\n * @returns `true` when the texts parse to the same items in the same order.\n */\nexport function textsMatch(texts: readonly string[], value: unknown): boolean {\n const typed = texts.flatMap(text => valueOfText(text) ?? [])\n const items = itemsOf(value)\n\n return typed.length === items.length && typed.every((item, index) => sameItem(item, items[index]))\n\n // Helpers\n\n /**\n * Whether two items are equal: the same number, or the same unparsed text.\n *\n * @param a - First item.\n * @param b - Second item.\n * @returns `true` when equal.\n */\n function sameItem(a: DurationItem, b: DurationItem | undefined): boolean {\n return typeof a === \"number\" ? a === b : isUnparsed(b) && a.text === b.text\n }\n}\n"],"mappings":";;;;;;;;;AAmBA,SAAgB,YAAY,MAAmC;CAE7D,IAAI,KAAK,KAAK,MAAM,IAAI,OAAO;CAE/B,IAAI;EAGF,MAAM,QAAQ,KAAK,MAAM,GAAG,IAAI,CAAC,KAAK;EAGtC,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,EAAE,KAAK;CACjD,QAAQ;EACN,OAAO,EAAE,KAAK;CAChB;AACF;;;;;;;AAQA,SAAgB,WAAW,MAA+B;CACxD,OAAO,OAAO,SAAS,YAAY,OAAO,SAAS,IAAI;AACzD;;;;;;;AAQA,SAAgB,WAAW,MAAyC;CAClE,OAAO,QAAQ,QAAQ,OAAO,SAAS,YAAY,UAAU,QAAQ,OAAO,KAAK,SAAS;AAC5F;;;;;;;AAQA,SAAgB,QAAQ,OAAgC;CACtD,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,EAAA,CAAG,QAC9C,SAAQ,WAAW,IAAI,KAAK,WAAW,IAAI,CAC7C;AACF;;;;;;;AAQA,SAAgB,QAAQ,OAA0B;CAChD,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAI,SAAS,OAAO,SAAS,WAAW,GAAG,IAAI,IAAI,KAAK,IAAK;AACrF;;;;;;;;;AAUA,SAAgB,WAAW,OAA0B,OAAyB;CAC5E,MAAM,QAAQ,MAAM,SAAQ,SAAQ,YAAY,IAAI,KAAK,CAAC,CAAC;CAC3D,MAAM,QAAQ,QAAQ,KAAK;CAE3B,OAAO,MAAM,WAAW,MAAM,UAAU,MAAM,OAAO,MAAM,UAAU,SAAS,MAAM,MAAM,MAAM,CAAC;;;;;;;;CAWjG,SAAS,SAAS,GAAiB,GAAsC;EACvE,OAAO,OAAO,MAAM,WAAW,MAAM,IAAI,WAAW,CAAC,KAAK,EAAE,SAAS,EAAE;CACzE;AACF"}
@@ -0,0 +1,36 @@
1
+ import { NumberField } from "payload";
2
+ import { DistributiveOmit, FullyUndefinable } from "@cutticat/types";
3
+ //#region lib/field.d.ts
4
+ /**
5
+ * Options of {@link durationField}: a Payload `number` field config without `type`.
6
+ *
7
+ * `min` defaults to `0`. `min: null` allows negative durations.
8
+ */
9
+ export type DurationFieldOptions = DistributiveOmit<NumberField, "type" | "min" | "max"> & FullyUndefinable<{
10
+ /** Smallest allowed value in milliseconds, `null` for no bound. Defaults to `0`. */
11
+ min: number | null;
12
+ /** Largest allowed value in milliseconds, `null` for no bound. Defaults to `null`. */
13
+ max: number | null;
14
+ }>;
15
+ /**
16
+ * Builds a Payload `number` field edited as an `@cutticat/ms` duration.
17
+ *
18
+ * The database stores milliseconds, or an array of them with `hasMany`. The admin input
19
+ * accepts strings such as `10d` or `1h 30m`, and the list view shows the same format.
20
+ *
21
+ * Validation runs on the server. Text that does not parse is rejected with Payload's
22
+ * `validation:invalidInput`; `min` and `max` with Payload's own messages, the numbers shown as
23
+ * durations. Then Payload's number validation, or `validate` from the options, checks the rest.
24
+ * A draft save that Payload does not validate drops unparsed text instead.
25
+ *
26
+ * @param options - Number field config; `min` defaults to `0`.
27
+ * @returns A number field with the duration input, list cell, and validation.
28
+ * @example
29
+ * ```typescript
30
+ * durationField({ name: "timeoutMs", required: true })
31
+ * durationField({ name: "offsetMs", min: null })
32
+ * ```
33
+ */
34
+ export declare function durationField({ admin, hooks, max, min, validate, ...field }: Readonly<DurationFieldOptions>): NumberField;
35
+ //#endregion
36
+ //# sourceMappingURL=field.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field.d.ts","names":[],"sources":["../../lib/field.ts"],"mappings":";;;;;;;;YAkBY,uBAAuB,iBAAiB,uCAClD;;EAEE;;EAEA;;;;;;;;;;;;;;;;;;;;;wBAsBY,gBACd,OACA,OACA,KACA,KACA,aACG,SAGF,SAAS,wBAAwB"}
@@ -0,0 +1,53 @@
1
+ import { createDurationValidation, dropUnparsedFromDraft } from "./validation.js";
2
+ //#region lib/field.ts
3
+ /** Import-map path of the admin input. */
4
+ const fieldComponent = "@cutticat/payload-field-ms/client#DurationField";
5
+ /** Import-map path of the list-view cell. */
6
+ const cellComponent = "@cutticat/payload-field-ms/client#DurationCell";
7
+ /** Shown in an empty input when the config sets no placeholder. */
8
+ const defaultPlaceholder = "10d";
9
+ /**
10
+ * Builds a Payload `number` field edited as an `@cutticat/ms` duration.
11
+ *
12
+ * The database stores milliseconds, or an array of them with `hasMany`. The admin input
13
+ * accepts strings such as `10d` or `1h 30m`, and the list view shows the same format.
14
+ *
15
+ * Validation runs on the server. Text that does not parse is rejected with Payload's
16
+ * `validation:invalidInput`; `min` and `max` with Payload's own messages, the numbers shown as
17
+ * durations. Then Payload's number validation, or `validate` from the options, checks the rest.
18
+ * A draft save that Payload does not validate drops unparsed text instead.
19
+ *
20
+ * @param options - Number field config; `min` defaults to `0`.
21
+ * @returns A number field with the duration input, list cell, and validation.
22
+ * @example
23
+ * ```typescript
24
+ * durationField({ name: "timeoutMs", required: true })
25
+ * durationField({ name: "offsetMs", min: null })
26
+ * ```
27
+ */
28
+ function durationField({ admin, hooks, max = null, min = 0, validate, ...field }) {
29
+ return {
30
+ ...field,
31
+ ...min == null ? {} : { min },
32
+ ...max == null ? {} : { max },
33
+ type: "number",
34
+ validate: createDurationValidation({ validate: validate ?? null }),
35
+ hooks: {
36
+ ...hooks,
37
+ beforeChange: [dropUnparsedFromDraft, ...hooks?.beforeChange ?? []]
38
+ },
39
+ admin: {
40
+ ...admin,
41
+ placeholder: admin?.placeholder ?? defaultPlaceholder,
42
+ components: {
43
+ ...admin?.components,
44
+ Cell: cellComponent,
45
+ Field: fieldComponent
46
+ }
47
+ }
48
+ };
49
+ }
50
+ //#endregion
51
+ export { durationField };
52
+
53
+ //# sourceMappingURL=field.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field.js","names":[],"sources":["../../lib/field.ts"],"sourcesContent":["import type { NumberField, NumberFieldValidation } from \"payload\"\nimport type { DistributiveOmit, FullyUndefinable } from \"@cutticat/types\"\nimport { createDurationValidation, dropUnparsedFromDraft } from \"./validation.js\"\n\n/** Import-map path of the admin input. */\nconst fieldComponent = \"@cutticat/payload-field-ms/client#DurationField\"\n\n/** Import-map path of the list-view cell. */\nconst cellComponent = \"@cutticat/payload-field-ms/client#DurationCell\"\n\n/** Shown in an empty input when the config sets no placeholder. */\nconst defaultPlaceholder = \"10d\"\n\n/**\n * Options of {@link durationField}: a Payload `number` field config without `type`.\n *\n * `min` defaults to `0`. `min: null` allows negative durations.\n */\nexport type DurationFieldOptions = DistributiveOmit<NumberField, \"type\" | \"min\" | \"max\"> &\n FullyUndefinable<{\n /** Smallest allowed value in milliseconds, `null` for no bound. Defaults to `0`. */\n min: number | null\n /** Largest allowed value in milliseconds, `null` for no bound. Defaults to `null`. */\n max: number | null\n }>\n\n/**\n * Builds a Payload `number` field edited as an `@cutticat/ms` duration.\n *\n * The database stores milliseconds, or an array of them with `hasMany`. The admin input\n * accepts strings such as `10d` or `1h 30m`, and the list view shows the same format.\n *\n * Validation runs on the server. Text that does not parse is rejected with Payload's\n * `validation:invalidInput`; `min` and `max` with Payload's own messages, the numbers shown as\n * durations. Then Payload's number validation, or `validate` from the options, checks the rest.\n * A draft save that Payload does not validate drops unparsed text instead.\n *\n * @param options - Number field config; `min` defaults to `0`.\n * @returns A number field with the duration input, list cell, and validation.\n * @example\n * ```typescript\n * durationField({ name: \"timeoutMs\", required: true })\n * durationField({ name: \"offsetMs\", min: null })\n * ```\n */\nexport function durationField({\n admin,\n hooks,\n max = null,\n min = 0,\n validate,\n ...field\n // Readonly, not DeepReadonly: on Payload's field config type it exceeds TypeScript's\n // instantiation depth\n}: Readonly<DurationFieldOptions>): NumberField {\n return {\n ...field,\n ...(min == null ? {} : { min }),\n ...(max == null ? {} : { max }),\n type: \"number\",\n validate: createDurationValidation({\n // `validate` is typed for one `hasMany` variant; the value always matches the field's own\n validate: (validate as NumberFieldValidation | undefined) ?? null,\n }),\n hooks: {\n ...hooks,\n beforeChange: [dropUnparsedFromDraft, ...(hooks?.beforeChange ?? [])],\n },\n admin: {\n ...admin,\n placeholder: admin?.placeholder ?? defaultPlaceholder,\n components: {\n ...admin?.components,\n Cell: cellComponent,\n Field: fieldComponent,\n },\n },\n }\n}\n"],"mappings":";;;AAKA,MAAM,iBAAiB;;AAGvB,MAAM,gBAAgB;;AAGtB,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;AAkC3B,SAAgB,cAAc,EAC5B,OACA,OACA,MAAM,MACN,MAAM,GACN,UACA,GAAG,SAG2C;CAC9C,OAAO;EACL,GAAG;EACH,GAAI,OAAO,OAAO,CAAC,IAAI,EAAE,IAAI;EAC7B,GAAI,OAAO,OAAO,CAAC,IAAI,EAAE,IAAI;EAC7B,MAAM;EACN,UAAU,yBAAyB,EAEjC,UAAW,YAAkD,KAC/D,CAAC;EACD,OAAO;GACL,GAAG;GACH,cAAc,CAAC,uBAAuB,GAAI,OAAO,gBAAgB,CAAC,CAAE;EACtE;EACA,OAAO;GACL,GAAG;GACH,aAAa,OAAO,eAAe;GACnC,YAAY;IACV,GAAG,OAAO;IACV,MAAM;IACN,OAAO;GACT;EACF;CACF;AACF"}
@@ -0,0 +1,3 @@
1
+ import { DurationFieldOptions, durationField } from "./field.js";
2
+ import { CreateDurationValidationOptions, createDurationValidation, dropUnparsedFromDraft } from "./validation.js";
3
+ export { CreateDurationValidationOptions, DurationFieldOptions, createDurationValidation, dropUnparsedFromDraft, durationField };
@@ -0,0 +1,3 @@
1
+ import { createDurationValidation, dropUnparsedFromDraft } from "./validation.js";
2
+ import { durationField } from "./field.js";
3
+ export { createDurationValidation, dropUnparsedFromDraft, durationField };
@@ -0,0 +1,15 @@
1
+ import "@cutticat/ms";
2
+ //#region lib/internal/durations.ts
3
+ /**
4
+ * Whether an item is a duration that can be saved and shown.
5
+ *
6
+ * @param item - Any value.
7
+ * @returns `true` for a finite number.
8
+ */
9
+ function isDuration(item) {
10
+ return typeof item === "number" && Number.isFinite(item);
11
+ }
12
+ //#endregion
13
+ export { isDuration };
14
+
15
+ //# sourceMappingURL=durations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"durations.js","names":[],"sources":["../../../lib/internal/durations.ts"],"sourcesContent":["import { ms } from \"@cutticat/ms\"\n\n/**\n * Text the user typed that does not parse. It stays in the form value so the server rejects\n * the save. An object, not a string: Payload turns a string in a single number field into a\n * number with `parseFloat` before validation, so `5 мин` would be saved as `5`.\n */\nexport type UnparsedDuration = { text: string }\n\n/** One item of a duration field value: milliseconds, or unparsed text. */\nexport type DurationItem = number | UnparsedDuration\n\n/**\n * Field value for typed text.\n *\n * @param text - Input text, such as `10d` or `1h 30m`.\n * @returns Whole milliseconds; `null` for empty text; `{ text }` when `@cutticat/ms` cannot\n * parse it.\n */\nexport function valueOfText(text: string): DurationItem | null {\n // `ms` reads blank text as `0`; here it is no value\n if (text.trim() === \"\") return null\n\n try {\n // `ms` keeps a fraction such as `0.5ms`, but formats only whole milliseconds, so the input\n // would show another number after a reload. `|| 0` turns `-0` into `0`\n const value = Math.round(ms(text)) || 0\n\n // Such as `1e400`, which reads as `Infinity`\n return Number.isFinite(value) ? value : { text }\n } catch {\n return { text }\n }\n}\n\n/**\n * Whether an item is a duration that can be saved and shown.\n *\n * @param item - Any value.\n * @returns `true` for a finite number.\n */\nexport function isDuration(item: unknown): item is number {\n return typeof item === \"number\" && Number.isFinite(item)\n}\n\n/**\n * Whether an item is unparsed text.\n *\n * @param item - Any value.\n * @returns `true` for `{ text: string }`.\n */\nexport function isUnparsed(item: unknown): item is UnparsedDuration {\n return item != null && typeof item === \"object\" && \"text\" in item && typeof item.text === \"string\"\n}\n\n/**\n * Items of a field value as a list.\n *\n * @param value - A single value, an array of them with `hasMany`, or empty.\n * @returns Durations and unparsed texts in order; anything else, `NaN` included, is skipped.\n */\nexport function itemsOf(value: unknown): DurationItem[] {\n return (Array.isArray(value) ? value : [value]).filter(\n item => isDuration(item) || isUnparsed(item)\n )\n}\n\n/**\n * Texts the input and the list show for a field value.\n *\n * @param value - Field value.\n * @returns Durations in the `@cutticat/ms` short form, and unparsed texts as typed.\n */\nexport function textsOf(value: unknown): string[] {\n return itemsOf(value).map(item => (typeof item === \"number\" ? ms(item) : item.text))\n}\n\n/**\n * Whether texts on screen already give a field value, so a re-render does not replace what\n * the user is typing.\n *\n * @param texts - Texts on screen; empty ones are skipped.\n * @param value - Field value.\n * @returns `true` when the texts parse to the same items in the same order.\n */\nexport function textsMatch(texts: readonly string[], value: unknown): boolean {\n const typed = texts.flatMap(text => valueOfText(text) ?? [])\n const items = itemsOf(value)\n\n return typed.length === items.length && typed.every((item, index) => sameItem(item, items[index]))\n\n // Helpers\n\n /**\n * Whether two items are equal: the same number, or the same unparsed text.\n *\n * @param a - First item.\n * @param b - Second item.\n * @returns `true` when equal.\n */\n function sameItem(a: DurationItem, b: DurationItem | undefined): boolean {\n return typeof a === \"number\" ? a === b : isUnparsed(b) && a.text === b.text\n }\n}\n"],"mappings":";;;;;;;;AAyCA,SAAgB,WAAW,MAA+B;CACxD,OAAO,OAAO,SAAS,YAAY,OAAO,SAAS,IAAI;AACzD"}
@@ -0,0 +1,48 @@
1
+ import { FieldHookArgs, NumberFieldValidation } from "payload";
2
+ import { FullyUndefinable } from "@cutticat/types";
3
+ //#region lib/validation.d.ts
4
+ /** Options of {@link createDurationValidation}. */
5
+ export type CreateDurationValidationOptions = FullyUndefinable<{
6
+ /**
7
+ * Validation to run after the duration checks, `null` for Payload's number validation.
8
+ * Defaults to `null`.
9
+ */
10
+ validate: NumberFieldValidation | null;
11
+ }>;
12
+ /**
13
+ * Validation of a duration field: what {@link durationField} sets as `validate`. Checks every
14
+ * item of the value against the field's `min` and `max`, then hands over to the number
15
+ * validation. Use it for a number field built by hand with the duration input, together with
16
+ * {@link dropUnparsedFromDraft}.
17
+ *
18
+ * An item that is not a finite number, such as text that did not parse, is rejected with
19
+ * Payload's `validation:invalidInput`; `min` and `max` with Payload's own messages, the numbers
20
+ * shown as durations.
21
+ *
22
+ * @param options - The validation to run next.
23
+ * @returns A Payload number field validation.
24
+ * @example
25
+ * ```typescript
26
+ * const field: NumberField = {
27
+ * name: "timeoutMs",
28
+ * type: "number",
29
+ * min: 0,
30
+ * validate: createDurationValidation(),
31
+ * hooks: { beforeChange: [dropUnparsedFromDraft] },
32
+ * admin: { components: { Field: "@cutticat/payload-field-ms/client#DurationField" } },
33
+ * }
34
+ * ```
35
+ */
36
+ export declare function createDurationValidation({ validate }?: Readonly<CreateDurationValidationOptions>): NumberFieldValidation;
37
+ /**
38
+ * `beforeChange` hook that keeps unparsed text out of the database on a draft save that Payload
39
+ * does not validate: the item is dropped, a single value keeps what was saved before. With
40
+ * `versions.drafts.validate` the hook leaves the value to the validation. {@link durationField}
41
+ * adds it; a field built by hand with the duration input needs it too.
42
+ *
43
+ * @param args - Payload field hook arguments.
44
+ * @returns The value to save.
45
+ */
46
+ export declare function dropUnparsedFromDraft({ collection, data, global, previousValue, value }: FieldHookArgs): unknown;
47
+ //#endregion
48
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","names":[],"sources":["../../lib/validation.ts"],"mappings":";;;;YAMY,kCAAkC;;;;;EAK5C,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;wBA2BI,2BACd,aACC,SAAS,mCAAwC;;;;;;;;;;wBAqDpC,wBACd,YACA,MACA,QACA,eACA,SACC"}
@@ -0,0 +1,86 @@
1
+ import { isDuration } from "./internal/durations.js";
2
+ import { validations } from "payload";
3
+ import { ms } from "@cutticat/ms";
4
+ //#region lib/validation.ts
5
+ /**
6
+ * Validation of a duration field: what {@link durationField} sets as `validate`. Checks every
7
+ * item of the value against the field's `min` and `max`, then hands over to the number
8
+ * validation. Use it for a number field built by hand with the duration input, together with
9
+ * {@link dropUnparsedFromDraft}.
10
+ *
11
+ * An item that is not a finite number, such as text that did not parse, is rejected with
12
+ * Payload's `validation:invalidInput`; `min` and `max` with Payload's own messages, the numbers
13
+ * shown as durations.
14
+ *
15
+ * @param options - The validation to run next.
16
+ * @returns A Payload number field validation.
17
+ * @example
18
+ * ```typescript
19
+ * const field: NumberField = {
20
+ * name: "timeoutMs",
21
+ * type: "number",
22
+ * min: 0,
23
+ * validate: createDurationValidation(),
24
+ * hooks: { beforeChange: [dropUnparsedFromDraft] },
25
+ * admin: { components: { Field: "@cutticat/payload-field-ms/client#DurationField" } },
26
+ * }
27
+ * ```
28
+ */
29
+ function createDurationValidation({ validate = null } = {}) {
30
+ return (value, args) => {
31
+ const { max, min, req: { t } } = args;
32
+ const label = t("general:value");
33
+ for (const item of itemsToCheck(value)) {
34
+ if (!isDuration(item)) return t("validation:invalidInput");
35
+ if (typeof min === "number" && item < min) return t("validation:lessThanMin", {
36
+ label,
37
+ min: ms(min),
38
+ value: ms(item)
39
+ });
40
+ if (typeof max === "number" && item > max) return t("validation:greaterThanMax", {
41
+ label,
42
+ max: ms(max),
43
+ value: ms(item)
44
+ });
45
+ }
46
+ return (validate ?? validations.number)(value, args);
47
+ };
48
+ /**
49
+ * Items of a value as Payload hands it over, unparsed and malformed ones included.
50
+ *
51
+ * @param value - A single value, an array of them with `hasMany`, or empty.
52
+ * @returns The items to check.
53
+ */
54
+ function itemsToCheck(value) {
55
+ if (Array.isArray(value)) return value;
56
+ return value == null ? [] : [value];
57
+ }
58
+ }
59
+ /**
60
+ * `beforeChange` hook that keeps unparsed text out of the database on a draft save that Payload
61
+ * does not validate: the item is dropped, a single value keeps what was saved before. With
62
+ * `versions.drafts.validate` the hook leaves the value to the validation. {@link durationField}
63
+ * adds it; a field built by hand with the duration input needs it too.
64
+ *
65
+ * @param args - Payload field hook arguments.
66
+ * @returns The value to save.
67
+ */
68
+ function dropUnparsedFromDraft({ collection, data, global, previousValue, value }) {
69
+ if (data?._status !== "draft" || validatesDrafts()) return value;
70
+ if (Array.isArray(value)) return value.filter(isDuration);
71
+ return value == null || isDuration(value) ? value : previousValue ?? null;
72
+ /**
73
+ * Whether Payload validates a draft save of this document, as `versions.drafts.validate` sets.
74
+ *
75
+ * @returns `true` when draft saves are validated.
76
+ */
77
+ function validatesDrafts() {
78
+ const versions = (collection ?? global)?.versions;
79
+ const drafts = typeof versions === "object" ? versions.drafts : void 0;
80
+ return typeof drafts === "object" && drafts.validate === true;
81
+ }
82
+ }
83
+ //#endregion
84
+ export { createDurationValidation, dropUnparsedFromDraft };
85
+
86
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","names":[],"sources":["../../lib/validation.ts"],"sourcesContent":["import { type FieldHookArgs, type NumberFieldValidation, validations } from \"payload\"\nimport { ms } from \"@cutticat/ms\"\nimport type { FullyUndefinable } from \"@cutticat/types\"\nimport { isDuration } from \"./internal/durations.js\"\n\n/** Options of {@link createDurationValidation}. */\nexport type CreateDurationValidationOptions = FullyUndefinable<{\n /**\n * Validation to run after the duration checks, `null` for Payload's number validation.\n * Defaults to `null`.\n */\n validate: NumberFieldValidation | null\n}>\n\n/**\n * Validation of a duration field: what {@link durationField} sets as `validate`. Checks every\n * item of the value against the field's `min` and `max`, then hands over to the number\n * validation. Use it for a number field built by hand with the duration input, together with\n * {@link dropUnparsedFromDraft}.\n *\n * An item that is not a finite number, such as text that did not parse, is rejected with\n * Payload's `validation:invalidInput`; `min` and `max` with Payload's own messages, the numbers\n * shown as durations.\n *\n * @param options - The validation to run next.\n * @returns A Payload number field validation.\n * @example\n * ```typescript\n * const field: NumberField = {\n * name: \"timeoutMs\",\n * type: \"number\",\n * min: 0,\n * validate: createDurationValidation(),\n * hooks: { beforeChange: [dropUnparsedFromDraft] },\n * admin: { components: { Field: \"@cutticat/payload-field-ms/client#DurationField\" } },\n * }\n * ```\n */\nexport function createDurationValidation({\n validate = null,\n}: Readonly<CreateDurationValidationOptions> = {}): NumberFieldValidation {\n return (value, args) => {\n // Payload passes the field config in the arguments\n const {\n max,\n min,\n req: { t },\n } = args\n const label = t(\"general:value\")\n\n for (const item of itemsToCheck(value)) {\n if (!isDuration(item)) {\n return t(\"validation:invalidInput\")\n }\n\n if (typeof min === \"number\" && item < min) {\n return t(\"validation:lessThanMin\", { label, min: ms(min), value: ms(item) })\n }\n\n if (typeof max === \"number\" && item > max) {\n return t(\"validation:greaterThanMax\", { label, max: ms(max), value: ms(item) })\n }\n }\n\n const next = validate ?? (validations.number as NumberFieldValidation)\n\n return next(value, args)\n }\n\n // Helpers\n\n /**\n * Items of a value as Payload hands it over, unparsed and malformed ones included.\n *\n * @param value - A single value, an array of them with `hasMany`, or empty.\n * @returns The items to check.\n */\n function itemsToCheck(value: unknown): unknown[] {\n if (Array.isArray(value)) return value\n\n return value == null ? [] : [value]\n }\n}\n\n/**\n * `beforeChange` hook that keeps unparsed text out of the database on a draft save that Payload\n * does not validate: the item is dropped, a single value keeps what was saved before. With\n * `versions.drafts.validate` the hook leaves the value to the validation. {@link durationField}\n * adds it; a field built by hand with the duration input needs it too.\n *\n * @param args - Payload field hook arguments.\n * @returns The value to save.\n */\nexport function dropUnparsedFromDraft({\n collection,\n data,\n global,\n previousValue,\n value,\n}: FieldHookArgs): unknown {\n if (data?._status !== \"draft\" || validatesDrafts()) return value\n if (Array.isArray(value)) return value.filter(isDuration)\n\n return value == null || isDuration(value) ? value : (previousValue ?? null)\n\n // Helpers\n\n /**\n * Whether Payload validates a draft save of this document, as `versions.drafts.validate` sets.\n *\n * @returns `true` when draft saves are validated.\n */\n function validatesDrafts(): boolean {\n const versions = (collection ?? global)?.versions\n const drafts = typeof versions === \"object\" ? versions.drafts : undefined\n\n return typeof drafts === \"object\" && drafts.validate === true\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,yBAAyB,EACvC,WAAW,SACkC,CAAC,GAA0B;CACxE,QAAQ,OAAO,SAAS;EAEtB,MAAM,EACJ,KACA,KACA,KAAK,EAAE,QACL;EACJ,MAAM,QAAQ,EAAE,eAAe;EAE/B,KAAK,MAAM,QAAQ,aAAa,KAAK,GAAG;GACtC,IAAI,CAAC,WAAW,IAAI,GAClB,OAAO,EAAE,yBAAyB;GAGpC,IAAI,OAAO,QAAQ,YAAY,OAAO,KACpC,OAAO,EAAE,0BAA0B;IAAE;IAAO,KAAK,GAAG,GAAG;IAAG,OAAO,GAAG,IAAI;GAAE,CAAC;GAG7E,IAAI,OAAO,QAAQ,YAAY,OAAO,KACpC,OAAO,EAAE,6BAA6B;IAAE;IAAO,KAAK,GAAG,GAAG;IAAG,OAAO,GAAG,IAAI;GAAE,CAAC;EAElF;EAIA,QAFa,YAAa,YAAY,OAAA,CAE1B,OAAO,IAAI;CACzB;;;;;;;CAUA,SAAS,aAAa,OAA2B;EAC/C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;EAEjC,OAAO,SAAS,OAAO,CAAC,IAAI,CAAC,KAAK;CACpC;AACF;;;;;;;;;;AAWA,SAAgB,sBAAsB,EACpC,YACA,MACA,QACA,eACA,SACyB;CACzB,IAAI,MAAM,YAAY,WAAW,gBAAgB,GAAG,OAAO;CAC3D,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,OAAO,UAAU;CAExD,OAAO,SAAS,QAAQ,WAAW,KAAK,IAAI,QAAS,iBAAiB;;;;;;CAStE,SAAS,kBAA2B;EAClC,MAAM,YAAY,cAAc,OAAA,EAAS;EACzC,MAAM,SAAS,OAAO,aAAa,WAAW,SAAS,SAAS,KAAA;EAEhE,OAAO,OAAO,WAAW,YAAY,OAAO,aAAa;CAC3D;AACF"}
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "@cutticat/payload-field-ms",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "publishConfig": {
4
+ "access": "public"
5
+ },
6
+ "version": "1.0.0",
7
+ "description": "Payload number field that edits a duration with @cutticat/ms",
8
+ "author": "Maksim Victorovich Fomin",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://gitflic.ru/project/cutticat-npm/payload-field-ms"
12
+ },
13
+ "homepage": "https://cutticat.com",
14
+ "keywords": [
15
+ "payload",
16
+ "payloadcms",
17
+ "field",
18
+ "duration",
19
+ "milliseconds",
20
+ "cutticat"
21
+ ],
22
+ "type": "module",
23
+ "engines": {
24
+ "node": ">=22.18.0"
25
+ },
26
+ "dependencies": {
27
+ "@cutticat/ms": "^1.1.0",
28
+ "@cutticat/objects": "^4.1.0",
29
+ "@cutticat/types": "^2.1.0"
30
+ },
31
+ "devDependencies": {
32
+ "@biomejs/biome": "2.4.6",
33
+ "@cutticat/md-url-map": "^2.0.0",
34
+ "@payloadcms/ui": "3.88.0",
35
+ "@types/node": "^25.0.3",
36
+ "@types/react": "^19.2.14",
37
+ "payload": "3.88.0",
38
+ "react": "19.2.6",
39
+ "react-dom": "19.2.6",
40
+ "rimraf": "^6.1.0",
41
+ "tsdown": "0.23.0",
42
+ "tsx": "^4.19.2",
43
+ "typescript": "^5.9.3"
44
+ },
45
+ "peerDependencies": {
46
+ "@payloadcms/ui": ">=3.80.0 <4.0.0",
47
+ "payload": ">=3.80.0 <4.0.0",
48
+ "react": ">=19.0.0",
49
+ "react-dom": ">=19.0.0"
50
+ },
51
+ "exports": {
52
+ ".": {
53
+ "types": "./dist/field/index.d.ts",
54
+ "import": "./dist/field/index.js",
55
+ "default": "./dist/field/index.js"
56
+ },
57
+ "./client": {
58
+ "types": "./dist/client/index.d.ts",
59
+ "import": "./dist/client/index.js",
60
+ "default": "./dist/client/index.js"
61
+ }
62
+ },
63
+ "files": [
64
+ "dist/**/*"
65
+ ],
66
+ "license": "MIT",
67
+ "scripts": {
68
+ "lint": "biome check .",
69
+ "lint:fix": "biome check --write .",
70
+ "lint:fix:unsafe": "biome check --write --unsafe .",
71
+ "format": "biome format --write .",
72
+ "format:check": "biome format .",
73
+ "clean": "rimraf ./dist",
74
+ "build": "tsc --noEmit -p ./tsconfig.build.json && tsdown",
75
+ "test": "tsx --test \"./tests/**/*.test.ts\"",
76
+ "test:watch": "tsx --test --watch \"./tests/**/*.test.ts\"",
77
+ "test:coverage": "tsx --test --experimental-test-coverage \"./tests/**/*.test.ts\""
78
+ }
6
79
  }