sanity-plugin-variant-picker 0.1.0 → 0.2.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/README.md +29 -0
- package/dist/index.d.ts +22 -2
- package/dist/index.js +29 -7
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,6 +7,7 @@ A Sanity Studio `string` field built like a link picker: one input and a popover
|
|
|
7
7
|
- **Search**: type to filter by title or value; Enter picks the first match.
|
|
8
8
|
- **Picked value**: shown as a native preview row with a pencil on the right that clears it and reopens the search, like sanity-plugin-color-select.
|
|
9
9
|
- **A plain string value**: stores the picked item's `value`, the same as a native string select.
|
|
10
|
+
- **Existing fields too**: `stringLists: true` puts the picker on every `string` field with an `options.list`, with no schema changes.
|
|
10
11
|
|
|
11
12
|
## Install
|
|
12
13
|
|
|
@@ -50,6 +51,34 @@ defineField({
|
|
|
50
51
|
|
|
51
52
|
`icon` takes a component (e.g. from `@sanity/icons`), an element, or an emoji string. Set a field's placeholder with `options.placeholder` (default "Search a variant"): Sanity drops a field-level `placeholder` on types that extend `string`. Items without a `value` are skipped.
|
|
52
53
|
|
|
54
|
+
## Existing string fields
|
|
55
|
+
|
|
56
|
+
To use the picker on the `string` fields you already have, turn on `stringLists`:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
plugins: [variantPicker({stringLists: true})]
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Every `string` field with a non-empty `options.list` then gets the picker, with no schema changes. The field keeps `type: 'string'`, so `sanity typegen` still generates its literal union (`'sm' | 'md'`). With `type: 'variantPicker'` it generates `string`. Stored values don't change.
|
|
63
|
+
|
|
64
|
+
It skips:
|
|
65
|
+
|
|
66
|
+
- **Radio groups** (`options.layout: 'radio'`): every option is visible and one click away, so they stay native. Set `layout: 'dropdown'` (or drop `layout`) to switch one over.
|
|
67
|
+
- **Fields with their own input** (`components.input`, on the field or on a type it extends): those always win.
|
|
68
|
+
|
|
69
|
+
For a single field instead, keep `type: 'string'` and set the input yourself:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import {VariantPickerInput} from 'sanity-plugin-variant-picker'
|
|
73
|
+
|
|
74
|
+
defineField({
|
|
75
|
+
name: 'size',
|
|
76
|
+
type: 'string',
|
|
77
|
+
options: {list: ['small', 'large']},
|
|
78
|
+
components: {input: VariantPickerInput},
|
|
79
|
+
})
|
|
80
|
+
```
|
|
81
|
+
|
|
53
82
|
## Stored value
|
|
54
83
|
|
|
55
84
|
The picked item's `value`, as a string:
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import {Plugin as Plugin_2} from 'sanity'
|
|
2
2
|
import {default as React_2} from 'react'
|
|
3
|
+
import type {SchemaType} from 'sanity'
|
|
3
4
|
import {StringInputProps} from 'sanity'
|
|
4
5
|
import type {StringOptions} from 'sanity'
|
|
5
6
|
|
|
6
7
|
/** Case-insensitive match on the title or the value. */
|
|
7
8
|
export declare function filterItems(items: VariantItem[], query: string): VariantItem[]
|
|
8
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Whether `stringLists` takes over a field: a `string` with a non-empty `options.list` that isn't
|
|
12
|
+
* a radio group and doesn't set its own input. Radios stay native (every option visible, one
|
|
13
|
+
* click), and a field's own `components.input` always wins.
|
|
14
|
+
*/
|
|
15
|
+
export declare function isPickableStringList(schemaType: SchemaType): boolean
|
|
16
|
+
|
|
9
17
|
/**
|
|
10
18
|
* Reads `options.list` the way Sanity's native string select does: `{title, value}` items are
|
|
11
19
|
* kept, plain strings become `{title: Capitalized, value}`. Items without a value are skipped.
|
|
@@ -23,7 +31,8 @@ export declare type VariantItem = {
|
|
|
23
31
|
/**
|
|
24
32
|
* Registers a `variantPicker` field type: a native `string` with a searchable popover input.
|
|
25
33
|
* It reads `options.list` exactly like a string field (`{title, value}` items or plain strings)
|
|
26
|
-
* and stores the picked item's `value`.
|
|
34
|
+
* and stores the picked item's `value`. With `stringLists: true`, plain `string` list fields get
|
|
35
|
+
* the same input.
|
|
27
36
|
*
|
|
28
37
|
* @example
|
|
29
38
|
* ```ts
|
|
@@ -38,7 +47,18 @@ export declare type VariantItem = {
|
|
|
38
47
|
* })
|
|
39
48
|
* ```
|
|
40
49
|
*/
|
|
41
|
-
export declare const variantPicker: Plugin_2<void>
|
|
50
|
+
export declare const variantPicker: Plugin_2<void | VariantPickerConfig>
|
|
51
|
+
|
|
52
|
+
/** Options for {@link variantPicker}. */
|
|
53
|
+
export declare interface VariantPickerConfig {
|
|
54
|
+
/**
|
|
55
|
+
* Use the picker for plain `string` fields with an `options.list` too, so no schema changes
|
|
56
|
+
* are needed and the field keeps `type: 'string'` (and typegen keeps its literal union).
|
|
57
|
+
* Radio fields (`options.layout: 'radio'`) and fields with their own `components.input` are
|
|
58
|
+
* left alone. Default `false`.
|
|
59
|
+
*/
|
|
60
|
+
stringLists?: boolean
|
|
61
|
+
}
|
|
42
62
|
|
|
43
63
|
/**
|
|
44
64
|
* A string input, like the color select: with no value, an input with a popover listing the
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { set, unset, SanityDefaultPreview, definePlugin, defineType } from "sanity";
|
|
2
2
|
import { jsxs, Fragment, jsx } from "react/jsx-runtime";
|
|
3
3
|
import { EditIcon } from "@sanity/icons/Edit";
|
|
4
|
-
import { useClickOutsideEvent, Card, Box, TextInput,
|
|
4
|
+
import { useClickOutsideEvent, Card, Box, TextInput, Flex, Text, Stack, Button } from "@sanity/ui";
|
|
5
5
|
import { Popover } from "@sanity/ui/popover";
|
|
6
6
|
import { Tooltip } from "@sanity/ui/tooltip";
|
|
7
7
|
import React, { useMemo, useState, useRef, useEffect, useCallback } from "react";
|
|
@@ -37,9 +37,9 @@ function ItemList({
|
|
|
37
37
|
selected,
|
|
38
38
|
onSelect
|
|
39
39
|
}) {
|
|
40
|
-
return /* @__PURE__ */ jsxs(
|
|
41
|
-
/* @__PURE__ */ jsx(Box, { paddingX: 2, paddingY: 3, children: /* @__PURE__ */ jsx(Text, { size: 1, weight: "medium", children: label }) }),
|
|
42
|
-
items.length > 0 ? /* @__PURE__ */ jsx(Stack, { gap: 1, style: { maxHeight: 390, overflowY: "auto" }, children: items.map((item, index) => /* @__PURE__ */ jsx(
|
|
40
|
+
return /* @__PURE__ */ jsxs(Flex, { direction: "column", gap: 1, style: { minHeight: 0 }, children: [
|
|
41
|
+
/* @__PURE__ */ jsx(Box, { paddingX: 2, paddingY: 3, style: { flexShrink: 0 }, children: /* @__PURE__ */ jsx(Text, { size: 1, weight: "medium", children: label }) }),
|
|
42
|
+
items.length > 0 ? /* @__PURE__ */ jsx(Stack, { gap: 1, style: { flex: 1, minHeight: 0, maxHeight: 390, overflowY: "auto" }, children: items.map((item, index) => /* @__PURE__ */ jsx(
|
|
43
43
|
Button,
|
|
44
44
|
{
|
|
45
45
|
mode: "bleed",
|
|
@@ -146,7 +146,14 @@ function VariantPickerInput(props) {
|
|
|
146
146
|
ref: popoverRef,
|
|
147
147
|
padding: 1,
|
|
148
148
|
radius: 4,
|
|
149
|
-
|
|
149
|
+
display: "flex",
|
|
150
|
+
style: {
|
|
151
|
+
width: 340,
|
|
152
|
+
maxHeight: "inherit",
|
|
153
|
+
minHeight: 0,
|
|
154
|
+
flexDirection: "column",
|
|
155
|
+
overflow: "hidden"
|
|
156
|
+
},
|
|
150
157
|
onKeyDown: (event) => {
|
|
151
158
|
event.key === "Escape" && close();
|
|
152
159
|
},
|
|
@@ -211,7 +218,20 @@ function VariantPickerInput(props) {
|
|
|
211
218
|
) })
|
|
212
219
|
] });
|
|
213
220
|
}
|
|
214
|
-
|
|
221
|
+
function hasOwnInput(schemaType) {
|
|
222
|
+
for (let type = schemaType; type; type = type.type)
|
|
223
|
+
if (type.components?.input) return !0;
|
|
224
|
+
return !1;
|
|
225
|
+
}
|
|
226
|
+
function isPickableStringList(schemaType) {
|
|
227
|
+
if (schemaType.jsonType !== "string") return !1;
|
|
228
|
+
const options = schemaType.options;
|
|
229
|
+
return !Array.isArray(options?.list) || options.list.length === 0 || options.layout === "radio" ? !1 : !hasOwnInput(schemaType);
|
|
230
|
+
}
|
|
231
|
+
function StringListInput(props) {
|
|
232
|
+
return isPickableStringList(props.schemaType) ? /* @__PURE__ */ jsx(VariantPickerInput, { ...props }) : props.renderDefault(props);
|
|
233
|
+
}
|
|
234
|
+
const variantPicker = definePlugin((config) => ({
|
|
215
235
|
name: "variant-picker",
|
|
216
236
|
schema: {
|
|
217
237
|
types: [
|
|
@@ -222,11 +242,13 @@ const variantPicker = definePlugin(() => ({
|
|
|
222
242
|
components: { input: VariantPickerInput }
|
|
223
243
|
})
|
|
224
244
|
]
|
|
225
|
-
}
|
|
245
|
+
},
|
|
246
|
+
...config?.stringLists ? { form: { components: { input: StringListInput } } } : {}
|
|
226
247
|
}));
|
|
227
248
|
export {
|
|
228
249
|
VariantPickerInput,
|
|
229
250
|
filterItems,
|
|
251
|
+
isPickableStringList,
|
|
230
252
|
toItems,
|
|
231
253
|
variantPicker
|
|
232
254
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/list.ts","../src/input.tsx","../src/index.ts"],"sourcesContent":["import React from 'react'\nimport type {StringOptions} from 'sanity'\n\n/** An icon for a list item: a component (e.g. from `@sanity/icons`), an element, or an emoji. */\nexport type VariantIcon = React.ComponentType | React.ReactNode\n\n/** A `{title, value}` item of `options.list`, plus an optional `icon`. */\nexport type VariantListItem = {_key?: string; title: string; value?: string; icon?: VariantIcon}\n\n/** One option of the field's `options.list`, normalized. */\nexport type VariantItem = {_key?: string; title: string; value: string; icon?: React.ReactNode}\n\nconst capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1)\n\nconst isTitled = (option: unknown): option is VariantListItem =>\n typeof option === 'object' && option !== null && 'title' in option\n\nconst isComponent = (icon: unknown): icon is React.ElementType =>\n typeof icon === 'function' ||\n Boolean(icon && typeof icon === 'object' && '$$typeof' in icon && !React.isValidElement(icon))\n\n/**\n * Icons become elements so the preview renders them as media: components are created, and text\n * (an emoji) is wrapped, since the preview would read a bare string as an image URL.\n */\nfunction toIconNode(icon: VariantIcon | undefined): React.ReactNode {\n if (icon === undefined || icon === null || icon === false || icon === '') return undefined\n if (isComponent(icon)) return React.createElement(icon)\n if (typeof icon === 'string' || typeof icon === 'number') {\n return React.createElement('span', {style: {fontSize: '1.25em', lineHeight: 1}}, icon)\n }\n return icon as React.ReactNode\n}\n\n/**\n * Reads `options.list` the way Sanity's native string select does: `{title, value}` items are\n * kept, plain strings become `{title: Capitalized, value}`. Items without a value are skipped.\n */\nexport function toItems(list: StringOptions['list']): VariantItem[] {\n return (list ?? []).flatMap((option: unknown) => {\n if (isTitled(option)) {\n // A string field stores strings: other values can't be picked (or searched) safely.\n if (typeof option.value !== 'string') return []\n return [\n {\n _key: option._key,\n title: String(option.title ?? option.value),\n value: option.value,\n icon: toIconNode(option.icon),\n },\n ]\n }\n return typeof option === 'string' ? [{title: capitalize(option), value: option}] : []\n })\n}\n\n/** Case-insensitive match on the title or the value. */\nexport function filterItems(items: VariantItem[], query: string): VariantItem[] {\n const q = query.trim().toLowerCase()\n if (!q) return items\n return items.filter(\n (item) => item.title.toLowerCase().includes(q) || item.value.toLowerCase().includes(q),\n )\n}\n","import {EditIcon} from '@sanity/icons/Edit'\nimport {Box, Button, Card, Flex, Stack, Text, TextInput, useClickOutsideEvent} from '@sanity/ui'\nimport {Popover} from '@sanity/ui/popover'\nimport {Tooltip} from '@sanity/ui/tooltip'\nimport React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'\nimport {SanityDefaultPreview, set, unset, type StringInputProps} from 'sanity'\n\nimport {filterItems, toItems, type VariantItem} from './list'\n\n/**\n * Keep focus in the field while clicking inside the popover. Otherwise the field's blur clears\n * the search and swaps the popover content before the click lands.\n */\nconst keepInputFocus = (event: React.MouseEvent) => event.preventDefault()\n\n/** An item's title with its icon on the left, as a native compact preview. */\nfunction ItemPreview({item}: {item: Pick<VariantItem, 'title' | 'icon'>}) {\n // `icon={false}` hides all media, so it only stands in for a missing icon.\n return item.icon ? (\n <SanityDefaultPreview layout=\"compact\" title={item.title} media={item.icon} />\n ) : (\n <SanityDefaultPreview layout=\"compact\" title={item.title} icon={false} />\n )\n}\n\nfunction ItemList({\n items,\n label,\n empty,\n selected,\n onSelect,\n}: {\n items: VariantItem[]\n label: string\n empty: string\n selected?: string\n onSelect: (item: VariantItem) => void\n}) {\n return (\n <Stack gap={1}>\n <Box paddingX={2} paddingY={3}>\n <Text size={1} weight=\"medium\">\n {label}\n </Text>\n </Box>\n {items.length > 0 ? (\n <Stack gap={1} style={{maxHeight: 390, overflowY: 'auto'}}>\n {items.map((item, index) => (\n <Button\n // Lists may repeat a value; the index keeps keys unique.\n key={item._key ?? `${item.value}-${index}`}\n mode=\"bleed\"\n width=\"fill\"\n padding={1}\n selected={item.value === selected}\n onMouseDown={keepInputFocus}\n onClick={() => onSelect(item)}\n >\n <ItemPreview item={item} />\n </Button>\n ))}\n </Stack>\n ) : (\n <Box paddingX={2} paddingBottom={3}>\n <Text size={1} muted>\n {empty}\n </Text>\n </Box>\n )}\n </Stack>\n )\n}\n\n/**\n * The picked item, shown like the color select's preset row: the preview is a bleed button with\n * the native hover that opens the list (the value stays until another is picked), and the pencil\n * on the right clears it and reopens the search.\n */\nfunction SelectedItem({\n item,\n readOnly,\n invalid,\n fieldId,\n focusRef,\n onFieldFocus,\n onFieldBlur,\n onOpen,\n onEscape,\n onReplace,\n}: {\n item: Pick<VariantItem, 'title' | 'icon'>\n readOnly?: boolean\n /** A validation error: the row takes the critical tone, like a native input. */\n invalid?: boolean\n /**\n * Sanity's focus wiring, on the preview button (the row's main control), so the label,\n * jumping to the field from a validation message and presence all work.\n */\n fieldId?: string\n focusRef?: React.Ref<HTMLButtonElement>\n onFieldFocus?: React.FocusEventHandler<HTMLButtonElement>\n onFieldBlur?: React.FocusEventHandler<HTMLButtonElement>\n onOpen: () => void\n onEscape: () => void\n onReplace: () => void\n}) {\n return (\n <Card border radius={2} overflow=\"hidden\" tone={invalid ? 'critical' : undefined}>\n <Flex align=\"center\" style={{height: 33}}>\n <Box flex={1} style={{minWidth: 0}}>\n {readOnly ? (\n <Box paddingX={1}>\n <ItemPreview item={item} />\n </Box>\n ) : (\n <Button\n id={fieldId}\n ref={focusRef}\n mode=\"bleed\"\n // Exactly the row's height, like the color select: padding would overflow the row\n // and push the clipped hover out to the border.\n padding={0}\n width=\"fill\"\n style={{clipPath: 'inset(3px round 2px)'}}\n onFocus={onFieldFocus}\n onBlur={onFieldBlur}\n onClick={onOpen}\n onKeyDown={(event) => {\n if (event.key === 'Escape') onEscape()\n }}\n >\n <ItemPreview item={item} />\n </Button>\n )}\n </Box>\n {!readOnly && (\n <Tooltip\n animate\n portal\n placement=\"top\"\n content={\n <Text size={1} weight=\"medium\">\n Replace variant\n </Text>\n }\n >\n <Button\n aria-label=\"Replace variant\"\n icon={EditIcon}\n mode=\"bleed\"\n style={{clipPath: 'inset(3px round 2px)'}}\n onClick={onReplace}\n />\n </Tooltip>\n )}\n </Flex>\n </Card>\n )\n}\n\n/** Points each ref (callback or object) at `node`. */\nfunction assignRefs<T>(node: T | null, ...refs: Array<React.Ref<T> | undefined>) {\n for (const ref of refs) {\n if (typeof ref === 'function') ref(node)\n else if (ref) (ref as React.MutableRefObject<T | null>).current = node\n }\n}\n\n/**\n * A string input, like the color select: with no value, an input with a popover listing the\n * field's `options.list` (typing searches it); with a value, the picked item, which opens the\n * same list, and a pencil that clears it and reopens the search.\n */\nexport function VariantPickerInput(props: StringInputProps) {\n const {value, onChange, readOnly, elementProps, schemaType, validationError, validation} = props\n const invalid = validation.some((marker) => marker.level === 'error')\n // Sanity drops a field-level `placeholder` on types that extend `string` (only `options` and a\n // few other keys carry over), so `options.placeholder` is the way to set one per field.\n const placeholder =\n (schemaType.options as {placeholder?: string} | undefined)?.placeholder ||\n (schemaType as {placeholder?: string}).placeholder ||\n 'Search a variant'\n const items = useMemo(() => toItems(schemaType.options?.list), [schemaType.options?.list])\n // A stored value missing from the list still shows, as its raw value.\n const selected = value\n ? (items.find((item) => item.value === value) ?? {title: value, icon: undefined})\n : null\n\n const [open, setOpen] = useState(false)\n const [container, setContainer] = useState<HTMLDivElement | null>(null)\n const popoverRef = useRef<HTMLDivElement | null>(null)\n const inputRef = useRef<HTMLInputElement | null>(null)\n // Set by the pencil: focus the input once it's rendered (after the value is cleared).\n const focusPending = useRef(false)\n // Text typed in the field: a search over the list.\n const [typed, setTyped] = useState<string | null>(null)\n const query = typed ?? ''\n const matches = useMemo(() => filterItems(items, query), [items, query])\n\n useEffect(() => {\n if (focusPending.current && inputRef.current) {\n focusPending.current = false\n inputRef.current.focus()\n }\n })\n\n const close = useCallback(() => {\n setOpen(false)\n setTyped(null)\n }, [])\n\n useClickOutsideEvent(open && close, () => [container, popoverRef.current])\n\n const select = (item: VariantItem) => {\n if (item.value !== value) onChange(set(item.value))\n close()\n }\n\n // Pencil: clear the value and reopen the popover to pick anew.\n const replace = () => {\n setTyped(null)\n onChange(unset())\n setOpen(true)\n focusPending.current = true\n }\n\n // Leaving the field drops the search.\n const commitTyped = () => setTyped(null)\n\n let label = 'Variants'\n if (query.trim()) label = `${matches.length} ${matches.length === 1 ? 'result' : 'results'}`\n const empty = query.trim() ? `No variants match “${query.trim()}”` : 'No variants'\n\n return (\n <>\n <Popover\n open={open && !readOnly}\n referenceElement={container}\n portal\n placement=\"bottom-start\"\n fallbackPlacements={['top-start']}\n animate\n constrainSize\n radius={4}\n shadow={3}\n content={\n <Card\n ref={popoverRef}\n padding={1}\n radius={4}\n style={{width: 340, maxHeight: 'inherit', overflow: 'auto'}}\n onKeyDown={(event) => {\n if (event.key === 'Escape') close()\n }}\n >\n <ItemList\n items={matches}\n label={label}\n empty={empty}\n selected={value}\n onSelect={select}\n />\n </Card>\n }\n />\n <Box ref={setContainer}>\n {selected ? (\n <SelectedItem\n item={selected}\n readOnly={readOnly}\n invalid={invalid}\n fieldId={elementProps.id}\n focusRef={elementProps.ref as unknown as React.Ref<HTMLButtonElement>}\n onFieldFocus={\n elementProps.onFocus as unknown as React.FocusEventHandler<HTMLButtonElement>\n }\n onFieldBlur={\n elementProps.onBlur as unknown as React.FocusEventHandler<HTMLButtonElement>\n }\n onOpen={() => setOpen((wasOpen) => !wasOpen)}\n onEscape={close}\n onReplace={replace}\n />\n ) : (\n <TextInput\n {...elementProps}\n ref={(node) =>\n assignRefs(\n node,\n inputRef,\n elementProps.ref as React.Ref<HTMLInputElement> | undefined,\n )\n }\n readOnly={readOnly}\n customValidity={validationError}\n placeholder={placeholder}\n fontSize={1}\n weight=\"medium\"\n value={query}\n style={{height: 35}}\n onFocus={(event) => {\n elementProps.onFocus(event)\n setOpen(true)\n }}\n onClick={() => setOpen(true)}\n onChange={(event) => {\n setTyped(event.currentTarget.value)\n setOpen(true)\n }}\n onBlur={(event) => {\n elementProps.onBlur(event)\n commitTyped()\n }}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n // Enter picks the first match of a search.\n if (query.trim() && matches[0]) select(matches[0])\n }\n if (event.key === 'Escape') close()\n }}\n />\n )}\n </Box>\n </>\n )\n}\n","import {definePlugin, defineType} from 'sanity'\n\nimport {VariantPickerInput} from './input'\n\n/**\n * Registers a `variantPicker` field type: a native `string` with a searchable popover input.\n * It reads `options.list` exactly like a string field (`{title, value}` items or plain strings)\n * and stores the picked item's `value`.\n *\n * @example\n * ```ts\n * // sanity.config.ts\n * plugins: [variantPicker()]\n *\n * // schema\n * defineField({\n * name: 'size',\n * type: 'variantPicker',\n * options: {list: [{title: 'Small', value: 'sm'}, 'large']},\n * })\n * ```\n */\nexport const variantPicker = definePlugin(() => ({\n name: 'variant-picker',\n schema: {\n types: [\n defineType({\n name: 'variantPicker',\n title: 'Variant',\n type: 'string',\n components: {input: VariantPickerInput},\n }),\n ],\n },\n}))\n\nexport {VariantPickerInput} from './input'\nexport {filterItems, toItems, type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AAQ,GAAA;AAAA,QAChB,SAAS,CAAC,UAAU;AAClB,uBAAa,QAAQ,KAAK,GAC1B,QAAQ,EAAI;AAAA,QACd;AAAA,QACA,SAAS,MAAM,QAAQ,EAAI;AAAA,QAC3B,UAAU,CAAC,UAAU;AACnB,mBAAS,MAAM,cAAc,KAAK,GAClC,QAAQ,EAAI;AAAA,QACd;AAAA,QACA,QAAQ,CAAC,UAAU;AACjB,uBAAa,OAAO,KAAK,GACzB,YAAA;AAAA,QACF;AAAA,QACA,WAAW,CAAC,UAAU;AAChB,gBAAM,QAAQ,YAChB,MAAM,kBAEF,MAAM,UAAU,QAAQ,CAAC,KAAG,OAAO,QAAQ,CAAC,CAAC,IAE/C,MAAM,QAAQ,YAAU,MAAA;AAAA,QAC9B;AAAA,MAAA;AAAA,IAAA,EACF,CAEJ;AAAA,EAAA,GACF;AAEJ;AChTO,MAAM,gBAAgB,aAAa,OAAO;AAAA,EAC/C,MAAM;AAAA,EACN,QAAQ;AAAA,IACN,OAAO;AAAA,MACL,WAAW;AAAA,QACT,MAAM;AAAA,QACN,OAAO;AAAA,QACP,MAAM;AAAA,QACN,YAAY,EAAC,OAAO,mBAAA;AAAA,MAAkB,CACvC;AAAA,IAAA;AAAA,EACH;AAEJ,EAAE;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/list.ts","../src/input.tsx","../src/stringLists.tsx","../src/index.ts"],"sourcesContent":["import React from 'react'\nimport type {StringOptions} from 'sanity'\n\n/** An icon for a list item: a component (e.g. from `@sanity/icons`), an element, or an emoji. */\nexport type VariantIcon = React.ComponentType | React.ReactNode\n\n/** A `{title, value}` item of `options.list`, plus an optional `icon`. */\nexport type VariantListItem = {_key?: string; title: string; value?: string; icon?: VariantIcon}\n\n/** One option of the field's `options.list`, normalized. */\nexport type VariantItem = {_key?: string; title: string; value: string; icon?: React.ReactNode}\n\nconst capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1)\n\nconst isTitled = (option: unknown): option is VariantListItem =>\n typeof option === 'object' && option !== null && 'title' in option\n\nconst isComponent = (icon: unknown): icon is React.ElementType =>\n typeof icon === 'function' ||\n Boolean(icon && typeof icon === 'object' && '$$typeof' in icon && !React.isValidElement(icon))\n\n/**\n * Icons become elements so the preview renders them as media: components are created, and text\n * (an emoji) is wrapped, since the preview would read a bare string as an image URL.\n */\nfunction toIconNode(icon: VariantIcon | undefined): React.ReactNode {\n if (icon === undefined || icon === null || icon === false || icon === '') return undefined\n if (isComponent(icon)) return React.createElement(icon)\n if (typeof icon === 'string' || typeof icon === 'number') {\n return React.createElement('span', {style: {fontSize: '1.25em', lineHeight: 1}}, icon)\n }\n return icon as React.ReactNode\n}\n\n/**\n * Reads `options.list` the way Sanity's native string select does: `{title, value}` items are\n * kept, plain strings become `{title: Capitalized, value}`. Items without a value are skipped.\n */\nexport function toItems(list: StringOptions['list']): VariantItem[] {\n return (list ?? []).flatMap((option: unknown) => {\n if (isTitled(option)) {\n // A string field stores strings: other values can't be picked (or searched) safely.\n if (typeof option.value !== 'string') return []\n return [\n {\n _key: option._key,\n title: String(option.title ?? option.value),\n value: option.value,\n icon: toIconNode(option.icon),\n },\n ]\n }\n return typeof option === 'string' ? [{title: capitalize(option), value: option}] : []\n })\n}\n\n/** Case-insensitive match on the title or the value. */\nexport function filterItems(items: VariantItem[], query: string): VariantItem[] {\n const q = query.trim().toLowerCase()\n if (!q) return items\n return items.filter(\n (item) => item.title.toLowerCase().includes(q) || item.value.toLowerCase().includes(q),\n )\n}\n","import {EditIcon} from '@sanity/icons/Edit'\nimport {Box, Button, Card, Flex, Stack, Text, TextInput, useClickOutsideEvent} from '@sanity/ui'\nimport {Popover} from '@sanity/ui/popover'\nimport {Tooltip} from '@sanity/ui/tooltip'\nimport React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'\nimport {SanityDefaultPreview, set, unset, type StringInputProps} from 'sanity'\n\nimport {filterItems, toItems, type VariantItem} from './list'\n\n/**\n * Keep focus in the field while clicking inside the popover. Otherwise the field's blur clears\n * the search and swaps the popover content before the click lands.\n */\nconst keepInputFocus = (event: React.MouseEvent) => event.preventDefault()\n\n/** An item's title with its icon on the left, as a native compact preview. */\nfunction ItemPreview({item}: {item: Pick<VariantItem, 'title' | 'icon'>}) {\n // `icon={false}` hides all media, so it only stands in for a missing icon.\n return item.icon ? (\n <SanityDefaultPreview layout=\"compact\" title={item.title} media={item.icon} />\n ) : (\n <SanityDefaultPreview layout=\"compact\" title={item.title} icon={false} />\n )\n}\n\nfunction ItemList({\n items,\n label,\n empty,\n selected,\n onSelect,\n}: {\n items: VariantItem[]\n label: string\n empty: string\n selected?: string\n onSelect: (item: VariantItem) => void\n}) {\n // The list is the popover's only scroll area: the label stays put, and when the viewport is\n // short the list shrinks to fit (rather than the card scrolling around a scrolling list).\n return (\n <Flex direction=\"column\" gap={1} style={{minHeight: 0}}>\n <Box paddingX={2} paddingY={3} style={{flexShrink: 0}}>\n <Text size={1} weight=\"medium\">\n {label}\n </Text>\n </Box>\n {items.length > 0 ? (\n <Stack gap={1} style={{flex: 1, minHeight: 0, maxHeight: 390, overflowY: 'auto'}}>\n {items.map((item, index) => (\n <Button\n // Lists may repeat a value; the index keeps keys unique.\n key={item._key ?? `${item.value}-${index}`}\n mode=\"bleed\"\n width=\"fill\"\n padding={1}\n selected={item.value === selected}\n onMouseDown={keepInputFocus}\n onClick={() => onSelect(item)}\n >\n <ItemPreview item={item} />\n </Button>\n ))}\n </Stack>\n ) : (\n <Box paddingX={2} paddingBottom={3}>\n <Text size={1} muted>\n {empty}\n </Text>\n </Box>\n )}\n </Flex>\n )\n}\n\n/**\n * The picked item, shown like the color select's preset row: the preview is a bleed button with\n * the native hover that opens the list (the value stays until another is picked), and the pencil\n * on the right clears it and reopens the search.\n */\nfunction SelectedItem({\n item,\n readOnly,\n invalid,\n fieldId,\n focusRef,\n onFieldFocus,\n onFieldBlur,\n onOpen,\n onEscape,\n onReplace,\n}: {\n item: Pick<VariantItem, 'title' | 'icon'>\n readOnly?: boolean\n /** A validation error: the row takes the critical tone, like a native input. */\n invalid?: boolean\n /**\n * Sanity's focus wiring, on the preview button (the row's main control), so the label,\n * jumping to the field from a validation message and presence all work.\n */\n fieldId?: string\n focusRef?: React.Ref<HTMLButtonElement>\n onFieldFocus?: React.FocusEventHandler<HTMLButtonElement>\n onFieldBlur?: React.FocusEventHandler<HTMLButtonElement>\n onOpen: () => void\n onEscape: () => void\n onReplace: () => void\n}) {\n return (\n <Card border radius={2} overflow=\"hidden\" tone={invalid ? 'critical' : undefined}>\n <Flex align=\"center\" style={{height: 33}}>\n <Box flex={1} style={{minWidth: 0}}>\n {readOnly ? (\n <Box paddingX={1}>\n <ItemPreview item={item} />\n </Box>\n ) : (\n <Button\n id={fieldId}\n ref={focusRef}\n mode=\"bleed\"\n // Exactly the row's height, like the color select: padding would overflow the row\n // and push the clipped hover out to the border.\n padding={0}\n width=\"fill\"\n style={{clipPath: 'inset(3px round 2px)'}}\n onFocus={onFieldFocus}\n onBlur={onFieldBlur}\n onClick={onOpen}\n onKeyDown={(event) => {\n if (event.key === 'Escape') onEscape()\n }}\n >\n <ItemPreview item={item} />\n </Button>\n )}\n </Box>\n {!readOnly && (\n <Tooltip\n animate\n portal\n placement=\"top\"\n content={\n <Text size={1} weight=\"medium\">\n Replace variant\n </Text>\n }\n >\n <Button\n aria-label=\"Replace variant\"\n icon={EditIcon}\n mode=\"bleed\"\n style={{clipPath: 'inset(3px round 2px)'}}\n onClick={onReplace}\n />\n </Tooltip>\n )}\n </Flex>\n </Card>\n )\n}\n\n/** Points each ref (callback or object) at `node`. */\nfunction assignRefs<T>(node: T | null, ...refs: Array<React.Ref<T> | undefined>) {\n for (const ref of refs) {\n if (typeof ref === 'function') ref(node)\n else if (ref) (ref as React.MutableRefObject<T | null>).current = node\n }\n}\n\n/**\n * A string input, like the color select: with no value, an input with a popover listing the\n * field's `options.list` (typing searches it); with a value, the picked item, which opens the\n * same list, and a pencil that clears it and reopens the search.\n */\nexport function VariantPickerInput(props: StringInputProps) {\n const {value, onChange, readOnly, elementProps, schemaType, validationError, validation} = props\n const invalid = validation.some((marker) => marker.level === 'error')\n // Sanity drops a field-level `placeholder` on types that extend `string` (only `options` and a\n // few other keys carry over), so `options.placeholder` is the way to set one per field.\n const placeholder =\n (schemaType.options as {placeholder?: string} | undefined)?.placeholder ||\n (schemaType as {placeholder?: string}).placeholder ||\n 'Search a variant'\n const items = useMemo(() => toItems(schemaType.options?.list), [schemaType.options?.list])\n // A stored value missing from the list still shows, as its raw value.\n const selected = value\n ? (items.find((item) => item.value === value) ?? {title: value, icon: undefined})\n : null\n\n const [open, setOpen] = useState(false)\n const [container, setContainer] = useState<HTMLDivElement | null>(null)\n const popoverRef = useRef<HTMLDivElement | null>(null)\n const inputRef = useRef<HTMLInputElement | null>(null)\n // Set by the pencil: focus the input once it's rendered (after the value is cleared).\n const focusPending = useRef(false)\n // Text typed in the field: a search over the list.\n const [typed, setTyped] = useState<string | null>(null)\n const query = typed ?? ''\n const matches = useMemo(() => filterItems(items, query), [items, query])\n\n useEffect(() => {\n if (focusPending.current && inputRef.current) {\n focusPending.current = false\n inputRef.current.focus()\n }\n })\n\n const close = useCallback(() => {\n setOpen(false)\n setTyped(null)\n }, [])\n\n useClickOutsideEvent(open && close, () => [container, popoverRef.current])\n\n const select = (item: VariantItem) => {\n if (item.value !== value) onChange(set(item.value))\n close()\n }\n\n // Pencil: clear the value and reopen the popover to pick anew.\n const replace = () => {\n setTyped(null)\n onChange(unset())\n setOpen(true)\n focusPending.current = true\n }\n\n // Leaving the field drops the search.\n const commitTyped = () => setTyped(null)\n\n let label = 'Variants'\n if (query.trim()) label = `${matches.length} ${matches.length === 1 ? 'result' : 'results'}`\n const empty = query.trim() ? `No variants match “${query.trim()}”` : 'No variants'\n\n return (\n <>\n <Popover\n open={open && !readOnly}\n referenceElement={container}\n portal\n placement=\"bottom-start\"\n fallbackPlacements={['top-start']}\n animate\n constrainSize\n radius={4}\n shadow={3}\n content={\n <Card\n ref={popoverRef}\n padding={1}\n radius={4}\n display=\"flex\"\n style={{\n width: 340,\n maxHeight: 'inherit',\n minHeight: 0,\n flexDirection: 'column',\n overflow: 'hidden',\n }}\n onKeyDown={(event) => {\n if (event.key === 'Escape') close()\n }}\n >\n <ItemList\n items={matches}\n label={label}\n empty={empty}\n selected={value}\n onSelect={select}\n />\n </Card>\n }\n />\n <Box ref={setContainer}>\n {selected ? (\n <SelectedItem\n item={selected}\n readOnly={readOnly}\n invalid={invalid}\n fieldId={elementProps.id}\n focusRef={elementProps.ref as unknown as React.Ref<HTMLButtonElement>}\n onFieldFocus={\n elementProps.onFocus as unknown as React.FocusEventHandler<HTMLButtonElement>\n }\n onFieldBlur={\n elementProps.onBlur as unknown as React.FocusEventHandler<HTMLButtonElement>\n }\n onOpen={() => setOpen((wasOpen) => !wasOpen)}\n onEscape={close}\n onReplace={replace}\n />\n ) : (\n <TextInput\n {...elementProps}\n ref={(node) =>\n assignRefs(\n node,\n inputRef,\n elementProps.ref as React.Ref<HTMLInputElement> | undefined,\n )\n }\n readOnly={readOnly}\n customValidity={validationError}\n placeholder={placeholder}\n fontSize={1}\n weight=\"medium\"\n value={query}\n style={{height: 35}}\n onFocus={(event) => {\n elementProps.onFocus(event)\n setOpen(true)\n }}\n onClick={() => setOpen(true)}\n onChange={(event) => {\n setTyped(event.currentTarget.value)\n setOpen(true)\n }}\n onBlur={(event) => {\n elementProps.onBlur(event)\n commitTyped()\n }}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n // Enter picks the first match of a search.\n if (query.trim() && matches[0]) select(matches[0])\n }\n if (event.key === 'Escape') close()\n }}\n />\n )}\n </Box>\n </>\n )\n}\n","import type React from 'react'\nimport type {InputProps, SchemaType, StringInputProps, StringOptions} from 'sanity'\n\nimport {VariantPickerInput} from './input'\n\n/** True when the type, or a type it extends, sets its own input component. */\nfunction hasOwnInput(schemaType: SchemaType): boolean {\n for (let type: SchemaType | undefined = schemaType; type; type = type.type) {\n if (type.components?.input) return true\n }\n return false\n}\n\n/**\n * Whether `stringLists` takes over a field: a `string` with a non-empty `options.list` that isn't\n * a radio group and doesn't set its own input. Radios stay native (every option visible, one\n * click), and a field's own `components.input` always wins.\n */\nexport function isPickableStringList(schemaType: SchemaType): boolean {\n if (schemaType.jsonType !== 'string') return false\n const options = schemaType.options as StringOptions | undefined\n if (!Array.isArray(options?.list) || options.list.length === 0) return false\n if (options.layout === 'radio') return false\n return !hasOwnInput(schemaType)\n}\n\n/**\n * Form middleware for `stringLists`: renders the variant picker for plain `string` list fields\n * and leaves every other input to the next renderer.\n */\nexport function StringListInput(props: InputProps): React.JSX.Element {\n if (isPickableStringList(props.schemaType)) {\n return <VariantPickerInput {...(props as StringInputProps)} />\n }\n return props.renderDefault(props)\n}\n","import {definePlugin, defineType} from 'sanity'\n\nimport {VariantPickerInput} from './input'\nimport {StringListInput} from './stringLists'\n\n/** Options for {@link variantPicker}. */\nexport interface VariantPickerConfig {\n /**\n * Use the picker for plain `string` fields with an `options.list` too, so no schema changes\n * are needed and the field keeps `type: 'string'` (and typegen keeps its literal union).\n * Radio fields (`options.layout: 'radio'`) and fields with their own `components.input` are\n * left alone. Default `false`.\n */\n stringLists?: boolean\n}\n\n/**\n * Registers a `variantPicker` field type: a native `string` with a searchable popover input.\n * It reads `options.list` exactly like a string field (`{title, value}` items or plain strings)\n * and stores the picked item's `value`. With `stringLists: true`, plain `string` list fields get\n * the same input.\n *\n * @example\n * ```ts\n * // sanity.config.ts\n * plugins: [variantPicker()]\n *\n * // schema\n * defineField({\n * name: 'size',\n * type: 'variantPicker',\n * options: {list: [{title: 'Small', value: 'sm'}, 'large']},\n * })\n * ```\n */\nexport const variantPicker = definePlugin<VariantPickerConfig | void>((config) => ({\n name: 'variant-picker',\n schema: {\n types: [\n defineType({\n name: 'variantPicker',\n title: 'Variant',\n type: 'string',\n components: {input: VariantPickerInput},\n }),\n ],\n },\n ...(config?.stringLists ? {form: {components: {input: StringListInput}}} : {}),\n}))\n\nexport {VariantPickerInput} from './input'\nexport {filterItems, toItems, type VariantItem} from './list'\nexport {isPickableStringList} from './stringLists'\n"],"names":[],"mappings":";;;;;;;AAYA,MAAM,aAAa,CAAC,SAAiB,KAAK,OAAO,CAAC,EAAE,gBAAgB,KAAK,MAAM,CAAC,GAE1E,WAAW,CAAC,WAChB,OAAO,UAAW,YAAY,WAAW,QAAQ,WAAW,QAExD,cAAc,CAAC,SACnB,OAAO,QAAS,cAChB,CAAA,EAAQ,QAAQ,OAAO,QAAS,YAAY,cAAc,QAAQ,CAAC,MAAM,eAAe,IAAI;AAM9F,SAAS,WAAW,MAAgD;AAClE,MAAI,EAAsB,QAAS,QAAQ,SAAS,MAAS,SAAS;AACtE,WAAI,YAAY,IAAI,IAAU,MAAM,cAAc,IAAI,IAClD,OAAO,QAAS,YAAY,OAAO,QAAS,WACvC,MAAM,cAAc,QAAQ,EAAC,OAAO,EAAC,UAAU,UAAU,YAAY,EAAA,KAAK,IAAI,IAEhF;AACT;AAMO,SAAS,QAAQ,MAA4C;AAClE,UAAQ,QAAQ,CAAA,GAAI,QAAQ,CAAC,WACvB,SAAS,MAAM,IAEb,OAAO,OAAO,SAAU,WAAiB,CAAA,IACtC;AAAA,IACL;AAAA,MACE,MAAM,OAAO;AAAA,MACb,OAAO,OAAO,OAAO,SAAS,OAAO,KAAK;AAAA,MAC1C,OAAO,OAAO;AAAA,MACd,MAAM,WAAW,OAAO,IAAI;AAAA,IAAA;AAAA,EAC9B,IAGG,OAAO,UAAW,WAAW,CAAC,EAAC,OAAO,WAAW,MAAM,GAAG,OAAO,OAAA,CAAO,IAAI,CAAA,CACpF;AACH;AAGO,SAAS,YAAY,OAAsB,OAA8B;AAC9E,QAAM,IAAI,MAAM,KAAA,EAAO,YAAA;AACvB,SAAK,IACE,MAAM;AAAA,IACX,CAAC,SAAS,KAAK,MAAM,cAAc,SAAS,CAAC,KAAK,KAAK,MAAM,YAAA,EAAc,SAAS,CAAC;AAAA,EAAA,IAFxE;AAIjB;AClDA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