@nocode-factory/sanity-kit 2.27.1 → 2.29.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/bin/ncf-kit.mjs +43 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +206 -98
- package/dist/index.js.map +1 -1
- package/dist/schema.d.ts +38 -1
- package/dist/schema.js +77 -1
- package/dist/schema.js.map +1 -0
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +159 -70
- package/src/form/TranslationTodoInput.tsx +33 -6
- package/src/index.ts +1 -1
- package/src/lib/slugify.ts +12 -0
- package/src/schema/formTabs.ts +53 -0
- package/src/schema/index.ts +2 -0
- package/src/version.ts +1 -1
package/dist/schema.d.ts
CHANGED
|
@@ -1,2 +1,39 @@
|
|
|
1
1
|
import { a as defineComponentDefaults, i as defaultsFieldName, n as componentDefaultsMainDocument, o as requiredUnlessDefault, r as componentDefaultsMainDocuments, s as requiredUnlessDefaultFor, t as DEFAULT_COMPONENT_DEFAULTS_TYPE } from "./componentDefaults-CNiuukLt.js";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
|
|
4
|
+
*
|
|
5
|
+
* Un formulaire de page en une seule colonne mélange le contenu, le page builder et
|
|
6
|
+
* les réglages SEO : on cherche, on se trompe de champ. Ici, chaque champ d'un
|
|
7
|
+
* document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.
|
|
8
|
+
* - Sections : le champ du page builder (`pageBuilderField`, défaut `pageBuilder`).
|
|
9
|
+
* - SEO : `seo`, `structuredData` et les champs de métadonnées connus.
|
|
10
|
+
* - Settings : réglages de page (`pageOptions`, `options`, `settings`...).
|
|
11
|
+
* - Content : tout le reste (titre, slug, corps, image...).
|
|
12
|
+
* Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son
|
|
13
|
+
* `group` le garde. Pas d'onglets pour un document qui n'aurait qu'un onglet.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* schema: {types: withNcfFormTabs(schemaTypes, {pageBuilderField: 'pageBuilder'})}
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
declare const GROUPS: readonly [{
|
|
20
|
+
readonly name: "content";
|
|
21
|
+
readonly title: "Content";
|
|
22
|
+
readonly default: true;
|
|
23
|
+
}, {
|
|
24
|
+
readonly name: "sections";
|
|
25
|
+
readonly title: "Sections";
|
|
26
|
+
}, {
|
|
27
|
+
readonly name: "seo";
|
|
28
|
+
readonly title: "SEO";
|
|
29
|
+
}, {
|
|
30
|
+
readonly name: "settings";
|
|
31
|
+
readonly title: "Settings";
|
|
32
|
+
}];
|
|
33
|
+
/** Onglet d'un champ d'après son nom. */
|
|
34
|
+
export declare function formTabOf(name: string, pageBuilderField?: string): (typeof GROUPS)[number]['name'];
|
|
35
|
+
export declare function withNcfFormTabs<T>(types: readonly T[], options?: {
|
|
36
|
+
pageBuilderField?: string;
|
|
37
|
+
}): T[];
|
|
38
|
+
export { DEFAULT_COMPONENT_DEFAULTS_TYPE, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, requiredUnlessDefault, requiredUnlessDefaultFor };
|
|
39
|
+
//# sourceMappingURL=schema.d.ts.map
|
package/dist/schema.js
CHANGED
|
@@ -1,2 +1,78 @@
|
|
|
1
1
|
import { a as defineComponentDefaults, i as defaultsFieldName, n as componentDefaultsMainDocument, o as requiredUnlessDefault, r as componentDefaultsMainDocuments, s as requiredUnlessDefaultFor, t as DEFAULT_COMPONENT_DEFAULTS_TYPE } from "./componentDefaults-2eWjLLBf.js";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
|
|
4
|
+
*
|
|
5
|
+
* Un formulaire de page en une seule colonne mélange le contenu, le page builder et
|
|
6
|
+
* les réglages SEO : on cherche, on se trompe de champ. Ici, chaque champ d'un
|
|
7
|
+
* document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.
|
|
8
|
+
* - Sections : le champ du page builder (`pageBuilderField`, défaut `pageBuilder`).
|
|
9
|
+
* - SEO : `seo`, `structuredData` et les champs de métadonnées connus.
|
|
10
|
+
* - Settings : réglages de page (`pageOptions`, `options`, `settings`...).
|
|
11
|
+
* - Content : tout le reste (titre, slug, corps, image...).
|
|
12
|
+
* Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son
|
|
13
|
+
* `group` le garde. Pas d'onglets pour un document qui n'aurait qu'un onglet.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* schema: {types: withNcfFormTabs(schemaTypes, {pageBuilderField: 'pageBuilder'})}
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
const SEO_FIELDS = /* @__PURE__ */ new Set([
|
|
20
|
+
"seo",
|
|
21
|
+
"structuredData",
|
|
22
|
+
"jsonld",
|
|
23
|
+
"noindex",
|
|
24
|
+
"metaTitle",
|
|
25
|
+
"metaDescription",
|
|
26
|
+
"ogImage",
|
|
27
|
+
"canonical",
|
|
28
|
+
"canonicalUrl"
|
|
29
|
+
]), SETTINGS_FIELDS = /* @__PURE__ */ new Set([
|
|
30
|
+
"pageOptions",
|
|
31
|
+
"options",
|
|
32
|
+
"settings",
|
|
33
|
+
"hideFromMenu",
|
|
34
|
+
"showInMenu",
|
|
35
|
+
"parent",
|
|
36
|
+
"publishedAt",
|
|
37
|
+
"redirects"
|
|
38
|
+
]), GROUPS = [
|
|
39
|
+
{
|
|
40
|
+
name: "content",
|
|
41
|
+
title: "Content",
|
|
42
|
+
default: !0
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: "sections",
|
|
46
|
+
title: "Sections"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: "seo",
|
|
50
|
+
title: "SEO"
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
name: "settings",
|
|
54
|
+
title: "Settings"
|
|
55
|
+
}
|
|
56
|
+
];
|
|
57
|
+
/** Onglet d'un champ d'après son nom. */
|
|
58
|
+
function formTabOf(name, pageBuilderField = "pageBuilder") {
|
|
59
|
+
return name === pageBuilderField ? "sections" : SEO_FIELDS.has(name) ? "seo" : SETTINGS_FIELDS.has(name) ? "settings" : "content";
|
|
60
|
+
}
|
|
61
|
+
function withNcfFormTabs(types, options = {}) {
|
|
62
|
+
return types.map((input) => {
|
|
63
|
+
let type = input;
|
|
64
|
+
if (type.type !== "document" || type.groups || !Array.isArray(type.fields)) return input;
|
|
65
|
+
let fields = type.fields.map((field) => field.group || !field.name ? field : {
|
|
66
|
+
...field,
|
|
67
|
+
group: formTabOf(field.name, options.pageBuilderField)
|
|
68
|
+
}), used = new Set(fields.filter((f) => f.hidden !== !0).map((f) => f.group).flat()), groups = GROUPS.filter((g) => used.has(g.name)).map((g) => ({ ...g }));
|
|
69
|
+
return groups.length < 2 ? input : (groups.some((g) => "default" in g && g.default) || (groups[0].default = !0), {
|
|
70
|
+
...type,
|
|
71
|
+
groups,
|
|
72
|
+
fields
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export { DEFAULT_COMPONENT_DEFAULTS_TYPE, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, formTabOf, requiredUnlessDefault, requiredUnlessDefaultFor, withNcfFormTabs };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../src/schema/formTabs.ts"],"sourcesContent":["/**\n * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.\n *\n * Un formulaire de page en une seule colonne mélange le contenu, le page builder et\n * les réglages SEO : on cherche, on se trompe de champ. Ici, chaque champ d'un\n * document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.\n * - Sections : le champ du page builder (`pageBuilderField`, défaut `pageBuilder`).\n * - SEO : `seo`, `structuredData` et les champs de métadonnées connus.\n * - Settings : réglages de page (`pageOptions`, `options`, `settings`...).\n * - Content : tout le reste (titre, slug, corps, image...).\n * Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son\n * `group` le garde. Pas d'onglets pour un document qui n'aurait qu'un onglet.\n *\n * ```ts\n * schema: {types: withNcfFormTabs(schemaTypes, {pageBuilderField: 'pageBuilder'})}\n * ```\n */\n\nconst SEO_FIELDS = new Set(['seo', 'structuredData', 'jsonld', 'noindex', 'metaTitle', 'metaDescription', 'ogImage', 'canonical', 'canonicalUrl'])\nconst SETTINGS_FIELDS = new Set(['pageOptions', 'options', 'settings', 'hideFromMenu', 'showInMenu', 'parent', 'publishedAt', 'redirects'])\n\nconst GROUPS = [\n {name: 'content', title: 'Content', default: true},\n {name: 'sections', title: 'Sections'},\n {name: 'seo', title: 'SEO'},\n {name: 'settings', title: 'Settings'},\n] as const\n\ntype Field = {name?: string; group?: unknown; hidden?: unknown}\ntype TypeLike = {type?: string; groups?: unknown; fields?: Field[]}\n\n/** Onglet d'un champ d'après son nom. */\nexport function formTabOf(name: string, pageBuilderField = 'pageBuilder'): (typeof GROUPS)[number]['name'] {\n if (name === pageBuilderField) return 'sections'\n if (SEO_FIELDS.has(name)) return 'seo'\n if (SETTINGS_FIELDS.has(name)) return 'settings'\n return 'content'\n}\n\nexport function withNcfFormTabs<T>(types: readonly T[], options: {pageBuilderField?: string} = {}): T[] {\n return types.map((input) => {\n const type = input as unknown as TypeLike\n if (type.type !== 'document' || type.groups || !Array.isArray(type.fields)) return input\n const fields = type.fields.map((field) =>\n field.group || !field.name ? field : {...field, group: formTabOf(field.name, options.pageBuilderField)},\n )\n const used = new Set(fields.filter((f) => f.hidden !== true).map((f) => f.group).flat())\n const groups = GROUPS.filter((g) => used.has(g.name)).map((g) => ({...g}))\n if (groups.length < 2) return input\n if (!groups.some((g) => 'default' in g && g.default)) (groups[0] as {default?: boolean}).default = true\n return {...type, groups, fields} as unknown as T\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAO;CAAkB;CAAU;CAAW;CAAa;CAAmB;CAAW;CAAa;AAAc,CAAC,GAC3I,kCAAkB,IAAI,IAAI;CAAC;CAAe;CAAW;CAAY;CAAgB;CAAc;CAAU;CAAe;AAAW,CAAC,GAEpI,SAAS;CACb;EAAC,MAAM;EAAW,OAAO;EAAW,SAAS;CAAI;CACjD;EAAC,MAAM;EAAY,OAAO;CAAU;CACpC;EAAC,MAAM;EAAO,OAAO;CAAK;CAC1B;EAAC,MAAM;EAAY,OAAO;CAAU;AACtC;;AAMA,SAAgB,UAAU,MAAc,mBAAmB,eAAgD;CAIzG,OAHI,SAAS,mBAAyB,aAClC,WAAW,IAAI,IAAI,IAAU,QAC7B,gBAAgB,IAAI,IAAI,IAAU,aAC/B;AACT;AAEA,SAAgB,gBAAmB,OAAqB,UAAuC,CAAC,GAAQ;CACtG,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAM,OAAO;EACb,IAAI,KAAK,SAAS,cAAc,KAAK,UAAU,CAAC,MAAM,QAAQ,KAAK,MAAM,GAAG,OAAO;EACnF,IAAM,SAAS,KAAK,OAAO,KAAK,UAC9B,MAAM,SAAS,CAAC,MAAM,OAAO,QAAQ;GAAC,GAAG;GAAO,OAAO,UAAU,MAAM,MAAM,QAAQ,gBAAgB;EAAC,CACxG,GACM,OAAO,IAAI,IAAI,OAAO,QAAQ,MAAM,EAAE,WAAW,EAAI,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,GACjF,SAAS,OAAO,QAAQ,MAAM,KAAK,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,EAAC,GAAG,EAAC,EAAE;EAGzE,OAFI,OAAO,SAAS,IAAU,SACzB,OAAO,MAAM,MAAM,aAAa,KAAK,EAAE,OAAO,MAAG,OAAQ,EAAE,CAAyB,UAAU,KAC5F;GAAC,GAAG;GAAM;GAAQ;EAAM;CACjC,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -6,36 +6,49 @@ import type {ResolvedKitConfig} from '../config/types'
|
|
|
6
6
|
import {useKitClient} from '../hooks/useKitClient'
|
|
7
7
|
import {hasChanges, propagate, type PropagationResult, type SchemaTypeLike} from '../lib/propagate'
|
|
8
8
|
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
9
|
-
import {setAtKey, valueAtKey} from '../lib/aiTexts'
|
|
9
|
+
import {collectTexts, setAtKey, valueAtKey} from '../lib/aiTexts'
|
|
10
10
|
import {translateValues} from '../lib/aiTranslate'
|
|
11
|
+
import {slugify} from '../lib/slugify'
|
|
11
12
|
|
|
12
13
|
type Doc = Record<string, unknown>
|
|
14
|
+
type Client = ReturnType<typeof useKitClient>
|
|
13
15
|
interface Target {
|
|
14
16
|
language: string
|
|
15
|
-
|
|
17
|
+
/** Document de la traduction ; absent : version à CRÉER. */
|
|
18
|
+
id: string | null
|
|
16
19
|
result: PropagationResult
|
|
17
20
|
selected: boolean
|
|
18
21
|
}
|
|
22
|
+
type Mode = 'update' | 'create'
|
|
19
23
|
|
|
20
24
|
/**
|
|
21
|
-
* Publier la version PRINCIPALE d'une page
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
25
|
+
* Publier la version PRINCIPALE d'une page :
|
|
26
|
+
* - page déjà publiée qui a des traductions : « Propagate to other languages? »
|
|
27
|
+
* applique la structure (sections ajoutées, supprimées, déplacées) et les valeurs
|
|
28
|
+
* non textuelles (images, liens, options…) ;
|
|
29
|
+
* - PREMIÈRE publication : « Create the other language versions? » crée la page dans
|
|
30
|
+
* chaque langue cochée, reliée à ses traductions (hreflang, bascule de langue).
|
|
31
|
+
* Avec « Translate with AI » (service du kit, coché par défaut) : textes traduits
|
|
32
|
+
* par l'IA et versions PUBLIÉES directement (aucun clic de plus). Sans, ou si l'IA
|
|
33
|
+
* échoue : brouillons, textes marqués « To translate ». Une modification d'une autre
|
|
34
|
+
* langue ne remonte jamais à la version principale.
|
|
28
35
|
* `masterLocale` : langue source (défaut : langue principale du site ; les valeurs
|
|
29
|
-
* par défaut des composants ont la leur, `i18n.defaultsSourceLocale`).
|
|
36
|
+
* par défaut des composants ont la leur, `i18n.defaultsSourceLocale`). `allowCreate` :
|
|
37
|
+
* propose la création des autres versions (types de pages seulement).
|
|
30
38
|
*/
|
|
31
|
-
export function withPropagation(
|
|
39
|
+
export function withPropagation(
|
|
40
|
+
Publish: DocumentActionComponent,
|
|
41
|
+
config: ResolvedKitConfig,
|
|
42
|
+
masterLocale?: string,
|
|
43
|
+
options: {allowCreate?: boolean} = {},
|
|
44
|
+
): DocumentActionComponent {
|
|
32
45
|
const i18n = config.i18n
|
|
33
46
|
const master = masterLocale ?? i18n?.defaultLocale
|
|
34
47
|
const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
35
48
|
const base = Publish(props)
|
|
36
49
|
const client = useKitClient()
|
|
37
50
|
const schema = useSchema()
|
|
38
|
-
const [run, setRun] = useState<{
|
|
51
|
+
const [run, setRun] = useState<{mode: Mode; after: Doc; targets: Target[]} | null>(null)
|
|
39
52
|
const current = (props.draft ?? props.published) as Doc | null
|
|
40
53
|
if (!base || !i18n || current?.[i18n.field] !== master) return base
|
|
41
54
|
return {
|
|
@@ -44,20 +57,30 @@ export function withPropagation(Publish: DocumentActionComponent, config: Resolv
|
|
|
44
57
|
const before = props.published as Doc | null
|
|
45
58
|
const after = props.draft as Doc | null
|
|
46
59
|
base.onHandle?.()
|
|
47
|
-
|
|
48
|
-
// vraiment quelque chose à propager (sinon, aucun clic de plus).
|
|
49
|
-
if (!before || !after) return
|
|
60
|
+
if (!after) return
|
|
50
61
|
const documentType = schema.get(props.type) as unknown as SchemaTypeLike | undefined
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
62
|
+
const source = String(after[i18n.field] ?? '')
|
|
63
|
+
// La fenêtre ne s'ouvre que s'il y a vraiment quelque chose à faire.
|
|
64
|
+
if (before) {
|
|
65
|
+
void findTargets(client, props.id, source, before, after, documentType)
|
|
66
|
+
.then((targets) => {
|
|
67
|
+
if (targets.some((t) => hasChanges(t.result))) setRun({mode: 'update', after, targets})
|
|
68
|
+
})
|
|
69
|
+
.catch(() => {})
|
|
70
|
+
} else if (options.allowCreate) {
|
|
71
|
+
void findMissing(client, props.id, source, i18n.locales)
|
|
72
|
+
.then((missing) => {
|
|
73
|
+
if (!missing.length) return
|
|
74
|
+
const result = propagate({}, {}, after, documentType)
|
|
75
|
+
setRun({mode: 'create', after, targets: missing.map((language) => ({language, id: null, result, selected: true}))})
|
|
76
|
+
})
|
|
77
|
+
.catch(() => {})
|
|
78
|
+
}
|
|
56
79
|
},
|
|
57
80
|
dialog: run
|
|
58
81
|
? {
|
|
59
82
|
type: 'dialog',
|
|
60
|
-
header: 'Propagate to other languages?',
|
|
83
|
+
header: run.mode === 'create' ? 'Create the other language versions?' : 'Propagate to other languages?',
|
|
61
84
|
width: 'medium',
|
|
62
85
|
onClose: () => {
|
|
63
86
|
setRun(null)
|
|
@@ -68,7 +91,7 @@ export function withPropagation(Publish: DocumentActionComponent, config: Resolv
|
|
|
68
91
|
config={config}
|
|
69
92
|
id={props.id}
|
|
70
93
|
type={props.type}
|
|
71
|
-
|
|
94
|
+
mode={run.mode}
|
|
72
95
|
after={run.after}
|
|
73
96
|
targets={run.targets}
|
|
74
97
|
onDone={() => {
|
|
@@ -85,21 +108,18 @@ export function withPropagation(Publish: DocumentActionComponent, config: Resolv
|
|
|
85
108
|
return Wrapped
|
|
86
109
|
}
|
|
87
110
|
|
|
88
|
-
async function
|
|
89
|
-
client
|
|
90
|
-
|
|
91
|
-
source: string,
|
|
92
|
-
before: Doc,
|
|
93
|
-
after: Doc,
|
|
94
|
-
documentType: SchemaTypeLike | undefined,
|
|
95
|
-
): Promise<Target[]> {
|
|
96
|
-
const translations = await client.fetch<{language: string; id: string}[]>(
|
|
97
|
-
`*[_type == "translation.metadata" && references($id)][0].translations[]{language, "id": value._ref}`,
|
|
111
|
+
async function translationsOf(client: Client, id: string): Promise<{language: string; id: string}[]> {
|
|
112
|
+
const list = await client.fetch<{language?: string; key?: string; id?: string}[] | null>(
|
|
113
|
+
`*[_type == "translation.metadata" && references($id)][0].translations[]{language, "key": _key, "id": value._ref}`,
|
|
98
114
|
{id},
|
|
99
115
|
)
|
|
116
|
+
return (list ?? []).map((t) => ({language: t.language ?? t.key ?? '', id: t.id ?? ''})).filter((t) => t.language && t.id)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function findTargets(client: Client, id: string, source: string, before: Doc, after: Doc, documentType: SchemaTypeLike | undefined): Promise<Target[]> {
|
|
100
120
|
const list: Target[] = []
|
|
101
|
-
for (const t of
|
|
102
|
-
if (
|
|
121
|
+
for (const t of await translationsOf(client, id)) {
|
|
122
|
+
if (t.id === id || t.language === source) continue
|
|
103
123
|
const target = (await client.getDocument<Doc>(`drafts.${t.id}`)) ?? (await client.getDocument<Doc>(t.id)) ?? null
|
|
104
124
|
if (!target) continue
|
|
105
125
|
const result = propagate(target, before, after, documentType)
|
|
@@ -108,76 +128,136 @@ async function findTargets(
|
|
|
108
128
|
return list
|
|
109
129
|
}
|
|
110
130
|
|
|
131
|
+
async function findMissing(client: Client, id: string, source: string, locales: string[]): Promise<string[]> {
|
|
132
|
+
const existing = new Set((await translationsOf(client, id)).map((t) => t.language))
|
|
133
|
+
return locales.filter((l) => l !== source && !existing.has(l))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const randomId = () =>
|
|
137
|
+
typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`
|
|
138
|
+
|
|
139
|
+
/** Relie les nouvelles versions à la page (translation.metadata de document-internationalization). */
|
|
140
|
+
async function linkTranslations(client: Client, sourceId: string, sourceLanguage: string, type: string, created: {language: string; id: string}[]) {
|
|
141
|
+
if (!created.length) return
|
|
142
|
+
const item = (language: string, ref: string) => ({
|
|
143
|
+
_key: language,
|
|
144
|
+
_type: 'internationalizedArrayReferenceValue',
|
|
145
|
+
language,
|
|
146
|
+
value: {_type: 'reference', _ref: ref, _weak: true, _strengthenOnPublish: {type}},
|
|
147
|
+
})
|
|
148
|
+
const meta = await client.fetch<{_id: string} | null>(`*[_type == "translation.metadata" && references($id)][0]{_id}`, {id: sourceId})
|
|
149
|
+
if (meta) {
|
|
150
|
+
await client
|
|
151
|
+
.patch(meta._id)
|
|
152
|
+
.setIfMissing({translations: []})
|
|
153
|
+
.append('translations', created.map((c) => item(c.language, c.id)))
|
|
154
|
+
.commit()
|
|
155
|
+
} else {
|
|
156
|
+
await client.create({
|
|
157
|
+
_id: randomId(),
|
|
158
|
+
_type: 'translation.metadata',
|
|
159
|
+
schemaTypes: [type],
|
|
160
|
+
translations: [item(sourceLanguage, sourceId), ...created.map((c) => item(c.language, c.id))],
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
111
165
|
function PropagateDialog(props: {
|
|
112
166
|
config: ResolvedKitConfig
|
|
113
167
|
id: string
|
|
114
168
|
type: string
|
|
115
|
-
|
|
169
|
+
mode: Mode
|
|
116
170
|
after: Doc
|
|
117
171
|
targets: Target[]
|
|
118
172
|
onDone: () => void
|
|
119
173
|
}) {
|
|
120
|
-
const {config, id, type, after, onDone} = props
|
|
174
|
+
const {config, id, type, mode, after, onDone} = props
|
|
121
175
|
const client = useKitClient()
|
|
122
176
|
const field = config.i18n?.field ?? 'language'
|
|
123
177
|
const source = String(after[field] ?? '')
|
|
178
|
+
const pageType = config.pageTypes.find((t) => t.type === type)
|
|
124
179
|
const [targets, setTargets] = useState<Target[]>(props.targets)
|
|
125
180
|
const [busy, setBusy] = useState(false)
|
|
126
181
|
const toast = useToast()
|
|
127
182
|
const [error, setError] = useState<string | null>(null)
|
|
128
|
-
//
|
|
183
|
+
// Traduction par l'IA (service du kit) et publication directe.
|
|
129
184
|
const [ai, setAi] = useState(Boolean(config.history))
|
|
185
|
+
const hasTexts = targets.some((t) => t.result.toTranslate.length)
|
|
130
186
|
|
|
131
187
|
const apply = async () => {
|
|
132
188
|
setBusy(true)
|
|
133
189
|
setError(null)
|
|
134
190
|
try {
|
|
135
|
-
const
|
|
136
|
-
|
|
191
|
+
const published: string[] = []
|
|
192
|
+
const drafted: string[] = []
|
|
193
|
+
const created: {language: string; id: string}[] = []
|
|
137
194
|
let aiError: string | null = null
|
|
138
195
|
for (const t of targets) {
|
|
139
196
|
if (!t.selected) continue
|
|
140
|
-
const {_rev, _createdAt, _updatedAt, ...doc} = t.result.document
|
|
197
|
+
const {_id, _rev, _createdAt, _updatedAt, ...doc} = structuredClone(t.result.document) as Doc
|
|
198
|
+
const targetId = t.id ?? randomId()
|
|
141
199
|
let remaining = t.result.toTranslate
|
|
200
|
+
let translatedOk = !remaining.length
|
|
142
201
|
if (ai && config.history && remaining.length) {
|
|
143
202
|
try {
|
|
144
203
|
const values = remaining.map((path) => valueAtKey(after, path))
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
204
|
+
// Texte vidé dans la version principale : vidé aussi (suit la valeur par défaut).
|
|
205
|
+
const toSend = values.map((v) => (collectTexts(v).some((s) => s.trim()) ? v : undefined))
|
|
206
|
+
const translated = await translateValues(config.history, source, t.language, toSend.map((v) => v ?? ''))
|
|
207
|
+
remaining = remaining.filter((path, n) => !setAtKey(doc, path, toSend[n] === undefined ? undefined : translated[n]))
|
|
208
|
+
translatedOk = !remaining.length
|
|
148
209
|
} catch (cause) {
|
|
149
210
|
aiError = cause instanceof Error ? cause.message : String(cause)
|
|
150
211
|
}
|
|
151
212
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
213
|
+
if (mode === 'create') {
|
|
214
|
+
doc[field] = t.language
|
|
215
|
+
const slugField = pageType?.slugField
|
|
216
|
+
const titleField = pageType?.titleField ?? 'title'
|
|
217
|
+
const title = typeof doc[titleField] === 'string' ? (doc[titleField] as string) : ''
|
|
218
|
+
const sourceSlug = slugField ? (after[slugField] as {current?: string} | undefined)?.current : undefined
|
|
219
|
+
if (slugField && (title || sourceSlug)) {
|
|
220
|
+
// Slug unique dans la langue : suffixe -2, -3... si déjà pris.
|
|
221
|
+
const base = slugify(title) || String(sourceSlug)
|
|
222
|
+
let slug = base
|
|
223
|
+
for (let n = 2; await client.fetch<boolean>(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`, {type, slug, language: t.language}); n++) slug = `${base}-${n}`
|
|
224
|
+
doc[slugField] = {_type: 'slug', current: slug}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const publish = ai && translatedOk
|
|
228
|
+
const tx = client.transaction()
|
|
229
|
+
if (publish) {
|
|
230
|
+
tx.createOrReplace({...doc, _id: targetId, _type: type} as {_id: string; _type: string})
|
|
231
|
+
if (t.id) tx.delete(`drafts.${t.id}`)
|
|
232
|
+
} else {
|
|
233
|
+
tx.createOrReplace({...doc, _id: `drafts.${targetId}`, _type: type} as {_id: string; _type: string})
|
|
164
234
|
}
|
|
165
|
-
|
|
235
|
+
await tx.commit()
|
|
236
|
+
// Liste « To translate » de cette version : ce qui reste à traduire.
|
|
237
|
+
const todoId = translationTodoId(targetId)
|
|
238
|
+
const existing = (await client.fetch<string[] | null>(`*[_id == $todoId][0].paths`, {todoId})) ?? []
|
|
239
|
+
const done = new Set(t.result.toTranslate.filter((p) => !remaining.includes(p)))
|
|
240
|
+
const paths = [...new Set([...existing.filter((p) => !done.has(p)), ...remaining])]
|
|
241
|
+
if (paths.length || existing.length)
|
|
242
|
+
await client.createOrReplace({_id: todoId, _type: TRANSLATION_TODO_TYPE, documentId: targetId, sourceId: id, sourceLanguage: source, paths})
|
|
243
|
+
if (!t.id) created.push({language: t.language, id: targetId})
|
|
244
|
+
;(publish ? published : drafted).push(t.language.toUpperCase())
|
|
166
245
|
}
|
|
246
|
+
await linkTranslations(client, id, source, type, created)
|
|
167
247
|
// Fini : la fenêtre se ferme seule, le résultat s'affiche en notification.
|
|
168
248
|
toast.push({
|
|
169
249
|
status: aiError ? 'warning' : 'success',
|
|
170
|
-
title: `
|
|
250
|
+
title: [published.length ? `Published: ${published.join(', ')}` : '', drafted.length ? `Drafts: ${drafted.join(', ')}` : ''].filter(Boolean).join(' · '),
|
|
171
251
|
description: aiError
|
|
172
|
-
? `AI translation failed (${aiError}):
|
|
173
|
-
:
|
|
174
|
-
?
|
|
175
|
-
: '
|
|
252
|
+
? `AI translation failed (${aiError}): saved as drafts, texts marked "To translate".`
|
|
253
|
+
: drafted.length
|
|
254
|
+
? 'Translate the fields marked "To translate", then publish each language.'
|
|
255
|
+
: 'Translated with AI and published.',
|
|
176
256
|
duration: 8000,
|
|
177
257
|
})
|
|
178
258
|
onDone()
|
|
179
259
|
} catch (cause) {
|
|
180
|
-
setError(`
|
|
260
|
+
setError(`Failed. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 160)})`)
|
|
181
261
|
} finally {
|
|
182
262
|
setBusy(false)
|
|
183
263
|
}
|
|
@@ -186,22 +266,26 @@ function PropagateDialog(props: {
|
|
|
186
266
|
return (
|
|
187
267
|
<Stack gap={4} padding={4}>
|
|
188
268
|
<Text size={1}>
|
|
189
|
-
|
|
190
|
-
|
|
269
|
+
{mode === 'create'
|
|
270
|
+
? `The ${source.toUpperCase()} page is published. Create it in the other languages?`
|
|
271
|
+
: `The ${source.toUpperCase()} version is published. Apply its changes to the other languages?`}{' '}
|
|
272
|
+
{ai
|
|
273
|
+
? 'Texts are translated with AI and each language is published.'
|
|
274
|
+
: 'Each language is saved as a draft, texts marked "To translate".'}
|
|
191
275
|
</Text>
|
|
192
|
-
{config.history &&
|
|
276
|
+
{config.history && hasTexts && (
|
|
193
277
|
<Flex as="label" align="center" gap={2}>
|
|
194
278
|
<Checkbox checked={ai} onChange={() => setAi(!ai)} />
|
|
195
|
-
<Text size={1}>Translate
|
|
279
|
+
<Text size={1}>Translate with AI and publish</Text>
|
|
196
280
|
</Flex>
|
|
197
281
|
)}
|
|
198
282
|
<Stack gap={3}>
|
|
199
283
|
{targets.map((t, index) => (
|
|
200
|
-
<Card key={t.id} padding={3} radius={2} border>
|
|
284
|
+
<Card key={`${t.language}-${t.id ?? 'new'}`} padding={3} radius={2} border>
|
|
201
285
|
<Flex gap={3} align="flex-start">
|
|
202
286
|
<Checkbox
|
|
203
287
|
checked={t.selected}
|
|
204
|
-
disabled={!hasChanges(t.result)}
|
|
288
|
+
disabled={mode === 'update' && !hasChanges(t.result)}
|
|
205
289
|
onChange={() => setTargets(targets.map((x, i) => (i === index ? {...x, selected: !x.selected} : x)))}
|
|
206
290
|
/>
|
|
207
291
|
<Box flex={1}>
|
|
@@ -210,7 +294,7 @@ function PropagateDialog(props: {
|
|
|
210
294
|
{t.language.toUpperCase()}
|
|
211
295
|
</Text>
|
|
212
296
|
<Text size={1} muted>
|
|
213
|
-
{summary(t.result)}
|
|
297
|
+
{mode === 'create' ? `New version (${t.result.toTranslate.length} texts)` : summary(t.result)}
|
|
214
298
|
</Text>
|
|
215
299
|
</Stack>
|
|
216
300
|
</Box>
|
|
@@ -225,7 +309,12 @@ function PropagateDialog(props: {
|
|
|
225
309
|
)}
|
|
226
310
|
<Flex justify="flex-end" gap={2}>
|
|
227
311
|
<Button text="Skip" mode="ghost" onClick={onDone} disabled={busy} />
|
|
228
|
-
<Button
|
|
312
|
+
<Button
|
|
313
|
+
text={busy ? 'Working…' : mode === 'create' ? 'Create' : 'Propagate'}
|
|
314
|
+
tone="primary"
|
|
315
|
+
onClick={() => void apply()}
|
|
316
|
+
disabled={busy || !targets.some((t) => t.selected)}
|
|
317
|
+
/>
|
|
229
318
|
</Flex>
|
|
230
319
|
</Stack>
|
|
231
320
|
)
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {createElement, useState, type ComponentType} from 'react'
|
|
2
|
-
import {set, useFormValue, type InputProps} from 'sanity'
|
|
1
|
+
import {createElement, useEffect, useState, type ComponentType} from 'react'
|
|
2
|
+
import {set, unset, 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'
|
|
7
|
+
import {collectTexts, valueAtKey} from '../lib/aiTexts'
|
|
8
8
|
import {translateValues} from '../lib/aiTranslate'
|
|
9
9
|
|
|
10
10
|
/**
|
|
@@ -24,6 +24,24 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
24
24
|
const key = fieldPathKey(props.path)
|
|
25
25
|
const inner = createElement(Inner, props)
|
|
26
26
|
const show = Boolean(todo?.paths?.includes(key))
|
|
27
|
+
// Texte de la version principale (publiée), affiché pour aider à traduire.
|
|
28
|
+
const [master, setMaster] = useState<string | null>(null)
|
|
29
|
+
const sourceId = show ? todo?.sourceId : undefined
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!sourceId) return
|
|
32
|
+
let alive = true
|
|
33
|
+
void client
|
|
34
|
+
.getDocument(sourceId)
|
|
35
|
+
.then((doc) => {
|
|
36
|
+
if (!alive) return
|
|
37
|
+
const text = collectTexts(valueAtKey(doc, key)).join('').trim()
|
|
38
|
+
setMaster(text || '(empty: follows the component default)')
|
|
39
|
+
})
|
|
40
|
+
.catch(() => alive && setMaster(null))
|
|
41
|
+
return () => {
|
|
42
|
+
alive = false
|
|
43
|
+
}
|
|
44
|
+
}, [client, sourceId, key])
|
|
27
45
|
const done = () => {
|
|
28
46
|
if (!todo) return
|
|
29
47
|
setBusy(true)
|
|
@@ -40,9 +58,13 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
40
58
|
try {
|
|
41
59
|
const source = (await client.getDocument(todo.sourceId)) ?? (await client.getDocument(`drafts.${todo.sourceId}`))
|
|
42
60
|
const value = valueAtKey(source, key)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
props.onChange(
|
|
61
|
+
// Texte vidé dans la version principale (il suit la valeur par défaut du
|
|
62
|
+
// composant) : vidé ici aussi, comme la version principale.
|
|
63
|
+
if (!collectTexts(value).some((t) => t.trim())) props.onChange(unset())
|
|
64
|
+
else {
|
|
65
|
+
const [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value])
|
|
66
|
+
props.onChange(set(translated))
|
|
67
|
+
}
|
|
46
68
|
await client
|
|
47
69
|
.patch(todo._id)
|
|
48
70
|
.set({paths: (todo.paths ?? []).filter((p) => p !== key)})
|
|
@@ -68,6 +90,11 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
68
90
|
)}
|
|
69
91
|
<Button mode="ghost" fontSize={1} padding={2} text="Mark as translated" disabled={busy} onClick={done} />
|
|
70
92
|
</Flex>
|
|
93
|
+
{master && (
|
|
94
|
+
<Text size={1} muted style={{marginTop: 8, whiteSpace: 'pre-wrap'}}>
|
|
95
|
+
{(todo?.sourceLanguage ?? '').toUpperCase()}: {master.length > 600 ? `${master.slice(0, 600)}…` : master}
|
|
96
|
+
</Text>
|
|
97
|
+
)}
|
|
71
98
|
{error && (
|
|
72
99
|
<Text size={1} style={{marginTop: 8, color: 'var(--card-badge-critical-fg-color, #c00)'}}>
|
|
73
100
|
{error}
|
package/src/index.ts
CHANGED
|
@@ -150,7 +150,7 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
150
150
|
actions: (prev, context) =>
|
|
151
151
|
config.pageTypeNames.includes(context.schemaType)
|
|
152
152
|
? prev.map((action) =>
|
|
153
|
-
action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config) : action,
|
|
153
|
+
action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config, undefined, {allowCreate: true}) : action,
|
|
154
154
|
)
|
|
155
155
|
: // Valeurs par défaut des composants : publier celles de la langue source
|
|
156
156
|
// (anglais en général) propose de retraduire celles des autres langues.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Slug d'URL depuis un titre : sans accents, minuscules, tirets. */
|
|
2
|
+
export function slugify(input: string, maxLength = 96): string {
|
|
3
|
+
return input
|
|
4
|
+
.normalize('NFD')
|
|
5
|
+
.replace(/[̀-ͯ]/g, '')
|
|
6
|
+
.toLowerCase()
|
|
7
|
+
.replace(/&/g, ' and ')
|
|
8
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
9
|
+
.replace(/^-+|-+$/g, '')
|
|
10
|
+
.slice(0, maxLength)
|
|
11
|
+
.replace(/-+$/g, '')
|
|
12
|
+
}
|