@nocode-factory/sanity-kit 2.7.0 → 2.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.7.0",
3
+ "version": "2.8.1",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -0,0 +1,135 @@
1
+ import {useState, type ComponentType} from 'react'
2
+ import {set, 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
+ resolveFieldPath,
15
+ type PathSegment,
16
+ } from '../lib/overrides'
17
+
18
+ /**
19
+ * Pastille bleue sur tout champ d'une instance de composant dont la valeur
20
+ * DIFFÈRE de la valeur par défaut du composant (valeur par défaut vide comprise),
21
+ * éléments de liste compris (comparés à l'élément de même rang). Au survol, elle
22
+ * devient « Réinitialiser » : retour à la valeur par défaut. Les champs
23
+ * « simples » la portent (texte, nombre, choix, case, liste, image, référence,
24
+ * couleur...) ; un objet composé (lien) la porte sur ses sous-champs.
25
+ */
26
+ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<InputProps> {
27
+ const {defaultsType} = config.componentPreview
28
+ const namespace = config.blockNamespace
29
+
30
+ function OverrideInput(props: InputProps) {
31
+ const schema = useSchema()
32
+ const path = props.path as PathSegment[]
33
+ // L'instance de composant : le premier élément de liste du chemin (page
34
+ // builder, corps d'article) ou, sinon, le champ de premier niveau (composant
35
+ // posé seul, ex. le CTA de fin d'article des Réglages).
36
+ const keyed = firstKeyedIndex(path)
37
+ const anchor = keyed >= 0 ? keyed : 0
38
+ const instance = useFormValue(path.slice(0, anchor + 1) as never)
39
+ const parent = useFormValue((path.length > 1 ? path.slice(0, -1) : path) as never)
40
+ const resolved = resolveFieldPath(path, anchor, instance, namespace)
41
+
42
+ if (!resolved || !schema.get(defaultsType) || !carriesDot(props.schemaType)) return props.renderDefault(props)
43
+ const shortName = blockName((instance as {_type: string})._type, namespace)
44
+ return <WithDot {...props} rel={resolved.path} inList={resolved.inList} shortName={shortName} parent={parent} />
45
+ }
46
+
47
+ function WithDot(props: InputProps & {rel: (string | number)[]; inList: boolean; shortName: string; parent: unknown}) {
48
+ const {rel, inList, shortName, parent, ...inputProps} = props
49
+ const client = useKitClient()
50
+ const languageField = config.i18n?.field ?? 'language'
51
+ const language = (useFormValue([languageField]) as string | undefined) ?? null
52
+ const defaults = useComponentDefaults(client, defaultsType, languageField, language)
53
+ const inherited = defaultValueAt(defaults, shortName, rel)
54
+ const field = rel[rel.length - 1] ?? ''
55
+
56
+ if (!isOverride(inputProps.value, inherited, field, parent)) return inputProps.renderDefault(inputProps)
57
+ // Champ de premier niveau : vidé, il hérite à nouveau. Champ d'un élément de
58
+ // liste : la valeur par défaut est recopiée (une liste remplie remplace celle
59
+ // du défaut en entier, un champ vidé y resterait vide).
60
+ const reset = () =>
61
+ inputProps.onChange(inList && inherited !== undefined && inherited !== null ? set(structuredClone(inherited)) : unset())
62
+ return (
63
+ <Flex align="flex-start" gap={2}>
64
+ <Box flex={1} style={{minWidth: 0}}>
65
+ {inputProps.renderDefault(inputProps)}
66
+ </Box>
67
+ <OverrideDot inherited={describeValue(inherited)} onReset={reset} />
68
+ </Flex>
69
+ )
70
+ }
71
+
72
+ return OverrideInput
73
+ }
74
+
75
+ // Champs qui portent la pastille : valeurs simples, listes, et objets « atomiques »
76
+ // (image, référence, ou objet à saisie personnalisée comme une couleur de charte).
77
+ type TypeChain = {name?: string; type?: TypeChain; components?: {input?: unknown}}
78
+ function carriesDot(schemaType: InputProps['schemaType']): boolean {
79
+ if (schemaType.jsonType !== 'object') return true
80
+ let t: TypeChain | undefined = schemaType as unknown as TypeChain
81
+ while (t) {
82
+ if (t.components?.input || t.name === 'image' || t.name === 'file' || t.name === 'reference') return true
83
+ t = t.type
84
+ }
85
+ return false
86
+ }
87
+
88
+ const BLUE = 'var(--card-badge-primary-dot-color, #2276fc)'
89
+
90
+ function OverrideDot(props: {inherited: string; onReset: () => void}) {
91
+ const [hover, setHover] = useState(false)
92
+ return (
93
+ <Tooltip
94
+ portal
95
+ placement="left"
96
+ content={
97
+ <Box padding={2} style={{maxWidth: 260}}>
98
+ <Text size={1}>
99
+ Valeur différente du défaut du composant ({props.inherited}). Survoler puis cliquer pour revenir à la valeur par défaut.
100
+ </Text>
101
+ </Box>
102
+ }
103
+ >
104
+ <button
105
+ type="button"
106
+ onClick={props.onReset}
107
+ onMouseEnter={() => setHover(true)}
108
+ onMouseLeave={() => setHover(false)}
109
+ onFocus={() => setHover(true)}
110
+ onBlur={() => setHover(false)}
111
+ aria-label="Réinitialiser à la valeur par défaut du composant"
112
+ style={{
113
+ marginTop: 9,
114
+ flex: 'none',
115
+ height: hover ? 22 : 10,
116
+ minWidth: 10,
117
+ padding: hover ? '0 8px' : 0,
118
+ borderRadius: 999,
119
+ border: 0,
120
+ background: BLUE,
121
+ color: '#fff',
122
+ fontSize: 11,
123
+ fontWeight: 600,
124
+ lineHeight: '22px',
125
+ whiteSpace: 'nowrap',
126
+ cursor: 'pointer',
127
+ transform: hover ? 'translateY(-6px)' : 'none',
128
+ transition: 'all 120ms ease',
129
+ }}
130
+ >
131
+ {hover ? '↺ Réinitialiser' : ''}
132
+ </button>
133
+ </Tooltip>
134
+ )
135
+ }
@@ -0,0 +1,68 @@
1
+ import {useEffect, useSyncExternalStore} from 'react'
2
+ import type {SanityClient} from 'sanity'
3
+
4
+ /**
5
+ * Valeurs par défaut des composants (dernière version, brouillon compris : la
6
+ * même que le formulaire du composant), dans la langue de 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 && ($language == null || !defined(${languageField}) || ${languageField} == $language)`
29
+ const params = {type, language}
30
+ const drafts = client.withConfig({perspective: 'drafts'})
31
+ const load = () =>
32
+ drafts
33
+ .fetch<Defaults>(`*[${filter}][0]`, params)
34
+ .then((value) => {
35
+ e.value = value
36
+ e.listeners.forEach((l) => l())
37
+ })
38
+ .catch(() => {})
39
+ void load()
40
+ const sub = client.listen(`*[${filter}]`, params, {visibility: 'query', includeResult: false}).subscribe({next: () => void load()})
41
+ e.stop = () => sub.unsubscribe()
42
+ }
43
+ return [key, e]
44
+ }
45
+
46
+ export function useComponentDefaults(client: SanityClient, type: string, languageField: string, language: string | null): Defaults {
47
+ const [, entry] = entryFor(client, type, languageField, language)
48
+ const value = useSyncExternalStore(
49
+ (listener) => {
50
+ entry.listeners.add(listener)
51
+ return () => {
52
+ entry.listeners.delete(listener)
53
+ }
54
+ },
55
+ () => entry.value,
56
+ )
57
+ // L'écoute reste ouverte tant qu'un champ l'utilise.
58
+ useEffect(
59
+ () => () => {
60
+ if (entry.listeners.size === 0 && entry.stop) {
61
+ entry.stop()
62
+ entry.stop = null
63
+ }
64
+ },
65
+ [entry],
66
+ )
67
+ return value
68
+ }
@@ -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
 
@@ -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,146 @@
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, listes comprises : un élément de
31
+ * liste est repéré par son rang (`['items', 0, 'title']`), comparé à l'élément de
32
+ * même rang de la valeur par défaut. `inList` : le champ est dans un élément de
33
+ * liste (une liste remplie remplace celle du défaut en entier : réinitialiser
34
+ * RECOPIE la valeur par défaut au lieu de vider le champ). `null` : pas un
35
+ * composant de l'espace de noms.
36
+ */
37
+ export function resolveFieldPath(
38
+ path: readonly PathSegment[],
39
+ index: number,
40
+ instance: unknown,
41
+ namespace: string,
42
+ ): {path: (string | number)[]; inList: boolean} | null {
43
+ const type = (instance as {_type?: unknown} | null)?._type
44
+ if (index < 0 || typeof type !== 'string' || !type.startsWith(namespace)) return null
45
+ const rest = path.slice(index + 1)
46
+ if (rest.length === 0) return null
47
+ const out: (string | number)[] = []
48
+ let inList = false
49
+ let node: unknown = instance
50
+ for (const seg of rest) {
51
+ if (typeof seg === 'string') {
52
+ out.push(seg)
53
+ node = node && typeof node === 'object' ? (node as Record<string, unknown>)[seg] : undefined
54
+ } else if (isKeyed(seg) || typeof seg === 'number') {
55
+ if (!Array.isArray(node)) return null
56
+ const i = typeof seg === 'number' ? seg : node.findIndex((item) => (item as {_key?: unknown})?._key === seg._key)
57
+ if (i < 0) return null
58
+ // Texte riche : comparé comme un tout (le champ), pas paragraphe par paragraphe.
59
+ if ((node[i] as {_type?: unknown} | null)?._type === 'block') return null
60
+ out.push(i)
61
+ inList = true
62
+ node = node[i]
63
+ } else return null
64
+ }
65
+ return {path: out, inList}
66
+ }
67
+
68
+ /** @deprecated Utiliser resolveFieldPath (listes comprises). */
69
+ export function relativeFieldPath(
70
+ path: readonly PathSegment[],
71
+ index: number,
72
+ instance: unknown,
73
+ namespace: string,
74
+ ): string[] | null {
75
+ const r = resolveFieldPath(path, index, instance, namespace)
76
+ return r && !r.inList ? (r.path as string[]) : null
77
+ }
78
+
79
+ /** Valeur par défaut d'un champ de composant. */
80
+ export function defaultValueAt(
81
+ defaults: Record<string, unknown> | null | undefined,
82
+ blockShortName: string,
83
+ relPath: readonly (string | number)[],
84
+ ): unknown {
85
+ let node: unknown = defaults?.[blockShortName]
86
+ for (const key of relPath) {
87
+ if (!node || typeof node !== 'object') return undefined
88
+ node = (node as Record<string | number, unknown>)[key]
89
+ }
90
+ return node
91
+ }
92
+
93
+ const hasLinkTarget = (link: unknown) => {
94
+ const l = (link ?? {}) as Record<string, unknown>
95
+ return LINK_TARGET_FIELDS.some((k) => (k === 'file' ? Boolean((l.file as {asset?: unknown} | undefined)?.asset) : !isEmptyValue(l[k])))
96
+ }
97
+
98
+ /**
99
+ * Le champ est-il un override ? Valeur propre à l'instance DIFFÉRENTE de la
100
+ * valeur par défaut du composant (y compris quand le composant n'a pas de valeur
101
+ * par défaut pour ce champ). Un champ vide hérite : jamais d'override. Une case
102
+ * décochée vaut une case non renseignée. Le type d'un lien ne compte que si le
103
+ * lien a sa propre cible (il est prérempli par le Studio).
104
+ */
105
+ export function isOverride(local: unknown, inherited: unknown, field: string | number, parent: unknown): boolean {
106
+ if (isEmptyValue(local)) return false
107
+ if (local === false && isEmptyValue(inherited)) return false
108
+ const parentType = (parent as {_type?: unknown} | null)?._type
109
+ if (field === 'type' && typeof parentType === 'string' && LINK_TYPES.has(parentType) && !hasLinkTarget(parent)) return false
110
+ return !sameValue(local, inherited)
111
+ }
112
+
113
+ /** Égalité de valeurs (champ identique au défaut : override « figé »). */
114
+ export function sameValue(a: unknown, b: unknown): boolean {
115
+ if (a === b) return true
116
+ const clean = (v: unknown): unknown =>
117
+ Array.isArray(v)
118
+ ? v.map(clean)
119
+ : v && typeof v === 'object'
120
+ ? Object.fromEntries(
121
+ Object.entries(v as Record<string, unknown>)
122
+ .filter(([k]) => !k.startsWith('_') || k === '_ref')
123
+ .sort(([x], [y]) => x.localeCompare(y))
124
+ .map(([k, x]) => [k, clean(x)]),
125
+ )
126
+ : v
127
+ return JSON.stringify(clean(a)) === JSON.stringify(clean(b))
128
+ }
129
+
130
+ /** Valeur par défaut lisible, pour la bulle de la pastille. */
131
+ export function describeValue(value: unknown): string {
132
+ if (isEmptyValue(value)) return 'vide (valeur du design system)'
133
+ if (typeof value === 'string') return value.length > 60 ? `« ${value.slice(0, 57)}… »` : `« ${value} »`
134
+ if (typeof value === 'boolean') return value ? 'Oui' : 'Non'
135
+ if (typeof value === 'number') return String(value)
136
+ if (Array.isArray(value)) return `${value.length} élément${value.length > 1 ? 's' : ''}`
137
+ if (value && typeof value === 'object') {
138
+ const v = value as Record<string, unknown>
139
+ if (typeof v.token === 'string') return `couleur ${v.token}`
140
+ if (typeof v.customHex === 'string') return `couleur ${v.customHex}`
141
+ if (typeof v.label === 'string') return `« ${v.label} »`
142
+ if (v.asset) return 'une image'
143
+ if (typeof v._ref === 'string') return 'un document'
144
+ }
145
+ return 'une valeur'
146
+ }
@@ -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
 
@@ -1,11 +1,9 @@
1
- import {useCallback, useMemo, useState} from 'react'
2
- import {useSchema} from 'sanity'
3
- import {useRouter} from 'sanity/router'
1
+ import {useMemo, useState} from 'react'
4
2
  import {Box, Button, Card, Flex, Grid, Spinner, Stack, Text} from '@sanity/ui'
5
3
  import {useKitConfig} from '../../context/KitContext'
6
4
  import {useOccurrences, OCCURRENCE_SCAN_LIMIT} from '../../hooks/useOccurrences'
7
- import {componentIntentParams, fillTemplate} from '../../lib/blocks'
8
- import {useKitClient} from '../../hooks/useKitClient'
5
+ import {fillTemplate} from '../../lib/blocks'
6
+ import {useOpenComponent} from '../../hooks/useOpenComponent'
9
7
  import {QueryError} from '../../ui/QueryError'
10
8
  import {BlockCard} from './BlockCard'
11
9
  import {SectionsMap} from './map/SectionsMap'
@@ -30,31 +28,7 @@ export function ComponentsTool() {
30
28
 
31
29
  const preview = config.componentPreview
32
30
  const canPreview = preview.provider === 'designSystemPage' && Boolean(config.previewUrl)
33
- const schema = useSchema()
34
- const router = useRouter()
35
- const client = useKitClient()
36
- const hasDefaults = Boolean(schema.get(preview.defaultsType))
37
-
38
- // Clic sur un composant : Presentation avec son rendu réel et ses valeurs par
39
- // défaut côte à côte. Sans document de valeurs par défaut dans le schéma : la
40
- // démo du design system dans un nouvel onglet.
41
- const openComponent = useCallback(
42
- async (type: string) => {
43
- if (!hasDefaults) {
44
- if (config.previewUrl) window.open(`${config.previewUrl}${preview.path}#${fillTemplate(preview.anchor, type, config.blockNamespace)}`, '_blank', 'noopener')
45
- return
46
- }
47
- const lang = config.i18n?.defaultLocale ?? null
48
- const id = await client
49
- .fetch<string | null>(
50
- `*[_type == $type] | order(select($lang != null && ${config.i18n?.field ?? 'language'} == $lang => 0, 1))[0]._id`,
51
- {type: preview.defaultsType, lang},
52
- )
53
- .catch(() => null)
54
- router.navigateIntent('edit', componentIntentParams(type, config.blockNamespace, preview, id ?? preview.defaultsType))
55
- },
56
- [hasDefaults, config, preview, client, router],
57
- )
31
+ const openComponent = useOpenComponent()
58
32
 
59
33
  const cards = useMemo(() => {
60
34
  const byName = new Map(blockTypes.map((b) => [b.name, b]))
@@ -190,7 +164,7 @@ export function ComponentsTool() {
190
164
  ? `${config.previewUrl}${fillTemplate(preview.thumbnail, block.name, config.blockNamespace)}`
191
165
  : null
192
166
  }
193
- onOpen={hasDefaults || config.previewUrl ? () => void openComponent(block.name) : undefined}
167
+ onOpen={openComponent ? () => openComponent(block.name) : undefined}
194
168
  />
195
169
  ))}
196
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
  )}
package/src/version.ts CHANGED
@@ -2,4 +2,4 @@
2
2
  * Version du kit, rapportée au service pour savoir quels projets tournent sur
3
3
  * quelle version. Tenue à jour avec `package.json`.
4
4
  */
5
- export const KIT_VERSION = '2.7.0'
5
+ export const KIT_VERSION = '2.8.1'