@nocode-factory/sanity-kit 2.8.2 → 2.9.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.
@@ -0,0 +1,142 @@
1
+ /**
2
+ * VALEURS PAR DÉFAUT DES COMPOSANTS, côté site. Module neutre (ni `'use client'`
3
+ * ni API serveur) : utilisable dans un composant serveur, un composant client et
4
+ * la configuration du client Sanity.
5
+ *
6
+ * ```ts
7
+ * import {applyDefaults, stegaFilter, reattributeTo} from '@nocode-factory/sanity-kit/web/defaults'
8
+ * ```
9
+ *
10
+ * Règle d'héritage : un champ VIDE d'une instance de section prend la valeur par
11
+ * défaut du composant (document Studio créé par `defineComponentDefaults`) ; un
12
+ * champ REMPLI est un override, jamais écrasé. La cible d'un lien (type +
13
+ * page/adresse/email...) forme un tout.
14
+ */
15
+ import {createEditUrl} from '@sanity/client/csm'
16
+ import {vercelStegaClean, vercelStegaCombine, vercelStegaDecode} from '@vercel/stega'
17
+
18
+ /** Valeurs par défaut, par type de section (`section.cta` -> objet). */
19
+ export type ComponentDefaults = Record<string, Record<string, unknown> | null | undefined>
20
+ /** Appelé sur chaque valeur héritée (chemin depuis l'instance). */
21
+ export type OnInherit = (value: unknown, path: string[]) => unknown
22
+
23
+ type Obj = Record<string, unknown>
24
+ const isEmpty = (v: unknown) => v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)
25
+ const isPlainObject = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)
26
+
27
+ const LINK_TYPES = new Set(['link', 'cardLink'])
28
+ const LINK_TARGET = ['type', 'page', 'fixedPath', 'href', 'email', 'phone', 'file']
29
+ const hasTarget = (l: Obj) =>
30
+ ['page', 'fixedPath', 'href', 'email', 'phone'].some((k) => !isEmpty(l[k])) || !!(l.file as Obj | undefined)?.asset
31
+
32
+ /** Complète les champs vides de `instance` avec `defaults`, récursivement. */
33
+ export function inherit<T>(instance: T, defaults: unknown, onInherit?: OnInherit, prefix: string[] = []): T {
34
+ if (!isPlainObject(defaults)) return instance
35
+ if (!isPlainObject(instance)) return (isEmpty(instance) ? (onInherit ? onInherit(defaults, prefix) : defaults) : instance) as T
36
+ const out: Obj = {...instance}
37
+ for (const [key, value] of Object.entries(defaults)) {
38
+ if (key.startsWith('_')) continue
39
+ const own = out[key]
40
+ if (isEmpty(own)) out[key] = onInherit ? onInherit(value, [...prefix, key]) : value
41
+ else if (isPlainObject(own) && isPlainObject(value) && !own._ref) out[key] = inherit(own, value, onInherit, [...prefix, key])
42
+ }
43
+ const isLink = LINK_TYPES.has(String(out._type ?? '')) || LINK_TYPES.has(String(defaults._type ?? ''))
44
+ if (isLink && !hasTarget(instance as Obj) && hasTarget(defaults)) {
45
+ for (const key of LINK_TARGET) if (key in defaults) out[key] = onInherit ? onInherit(defaults[key], [...prefix, key]) : defaults[key]
46
+ }
47
+ return out as T
48
+ }
49
+
50
+ /** Section avec les valeurs par défaut de son composant appliquées. */
51
+ export function applyDefaults<S extends {_type: string}>(section: S, defaults: ComponentDefaults | null | undefined, onInherit?: OnInherit): S {
52
+ return inherit(section, defaults?.[section._type], onInherit)
53
+ }
54
+
55
+ /**
56
+ * Requête GROQ des valeurs par défaut (paramètre `$locale`), une clé par type de
57
+ * section, avec la projection des sections du projet (liens, images, références
58
+ * résolus comme dans une page).
59
+ */
60
+ export function componentDefaultsQuery(sectionTypes: readonly string[], sectionProjection: string, options: {type?: string; namespace?: string; languageField?: string} = {}): string {
61
+ const {type = 'componentDefaults', namespace = 'section.', languageField = 'language'} = options
62
+ const fields = sectionTypes
63
+ .filter((t) => t.startsWith(namespace) && /^\w+$/.test(t.slice(namespace.length)))
64
+ .map((t) => `"${t}": ${t.slice(namespace.length)}{${sectionProjection}}`)
65
+ .join(',\n')
66
+ return `*[_type == "${type}" && ${languageField} == $locale][0]{${fields}}`
67
+ }
68
+
69
+ /* --- Preview (édition visuelle) --- */
70
+
71
+ /**
72
+ * Valeurs JAMAIS encodées par le stega : champs d'options et valeurs
73
+ * « identifiant ». Encodée, une valeur d'option (« md », « secondary »,
74
+ * « eclat ») n'est plus reconnue en preview et le site retombe sur la valeur par
75
+ * défaut : une taille de bouton, un fond ou une texture modifiés ne s'affichent pas.
76
+ */
77
+ export const STEGA_OPTION_RULES = {
78
+ fields: ['style', 'size', 'variant', 'kind', 'layout', 'align', 'tone', 'theme', 'format', 'texture', 'token', 'customHex', 'background', 'color', 'type', 'fixedPath', 'href', 'email', 'phone', 'language', 'slug', 'current', 'search'],
79
+ identifier: '^[a-z][a-z0-9-]{0,31}$',
80
+ } as const
81
+
82
+ const OPTION_FIELDS: ReadonlySet<string> = new Set(STEGA_OPTION_RULES.fields)
83
+ const IDENTIFIER = new RegExp(STEGA_OPTION_RULES.identifier)
84
+
85
+ export function isOptionValue(path: readonly unknown[], value: string): boolean {
86
+ const field = [...path].reverse().find((p): p is string => typeof p === 'string')
87
+ return (field !== undefined && OPTION_FIELDS.has(field)) || IDENTIFIER.test(value)
88
+ }
89
+
90
+ /** Filtre stega du client Sanity : `stega: {studioUrl, filter: stegaFilter}`. */
91
+ export function stegaFilter<P extends {sourcePath: readonly unknown[]; value: string; filterDefault: (props: P) => boolean}>(props: P): boolean {
92
+ return isOptionValue(props.sourcePath, props.value) ? false : props.filterDefault(props)
93
+ }
94
+
95
+ /**
96
+ * Où vit une instance : document (id, type) et chemin du champ qui la contient
97
+ * (une liste de sections, ou `single` : un champ qui EST la section).
98
+ */
99
+ export type SectionSource = {id: string; type: string; path: string; single?: boolean}
100
+
101
+ const decode = (s: string): {origin?: string; href?: string} | undefined => {
102
+ try {
103
+ return vercelStegaDecode(s) as {origin?: string; href?: string} | undefined
104
+ } catch {
105
+ return undefined
106
+ }
107
+ }
108
+
109
+ /**
110
+ * PREVIEW : une valeur héritée porte l'adresse du document des valeurs par
111
+ * défaut ; un clic dans Presentation ouvrirait ce document. Ce rappel (à passer
112
+ * à `applyDefaults` en mode brouillon) réétiquette chaque texte hérité vers le
113
+ * champ de l'INSTANCE dans la page, au format de Sanity : le clic ouvre
114
+ * l'instance, qui affiche la valeur héritée et permet de la surcharger.
115
+ */
116
+ export function reattributeTo(source: SectionSource, key?: string): OnInherit {
117
+ const base = key && !source.single ? `${source.path}[_key=="${key}"]` : source.path
118
+ const retag = (value: unknown, field: string): unknown => {
119
+ if (typeof value === 'string') {
120
+ const info = decode(value)
121
+ if (!info?.href) return value // valeur d'option, jamais encodée
122
+ const url = new URL(info.href, 'https://studio.invalid')
123
+ const baseUrl = url.searchParams.get('baseUrl')
124
+ if (!baseUrl) return value
125
+ const href = createEditUrl({
126
+ baseUrl,
127
+ workspace: url.searchParams.get('workspace') ?? undefined,
128
+ tool: url.searchParams.get('tool') ?? undefined,
129
+ // Identifiant de brouillon : pas de perspective imposée, Presentation garde la sienne.
130
+ id: `drafts.${source.id.replace(/^drafts\./, '')}`,
131
+ type: source.type,
132
+ path: `${base}.${field}`,
133
+ })
134
+ return vercelStegaCombine(vercelStegaClean(value), {origin: info.origin ?? 'sanity.io', href})
135
+ }
136
+ if (Array.isArray(value)) return value.map((v) => retag(v, field))
137
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, retag(v, field)]))
138
+ return value
139
+ }
140
+ // Le clic ouvre le champ de premier niveau de l'instance (celui qui hérite).
141
+ return (value, path) => retag(value, path[0] ?? '')
142
+ }