@nocode-factory/sanity-kit 2.16.0 → 2.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +175 -70
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/hooks/usePreviewTarget.ts +9 -3
- package/src/lib/openComponent.ts +5 -2
- package/src/lib/studioLinks.ts +20 -0
- package/src/lib/undo.ts +91 -0
- package/src/tools/history/DiffPanel.tsx +87 -37
- package/src/tools/navbar/PreviewLauncher.tsx +6 -2
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -2,6 +2,8 @@ import {useCallback, useMemo, useState} from 'react'
|
|
|
2
2
|
import {useKitConfig} from '../context/KitContext'
|
|
3
3
|
import {useKitClient} from './useKitClient'
|
|
4
4
|
import {
|
|
5
|
+
defaultEnvironmentId,
|
|
6
|
+
editableEnvironment,
|
|
5
7
|
customEnvironment,
|
|
6
8
|
CUSTOM_ENVIRONMENT_ID,
|
|
7
9
|
effectivePerspective,
|
|
@@ -74,7 +76,8 @@ export function usePreviewTargetState(): PreviewTargetState {
|
|
|
74
76
|
const scope = `${STORAGE_PREFIX}${client.config().projectId ?? 'sans-projet'}`
|
|
75
77
|
|
|
76
78
|
const environments = config.environments
|
|
77
|
-
|
|
79
|
+
// Par défaut la préproduction : c'est là qu'on édite.
|
|
80
|
+
const fallback = defaultEnvironmentId(environments, config.previewUrl)
|
|
78
81
|
|
|
79
82
|
const [environmentId, setStoredEnvironment] = useState<string | null>(() => {
|
|
80
83
|
const saved = read(`${scope}:environment`)
|
|
@@ -141,9 +144,12 @@ export function usePreviewTargetState(): PreviewTargetState {
|
|
|
141
144
|
// La production n'a que le contenu en ligne, quel que soit le choix retenu.
|
|
142
145
|
const shown = effectivePerspective(environment, perspective, config.previewUrl)
|
|
143
146
|
|
|
147
|
+
// Presentation s'ouvre toujours sur un environnement éditable (jamais la
|
|
148
|
+
// production) ; production choisie = préproduction, contenu en ligne.
|
|
144
149
|
const pathFor = useCallback(
|
|
145
|
-
(url: string | null) =>
|
|
146
|
-
|
|
150
|
+
(url: string | null) =>
|
|
151
|
+
presentationPath(url, {environment: editableEnvironment(environment, allEnvironments, config.previewUrl), perspective: shown}),
|
|
152
|
+
[environment, allEnvironments, config.previewUrl, shown],
|
|
147
153
|
)
|
|
148
154
|
|
|
149
155
|
const siteUrlFor = useCallback(
|
package/src/lib/openComponent.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type {SanityClient} from 'sanity'
|
|
2
2
|
import type {ResolvedKitConfig} from '../config/types'
|
|
3
3
|
import {componentIntentParams, fillTemplate} from './blocks'
|
|
4
|
-
import {presentationPath} from './studioLinks'
|
|
4
|
+
import {editableEnvironment, presentationPath, urlOn} from './studioLinks'
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Ouvre un composant : Presentation avec son rendu réel et ses valeurs par
|
|
@@ -71,6 +71,9 @@ export async function openDesignSystem(options: {
|
|
|
71
71
|
navigateIntent('edit', designSystemIntentParams(config, id ?? config.componentPreview.defaultsType))
|
|
72
72
|
return
|
|
73
73
|
}
|
|
74
|
-
|
|
74
|
+
// Sur la préproduction (éditable), jamais sur la production.
|
|
75
|
+
const env = editableEnvironment(config.environments[0] ?? null, config.environments, config.previewUrl)
|
|
76
|
+
const url = urlOn(env, config.componentPreview.path) ?? (config.previewUrl ? `${config.previewUrl}${config.componentPreview.path}` : null)
|
|
77
|
+
const path = presentationPath(url, env ? {environment: env} : {})
|
|
75
78
|
if (path) navigateUrl(path)
|
|
76
79
|
}
|
package/src/lib/studioLinks.ts
CHANGED
|
@@ -82,6 +82,26 @@ export function effectivePerspective(environment: NcfEnvironment | null, perspec
|
|
|
82
82
|
return environment && isPublicEnvironment(environment, previewUrl) ? 'published' : perspective
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Environnement où ouvrir Presentation : on n'édite jamais la production (elle ne
|
|
87
|
+
* montre pas les brouillons et ne charge pas l'édition visuelle : « Unable to
|
|
88
|
+
* connect »). Production choisie : la première préversion déclarée, qui montrera
|
|
89
|
+
* le contenu en ligne. Sans préversion : l'environnement choisi, tel quel.
|
|
90
|
+
*/
|
|
91
|
+
export function editableEnvironment(
|
|
92
|
+
selected: NcfEnvironment | null,
|
|
93
|
+
environments: readonly NcfEnvironment[],
|
|
94
|
+
previewUrl: string | null | undefined,
|
|
95
|
+
): NcfEnvironment | null {
|
|
96
|
+
if (!selected || !isPublicEnvironment(selected, previewUrl)) return selected
|
|
97
|
+
return environments.find((e) => !isPublicEnvironment(e, previewUrl)) ?? selected
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Environnement proposé par défaut : la première préversion, sinon le premier déclaré. */
|
|
101
|
+
export function defaultEnvironmentId(environments: readonly NcfEnvironment[], previewUrl: string | null | undefined): string | null {
|
|
102
|
+
return (environments.find((e) => !isPublicEnvironment(e, previewUrl)) ?? environments[0])?.id ?? null
|
|
103
|
+
}
|
|
104
|
+
|
|
85
105
|
export interface OnlineUrlOptions {
|
|
86
106
|
/** Chemin de la page (défaut : l'accueil). */
|
|
87
107
|
path?: string | null
|
package/src/lib/undo.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* « Annuler cette modification » de l'Historique.
|
|
3
|
+
*
|
|
4
|
+
* Remettre l'état d'avant TOUT ENTIER effacerait aussi ce qui a été fait après.
|
|
5
|
+
* On annule donc seulement ce que l'événement a changé, dans le document
|
|
6
|
+
* ACTUEL (fusion à trois états : avant, après, actuel) :
|
|
7
|
+
* - une valeur que l'événement a changée reprend sa valeur d'avant, sauf si
|
|
8
|
+
* elle a encore changé depuis (conflit : laissée telle quelle, signalée) ;
|
|
9
|
+
* - un élément de liste (section, bouton…) ajouté par l'événement est retiré,
|
|
10
|
+
* un élément supprimé est remis à sa place ;
|
|
11
|
+
* - tout le reste du document actuel est conservé.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const SYSTEM_KEYS = new Set(['_rev', '_updatedAt', '_createdAt', '_id', '_type'])
|
|
15
|
+
|
|
16
|
+
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
17
|
+
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
|
|
18
|
+
const keyed = (v: unknown): v is Array<Record<string, unknown> & {_key: string}> =>
|
|
19
|
+
Array.isArray(v) && v.every((item) => isObject(item) && typeof item._key === 'string')
|
|
20
|
+
|
|
21
|
+
export interface UndoResult {
|
|
22
|
+
/** Document actuel, modification annulée. */
|
|
23
|
+
document: Record<string, unknown>
|
|
24
|
+
/** Chemins changés depuis l'événement : non annulés. */
|
|
25
|
+
conflicts: string[]
|
|
26
|
+
/** Nombre de valeurs remises. */
|
|
27
|
+
reverted: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const ABSENT = Symbol('absent')
|
|
31
|
+
type Value = unknown | typeof ABSENT
|
|
32
|
+
|
|
33
|
+
function revert(current: Value, before: Value, after: Value, path: string, out: {conflicts: string[]; reverted: number}): Value {
|
|
34
|
+
if (same(before, after)) return current
|
|
35
|
+
// Rien n'a bougé depuis l'événement : on remet l'état d'avant tel quel.
|
|
36
|
+
if (same(current, after)) {
|
|
37
|
+
out.reverted++
|
|
38
|
+
return before
|
|
39
|
+
}
|
|
40
|
+
if (isObject(current) && isObject(before) && isObject(after)) {
|
|
41
|
+
const result: Record<string, unknown> = {...current}
|
|
42
|
+
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
43
|
+
if (SYSTEM_KEYS.has(key)) continue
|
|
44
|
+
const v = revert(key in current ? current[key] : ABSENT, key in before ? before[key] : ABSENT, key in after ? after[key] : ABSENT, path ? `${path}.${key}` : key, out)
|
|
45
|
+
if (v === ABSENT) delete result[key]
|
|
46
|
+
else result[key] = v
|
|
47
|
+
}
|
|
48
|
+
return result
|
|
49
|
+
}
|
|
50
|
+
if (keyed(current) && keyed(before) && keyed(after)) {
|
|
51
|
+
const result = [...current]
|
|
52
|
+
const at = (list: typeof current, key: string) => list.findIndex((item) => item._key === key)
|
|
53
|
+
for (const key of new Set([...before.map((i) => i._key), ...after.map((i) => i._key)])) {
|
|
54
|
+
const b = before[at(before, key)]
|
|
55
|
+
const a = after[at(after, key)]
|
|
56
|
+
const index = at(result, key)
|
|
57
|
+
const label = `${path}[${key}]`
|
|
58
|
+
if (index >= 0) {
|
|
59
|
+
const v = revert(result[index], b ?? ABSENT, a ?? ABSENT, label, out)
|
|
60
|
+
if (v === ABSENT) result.splice(index, 1)
|
|
61
|
+
else result[index] = v as (typeof result)[number]
|
|
62
|
+
} else if (b && !a) {
|
|
63
|
+
// Supprimé par l'événement, toujours absent : remis à sa place d'origine.
|
|
64
|
+
result.splice(Math.min(at(before, key), result.length), 0, b)
|
|
65
|
+
out.reverted++
|
|
66
|
+
} else if (b && a && !same(a, b)) {
|
|
67
|
+
// Modifié par l'événement puis supprimé depuis : on ne le ressuscite pas.
|
|
68
|
+
out.conflicts.push(label)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return result
|
|
72
|
+
}
|
|
73
|
+
out.conflicts.push(path || '(document)')
|
|
74
|
+
return current
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Annule l'événement `before` → `after` dans `current` (brouillon ou version
|
|
79
|
+
* publiée actuelle). `current` absent (document supprimé depuis) : l'état
|
|
80
|
+
* d'avant l'événement.
|
|
81
|
+
*/
|
|
82
|
+
export function undoChange(
|
|
83
|
+
current: Record<string, unknown> | null,
|
|
84
|
+
before: Record<string, unknown> | null,
|
|
85
|
+
after: Record<string, unknown> | null,
|
|
86
|
+
): UndoResult {
|
|
87
|
+
const out = {conflicts: [] as string[], reverted: 0}
|
|
88
|
+
const base = current ?? after ?? {}
|
|
89
|
+
const document = revert(base, before ?? {}, after ?? {}, '', out) as Record<string, unknown>
|
|
90
|
+
return {document: isObject(document) ? document : {}, conflicts: out.conflicts, reverted: out.reverted}
|
|
91
|
+
}
|
|
@@ -7,6 +7,8 @@ import {useKitConfig} from '../../context/KitContext'
|
|
|
7
7
|
import {useKitClient} from '../../hooks/useKitClient'
|
|
8
8
|
import {fetchDetail, type HistoryDetail, type HistoryEvent} from '../../lib/service'
|
|
9
9
|
import {diffDocuments} from '../../lib/diff'
|
|
10
|
+
import {undoChange} from '../../lib/undo'
|
|
11
|
+
import {UndoIcon} from '@sanity/icons/Undo'
|
|
10
12
|
import {ChangeRow} from './ChangeRow'
|
|
11
13
|
import {BORDER} from '../../ui/tokens'
|
|
12
14
|
import {ActorName} from '../../ui/ActorName'
|
|
@@ -33,6 +35,8 @@ export function DiffPanel(props: DiffPanelProps) {
|
|
|
33
35
|
const [error, setError] = useState<string | null>(null)
|
|
34
36
|
const [restoring, setRestoring] = useState(false)
|
|
35
37
|
const [restored, setRestored] = useState<string | null>(null)
|
|
38
|
+
/** Chemins changés depuis l'événement, laissés tels quels par l'annulation. */
|
|
39
|
+
const [conflicts, setConflicts] = useState<string[]>([])
|
|
36
40
|
|
|
37
41
|
useEffect(() => {
|
|
38
42
|
if (!config.history) return undefined
|
|
@@ -40,6 +44,7 @@ export function DiffPanel(props: DiffPanelProps) {
|
|
|
40
44
|
setLoading(true)
|
|
41
45
|
setError(null)
|
|
42
46
|
setRestored(null)
|
|
47
|
+
setConflicts([])
|
|
43
48
|
|
|
44
49
|
fetchDetail(config.history.endpoint, config.history.projectKey, event.id, controller.signal)
|
|
45
50
|
.then((result) => {
|
|
@@ -58,28 +63,23 @@ export function DiffPanel(props: DiffPanelProps) {
|
|
|
58
63
|
const snapshot = detail?.current.snapshot ?? null
|
|
59
64
|
const changes = detail ? diffDocuments(detail.previous?.snapshot ?? null, snapshot) : []
|
|
60
65
|
|
|
61
|
-
const
|
|
62
|
-
|
|
66
|
+
const base = event.document_id.replace(/^drafts\./, '')
|
|
67
|
+
|
|
68
|
+
// Écrit dans le brouillon, jamais par-dessus la version publiée : l'éditeur
|
|
69
|
+
// relit et publie. `createOrReplace` et non `patch` : un `patch` exige un
|
|
70
|
+
// document existant, et échouerait sur un document supprimé depuis.
|
|
71
|
+
const writeDraft = async (content: Record<string, unknown>) => {
|
|
72
|
+
const {_rev, _createdAt, _updatedAt, ...rest} = content
|
|
73
|
+
await client.createOrReplace({...rest, _id: `drafts.${base}`, _type: event.document_type} as {_id: string; _type: string})
|
|
74
|
+
setRestored(base)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const run = async (action: () => Promise<void>) => {
|
|
63
78
|
setRestoring(true)
|
|
64
79
|
setError(null)
|
|
80
|
+
setConflicts([])
|
|
65
81
|
try {
|
|
66
|
-
|
|
67
|
-
// existant, et échouerait donc sur une suppression — c'est-à-dire
|
|
68
|
-
// précisément quand une restauration compte le plus.
|
|
69
|
-
//
|
|
70
|
-
// On écrit dans le brouillon, jamais par-dessus la version publiée :
|
|
71
|
-
// l'éditeur relit et publie. Une restauration ne doit pas mettre en
|
|
72
|
-
// ligne un état ancien sans que personne l'ait vu.
|
|
73
|
-
const {_rev, _createdAt, _updatedAt, ...content} = snapshot as Record<string, unknown>
|
|
74
|
-
const base = event.document_id.replace(/^drafts\./, '')
|
|
75
|
-
|
|
76
|
-
await client.createOrReplace({
|
|
77
|
-
...content,
|
|
78
|
-
_id: `drafts.${base}`,
|
|
79
|
-
_type: event.document_type,
|
|
80
|
-
} as {_id: string; _type: string})
|
|
81
|
-
|
|
82
|
-
setRestored(base)
|
|
82
|
+
await action()
|
|
83
83
|
} catch (cause) {
|
|
84
84
|
setError(explainRestore(cause))
|
|
85
85
|
} finally {
|
|
@@ -87,6 +87,30 @@ export function DiffPanel(props: DiffPanelProps) {
|
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
/** Revenir à l'état d'avant CETTE modification, sans perdre ce qui a suivi. */
|
|
91
|
+
const undo = () =>
|
|
92
|
+
run(async () => {
|
|
93
|
+
if (!detail) return
|
|
94
|
+
// État actuel : le brouillon en cours, sinon la version publiée.
|
|
95
|
+
const current =
|
|
96
|
+
((await client.getDocument(`drafts.${base}`)) as Record<string, unknown> | undefined) ??
|
|
97
|
+
((await client.getDocument(base)) as Record<string, unknown> | undefined) ??
|
|
98
|
+
null
|
|
99
|
+
const result = undoChange(
|
|
100
|
+
current,
|
|
101
|
+
(detail.previous?.snapshot as Record<string, unknown> | null) ?? null,
|
|
102
|
+
(snapshot as Record<string, unknown> | null) ?? null,
|
|
103
|
+
)
|
|
104
|
+
await writeDraft(result.document)
|
|
105
|
+
setConflicts(result.conflicts)
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
/** Remettre le document entier dans l'état APRÈS cette modification. */
|
|
109
|
+
const restore = () =>
|
|
110
|
+
run(async () => {
|
|
111
|
+
if (snapshot) await writeDraft(snapshot as Record<string, unknown>)
|
|
112
|
+
})
|
|
113
|
+
|
|
90
114
|
return (
|
|
91
115
|
<Card radius={3} shadow={1} padding={3} style={{width: 420, flex: 'none', overflow: 'auto'}}>
|
|
92
116
|
<Stack gap={3}>
|
|
@@ -131,9 +155,14 @@ export function DiffPanel(props: DiffPanelProps) {
|
|
|
131
155
|
<Card padding={3} radius={2} tone="positive">
|
|
132
156
|
<Stack gap={3}>
|
|
133
157
|
<Text size={1}>
|
|
134
|
-
|
|
135
|
-
|
|
158
|
+
Fait <b>en brouillon</b>. Rien n'est encore en ligne : ouvrez le document,
|
|
159
|
+
vérifiez, puis <b>publiez</b>.
|
|
136
160
|
</Text>
|
|
161
|
+
{conflicts.length > 0 && (
|
|
162
|
+
<Text size={1}>
|
|
163
|
+
Non annulé, car modifié depuis : {conflicts.join(', ')}.
|
|
164
|
+
</Text>
|
|
165
|
+
)}
|
|
137
166
|
<IntentLink
|
|
138
167
|
intent="edit"
|
|
139
168
|
params={{id: restored, type: event.document_type}}
|
|
@@ -183,22 +212,43 @@ export function DiffPanel(props: DiffPanelProps) {
|
|
|
183
212
|
|
|
184
213
|
{snapshot && (
|
|
185
214
|
<Box style={{borderTop: `1px solid ${BORDER}`, paddingTop: 12}}>
|
|
186
|
-
<Stack gap={
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
215
|
+
<Stack gap={3}>
|
|
216
|
+
{detail.previous && changes.length > 0 && (
|
|
217
|
+
<Stack gap={2}>
|
|
218
|
+
<Button
|
|
219
|
+
mode="default"
|
|
220
|
+
tone="primary"
|
|
221
|
+
fontSize={1}
|
|
222
|
+
padding={3}
|
|
223
|
+
icon={UndoIcon}
|
|
224
|
+
text={restoring ? 'Annulation…' : 'Annuler cette modification'}
|
|
225
|
+
disabled={restoring}
|
|
226
|
+
onClick={undo}
|
|
227
|
+
/>
|
|
228
|
+
<Text size={0} muted>
|
|
229
|
+
Remet les valeurs d'avant cette modification, et seulement elles : ce
|
|
230
|
+
qui a été modifié ensuite est conservé. Le résultat va dans le
|
|
231
|
+
brouillon : publiez-le pour le mettre en ligne.
|
|
232
|
+
</Text>
|
|
233
|
+
</Stack>
|
|
234
|
+
)}
|
|
235
|
+
<Stack gap={2}>
|
|
236
|
+
<Button
|
|
237
|
+
mode="ghost"
|
|
238
|
+
tone="caution"
|
|
239
|
+
fontSize={1}
|
|
240
|
+
padding={3}
|
|
241
|
+
icon={RestoreIcon}
|
|
242
|
+
text={restoring ? 'Restauration…' : 'Restaurer le document tel qu’après cette modification'}
|
|
243
|
+
disabled={restoring}
|
|
244
|
+
onClick={restore}
|
|
245
|
+
/>
|
|
246
|
+
<Text size={0} muted>
|
|
247
|
+
Remet le document ENTIER dans l'état qui a suivi cette modification
|
|
248
|
+
(les modifications plus récentes sont perdues), dans le brouillon. La
|
|
249
|
+
version en ligne n'est pas touchée tant que vous ne publiez pas.
|
|
250
|
+
</Text>
|
|
251
|
+
</Stack>
|
|
202
252
|
</Stack>
|
|
203
253
|
</Box>
|
|
204
254
|
)}
|
|
@@ -3,7 +3,7 @@ import {useRouter} from 'sanity/router'
|
|
|
3
3
|
import type {ToolMenuProps} from 'sanity'
|
|
4
4
|
import {InlinePopover} from '../../ui/Popover'
|
|
5
5
|
import {KitProvider, useKitConfig} from '../../context/KitContext'
|
|
6
|
-
import {presentationPath, previewTargets, type PreviewPerspective} from '../../lib/studioLinks'
|
|
6
|
+
import {editableEnvironment, isPublicEnvironment, presentationPath, previewTargets, type PreviewPerspective} from '../../lib/studioLinks'
|
|
7
7
|
import {useOpenOnline} from '../../hooks/useOpenOnline'
|
|
8
8
|
import type {ConfigIssue, NcfEnvironment, ResolvedKitConfig} from '../../config/types'
|
|
9
9
|
import {EyeOpenIcon} from '@sanity/icons/EyeOpen'
|
|
@@ -46,8 +46,12 @@ export function NcfPreviewLauncher(props: ToolMenuProps) {
|
|
|
46
46
|
|
|
47
47
|
// Ouvre l'aperçu DANS le Studio : la page apparaît dans Presentation, sans
|
|
48
48
|
// quitter le Studio.
|
|
49
|
+
// Jamais la production dans Presentation (pas d'édition possible) : « Prod · En
|
|
50
|
+
// ligne » s'ouvre sur la préproduction, en contenu en ligne.
|
|
49
51
|
const openInStudio = (environment: NcfEnvironment, perspective: PreviewPerspective) => {
|
|
50
|
-
const
|
|
52
|
+
const target = editableEnvironment(environment, environments, config.previewUrl) ?? environment
|
|
53
|
+
const shown = isPublicEnvironment(environment, config.previewUrl) ? 'published' : perspective
|
|
54
|
+
const path = presentationPath(target.url, {environment: target, perspective: shown})
|
|
51
55
|
if (path) router.navigateUrl({path})
|
|
52
56
|
}
|
|
53
57
|
|
package/src/version.ts
CHANGED