@nocode-factory/sanity-kit 2.25.0 → 2.27.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/dist/{componentDefaults-BY3hQ6aD.js → componentDefaults-2eWjLLBf.js} +6 -6
- package/dist/componentDefaults-2eWjLLBf.js.map +1 -0
- package/dist/index.d.ts +11 -3
- package/dist/index.js +605 -406
- package/dist/index.js.map +1 -1
- package/dist/schema.js +1 -1
- package/dist/web-server.js +2 -2
- package/dist/web-server.js.map +1 -1
- package/dist/web.js +9 -9
- package/dist/web.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +52 -21
- package/src/actions/RemoveFromSite.tsx +9 -9
- package/src/config/defaults.ts +8 -8
- package/src/config/resolve.ts +4 -1
- package/src/config/types.ts +8 -0
- package/src/config/validate.ts +24 -24
- package/src/context/BoardLayoutContext.tsx +1 -1
- package/src/context/KitContext.tsx +1 -1
- package/src/context/PreviewTargetContext.tsx +1 -1
- package/src/form/OverrideInput.tsx +67 -6
- package/src/form/SlugUrlInput.tsx +2 -2
- package/src/form/TranslationTodoInput.tsx +38 -4
- package/src/hooks/useHistory.ts +5 -5
- package/src/hooks/useOccurrences.ts +1 -1
- package/src/hooks/useOpenOnline.ts +4 -4
- package/src/hooks/useTranslationTodo.ts +2 -1
- package/src/index.ts +9 -5
- package/src/lib/aiTexts.ts +72 -0
- package/src/lib/aiTranslate.ts +61 -0
- package/src/lib/grouping.ts +2 -2
- package/src/lib/overrides.ts +10 -10
- package/src/lib/pages.ts +3 -3
- package/src/lib/service.ts +5 -5
- package/src/lib/status.ts +3 -3
- package/src/lib/studioLinks.ts +6 -6
- package/src/schema/boardLayout.ts +32 -32
- package/src/schema/componentDefaults.ts +5 -5
- package/src/schema/translationTodo.ts +6 -6
- package/src/tools/components/BlockCard.tsx +3 -3
- package/src/tools/components/ComponentsTool.tsx +17 -17
- package/src/tools/components/map/SectionNode.tsx +1 -1
- package/src/tools/components/map/SectionsMap.tsx +10 -10
- package/src/tools/designSystem/DesignSystemTool.tsx +3 -3
- package/src/tools/history/DiffPanel.tsx +23 -23
- package/src/tools/history/HistoryTool.tsx +21 -23
- package/src/tools/more/MoreTool.tsx +1 -1
- package/src/tools/navbar/KitUpdate.tsx +8 -8
- package/src/tools/navbar/PreviewLauncher.tsx +6 -6
- package/src/tools/navbar/ToolButtons.tsx +2 -2
- package/src/tools/pages/ColumnHeader.tsx +18 -18
- package/src/tools/pages/ColumnVisibility.tsx +10 -10
- package/src/tools/pages/FieldValue.tsx +9 -9
- package/src/tools/pages/PagesTable.tsx +11 -11
- package/src/tools/pages/PagesTool.tsx +19 -19
- package/src/tools/pages/PagesToolbar.tsx +3 -3
- package/src/tools/pages/PathCell.tsx +1 -1
- package/src/tools/pages/PreviewTarget.tsx +10 -10
- package/src/tools/pages/SharePreview.tsx +19 -20
- package/src/tools/pages/TagCell.tsx +2 -2
- package/src/tools/pages/ViewTabs.tsx +4 -4
- package/src/tools/pages/board/BoardView.tsx +11 -11
- package/src/tools/pages/board/PageNode.tsx +5 -5
- package/src/tools/pages/board/PagePanel.tsx +10 -10
- package/src/tools/presentation/PreviewHeader.tsx +1 -1
- package/src/tools/shared/AnnotationNode.tsx +3 -3
- package/src/ui/ActorName.tsx +1 -1
- package/src/ui/ConfigIssues.tsx +3 -3
- package/src/ui/PreviewOriginsNotice.tsx +3 -3
- package/src/ui/ProjectStatusNotice.tsx +7 -7
- package/src/ui/QueryError.tsx +2 -2
- package/src/ui/ToolPlaceholder.tsx +2 -2
- package/src/ui/formatDate.ts +1 -1
- package/src/version.ts +1 -1
- package/src/web/PreviewBanner.tsx +9 -9
- package/src/web/draftModeToggle.ts +1 -1
- package/src/web/previewGrant.ts +5 -5
- package/dist/componentDefaults-BY3hQ6aD.js.map +0 -1
package/src/config/validate.ts
CHANGED
|
@@ -25,7 +25,7 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
25
25
|
if (config.pageTypes.length === 0) {
|
|
26
26
|
error(
|
|
27
27
|
'pageTypes',
|
|
28
|
-
"`pageTypes`
|
|
28
|
+
"`pageTypes` is empty. Declare at least one document type, e.g. pageTypes: ['page'].",
|
|
29
29
|
)
|
|
30
30
|
}
|
|
31
31
|
|
|
@@ -34,18 +34,18 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
34
34
|
const at = `pageTypes[${index}]`
|
|
35
35
|
|
|
36
36
|
if (!pageType.type) {
|
|
37
|
-
error(`${at}.type`, '
|
|
37
|
+
error(`${at}.type`, 'Document type missing or empty.')
|
|
38
38
|
return
|
|
39
39
|
}
|
|
40
40
|
if (seen.has(pageType.type)) {
|
|
41
|
-
error(`${at}.type`, `
|
|
41
|
+
error(`${at}.type`, `The type "${pageType.type}" is declared more than once.`)
|
|
42
42
|
}
|
|
43
43
|
seen.add(pageType.type)
|
|
44
44
|
|
|
45
45
|
// `path` et `pathPrefix` ensemble : le chemin fixe gagne, le préfixe ne
|
|
46
46
|
// sert à rien — le dire évite de chercher pourquoi il est ignoré.
|
|
47
47
|
if (pageType.path && pageType.pathPrefix) {
|
|
48
|
-
warn(`${at}.pathPrefix`,
|
|
48
|
+
warn(`${at}.pathPrefix`, `"${pageType.type}" has a fixed path: its pathPrefix is ignored.`)
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
// Sans slug ni chemin fixe, impossible de situer la page : elle
|
|
@@ -53,8 +53,8 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
53
53
|
if (!pageType.slugField && !pageType.path) {
|
|
54
54
|
error(
|
|
55
55
|
`${at}`,
|
|
56
|
-
|
|
57
|
-
`
|
|
56
|
+
`"${pageType.type}" has neither slugField nor path: the kit cannot build its URL. ` +
|
|
57
|
+
`Give it a fixed path, e.g. {type: '${pageType.type}', path: '/'} for a home page.`,
|
|
58
58
|
)
|
|
59
59
|
}
|
|
60
60
|
})
|
|
@@ -63,7 +63,7 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
63
63
|
if (config.previewUrl && !isAbsoluteHttpUrl(config.previewUrl)) {
|
|
64
64
|
error(
|
|
65
65
|
'previewUrl',
|
|
66
|
-
|
|
66
|
+
`"${config.previewUrl}" is not an absolute URL. Expected: https://example.com`,
|
|
67
67
|
)
|
|
68
68
|
}
|
|
69
69
|
|
|
@@ -72,8 +72,8 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
72
72
|
if (!config.previewUrl) {
|
|
73
73
|
warn(
|
|
74
74
|
'previewUrl',
|
|
75
|
-
"
|
|
76
|
-
'
|
|
75
|
+
"Component preview is enabled but `previewUrl` is missing: thumbnails and links " +
|
|
76
|
+
'to the design system page will be disabled.',
|
|
77
77
|
['components'],
|
|
78
78
|
)
|
|
79
79
|
}
|
|
@@ -81,7 +81,7 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
81
81
|
!config.componentPreview.thumbnail.includes('{kebab}')) {
|
|
82
82
|
warn(
|
|
83
83
|
'componentPreview.thumbnail',
|
|
84
|
-
'
|
|
84
|
+
'The template contains neither {name} nor {kebab}: every block will show the same image.',
|
|
85
85
|
['components'],
|
|
86
86
|
)
|
|
87
87
|
}
|
|
@@ -93,14 +93,14 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
93
93
|
if (!isAbsoluteHttpUrl(environment.url)) {
|
|
94
94
|
error(
|
|
95
95
|
`environments.${environment.id}.url`,
|
|
96
|
-
|
|
96
|
+
`"${environment.url}" is not an absolute URL. The preview will not be able to load this environment.`,
|
|
97
97
|
['pages'],
|
|
98
98
|
)
|
|
99
99
|
}
|
|
100
100
|
if (seenEnvironments.has(environment.id)) {
|
|
101
101
|
error(
|
|
102
102
|
'environments',
|
|
103
|
-
`
|
|
103
|
+
`Two environments share the id "${environment.id}": which one is used would be unpredictable.`,
|
|
104
104
|
['pages'],
|
|
105
105
|
)
|
|
106
106
|
}
|
|
@@ -116,28 +116,28 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
116
116
|
if (!config.history) {
|
|
117
117
|
warn(
|
|
118
118
|
'history',
|
|
119
|
-
|
|
120
|
-
'
|
|
121
|
-
'
|
|
119
|
+
'The History tab is enabled but no read key is configured. ' +
|
|
120
|
+
'Run `npx ncf-kit setup` in the studio folder (it is written to .env), ' +
|
|
121
|
+
'or set tools: {history: false}.',
|
|
122
122
|
['history'],
|
|
123
123
|
)
|
|
124
124
|
} else {
|
|
125
125
|
if (!config.history.endpoint || !isAbsoluteHttpUrl(config.history.endpoint)) {
|
|
126
126
|
error(
|
|
127
127
|
'history.endpoint',
|
|
128
|
-
|
|
128
|
+
`"${config.history.endpoint || ''}" is not an absolute URL to the read Edge Function.`,
|
|
129
129
|
['history'],
|
|
130
130
|
)
|
|
131
131
|
}
|
|
132
132
|
if (!config.history.projectKey?.trim()) {
|
|
133
|
-
error('history.projectKey', '`history.projectKey`
|
|
133
|
+
error('history.projectKey', '`history.projectKey` is empty.', ['history'])
|
|
134
134
|
}
|
|
135
135
|
// Garde-fou : une clé de service Supabase dans le Studio serait publique.
|
|
136
136
|
if (/^eyJ|^sb_secret_|service_role/i.test(config.history.projectKey ?? '')) {
|
|
137
137
|
error(
|
|
138
138
|
'history.projectKey',
|
|
139
|
-
'
|
|
140
|
-
|
|
139
|
+
'This value looks like a Supabase key. The Studio is public: ' +
|
|
140
|
+
'only ever put an opaque project identifier here, with no write access.',
|
|
141
141
|
['history'],
|
|
142
142
|
)
|
|
143
143
|
}
|
|
@@ -149,25 +149,25 @@ export function validateConfig(config: ResolvedKitConfig): ConfigIssue[] {
|
|
|
149
149
|
config.internalFields.forEach((field, index) => {
|
|
150
150
|
const at = `internalFields[${index}]`
|
|
151
151
|
if (!field.id?.trim()) {
|
|
152
|
-
error(`${at}.id`, '
|
|
152
|
+
error(`${at}.id`, 'Field id missing.', ['pages'])
|
|
153
153
|
return
|
|
154
154
|
}
|
|
155
155
|
if (fieldIds.has(field.id)) {
|
|
156
|
-
error(`${at}.id`, `
|
|
156
|
+
error(`${at}.id`, `The field "${field.id}" is declared more than once.`, ['pages'])
|
|
157
157
|
}
|
|
158
158
|
fieldIds.add(field.id)
|
|
159
159
|
if (!field.label?.trim()) {
|
|
160
|
-
warn(`${at}.label`, `
|
|
160
|
+
warn(`${at}.label`, `The field "${field.id}" has no label: its id will be shown.`, ['pages'])
|
|
161
161
|
}
|
|
162
162
|
// Un select sans choix ne serait qu'une liste vide.
|
|
163
163
|
if (field.type === 'select' && !field.options?.length) {
|
|
164
|
-
error(`${at}.options`, `
|
|
164
|
+
error(`${at}.options`, `The field "${field.id}" is of type select but has no options.`, ['pages'])
|
|
165
165
|
}
|
|
166
166
|
})
|
|
167
167
|
|
|
168
168
|
/* --- page builder --- */
|
|
169
169
|
if (!config.pageBuilderField) {
|
|
170
|
-
error('pageBuilderField', '
|
|
170
|
+
error('pageBuilderField', 'The page builder field cannot be empty.', [
|
|
171
171
|
'pages',
|
|
172
172
|
'components',
|
|
173
173
|
])
|
|
@@ -18,7 +18,7 @@ export function BoardLayoutProvider(props: {children: ReactNode}) {
|
|
|
18
18
|
export function useBoardLayout(): BoardLayoutState {
|
|
19
19
|
const value = useContext(BoardLayoutContext)
|
|
20
20
|
if (!value) {
|
|
21
|
-
throw new Error('useBoardLayout
|
|
21
|
+
throw new Error('useBoardLayout must be called inside BoardLayoutProvider.')
|
|
22
22
|
}
|
|
23
23
|
return value
|
|
24
24
|
}
|
|
@@ -22,7 +22,7 @@ export function KitProvider(props: KitProviderProps) {
|
|
|
22
22
|
export function useKitContext(): KitContextValue {
|
|
23
23
|
const value = useContext(KitContext)
|
|
24
24
|
if (!value) {
|
|
25
|
-
throw new Error('useKitContext
|
|
25
|
+
throw new Error('useKitContext must be called inside a tool of the @nocode-factory/sanity-kit plugin.')
|
|
26
26
|
}
|
|
27
27
|
return value
|
|
28
28
|
}
|
|
@@ -21,7 +21,7 @@ export function PreviewTargetProvider(props: {children: ReactNode}) {
|
|
|
21
21
|
export function usePreviewTarget(): PreviewTargetState {
|
|
22
22
|
const value = useContext(PreviewTargetContext)
|
|
23
23
|
if (!value) {
|
|
24
|
-
throw new Error('usePreviewTarget
|
|
24
|
+
throw new Error('usePreviewTarget must be called inside PreviewTargetProvider.')
|
|
25
25
|
}
|
|
26
26
|
return value
|
|
27
27
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import {useState, type ComponentType} from 'react'
|
|
2
2
|
import {set, unset, useFormValue, useSchema, type InputProps} from 'sanity'
|
|
3
3
|
import {useRouter} from 'sanity/router'
|
|
4
|
-
import {Box, Flex, Text} from '@sanity/ui'
|
|
4
|
+
import {Box, Button, Flex, Text} from '@sanity/ui'
|
|
5
5
|
import {Tooltip} from '@sanity/ui/tooltip'
|
|
6
6
|
import type {ResolvedKitConfig} from '../config/types'
|
|
7
7
|
import {blockName, componentIntentParams} from '../lib/blocks'
|
|
8
8
|
import {useKitClient} from '../hooks/useKitClient'
|
|
9
|
+
import {collectTexts} from '../lib/aiTexts'
|
|
10
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
9
11
|
import {useComponentDefaults} from '../hooks/useComponentDefaults'
|
|
10
12
|
import {
|
|
11
13
|
defaultValueAt,
|
|
@@ -59,6 +61,44 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
59
61
|
const defaults = useComponentDefaults(client, defaultsType, languageField, language)
|
|
60
62
|
const inherited = defaultValueAt(defaults, shortName, rel)
|
|
61
63
|
const field = rel[rel.length - 1] ?? ''
|
|
64
|
+
// Valeurs par défaut dans la langue SOURCE (anglais en général) : un champ qui
|
|
65
|
+
// hérite d'une valeur par défaut pas encore traduite dans cette langue (vide,
|
|
66
|
+
// ou identique au texte source) propose « Translate default with AI ».
|
|
67
|
+
const sourceLocale = config.i18n?.defaultsSourceLocale ?? null
|
|
68
|
+
const sourceDefaults = useComponentDefaults(client, defaultsType, languageField, sourceLocale)
|
|
69
|
+
const sourceDefault = defaultValueAt(sourceDefaults, shortName, rel)
|
|
70
|
+
const [translating, setTranslating] = useState(false)
|
|
71
|
+
const [translateError, setTranslateError] = useState<string | null>(null)
|
|
72
|
+
const untranslatedDefault =
|
|
73
|
+
Boolean(config.history && config.i18n && language && sourceLocale && language !== sourceLocale) &&
|
|
74
|
+
!inputProps.readOnly &&
|
|
75
|
+
isEmptyValue(inputProps.value) &&
|
|
76
|
+
collectTexts(sourceDefault).some((t) => t.trim()) &&
|
|
77
|
+
(isEmptyValue(inherited) || JSON.stringify(inherited) === JSON.stringify(sourceDefault))
|
|
78
|
+
const translateDefault = async () => {
|
|
79
|
+
const localeId = (defaults as {_id?: string} | null)?._id?.replace(/^drafts\./, '')
|
|
80
|
+
if (!config.history || !sourceLocale || !language) return
|
|
81
|
+
setTranslating(true)
|
|
82
|
+
setTranslateError(null)
|
|
83
|
+
try {
|
|
84
|
+
if (!localeId) throw new Error(`No ${language.toUpperCase()} component defaults document.`)
|
|
85
|
+
const [translated] = await translateValues(config.history, sourceLocale, language, [sourceDefault])
|
|
86
|
+
// Écrit dans le BROUILLON des valeurs par défaut de cette langue (à publier).
|
|
87
|
+
const published = await client.getDocument(localeId)
|
|
88
|
+
const path = [shortName, ...rel].map((seg, n) => (typeof seg === 'number' ? `[${seg}]` : n ? `.${seg}` : seg)).join('')
|
|
89
|
+
const tx = client.transaction()
|
|
90
|
+
if (published) {
|
|
91
|
+
const {_rev, _updatedAt, _createdAt, ...copy} = published
|
|
92
|
+
tx.createIfNotExists({...copy, _id: `drafts.${localeId}`} as {_id: string; _type: string})
|
|
93
|
+
}
|
|
94
|
+
tx.patch(`drafts.${localeId}`, (patch) => patch.set({[path]: translated}))
|
|
95
|
+
await tx.commit()
|
|
96
|
+
} catch (cause) {
|
|
97
|
+
setTranslateError(cause instanceof Error ? cause.message : String(cause))
|
|
98
|
+
} finally {
|
|
99
|
+
setTranslating(false)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
62
102
|
|
|
63
103
|
const router = useRouter()
|
|
64
104
|
|
|
@@ -99,10 +139,31 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
99
139
|
<Flex align="flex-start" gap={2}>
|
|
100
140
|
<Box flex={1} style={{minWidth: 0}}>
|
|
101
141
|
{inputProps.renderDefault(shown)}
|
|
142
|
+
{untranslatedDefault && (
|
|
143
|
+
<Flex align="center" gap={2} marginTop={2} wrap="wrap">
|
|
144
|
+
<Text size={0} muted>
|
|
145
|
+
Default not translated to {String(language).toUpperCase()}.
|
|
146
|
+
</Text>
|
|
147
|
+
<Button
|
|
148
|
+
mode="ghost"
|
|
149
|
+
tone="primary"
|
|
150
|
+
fontSize={0}
|
|
151
|
+
padding={2}
|
|
152
|
+
text={translating ? 'Translating…' : 'Translate default with AI'}
|
|
153
|
+
disabled={translating}
|
|
154
|
+
onClick={() => void translateDefault()}
|
|
155
|
+
/>
|
|
156
|
+
{translateError && (
|
|
157
|
+
<Text size={0} style={{color: 'var(--card-badge-critical-fg-color, #c00)'}}>
|
|
158
|
+
{translateError}
|
|
159
|
+
</Text>
|
|
160
|
+
)}
|
|
161
|
+
</Flex>
|
|
162
|
+
)}
|
|
102
163
|
{inherits && placeholder === null && (
|
|
103
164
|
<Box marginTop={2}>
|
|
104
165
|
<Text size={0} muted>
|
|
105
|
-
|
|
166
|
+
Component default value: {describeValue(inherited)}
|
|
106
167
|
</Text>
|
|
107
168
|
</Box>
|
|
108
169
|
)}
|
|
@@ -135,7 +196,7 @@ const BLUE = 'var(--card-badge-primary-dot-color, #2276fc)'
|
|
|
135
196
|
|
|
136
197
|
function OverrideDot(props: {hasDefault: boolean; full: string; short: string; onClick: () => void}) {
|
|
137
198
|
const [hover, setHover] = useState(false)
|
|
138
|
-
const label = props.hasDefault ? `↺ ${props.short}` : '
|
|
199
|
+
const label = props.hasDefault ? `↺ ${props.short}` : 'No default value'
|
|
139
200
|
return (
|
|
140
201
|
<Tooltip
|
|
141
202
|
portal
|
|
@@ -144,8 +205,8 @@ function OverrideDot(props: {hasDefault: boolean; full: string; short: string; o
|
|
|
144
205
|
<Box padding={2} style={{maxWidth: 280}}>
|
|
145
206
|
<Text size={1}>
|
|
146
207
|
{props.hasDefault
|
|
147
|
-
? `
|
|
148
|
-
: '
|
|
208
|
+
? `Different from the component default value (${props.full}). Click to go back to the default value: the field will follow it, even if it changes.`
|
|
209
|
+
: 'This component has no default value for this field. Click to set it (Components: default values).'}
|
|
149
210
|
</Text>
|
|
150
211
|
</Box>
|
|
151
212
|
}
|
|
@@ -157,7 +218,7 @@ function OverrideDot(props: {hasDefault: boolean; full: string; short: string; o
|
|
|
157
218
|
onMouseLeave={() => setHover(false)}
|
|
158
219
|
onFocus={() => setHover(true)}
|
|
159
220
|
onBlur={() => setHover(false)}
|
|
160
|
-
aria-label={props.hasDefault ? `
|
|
221
|
+
aria-label={props.hasDefault ? `Go back to the component default value: ${props.full}` : 'Set the component default value'}
|
|
161
222
|
style={{
|
|
162
223
|
marginTop: 9,
|
|
163
224
|
flex: 'none',
|
|
@@ -39,8 +39,8 @@ export function createSlugUrlInput(config: ResolvedKitConfig): ComponentType<Inp
|
|
|
39
39
|
<Text size={1} muted style={{flex: 1, minWidth: 0, wordBreak: 'break-all'}}>
|
|
40
40
|
{url}
|
|
41
41
|
</Text>
|
|
42
|
-
<Button mode="ghost" fontSize={1} padding={2} text={copied ? '
|
|
43
|
-
<Button as="a" href={url} target="_blank" rel="noopener noreferrer" mode="ghost" fontSize={1} padding={2} text="
|
|
42
|
+
<Button mode="ghost" fontSize={1} padding={2} text={copied ? 'Copied' : 'Copy'} onClick={copy} />
|
|
43
|
+
<Button as="a" href={url} target="_blank" rel="noopener noreferrer" mode="ghost" fontSize={1} padding={2} text="Open" />
|
|
44
44
|
</Flex>
|
|
45
45
|
</Card>
|
|
46
46
|
)}
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import {createElement, useState, type ComponentType} from 'react'
|
|
2
|
-
import {useFormValue, type InputProps} from 'sanity'
|
|
2
|
+
import {set, useFormValue, type InputProps} from 'sanity'
|
|
3
3
|
import {Button, Card, Flex, Stack, Text} from '@sanity/ui'
|
|
4
4
|
import type {ResolvedKitConfig} from '../config/types'
|
|
5
5
|
import {useKitClient} from '../hooks/useKitClient'
|
|
6
6
|
import {fieldPathKey, useTranslationTodo} from '../hooks/useTranslationTodo'
|
|
7
|
+
import {valueAtKey} from '../lib/aiTexts'
|
|
8
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
7
9
|
|
|
8
10
|
/**
|
|
9
11
|
* Sous un champ d'une traduction modifié dans la version principale (propagation) :
|
|
10
|
-
* « À traduire », avec « Marquer comme traduit » qui le retire de la liste
|
|
12
|
+
* « À traduire », avec « Marquer comme traduit » qui le retire de la liste, et
|
|
13
|
+
* « Translate with AI » (service du kit) : traduit le texte de la version principale
|
|
14
|
+
* dans ce champ (brouillon de cette langue), puis le retire de la liste.
|
|
11
15
|
*/
|
|
12
16
|
export function withTranslationTodo(Inner: ComponentType<InputProps>, config: ResolvedKitConfig): ComponentType<InputProps> {
|
|
13
17
|
function TranslationTodoInput(props: InputProps) {
|
|
@@ -15,6 +19,8 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
15
19
|
const client = useKitClient()
|
|
16
20
|
const todo = useTranslationTodo(client, config.i18n ? id : undefined)
|
|
17
21
|
const [busy, setBusy] = useState(false)
|
|
22
|
+
const [error, setError] = useState<string | null>(null)
|
|
23
|
+
const language = useFormValue([config.i18n?.field ?? 'language']) as string | undefined
|
|
18
24
|
const key = fieldPathKey(props.path)
|
|
19
25
|
const inner = createElement(Inner, props)
|
|
20
26
|
const show = Boolean(todo?.paths?.includes(key))
|
|
@@ -27,6 +33,26 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
27
33
|
.commit()
|
|
28
34
|
.finally(() => setBusy(false))
|
|
29
35
|
}
|
|
36
|
+
const translate = async () => {
|
|
37
|
+
if (!todo?.sourceId || !todo.sourceLanguage || !language || !config.history) return
|
|
38
|
+
setBusy(true)
|
|
39
|
+
setError(null)
|
|
40
|
+
try {
|
|
41
|
+
const source = (await client.getDocument(todo.sourceId)) ?? (await client.getDocument(`drafts.${todo.sourceId}`))
|
|
42
|
+
const value = valueAtKey(source, key)
|
|
43
|
+
if (value === undefined) throw new Error('Source text not found.')
|
|
44
|
+
const [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value])
|
|
45
|
+
props.onChange(set(translated))
|
|
46
|
+
await client
|
|
47
|
+
.patch(todo._id)
|
|
48
|
+
.set({paths: (todo.paths ?? []).filter((p) => p !== key)})
|
|
49
|
+
.commit()
|
|
50
|
+
} catch (cause) {
|
|
51
|
+
setError(cause instanceof Error ? cause.message : String(cause))
|
|
52
|
+
} finally {
|
|
53
|
+
setBusy(false)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
30
56
|
// Même structure que la mention soit là ou non : le champ n'est jamais recréé.
|
|
31
57
|
return (
|
|
32
58
|
<Stack gap={2}>
|
|
@@ -35,10 +61,18 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
35
61
|
<Card tone="caution" padding={2} radius={2} border>
|
|
36
62
|
<Flex align="center" gap={2}>
|
|
37
63
|
<Text size={1} style={{flex: 1}}>
|
|
38
|
-
|
|
64
|
+
To translate: changed in the {(todo?.sourceLanguage ?? '').toUpperCase()} version.
|
|
39
65
|
</Text>
|
|
40
|
-
|
|
66
|
+
{config.history && !props.readOnly && (
|
|
67
|
+
<Button tone="primary" fontSize={1} padding={2} text={busy ? 'Translating…' : 'Translate with AI'} disabled={busy} onClick={() => void translate()} />
|
|
68
|
+
)}
|
|
69
|
+
<Button mode="ghost" fontSize={1} padding={2} text="Mark as translated" disabled={busy} onClick={done} />
|
|
41
70
|
</Flex>
|
|
71
|
+
{error && (
|
|
72
|
+
<Text size={1} style={{marginTop: 8, color: 'var(--card-badge-critical-fg-color, #c00)'}}>
|
|
73
|
+
{error}
|
|
74
|
+
</Text>
|
|
75
|
+
)}
|
|
42
76
|
</Card>
|
|
43
77
|
)}
|
|
44
78
|
</Stack>
|
package/src/hooks/useHistory.ts
CHANGED
|
@@ -16,11 +16,11 @@ export interface HistoryState {
|
|
|
16
16
|
function explain(error: unknown): string {
|
|
17
17
|
const code = error instanceof Error ? error.message : String(error)
|
|
18
18
|
if (code === 'bad_key')
|
|
19
|
-
return "
|
|
19
|
+
return "The read key is not recognized: run `npx ncf-kit setup` again in the studio folder, then redeploy it."
|
|
20
20
|
if (code === 'project_inactive')
|
|
21
|
-
return "
|
|
22
|
-
if (code === 'missing_key') return '
|
|
23
|
-
return "
|
|
21
|
+
return "The log is not enabled for this project at NoCode Factory: `npx ncf-kit setup` enables it, or contact NoCode Factory."
|
|
22
|
+
if (code === 'missing_key') return 'No read key configured.'
|
|
23
|
+
return "The log could not be loaded."
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
/**
|
|
@@ -42,7 +42,7 @@ export function useHistory(documentId?: string): HistoryState {
|
|
|
42
42
|
|
|
43
43
|
useEffect(() => {
|
|
44
44
|
if (!history) {
|
|
45
|
-
setError('
|
|
45
|
+
setError('No read key configured.')
|
|
46
46
|
return undefined
|
|
47
47
|
}
|
|
48
48
|
|
|
@@ -52,7 +52,7 @@ export function useOccurrences(): OccurrencesState {
|
|
|
52
52
|
map.set(id, {
|
|
53
53
|
id,
|
|
54
54
|
type: doc._type,
|
|
55
|
-
title: (typeof title === 'string' ? title.trim() : '') || '
|
|
55
|
+
title: (typeof title === 'string' ? title.trim() : '') || 'Untitled',
|
|
56
56
|
})
|
|
57
57
|
}
|
|
58
58
|
return map
|
|
@@ -50,9 +50,9 @@ export function useOpenOnline() {
|
|
|
50
50
|
const tab = window.open('about:blank', '_blank')
|
|
51
51
|
if (!tab) return
|
|
52
52
|
tab.opener = null
|
|
53
|
-
tab.document.title = '
|
|
53
|
+
tab.document.title = 'Opening the preview…'
|
|
54
54
|
tab.document.body.innerHTML =
|
|
55
|
-
'<p style="font:15px/1.6 system-ui,sans-serif;color:#57534e;padding:2rem">
|
|
55
|
+
'<p style="font:15px/1.6 system-ui,sans-serif;color:#57534e;padding:2rem">Opening the preview…</p>'
|
|
56
56
|
|
|
57
57
|
try {
|
|
58
58
|
const {projectId, dataset, token} = client.config()
|
|
@@ -81,8 +81,8 @@ export function useOpenOnline() {
|
|
|
81
81
|
// On le dit dans l'onglet ouvert, plutôt que de laisser une page blanche
|
|
82
82
|
// ou d'envoyer sur la page de refus sans explication.
|
|
83
83
|
const message = explainGrantError(cause)
|
|
84
|
-
tab.document.title = '
|
|
85
|
-
tab.document.body.innerHTML = `<main style="font:15px/1.6 system-ui,sans-serif;color:#1c1917;padding:2rem;max-width:32rem"><h1 style="font-size:18px">
|
|
84
|
+
tab.document.title = 'Preview unavailable'
|
|
85
|
+
tab.document.body.innerHTML = `<main style="font:15px/1.6 system-ui,sans-serif;color:#1c1917;padding:2rem;max-width:32rem"><h1 style="font-size:18px">Unable to open the preview</h1><p style="color:#57534e"></p></main>`
|
|
86
86
|
const paragraph = tab.document.querySelector('p')
|
|
87
87
|
if (paragraph) paragraph.textContent = message
|
|
88
88
|
}
|
|
@@ -8,6 +8,7 @@ import {translationTodoId} from '../schema/translationTodo'
|
|
|
8
8
|
*/
|
|
9
9
|
export interface TranslationTodo {
|
|
10
10
|
_id: string
|
|
11
|
+
sourceId?: string
|
|
11
12
|
sourceLanguage?: string
|
|
12
13
|
paths?: string[]
|
|
13
14
|
}
|
|
@@ -31,7 +32,7 @@ function entryFor(client: SanityClient, documentId: string): Entry {
|
|
|
31
32
|
if (!e.stop) {
|
|
32
33
|
const load = () =>
|
|
33
34
|
client
|
|
34
|
-
.fetch<TranslationTodo | null>(`*[_id == $id][0]{_id, sourceLanguage, paths}`, {id})
|
|
35
|
+
.fetch<TranslationTodo | null>(`*[_id == $id][0]{_id, sourceId, sourceLanguage, paths}`, {id})
|
|
35
36
|
.then((value) => {
|
|
36
37
|
e.value = value
|
|
37
38
|
e.listeners.forEach((l) => l())
|
package/src/index.ts
CHANGED
|
@@ -85,11 +85,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
85
85
|
name: 'components',
|
|
86
86
|
tool: {
|
|
87
87
|
name: NCF_COMPONENTS_TOOL,
|
|
88
|
-
title: '
|
|
88
|
+
title: 'Components',
|
|
89
89
|
icon: ComponentIcon,
|
|
90
90
|
component: createToolComponent({
|
|
91
91
|
name: 'components',
|
|
92
|
-
title: '
|
|
92
|
+
title: 'Components',
|
|
93
93
|
config,
|
|
94
94
|
issues,
|
|
95
95
|
Component: ComponentsTool,
|
|
@@ -100,11 +100,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
100
100
|
name: 'history',
|
|
101
101
|
tool: {
|
|
102
102
|
name: NCF_HISTORY_TOOL,
|
|
103
|
-
title: '
|
|
103
|
+
title: 'History',
|
|
104
104
|
icon: ClockIcon,
|
|
105
105
|
component: createToolComponent({
|
|
106
106
|
name: 'history',
|
|
107
|
-
title: '
|
|
107
|
+
title: 'History',
|
|
108
108
|
config,
|
|
109
109
|
issues,
|
|
110
110
|
Component: HistoryTool,
|
|
@@ -152,7 +152,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
152
152
|
? prev.map((action) =>
|
|
153
153
|
action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config) : action,
|
|
154
154
|
)
|
|
155
|
-
:
|
|
155
|
+
: // Valeurs par défaut des composants : publier celles de la langue source
|
|
156
|
+
// (anglais en général) propose de retraduire celles des autres langues.
|
|
157
|
+
context.schemaType === config.componentPreview.defaultsType && config.i18n
|
|
158
|
+
? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action))
|
|
159
|
+
: prev,
|
|
156
160
|
},
|
|
157
161
|
|
|
158
162
|
// Le lanceur d'aperçu s'ajoute à droite des outils, dans la barre du haut
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Textes d'une valeur de champ, pour la traduction par IA : une chaîne, ou les
|
|
3
|
+
* morceaux de texte (spans) d'un texte riche. La structure (styles, liens, marques,
|
|
4
|
+
* _key) n'est jamais envoyée ni modifiée : seuls les textes sont remplacés.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
type Rec = Record<string, unknown>
|
|
8
|
+
const isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
9
|
+
|
|
10
|
+
/** Textes d'une valeur, dans l'ordre. */
|
|
11
|
+
export function collectTexts(value: unknown): string[] {
|
|
12
|
+
if (typeof value === 'string') return [value]
|
|
13
|
+
if (!Array.isArray(value)) return []
|
|
14
|
+
const out: string[] = []
|
|
15
|
+
for (const item of value) {
|
|
16
|
+
if (typeof item === 'string') out.push(item)
|
|
17
|
+
else if (isObj(item) && Array.isArray(item.children))
|
|
18
|
+
for (const child of item.children) if (isObj(child) && typeof child.text === 'string') out.push(child.text)
|
|
19
|
+
}
|
|
20
|
+
return out
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
|
|
24
|
+
export function replaceTexts(value: unknown, texts: readonly string[]): unknown {
|
|
25
|
+
let i = 0
|
|
26
|
+
const next = () => texts[i++] ?? ''
|
|
27
|
+
if (typeof value === 'string') return next()
|
|
28
|
+
if (!Array.isArray(value)) return value
|
|
29
|
+
return value.map((item) => {
|
|
30
|
+
if (typeof item === 'string') return next()
|
|
31
|
+
if (isObj(item) && Array.isArray(item.children))
|
|
32
|
+
return {...item, children: item.children.map((child) => (isObj(child) && typeof child.text === 'string' ? {...child, text: next()} : child))}
|
|
33
|
+
return item
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `sections[a].title` → segments (`[x]` : clé d'élément de liste, ou rang). */
|
|
38
|
+
export function parsePathKey(path: string): ({field: string} | {item: string})[] {
|
|
39
|
+
const out: ({field: string} | {item: string})[] = []
|
|
40
|
+
for (const m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] !== undefined ? {field: m[1]} : {item: m[2]!})
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function itemOf(list: unknown[], key: string): unknown {
|
|
45
|
+
return list.find((i) => isObj(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : undefined)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Valeur d'un document au chemin `sections[a].title`. */
|
|
49
|
+
export function valueAtKey(doc: unknown, path: string): unknown {
|
|
50
|
+
let cur: unknown = doc
|
|
51
|
+
for (const seg of parsePathKey(path)) {
|
|
52
|
+
if (cur == null) return undefined
|
|
53
|
+
if ('field' in seg) cur = isObj(cur) ? cur[seg.field] : undefined
|
|
54
|
+
else cur = Array.isArray(cur) ? itemOf(cur, seg.item) : undefined
|
|
55
|
+
}
|
|
56
|
+
return cur
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Écrit `value` au chemin dans `doc` (modifié sur place). Faux si le chemin n'existe pas. */
|
|
60
|
+
export function setAtKey(doc: Rec, path: string, value: unknown): boolean {
|
|
61
|
+
const segs = parsePathKey(path)
|
|
62
|
+
let cur: unknown = doc
|
|
63
|
+
for (let n = 0; n < segs.length - 1; n++) {
|
|
64
|
+
const seg = segs[n]!
|
|
65
|
+
cur = 'field' in seg ? (isObj(cur) ? cur[seg.field] : undefined) : Array.isArray(cur) ? itemOf(cur, seg.item) : undefined
|
|
66
|
+
if (cur == null) return false
|
|
67
|
+
}
|
|
68
|
+
const last = segs[segs.length - 1]
|
|
69
|
+
if (!last || !('field' in last) || !isObj(cur)) return false
|
|
70
|
+
cur[last.field] = value
|
|
71
|
+
return true
|
|
72
|
+
}
|