@nocode-factory/sanity-kit 2.56.0 → 2.58.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 +45 -8
- package/bin/item-types.mjs +131 -0
- package/bin/ncf-kit.mjs +97 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +6908 -6820
- package/dist/index.js.map +1 -1
- package/dist/inherited-DZvM35P6.js +101 -0
- package/dist/inherited-DZvM35P6.js.map +1 -0
- package/dist/protocol-Bl7Yj2Ro.js +31 -0
- package/dist/protocol-Bl7Yj2Ro.js.map +1 -0
- package/dist/web-edit.d.ts +192 -0
- package/dist/web-edit.js +144 -0
- package/dist/web-edit.js.map +1 -0
- package/dist/web-editing.d.ts +51 -0
- package/dist/web-editing.js +693 -0
- package/dist/web-editing.js.map +1 -0
- package/package.json +22 -2
- package/scripts/use-client.mjs +1 -1
- package/src/form/AssetSourceBrowser.tsx +68 -39
- package/src/index.ts +3 -2
- package/src/tools/collections/CollectionTable.tsx +116 -89
- package/src/ui/PreviewEditBridge.tsx +74 -0
- package/src/version.ts +1 -1
- package/src/web/edit/ImageReplaceLayer.tsx +174 -0
- package/src/web/edit/InlineTextEditor.tsx +365 -0
- package/src/web/edit/InlineTextOverlay.tsx +43 -0
- package/src/web/edit/PreviewEditing.tsx +191 -0
- package/src/web/edit/index.ts +18 -0
- package/src/web/edit/inherited.ts +174 -0
- package/src/web/edit/labels.ts +37 -0
- package/src/web/edit/protocol.ts +47 -0
- package/src/web/edit/store.ts +98 -0
- package/src/web/edit/targets.ts +186 -0
- package/src/web/editing.ts +18 -0
|
@@ -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)
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import {createDataAttribute} from '@sanity/visual-editing/create-data-attribute'
|
|
2
|
+
import {resolveEditInfo, studioPath, type ContentSourceMap, type ContentSourceMapParsedPath} from '@sanity/client/csm'
|
|
3
|
+
import {vercelStegaClean} from '@vercel/stega'
|
|
4
|
+
import {retagInheritedList, type InheritedEdit} from './inherited'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* ÉDITION DANS L'APERÇU, IMAGES (mode brouillon seulement) : chaque image est
|
|
8
|
+
* cliquable dans Presentation, alt rempli ou non, et porte son document et son
|
|
9
|
+
* chemin EXACTS pour la pastille « Replace this image » (`NcfPreviewEditing`).
|
|
10
|
+
*
|
|
11
|
+
* Sanity ne repère d'ordinaire une image que par son alt (texte encodé en stega) :
|
|
12
|
+
* une image sans alt n'avait aucun overlay. Ici, la carte des sources (Content
|
|
13
|
+
* Source Map, renvoyée par `sanityFetch` en brouillon) donne pour chaque image son
|
|
14
|
+
* document et son champ ; on les attache à la valeur (`_editTarget`, `_editPath`,
|
|
15
|
+
* `_editDoc`, `_editType`), que le composant pose avec `imageEditAttributes`.
|
|
16
|
+
*
|
|
17
|
+
* Câblage d'un projet (starter) :
|
|
18
|
+
* - `annotateImageEditTargets(data, sourceMap, {studioUrl})` sur le résultat de
|
|
19
|
+
* `sanityFetch` en brouillon ;
|
|
20
|
+
* - `withPreviewEditTargets(reattributeTo(source, key), source, key, collected, {studioUrl})`
|
|
21
|
+
* comme rappel d'héritage de `applyDefaults` ;
|
|
22
|
+
* - `rekeyOwnImageTargets(section, source, key, {studioUrl})` sur chaque section ;
|
|
23
|
+
* - `imageEditAttributes(image)` / `imageAlt(image)` sur chaque image affichée.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export type ImageEditValue = {
|
|
27
|
+
asset?: {_ref?: string}
|
|
28
|
+
alt?: string
|
|
29
|
+
_editTarget?: string
|
|
30
|
+
_editPath?: string
|
|
31
|
+
_editDoc?: string
|
|
32
|
+
_editType?: string
|
|
33
|
+
} | null | undefined
|
|
34
|
+
|
|
35
|
+
type Marked = {asset: {_ref: string}; _editTarget?: string; _editPath?: string; _editDoc?: string; _editType?: string}
|
|
36
|
+
type Segment = ContentSourceMapParsedPath[number]
|
|
37
|
+
|
|
38
|
+
function isImageValue(value: unknown): value is Marked {
|
|
39
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return false
|
|
40
|
+
const ref = (value as {asset?: {_ref?: unknown}}).asset?._ref
|
|
41
|
+
return typeof ref === 'string' && ref.startsWith('image-')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Pose le repère Sanity et le chemin exact. Image élément de liste
|
|
46
|
+
* (`…images[_key=="i3"]`) : Sanity n'active pas un repère placé dans un élément de
|
|
47
|
+
* liste d'images ; le repère vise la liste, le chemin exact reste dans `_editPath`.
|
|
48
|
+
*/
|
|
49
|
+
function mark(value: Marked, id: string, type: string, path: string, extra: Record<string, string | undefined> & {baseUrl: string}) {
|
|
50
|
+
const inList = /\[[^\]]+\]$/.test(path)
|
|
51
|
+
value._editTarget = createDataAttribute({...extra, id, type, path: inList ? path.replace(/\[[^\]]+\]$/, '') : path}).toString()
|
|
52
|
+
value._editPath = path
|
|
53
|
+
value._editDoc = id.replace(/^drafts\./, '')
|
|
54
|
+
value._editType = type
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type ImageEditOptions = {
|
|
58
|
+
/** Adresse du Studio (celle de `stega.studioUrl`). */
|
|
59
|
+
studioUrl: string
|
|
60
|
+
/** Type du document des valeurs par défaut des composants (jamais marqué). */
|
|
61
|
+
defaultsType?: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Marque chaque image du résultat d'une requête en brouillon. Une image venue du
|
|
66
|
+
* document des valeurs par défaut n'est pas marquée ici (un clic modifierait
|
|
67
|
+
* l'image de TOUTES les pages) : `withPreviewEditTargets` la fait viser l'instance.
|
|
68
|
+
*/
|
|
69
|
+
export function annotateImageEditTargets<T>(data: T, sourceMap: ContentSourceMap | null | undefined, options: ImageEditOptions): T {
|
|
70
|
+
if (!sourceMap) return data
|
|
71
|
+
const defaultsType = options.defaultsType ?? 'componentDefaults'
|
|
72
|
+
const fromSourceMap = (value: Marked, path: ContentSourceMapParsedPath) => {
|
|
73
|
+
const info = resolveEditInfo({studioUrl: options.studioUrl, resultSourceMap: sourceMap, resultPath: [...path, 'asset', '_ref']})
|
|
74
|
+
if (!info || info.type === defaultsType) return
|
|
75
|
+
const full = typeof info.path === 'string' ? info.path : studioPath.toString(info.path as never)
|
|
76
|
+
const imagePath = full.replace(/\.asset\._ref$/, '')
|
|
77
|
+
if (!imagePath || imagePath === full) return
|
|
78
|
+
mark(value, info.id, info.type, imagePath, {
|
|
79
|
+
baseUrl: info.baseUrl,
|
|
80
|
+
workspace: info.workspace,
|
|
81
|
+
tool: info.tool,
|
|
82
|
+
projectId: info.projectId,
|
|
83
|
+
dataset: info.dataset,
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
const visit = (value: unknown, path: ContentSourceMapParsedPath) => {
|
|
87
|
+
if (Array.isArray(value)) {
|
|
88
|
+
value.forEach((item, index) => {
|
|
89
|
+
const key = item && typeof item === 'object' && typeof (item as {_key?: unknown})._key === 'string' ? (item as {_key: string})._key : null
|
|
90
|
+
const segment: Segment = key ? {_key: key, _index: index} : index
|
|
91
|
+
visit(item, [...path, segment])
|
|
92
|
+
})
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
if (!value || typeof value !== 'object') return
|
|
96
|
+
if (isImageValue(value) && !value._editTarget) fromSourceMap(value, path)
|
|
97
|
+
for (const [key, child] of Object.entries(value)) {
|
|
98
|
+
if (key.startsWith('_edit')) continue
|
|
99
|
+
visit(child, [...path, key])
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
visit(data, [])
|
|
103
|
+
return data
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
type OnInherit = (value: unknown, path: string[]) => unknown
|
|
107
|
+
type Source = {id: string; type: string; path: string; single?: boolean}
|
|
108
|
+
|
|
109
|
+
const sectionBase = (source: Source, key: string | undefined) => (key && !source.single ? `${source.path}[_key=="${key}"]` : source.path)
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Rappel d'héritage pour `applyDefaults` (en aperçu), autour de `reattributeTo` :
|
|
113
|
+
* - image héritée : vise le champ image de L'INSTANCE (choisir une image crée une
|
|
114
|
+
* image propre à la page, la valeur par défaut ne change pas) ;
|
|
115
|
+
* - texte hérité : sa valeur par défaut exacte est jointe (`collected`) ;
|
|
116
|
+
* - liste simple ou texte riche hérité : modifiable ligne à ligne (voir `inherited.ts`).
|
|
117
|
+
* `collected` est à rendre par la section avec `inheritedEditScriptProps`.
|
|
118
|
+
*/
|
|
119
|
+
export function withPreviewEditTargets(onInherit: OnInherit, source: Source, key: string | undefined, collected: InheritedEdit[], options: ImageEditOptions): OnInherit {
|
|
120
|
+
const base = sectionBase(source, key)
|
|
121
|
+
const pageId = source.id.replace(/^drafts\./, '')
|
|
122
|
+
const markInherited = (value: unknown, path: string) => {
|
|
123
|
+
if (Array.isArray(value) || !value || typeof value !== 'object') return
|
|
124
|
+
if (isImageValue(value)) {
|
|
125
|
+
mark(value, pageId, source.type, path, {baseUrl: options.studioUrl})
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
for (const [k, child] of Object.entries(value)) if (!k.startsWith('_')) markInherited(child, `${path}.${k}`)
|
|
129
|
+
}
|
|
130
|
+
return (value, path) => {
|
|
131
|
+
const out = onInherit(value, path)
|
|
132
|
+
if (out && typeof out === 'object' && !Array.isArray(out)) {
|
|
133
|
+
const copy = isImageValue(out) ? {...out} : out
|
|
134
|
+
markInherited(copy, `${base}.${path.join('.')}`)
|
|
135
|
+
return copy
|
|
136
|
+
}
|
|
137
|
+
if (typeof out === 'string') collected.push({path: `${base}.${path.join('.')}`, value: vercelStegaClean(out)})
|
|
138
|
+
// Liste héritée directement par un champ de la section (le parent existe dans la page).
|
|
139
|
+
if (Array.isArray(out) && path.length === 1) return retagInheritedList(out, `${base}.${path[0]}`, source, collected)
|
|
140
|
+
return out
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Chemin EXACT des images qui appartiennent à la page, recalculé avec les clés
|
|
146
|
+
* `_key` de la section. La carte des sources donne parfois un rang au lieu de la
|
|
147
|
+
* clé (`images:0`) : Sanity ne retrouve alors pas le champ. Une image d'un AUTRE
|
|
148
|
+
* document (carte liée, témoignage...) garde son repère.
|
|
149
|
+
*/
|
|
150
|
+
export function rekeyOwnImageTargets<T>(section: T, source: Source, key: string | undefined, options: ImageEditOptions): T {
|
|
151
|
+
const pageId = source.id.replace(/^drafts\./, '')
|
|
152
|
+
const visit = (value: unknown, path: string) => {
|
|
153
|
+
if (Array.isArray(value)) {
|
|
154
|
+
value.forEach((item, index) => {
|
|
155
|
+
const k = item && typeof item === 'object' ? (item as {_key?: unknown})._key : undefined
|
|
156
|
+
visit(item, typeof k === 'string' ? `${path}[_key=="${k}"]` : `${path}[${index}]`)
|
|
157
|
+
})
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
if (!value || typeof value !== 'object') return
|
|
161
|
+
if (isImageValue(value) && value._editDoc) {
|
|
162
|
+
if (value._editDoc === pageId) mark(value, pageId, source.type, path, {baseUrl: options.studioUrl})
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
for (const [k, child] of Object.entries(value)) if (!k.startsWith('_')) visit(child, `${path}.${k}`)
|
|
166
|
+
}
|
|
167
|
+
visit(section, sectionBase(source, key))
|
|
168
|
+
return section
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export type ImageEditAttributes = {'data-sanity'?: string; 'data-edit-image'?: string; 'data-edit-doc'?: string; 'data-edit-type'?: string}
|
|
172
|
+
|
|
173
|
+
/** Attributs à poser sur le cadre d'une image marquée ; vide pour les visiteurs. */
|
|
174
|
+
export function imageEditAttributes(image: ImageEditValue): ImageEditAttributes {
|
|
175
|
+
if (!image?._editTarget || !image._editPath || !image._editDoc || !image._editType) return {}
|
|
176
|
+
return {'data-sanity': image._editTarget, 'data-edit-image': image._editPath, 'data-edit-doc': image._editDoc, 'data-edit-type': image._editType}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Alt d'une image marquée : nettoyé de ses marqueurs (sinon Sanity la prendrait
|
|
181
|
+
* pour un texte et le clic ouvrirait l'alt au lieu de l'image).
|
|
182
|
+
*/
|
|
183
|
+
export function imageAlt(image: ImageEditValue, alt?: string): string {
|
|
184
|
+
const value = alt ?? image?.alt ?? ''
|
|
185
|
+
return image?._editTarget ? vercelStegaClean(value) : value
|
|
186
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ÉDITION SUR PLACE dans l'aperçu (Presentation), point d'entrée **client** :
|
|
3
|
+
*
|
|
4
|
+
* ```tsx
|
|
5
|
+
* import {NcfPreviewEditing, ncfOverlayComponents} from '@nocode-factory/sanity-kit/web/editing'
|
|
6
|
+
*
|
|
7
|
+
* <VisualEditing refresh={useNcfPreviewRefresh()} components={ncfOverlayComponents} />
|
|
8
|
+
* <NcfPreviewEditing labels={messages.previewEditing} />
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* Séparé de `/web` : il dépend de `@sanity/visual-editing` et `@sanity/mutate`
|
|
12
|
+
* (fournis par next-sanity), qu'un projet sans édition visuelle n'a pas à installer.
|
|
13
|
+
* Côté données (requêtes, sections, images) : `@nocode-factory/sanity-kit/web/edit`.
|
|
14
|
+
*/
|
|
15
|
+
export {NcfPreviewEditing, ncfOverlayComponents} from './edit/PreviewEditing'
|
|
16
|
+
export type {NcfPreviewEditingProps} from './edit/PreviewEditing'
|
|
17
|
+
export {DEFAULT_PREVIEW_EDITING_LABELS} from './edit/labels'
|
|
18
|
+
export type {PreviewEditingLabels} from './edit/labels'
|