@nocode-factory/sanity-kit 2.6.2 → 2.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.6.2",
3
+ "version": "2.8.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -33,6 +33,8 @@ export const DEFAULT_COMPONENT_PREVIEW: Required<NcfComponentPreviewConfig> = {
33
33
  path: '/design-system',
34
34
  anchor: '{name}',
35
35
  thumbnail: '/sections/{name}.png',
36
+ defaultsType: 'componentDefaults',
37
+ live: '/design-system/composant?type={name}',
36
38
  }
37
39
 
38
40
  export const DEFAULT_TOOLS: Required<NcfToolsConfig> = {
@@ -98,6 +98,8 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
98
98
  path: input.componentPreview?.path ?? DEFAULT_COMPONENT_PREVIEW.path,
99
99
  anchor: input.componentPreview?.anchor ?? DEFAULT_COMPONENT_PREVIEW.anchor,
100
100
  thumbnail: input.componentPreview?.thumbnail ?? DEFAULT_COMPONENT_PREVIEW.thumbnail,
101
+ defaultsType: input.componentPreview?.defaultsType ?? DEFAULT_COMPONENT_PREVIEW.defaultsType,
102
+ live: input.componentPreview?.live ?? DEFAULT_COMPONENT_PREVIEW.live,
101
103
  },
102
104
  serviceEndpoint:
103
105
  input.serviceEndpoint === false
@@ -52,6 +52,14 @@ export interface NcfComponentPreviewConfig {
52
52
  anchor?: string
53
53
  /** Chemin de la capture, relatif à `previewUrl`. Gabarit : {name} / {kebab}. */
54
54
  thumbnail?: string
55
+ /**
56
+ * Type du document des valeurs par défaut des composants (un champ par
57
+ * composant, nommé `{name}`). Présent dans le schéma : un clic sur un composant
58
+ * ouvre Presentation avec son rendu réel et ses valeurs par défaut côte à côte.
59
+ */
60
+ defaultsType?: string
61
+ /** Page qui rend un composant seul, avec ses valeurs par défaut. Gabarit : {name} / {kebab}. */
62
+ live?: string
55
63
  }
56
64
 
57
65
  /** Journal des modifications (phase 2). */
@@ -232,6 +240,8 @@ export interface ResolvedComponentPreview {
232
240
  path: string
233
241
  anchor: string
234
242
  thumbnail: string
243
+ defaultsType: string
244
+ live: string
235
245
  }
236
246
 
237
247
  export interface ResolvedKitConfig {
@@ -0,0 +1,134 @@
1
+ import {useState, type ComponentType} from 'react'
2
+ import {unset, useFormValue, useSchema, type InputProps} from 'sanity'
3
+ import {Box, Flex, Text} from '@sanity/ui'
4
+ import {Tooltip} from '@sanity/ui/tooltip'
5
+ import type {ResolvedKitConfig} from '../config/types'
6
+ import {blockName} from '../lib/blocks'
7
+ import {useKitClient} from '../hooks/useKitClient'
8
+ import {useComponentDefaults} from '../hooks/useComponentDefaults'
9
+ import {
10
+ defaultValueAt,
11
+ describeValue,
12
+ firstKeyedIndex,
13
+ isOverride,
14
+ relativeFieldPath,
15
+ sameValue,
16
+ type PathSegment,
17
+ } from '../lib/overrides'
18
+
19
+ /**
20
+ * Pastille bleue sur un champ d'une instance de composant qui a sa PROPRE valeur
21
+ * alors que le composant en a une par défaut (override). Au survol, elle devient
22
+ * « Réinitialiser » : le champ est vidé et reprend la valeur par défaut du
23
+ * composant. Seuls les champs « simples » en portent une (texte, nombre, choix,
24
+ * case, liste, image, couleur...) ; un objet composé (lien) les porte sur ses
25
+ * sous-champs.
26
+ */
27
+ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<InputProps> {
28
+ const {defaultsType} = config.componentPreview
29
+ const namespace = config.blockNamespace
30
+
31
+ function OverrideInput(props: InputProps) {
32
+ const schema = useSchema()
33
+ const path = props.path as PathSegment[]
34
+ const index = firstKeyedIndex(path)
35
+ // Une seule lecture de valeur : l'instance de composant (premier élément de
36
+ // liste du chemin) ; à défaut, la valeur du champ lui-même (bon marché).
37
+ const instance = useFormValue(index >= 0 ? (path.slice(0, index + 1) as never) : (path as never))
38
+ const parent = useFormValue((path.length > 1 ? path.slice(0, -1) : path) as never)
39
+ const rel = index >= 0 ? relativeFieldPath(path, index, instance, namespace) : null
40
+
41
+ if (!rel || !schema.get(defaultsType) || !carriesDot(props.schemaType)) return props.renderDefault(props)
42
+ const shortName = blockName((instance as {_type: string})._type, namespace)
43
+ return <WithDot {...props} rel={rel} shortName={shortName} parent={parent} />
44
+ }
45
+
46
+ function WithDot(props: InputProps & {rel: string[]; shortName: string; parent: unknown}) {
47
+ const {rel, shortName, parent, ...inputProps} = props
48
+ const client = useKitClient()
49
+ const languageField = config.i18n?.field ?? 'language'
50
+ const language = (useFormValue([languageField]) as string | undefined) ?? null
51
+ const defaults = useComponentDefaults(client, defaultsType, languageField, language)
52
+ const inherited = defaultValueAt(defaults, shortName, rel)
53
+ const field = rel[rel.length - 1] ?? ''
54
+
55
+ if (!isOverride(inputProps.value, inherited, field, parent)) return inputProps.renderDefault(inputProps)
56
+ return (
57
+ <Flex align="flex-start" gap={2}>
58
+ <Box flex={1} style={{minWidth: 0}}>
59
+ {inputProps.renderDefault(inputProps)}
60
+ </Box>
61
+ <OverrideDot
62
+ inherited={describeValue(inherited)}
63
+ same={sameValue(inputProps.value, inherited)}
64
+ onReset={() => inputProps.onChange(unset())}
65
+ />
66
+ </Flex>
67
+ )
68
+ }
69
+
70
+ return OverrideInput
71
+ }
72
+
73
+ // Champs qui portent la pastille : valeurs simples, listes, et objets « atomiques »
74
+ // (image, référence, ou objet à saisie personnalisée comme une couleur de charte).
75
+ type TypeChain = {name?: string; type?: TypeChain; components?: {input?: unknown}}
76
+ function carriesDot(schemaType: InputProps['schemaType']): boolean {
77
+ if (schemaType.jsonType !== 'object') return true
78
+ let t: TypeChain | undefined = schemaType as unknown as TypeChain
79
+ while (t) {
80
+ if (t.components?.input || t.name === 'image' || t.name === 'file' || t.name === 'reference') return true
81
+ t = t.type
82
+ }
83
+ return false
84
+ }
85
+
86
+ const BLUE = 'var(--card-badge-primary-dot-color, #2276fc)'
87
+
88
+ function OverrideDot(props: {inherited: string; same: boolean; onReset: () => void}) {
89
+ const [hover, setHover] = useState(false)
90
+ return (
91
+ <Tooltip
92
+ portal
93
+ placement="left"
94
+ content={
95
+ <Box padding={2} style={{maxWidth: 260}}>
96
+ <Text size={1}>
97
+ Valeur propre à cette instance{props.same ? ' (identique au défaut, mais figée : elle ne suivra pas ses changements)' : ''}.
98
+ Défaut du composant : {props.inherited}.
99
+ </Text>
100
+ </Box>
101
+ }
102
+ >
103
+ <button
104
+ type="button"
105
+ onClick={props.onReset}
106
+ onMouseEnter={() => setHover(true)}
107
+ onMouseLeave={() => setHover(false)}
108
+ onFocus={() => setHover(true)}
109
+ onBlur={() => setHover(false)}
110
+ aria-label="Réinitialiser à la valeur par défaut du composant"
111
+ style={{
112
+ marginTop: 9,
113
+ flex: 'none',
114
+ height: hover ? 22 : 10,
115
+ minWidth: 10,
116
+ padding: hover ? '0 8px' : 0,
117
+ borderRadius: 999,
118
+ border: 0,
119
+ background: BLUE,
120
+ color: '#fff',
121
+ fontSize: 11,
122
+ fontWeight: 600,
123
+ lineHeight: '22px',
124
+ whiteSpace: 'nowrap',
125
+ cursor: 'pointer',
126
+ transform: hover ? 'translateY(-6px)' : 'none',
127
+ transition: 'all 120ms ease',
128
+ }}
129
+ >
130
+ {hover ? '↺ Réinitialiser' : ''}
131
+ </button>
132
+ </Tooltip>
133
+ )
134
+ }
@@ -0,0 +1,67 @@
1
+ import {useEffect, useSyncExternalStore} from 'react'
2
+ import type {SanityClient} from 'sanity'
3
+
4
+ /**
5
+ * Valeurs par défaut des composants (document publié, dans la langue de
6
+ * l'instance), lues UNE fois et tenues à jour en direct pour tous les champs du
7
+ * formulaire : une seule requête et une seule écoute, quel que soit le nombre de
8
+ * pastilles affichées.
9
+ */
10
+ type Defaults = Record<string, unknown> | null
11
+ interface Entry {
12
+ value: Defaults
13
+ listeners: Set<() => void>
14
+ stop: (() => void) | null
15
+ }
16
+ const store = new Map<string, Entry>()
17
+
18
+ function entryFor(client: SanityClient, type: string, languageField: string, language: string | null): [string, Entry] {
19
+ const {projectId, dataset} = client.config()
20
+ const key = `${projectId}:${dataset}:${type}:${language ?? ''}`
21
+ let entry = store.get(key)
22
+ if (!entry) {
23
+ entry = {value: null, listeners: new Set(), stop: null}
24
+ store.set(key, entry)
25
+ }
26
+ const e = entry
27
+ if (!e.stop) {
28
+ const filter = `_type == $type && !(_id in path("drafts.**")) && ($language == null || !defined(${languageField}) || ${languageField} == $language)`
29
+ const params = {type, language}
30
+ const load = () =>
31
+ client
32
+ .fetch<Defaults>(`*[${filter}][0]`, params)
33
+ .then((value) => {
34
+ e.value = value
35
+ e.listeners.forEach((l) => l())
36
+ })
37
+ .catch(() => {})
38
+ void load()
39
+ const sub = client.listen(`*[${filter}]`, params, {visibility: 'query', includeResult: false}).subscribe({next: () => void load()})
40
+ e.stop = () => sub.unsubscribe()
41
+ }
42
+ return [key, e]
43
+ }
44
+
45
+ export function useComponentDefaults(client: SanityClient, type: string, languageField: string, language: string | null): Defaults {
46
+ const [, entry] = entryFor(client, type, languageField, language)
47
+ const value = useSyncExternalStore(
48
+ (listener) => {
49
+ entry.listeners.add(listener)
50
+ return () => {
51
+ entry.listeners.delete(listener)
52
+ }
53
+ },
54
+ () => entry.value,
55
+ )
56
+ // L'écoute reste ouverte tant qu'un champ l'utilise.
57
+ useEffect(
58
+ () => () => {
59
+ if (entry.listeners.size === 0 && entry.stop) {
60
+ entry.stop()
61
+ entry.stop = null
62
+ }
63
+ },
64
+ [entry],
65
+ )
66
+ return value
67
+ }
@@ -0,0 +1,43 @@
1
+ import {useCallback} from 'react'
2
+ import {useSchema} from 'sanity'
3
+ import {useRouter} from 'sanity/router'
4
+ import {useKitConfig} from '../context/KitContext'
5
+ import {componentIntentParams, fillTemplate} from '../lib/blocks'
6
+ import {useKitClient} from './useKitClient'
7
+
8
+ /**
9
+ * Ouvre un composant : Presentation avec son rendu réel et ses valeurs par
10
+ * défaut côte à côte. Sans document de valeurs par défaut dans le schéma : la
11
+ * démo du design system dans un nouvel onglet. `null` : rien à ouvrir.
12
+ * Partagé par la grille et la vue Map de l'onglet Composants.
13
+ */
14
+ export function useOpenComponent(): ((type: string) => void) | null {
15
+ const config = useKitConfig()
16
+ const schema = useSchema()
17
+ const router = useRouter()
18
+ const client = useKitClient()
19
+ const preview = config.componentPreview
20
+ const hasDefaults = Boolean(schema.get(preview.defaultsType))
21
+
22
+ const open = useCallback(
23
+ async (type: string) => {
24
+ if (!hasDefaults) {
25
+ if (config.previewUrl)
26
+ window.open(`${config.previewUrl}${preview.path}#${fillTemplate(preview.anchor, type, config.blockNamespace)}`, '_blank', 'noopener')
27
+ return
28
+ }
29
+ const lang = config.i18n?.defaultLocale ?? null
30
+ const id = await client
31
+ .fetch<string | null>(
32
+ `*[_type == $type] | order(select($lang != null && ${config.i18n?.field ?? 'language'} == $lang => 0, 1))[0]._id`,
33
+ {type: preview.defaultsType, lang},
34
+ )
35
+ .catch(() => null)
36
+ router.navigateIntent('edit', componentIntentParams(type, config.blockNamespace, preview, id ?? preview.defaultsType))
37
+ },
38
+ [hasDefaults, config, preview, client, router],
39
+ )
40
+
41
+ if (!hasDefaults && !config.previewUrl) return null
42
+ return (type: string) => void open(type)
43
+ }
package/src/index.ts CHANGED
@@ -34,6 +34,8 @@ export const NCF_TOOL_NAMES = [
34
34
  * La configuration est validée au démarrage. Une option invalide n'empêche
35
35
  * pas le Studio de démarrer : l'onglet concerné affiche le détail à corriger.
36
36
  */
37
+ import {createOverrideInput} from './form/OverrideInput'
38
+
37
39
  export const ncfKit = definePlugin<NcfKitConfig>((options) => {
38
40
  const config = resolveConfig(options)
39
41
  const issues = validateConfig(config)
@@ -111,6 +113,12 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
111
113
  studio: {
112
114
  components: {toolMenu: createPreviewLauncher(config, issues)},
113
115
  },
116
+
117
+ // Pastille bleue sur les champs d'une instance de composant qui surchargent
118
+ // la valeur par défaut du composant ; survol = « Réinitialiser ».
119
+ form: {
120
+ components: {input: createOverrideInput(config)},
121
+ },
114
122
  }
115
123
  })
116
124
 
package/src/lib/blocks.ts CHANGED
@@ -36,3 +36,24 @@ export function humanizeBlockName(type: string, namespace: string): string {
36
36
  const [first = '', ...rest] = words
37
37
  return [first.charAt(0).toUpperCase() + first.slice(1), ...rest].join(' ')
38
38
  }
39
+
40
+ /**
41
+ * Paramètres de l'intention qui ouvre un composant dans Presentation : son rendu
42
+ * réel (page `live`) à gauche, le champ de ses valeurs par défaut à droite.
43
+ * `documentId` : document des valeurs par défaut (créé à la première saisie s'il
44
+ * n'existe pas encore).
45
+ */
46
+ export function componentIntentParams(
47
+ type: string,
48
+ namespace: string,
49
+ preview: {defaultsType: string; live: string},
50
+ documentId: string,
51
+ ): Record<string, string> {
52
+ return {
53
+ id: documentId.replace(/^drafts\./, ''),
54
+ type: preview.defaultsType,
55
+ mode: 'presentation',
56
+ path: blockName(type, namespace),
57
+ preview: fillTemplate(preview.live, type, namespace),
58
+ }
59
+ }
@@ -12,6 +12,12 @@ export interface BlockOccurrence {
12
12
  count: number
13
13
  /** Identifiants des documents où le bloc apparaît, sans doublon. */
14
14
  documentIds: string[]
15
+ /**
16
+ * Emplacement de chaque instance : document et chemin depuis la racine du
17
+ * champ page builder (`[{_key}]`, ou plus profond pour un bloc imbriqué).
18
+ * Sert à ouvrir le formulaire directement sur l'instance.
19
+ */
20
+ locations: {documentId: string; path: ({_key: string} | string | number)[]}[]
15
21
  }
16
22
 
17
23
  export interface OccurrenceInput {
@@ -40,11 +46,12 @@ export function collectOccurrences(
40
46
  const seenPerType = new Map<string, Set<string>>()
41
47
 
42
48
  for (const doc of docs) {
43
- walk(doc.blocks, (type) => {
49
+ walk(doc.blocks, (type, path) => {
44
50
  if (!known.has(type)) return
45
51
 
46
- const entry = result.get(type) ?? {type, count: 0, documentIds: []}
52
+ const entry = result.get(type) ?? {type, count: 0, documentIds: [], locations: []}
47
53
  entry.count += 1
54
+ entry.locations.push({documentId: doc._id, path})
48
55
  result.set(type, entry)
49
56
 
50
57
  const seen = seenPerType.get(type) ?? new Set<string>()
@@ -59,18 +66,23 @@ export function collectOccurrences(
59
66
  return result
60
67
  }
61
68
 
62
- /** Appelle `visit` pour chaque `_type` rencontré, à toute profondeur. */
63
- function walk(value: unknown, visit: (type: string) => void): void {
69
+ type Segment = {_key: string} | string | number
70
+
71
+ /** Appelle `visit` pour chaque `_type` rencontré, à toute profondeur, avec son chemin. */
72
+ function walk(value: unknown, visit: (type: string, path: Segment[]) => void, path: Segment[] = []): void {
64
73
  if (Array.isArray(value)) {
65
- for (const item of value) walk(item, visit)
74
+ value.forEach((item, i) => {
75
+ const key = (item as {_key?: unknown} | null)?._key
76
+ walk(item, visit, [...path, typeof key === 'string' ? {_key: key} : i])
77
+ })
66
78
  return
67
79
  }
68
80
  if (value === null || typeof value !== 'object') return
69
81
 
70
82
  const type = (value as {_type?: unknown})._type
71
- if (typeof type === 'string') visit(type)
83
+ if (typeof type === 'string') visit(type, path)
72
84
 
73
- for (const child of Object.values(value)) walk(child, visit)
85
+ for (const [k, child] of Object.entries(value)) walk(child, visit, [...path, k])
74
86
  }
75
87
 
76
88
  /**
@@ -83,7 +95,7 @@ export function occurrencesForTypes(
83
95
  ): BlockOccurrence[] {
84
96
  const counted = collectOccurrences(docs, {blockTypes})
85
97
  return blockTypes.map(
86
- (type) => counted.get(type) ?? {type, count: 0, documentIds: []},
98
+ (type) => counted.get(type) ?? {type, count: 0, documentIds: [], locations: []},
87
99
  )
88
100
  }
89
101
 
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Overrides d'une instance de composant par rapport aux valeurs par défaut du
3
+ * composant (document `componentPreview.defaultsType`, un champ par composant
4
+ * nommé comme le bloc sans son espace de noms : `section.cta` -> `cta`).
5
+ *
6
+ * Règle d'héritage (appliquée par le site) : un champ VIDE de l'instance prend la
7
+ * valeur par défaut, un champ REMPLI est un override. La cible d'un lien (type +
8
+ * page/adresse/email...) forme un tout : sans cible, le lien hérite de la cible
9
+ * par défaut, type compris.
10
+ */
11
+
12
+ export type PathSegment = string | number | {_key: string} | [number | '', number | '']
13
+
14
+ export const LINK_TARGET_FIELDS = ['page', 'fixedPath', 'href', 'email', 'phone', 'file'] as const
15
+ const LINK_TYPES = new Set(['link', 'cardLink'])
16
+
17
+ export function isEmptyValue(value: unknown): boolean {
18
+ return value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)
19
+ }
20
+
21
+ const isKeyed = (s: PathSegment): s is {_key: string} =>
22
+ typeof s === 'object' && s !== null && !Array.isArray(s) && typeof (s as {_key?: unknown})._key === 'string'
23
+
24
+ /** Index du premier élément de liste du chemin (l'instance de composant dans le page builder), ou -1. */
25
+ export function firstKeyedIndex(path: readonly PathSegment[]): number {
26
+ return path.findIndex(isKeyed)
27
+ }
28
+
29
+ /**
30
+ * Chemin du champ à l'intérieur de l'instance (`['cta', 'style']`), si `instance`
31
+ * est bien un composant de l'espace de noms et que le chemin ne traverse pas une
32
+ * liste (une liste remplie remplace celle du défaut en entier : pas d'héritage
33
+ * élément par élément).
34
+ */
35
+ export function relativeFieldPath(
36
+ path: readonly PathSegment[],
37
+ index: number,
38
+ instance: unknown,
39
+ namespace: string,
40
+ ): string[] | null {
41
+ const type = (instance as {_type?: unknown} | null)?._type
42
+ if (index < 0 || typeof type !== 'string' || !type.startsWith(namespace)) return null
43
+ const rel = path.slice(index + 1)
44
+ if (rel.length === 0 || !rel.every((s) => typeof s === 'string')) return null
45
+ return rel as string[]
46
+ }
47
+
48
+ /** Valeur par défaut d'un champ de composant. */
49
+ export function defaultValueAt(
50
+ defaults: Record<string, unknown> | null | undefined,
51
+ blockShortName: string,
52
+ relPath: readonly string[],
53
+ ): unknown {
54
+ let node: unknown = defaults?.[blockShortName]
55
+ for (const key of relPath) {
56
+ if (!node || typeof node !== 'object') return undefined
57
+ node = (node as Record<string, unknown>)[key]
58
+ }
59
+ return node
60
+ }
61
+
62
+ /**
63
+ * Le champ est-il un override ? Valeur propre à l'instance ET valeur par défaut
64
+ * existante (sans défaut, il n'y a rien à surcharger). Le type d'un lien n'est
65
+ * jamais signalé : il est prérempli par le Studio et ne compte que si le lien a
66
+ * une cible.
67
+ */
68
+ export function isOverride(local: unknown, inherited: unknown, field: string, parent: unknown): boolean {
69
+ if (isEmptyValue(local) || isEmptyValue(inherited)) return false
70
+ const parentType = (parent as {_type?: unknown} | null)?._type
71
+ if (field === 'type' && typeof parentType === 'string' && LINK_TYPES.has(parentType)) return false
72
+ return true
73
+ }
74
+
75
+ /** Égalité de valeurs (champ identique au défaut : override « figé »). */
76
+ export function sameValue(a: unknown, b: unknown): boolean {
77
+ if (a === b) return true
78
+ const clean = (v: unknown): unknown =>
79
+ Array.isArray(v)
80
+ ? v.map(clean)
81
+ : v && typeof v === 'object'
82
+ ? Object.fromEntries(
83
+ Object.entries(v as Record<string, unknown>)
84
+ .filter(([k]) => !k.startsWith('_') || k === '_ref')
85
+ .sort(([x], [y]) => x.localeCompare(y))
86
+ .map(([k, x]) => [k, clean(x)]),
87
+ )
88
+ : v
89
+ return JSON.stringify(clean(a)) === JSON.stringify(clean(b))
90
+ }
91
+
92
+ /** Valeur par défaut lisible, pour la bulle de la pastille. */
93
+ export function describeValue(value: unknown): string {
94
+ if (typeof value === 'string') return value.length > 60 ? `« ${value.slice(0, 57)}… »` : `« ${value} »`
95
+ if (typeof value === 'boolean') return value ? 'Oui' : 'Non'
96
+ if (typeof value === 'number') return String(value)
97
+ if (Array.isArray(value)) return `${value.length} élément${value.length > 1 ? 's' : ''}`
98
+ if (value && typeof value === 'object') {
99
+ const v = value as Record<string, unknown>
100
+ if (typeof v.token === 'string') return `couleur ${v.token}`
101
+ if (typeof v.customHex === 'string') return `couleur ${v.customHex}`
102
+ if (typeof v.label === 'string') return `« ${v.label} »`
103
+ if (v.asset) return 'une image'
104
+ if (typeof v._ref === 'string') return 'un document'
105
+ }
106
+ return 'une valeur'
107
+ }
@@ -55,7 +55,7 @@ export function layoutSectionsMap(
55
55
  const entries = blocks
56
56
  .map((block) => ({
57
57
  block,
58
- occurrence: byType.get(block.name) ?? {type: block.name, count: 0, documentIds: []},
58
+ occurrence: byType.get(block.name) ?? {type: block.name, count: 0, documentIds: [], locations: []},
59
59
  }))
60
60
  .sort(compareBy(order))
61
61
 
@@ -10,6 +10,8 @@ export interface BlockCardProps {
10
10
  occurrence: BlockOccurrence
11
11
  namespace: string
12
12
  thumbnailUrl: string | null
13
+ /** Au clic : rendu réel du composant et réglage de ses valeurs par défaut. */
14
+ onOpen?: () => void
13
15
  }
14
16
 
15
17
  /**
@@ -21,12 +23,20 @@ export interface BlockCardProps {
21
23
  * à le lire.
22
24
  */
23
25
  export function BlockCard(props: BlockCardProps) {
24
- const {block, occurrence, namespace, thumbnailUrl} = props
26
+ const {block, occurrence, namespace, thumbnailUrl, onOpen} = props
25
27
  const [failed, setFailed] = useState(false)
26
28
  const unused = occurrence.count === 0
27
29
 
28
30
  return (
29
- <Card radius={3} shadow={1} padding={0} style={{height: '100%', overflow: 'hidden'}}>
31
+ <Card
32
+ radius={3}
33
+ shadow={1}
34
+ padding={0}
35
+ as={onOpen ? 'button' : undefined}
36
+ onClick={onOpen}
37
+ title={onOpen ? 'Voir le composant en vrai et régler ses valeurs par défaut' : undefined}
38
+ style={{height: '100%', overflow: 'hidden', width: '100%', textAlign: 'left', cursor: onOpen ? 'pointer' : undefined}}
39
+ >
30
40
  <Stack gap={0} style={{height: '100%'}}>
31
41
  <Box
32
42
  style={{
@@ -3,6 +3,7 @@ import {Box, Button, Card, Flex, Grid, Spinner, Stack, Text} from '@sanity/ui'
3
3
  import {useKitConfig} from '../../context/KitContext'
4
4
  import {useOccurrences, OCCURRENCE_SCAN_LIMIT} from '../../hooks/useOccurrences'
5
5
  import {fillTemplate} from '../../lib/blocks'
6
+ import {useOpenComponent} from '../../hooks/useOpenComponent'
6
7
  import {QueryError} from '../../ui/QueryError'
7
8
  import {BlockCard} from './BlockCard'
8
9
  import {SectionsMap} from './map/SectionsMap'
@@ -27,6 +28,7 @@ export function ComponentsTool() {
27
28
 
28
29
  const preview = config.componentPreview
29
30
  const canPreview = preview.provider === 'designSystemPage' && Boolean(config.previewUrl)
31
+ const openComponent = useOpenComponent()
30
32
 
31
33
  const cards = useMemo(() => {
32
34
  const byName = new Map(blockTypes.map((b) => [b.name, b]))
@@ -162,6 +164,7 @@ export function ComponentsTool() {
162
164
  ? `${config.previewUrl}${fillTemplate(preview.thumbnail, block.name, config.blockNamespace)}`
163
165
  : null
164
166
  }
167
+ onOpen={openComponent ? () => openComponent(block.name) : undefined}
165
168
  />
166
169
  ))}
167
170
  </Grid>
@@ -11,6 +11,8 @@ import {
11
11
  import '@xyflow/react/dist/style.css'
12
12
  import {Box, Button, Card, Flex, Stack, Text} from '@sanity/ui'
13
13
  import {IntentLink} from 'sanity/router'
14
+ import {pathToString, type Path} from 'sanity'
15
+ import {useOpenComponent} from '../../../hooks/useOpenComponent'
14
16
  import {AddIcon} from '@sanity/icons/Add'
15
17
  import {useKitConfig} from '../../../context/KitContext'
16
18
  import {useBoardLayout} from '../../../context/BoardLayoutContext'
@@ -64,6 +66,7 @@ function MapCanvas(props: SectionsMapProps) {
64
66
  useAnnotations('sections')
65
67
  const [nodes, setNodes, onNodesChange] = useNodesState<MapFlowNode>([])
66
68
 
69
+ const openComponent = useOpenComponent()
67
70
  const preview = config.componentPreview
68
71
  const canPreview = preview.provider === 'designSystemPage' && Boolean(config.previewUrl)
69
72
 
@@ -286,19 +289,40 @@ function MapCanvas(props: SectionsMapProps) {
286
289
  ? 'Jamais utilisé sur le site.'
287
290
  : `${selectedPages.length} page${selectedPages.length > 1 ? 's' : ''} · ${selectedEntry.occurrence.count} instance${selectedEntry.occurrence.count > 1 ? 's' : ''}`}
288
291
  </Text>
292
+ {openComponent && (
293
+ <Box>
294
+ <Button
295
+ mode="default"
296
+ tone="primary"
297
+ fontSize={1}
298
+ padding={2}
299
+ text="Ouvrir le composant"
300
+ title="Rendu réel et valeurs par défaut, côte à côte"
301
+ onClick={() => openComponent(selectedEntry.block.name)}
302
+ />
303
+ </Box>
304
+ )}
289
305
  <Stack gap={2}>
290
- {selectedPages.map((page) => (
291
- <IntentLink
292
- key={page.id}
293
- intent="edit"
294
- params={{id: page.id, type: page.type}}
295
- style={{textDecoration: 'none', color: 'inherit'}}
296
- >
297
- <Text size={1} textOverflow="ellipsis">
298
- {page.title}
299
- </Text>
300
- </IntentLink>
301
- ))}
306
+ {selectedPages.map((page) => {
307
+ // Ouvre la page directement sur l'instance du composant (la
308
+ // première s'il y en a plusieurs sur la page).
309
+ const here = selectedEntry.occurrence.locations.filter((l) => l.documentId === page.id)
310
+ const first = here[0]
311
+ const path = first ? pathToString([config.pageBuilderField, ...first.path] as Path) : undefined
312
+ return (
313
+ <IntentLink
314
+ key={page.id}
315
+ intent="edit"
316
+ params={path ? {id: page.id, type: page.type, path} : {id: page.id, type: page.type}}
317
+ style={{textDecoration: 'none', color: 'inherit'}}
318
+ >
319
+ <Text size={1} textOverflow="ellipsis">
320
+ {page.title}
321
+ {here.length > 1 ? ` (${here.length} instances)` : ''}
322
+ </Text>
323
+ </IntentLink>
324
+ )
325
+ })}
302
326
  </Stack>
303
327
 
304
328
  {designSystemUrl && (
@@ -320,7 +344,7 @@ function MapCanvas(props: SectionsMapProps) {
320
344
  ) : (
321
345
  <Flex align="center" justify="center" style={{height: '100%'}}>
322
346
  <Text size={0} muted align="center">
323
- Cliquer une section pour voir les pages qui l’utilisent.
347
+ Cliquer une section pour l’ouvrir (rendu réel et valeurs par défaut) ou aller à ses emplacements dans les pages.
324
348
  </Text>
325
349
  </Flex>
326
350
  )}