@nocode-factory/sanity-kit 2.23.0 → 2.25.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.23.0",
3
+ "version": "2.25.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -0,0 +1,85 @@
1
+ import {createElement, useEffect, useState, type ComponentType} from 'react'
2
+ import {useFormValue, type InputProps} from 'sanity'
3
+ import {usePresentationNavigate, usePresentationParams} from 'sanity/presentation'
4
+ import {Button, Card, Flex, Stack, Text} from '@sanity/ui'
5
+ import type {ResolvedKitConfig} from '../config/types'
6
+ import {useKitClient} from '../hooks/useKitClient'
7
+ import {localeOfPreview} from '../lib/previewLocale'
8
+
9
+ /**
10
+ * Presentation : le panneau d'édition DOIT montrer la langue de l'aperçu. Si le
11
+ * document édité n'est pas dans la langue de la page affichée (ex. aperçu EN, panneau
12
+ * FR), un bandeau le dit en haut du formulaire, avec un bouton qui ouvre la bonne
13
+ * version. Évite de modifier le français en croyant modifier l'anglais.
14
+ * Structure stable : le formulaire garde sa place, que le bandeau soit là ou non.
15
+ */
16
+ export function withLanguageMismatch(Inner: ComponentType<InputProps>, config: ResolvedKitConfig): ComponentType<InputProps> {
17
+ const i18n = config.i18n
18
+ function LanguageMismatch(props: InputProps) {
19
+ const inner = createElement(Inner, props)
20
+ if (!i18n || props.path.length > 0) return inner
21
+ return (
22
+ <Stack gap={4}>
23
+ <MismatchCheck />
24
+ {inner}
25
+ </Stack>
26
+ )
27
+ }
28
+
29
+ function MismatchCheck() {
30
+ const params = usePresentationParams(false)
31
+ const language = useFormValue([i18n?.field ?? 'language']) as string | undefined
32
+ const shown = localeOfPreview(params?.preview, i18n)
33
+ if (!params || !language || !shown || language === shown) return null
34
+ return <MismatchBanner editing={language} shown={shown} />
35
+ }
36
+
37
+ function MismatchBanner(props: {editing: string; shown: string}) {
38
+ const {editing, shown} = props
39
+ const navigate = usePresentationNavigate()
40
+ const client = useKitClient()
41
+ const id = (useFormValue(['_id']) as string | undefined)?.replace(/^drafts\./, '')
42
+ const type = useFormValue(['_type']) as string | undefined
43
+ const [target, setTarget] = useState<string | null | undefined>(undefined)
44
+
45
+ useEffect(() => {
46
+ if (!id) return
47
+ let alive = true
48
+ client
49
+ .fetch<string | null>(
50
+ `*[_type == "translation.metadata" && references($id)][0].translations[_key == $lang || language == $lang][0].value._ref`,
51
+ {id, lang: shown},
52
+ )
53
+ .then((ref) => alive && setTarget(ref ?? null))
54
+ .catch(() => alive && setTarget(null))
55
+ return () => {
56
+ alive = false
57
+ }
58
+ }, [client, id, shown])
59
+
60
+ return (
61
+ <Card tone="caution" padding={3} radius={2} border>
62
+ <Flex align="center" gap={3} wrap="wrap">
63
+ <Text size={1} weight="semibold" style={{flex: 1, minWidth: 200}}>
64
+ You are editing the {editing.toUpperCase()} version. The preview shows {shown.toUpperCase()}.
65
+ </Text>
66
+ {target && type ? (
67
+ <Button
68
+ tone="caution"
69
+ fontSize={1}
70
+ padding={2}
71
+ text={`Edit the ${shown.toUpperCase()} version`}
72
+ onClick={() => navigate(undefined, {type, id: target})}
73
+ />
74
+ ) : target === null ? (
75
+ <Text size={1} muted>
76
+ No {shown.toUpperCase()} version of this document yet.
77
+ </Text>
78
+ ) : null}
79
+ </Flex>
80
+ </Card>
81
+ )
82
+ }
83
+
84
+ return LanguageMismatch
85
+ }
@@ -0,0 +1,35 @@
1
+ import {createElement, type ComponentType} from 'react'
2
+ import {usePerspective, type InputProps} from 'sanity'
3
+ import {Box, Text} from '@sanity/ui'
4
+ import {Tooltip} from '@sanity/ui/tooltip'
5
+
6
+ // Champs « simples » (texte, nombre, case, date...) : la bulle sur un objet ou une
7
+ // liste doublerait celle de chacun de ses champs.
8
+ const LEAF = new Set(['string', 'number', 'boolean'])
9
+
10
+ /**
11
+ * Vue « Published » : le formulaire est en lecture seule et rien ne dit pourquoi.
12
+ * Au survol d'un champ : « Switch to Drafts to edit ». La structure ne change
13
+ * qu'avec la vue (jamais pendant la frappe : le champ n'est pas recréé).
14
+ */
15
+ export function withPublishedHint(Inner: ComponentType<InputProps>): ComponentType<InputProps> {
16
+ function PublishedHint(props: InputProps) {
17
+ const {selectedPerspectiveName} = usePerspective()
18
+ const inner = createElement(Inner, props)
19
+ if (selectedPerspectiveName !== 'published' || !LEAF.has(props.schemaType.jsonType)) return inner
20
+ return (
21
+ <Tooltip
22
+ portal
23
+ placement="top"
24
+ content={
25
+ <Box padding={2}>
26
+ <Text size={1}>Switch to Drafts to edit</Text>
27
+ </Box>
28
+ }
29
+ >
30
+ <div>{inner}</div>
31
+ </Tooltip>
32
+ )
33
+ }
34
+ return PublishedHint
35
+ }
package/src/index.ts CHANGED
@@ -44,6 +44,8 @@ import {createOverrideInput} from './form/OverrideInput'
44
44
  import {RemoveFromSiteAction} from './actions/RemoveFromSite'
45
45
  import {createSlugUrlInput, isSlugInput} from './form/SlugUrlInput'
46
46
  import {withTranslationTodo} from './form/TranslationTodoInput'
47
+ import {withPublishedHint} from './form/PublishedHint'
48
+ import {withLanguageMismatch} from './form/LanguageMismatch'
47
49
  import {withPropagation} from './actions/PropagatePublish'
48
50
 
49
51
  /** Champs du formulaire : adresse sous le Slug d'une page, pastille sur les sections. */
@@ -54,7 +56,9 @@ function createKitInput(config: Parameters<typeof createOverrideInput>[0]): Comp
54
56
  return isSlugInput(props) ? createElement(SlugUrl, props) : createElement(Override, props)
55
57
  }
56
58
  // Traductions : pastille « À traduire » sur les champs modifiés dans la version principale.
57
- return config.i18n ? withTranslationTodo(KitInput, config) : KitInput
59
+ // Vue « Published » : « Switch to Drafts to edit » au survol d'un champ.
60
+ // Presentation : bandeau si le document édité n'est pas dans la langue de l'aperçu.
61
+ return withPublishedHint(config.i18n ? withLanguageMismatch(withTranslationTodo(KitInput, config), config) : KitInput)
58
62
  }
59
63
 
60
64
  export const ncfKit = definePlugin<NcfKitConfig>((options) => {
@@ -365,3 +369,6 @@ export type {Annotation} from './lib/graph'
365
369
  export type {AddColumnInput} from './lib/columns'
366
370
  export type {AnnotationsState} from './hooks/useAnnotations'
367
371
  export type {PathInput} from './lib/paths'
372
+
373
+ export {ncfMainDocuments} from './lib/mainDocuments'
374
+ export type {MainDocumentRoute} from './lib/mainDocuments'
@@ -0,0 +1,72 @@
1
+ import type {NcfKitConfig} from '../config/types'
2
+ import {resolveConfig} from '../config/resolve'
3
+ import type {SiteRoutesRegistry} from './siteRoutes'
4
+
5
+ /** Une entrée de `presentationTool({resolve: {mainDocuments: defineDocuments([...])}})`. */
6
+ export interface MainDocumentRoute {
7
+ route: string
8
+ filter: string
9
+ }
10
+
11
+ const SAFE = /^[A-Za-z0-9_.-]+$/
12
+ const quote = (value: string) => JSON.stringify(value)
13
+
14
+ /**
15
+ * Presentation : le document du panneau de droite est TOUJOURS celui de la page
16
+ * affichée, DANS SA LANGUE. Sans cette liste, changer de langue (ou de page) dans
17
+ * l'aperçu laisse le panneau sur l'ancien document : on modifie le français en
18
+ * regardant l'anglais.
19
+ *
20
+ * Une route par adresse et par langue (langue principale sans préfixe, les autres
21
+ * sous /<langue>) : accueil, pages codées du registre (`pageSlug`), collections
22
+ * (`<préfixe>/:slug`), design system (valeurs par défaut des composants). Ordre :
23
+ * langues préfixées d'abord, puis du plus précis au plus général (`/:slug` en
24
+ * dernier), pour que `/en` ne soit pas lu comme la page de slug « en ».
25
+ *
26
+ * ```ts
27
+ * presentationTool({resolve: {mainDocuments: defineDocuments(ncfMainDocuments(ncfOptions, {siteRoutes: routes}))}})
28
+ * ```
29
+ */
30
+ export function ncfMainDocuments(
31
+ options: NcfKitConfig,
32
+ extra: {siteRoutes?: SiteRoutesRegistry; designSystemRoutes?: string[]} = {},
33
+ ): MainDocumentRoute[] {
34
+ const config = resolveConfig(options)
35
+ const i18n = config.i18n
36
+ const field = i18n?.field ?? 'language'
37
+ const locales = i18n ? [...i18n.locales.filter((l) => l !== i18n.defaultLocale), i18n.defaultLocale] : [null]
38
+ const slugTypes = config.pageTypes.filter((t) => t.slugField && !t.path)
39
+ const defaultsType = config.componentPreview.defaultsType
40
+ const designSystem = extra.designSystemRoutes ?? ['/design-system/composant', '/design-system']
41
+
42
+ const out: MainDocumentRoute[] = []
43
+ for (const locale of locales) {
44
+ if (locale !== null && !SAFE.test(locale)) continue
45
+ const prefix = locale === null || locale === i18n?.defaultLocale ? '' : `/${locale}`
46
+ const lang = locale === null ? '' : ` && ${field} == ${quote(locale)}`
47
+ const at = (path: string) => (path === '/' || path === '' ? prefix || '/' : `${prefix}${path}`)
48
+
49
+ // Design system : valeurs par défaut des composants de la langue affichée.
50
+ for (const route of designSystem) out.push({route: at(route), filter: `_type == ${quote(defaultsType)}${lang}`})
51
+
52
+ // Pages codées du registre qui portent un document « Page » (pageSlug).
53
+ for (const fixed of extra.siteRoutes?.fixed ?? []) {
54
+ if (!fixed.pageSlug || fixed.system || fixed.notFound || !SAFE.test(fixed.pageSlug)) continue
55
+ // Le document d'une page codée est une page « à la racine » (Page, Legal page).
56
+ const types = slugTypes.filter((t) => !t.pathPrefix || t.pathPrefix === '/').map((t) => quote(t.type)).join(', ')
57
+ if (!types) continue
58
+ out.push({route: at(fixed.path), filter: `_type in [${types}] && slug.current == ${quote(fixed.pageSlug)}${lang}`})
59
+ }
60
+
61
+ // Pages à chemin fixe (l'accueil).
62
+ for (const t of config.pageTypes) if (t.path) out.push({route: at(t.path), filter: `_type == ${quote(t.type)}${lang}`})
63
+
64
+ // Collections : préfixe le plus long d'abord, la racine (`/:slug`) en dernier.
65
+ const collections = [...slugTypes].sort((a, b) => (b.pathPrefix ?? '').length - (a.pathPrefix ?? '').length)
66
+ for (const t of collections) {
67
+ const base = t.pathPrefix && t.pathPrefix !== '/' ? t.pathPrefix : ''
68
+ out.push({route: at(`${base}/:slug`), filter: `_type == ${quote(t.type)} && ${t.slugField}.current == $slug${lang}`})
69
+ }
70
+ }
71
+ return out
72
+ }
@@ -0,0 +1,17 @@
1
+ import type {ResolvedI18n} from '../config/types'
2
+
3
+ /**
4
+ * Langue de la page affichée dans l'aperçu, d'après son adresse : premier segment
5
+ * s'il est une langue autre que la principale (/en/...), sinon la langue principale.
6
+ */
7
+ export function localeOfPreview(preview: string | null | undefined, i18n: ResolvedI18n | null): string | null {
8
+ if (!i18n || !preview) return null
9
+ let pathname: string
10
+ try {
11
+ pathname = new URL(preview, 'http://preview.local').pathname
12
+ } catch {
13
+ return null
14
+ }
15
+ const first = pathname.split('/').filter(Boolean)[0]
16
+ return first && first !== i18n.defaultLocale && i18n.locales.includes(first) ? first : i18n.defaultLocale
17
+ }
@@ -6,7 +6,7 @@ import type {NcfPageTypeInput} from '../config/types'
6
6
  * (sections, titres, noindex) qui ne concernent pas le kit.
7
7
  */
8
8
  export interface SiteRoutesRegistry {
9
- fixed?: {path: string; homePage?: boolean; system?: boolean; notFound?: boolean}[]
9
+ fixed?: {path: string; homePage?: boolean; system?: boolean; notFound?: boolean; pageSlug?: string}[]
10
10
  collections?: {type: string; pathPrefix?: string}[]
11
11
  }
12
12
 
@@ -0,0 +1,25 @@
1
+ import {useEffect} from 'react'
2
+ import {usePerspective, useSetPerspective} from 'sanity'
3
+
4
+ // Une fois par chargement de page (la barre d'outils est rendue deux fois : barre
5
+ // du haut et volet latéral).
6
+ let checked = false
7
+
8
+ /**
9
+ * À l'ouverture du Studio, on édite : vue « Drafts », jamais « Published ». Un lien
10
+ * « Prod · En ligne » (perspective=published dans l'adresse) ou un Studio rechargé
11
+ * sur cette vue rouvrait sinon en lecture seule. Ensuite, le choix de l'utilisateur
12
+ * est respecté jusqu'au prochain chargement.
13
+ */
14
+ export function DraftsOnLoad() {
15
+ const {selectedPerspectiveName} = usePerspective()
16
+ const setPerspective = useSetPerspective()
17
+ useEffect(() => {
18
+ if (checked) return
19
+ checked = true
20
+ // L'adresse fait foi dès le premier rendu (la vue choisie peut arriver après).
21
+ const fromUrl = typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('perspective') === 'published'
22
+ if (selectedPerspectiveName === 'published' || fromUrl) setPerspective('drafts')
23
+ }, [selectedPerspectiveName, setPerspective])
24
+ return null
25
+ }
@@ -1,3 +1,4 @@
1
+ import {DraftsOnLoad} from './DraftsOnLoad'
1
2
  import {Box, Button, Flex, Stack, Text} from '@sanity/ui'
2
3
  import {useRouter} from 'sanity/router'
3
4
  import type {ToolMenuProps} from 'sanity'
@@ -156,6 +157,7 @@ export function createPreviewLauncher(config: ResolvedKitConfig, issues: ConfigI
156
157
  return function NcfToolMenu(props: ToolMenuProps) {
157
158
  return (
158
159
  <KitProvider config={config} issues={issues}>
160
+ <DraftsOnLoad />
159
161
  <NcfPreviewLauncher {...props} />
160
162
  </KitProvider>
161
163
  )
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.23.0'
6
+ export const KIT_VERSION = '2.25.0'