@nocode-factory/sanity-kit 2.54.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 +61 -6
- package/bin/item-types.mjs +131 -0
- package/bin/ncf-kit.mjs +97 -0
- package/dist/index.d.ts +48 -4
- package/dist/index.js +7222 -6916
- 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/hooks/useCollection.ts +19 -3
- package/src/index.ts +3 -2
- package/src/lib/collectionQuery.ts +10 -2
- package/src/structure/collections.tsx +35 -5
- package/src/tools/collections/CollectionTable.tsx +295 -89
- package/src/tools/collections/CollectionToolbar.tsx +53 -4
- 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,74 @@
|
|
|
1
|
+
import {useEffect, useState} from 'react'
|
|
2
|
+
import {useClient, useDocumentOperation, type LayoutProps} from 'sanity'
|
|
3
|
+
import {MediaPickerDialog} from '../form/AssetSourceBrowser'
|
|
4
|
+
import {isReplaceImageRequest, replaceImagePatch} from '../web/edit/protocol'
|
|
5
|
+
import {HelpTextStyle} from './HelpTextStyle'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* « Replace this image » depuis l'aperçu (Presentation) : un clic sur une image de
|
|
9
|
+
* l'aperçu (`NcfPreviewEditing`) envoie un message ; le Studio ouvre la médiathèque
|
|
10
|
+
* en quasi plein écran (masonry, dossiers, recherche : comme l'onglet Assets) et
|
|
11
|
+
* l'image choisie remplace celle du champ dans le BROUILLON (même chemin que le
|
|
12
|
+
* formulaire). Cadrage et point focal de l'ancienne image retirés.
|
|
13
|
+
*
|
|
14
|
+
* Sécurité : seul un message venu d'une fenêtre affichée par ce Studio
|
|
15
|
+
* (`window.frames`), depuis l'origine d'un environnement du kit, est pris en
|
|
16
|
+
* compte ; il ne fait qu'ouvrir le sélecteur, le choix reste à l'utilisateur.
|
|
17
|
+
*/
|
|
18
|
+
type Request = {documentId: string; documentType: string; path: string}
|
|
19
|
+
|
|
20
|
+
/** Le message vient-il d'une sous-fenêtre de ce Studio ? (le tableau de bord sanity.io encastre le Studio : on parcourt window.frames.) */
|
|
21
|
+
function fromChildFrame(source: MessageEventSource | null): boolean {
|
|
22
|
+
if (!source) return false
|
|
23
|
+
for (let i = 0; i < window.frames.length; i++) if (window.frames[i] === source) return true
|
|
24
|
+
return false
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function PreviewEditBridge({origins}: {origins: readonly string[]}) {
|
|
28
|
+
const client = useClient({apiVersion: '2025-02-19'})
|
|
29
|
+
const [request, setRequest] = useState<Request | null>(null)
|
|
30
|
+
|
|
31
|
+
useEffect(() => {
|
|
32
|
+
if (!origins.length) return
|
|
33
|
+
const onMessage = async (event: MessageEvent) => {
|
|
34
|
+
if (!origins.includes(event.origin) || !fromChildFrame(event.source) || !isReplaceImageRequest(event.data)) return
|
|
35
|
+
const documentId = event.data.documentId.replace(/^drafts\./, '')
|
|
36
|
+
const documentType = event.data.documentType || (await client.fetch<string | null>('*[_id in [$id, "drafts." + $id]][0]._type', {id: documentId}))
|
|
37
|
+
if (documentType) setRequest({documentId, documentType, path: event.data.path})
|
|
38
|
+
}
|
|
39
|
+
window.addEventListener('message', onMessage)
|
|
40
|
+
return () => window.removeEventListener('message', onMessage)
|
|
41
|
+
}, [client, origins])
|
|
42
|
+
|
|
43
|
+
if (!request) return null
|
|
44
|
+
return <ReplaceImageDialog key={`${request.documentId}:${request.path}`} request={request} onDone={() => setRequest(null)} />
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function ReplaceImageDialog({request, onDone}: {request: Request; onDone: () => void}) {
|
|
48
|
+
const {patch} = useDocumentOperation(request.documentId, request.documentType)
|
|
49
|
+
return (
|
|
50
|
+
<MediaPickerDialog
|
|
51
|
+
id="ncf-preview-replace-image"
|
|
52
|
+
title="Replace image"
|
|
53
|
+
kind="image"
|
|
54
|
+
size="wide"
|
|
55
|
+
onClose={onDone}
|
|
56
|
+
onPick={(asset) => {
|
|
57
|
+
patch.execute(replaceImagePatch(request.path, asset._id))
|
|
58
|
+
onDone()
|
|
59
|
+
}}
|
|
60
|
+
/>
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Habillage du Studio posé par le plugin : feuille de style des aides + pont de l'aperçu. */
|
|
65
|
+
export function createKitLayout(origins: readonly string[]) {
|
|
66
|
+
return function KitLayout(props: LayoutProps) {
|
|
67
|
+
return (
|
|
68
|
+
<>
|
|
69
|
+
<HelpTextStyle {...props} />
|
|
70
|
+
<PreviewEditBridge origins={origins} />
|
|
71
|
+
</>
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import {useEffect, useState} from 'react'
|
|
2
|
+
import {createPortal} from 'react-dom'
|
|
3
|
+
import {CHIP, FONT} from './labels'
|
|
4
|
+
import {REPLACE_IMAGE_MESSAGE} from './protocol'
|
|
5
|
+
import {isEditMode} from './store'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* « Replace this image » dans l'aperçu, INDÉPENDANT du mécanisme de composants de
|
|
9
|
+
* Sanity (qui ne s'active pas sur toutes les images : éléments de liste, images
|
|
10
|
+
* héritées). Chaque image éditable porte son document et son chemin exacts
|
|
11
|
+
* (attributs `data-edit-*`, `imageEditAttributes`) :
|
|
12
|
+
* - au survol, une pastille en haut de la partie VISIBLE de l'image (sous le
|
|
13
|
+
* header, dans les cadres qui la rognent) ; transparente à la souris ;
|
|
14
|
+
* - au clic, le Studio (fenêtre parente) ouvre la médiathèque pour ce champ (pont
|
|
15
|
+
* monté par le plugin du kit). Le message ne vise que l'origine du Studio.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const SELECTOR = '[data-edit-image][data-edit-doc][data-edit-type]'
|
|
19
|
+
|
|
20
|
+
function studioOrigin(): string | null {
|
|
21
|
+
const ancestor = window.location.ancestorOrigins?.[0]
|
|
22
|
+
if (ancestor) return ancestor
|
|
23
|
+
try {
|
|
24
|
+
return document.referrer ? new URL(document.referrer).origin : null
|
|
25
|
+
} catch {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Hauteur du header du site (`--header-height`, px ou rem), 0 sinon. */
|
|
31
|
+
function headerHeight(): number {
|
|
32
|
+
const root = getComputedStyle(document.documentElement)
|
|
33
|
+
const raw = root.getPropertyValue('--header-height').trim()
|
|
34
|
+
return (parseFloat(raw) || 0) * (raw.endsWith('rem') ? parseFloat(root.fontSize) || 16 : 1)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Rectangle visible : rogné par les ancêtres qui coupent, la fenêtre et le header. */
|
|
38
|
+
function visibleRect(element: Element) {
|
|
39
|
+
const r = element.getBoundingClientRect()
|
|
40
|
+
let top = Math.max(r.top, headerHeight())
|
|
41
|
+
let left = Math.max(r.left, 0)
|
|
42
|
+
let right = Math.min(r.right, window.innerWidth)
|
|
43
|
+
let bottom = Math.min(r.bottom, window.innerHeight)
|
|
44
|
+
for (let n = element.parentElement; n && n !== document.body; n = n.parentElement) {
|
|
45
|
+
const cs = getComputedStyle(n)
|
|
46
|
+
if (cs.overflowX === 'visible' && cs.overflowY === 'visible') continue
|
|
47
|
+
const c = n.getBoundingClientRect()
|
|
48
|
+
top = Math.max(top, c.top)
|
|
49
|
+
left = Math.max(left, c.left)
|
|
50
|
+
right = Math.min(right, c.right)
|
|
51
|
+
bottom = Math.min(bottom, c.bottom)
|
|
52
|
+
}
|
|
53
|
+
return {top, left, right, bottom}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Image éditable sous la souris, même RECOUVERTE par des calques décoratifs
|
|
58
|
+
* (dégradé, voile, bloc de titre en plein cadre) : on parcourt la pile d'éléments
|
|
59
|
+
* sous le point et on traverse tout calque sans texte. Un vrai texte (ou un champ
|
|
60
|
+
* de saisie) posé sur l'image garde la priorité, pour rester modifiable.
|
|
61
|
+
*/
|
|
62
|
+
const VISIBLE_TEXT = /[^\s-]/
|
|
63
|
+
function hasOwnText(el: Element) {
|
|
64
|
+
for (const n of el.childNodes) if (n.nodeType === Node.TEXT_NODE && VISIBLE_TEXT.test(n.textContent ?? '')) return true
|
|
65
|
+
return false
|
|
66
|
+
}
|
|
67
|
+
export function imageAt(x: number, y: number): HTMLElement | null {
|
|
68
|
+
for (const el of document.elementsFromPoint(x, y)) {
|
|
69
|
+
const image = el.closest(SELECTOR) as HTMLElement | null
|
|
70
|
+
if (image) return image
|
|
71
|
+
if (hasOwnText(el) || el.matches('input, textarea, select, button, [contenteditable]')) return null
|
|
72
|
+
}
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function ImageReplaceLayer({label}: {label: string}) {
|
|
77
|
+
const [target, setTarget] = useState<HTMLElement | null>(null)
|
|
78
|
+
const [pos, setPos] = useState<{top: number; left: number} | null>(null)
|
|
79
|
+
|
|
80
|
+
useEffect(() => {
|
|
81
|
+
if (window.parent === window) return
|
|
82
|
+
let frame = 0
|
|
83
|
+
const onMove = (event: PointerEvent) => {
|
|
84
|
+
const {clientX, clientY} = event
|
|
85
|
+
cancelAnimationFrame(frame)
|
|
86
|
+
frame = requestAnimationFrame(() => {
|
|
87
|
+
const el = isEditMode() ? imageAt(clientX, clientY) : null
|
|
88
|
+
setTarget((prev) => (prev === el ? prev : el))
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
const onLeaveWindow = (event: PointerEvent) => {
|
|
92
|
+
if (!event.relatedTarget) setTarget(null)
|
|
93
|
+
}
|
|
94
|
+
const onClick = (event: MouseEvent) => {
|
|
95
|
+
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !isEditMode()) return
|
|
96
|
+
const el = imageAt(event.clientX, event.clientY)
|
|
97
|
+
const origin = studioOrigin()
|
|
98
|
+
if (!el || !origin) return
|
|
99
|
+
// Le clic sert à remplacer l'image : jamais suivre un lien posé au-dessus.
|
|
100
|
+
event.preventDefault()
|
|
101
|
+
setTarget(null)
|
|
102
|
+
window.parent.postMessage(
|
|
103
|
+
{
|
|
104
|
+
type: REPLACE_IMAGE_MESSAGE,
|
|
105
|
+
documentId: el.getAttribute('data-edit-doc'),
|
|
106
|
+
documentType: el.getAttribute('data-edit-type'),
|
|
107
|
+
path: el.getAttribute('data-edit-image'),
|
|
108
|
+
},
|
|
109
|
+
origin,
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
document.addEventListener('pointermove', onMove, {passive: true})
|
|
113
|
+
document.documentElement.addEventListener('pointerout', onLeaveWindow, {passive: true})
|
|
114
|
+
window.addEventListener('click', onClick, {capture: true})
|
|
115
|
+
return () => {
|
|
116
|
+
cancelAnimationFrame(frame)
|
|
117
|
+
document.removeEventListener('pointermove', onMove)
|
|
118
|
+
document.documentElement.removeEventListener('pointerout', onLeaveWindow)
|
|
119
|
+
window.removeEventListener('click', onClick, {capture: true})
|
|
120
|
+
}
|
|
121
|
+
}, [])
|
|
122
|
+
|
|
123
|
+
// Suit l'image (défilement, parallaxe) tant qu'elle est survolée.
|
|
124
|
+
useEffect(() => {
|
|
125
|
+
if (!target) return
|
|
126
|
+
let frame = 0
|
|
127
|
+
const measure = () => {
|
|
128
|
+
const v = visibleRect(target)
|
|
129
|
+
const half = 110
|
|
130
|
+
const center = Math.min(Math.max((v.left + v.right) / 2, half + 8), window.innerWidth - half - 8)
|
|
131
|
+
const next = v.bottom - v.top < 40 || v.right - v.left < 40 ? null : {top: Math.round(v.top + 16), left: Math.round(center)}
|
|
132
|
+
setPos((prev) => (prev && next && prev.top === next.top && prev.left === next.left ? prev : next))
|
|
133
|
+
frame = requestAnimationFrame(measure)
|
|
134
|
+
}
|
|
135
|
+
measure()
|
|
136
|
+
return () => {
|
|
137
|
+
cancelAnimationFrame(frame)
|
|
138
|
+
setPos(null)
|
|
139
|
+
}
|
|
140
|
+
}, [target])
|
|
141
|
+
|
|
142
|
+
if (!target || !pos) return null
|
|
143
|
+
return createPortal(
|
|
144
|
+
<span
|
|
145
|
+
aria-hidden
|
|
146
|
+
style={{
|
|
147
|
+
pointerEvents: 'none',
|
|
148
|
+
position: 'fixed',
|
|
149
|
+
zIndex: 2147482000,
|
|
150
|
+
top: pos.top,
|
|
151
|
+
left: pos.left,
|
|
152
|
+
transform: 'translateX(-50%)',
|
|
153
|
+
display: 'flex',
|
|
154
|
+
alignItems: 'center',
|
|
155
|
+
gap: 8,
|
|
156
|
+
padding: '6px 12px 6px 8px',
|
|
157
|
+
borderRadius: 999,
|
|
158
|
+
background: CHIP,
|
|
159
|
+
color: '#fff',
|
|
160
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
|
|
161
|
+
font: `500 13px/1 ${FONT}`,
|
|
162
|
+
whiteSpace: 'nowrap',
|
|
163
|
+
}}
|
|
164
|
+
>
|
|
165
|
+
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
|
|
166
|
+
<rect x="2" y="3" width="12" height="10" rx="1.5" />
|
|
167
|
+
<circle cx="6" cy="6.5" r="1.2" />
|
|
168
|
+
<path d="M14 10.5l-3.5-3.5L4 13" />
|
|
169
|
+
</svg>
|
|
170
|
+
{label}
|
|
171
|
+
</span>,
|
|
172
|
+
document.body,
|
|
173
|
+
)
|
|
174
|
+
}
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import {useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent} from 'react'
|
|
2
|
+
import {createPortal} from 'react-dom'
|
|
3
|
+
import {useDocuments, type SanityNode} from '@sanity/visual-editing'
|
|
4
|
+
import {at, set, unset} from '@sanity/mutate'
|
|
5
|
+
import {getAtPath, parse} from '@sanity/mutate/path'
|
|
6
|
+
import {vercelStegaClean, vercelStegaDecode} from '@vercel/stega'
|
|
7
|
+
import {inheritedListValue, materializeInheritedList} from './inherited'
|
|
8
|
+
import {ACCENT, CHIP, FONT, type PreviewEditingLabels} from './labels'
|
|
9
|
+
import {inlineEdit, isEditMode, isSpanTextPath, type InlineTarget} from './store'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Éditeur de texte SUR PLACE : au clic sur un texte modifiable, un champ de
|
|
13
|
+
* saisie prend sa place exacte, dans sa typographie. Entrée ou clic ailleurs =
|
|
14
|
+
* enregistré dans le BROUILLON (patch du seul champ, par le canal de l'aperçu),
|
|
15
|
+
* Échap = annulé. Le panneau du Studio s'ouvre en même temps sur le champ
|
|
16
|
+
* (comportement de Sanity, conservé). Rien n'est publié.
|
|
17
|
+
*/
|
|
18
|
+
export function InlineTextEditor({labels}: {labels: PreviewEditingLabels}) {
|
|
19
|
+
const target = useSyncExternalStore(inlineEdit.subscribe, inlineEdit.getEditing, () => null)
|
|
20
|
+
|
|
21
|
+
// Écoute en capture sur la fenêtre : passe avant le clic que Sanity intercepte sur
|
|
22
|
+
// l'élément (sans l'arrêter, pour que le panneau s'ouvre aussi sur le champ).
|
|
23
|
+
useEffect(() => {
|
|
24
|
+
const onClick = (event: MouseEvent) => {
|
|
25
|
+
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
|
|
26
|
+
if (!isEditMode()) return
|
|
27
|
+
const hovered = inlineEdit.getHovered() ?? inheritedListTarget(event.target)
|
|
28
|
+
if (!hovered || !(event.target instanceof Node) || !hovered.element.contains(event.target)) return
|
|
29
|
+
if (inlineEdit.getEditing()?.element === hovered.element) return
|
|
30
|
+
event.preventDefault()
|
|
31
|
+
inlineEdit.open(hovered)
|
|
32
|
+
}
|
|
33
|
+
window.addEventListener('click', onClick, {capture: true})
|
|
34
|
+
return () => window.removeEventListener('click', onClick, {capture: true})
|
|
35
|
+
}, [])
|
|
36
|
+
|
|
37
|
+
if (!target) return null
|
|
38
|
+
return createPortal(<EditorSession key={`${target.node.id}:${target.node.path}`} target={target} labels={labels} />, document.body)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/* ------------------------------------------------------------------------- */
|
|
42
|
+
/* Valeurs héritées jointes à la page (inheritedEditScriptProps) */
|
|
43
|
+
/* ------------------------------------------------------------------------- */
|
|
44
|
+
|
|
45
|
+
type InheritedListData = {path: string; items: Record<string, unknown>[]}
|
|
46
|
+
|
|
47
|
+
function inheritedListFor(path: string): InheritedListData | null {
|
|
48
|
+
for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-list]')) {
|
|
49
|
+
const listPath = script.dataset.ncfInheritedList ?? ''
|
|
50
|
+
if (!listPath || !path.startsWith(`${listPath}[`)) continue
|
|
51
|
+
try {
|
|
52
|
+
return {path: listPath, items: JSON.parse(script.textContent ?? '[]')}
|
|
53
|
+
} catch {
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function inheritedValueFor(path: string): string | null {
|
|
61
|
+
for (const script of document.querySelectorAll<HTMLScriptElement>('script[data-ncf-inherited-value]')) {
|
|
62
|
+
if (script.dataset.ncfInheritedValue !== path) continue
|
|
63
|
+
try {
|
|
64
|
+
const value = JSON.parse(script.textContent ?? 'null')
|
|
65
|
+
return typeof value === 'string' ? value : null
|
|
66
|
+
} catch {
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Ligne d'une liste héritée : Sanity n'active pas son composant sur un élément
|
|
75
|
+
* que la page n'a pas encore (pas de crayon), mais chaque texte porte sa ligne
|
|
76
|
+
* exacte (stega). Le clic sur un tel texte ouvre l'éditeur directement.
|
|
77
|
+
*/
|
|
78
|
+
function inheritedListTarget(target: EventTarget | null): InlineTarget | null {
|
|
79
|
+
let el = target instanceof Element ? target : null
|
|
80
|
+
for (let depth = 0; el && depth < 5; depth++, el = el.parentElement) {
|
|
81
|
+
const info = vercelStegaDecode(el.textContent ?? '') as {href?: string} | undefined
|
|
82
|
+
if (!info?.href) continue
|
|
83
|
+
const href = decodeURIComponent(info.href)
|
|
84
|
+
const id = /[;/]id=([^;?]+)/.exec(href)?.[1]?.replace(/^drafts\./, '')
|
|
85
|
+
const type = /;type=([^;?]+)/.exec(href)?.[1]
|
|
86
|
+
const path = /;path=([^;?]+)/.exec(href)?.[1]
|
|
87
|
+
if (!id || !path || !inheritedListFor(path) || !(el instanceof HTMLElement)) return null
|
|
88
|
+
return {element: el, node: {id, type, path} as SanityNode}
|
|
89
|
+
}
|
|
90
|
+
return null
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/* ------------------------------------------------------------------------- */
|
|
94
|
+
/* Session d'édition */
|
|
95
|
+
/* ------------------------------------------------------------------------- */
|
|
96
|
+
|
|
97
|
+
type Status = 'loading' | 'editing' | 'saving'
|
|
98
|
+
type Box = {top: number; left: number; width: number; height: number}
|
|
99
|
+
|
|
100
|
+
const TYPO_PROPS = ['font-family', 'font-size', 'font-weight', 'font-style', 'font-variant', 'font-feature-settings', 'line-height', 'letter-spacing', 'word-spacing', 'text-transform', 'text-align', 'color'] as const
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Typographie du texte affiché : celle de l'élément qui porte le premier morceau
|
|
104
|
+
* de texte (un titre découpé pour une animation garde ses mots dans des sous-éléments).
|
|
105
|
+
*/
|
|
106
|
+
function textStyle(element: HTMLElement): CSSProperties {
|
|
107
|
+
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, {
|
|
108
|
+
acceptNode: (n) => (n.textContent?.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP),
|
|
109
|
+
})
|
|
110
|
+
const host = (walker.nextNode()?.parentElement as HTMLElement | null) ?? element
|
|
111
|
+
const cs = getComputedStyle(host)
|
|
112
|
+
const style: Record<string, string> = {}
|
|
113
|
+
for (const prop of TYPO_PROPS) style[prop.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())] = cs.getPropertyValue(prop)
|
|
114
|
+
return style as CSSProperties
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const sameBox = (a: Box | null, b: Box) => !!a && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height
|
|
118
|
+
|
|
119
|
+
const CHIP_STYLE: CSSProperties = {
|
|
120
|
+
position: 'absolute',
|
|
121
|
+
left: 0,
|
|
122
|
+
display: 'flex',
|
|
123
|
+
alignItems: 'center',
|
|
124
|
+
gap: 4,
|
|
125
|
+
padding: 4,
|
|
126
|
+
borderRadius: 999,
|
|
127
|
+
background: CHIP,
|
|
128
|
+
color: '#fff',
|
|
129
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
|
|
130
|
+
font: `500 13px/1 ${FONT}`,
|
|
131
|
+
fontStyle: 'normal',
|
|
132
|
+
textTransform: 'none',
|
|
133
|
+
letterSpacing: 'normal',
|
|
134
|
+
whiteSpace: 'nowrap',
|
|
135
|
+
}
|
|
136
|
+
const BUTTON_STYLE: CSSProperties = {display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', border: 0, borderRadius: 999, font: 'inherit', cursor: 'pointer'}
|
|
137
|
+
const KBD_STYLE: CSSProperties = {font: `11px/1 ${FONT}`, opacity: 0.7}
|
|
138
|
+
|
|
139
|
+
function EditorSession({target, labels}: {target: InlineTarget; labels: PreviewEditingLabels}) {
|
|
140
|
+
const {element, node} = target
|
|
141
|
+
const {getDocument} = useDocuments()
|
|
142
|
+
const [status, setStatus] = useState<Status>('loading')
|
|
143
|
+
const [value, setValue] = useState('')
|
|
144
|
+
const [inherited, setInherited] = useState(false)
|
|
145
|
+
const [box, setBox] = useState<Box | null>(null)
|
|
146
|
+
const [typo] = useState(() => textStyle(element))
|
|
147
|
+
const initial = useRef('')
|
|
148
|
+
// Texte de départ d'un texte hérité (valeur par défaut) : inchangé = rien à enregistrer.
|
|
149
|
+
const inheritedStart = useRef('')
|
|
150
|
+
const multiline = useRef(false)
|
|
151
|
+
const rootRef = useRef<HTMLDivElement>(null)
|
|
152
|
+
const fieldRef = useRef<HTMLTextAreaElement>(null)
|
|
153
|
+
|
|
154
|
+
// Le texte d'origine est masqué (mise en page conservée) le temps de l'édition.
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
const previous = element.style.visibility
|
|
157
|
+
element.style.visibility = 'hidden'
|
|
158
|
+
return () => {
|
|
159
|
+
element.style.visibility = previous
|
|
160
|
+
}
|
|
161
|
+
}, [element])
|
|
162
|
+
|
|
163
|
+
// Suit l'élément (défilement, défilement doux, redimensionnement).
|
|
164
|
+
useEffect(() => {
|
|
165
|
+
let frame = 0
|
|
166
|
+
const tick = () => {
|
|
167
|
+
const r = element.getBoundingClientRect()
|
|
168
|
+
const next = {top: r.top, left: r.left, width: r.width, height: r.height}
|
|
169
|
+
setBox((prev) => (sameBox(prev, next) ? prev : next))
|
|
170
|
+
frame = requestAnimationFrame(tick)
|
|
171
|
+
}
|
|
172
|
+
tick()
|
|
173
|
+
return () => cancelAnimationFrame(frame)
|
|
174
|
+
}, [element])
|
|
175
|
+
|
|
176
|
+
// Valeur réelle du champ dans le brouillon. Champ vide = valeur HÉRITÉE : on part
|
|
177
|
+
// de la valeur par défaut exacte jointe à la page, jamais du texte affiché.
|
|
178
|
+
useEffect(() => {
|
|
179
|
+
let cancelled = false
|
|
180
|
+
getDocument(node.id)
|
|
181
|
+
.getSnapshot()
|
|
182
|
+
.then((doc) => {
|
|
183
|
+
if (cancelled) return
|
|
184
|
+
const stored = doc ? getAtPath(parse(node.path), doc) : undefined
|
|
185
|
+
const list = inheritedListFor(node.path)
|
|
186
|
+
const text =
|
|
187
|
+
typeof stored === 'string' && stored !== ''
|
|
188
|
+
? stored
|
|
189
|
+
: (inheritedValueFor(node.path) ?? (list ? inheritedListValue(list, node.path) : null) ?? vercelStegaClean(element.textContent ?? '').trim())
|
|
190
|
+
initial.current = typeof stored === 'string' ? stored : ''
|
|
191
|
+
inheritedStart.current = text
|
|
192
|
+
multiline.current = text.includes('\n')
|
|
193
|
+
setInherited(typeof stored !== 'string' || stored === '')
|
|
194
|
+
setValue(text)
|
|
195
|
+
setStatus('editing')
|
|
196
|
+
})
|
|
197
|
+
.catch(() => {
|
|
198
|
+
if (!cancelled) inlineEdit.close()
|
|
199
|
+
})
|
|
200
|
+
return () => {
|
|
201
|
+
cancelled = true
|
|
202
|
+
}
|
|
203
|
+
}, [getDocument, node.id, node.path, element])
|
|
204
|
+
|
|
205
|
+
useEffect(() => {
|
|
206
|
+
if (status !== 'editing') return
|
|
207
|
+
const field = fieldRef.current
|
|
208
|
+
if (!field) return
|
|
209
|
+
const focusField = () => {
|
|
210
|
+
field.focus({preventScroll: true})
|
|
211
|
+
field.setSelectionRange(field.value.length, field.value.length)
|
|
212
|
+
}
|
|
213
|
+
focusField()
|
|
214
|
+
// Le Studio ouvre le champ dans son panneau juste après le clic et y place le
|
|
215
|
+
// curseur : l'aperçu le reprend pendant ce court instant (sinon la saisie partirait
|
|
216
|
+
// dans le champ du Studio).
|
|
217
|
+
const until = performance.now() + 1500
|
|
218
|
+
const onBlur = () => {
|
|
219
|
+
if (performance.now() < until) window.setTimeout(focusField, 0)
|
|
220
|
+
}
|
|
221
|
+
window.addEventListener('blur', onBlur)
|
|
222
|
+
const retry = window.setTimeout(focusField, 300)
|
|
223
|
+
return () => {
|
|
224
|
+
window.removeEventListener('blur', onBlur)
|
|
225
|
+
window.clearTimeout(retry)
|
|
226
|
+
}
|
|
227
|
+
}, [status])
|
|
228
|
+
|
|
229
|
+
useLayoutEffect(() => {
|
|
230
|
+
const field = fieldRef.current
|
|
231
|
+
if (!field) return
|
|
232
|
+
field.style.height = 'auto'
|
|
233
|
+
field.style.height = `${field.scrollHeight}px`
|
|
234
|
+
}, [value, box?.width, status])
|
|
235
|
+
|
|
236
|
+
const save = useCallback(() => {
|
|
237
|
+
const next = multiline.current ? value : value.replace(/\s*\n\s*/g, ' ')
|
|
238
|
+
if (next === initial.current || (inherited && next.trim() === inheritedStart.current.trim())) {
|
|
239
|
+
inlineEdit.close()
|
|
240
|
+
return
|
|
241
|
+
}
|
|
242
|
+
// Ligne d'une liste héritée que la page n'a pas encore : la liste par défaut est
|
|
243
|
+
// recopiée dans la page avec cette ligne modifiée (même enregistrement).
|
|
244
|
+
const list = inherited ? inheritedListFor(node.path) : null
|
|
245
|
+
const items = list ? materializeInheritedList(list, node.path, next) : null
|
|
246
|
+
const doc = getDocument(node.id)
|
|
247
|
+
if (list && items) doc.patch([at(list.path, set(items))])
|
|
248
|
+
// Morceau de texte riche : jamais retiré (un morceau sans texte casse le bloc), vidé.
|
|
249
|
+
else if (isSpanTextPath(node.path)) doc.patch([at(node.path, set(next))])
|
|
250
|
+
else doc.patch([at(node.path, next.trim() === '' ? unset() : set(next))])
|
|
251
|
+
setStatus('saving')
|
|
252
|
+
}, [value, inherited, getDocument, node.id, node.path])
|
|
253
|
+
|
|
254
|
+
// Enregistré : le texte saisi reste affiché jusqu'à ce que l'aperçu montre la
|
|
255
|
+
// nouvelle valeur (pas de retour éclair à l'ancien texte), 6 s au plus.
|
|
256
|
+
useEffect(() => {
|
|
257
|
+
if (status !== 'saving') return
|
|
258
|
+
const expected = value.replace(/\s+/g, ' ').trim()
|
|
259
|
+
const started = performance.now()
|
|
260
|
+
const timer = window.setInterval(() => {
|
|
261
|
+
const shown = vercelStegaClean(element.textContent ?? '').replace(/\s+/g, ' ').trim()
|
|
262
|
+
if (shown.includes(expected) || expected === '' || performance.now() - started > 6000) inlineEdit.close()
|
|
263
|
+
}, 150)
|
|
264
|
+
return () => window.clearInterval(timer)
|
|
265
|
+
}, [status, value, element])
|
|
266
|
+
|
|
267
|
+
// Clic ailleurs dans l'aperçu = enregistrer.
|
|
268
|
+
useEffect(() => {
|
|
269
|
+
if (status !== 'editing') return
|
|
270
|
+
const onPointerDown = (event: PointerEvent) => {
|
|
271
|
+
if (event.target instanceof Node && rootRef.current?.contains(event.target)) return
|
|
272
|
+
save()
|
|
273
|
+
}
|
|
274
|
+
window.addEventListener('pointerdown', onPointerDown, {capture: true})
|
|
275
|
+
return () => window.removeEventListener('pointerdown', onPointerDown, {capture: true})
|
|
276
|
+
}, [status, save])
|
|
277
|
+
|
|
278
|
+
const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
|
|
279
|
+
if (event.key === 'Escape') {
|
|
280
|
+
event.preventDefault()
|
|
281
|
+
inlineEdit.close()
|
|
282
|
+
} else if (event.key === 'Enter' && !(event.shiftKey && multiline.current)) {
|
|
283
|
+
event.preventDefault()
|
|
284
|
+
save()
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (!box) return null
|
|
289
|
+
const below = box.top + box.height + 56 < window.innerHeight
|
|
290
|
+
const place: CSSProperties = below ? {top: '100%', marginTop: 12} : {bottom: '100%', marginBottom: 12}
|
|
291
|
+
|
|
292
|
+
return (
|
|
293
|
+
<div
|
|
294
|
+
ref={rootRef}
|
|
295
|
+
data-sanity-overlay-element
|
|
296
|
+
style={{position: 'fixed', zIndex: 2147483000, top: box.top, left: box.left, width: box.width, minHeight: box.height}}
|
|
297
|
+
>
|
|
298
|
+
<textarea
|
|
299
|
+
ref={fieldRef}
|
|
300
|
+
value={value}
|
|
301
|
+
rows={1}
|
|
302
|
+
spellCheck
|
|
303
|
+
readOnly={status !== 'editing'}
|
|
304
|
+
aria-label={labels.fieldLabel}
|
|
305
|
+
onChange={(e) => setValue(e.target.value)}
|
|
306
|
+
onKeyDown={onKeyDown}
|
|
307
|
+
style={{
|
|
308
|
+
...typo,
|
|
309
|
+
display: 'block',
|
|
310
|
+
width: '100%',
|
|
311
|
+
minHeight: box.height,
|
|
312
|
+
margin: 0,
|
|
313
|
+
padding: 0,
|
|
314
|
+
border: 0,
|
|
315
|
+
borderRadius: 2,
|
|
316
|
+
resize: 'none',
|
|
317
|
+
overflow: 'hidden',
|
|
318
|
+
background: 'transparent',
|
|
319
|
+
caretColor: ACCENT,
|
|
320
|
+
outline: `2px solid ${ACCENT}`,
|
|
321
|
+
outlineOffset: 4,
|
|
322
|
+
opacity: status === 'loading' ? 0 : 1,
|
|
323
|
+
}}
|
|
324
|
+
/>
|
|
325
|
+
<div style={{...CHIP_STYLE, ...place}}>
|
|
326
|
+
{status === 'saving' ? (
|
|
327
|
+
<span style={{padding: '6px 10px'}}>{labels.saved}</span>
|
|
328
|
+
) : (
|
|
329
|
+
<>
|
|
330
|
+
<button type="button" onClick={save} disabled={status !== 'editing'} style={{...BUTTON_STYLE, background: ACCENT, color: '#fff'}}>
|
|
331
|
+
{labels.save}
|
|
332
|
+
<kbd style={KBD_STYLE}>↵</kbd>
|
|
333
|
+
</button>
|
|
334
|
+
<button type="button" onClick={() => inlineEdit.close()} style={{...BUTTON_STYLE, background: 'transparent', color: 'rgba(255,255,255,0.85)'}}>
|
|
335
|
+
{labels.cancel}
|
|
336
|
+
<kbd style={KBD_STYLE}>Esc</kbd>
|
|
337
|
+
</button>
|
|
338
|
+
</>
|
|
339
|
+
)}
|
|
340
|
+
</div>
|
|
341
|
+
{inherited && status === 'editing' && (
|
|
342
|
+
<p
|
|
343
|
+
style={{
|
|
344
|
+
position: 'absolute',
|
|
345
|
+
left: 0,
|
|
346
|
+
...(below ? {top: '100%', marginTop: 56} : {bottom: '100%', marginBottom: 56}),
|
|
347
|
+
width: 'max-content',
|
|
348
|
+
maxWidth: 'min(28rem, 90vw)',
|
|
349
|
+
padding: '8px 12px',
|
|
350
|
+
borderRadius: 6,
|
|
351
|
+
background: '#fff',
|
|
352
|
+
color: '#1b1d21',
|
|
353
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
|
|
354
|
+
font: `12px/1.35 ${FONT}`,
|
|
355
|
+
fontStyle: 'normal',
|
|
356
|
+
textTransform: 'none',
|
|
357
|
+
letterSpacing: 'normal',
|
|
358
|
+
}}
|
|
359
|
+
>
|
|
360
|
+
{labels.inheritedNote}
|
|
361
|
+
</p>
|
|
362
|
+
)}
|
|
363
|
+
</div>
|
|
364
|
+
)
|
|
365
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import {useEffect} from 'react'
|
|
2
|
+
import type {OverlayComponentProps} from '@sanity/visual-editing/unstable_overlay-components'
|
|
3
|
+
import {ACCENT} from './labels'
|
|
4
|
+
import {inlineEdit} from './store'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Monté par l'overlay de Sanity au survol d'un texte modifiable sur place : crayon
|
|
8
|
+
* en haut à droite du cadre, et inscription comme cible du prochain clic
|
|
9
|
+
* (`InlineTextEditor` écoute le clic avant Sanity).
|
|
10
|
+
*/
|
|
11
|
+
export function InlineTextOverlay({element, node}: OverlayComponentProps) {
|
|
12
|
+
useEffect(() => {
|
|
13
|
+
if (!(element instanceof HTMLElement)) return
|
|
14
|
+
inlineEdit.setHovered({element, node})
|
|
15
|
+
return () => inlineEdit.clearHovered(element)
|
|
16
|
+
}, [element, node])
|
|
17
|
+
|
|
18
|
+
return (
|
|
19
|
+
<span
|
|
20
|
+
aria-hidden
|
|
21
|
+
style={{
|
|
22
|
+
pointerEvents: 'none',
|
|
23
|
+
position: 'absolute',
|
|
24
|
+
top: -12,
|
|
25
|
+
right: -12,
|
|
26
|
+
display: 'flex',
|
|
27
|
+
width: 24,
|
|
28
|
+
height: 24,
|
|
29
|
+
alignItems: 'center',
|
|
30
|
+
justifyContent: 'center',
|
|
31
|
+
borderRadius: 999,
|
|
32
|
+
background: ACCENT,
|
|
33
|
+
color: '#fff',
|
|
34
|
+
boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
|
|
35
|
+
}}
|
|
36
|
+
>
|
|
37
|
+
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
|
|
38
|
+
<path d="M10.5 2.5l3 3L6 13H3v-3l7.5-7.5z" />
|
|
39
|
+
<path d="M9 4l3 3" />
|
|
40
|
+
</svg>
|
|
41
|
+
</span>
|
|
42
|
+
)
|
|
43
|
+
}
|