@nocode-factory/sanity-kit 2.62.0 → 2.64.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +76 -0
- package/README.md +20 -0
- package/bin/check-lcp.mjs +195 -0
- package/bin/ncf-kit.mjs +32 -0
- package/dist/index.d.ts +46 -2
- package/dist/index.js +380 -19
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/form/choices/ChoiceInputs.tsx +268 -0
- package/src/form/choices/inheritedValue.ts +55 -0
- package/src/form/choices/options.ts +55 -0
- package/src/form/choices/withNcfChoiceInputs.ts +54 -0
- package/src/index.ts +2 -0
- package/src/tools/components/BlockCard.tsx +9 -5
- package/src/tools/components/ComponentsTool.tsx +29 -5
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import {useCallback, useEffect, useState, type ComponentType} from 'react'
|
|
2
|
+
import {Button, Flex, Radio, Stack, Text} from '@sanity/ui'
|
|
3
|
+
import {
|
|
4
|
+
set,
|
|
5
|
+
unset,
|
|
6
|
+
useFormValue,
|
|
7
|
+
type ArrayOfObjectsInputProps,
|
|
8
|
+
type NumberInputProps,
|
|
9
|
+
type StringInputProps,
|
|
10
|
+
} from 'sanity'
|
|
11
|
+
import {useInheritedValue} from './inheritedValue'
|
|
12
|
+
import type {ResolvedChoiceInputsOptions} from './options'
|
|
13
|
+
|
|
14
|
+
// SAISIES DE CHOIX DES SECTIONS (kit >= 2.64.0) : ce qui s'applique est TOUJOURS visible.
|
|
15
|
+
// - Liste de choix (fond, position de l'image, mise en page, style et taille du bouton…) :
|
|
16
|
+
// champ vide = hérite ; on coche la valeur par défaut du composant (Réglages >
|
|
17
|
+
// Composants : valeurs par défaut), sinon la valeur du code (options.ncfFallback, sinon
|
|
18
|
+
// la première de la liste, comme le site), marquée « (default) », SANS l'enregistrer.
|
|
19
|
+
// Choisir une autre valeur l'enregistre (la pastille bleue du kit et sa croix de retour
|
|
20
|
+
// apparaissent) ; recliquer sur la valeur par défaut revient à l'héritage.
|
|
21
|
+
// options.ncfSwatches {valeur: jeton} : carré de couleur ; options.ncfThumbs {valeur:
|
|
22
|
+
// SVG} : cartes illustrées (on voit chaque variante).
|
|
23
|
+
// - Niveau de titre (options.ncfHeadingLevel) : niveau logique du composant coché.
|
|
24
|
+
// - Texte d'un élément de liste : vide = rien ne s'affiche (dit dans le champ).
|
|
25
|
+
// - Liste d'éléments héritée : « Add item » recopie d'abord les éléments par défaut.
|
|
26
|
+
// - Nombre avec options.range : curseur.
|
|
27
|
+
// Posées sur le TYPE du champ (components.input), donc sous la pastille du kit.
|
|
28
|
+
|
|
29
|
+
type ListItem = string | {title?: string; value?: string}
|
|
30
|
+
type ChoiceOptions = {
|
|
31
|
+
list?: ListItem[]
|
|
32
|
+
ncfFallback?: string
|
|
33
|
+
ncfSwatches?: Record<string, string>
|
|
34
|
+
ncfThumbs?: Record<string, string>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const normalize = (list: ListItem[] = []) =>
|
|
38
|
+
list.map((item) =>
|
|
39
|
+
typeof item === 'string' ? {title: item, value: item} : {title: item.title ?? item.value ?? '', value: item.value ?? ''},
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
function Label({text, isDefault, suffix}: {text: string; isDefault: boolean; suffix: string}) {
|
|
43
|
+
return (
|
|
44
|
+
<Text size={1} weight={isDefault ? 'semibold' : 'regular'}>
|
|
45
|
+
{text}
|
|
46
|
+
{isDefault ? ` ${suffix}` : ''}
|
|
47
|
+
</Text>
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function createChoiceInputs(o: ResolvedChoiceInputsOptions) {
|
|
52
|
+
const {labels} = o
|
|
53
|
+
|
|
54
|
+
function DefaultChoiceInput(props: StringInputProps) {
|
|
55
|
+
const options = (props.schemaType.options ?? {}) as ChoiceOptions
|
|
56
|
+
const list = normalize(options.list)
|
|
57
|
+
const raw = useInheritedValue(props.path, o.defaultsType, o.namespace)
|
|
58
|
+
const inherited = typeof raw === 'string' && raw ? raw : null
|
|
59
|
+
// Repli propre à un emplacement (ex. style « secondary » du bouton secondaire) :
|
|
60
|
+
// clé « champParent.champ » de options.fallbacks de withNcfChoiceInputs.
|
|
61
|
+
const parent = props.path[props.path.length - 2]
|
|
62
|
+
const field = props.path[props.path.length - 1]
|
|
63
|
+
const conventional = typeof parent === 'string' && typeof field === 'string' ? o.fallbacks[`${parent}.${field}`] : undefined
|
|
64
|
+
const fallback = inherited ?? conventional ?? options.ncfFallback ?? list[0]?.value
|
|
65
|
+
const current = props.value || fallback
|
|
66
|
+
const pick = (value: string) => props.onChange(value === fallback ? unset() : set(value))
|
|
67
|
+
|
|
68
|
+
if (options.ncfThumbs) {
|
|
69
|
+
return (
|
|
70
|
+
<div role="radiogroup" style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(132px, 1fr))', gap: 10}}>
|
|
71
|
+
{list.map(({title, value}) => {
|
|
72
|
+
const checked = current === value
|
|
73
|
+
return (
|
|
74
|
+
<button
|
|
75
|
+
key={value}
|
|
76
|
+
type="button"
|
|
77
|
+
role="radio"
|
|
78
|
+
aria-checked={checked}
|
|
79
|
+
disabled={props.readOnly}
|
|
80
|
+
onClick={() => pick(value)}
|
|
81
|
+
style={{
|
|
82
|
+
display: 'flex',
|
|
83
|
+
flexDirection: 'column',
|
|
84
|
+
gap: 6,
|
|
85
|
+
padding: 8,
|
|
86
|
+
textAlign: 'left',
|
|
87
|
+
borderRadius: 6,
|
|
88
|
+
cursor: props.readOnly ? 'default' : 'pointer',
|
|
89
|
+
color: 'var(--card-fg-color)',
|
|
90
|
+
background: checked ? 'var(--card-bg2-color, transparent)' : 'transparent',
|
|
91
|
+
border: checked ? '2px solid var(--card-focus-ring-color, #2276fc)' : '1px solid var(--card-border-color, #ccc)',
|
|
92
|
+
margin: checked ? 0 : 1,
|
|
93
|
+
}}
|
|
94
|
+
>
|
|
95
|
+
<span aria-hidden="true" style={{display: 'block', width: '100%'}} dangerouslySetInnerHTML={{__html: options.ncfThumbs?.[value] ?? ''}} />
|
|
96
|
+
<Label text={title} isDefault={value === fallback} suffix={labels.default} />
|
|
97
|
+
</button>
|
|
98
|
+
)
|
|
99
|
+
})}
|
|
100
|
+
</div>
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return (
|
|
105
|
+
<Flex wrap="wrap" style={{gap: '10px 20px'}}>
|
|
106
|
+
{list.map(({title, value}) => {
|
|
107
|
+
const swatch = options.ncfSwatches?.[value]
|
|
108
|
+
const color = swatch ? o.colors[swatch]?.value : undefined
|
|
109
|
+
return (
|
|
110
|
+
<label key={value} style={{display: 'flex', alignItems: 'center', gap: 8, cursor: props.readOnly ? 'default' : 'pointer'}}>
|
|
111
|
+
<Radio name={props.id} value={value} checked={current === value} disabled={props.readOnly} onChange={() => pick(value)} />
|
|
112
|
+
{color && (
|
|
113
|
+
<span
|
|
114
|
+
aria-hidden="true"
|
|
115
|
+
style={{width: 16, height: 16, borderRadius: 3, background: color, boxShadow: 'inset 0 0 0 1px rgba(0, 0, 0, 0.18)', flex: 'none'}}
|
|
116
|
+
/>
|
|
117
|
+
)}
|
|
118
|
+
<Label text={title} isDefault={value === fallback} suffix={labels.default} />
|
|
119
|
+
</label>
|
|
120
|
+
)
|
|
121
|
+
})}
|
|
122
|
+
</Flex>
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const LEVELS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'] as const
|
|
127
|
+
const sectionDefault = (type: string) => o.headingLevels.sections[type] ?? o.headingLevels.default
|
|
128
|
+
const below = (level: string) => `h${Math.min(Number(level.slice(1)) + 1, 6)}`
|
|
129
|
+
|
|
130
|
+
// Niveau du titre d'une section (options.ncfHeadingLevel = {section: type}) ou de ses
|
|
131
|
+
// éléments ({item: true}, un niveau sous le titre de la section). Défauts : le fichier
|
|
132
|
+
// heading-levels.json du projet, la même source que le site. P : aspect de titre, sans
|
|
133
|
+
// valeur de titre pour Google ni les lecteurs d'écran.
|
|
134
|
+
function HeadingLevelInput(props: StringInputProps) {
|
|
135
|
+
const options = ((props.schemaType.options ?? {}) as {ncfHeadingLevel?: {section?: string; item?: boolean}}).ncfHeadingLevel ?? {}
|
|
136
|
+
const parent = useFormValue(props.path.slice(0, -1)) as {_type?: string; headingLevel?: string | null} | undefined
|
|
137
|
+
const type = options.section ?? parent?._type ?? ''
|
|
138
|
+
let fallback = sectionDefault(type)
|
|
139
|
+
if (options.item) {
|
|
140
|
+
const section = parent?.headingLevel || sectionDefault(type)
|
|
141
|
+
fallback = below(section === 'p' ? sectionDefault(type) : section)
|
|
142
|
+
}
|
|
143
|
+
const current = props.value || fallback
|
|
144
|
+
return (
|
|
145
|
+
<Flex wrap="wrap" style={{gap: 16}}>
|
|
146
|
+
{LEVELS.map((level) => (
|
|
147
|
+
<label key={level} style={{display: 'flex', alignItems: 'center', gap: 8, cursor: props.readOnly ? 'default' : 'pointer'}}>
|
|
148
|
+
<Radio
|
|
149
|
+
name={props.id}
|
|
150
|
+
value={level}
|
|
151
|
+
checked={current === level}
|
|
152
|
+
disabled={props.readOnly}
|
|
153
|
+
onChange={() => props.onChange(level === fallback ? unset() : set(level))}
|
|
154
|
+
/>
|
|
155
|
+
<Label text={level.toUpperCase()} isDefault={level === fallback} suffix={labels.default} />
|
|
156
|
+
</label>
|
|
157
|
+
))}
|
|
158
|
+
</Flex>
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Texte d'un ÉLÉMENT de liste : une liste propre à la page n'hérite rien élément par
|
|
163
|
+
// élément (applyDefaults : la liste entière ou rien), vide = rien ne s'affiche.
|
|
164
|
+
function ItemTextInput(props: StringInputProps) {
|
|
165
|
+
return props.renderDefault({...props, elementProps: {...props.elementProps, placeholder: labels.emptyItem}})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Liste d'éléments qui HÉRITE des éléments par défaut (vide dans la page) : « Add item »
|
|
169
|
+
// natif créerait une liste réduite au nouvel élément vide, la section disparaîtrait de
|
|
170
|
+
// l'aperçu. On recopie d'abord les éléments par défaut, puis l'ajout natif.
|
|
171
|
+
function InheritedListInput(props: ArrayOfObjectsInputProps) {
|
|
172
|
+
const inherited = useInheritedValue(props.path, o.defaultsType, o.namespace)
|
|
173
|
+
const inherits = !props.value?.length && Array.isArray(inherited) && inherited.length > 0
|
|
174
|
+
if (!inherits) return props.renderDefault(props)
|
|
175
|
+
const defaults = () => structuredClone(inherited) as {_key: string}[]
|
|
176
|
+
return props.renderDefault({
|
|
177
|
+
...props,
|
|
178
|
+
onItemAppend: (item: Parameters<ArrayOfObjectsInputProps["onItemAppend"]>[0]) => {
|
|
179
|
+
props.onChange(set(defaults()))
|
|
180
|
+
props.onItemAppend(item)
|
|
181
|
+
},
|
|
182
|
+
onItemPrepend: (item: Parameters<ArrayOfObjectsInputProps["onItemPrepend"]>[0]) => {
|
|
183
|
+
props.onChange(set(defaults()))
|
|
184
|
+
props.onItemPrepend(item)
|
|
185
|
+
},
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Curseur (number avec options.range = {min, max, step, labels: [g, m, d], unit}).
|
|
190
|
+
// Enregistré au relâchement ; « Reset » vide le champ (il reprend la valeur par défaut).
|
|
191
|
+
function RangeInput(props: NumberInputProps) {
|
|
192
|
+
const {onChange, readOnly, value, schemaType} = props
|
|
193
|
+
const range = ((schemaType.options as {range?: Range} | undefined)?.range ?? {min: 0, max: 100}) as Range
|
|
194
|
+
const mid = (range.min + range.max) / 2
|
|
195
|
+
const [draft, setDraft] = useState<number>(typeof value === 'number' ? value : mid)
|
|
196
|
+
useEffect(() => {
|
|
197
|
+
setDraft(typeof value === 'number' ? value : mid)
|
|
198
|
+
}, [value, mid])
|
|
199
|
+
const commit = useCallback(() => {
|
|
200
|
+
if (draft !== value) onChange(set(draft))
|
|
201
|
+
}, [draft, value, onChange])
|
|
202
|
+
return (
|
|
203
|
+
<Stack gap={3}>
|
|
204
|
+
<style>{RANGE_CSS}</style>
|
|
205
|
+
<Flex align="center" gap={3}>
|
|
206
|
+
<div className="ncf-range-wrap">
|
|
207
|
+
<input
|
|
208
|
+
className="ncf-range"
|
|
209
|
+
type="range"
|
|
210
|
+
min={range.min}
|
|
211
|
+
max={range.max}
|
|
212
|
+
step={range.step ?? 1}
|
|
213
|
+
value={draft}
|
|
214
|
+
disabled={readOnly}
|
|
215
|
+
aria-label={schemaType.title}
|
|
216
|
+
onChange={(e) => setDraft(Number(e.currentTarget.value))}
|
|
217
|
+
onPointerUp={commit}
|
|
218
|
+
onKeyUp={commit}
|
|
219
|
+
onBlur={commit}
|
|
220
|
+
/>
|
|
221
|
+
</div>
|
|
222
|
+
<Text size={1} weight="medium" style={{minWidth: '3.5em', textAlign: 'right', whiteSpace: 'nowrap'}}>
|
|
223
|
+
{draft > 0 ? `+${draft}` : draft}
|
|
224
|
+
{range.unit ?? ''}
|
|
225
|
+
</Text>
|
|
226
|
+
</Flex>
|
|
227
|
+
{range.labels && (
|
|
228
|
+
<Flex justify="space-between">
|
|
229
|
+
{range.labels.map((l) => (
|
|
230
|
+
<Text key={l} size={0} muted>
|
|
231
|
+
{l}
|
|
232
|
+
</Text>
|
|
233
|
+
))}
|
|
234
|
+
</Flex>
|
|
235
|
+
)}
|
|
236
|
+
{typeof value === 'number' && !readOnly && (
|
|
237
|
+
<Flex>
|
|
238
|
+
<Button mode="bleed" fontSize={1} padding={2} text={labels.reset} onClick={() => onChange(unset())} />
|
|
239
|
+
</Flex>
|
|
240
|
+
)}
|
|
241
|
+
</Stack>
|
|
242
|
+
)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
DefaultChoiceInput: DefaultChoiceInput as ComponentType<never>,
|
|
247
|
+
HeadingLevelInput: HeadingLevelInput as ComponentType<never>,
|
|
248
|
+
ItemTextInput: ItemTextInput as ComponentType<never>,
|
|
249
|
+
InheritedListInput: InheritedListInput as ComponentType<never>,
|
|
250
|
+
RangeInput: RangeInput as ComponentType<never>,
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
type Range = {min: number; max: number; step?: number; labels?: [string, string, string]; unit?: string}
|
|
255
|
+
|
|
256
|
+
// Le curseur natif prend la couleur du fond du Studio (ligne invisible) : ligne et curseur
|
|
257
|
+
// dessinés ici aux couleurs du thème (clair ou sombre), repère au centre.
|
|
258
|
+
const RANGE_CSS = `
|
|
259
|
+
.ncf-range{-webkit-appearance:none;appearance:none;flex:1;height:24px;margin:0;background:transparent;cursor:pointer}
|
|
260
|
+
.ncf-range:disabled{cursor:default;opacity:.5}
|
|
261
|
+
.ncf-range::-webkit-slider-runnable-track{height:2px;border-radius:2px;background:var(--card-muted-fg-color,#8a8a8a)}
|
|
262
|
+
.ncf-range::-moz-range-track{height:2px;border-radius:2px;background:var(--card-muted-fg-color,#8a8a8a)}
|
|
263
|
+
.ncf-range::-webkit-slider-thumb{-webkit-appearance:none;width:18px;height:18px;margin-top:-8px;border-radius:50%;background:var(--card-focus-ring-color,#2276fc);border:2px solid var(--card-bg-color,#fff);box-shadow:0 0 0 1px var(--card-focus-ring-color,#2276fc)}
|
|
264
|
+
.ncf-range::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--card-focus-ring-color,#2276fc);border:2px solid var(--card-bg-color,#fff);box-shadow:0 0 0 1px var(--card-focus-ring-color,#2276fc)}
|
|
265
|
+
.ncf-range:focus-visible{outline:2px solid var(--card-focus-ring-color,#2276fc);outline-offset:4px;border-radius:4px}
|
|
266
|
+
.ncf-range-wrap{position:relative;flex:1;display:flex;align-items:center}
|
|
267
|
+
.ncf-range-wrap::before{content:"";position:absolute;left:50%;top:50%;width:2px;height:12px;margin:-6px 0 0 -1px;border-radius:1px;background:var(--card-muted-fg-color,#8a8a8a);pointer-events:none}
|
|
268
|
+
`
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import {useEffect, useState} from 'react'
|
|
2
|
+
import {useClient, useFormValue, type Path} from 'sanity'
|
|
3
|
+
|
|
4
|
+
// Valeur par défaut du composant (Réglages > Composants : valeurs par défaut) pour un
|
|
5
|
+
// champ d'une instance de section : ce dont le champ hérite quand il est vide
|
|
6
|
+
// (applyDefaults du kit côté site). Document PUBLIÉ, comme le site.
|
|
7
|
+
// Partagé par les saisies de choix (DefaultChoiceInput) et les listes (InheritedListInput).
|
|
8
|
+
|
|
9
|
+
type Defaults = Record<string, unknown> | null
|
|
10
|
+
|
|
11
|
+
const QUERY = `*[_type == $type && !(_id in path("drafts.**")) && select(defined($language) => language == $language, true)][0]`
|
|
12
|
+
const TTL = 10_000
|
|
13
|
+
|
|
14
|
+
// Une seule requête pour tous les champs d'un formulaire (cache court par type et langue).
|
|
15
|
+
const cache = new Map<string, {at: number; value: Promise<Defaults>}>()
|
|
16
|
+
function loadDefaults(client: ReturnType<typeof useClient>, type: string, language: string | null): Promise<Defaults> {
|
|
17
|
+
const key = `${type}:${language ?? ''}`
|
|
18
|
+
const hit = cache.get(key)
|
|
19
|
+
if (hit && Date.now() - hit.at < TTL) return hit.value
|
|
20
|
+
const value = client.fetch<Defaults>(QUERY, {type, language}).catch(() => null)
|
|
21
|
+
cache.set(key, {at: Date.now(), value})
|
|
22
|
+
return value
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const isKeyed = (segment: Path[number]) => typeof segment === 'object' && segment !== null && '_key' in segment
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Valeur héritée par le champ `path` (undefined : rien à hériter ici, par exemple dans le
|
|
29
|
+
* document des valeurs par défaut lui-même ou dans un élément de liste).
|
|
30
|
+
*/
|
|
31
|
+
export function useInheritedValue(path: Path, defaultsType: string, namespace: string): unknown {
|
|
32
|
+
const client = useClient({apiVersion: '2024-10-01'})
|
|
33
|
+
const docType = useFormValue(['_type']) as string | undefined
|
|
34
|
+
const language = (useFormValue(['language']) as string | undefined) ?? null
|
|
35
|
+
const keyed = path.findIndex(isKeyed)
|
|
36
|
+
const instance = useFormValue(keyed >= 0 ? path.slice(0, keyed + 1) : []) as {_type?: string} | undefined
|
|
37
|
+
const active = docType !== defaultsType && keyed >= 0
|
|
38
|
+
const [defaults, setDefaults] = useState<Defaults>(null)
|
|
39
|
+
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
if (!active) return
|
|
42
|
+
let live = true
|
|
43
|
+
loadDefaults(client, defaultsType, language).then((d) => live && setDefaults(d))
|
|
44
|
+
return () => {
|
|
45
|
+
live = false
|
|
46
|
+
}
|
|
47
|
+
}, [client, defaultsType, language, active])
|
|
48
|
+
|
|
49
|
+
const rel = path.slice(keyed + 1)
|
|
50
|
+
if (!active || !defaults || !instance?._type || rel.some(isKeyed)) return undefined
|
|
51
|
+
let node: unknown = defaults[instance._type.startsWith(namespace) ? instance._type.slice(namespace.length) : instance._type]
|
|
52
|
+
for (const segment of rel)
|
|
53
|
+
node = node && typeof node === 'object' ? (node as Record<string, unknown>)[segment as string] : undefined
|
|
54
|
+
return node
|
|
55
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import {DEFAULT_COMPONENT_DEFAULTS_TYPE} from '../../schema/componentDefaults'
|
|
2
|
+
|
|
3
|
+
/** Options de withNcfChoiceInputs (sanity.config.ts du projet). */
|
|
4
|
+
export interface NcfChoiceInputsOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Couleurs de la charte, pour les carrés de couleur (options.ncfSwatches) : la clé
|
|
7
|
+
* `colors` de web/app/lib/design-tokens.json ({jeton: {value: '#hex'}}).
|
|
8
|
+
*/
|
|
9
|
+
colors?: Record<string, {value: string}>
|
|
10
|
+
/**
|
|
11
|
+
* Niveaux de titre logiques, la même source que le site : web/app/lib/heading-levels.json
|
|
12
|
+
* ({default: 'h2', sections: {'section.hero': 'h1', ...}}).
|
|
13
|
+
*/
|
|
14
|
+
headingLevels?: {default?: string; sections?: Record<string, string>}
|
|
15
|
+
/** Type du document des valeurs par défaut (défaut : componentDefaults). */
|
|
16
|
+
defaultsType?: string
|
|
17
|
+
/** Préfixe des types de sections (défaut : « section. »). */
|
|
18
|
+
namespace?: string
|
|
19
|
+
/** Type des liens dont les champs style et size reçoivent la saisie (défaut : link). */
|
|
20
|
+
linkType?: string
|
|
21
|
+
/**
|
|
22
|
+
* Repli propre à un emplacement, quand ni l'instance ni les valeurs par défaut ne
|
|
23
|
+
* fixent la valeur : {'champParent.champ': valeur}. Ex. {'secondary.style': 'secondary'}
|
|
24
|
+
* pour un bouton secondaire, comme le site (LinkButton defaultStyle).
|
|
25
|
+
*/
|
|
26
|
+
fallbacks?: Record<string, string>
|
|
27
|
+
/** Libellés (interface du kit en anglais par défaut ; le starter les passe en français). */
|
|
28
|
+
labels?: {default?: string; reset?: string; emptyItem?: string}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ResolvedChoiceInputsOptions {
|
|
32
|
+
colors: Record<string, {value: string}>
|
|
33
|
+
headingLevels: {default: string; sections: Record<string, string>}
|
|
34
|
+
defaultsType: string
|
|
35
|
+
namespace: string
|
|
36
|
+
linkType: string
|
|
37
|
+
fallbacks: Record<string, string>
|
|
38
|
+
labels: {default: string; reset: string; emptyItem: string}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function resolveChoiceInputsOptions(input: NcfChoiceInputsOptions = {}): ResolvedChoiceInputsOptions {
|
|
42
|
+
return {
|
|
43
|
+
colors: input.colors ?? {},
|
|
44
|
+
headingLevels: {default: input.headingLevels?.default ?? 'h2', sections: input.headingLevels?.sections ?? {}},
|
|
45
|
+
defaultsType: input.defaultsType ?? DEFAULT_COMPONENT_DEFAULTS_TYPE,
|
|
46
|
+
namespace: input.namespace ?? 'section.',
|
|
47
|
+
linkType: input.linkType ?? 'link',
|
|
48
|
+
fallbacks: input.fallbacks ?? {},
|
|
49
|
+
labels: {
|
|
50
|
+
default: input.labels?.default ?? '(default)',
|
|
51
|
+
reset: input.labels?.reset ?? 'Reset',
|
|
52
|
+
emptyItem: input.labels?.emptyItem ?? 'Empty: nothing is shown',
|
|
53
|
+
},
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type {ComponentType} from 'react'
|
|
2
|
+
import {createChoiceInputs} from './ChoiceInputs'
|
|
3
|
+
import {resolveChoiceInputsOptions, type NcfChoiceInputsOptions} from './options'
|
|
4
|
+
|
|
5
|
+
type FieldLike = {
|
|
6
|
+
name?: string
|
|
7
|
+
type?: string
|
|
8
|
+
options?: {list?: unknown[]; ncfHeadingLevel?: unknown; range?: unknown}
|
|
9
|
+
components?: {input?: ComponentType<never>}
|
|
10
|
+
fields?: FieldLike[]
|
|
11
|
+
of?: FieldLike[]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Saisies de choix du kit sur les types du projet (sanity.config.ts, `schema.types`) :
|
|
16
|
+
* sections (et leur document de valeurs par défaut), champs style et size des liens.
|
|
17
|
+
* Un champ qui a déjà sa propre saisie (components.input) n'est jamais remplacé.
|
|
18
|
+
* Appliqué dans sanity.config.ts seulement : les scripts qui lisent les schémas
|
|
19
|
+
* (npm run options, defaults:fill) n'importent aucun composant React.
|
|
20
|
+
*/
|
|
21
|
+
export function withNcfChoiceInputs<T>(types: T[], options: NcfChoiceInputsOptions = {}): T[] {
|
|
22
|
+
const o = resolveChoiceInputsOptions(options)
|
|
23
|
+
const inputs = createChoiceInputs(o)
|
|
24
|
+
const choiceFor = (f: FieldLike) => (f.options?.ncfHeadingLevel ? inputs.HeadingLevelInput : inputs.DefaultChoiceInput)
|
|
25
|
+
|
|
26
|
+
function walk<F extends FieldLike>(f: F, inItem = false): F {
|
|
27
|
+
const out: FieldLike = {...f}
|
|
28
|
+
if (f.type === 'number' && f.options?.range && !f.components?.input) out.components = {...f.components, input: inputs.RangeInput}
|
|
29
|
+
else if (f.type === 'string' && f.options?.list?.length && !f.components?.input) out.components = {...f.components, input: choiceFor(f)}
|
|
30
|
+
else if (inItem && f.name && f.name !== 'anchor' && f.name !== 'alt' && (f.type === 'string' || f.type === 'text') && !f.components?.input)
|
|
31
|
+
out.components = {...f.components, input: inputs.ItemTextInput}
|
|
32
|
+
if (f.type === 'array' && f.of?.some((m) => m.type === 'object' || m.fields) && !f.components?.input)
|
|
33
|
+
out.components = {...f.components, input: inputs.InheritedListInput}
|
|
34
|
+
if (f.fields) out.fields = f.fields.map((c) => walk(c, inItem))
|
|
35
|
+
// Membres d'une liste : leurs champs sont des champs d'élément.
|
|
36
|
+
if (f.of) out.of = f.of.map((m) => walk(m, f.type === 'array' && !!m.fields))
|
|
37
|
+
return out as F
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return types.map((t) => {
|
|
41
|
+
const type = t as FieldLike
|
|
42
|
+
if (type.name?.startsWith(o.namespace) || type.name === o.defaultsType) return walk(type) as T
|
|
43
|
+
if (type.name === o.linkType)
|
|
44
|
+
return {
|
|
45
|
+
...type,
|
|
46
|
+
fields: type.fields?.map((f) =>
|
|
47
|
+
(f.name === 'style' || f.name === 'size') && f.options?.list?.length && !f.components?.input
|
|
48
|
+
? {...f, components: {...f.components, input: inputs.DefaultChoiceInput}}
|
|
49
|
+
: f,
|
|
50
|
+
),
|
|
51
|
+
} as T
|
|
52
|
+
return t
|
|
53
|
+
})
|
|
54
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -398,6 +398,8 @@ export {NcfKitUpdate} from './tools/navbar/KitUpdate'
|
|
|
398
398
|
export {NcfKitNavbar} from './tools/navbar/KitUpdateNavbar'
|
|
399
399
|
export {HelpTextStyle} from './ui/HelpTextStyle'
|
|
400
400
|
export {defineCodeEmbedType} from './form/codeEmbedType'
|
|
401
|
+
export {withNcfChoiceInputs} from './form/choices/withNcfChoiceInputs'
|
|
402
|
+
export type {NcfChoiceInputsOptions} from './form/choices/options'
|
|
401
403
|
export type {CodeEmbedTypeOptions} from './form/codeEmbedType'
|
|
402
404
|
export {CodeEditorInput, codeEditorInput} from './form/CodeEditorInput'
|
|
403
405
|
export type {CodeLanguage} from './form/CodeEditorInput'
|
|
@@ -10,7 +10,8 @@ export interface BlockCardProps {
|
|
|
10
10
|
block: BlockTypeInfo
|
|
11
11
|
occurrence: BlockOccurrence
|
|
12
12
|
namespace: string
|
|
13
|
-
|
|
13
|
+
/** Vignettes à essayer dans l'ordre (mosaïque des dispositions, puis capture simple). */
|
|
14
|
+
thumbnailUrls: string[]
|
|
14
15
|
/** Au clic : rendu réel du composant et réglage de ses valeurs par défaut. */
|
|
15
16
|
onOpen?: () => void
|
|
16
17
|
/** Renommer / ranger dans un groupe. Masqué si absent. */
|
|
@@ -26,8 +27,10 @@ export interface BlockCardProps {
|
|
|
26
27
|
* à le lire.
|
|
27
28
|
*/
|
|
28
29
|
export function BlockCard(props: BlockCardProps) {
|
|
29
|
-
const {block, occurrence, namespace,
|
|
30
|
-
const [
|
|
30
|
+
const {block, occurrence, namespace, thumbnailUrls, onOpen, onEdit} = props
|
|
31
|
+
const [attempt, setAttempt] = useState(0)
|
|
32
|
+
const thumbnailUrl = thumbnailUrls[attempt] ?? null
|
|
33
|
+
const failed = thumbnailUrls.length > 0 && attempt >= thumbnailUrls.length
|
|
31
34
|
const unused = occurrence.count === 0
|
|
32
35
|
|
|
33
36
|
return (
|
|
@@ -53,12 +56,13 @@ export function BlockCard(props: BlockCardProps) {
|
|
|
53
56
|
background: 'var(--card-muted-bg-color, rgba(127,127,127,0.08))',
|
|
54
57
|
}}
|
|
55
58
|
>
|
|
56
|
-
{thumbnailUrl
|
|
59
|
+
{thumbnailUrl ? (
|
|
57
60
|
<img
|
|
61
|
+
key={thumbnailUrl}
|
|
58
62
|
src={thumbnailUrl}
|
|
59
63
|
alt=""
|
|
60
64
|
loading="lazy"
|
|
61
|
-
onError={() =>
|
|
65
|
+
onError={() => setAttempt((n) => n + 1)}
|
|
62
66
|
style={{width: '100%', height: '100%', objectFit: 'contain', display: 'block'}}
|
|
63
67
|
/>
|
|
64
68
|
) : (
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {useMemo, useState} from 'react'
|
|
1
|
+
import {useMemo, useState, type CSSProperties} from 'react'
|
|
2
2
|
import {Box, Button, Card, Dialog, Flex, Grid, Spinner, Stack, Text, TextInput} from '@sanity/ui'
|
|
3
3
|
import {EditIcon} from '@sanity/icons/Edit'
|
|
4
4
|
import {TrashIcon} from '@sanity/icons/Trash'
|
|
@@ -27,6 +27,30 @@ const ORDERS: {value: Order; label: string}[] = [
|
|
|
27
27
|
]
|
|
28
28
|
|
|
29
29
|
/** Outil Composants, sous son provider d'organisation (groupes + noms). */
|
|
30
|
+
/**
|
|
31
|
+
* Vignette d'un composant : d'abord la MOSAÏQUE de toutes ses dispositions
|
|
32
|
+
* (`<capture>--dispositions.png`, produite par le script des captures du starter), pour
|
|
33
|
+
* voir d'un coup toutes les variantes disponibles ; à défaut, la capture simple.
|
|
34
|
+
*/
|
|
35
|
+
export function thumbnailCandidates(url: string): string[] {
|
|
36
|
+
if (url.includes('--dispositions')) return [url]
|
|
37
|
+
const mosaic = url.replace(/(\.[a-z0-9]+)(\?.*)?$/i, '--dispositions$1$2')
|
|
38
|
+
return mosaic === url ? [url] : [mosaic, url]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Vue par groupes : chaque groupe dans un cadre, un sur deux sur un fond teinté, pour
|
|
43
|
+
* distinguer les groupes d'un coup d'œil. Teinte tirée des couleurs du thème du Studio
|
|
44
|
+
* (clair et sombre).
|
|
45
|
+
*/
|
|
46
|
+
function groupStyle(index: number): CSSProperties {
|
|
47
|
+
return {
|
|
48
|
+
padding: '1rem 1.25rem 1.25rem',
|
|
49
|
+
borderRadius: '0.75rem',
|
|
50
|
+
background: index % 2 ? 'color-mix(in srgb, var(--card-fg-color) 5%, var(--card-bg-color))' : undefined,
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
30
54
|
export function ComponentsTool() {
|
|
31
55
|
return (
|
|
32
56
|
<ComponentMetaProvider>
|
|
@@ -73,7 +97,7 @@ function ComponentsToolInner() {
|
|
|
73
97
|
block={card.block}
|
|
74
98
|
occurrence={card.occurrence}
|
|
75
99
|
namespace={config.blockNamespace}
|
|
76
|
-
|
|
100
|
+
thumbnailUrls={canPreview ? thumbnailCandidates(`${config.previewUrl}${fillTemplate(preview.thumbnail, card.block.name, config.blockNamespace)}`) : []}
|
|
77
101
|
onOpen={openComponent ? () => openComponent(card.block.name) : undefined}
|
|
78
102
|
onEdit={() => setEditing(card.block.name)}
|
|
79
103
|
/>
|
|
@@ -156,8 +180,8 @@ function ComponentsToolInner() {
|
|
|
156
180
|
<SectionsMap blockTypes={named} occurrences={occurrences} pagesById={pagesById} order={order === 'schema' ? 'type' : order} />
|
|
157
181
|
) : grouping ? (
|
|
158
182
|
<Stack gap={5}>
|
|
159
|
-
{grouping.grouped.map(({group, blocks}) => (
|
|
160
|
-
<Stack key={group.id} gap={3}>
|
|
183
|
+
{grouping.grouped.map(({group, blocks}, index) => (
|
|
184
|
+
<Stack key={group.id} gap={3} data-ncf-component-group={group.id} style={groupStyle(index)}>
|
|
161
185
|
<Flex align="center" gap={2}>
|
|
162
186
|
<Text size={2} weight="semibold">
|
|
163
187
|
{group.name}
|
|
@@ -180,7 +204,7 @@ function ComponentsToolInner() {
|
|
|
180
204
|
)}
|
|
181
205
|
</Stack>
|
|
182
206
|
))}
|
|
183
|
-
<Stack gap={3}>
|
|
207
|
+
<Stack gap={3} data-ncf-component-group="" style={groupStyle(grouping.grouped.length)}>
|
|
184
208
|
<Text size={2} weight="semibold" muted>
|
|
185
209
|
Sans groupe
|
|
186
210
|
</Text>
|
package/src/version.ts
CHANGED