@nocode-factory/sanity-kit 2.56.0 → 2.59.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.
Files changed (47) hide show
  1. package/README.md +45 -8
  2. package/bin/item-types.mjs +131 -0
  3. package/bin/ncf-kit.mjs +121 -2
  4. package/dist/{finalUrl-IXF3zbT9.js → finalUrl-DYyjKCjh.js} +2 -1
  5. package/dist/finalUrl-DYyjKCjh.js.map +1 -0
  6. package/dist/{fixCrossLanguageReferences-CDczoic9.js → fixCrossLanguageReferences-C4A61VWW.js} +2 -2
  7. package/dist/{fixCrossLanguageReferences-CDczoic9.js.map → fixCrossLanguageReferences-C4A61VWW.js.map} +1 -1
  8. package/dist/{fixCrossLanguageReferences-C1VsmGsJ.d.ts → fixCrossLanguageReferences-CfFDSTD5.d.ts} +8 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.js +7240 -7011
  11. package/dist/index.js.map +1 -1
  12. package/dist/inherited-DZvM35P6.js +101 -0
  13. package/dist/inherited-DZvM35P6.js.map +1 -0
  14. package/dist/jsonld.js +1 -1
  15. package/dist/protocol-Bl7Yj2Ro.js +31 -0
  16. package/dist/protocol-Bl7Yj2Ro.js.map +1 -0
  17. package/dist/schema.d.ts +1 -1
  18. package/dist/schema.js +2 -2
  19. package/dist/web-edit.d.ts +192 -0
  20. package/dist/web-edit.js +144 -0
  21. package/dist/web-edit.js.map +1 -0
  22. package/dist/web-editing.d.ts +51 -0
  23. package/dist/web-editing.js +693 -0
  24. package/dist/web-editing.js.map +1 -0
  25. package/package.json +22 -2
  26. package/scripts/use-client.mjs +1 -1
  27. package/src/config/resolve.ts +1 -0
  28. package/src/config/types.ts +7 -1
  29. package/src/form/AssetSourceBrowser.tsx +68 -39
  30. package/src/index.ts +12 -5
  31. package/src/lib/i18nTemplates.ts +38 -4
  32. package/src/tools/collections/CollectionTable.tsx +116 -89
  33. package/src/tools/presentation/PagesNavigator.tsx +150 -56
  34. package/src/ui/PreviewEditBridge.tsx +74 -0
  35. package/src/version.ts +1 -1
  36. package/src/web/edit/ImageReplaceLayer.tsx +174 -0
  37. package/src/web/edit/InlineTextEditor.tsx +365 -0
  38. package/src/web/edit/InlineTextOverlay.tsx +43 -0
  39. package/src/web/edit/PreviewEditing.tsx +191 -0
  40. package/src/web/edit/index.ts +18 -0
  41. package/src/web/edit/inherited.ts +174 -0
  42. package/src/web/edit/labels.ts +37 -0
  43. package/src/web/edit/protocol.ts +47 -0
  44. package/src/web/edit/store.ts +98 -0
  45. package/src/web/edit/targets.ts +186 -0
  46. package/src/web/editing.ts +18 -0
  47. package/dist/finalUrl-IXF3zbT9.js.map +0 -1
@@ -0,0 +1,191 @@
1
+ import {useEffect, useRef, useState} from 'react'
2
+ import type {OverlayComponentResolver} from '@sanity/visual-editing'
3
+ import {ImageReplaceLayer} from './ImageReplaceLayer'
4
+ import {InlineTextEditor} from './InlineTextEditor'
5
+ import {InlineTextOverlay} from './InlineTextOverlay'
6
+ import {CHIP, FONT, DEFAULT_PREVIEW_EDITING_LABELS, type PreviewEditingLabels} from './labels'
7
+ import {EDIT_MODE_ATTRIBUTE, EDIT_MODE_STORAGE_KEY, PREVIEW_EDIT_ATTRIBUTE, isEditMode, isInlineEditablePath, setEditModeResolver} from './store'
8
+
9
+ /**
10
+ * ÉDITION SUR PLACE dans l'aperçu (Presentation), à monter à côté de
11
+ * `<VisualEditing/>` en mode brouillon :
12
+ *
13
+ * ```tsx
14
+ * <VisualEditing refresh={useNcfPreviewRefresh()} components={ncfOverlayComponents} />
15
+ * <NcfPreviewEditing labels={messages.previewEditing} />
16
+ * ```
17
+ *
18
+ * - texte (champ chaîne, ligne d'un titre en texte riche) : crayon au survol, au
19
+ * clic un champ de saisie à sa place exacte ; enregistré dans le brouillon ;
20
+ * - image : « Replace this image » au survol, au clic le Studio ouvre la
21
+ * médiathèque (pont monté par le plugin du kit) ;
22
+ * - « Mode édition / Mode visite » : en visite, un clic suit les liens.
23
+ */
24
+ export const ncfOverlayComponents: OverlayComponentResolver = (context) => {
25
+ if (isEditMode() && isInlineEditablePath(context.type, context.node.path, context.element)) return InlineTextOverlay
26
+ return undefined
27
+ }
28
+
29
+ export type NcfPreviewEditingProps = {
30
+ /** Libellés (anglais par défaut) : passer ceux de la langue du projet. */
31
+ labels?: Partial<PreviewEditingLabels>
32
+ /**
33
+ * `'toggle'` (défaut) : interrupteur « Edit mode / Browse mode » du kit, en bas
34
+ * à gauche de l'aperçu, mémorisé. Une fonction : le projet décide (ex. son propre
35
+ * interrupteur d'animations) ; le kit n'affiche alors rien.
36
+ */
37
+ editMode?: 'toggle' | (() => boolean)
38
+ }
39
+
40
+ /**
41
+ * En mode édition, la zone cliquable étendue d'un lien (carte entièrement
42
+ * cliquable : `a::after` en plein cadre) est transparente à la souris : texte et
43
+ * images de la carte redeviennent atteignables.
44
+ */
45
+ const EDIT_CSS = `html[${PREVIEW_EDIT_ATTRIBUTE}] a::after, html[${PREVIEW_EDIT_ATTRIBUTE}] a::before { pointer-events: none !important; }`
46
+
47
+ export function NcfPreviewEditing({labels, editMode = 'toggle'}: NcfPreviewEditingProps) {
48
+ const text = {...DEFAULT_PREVIEW_EDITING_LABELS, ...labels}
49
+ const custom = typeof editMode === 'function' ? editMode : null
50
+ // Dernière fonction du projet, sans relancer l'effet à chaque rendu.
51
+ const customRef = useRef(custom)
52
+ customRef.current = custom
53
+ const hasCustom = custom !== null
54
+ useOverlayRectRefresh()
55
+
56
+ useEffect(() => {
57
+ setEditModeResolver(hasCustom ? () => customRef.current?.() ?? false : null)
58
+ const root = document.documentElement
59
+ // Ne touche l'attribut que s'il doit changer : l'observateur ci-dessous ne se
60
+ // relance pas lui-même.
61
+ const sync = () => {
62
+ const want = isEditMode()
63
+ if (want && !root.hasAttribute(PREVIEW_EDIT_ATTRIBUTE)) root.setAttribute(PREVIEW_EDIT_ATTRIBUTE, '')
64
+ else if (!want && root.hasAttribute(PREVIEW_EDIT_ATTRIBUTE)) root.removeAttribute(PREVIEW_EDIT_ATTRIBUTE)
65
+ }
66
+ sync()
67
+ // Le mode peut changer sans rechargement (interrupteur du kit ou du projet,
68
+ // qui posent un attribut sur <html>) : on resynchronise à chaque changement.
69
+ const observer = new MutationObserver(sync)
70
+ observer.observe(root, {attributes: true})
71
+ return () => {
72
+ observer.disconnect()
73
+ root.removeAttribute(PREVIEW_EDIT_ATTRIBUTE)
74
+ setEditModeResolver(null)
75
+ }
76
+ }, [hasCustom])
77
+
78
+ return (
79
+ <>
80
+ <style>{EDIT_CSS}</style>
81
+ <InlineTextEditor labels={text} />
82
+ <ImageReplaceLayer label={text.replaceImage} />
83
+ {!hasCustom && <EditModeToggle labels={text} />}
84
+ </>
85
+ )
86
+ }
87
+
88
+ /** Interrupteur « Edit mode / Browse mode » : affiché dans l'aperçu du Studio seulement. */
89
+ function EditModeToggle({labels}: {labels: PreviewEditingLabels}) {
90
+ const [embedded, setEmbedded] = useState(false)
91
+ const [edit, setEdit] = useState(true)
92
+
93
+ useEffect(() => {
94
+ let inFrame = true
95
+ try {
96
+ inFrame = window.self !== window.top
97
+ } catch {
98
+ inFrame = true
99
+ }
100
+ setEmbedded(inFrame)
101
+ let stored: string | null = null
102
+ try {
103
+ stored = window.localStorage.getItem(EDIT_MODE_STORAGE_KEY)
104
+ } catch {
105
+ stored = null
106
+ }
107
+ const next = stored !== 'browse'
108
+ setEdit(next)
109
+ document.documentElement.setAttribute(EDIT_MODE_ATTRIBUTE, next ? 'edit' : 'browse')
110
+ return () => document.documentElement.removeAttribute(EDIT_MODE_ATTRIBUTE)
111
+ }, [])
112
+
113
+ if (!embedded) return null
114
+ const toggle = () => {
115
+ const next = !edit
116
+ setEdit(next)
117
+ document.documentElement.setAttribute(EDIT_MODE_ATTRIBUTE, next ? 'edit' : 'browse')
118
+ try {
119
+ window.localStorage.setItem(EDIT_MODE_STORAGE_KEY, next ? 'edit' : 'browse')
120
+ } catch {
121
+ // Stockage indisponible : le choix vaut pour cette page seulement.
122
+ }
123
+ }
124
+
125
+ return (
126
+ <button
127
+ type="button"
128
+ role="switch"
129
+ aria-checked={edit}
130
+ aria-label={labels.modeLabel}
131
+ onClick={toggle}
132
+ data-sanity-overlay-element
133
+ style={{
134
+ position: 'fixed',
135
+ left: 16,
136
+ bottom: 16,
137
+ zIndex: 2147482500,
138
+ display: 'flex',
139
+ alignItems: 'center',
140
+ gap: 8,
141
+ padding: '8px 14px 8px 10px',
142
+ border: 0,
143
+ borderRadius: 999,
144
+ background: CHIP,
145
+ color: '#fff',
146
+ boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
147
+ font: `500 12px/1 ${FONT}`,
148
+ cursor: 'pointer',
149
+ }}
150
+ >
151
+ <span aria-hidden style={{width: 8, height: 8, borderRadius: 999, background: edit ? '#3ecf8e' : 'rgba(255,255,255,0.45)'}} />
152
+ {edit ? labels.editMode : labels.browseMode}
153
+ </button>
154
+ )
155
+ }
156
+
157
+ /**
158
+ * Cadres de Sanity à la bonne place. L'overlay mémorise la position de chaque
159
+ * élément et ne la remesure qu'au redimensionnement : une page qui se décale
160
+ * après le chargement (photos différées, effets liés au défilement) laissait les
161
+ * cadres à l'ancienne place. On demande la remesure quand la hauteur de la page
162
+ * change, quand une image finit de charger et à la fin d'un défilement, par le
163
+ * signal que Sanity écoute déjà : un événement « scroll » sur <body> (il ne
164
+ * remonte pas jusqu'à la fenêtre : aucun effet de défilement ne le reçoit).
165
+ */
166
+ function useOverlayRectRefresh() {
167
+ useEffect(() => {
168
+ let frame = 0
169
+ let timer = 0
170
+ const refresh = () => {
171
+ cancelAnimationFrame(frame)
172
+ frame = requestAnimationFrame(() => document.body.dispatchEvent(new Event('scroll')))
173
+ }
174
+ const onScroll = () => {
175
+ window.clearTimeout(timer)
176
+ timer = window.setTimeout(refresh, 120)
177
+ }
178
+ const ro = new ResizeObserver(refresh)
179
+ ro.observe(document.body)
180
+ window.addEventListener('scroll', onScroll, {passive: true})
181
+ document.addEventListener('load', refresh, true)
182
+ refresh()
183
+ return () => {
184
+ ro.disconnect()
185
+ cancelAnimationFrame(frame)
186
+ window.clearTimeout(timer)
187
+ window.removeEventListener('scroll', onScroll)
188
+ document.removeEventListener('load', refresh, true)
189
+ }
190
+ }, [])
191
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * ÉDITION DANS L'APERÇU, côté données. Module neutre (ni `'use client'` ni API
3
+ * serveur) : requêtes en brouillon, `<Sections/>`, composants d'image.
4
+ *
5
+ * ```ts
6
+ * import {annotateImageEditTargets, withPreviewEditTargets, rekeyOwnImageTargets, imageEditAttributes, imageAlt, inheritedEditScriptProps} from '@nocode-factory/sanity-kit/web/edit'
7
+ * ```
8
+ *
9
+ * Les composants (éditeur, pastille d'image, interrupteur) sont dans
10
+ * `@nocode-factory/sanity-kit/web` (`NcfPreviewEditing`, `ncfOverlayComponents`).
11
+ * Dépendances : `@sanity/visual-editing` (fourni par next-sanity).
12
+ */
13
+ export {annotateImageEditTargets, withPreviewEditTargets, rekeyOwnImageTargets, imageEditAttributes, imageAlt} from './targets'
14
+ export type {ImageEditValue, ImageEditOptions, ImageEditAttributes} from './targets'
15
+ export {retagInheritedList, inheritedEditScriptProps, inheritedListValue, materializeInheritedList} from './inherited'
16
+ export type {InheritedEdit} from './inherited'
17
+ export {REPLACE_IMAGE_MESSAGE, isReplaceImageRequest, replaceImagePatch} from './protocol'
18
+ export type {ReplaceImageRequest} from './protocol'
@@ -0,0 +1,174 @@
1
+ import {vercelStegaClean, vercelStegaCombine, vercelStegaDecode} from '@vercel/stega'
2
+ import {createEditUrl} from '@sanity/client/csm'
3
+
4
+ /**
5
+ * ÉDITION DANS L'APERÇU, valeurs HÉRITÉES des valeurs par défaut du composant
6
+ * (champ vide dans la page : le site affiche la valeur par défaut).
7
+ *
8
+ * `reattributeTo` fait déjà pointer chaque texte hérité vers le champ de
9
+ * l'INSTANCE (et non vers le document des valeurs par défaut). Ici, deux cas que
10
+ * Sanity ne sait pas éditer sur place :
11
+ *
12
+ * - **Texte hérité** (`value`) : l'éditeur doit partir de la valeur par défaut
13
+ * EXACTE, jamais du texte affiché que le composant met en forme (guillemets
14
+ * ajoutés, retours à la ligne rendus en espaces).
15
+ * - **Liste héritée** (`items`) : liste SIMPLE (textes, nombres, cases) ou TEXTE
16
+ * RICHE sans lien (titre en lignes, italique). La page n'a pas encore ses
17
+ * éléments, Sanity n'y active aucun composant. Chaque texte vise sa ligne exacte
18
+ * (`…titleLines[_key=="k"].text`, `…title[_key=="b"].children[_key=="s"].text`) ;
19
+ * à l'enregistrement, la liste par défaut est RECOPIÉE dans la page avec la
20
+ * ligne modifiée, en un seul patch du brouillon (comme « Edit default items »).
21
+ * La valeur par défaut du composant ne change jamais.
22
+ *
23
+ * Une liste avec liens, images ou références reste gérée dans le panneau : la
24
+ * recopier depuis l'aperçu risquerait d'abîmer les données.
25
+ *
26
+ * Ces entrées sont jointes à la page en mode brouillon seulement
27
+ * (`<script type="application/json" data-ncf-inherited-…>`, voir
28
+ * `inheritedEditScriptProps`).
29
+ */
30
+ export type InheritedEdit = {path: string; items: Record<string, unknown>[]} | {path: string; value: string}
31
+
32
+ type Source = {id: string; type: string}
33
+
34
+ const isPrimitive = (v: unknown) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
35
+
36
+ function isSimpleList(value: unknown): value is Record<string, unknown>[] {
37
+ return (
38
+ Array.isArray(value) &&
39
+ value.length > 0 &&
40
+ value.every(
41
+ (item) =>
42
+ item &&
43
+ typeof item === 'object' &&
44
+ !Array.isArray(item) &&
45
+ typeof (item as {_key?: unknown})._key === 'string' &&
46
+ (item as {_type?: unknown})._type !== 'block' &&
47
+ Object.entries(item as Record<string, unknown>).every(([k, v]) => (k.startsWith('_') ? k === '_key' || k === '_type' : isPrimitive(v))),
48
+ )
49
+ )
50
+ }
51
+
52
+ type Block = {_key: string; _type: 'block'; children: {_key: string; _type: 'span'; text: string}[]; markDefs?: unknown[]}
53
+ function isPlainBlocks(value: unknown): value is Block[] {
54
+ return (
55
+ Array.isArray(value) &&
56
+ value.length > 0 &&
57
+ value.every(
58
+ (b) =>
59
+ b?._type === 'block' &&
60
+ typeof b._key === 'string' &&
61
+ !b.markDefs?.length &&
62
+ Array.isArray(b.children) &&
63
+ b.children.every(
64
+ (c: {_type?: unknown; _key?: unknown; text?: unknown}) => c?._type === 'span' && typeof c._key === 'string' && typeof c.text === 'string',
65
+ ),
66
+ )
67
+ )
68
+ }
69
+
70
+ /** Réétiquette un texte (stega) vers un autre chemin du document de la page. */
71
+ function retag(text: string, source: Source, path: string): string {
72
+ const info = vercelStegaDecode(text) as {origin?: string; href?: string} | undefined
73
+ if (!info?.href) return text
74
+ const url = new URL(info.href, 'https://studio.invalid')
75
+ const baseUrl = url.searchParams.get('baseUrl')
76
+ if (!baseUrl) return text
77
+ const href = createEditUrl({
78
+ baseUrl,
79
+ workspace: url.searchParams.get('workspace') ?? undefined,
80
+ tool: url.searchParams.get('tool') ?? undefined,
81
+ id: `drafts.${source.id.replace(/^drafts\./, '')}`,
82
+ type: source.type,
83
+ path,
84
+ })
85
+ return vercelStegaCombine(vercelStegaClean(text), {origin: info.origin ?? 'sanity.io', href})
86
+ }
87
+
88
+ /**
89
+ * Liste héritée (déjà réétiquetée par `reattributeTo`) : renvoie la liste avec
90
+ * chaque texte pointé vers sa ligne et inscrit la liste par défaut (textes
91
+ * nettoyés) dans `collected`. Toute autre valeur est rendue telle quelle.
92
+ */
93
+ export function retagInheritedList(value: unknown, listPath: string, source: Source, collected: InheritedEdit[]): unknown {
94
+ if (isPlainBlocks(value)) {
95
+ collected.push({path: listPath, items: vercelStegaClean(value) as Record<string, unknown>[]})
96
+ return value.map((b) => ({
97
+ ...b,
98
+ children: b.children.map((c) => ({...c, text: retag(c.text, source, `${listPath}[_key=="${b._key}"].children[_key=="${c._key}"].text`)})),
99
+ }))
100
+ }
101
+ if (!isSimpleList(value)) return value
102
+ collected.push({
103
+ path: listPath,
104
+ items: value.map((item) => Object.fromEntries(Object.entries(item).map(([k, v]) => [k, typeof v === 'string' ? vercelStegaClean(v) : v]))),
105
+ })
106
+ return value.map((item) =>
107
+ Object.fromEntries(
108
+ Object.entries(item).map(([k, v]) => [k, typeof v === 'string' && !k.startsWith('_') ? retag(v, source, `${listPath}[_key=="${item._key as string}"].${k}`) : v]),
109
+ ),
110
+ )
111
+ }
112
+
113
+ /** Attributs du `<script>` qui joint une entrée héritée à la page (mode brouillon). */
114
+ export function inheritedEditScriptProps(entry: InheritedEdit) {
115
+ return {
116
+ type: 'application/json',
117
+ ...('items' in entry ? {'data-ncf-inherited-list': entry.path} : {'data-ncf-inherited-value': entry.path}),
118
+ dangerouslySetInnerHTML: {__html: JSON.stringify('items' in entry ? entry.items : entry.value).replace(/</g, '\\u003c')},
119
+ }
120
+ }
121
+
122
+ /* ------------------------------------------------------------------------- */
123
+ /* Côté éditeur : lecture et recopie (pur, testé) */
124
+ /* ------------------------------------------------------------------------- */
125
+
126
+ type Step = {key: string} | {field: string}
127
+
128
+ /** Étapes d'un chemin RELATIF à la liste : `[_key=="b"].children[_key=="s"].text`. */
129
+ function steps(listPath: string, path: string): Step[] | null {
130
+ if (!path.startsWith(`${listPath}[`)) return null
131
+ const rest = path.slice(listPath.length)
132
+ const out: Step[] = []
133
+ let consumed = 0
134
+ for (const m of rest.matchAll(/\[_key=="([^"]+)"\]|\.(\w+)/g)) {
135
+ if (m.index !== consumed) return null
136
+ consumed += m[0].length
137
+ out.push(m[1] ? {key: m[1]} : {field: m[2] as string})
138
+ }
139
+ return consumed === rest.length && out.length > 0 && 'key' in out[0]! ? out : null
140
+ }
141
+
142
+ /** Texte exact d'une ligne de liste héritée, ou null. */
143
+ export function inheritedListValue(list: {path: string; items: Record<string, unknown>[]}, path: string): string | null {
144
+ const s = steps(list.path, path)
145
+ if (!s) return null
146
+ let value: unknown = list.items
147
+ for (const step of s) {
148
+ if ('key' in step) value = Array.isArray(value) ? value.find((v) => v?._key === step.key) : undefined
149
+ else value = value && typeof value === 'object' ? (value as Record<string, unknown>)[step.field] : undefined
150
+ }
151
+ return typeof value === 'string' ? value : null
152
+ }
153
+
154
+ /** Liste par défaut recopiée avec la ligne `path` remplacée par `next`, ou null. */
155
+ export function materializeInheritedList(list: {path: string; items: Record<string, unknown>[]}, path: string, next: string): Record<string, unknown>[] | null {
156
+ const s = steps(list.path, path)
157
+ if (!s) return null
158
+ const write = (value: unknown, i: number): unknown => {
159
+ if (i === s.length) return next
160
+ const step = s[i]!
161
+ if ('key' in step) {
162
+ if (!Array.isArray(value) || !value.some((v) => v?._key === step.key)) throw new Error('absent')
163
+ return value.map((v) => (v?._key === step.key ? write(v, i + 1) : v))
164
+ }
165
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('absent')
166
+ const obj = value as Record<string, unknown>
167
+ return {...obj, [step.field]: write(obj[step.field], i + 1)}
168
+ }
169
+ try {
170
+ return write(list.items, 0) as Record<string, unknown>[]
171
+ } catch {
172
+ return null
173
+ }
174
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Libellés de l'édition sur place. Anglais par défaut (interface du kit) ; un
3
+ * projet passe les siens (fichier de textes de sa langue) à `NcfPreviewEditing`.
4
+ */
5
+ export type PreviewEditingLabels = {
6
+ /** Nom accessible du champ de saisie. */
7
+ fieldLabel: string
8
+ save: string
9
+ cancel: string
10
+ /** Affiché le temps que l'aperçu montre la nouvelle valeur. */
11
+ saved: string
12
+ /** Sous un texte hérité des valeurs par défaut du composant. */
13
+ inheritedNote: string
14
+ /** Pastille au survol d'une image. */
15
+ replaceImage: string
16
+ /** Interrupteur du kit (mode `toggle`). */
17
+ editMode: string
18
+ browseMode: string
19
+ modeLabel: string
20
+ }
21
+
22
+ export const DEFAULT_PREVIEW_EDITING_LABELS: PreviewEditingLabels = {
23
+ fieldLabel: 'Edit text',
24
+ save: 'Save',
25
+ cancel: 'Cancel',
26
+ saved: 'Saved to draft',
27
+ inheritedNote: 'Component default text: editing it here creates text specific to this page.',
28
+ replaceImage: 'Replace this image',
29
+ editMode: 'Edit mode',
30
+ browseMode: 'Browse mode',
31
+ modeLabel: 'Preview mode: edit or browse',
32
+ }
33
+
34
+ /** Couleurs : surchargeables par le projet (variables CSS sur :root). */
35
+ export const ACCENT = 'var(--ncf-edit-accent, #2276fc)'
36
+ export const CHIP = 'var(--ncf-edit-chip, #1b1d21)'
37
+ export const FONT = 'var(--ncf-edit-font, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif)'
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Message « remplacer cette image » envoyé par l'aperçu (Presentation) au Studio.
3
+ *
4
+ * Partagé par le front (`NcfPreviewEditing`, couche des images) et le Studio
5
+ * (pont monté par le plugin, qui ouvre la médiathèque). Module pur : ni React,
6
+ * ni `sanity`, importable des deux côtés.
7
+ */
8
+ export const REPLACE_IMAGE_MESSAGE = 'ncf-kit/replace-image'
9
+
10
+ export type ReplaceImageRequest = {
11
+ type: typeof REPLACE_IMAGE_MESSAGE
12
+ /** Document à modifier (sans préfixe `drafts.`). */
13
+ documentId: string
14
+ /** Type du document, quand le front le connaît ; sinon le Studio le lit. */
15
+ documentType: string | null
16
+ /** Chemin EXACT du champ image (`sections[_key=="a"].items[_key=="b"].image`). */
17
+ path: string
18
+ }
19
+
20
+ /** Chemin de champ Sanity sûr : lettres, chiffres, clés entre guillemets, rien d'autre. */
21
+ const SAFE_PATH = /^[A-Za-z0-9_\-.[\]="]+$/
22
+
23
+ /** Le message reçu est-il une demande de remplacement bien formée ? */
24
+ export function isReplaceImageRequest(data: unknown): data is ReplaceImageRequest {
25
+ if (!data || typeof data !== 'object') return false
26
+ const d = data as Record<string, unknown>
27
+ return (
28
+ d.type === REPLACE_IMAGE_MESSAGE &&
29
+ typeof d.documentId === 'string' &&
30
+ d.documentId.length > 0 &&
31
+ typeof d.path === 'string' &&
32
+ SAFE_PATH.test(d.path) &&
33
+ (d.documentType === null || d.documentType === undefined || typeof d.documentType === 'string')
34
+ )
35
+ }
36
+
37
+ /**
38
+ * Patch du remplacement : l'image choisie remplace celle du champ. Cadrage et
39
+ * point focal sont retirés : calés sur l'ancienne photo, ils seraient faux.
40
+ */
41
+ export function replaceImagePatch(path: string, assetId: string) {
42
+ return [
43
+ {setIfMissing: {[path]: {_type: 'image'}}},
44
+ {set: {[`${path}.asset`]: {_type: 'reference', _ref: assetId}}},
45
+ {unset: [`${path}.crop`, `${path}.hotspot`]},
46
+ ]
47
+ }
@@ -0,0 +1,98 @@
1
+ import type {SanityNode} from '@sanity/visual-editing'
2
+ import {VERCEL_STEGA_REGEX} from '@vercel/stega'
3
+
4
+ /**
5
+ * État partagé de l'édition sur place (aperçu en mode brouillon seulement).
6
+ * - « survolé » : le texte que l'overlay de Sanity encadre (posé par
7
+ * `InlineTextOverlay`, monté par Sanity au survol seulement) ;
8
+ * - « en cours » : le texte ouvert dans l'éditeur. L'éditeur vit hors de l'arbre
9
+ * des overlays : Sanity démonte ses composants dès que la souris quitte
10
+ * l'élément, la saisie ne doit pas dépendre du survol.
11
+ */
12
+ export type InlineTarget = {element: HTMLElement; node: SanityNode}
13
+
14
+ let hovered: InlineTarget | null = null
15
+ let editing: InlineTarget | null = null
16
+ const listeners = new Set<() => void>()
17
+ const emit = () => listeners.forEach((l) => l())
18
+
19
+ export const inlineEdit = {
20
+ subscribe(listener: () => void) {
21
+ listeners.add(listener)
22
+ return () => listeners.delete(listener)
23
+ },
24
+ getHovered: () => hovered,
25
+ getEditing: () => editing,
26
+ setHovered(target: InlineTarget | null) {
27
+ hovered = target
28
+ },
29
+ clearHovered(element: HTMLElement) {
30
+ if (hovered?.element === element) hovered = null
31
+ },
32
+ open(target: InlineTarget) {
33
+ editing = target
34
+ emit()
35
+ },
36
+ close() {
37
+ editing = null
38
+ emit()
39
+ },
40
+ }
41
+
42
+ /* ------------------------------------------------------------------------- */
43
+ /* Mode édition / mode visite */
44
+ /* ------------------------------------------------------------------------- */
45
+
46
+ /**
47
+ * « Mode édition » : texte et images se modifient sur place. « Mode visite » : un
48
+ * clic suit les liens (cartes, boutons), comme sur le site. Par défaut, le kit
49
+ * affiche son interrupteur dans l'aperçu ; un projet peut brancher le sien
50
+ * (`editMode` de `NcfPreviewEditing`, ex. un interrupteur d'animations).
51
+ */
52
+ export const EDIT_MODE_ATTRIBUTE = 'data-ncf-edit-mode'
53
+ export const PREVIEW_EDIT_ATTRIBUTE = 'data-ncf-preview-edit'
54
+ export const EDIT_MODE_STORAGE_KEY = 'ncf-preview-mode'
55
+
56
+ const defaultEditMode = () => typeof document !== 'undefined' && document.documentElement.getAttribute(EDIT_MODE_ATTRIBUTE) !== 'browse'
57
+ let editModeResolver: () => boolean = defaultEditMode
58
+
59
+ export function setEditModeResolver(resolver: (() => boolean) | null) {
60
+ editModeResolver = resolver ?? defaultEditMode
61
+ }
62
+
63
+ export function isEditMode(): boolean {
64
+ try {
65
+ return editModeResolver()
66
+ } catch {
67
+ return false
68
+ }
69
+ }
70
+
71
+ /* ------------------------------------------------------------------------- */
72
+ /* Quel texte se modifie sur place ? */
73
+ /* ------------------------------------------------------------------------- */
74
+
75
+ /** Nombre de textes marqués (stega) dans un texte affiché. */
76
+ export function stegaRuns(text: string): number {
77
+ return text.match(VERCEL_STEGA_REGEX)?.length ?? 0
78
+ }
79
+
80
+ /**
81
+ * Texte modifiable sur place : champ chaîne, ou morceau d'un texte riche qui a SON
82
+ * élément (un seul texte marqué dedans : titre en lignes, passage en italique ;
83
+ * dans un paragraphe fait de plusieurs morceaux, l'éditeur masquerait tout le
84
+ * paragraphe pour n'en modifier qu'une partie : panneau). Jamais un alt (une
85
+ * image n'est pas un texte, même repérée par son alt), un élément sans texte, ni
86
+ * un slug (une adresse se change dans le panneau, qui crée la 301).
87
+ */
88
+ export function isInlineEditablePath(type: string, path: string, element: Element): boolean {
89
+ if (type !== 'string') return false
90
+ if (/(^|\.)alt$/.test(path)) return false
91
+ if (element.matches('img, picture, video, svg, canvas, iframe') || !element.textContent?.trim()) return false
92
+ if (/\.children\[[^\]]+\]\.text$/.test(path) && stegaRuns(element.textContent ?? '') !== 1) return false
93
+ if (/(^|\.)slug\.current$/.test(path) || path.endsWith('.current')) return false
94
+ return true
95
+ }
96
+
97
+ /** Chemin d'un morceau de texte riche (jamais retiré, seulement vidé). */
98
+ export const isSpanTextPath = (path: string) => /\.children\[[^\]]+\]\.text$/.test(path)