@textunited/sanity-plugin 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1003 @@
1
+ import { activeProjects, projectLanguages, projectForLanguage, getBaseDocumentId, getDocumentTypeConfig, loadTargets, extractTranslationUnits, sentRecord, readProjects, emptyState, migrateLegacyState, planTranslation } from '../chunk-JLJTUACB.js';
2
+ import { definePlugin, defineDocumentInspector, useClient, useSchema, useEditState } from 'sanity';
3
+ import { useMemo, useState, useEffect, useRef, useCallback } from 'react';
4
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
+ import { LaunchIcon, CloseIcon, CheckmarkCircleIcon, TranslateIcon } from '@sanity/icons';
6
+ import { useToast, Flex, Card, Text, Box, Button, Stack, Spinner, Checkbox, Radio, Badge } from '@sanity/ui';
7
+ import { useDocumentPane } from 'sanity/structure';
8
+
9
+ // src/studio/logic.ts
10
+ var PROJECT_TYPE_OPTIONS = [
11
+ {
12
+ value: "outsourced",
13
+ title: "TextUnited translators (outsourced)",
14
+ description: "TextUnited manages the project and assigns its translators."
15
+ },
16
+ {
17
+ value: "inHouse",
18
+ title: "Your own team (in-house)",
19
+ description: "People from your TextUnited account translate. Pick at least one translator."
20
+ }
21
+ ];
22
+ function projectTypeLabel(type) {
23
+ return type === "inHouse" ? "In-house" : type === "outsourced" ? "Outsourced" : "Unknown type";
24
+ }
25
+ function validateTeam(team) {
26
+ return team.some((member) => member.translator) ? null : "Pick at least one translator.";
27
+ }
28
+ function teamForRequest(team) {
29
+ return team.filter((member) => member.translator || member.proofreader || member.projectManager).map(({ id, username, translator, proofreader, projectManager }) => ({
30
+ _key: String(id),
31
+ id,
32
+ username,
33
+ translator,
34
+ proofreader,
35
+ projectManager
36
+ }));
37
+ }
38
+ function readTranslationState(document) {
39
+ const { projects, archived, stopped } = readProjects(document);
40
+ let state = emptyState();
41
+ try {
42
+ if (typeof document?.stateJson === "string") state = JSON.parse(document.stateJson);
43
+ } catch {
44
+ }
45
+ if (typeof document?.projectsJson !== "string") state = migrateLegacyState(state, projects[0]?.customId);
46
+ return { state, projects, archived, stopped };
47
+ }
48
+ var REVIEWED_STATUSES = /* @__PURE__ */ new Set(["translated", "proofread"]);
49
+ function languageProgress(state, projects) {
50
+ const progress = /* @__PURE__ */ new Map();
51
+ for (const project of projects) {
52
+ for (const language of project.languages) {
53
+ const entry = { reviewed: 0, total: 0 };
54
+ for (const record of Object.values(state.units)) {
55
+ if (!sentRecord(record, project.customId)) continue;
56
+ entry.total += 1;
57
+ if (REVIEWED_STATUSES.has(String(record.languages[language]?.status ?? "").toLowerCase())) entry.reviewed += 1;
58
+ }
59
+ if (entry.total > 0) progress.set(language, entry);
60
+ }
61
+ }
62
+ return progress;
63
+ }
64
+ var INSTALL_GUIDE_URL = "https://github.com/TextUnited/textunited-sanity-plugin/blob/main/docs/INSTALL.md#before-you-start-how-does-your-studio-store-translations";
65
+ function checkLocalizationSetup(config, documentType, schemaTypeNames) {
66
+ const typeConfig = config.documentTypes.find((entry) => entry.type === documentType);
67
+ if (!typeConfig) return null;
68
+ const names = [...schemaTypeNames];
69
+ if (typeConfig.model === "fieldLevel" && !names.some((name) => name.startsWith("internationalizedArray"))) {
70
+ return `\u201C${documentType}\u201D is set up to translate fields (fieldLevel), but this Studio has no Internationalized Array plugin (sanity-plugin-internationalized-array). Add it, or change the model in the translation configuration.`;
71
+ }
72
+ if (typeConfig.model === "documentLevel" && !names.includes("translation.metadata")) {
73
+ return `\u201C${documentType}\u201D is set up to translate whole documents (documentLevel), but this Studio has no Document Internationalization plugin (@sanity/document-internationalization). Add it, or change the model in the translation configuration.`;
74
+ }
75
+ return null;
76
+ }
77
+ function fieldLanguageIds(value, found = /* @__PURE__ */ new Set()) {
78
+ if (Array.isArray(value)) {
79
+ for (const item of value) {
80
+ const record = item;
81
+ if (record && typeof record._key === "string" && typeof record._type === "string" && /^internationalizedArray.*Value$/.test(record._type)) {
82
+ found.add(record._key);
83
+ }
84
+ fieldLanguageIds(item, found);
85
+ }
86
+ } else if (value && typeof value === "object") {
87
+ for (const child of Object.values(value)) fieldLanguageIds(child, found);
88
+ }
89
+ return found;
90
+ }
91
+ function checkLanguageIds(config, documentType, document) {
92
+ const typeConfig = config.documentTypes.find((entry) => entry.type === documentType);
93
+ if (!typeConfig || !document) return null;
94
+ const configured = [config.sourceLanguage, ...config.targetLanguages].map((language2) => language2.id);
95
+ if (typeConfig.model === "fieldLevel") {
96
+ const ids = fieldLanguageIds(document);
97
+ if (ids.size === 0 || ids.has(config.sourceLanguage.id)) return null;
98
+ return `The fields of this document use the language ids ${[...ids].map((id) => `\u201C${id}\u201D`).join(", ")}, but the translation configuration expects \u201C${config.sourceLanguage.id}\u201D for ${config.sourceLanguage.title}. Use the same ids as the Internationalized Array plugin.`;
99
+ }
100
+ const language = document[typeConfig.languageField ?? "language"];
101
+ if (typeof language === "string" && language !== "" && !configured.includes(language)) {
102
+ return `This document's language is \u201C${language}\u201D, which is not in the translation configuration (${configured.map((id) => `\u201C${id}\u201D`).join(", ")}). Use the same ids as the Document Internationalization plugin.`;
103
+ }
104
+ return null;
105
+ }
106
+ function canTranslateDocument(config, documentType, document) {
107
+ const typeConfig = config.documentTypes.find((entry) => entry.type === documentType);
108
+ if (!typeConfig) return { allowed: false, reason: "This document type is not set up for translation" };
109
+ if (!document) return { allowed: false, reason: "Save the document before translating it" };
110
+ if (typeConfig.model === "documentLevel") {
111
+ const language = document[typeConfig.languageField ?? "language"];
112
+ if (language !== void 0 && language !== config.sourceLanguage.id) {
113
+ return { allowed: false, reason: `Translations are requested from the ${config.sourceLanguage.title} version` };
114
+ }
115
+ }
116
+ return { allowed: true };
117
+ }
118
+ function describeRequest(request) {
119
+ if (!request) return "Not translated with TextUnited yet.";
120
+ if (request.status === "queued" || request.status === "running") return "Translation request in progress\u2026";
121
+ if (request.status === "failed") return `The last request failed: ${request.error ?? "unknown error"}`;
122
+ let summary = {};
123
+ try {
124
+ summary = JSON.parse(request.summaryJson ?? "{}");
125
+ } catch {
126
+ }
127
+ if (summary.action === "stop") return `Stopped translating ${(summary.languages ?? []).join(", ").toUpperCase()}.`;
128
+ if (summary.action === "resume") return `Resumed translating ${(summary.languages ?? []).join(", ").toUpperCase()}.`;
129
+ if (!summary.tasksSent?.length) return "Nothing needed translation in the last request.";
130
+ const applied = summary.outcomes?.applied ?? 0;
131
+ const kept = summary.outcomes?.keptManualEdit ?? 0;
132
+ const texts = summary.textsSent ?? summary.unitsSelected;
133
+ const sent = typeof texts === "number" ? `${texts} text(s)` : `${summary.tasksSent.length} part(s) of the document`;
134
+ const parts = [
135
+ `${summary.projectCreated ? "Created the TextUnited project and sent" : "Sent"} ${sent}.`,
136
+ `${applied} machine translation(s) added to the draft.`
137
+ ];
138
+ if (kept > 0) parts.push(`${kept} translation(s) edited by hand were kept.`);
139
+ const awaiting = summary.tasksAwaitingTranslation?.length ?? 0;
140
+ if (awaiting > 0) {
141
+ parts.push(`TextUnited is still preparing ${awaiting} part(s); their translations will be added later.`);
142
+ }
143
+ return parts.join(" ");
144
+ }
145
+
146
+ // src/studio/summary.ts
147
+ function countWords(content) {
148
+ const text = content.replace(/<[^>]+>/g, " ").trim();
149
+ return text ? text.split(/\s+/).length : 0;
150
+ }
151
+ function summarizePending(args) {
152
+ const mode = args.mode ?? "changed";
153
+ const projects = args.projects ?? [];
154
+ const planFor = (languages) => planTranslation({
155
+ units: args.units,
156
+ targets: args.targets,
157
+ state: args.state,
158
+ languages,
159
+ mode,
160
+ projectCustomId: languages[0] ? projectForLanguage(projects, languages[0])?.customId : void 0
161
+ });
162
+ const groups = /* @__PURE__ */ new Map();
163
+ for (const language of args.languages) {
164
+ const key = projectForLanguage(projects, language)?.customId ?? "";
165
+ groups.set(key, [...groups.get(key) ?? [], language]);
166
+ }
167
+ const selected = /* @__PURE__ */ new Map();
168
+ for (const languages of groups.values()) {
169
+ for (const entry of planFor(languages).selected) {
170
+ if (!selected.has(entry.unit.id) || entry.reason === "sourceChanged") selected.set(entry.unit.id, entry);
171
+ }
172
+ }
173
+ const byLanguage = {};
174
+ for (const language of args.languages) byLanguage[language] = planFor([language]).selected.length;
175
+ const chosen = [...selected.values()];
176
+ return {
177
+ texts: chosen.length,
178
+ changed: chosen.filter(({ reason }) => reason === "sourceChanged").length,
179
+ untranslated: chosen.filter(({ reason }) => reason === "missing").length,
180
+ words: chosen.reduce(
181
+ (sum, { unit }) => sum + unit.segments.reduce((total, segment) => total + countWords(segment.content), 0),
182
+ 0
183
+ ),
184
+ byLanguage
185
+ };
186
+ }
187
+ function describePending(summary) {
188
+ const parts = [];
189
+ if (summary.changed > 0) parts.push(`${summary.changed} changed`);
190
+ if (summary.untranslated > 0) parts.push(`${summary.untranslated} not translated yet`);
191
+ const words = summary.words === 1 ? "1 word" : `${summary.words} words`;
192
+ return `${parts.join(", ")} \xB7 about ${words}`;
193
+ }
194
+ function badgeLabel(progress, projectLanguages2) {
195
+ const languages = (projectLanguages2 ?? []).filter((language) => progress.has(language));
196
+ if (languages.length === 0) return null;
197
+ const complete = languages.every((language) => {
198
+ const entry = progress.get(language);
199
+ return entry.reviewed === entry.total;
200
+ });
201
+ if (languages.length > 3) {
202
+ const done = languages.filter((language) => {
203
+ const entry = progress.get(language);
204
+ return entry.reviewed === entry.total;
205
+ }).length;
206
+ return { label: `Translated ${done}/${languages.length}`, complete };
207
+ }
208
+ const label = languages.map((language) => {
209
+ const entry = progress.get(language);
210
+ return `${language.toUpperCase()} ${entry.reviewed}/${entry.total}`;
211
+ }).join(" \xB7 ");
212
+ return { label, complete };
213
+ }
214
+ function TextUnitedIcon() {
215
+ return /* @__PURE__ */ jsxs(
216
+ "svg",
217
+ {
218
+ "data-sanity-icon": "textunited",
219
+ width: "1em",
220
+ height: "1em",
221
+ viewBox: "0 0 25 25",
222
+ fill: "none",
223
+ xmlns: "http://www.w3.org/2000/svg",
224
+ "aria-hidden": "true",
225
+ children: [
226
+ /* @__PURE__ */ jsx("rect", { x: "4.5", y: "5.5", width: "16", height: "14", rx: "2.5", stroke: "currentColor", strokeWidth: 1.2 }),
227
+ /* @__PURE__ */ jsx(
228
+ "text",
229
+ {
230
+ x: "12.5",
231
+ y: "15.6",
232
+ textAnchor: "middle",
233
+ fontSize: "8",
234
+ fontWeight: 700,
235
+ fontFamily: "system-ui, -apple-system, 'Segoe UI', sans-serif",
236
+ fill: "currentColor",
237
+ children: "TU"
238
+ }
239
+ )
240
+ ]
241
+ }
242
+ );
243
+ }
244
+ var API_VERSION = "2025-02-19";
245
+ function TeamPicker(props) {
246
+ const { handlerUrl, team, onChange, disabled, savedRoles } = props;
247
+ const client = useClient({ apiVersion: API_VERSION });
248
+ const [error, setError] = useState(null);
249
+ const [loading, setLoading] = useState(team.length === 0);
250
+ useEffect(() => {
251
+ if (team.length > 0) return void 0;
252
+ let cancelled = false;
253
+ const load = async () => {
254
+ const queryId = `textunited.teamQuery.${crypto.randomUUID()}`;
255
+ try {
256
+ await client.create({ _id: queryId, _type: "textunited.teamQuery", requestedAt: (/* @__PURE__ */ new Date()).toISOString() });
257
+ const response = await fetch(`${handlerUrl.replace(/\/+$/, "")}/team`, {
258
+ method: "POST",
259
+ headers: { "Content-Type": "application/json" },
260
+ body: JSON.stringify({ queryId })
261
+ });
262
+ const body = await response.json();
263
+ if (!response.ok) throw new Error(body.message ?? `The server answered ${response.status}`);
264
+ if (!cancelled) {
265
+ onChange(
266
+ (body.members ?? []).map((member) => ({
267
+ ...member,
268
+ translator: savedRoles?.[member.id]?.translator === true,
269
+ proofreader: savedRoles?.[member.id]?.proofreader === true,
270
+ projectManager: savedRoles?.[member.id]?.projectManager === true
271
+ }))
272
+ );
273
+ }
274
+ } catch (loadError) {
275
+ if (!cancelled) setError(loadError instanceof Error ? loadError.message : "Could not load the team");
276
+ } finally {
277
+ if (!cancelled) setLoading(false);
278
+ }
279
+ };
280
+ void load();
281
+ return () => {
282
+ cancelled = true;
283
+ };
284
+ }, []);
285
+ if (loading) {
286
+ return /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 2, children: [
287
+ /* @__PURE__ */ jsx(Spinner, { muted: true }),
288
+ /* @__PURE__ */ jsx(Text, { size: 1, muted: true, children: "Loading people from TextUnited\u2026" })
289
+ ] });
290
+ }
291
+ if (error) {
292
+ return /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "critical", children: /* @__PURE__ */ jsx(Text, { size: 1, children: error }) });
293
+ }
294
+ if (team.length === 0) {
295
+ return /* @__PURE__ */ jsx(Text, { size: 1, muted: true, children: "Nobody in this TextUnited account can be added to a team." });
296
+ }
297
+ const toggle = (id, role) => onChange(team.map((member) => member.id === id ? { ...member, [role]: !member[role] } : member));
298
+ return /* @__PURE__ */ jsx(Stack, { space: 3, children: team.map((member) => /* @__PURE__ */ jsx(Card, { padding: 2, radius: 2, border: true, children: /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
299
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "center", wrap: "wrap", children: [
300
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "medium", children: member.name }),
301
+ member.kind === "collaborator" ? /* @__PURE__ */ jsx(Badge, { children: "Collaborator" }) : null,
302
+ /* @__PURE__ */ jsx(Text, { size: 0, muted: true, children: member.username })
303
+ ] }),
304
+ /* @__PURE__ */ jsx(Flex, { gap: 4, wrap: "wrap", children: [
305
+ ["translator", "Translator"],
306
+ ["proofreader", "Proofreader"],
307
+ ["projectManager", "Project manager"]
308
+ ].map(([role, label]) => /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "center", as: "label", children: [
309
+ /* @__PURE__ */ jsx(Checkbox, { checked: member[role], disabled, onChange: () => toggle(member.id, role) }),
310
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: label }) })
311
+ ] }, role)) })
312
+ ] }) }, member.id)) });
313
+ }
314
+ var API_VERSION2 = "2025-02-19";
315
+ var STATUS_QUERY = `{
316
+ "state": *[_id == $stateId][0]{projectCustomId, projectLanguages, projectType, projectId, projectsJson, stateJson, pending, updatedAt},
317
+ "requests": *[_type == "textunited.translationRequest" && documentId == $documentId]
318
+ | order(_createdAt desc)[0...5]{_id, _createdAt, status, error, summaryJson, languages, mode}
319
+ }`;
320
+ function useTranslationData(documentId, documentType, options) {
321
+ const baseId = getBaseDocumentId(documentId);
322
+ const client = useClient({ apiVersion: API_VERSION2 });
323
+ const editState = useEditState(baseId, documentType);
324
+ const source = editState.draft ?? editState.published ?? null;
325
+ const typeConfig = getDocumentTypeConfig(options.translation, documentType);
326
+ const [status, setStatus] = useState(null);
327
+ const [error, setError] = useState(null);
328
+ const [documentLevelTargets, setDocumentLevelTargets] = useState(null);
329
+ const mounted = useRef(true);
330
+ const loadStatus = useCallback(async () => {
331
+ try {
332
+ const data = await client.fetch(
333
+ STATUS_QUERY,
334
+ { documentId: baseId, stateId: `textunited.state.${baseId}` },
335
+ { perspective: "raw" }
336
+ );
337
+ if (mounted.current) {
338
+ setStatus(data);
339
+ setError(null);
340
+ }
341
+ } catch (loadError) {
342
+ if (mounted.current) setError(loadError instanceof Error ? loadError.message : "Could not load the status");
343
+ }
344
+ }, [client, baseId]);
345
+ const languages = useMemo(
346
+ () => options.translation.targetLanguages.map((language) => language.id),
347
+ [options.translation]
348
+ );
349
+ const loadDocumentLevelTargets = useCallback(async () => {
350
+ if (!source || typeConfig?.model !== "documentLevel") return;
351
+ const store = {
352
+ getDocument: (id) => client.fetch("*[_id == $id][0]", { id }, { perspective: "raw" }),
353
+ findTranslationMetadata: (id) => client.fetch('*[_type == "translation.metadata" && $id in translations[].value._ref][0]', { id }, {
354
+ perspective: "raw"
355
+ }),
356
+ mutate: () => Promise.reject(new Error("read only")),
357
+ listPendingDocuments: () => Promise.resolve([])
358
+ };
359
+ try {
360
+ const loaded = await loadTargets({ store, source, typeConfig, languages });
361
+ if (mounted.current) setDocumentLevelTargets(loaded.targets);
362
+ } catch (loadError) {
363
+ if (mounted.current) setError(loadError instanceof Error ? loadError.message : "Could not load translations");
364
+ }
365
+ }, [client, typeConfig, languages, source?._id]);
366
+ const refresh = useCallback(() => {
367
+ void loadStatus();
368
+ void loadDocumentLevelTargets();
369
+ }, [loadStatus, loadDocumentLevelTargets]);
370
+ useEffect(() => {
371
+ mounted.current = true;
372
+ refresh();
373
+ return () => {
374
+ mounted.current = false;
375
+ };
376
+ }, [refresh]);
377
+ useEffect(() => {
378
+ const subscription = client.listen(
379
+ '*[(_id == $stateId) || (_type == "textunited.translationRequest" && documentId == $documentId)]',
380
+ { documentId: baseId, stateId: `textunited.state.${baseId}` },
381
+ { visibility: "query", includeResult: false }
382
+ ).subscribe({ next: () => refresh(), error: () => void 0 });
383
+ return () => subscription.unsubscribe();
384
+ }, [client, baseId, refresh]);
385
+ const units = useMemo(
386
+ () => source && typeConfig ? extractTranslationUnits(source, typeConfig, options.translation) : [],
387
+ [source, typeConfig, options.translation]
388
+ );
389
+ const targets = typeConfig?.model === "fieldLevel" && source ? { model: "fieldLevel", document: source } : documentLevelTargets;
390
+ const read = useMemo(() => readTranslationState(status?.state ?? null), [status?.state]);
391
+ return {
392
+ loading: !status && !error,
393
+ error,
394
+ state: status?.state ?? null,
395
+ translationState: read.state,
396
+ projects: read.projects,
397
+ archived: read.archived,
398
+ stopped: read.stopped,
399
+ requests: status?.requests ?? [],
400
+ source,
401
+ units,
402
+ targets,
403
+ refresh
404
+ };
405
+ }
406
+ var API_VERSION3 = "2025-02-19";
407
+ function teamStorageKey(projectId, dataset) {
408
+ return `textunited.team.${projectId}.${dataset}`;
409
+ }
410
+ function readSavedRoles(key) {
411
+ try {
412
+ return JSON.parse(window.localStorage.getItem(key) ?? "{}");
413
+ } catch {
414
+ return {};
415
+ }
416
+ }
417
+ function saveRoles(key, team) {
418
+ try {
419
+ const roles = {};
420
+ for (const member of team) {
421
+ if (member.translator || member.proofreader || member.projectManager) {
422
+ roles[member.id] = {
423
+ translator: member.translator,
424
+ proofreader: member.proofreader,
425
+ projectManager: member.projectManager
426
+ };
427
+ }
428
+ }
429
+ window.localStorage.setItem(key, JSON.stringify(roles));
430
+ } catch {
431
+ }
432
+ }
433
+ function isRunning(request) {
434
+ return request?.status === "queued" || request?.status === "running";
435
+ }
436
+ function formatTime(value) {
437
+ if (!value) return "";
438
+ const date = new Date(value);
439
+ const sameDay = date.toDateString() === (/* @__PURE__ */ new Date()).toDateString();
440
+ return sameDay ? date.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" }) : date.toLocaleDateString(void 0, { day: "numeric", month: "short" });
441
+ }
442
+ function ProgressBar(props) {
443
+ return /* @__PURE__ */ jsx(
444
+ "div",
445
+ {
446
+ role: "progressbar",
447
+ "aria-valuemin": 0,
448
+ "aria-valuemax": 100,
449
+ "aria-valuenow": Math.round(props.value * 100),
450
+ style: { height: 4, borderRadius: 2, overflow: "hidden", background: "var(--card-border-color)" },
451
+ children: /* @__PURE__ */ jsx(
452
+ "div",
453
+ {
454
+ style: {
455
+ height: 4,
456
+ width: `${Math.round(props.value * 100)}%`,
457
+ background: props.complete ? "var(--card-badge-positive-dot-color, #3ab667)" : "var(--card-focus-ring-color, #556bfc)"
458
+ }
459
+ }
460
+ )
461
+ }
462
+ );
463
+ }
464
+ function TranslationPanel(props) {
465
+ const { documentId, documentType, options } = props;
466
+ const client = useClient({ apiVersion: API_VERSION3 });
467
+ const toast = useToast();
468
+ const data = useTranslationData(documentId, documentType, options);
469
+ const { projectId: sanityProjectId, dataset } = client.config();
470
+ const storageKey = teamStorageKey(String(sanityProjectId), String(dataset));
471
+ const { projects, archived, stopped } = data;
472
+ const active = useMemo(() => activeProjects(projects, stopped), [projects, stopped]);
473
+ const hasProject = projects.length > 0;
474
+ const languages = options.translation.targetLanguages;
475
+ const [selected, setSelected] = useState(null);
476
+ useEffect(() => {
477
+ if (!data.loading && selected === null) setSelected(projectLanguages(active));
478
+ }, [data.loading, selected, active]);
479
+ const chosen = (selected ?? []).filter(
480
+ (id) => !stopped.includes(id) && languages.some((language) => language.id === id)
481
+ );
482
+ const [resetMode, setResetMode] = useState(false);
483
+ const newLanguages = resetMode ? chosen : chosen.filter((id) => !projectForLanguage(projects, id));
484
+ const needsNewProject = !hasProject || newLanguages.length > 0;
485
+ const allowedTypes = options.projectTypes?.length ? options.projectTypes : ["outsourced", "inHouse"];
486
+ const preferredType = projects[0]?.projectType && allowedTypes.includes(projects[0].projectType) ? projects[0].projectType : options.defaultProjectType && allowedTypes.includes(options.defaultProjectType) ? options.defaultProjectType : allowedTypes[0] ?? "outsourced";
487
+ const [projectType, setProjectType] = useState(null);
488
+ const typeForNewProject = projectType ?? preferredType;
489
+ const [team, setTeam] = useState([]);
490
+ const inHouse = needsNewProject && typeForNewProject === "inHouse";
491
+ const teamError = inHouse ? validateTeam(team) : null;
492
+ const [showMore, setShowMore] = useState(false);
493
+ const [submitting, setSubmitting] = useState(false);
494
+ const [submitError, setSubmitError] = useState(null);
495
+ const progress = useMemo(
496
+ () => languageProgress(data.translationState, active),
497
+ [data.translationState, active]
498
+ );
499
+ const pending = useMemo(
500
+ () => data.targets ? summarizePending({
501
+ units: data.units,
502
+ targets: data.targets,
503
+ state: data.translationState,
504
+ languages: chosen,
505
+ projects: resetMode ? [] : projects
506
+ }) : null,
507
+ // eslint-disable-next-line react-hooks/exhaustive-deps
508
+ [data.units, data.targets, data.translationState, chosen.join(","), projects, resetMode]
509
+ );
510
+ const perLanguage = useMemo(
511
+ () => data.targets ? summarizePending({
512
+ units: data.units,
513
+ targets: data.targets,
514
+ state: data.translationState,
515
+ languages: languages.map((language) => language.id).filter((id) => !stopped.includes(id)),
516
+ projects
517
+ }).byLanguage : {},
518
+ [data.units, data.targets, data.translationState, languages, projects]
519
+ );
520
+ const reviewedTotal = [...progress.values()].reduce((sum, entry) => sum + entry.reviewed, 0);
521
+ const previousReviewed = useRef(null);
522
+ useEffect(() => {
523
+ if (data.loading) return;
524
+ const previous = previousReviewed.current;
525
+ previousReviewed.current = reviewedTotal;
526
+ if (previous !== null && reviewedTotal > previous) {
527
+ const added = reviewedTotal - previous;
528
+ toast.push({
529
+ status: "success",
530
+ title: `${added} reviewed translation${added === 1 ? "" : "s"} added to the draft`
531
+ });
532
+ }
533
+ }, [reviewedTotal, data.loading, toast]);
534
+ const lastRequest = data.requests[0];
535
+ const running = isRunning(lastRequest);
536
+ const check = canTranslateDocument(options.translation, documentType, data.source);
537
+ const schema = useSchema();
538
+ const setupError = useMemo(
539
+ () => checkLocalizationSetup(options.translation, documentType, schema.getTypeNames()) ?? checkLanguageIds(options.translation, documentType, data.source),
540
+ [options.translation, documentType, schema, data.source]
541
+ );
542
+ const send = async (mode, reset = false) => {
543
+ setSubmitting(true);
544
+ setSubmitError(null);
545
+ const requestId = `textunited.request.${crypto.randomUUID()}`;
546
+ try {
547
+ await client.create({
548
+ _id: requestId,
549
+ _type: "textunited.translationRequest",
550
+ documentId: getBaseDocumentId(documentId),
551
+ languages: chosen,
552
+ mode,
553
+ status: "queued",
554
+ requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
555
+ ...reset ? { reset: true } : {},
556
+ // The project type and team matter only when the request creates a project.
557
+ ...needsNewProject ? { projectType: typeForNewProject, ...inHouse ? { team: teamForRequest(team) } : {} } : {}
558
+ });
559
+ if (inHouse) saveRoles(storageKey, team);
560
+ } catch (error) {
561
+ setSubmitError(error instanceof Error ? error.message : "Could not create the translation request");
562
+ setSubmitting(false);
563
+ return;
564
+ }
565
+ fetch(`${options.handlerUrl.replace(/\/+$/, "")}/jobs`, {
566
+ method: "POST",
567
+ headers: { "Content-Type": "application/json" },
568
+ body: JSON.stringify({ requestId })
569
+ }).catch(() => {
570
+ setSubmitError(
571
+ "The translation server could not be reached. The request is saved and can be processed later; check the handlerUrl setting and the server."
572
+ );
573
+ });
574
+ data.refresh();
575
+ setSubmitting(false);
576
+ setShowMore(false);
577
+ setResetMode(false);
578
+ };
579
+ const [stopTarget, setStopTarget] = useState(null);
580
+ const changeLanguage = async (action, language) => {
581
+ setSubmitting(true);
582
+ setSubmitError(null);
583
+ const requestId = `textunited.request.${crypto.randomUUID()}`;
584
+ try {
585
+ await client.create({
586
+ _id: requestId,
587
+ _type: "textunited.translationRequest",
588
+ documentId: getBaseDocumentId(documentId),
589
+ languages: [language],
590
+ mode: "changed",
591
+ action,
592
+ status: "queued",
593
+ requestedAt: (/* @__PURE__ */ new Date()).toISOString()
594
+ });
595
+ await fetch(`${options.handlerUrl.replace(/\/+$/, "")}/jobs`, {
596
+ method: "POST",
597
+ headers: { "Content-Type": "application/json" },
598
+ body: JSON.stringify({ requestId })
599
+ });
600
+ setSelected(
601
+ (current) => action === "stop" ? (current ?? []).filter((id) => id !== language) : [...current ?? [], language]
602
+ );
603
+ } catch (error) {
604
+ setSubmitError(error instanceof Error ? error.message : "Could not change the language");
605
+ }
606
+ data.refresh();
607
+ setSubmitting(false);
608
+ setStopTarget(null);
609
+ setShowMore(false);
610
+ };
611
+ const linkTo = (project) => typeof project.projectId === "number" && options.projectUrl ? options.projectUrl(project.projectId) : null;
612
+ const titleOf = (id) => languages.find((language) => language.id === id)?.title ?? id;
613
+ const listTitles = (ids) => ids.map(titleOf).join(", ");
614
+ const headerLink = projects.length === 1 && projects[0] ? linkTo(projects[0]) : null;
615
+ const sendLabel = () => {
616
+ if (chosen.length === 0) return "Choose a language";
617
+ if (teamError && team.length > 0) return teamError;
618
+ if (resetMode) return `Start a new project for ${chosen.length === 1 ? "1 language" : `${chosen.length} languages`}`;
619
+ if (!pending || pending.texts === 0) return "Nothing to send";
620
+ return `Send ${pending.texts === 1 ? "1 text" : `${pending.texts} texts`} to TextUnited`;
621
+ };
622
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", height: "fill", style: { overflow: "auto" }, children: [
623
+ /* @__PURE__ */ jsx(Card, { borderBottom: true, paddingX: 3, paddingY: 2, children: /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 2, children: [
624
+ /* @__PURE__ */ jsx(Text, { size: 1, children: /* @__PURE__ */ jsx(TextUnitedIcon, {}) }),
625
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: "TextUnited" }) }),
626
+ headerLink ? /* @__PURE__ */ jsx(
627
+ Button,
628
+ {
629
+ as: "a",
630
+ href: headerLink,
631
+ target: "_blank",
632
+ rel: "noreferrer",
633
+ mode: "bleed",
634
+ fontSize: 1,
635
+ padding: 2,
636
+ icon: LaunchIcon,
637
+ text: "Open in TextUnited"
638
+ }
639
+ ) : null,
640
+ props.onClose ? /* @__PURE__ */ jsx(Button, { mode: "bleed", fontSize: 1, padding: 2, icon: CloseIcon, "aria-label": "Close", onClick: props.onClose }) : null
641
+ ] }) }),
642
+ /* @__PURE__ */ jsxs(Stack, { space: 4, padding: 3, children: [
643
+ data.loading ? /* @__PURE__ */ jsx(Flex, { justify: "center", padding: 4, children: /* @__PURE__ */ jsx(Spinner, { muted: true }) }) : null,
644
+ setupError ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "critical", children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
645
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: "Translation is not set up for this document type" }),
646
+ /* @__PURE__ */ jsx(Text, { size: 1, children: setupError }),
647
+ /* @__PURE__ */ jsx(Text, { size: 1, children: /* @__PURE__ */ jsx("a", { href: INSTALL_GUIDE_URL, target: "_blank", rel: "noreferrer", children: "Read the installation guide" }) })
648
+ ] }) }) : null,
649
+ !data.loading && !setupError && !check.allowed ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "caution", children: /* @__PURE__ */ jsx(Text, { size: 1, children: check.reason }) }) : null,
650
+ !data.loading && !setupError && check.allowed ? /* @__PURE__ */ jsxs(Fragment, { children: [
651
+ data.source && data.units.length === 0 ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "caution", children: /* @__PURE__ */ jsxs(Text, { size: 1, children: [
652
+ "This document has no texts to translate. Fill in the ",
653
+ options.translation.sourceLanguage.title,
654
+ " ",
655
+ "version, and check that its fields use localized field types (fieldLevel) or are listed in the translation configuration (documentLevel)."
656
+ ] }) }) : null,
657
+ running ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "primary", children: /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 3, children: [
658
+ /* @__PURE__ */ jsx(Spinner, { muted: true }),
659
+ /* @__PURE__ */ jsx(Text, { size: 1, children: "Sending to TextUnited\u2026" })
660
+ ] }) }) : lastRequest?.status === "failed" ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "critical", children: /* @__PURE__ */ jsx(Text, { size: 1, children: describeRequest(lastRequest) }) }) : null,
661
+ data.error ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "critical", children: /* @__PURE__ */ jsx(Text, { size: 1, children: data.error }) }) : null,
662
+ !running && !resetMode && pending && chosen.length > 0 ? pending.texts > 0 ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "caution", children: /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
663
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: pending.texts === 1 ? "1 text needs translation" : `${pending.texts} texts need translation` }),
664
+ /* @__PURE__ */ jsx(Text, { size: 1, muted: true, children: describePending(pending) })
665
+ ] }) }) : /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "positive", children: /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 2, children: [
666
+ /* @__PURE__ */ jsx(Text, { size: 1, children: /* @__PURE__ */ jsx(CheckmarkCircleIcon, {}) }),
667
+ /* @__PURE__ */ jsx(Text, { size: 1, children: "Everything has been sent to TextUnited" })
668
+ ] }) }) : null,
669
+ /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
670
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: "Languages" }),
671
+ languages.map((language) => {
672
+ const entry = progress.get(language.id);
673
+ const inProject = Boolean(projectForLanguage(projects, language.id));
674
+ const toSend = perLanguage[language.id] ?? 0;
675
+ const done = entry && entry.total > 0 && entry.reviewed === entry.total;
676
+ if (stopped.includes(language.id)) {
677
+ return /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 2, children: [
678
+ /* @__PURE__ */ jsx(Checkbox, { checked: false, disabled: true }),
679
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { size: 1, muted: true, children: language.title }) }),
680
+ /* @__PURE__ */ jsx(Text, { size: 0, muted: true, children: "Stopped" }),
681
+ /* @__PURE__ */ jsx(
682
+ Button,
683
+ {
684
+ mode: "bleed",
685
+ fontSize: 0,
686
+ padding: 1,
687
+ text: "Resume",
688
+ disabled: running || submitting,
689
+ onClick: () => void changeLanguage("resume", language.id)
690
+ }
691
+ )
692
+ ] }, language.id);
693
+ }
694
+ return /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
695
+ /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 2, as: "label", children: [
696
+ /* @__PURE__ */ jsx(
697
+ Checkbox,
698
+ {
699
+ checked: chosen.includes(language.id),
700
+ disabled: running,
701
+ onChange: () => setSelected(
702
+ (current) => (current ?? []).includes(language.id) ? (current ?? []).filter((id) => id !== language.id) : [...current ?? [], language.id]
703
+ )
704
+ }
705
+ ),
706
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { size: 1, children: language.title }) }),
707
+ /* @__PURE__ */ jsx(Text, { size: 0, muted: true, children: hasProject && !inProject ? "Not ordered yet" : toSend > 0 && inProject ? `${toSend} to send` : done ? "Reviewed" : entry ? `${entry.reviewed} of ${entry.total} reviewed` : "" })
708
+ ] }),
709
+ entry && entry.total > 0 ? /* @__PURE__ */ jsx(Box, { paddingLeft: 4, children: /* @__PURE__ */ jsx(ProgressBar, { value: entry.reviewed / entry.total, complete: Boolean(done) }) }) : null
710
+ ] }, language.id);
711
+ })
712
+ ] }),
713
+ hasProject && !resetMode && newLanguages.length > 0 ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "primary", children: /* @__PURE__ */ jsxs(Text, { size: 1, children: [
714
+ listTitles(newLanguages),
715
+ " ",
716
+ newLanguages.length === 1 ? "is" : "are",
717
+ " ordered as a new TextUnited project. The current ",
718
+ projects.length === 1 ? "project stays" : "projects stay",
719
+ " as",
720
+ " ",
721
+ projects.length === 1 ? "it is" : "they are",
722
+ "."
723
+ ] }) }) : null,
724
+ resetMode ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "caution", children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
725
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: "Start a new TextUnited project" }),
726
+ /* @__PURE__ */ jsxs(Text, { size: 1, children: [
727
+ "Every text of this document is sent again, for the chosen languages, to a new project. The current ",
728
+ projects.length === 1 ? "project stays" : "projects stay",
729
+ " in TextUnited as ",
730
+ projects.length === 1 ? "it is" : "they are",
731
+ ", but this document no longer follows ",
732
+ projects.length === 1 ? "it" : "them",
733
+ ". Translations already in Sanity are kept."
734
+ ] }),
735
+ /* @__PURE__ */ jsx(Button, { mode: "bleed", fontSize: 1, text: "Cancel", onClick: () => setResetMode(false) })
736
+ ] }) }) : null,
737
+ needsNewProject && allowedTypes.length > 1 ? /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
738
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: hasProject ? "Who translates the new project" : "Who translates" }),
739
+ PROJECT_TYPE_OPTIONS.filter((option) => allowedTypes.includes(option.value)).map((option) => /* @__PURE__ */ jsxs(Flex, { gap: 2, as: "label", align: "flex-start", children: [
740
+ /* @__PURE__ */ jsx(
741
+ Radio,
742
+ {
743
+ checked: typeForNewProject === option.value,
744
+ disabled: running,
745
+ name: `textunited-project-type-${documentId}`,
746
+ value: option.value,
747
+ onChange: () => setProjectType(option.value)
748
+ }
749
+ ),
750
+ /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
751
+ /* @__PURE__ */ jsx(Text, { size: 1, children: option.title }),
752
+ /* @__PURE__ */ jsx(Text, { size: 0, muted: true, children: option.description })
753
+ ] })
754
+ ] }, option.value)),
755
+ inHouse ? /* @__PURE__ */ jsx(
756
+ TeamPicker,
757
+ {
758
+ handlerUrl: options.handlerUrl,
759
+ team,
760
+ onChange: setTeam,
761
+ disabled: running,
762
+ savedRoles: readSavedRoles(storageKey)
763
+ }
764
+ ) : null
765
+ ] }) : null,
766
+ submitError ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "critical", children: /* @__PURE__ */ jsx(Text, { size: 1, children: submitError }) }) : null,
767
+ stopTarget ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, tone: "caution", children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
768
+ /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
769
+ "Stop translating ",
770
+ titleOf(stopTarget),
771
+ "?"
772
+ ] }),
773
+ /* @__PURE__ */ jsxs(Text, { size: 1, children: [
774
+ "Changes of this document are no longer sent for ",
775
+ titleOf(stopTarget),
776
+ ", and translations from TextUnited are no longer written or restored. The language stays in its TextUnited project, where translators may still work on it; ask your project manager if it should be cancelled. You can resume it at any time."
777
+ ] }),
778
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, children: [
779
+ /* @__PURE__ */ jsx(
780
+ Button,
781
+ {
782
+ tone: "caution",
783
+ text: `Stop ${titleOf(stopTarget)}`,
784
+ loading: submitting,
785
+ onClick: () => void changeLanguage("stop", stopTarget)
786
+ }
787
+ ),
788
+ /* @__PURE__ */ jsx(Button, { mode: "bleed", text: "Cancel", onClick: () => setStopTarget(null) })
789
+ ] })
790
+ ] }) }) : null,
791
+ /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
792
+ /* @__PURE__ */ jsx(
793
+ Button,
794
+ {
795
+ tone: resetMode ? "caution" : "primary",
796
+ icon: TranslateIcon,
797
+ loading: submitting,
798
+ disabled: running || chosen.length === 0 || teamError !== null || !resetMode && (!pending || pending.texts === 0),
799
+ text: sendLabel(),
800
+ onClick: () => void send("changed", resetMode)
801
+ }
802
+ ),
803
+ hasProject && !resetMode ? /* @__PURE__ */ jsx(
804
+ Button,
805
+ {
806
+ mode: "bleed",
807
+ fontSize: 1,
808
+ text: showMore ? "Fewer options" : "More options",
809
+ onClick: () => setShowMore((value) => !value)
810
+ }
811
+ ) : null,
812
+ showMore && !resetMode ? /* @__PURE__ */ jsx(Card, { padding: 3, radius: 2, border: true, children: /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
813
+ /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
814
+ /* @__PURE__ */ jsx(Text, { size: 1, muted: true, children: "Sends every text again for the chosen languages and replaces all their translations, including ones edited by hand in Sanity." }),
815
+ /* @__PURE__ */ jsx(
816
+ Button,
817
+ {
818
+ mode: "ghost",
819
+ tone: "critical",
820
+ text: "Retranslate everything",
821
+ disabled: running || chosen.length === 0 || newLanguages.length > 0,
822
+ onClick: () => void send("all")
823
+ }
824
+ )
825
+ ] }),
826
+ projectLanguages(active).length > 0 ? /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
827
+ /* @__PURE__ */ jsx(Text, { size: 1, muted: true, children: "Stop translating a language on this document: nothing is sent, written or restored for it any more. Its texts in Sanity stay until you remove them." }),
828
+ /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", children: projectLanguages(active).map((id) => /* @__PURE__ */ jsx(
829
+ Button,
830
+ {
831
+ mode: "ghost",
832
+ fontSize: 1,
833
+ text: `Stop ${titleOf(id)}`,
834
+ disabled: running,
835
+ onClick: () => {
836
+ setStopTarget(id);
837
+ setShowMore(false);
838
+ }
839
+ },
840
+ id
841
+ )) })
842
+ ] }) : null,
843
+ /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
844
+ /* @__PURE__ */ jsx(Text, { size: 1, muted: true, children: "Starts over with a new TextUnited project, for example to change who translates. Every text is sent again." }),
845
+ /* @__PURE__ */ jsx(
846
+ Button,
847
+ {
848
+ mode: "ghost",
849
+ text: "Start a new TextUnited project",
850
+ disabled: running,
851
+ onClick: () => {
852
+ setResetMode(true);
853
+ setShowMore(false);
854
+ }
855
+ }
856
+ )
857
+ ] })
858
+ ] }) }) : null
859
+ ] }),
860
+ /* @__PURE__ */ jsx(Text, { size: 0, muted: true, children: "A machine translation is added to the draft right away. Reviewed translations replace it as translators confirm them in TextUnited. Publish the document to show them on the site." }),
861
+ projects.length > 1 || archived.length > 0 ? /* @__PURE__ */ jsx(Card, { borderTop: true, paddingTop: 3, children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
862
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: "TextUnited projects" }),
863
+ [...projects.map((project) => ({ project, old: false })), ...archived.map((project) => ({ project, old: true }))].map(
864
+ ({ project, old }) => {
865
+ const link = linkTo(project);
866
+ return /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "center", children: [
867
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsxs(Text, { size: 0, muted: old, children: [
868
+ listTitles(project.languages),
869
+ project.projectType ? ` \xB7 ${projectTypeLabel(project.projectType)}` : "",
870
+ old ? " \xB7 replaced" : ""
871
+ ] }) }),
872
+ link ? /* @__PURE__ */ jsx(Text, { size: 0, children: /* @__PURE__ */ jsx("a", { href: link, target: "_blank", rel: "noreferrer", children: "Open" }) }) : null
873
+ ] }, project.customId);
874
+ }
875
+ )
876
+ ] }) }) : null,
877
+ data.requests.length > 0 ? /* @__PURE__ */ jsx(Card, { borderTop: true, paddingTop: 3, children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
878
+ /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: "History" }),
879
+ data.requests.slice(0, 3).map((request) => /* @__PURE__ */ jsxs(Flex, { gap: 2, children: [
880
+ /* @__PURE__ */ jsx(Box, { style: { minWidth: 44 }, children: /* @__PURE__ */ jsx(Text, { size: 0, muted: true, children: formatTime(request._createdAt) }) }),
881
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { size: 0, muted: true, children: describeRequest(request) }) })
882
+ ] }, request._id))
883
+ ] }) }) : null
884
+ ] }) : null
885
+ ] })
886
+ ] });
887
+ }
888
+ var INSPECTOR_NAME = "textunited-translation";
889
+ var API_VERSION4 = "2025-02-19";
890
+ function useStateSummary(documentId) {
891
+ const client = useClient({ apiVersion: API_VERSION4 });
892
+ const stateId = `textunited.state.${getBaseDocumentId(documentId)}`;
893
+ const [state, setState] = useState(null);
894
+ useEffect(() => {
895
+ let active = true;
896
+ const load = () => client.fetch("*[_id == $id][0]{projectCustomId, projectLanguages, projectType, projectId, projectsJson, stateJson}", { id: stateId }, { perspective: "raw" }).then((value) => active && setState(value)).catch(() => void 0);
897
+ void load();
898
+ const subscription = client.listen("*[_id == $id]", { id: stateId }, { visibility: "query", includeResult: false }).subscribe({ next: () => void load(), error: () => void 0 });
899
+ return () => {
900
+ active = false;
901
+ subscription.unsubscribe();
902
+ };
903
+ }, [client, stateId]);
904
+ return state;
905
+ }
906
+ function createTranslationInspector(options) {
907
+ return defineDocumentInspector({
908
+ name: INSPECTOR_NAME,
909
+ useMenuItem: () => ({
910
+ icon: TextUnitedIcon,
911
+ title: "TextUnited",
912
+ showAsAction: true
913
+ }),
914
+ component: (props) => /* @__PURE__ */ jsx(
915
+ TranslationPanel,
916
+ {
917
+ documentId: props.documentId,
918
+ documentType: props.documentType,
919
+ options,
920
+ onClose: props.onClose
921
+ }
922
+ )
923
+ });
924
+ }
925
+ function createTranslationBadge() {
926
+ const TranslationBadge = (props) => {
927
+ const state = useStateSummary(props.id);
928
+ const badge = useMemo(() => {
929
+ const { state: translationState, projects, stopped } = readTranslationState(state);
930
+ const active = activeProjects(projects, stopped);
931
+ if (active.length === 0) return null;
932
+ return badgeLabel(languageProgress(translationState, active), projectLanguages(active));
933
+ }, [state]);
934
+ if (!badge) return null;
935
+ return {
936
+ label: badge.label,
937
+ title: "Texts reviewed by translators in TextUnited, per language",
938
+ color: badge.complete ? "success" : "warning"
939
+ };
940
+ };
941
+ return TranslationBadge;
942
+ }
943
+ function useOptionalDocumentPane() {
944
+ try {
945
+ return useDocumentPane();
946
+ } catch {
947
+ return null;
948
+ }
949
+ }
950
+ function createTranslateAction(options) {
951
+ const TranslateAction = (props) => {
952
+ const [open, setOpen] = useState(false);
953
+ const pane = useOptionalDocumentPane();
954
+ const document = props.draft ?? props.published;
955
+ const check = canTranslateDocument(options.translation, props.type, document);
956
+ return {
957
+ label: "Translate with TextUnited",
958
+ icon: TextUnitedIcon,
959
+ disabled: !check.allowed,
960
+ title: check.reason,
961
+ onHandle: () => {
962
+ if (pane) pane.openInspector(INSPECTOR_NAME);
963
+ else setOpen(true);
964
+ props.onComplete();
965
+ },
966
+ dialog: open && !pane ? {
967
+ type: "dialog",
968
+ header: "Translate with TextUnited",
969
+ width: "small",
970
+ onClose: () => setOpen(false),
971
+ content: /* @__PURE__ */ jsx(TranslationPanel, { documentId: props.id, documentType: props.type, options })
972
+ } : null
973
+ };
974
+ };
975
+ TranslateAction.displayName = "TextUnitedTranslateAction";
976
+ return TranslateAction;
977
+ }
978
+
979
+ // src/studio/index.ts
980
+ var textUnitedTranslations = definePlugin((options) => {
981
+ if (!options?.handlerUrl) {
982
+ throw new Error("textUnitedTranslations: the handlerUrl option is required");
983
+ }
984
+ if (!options.translation?.targetLanguages?.length) {
985
+ throw new Error("textUnitedTranslations: configure at least one target language");
986
+ }
987
+ const types = new Set(options.translation.documentTypes.map((entry) => entry.type));
988
+ const TranslateAction = createTranslateAction(options);
989
+ const TranslationBadge = createTranslationBadge();
990
+ const translationInspector = createTranslationInspector(options);
991
+ return {
992
+ name: "@textunited/sanity-plugin",
993
+ document: {
994
+ actions: (previous, context) => types.has(context.schemaType) ? [...previous, TranslateAction] : previous,
995
+ badges: (previous, context) => types.has(context.schemaType) ? [...previous, TranslationBadge] : previous,
996
+ inspectors: (previous, context) => types.has(context.documentType) ? [...previous, translationInspector] : previous
997
+ }
998
+ };
999
+ });
1000
+
1001
+ export { textUnitedTranslations };
1002
+ //# sourceMappingURL=index.js.map
1003
+ //# sourceMappingURL=index.js.map