@sanity/document-internationalization 4.1.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +44 -36
  3. package/dist/_chunks-es/{resources.mjs → resources.js} +1 -1
  4. package/dist/{_chunks-cjs → _chunks-es}/resources.js.map +1 -1
  5. package/dist/index.d.ts +112 -88
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +1075 -1337
  8. package/dist/index.js.map +1 -1
  9. package/package.json +35 -69
  10. package/dist/_chunks-cjs/resources.js +0 -8
  11. package/dist/_chunks-es/resources.mjs.map +0 -1
  12. package/dist/_legacy/resources.esm.js +0 -9
  13. package/dist/_legacy/resources.esm.js.map +0 -1
  14. package/dist/index.d.mts +0 -108
  15. package/dist/index.esm.js +0 -1625
  16. package/dist/index.esm.js.map +0 -1
  17. package/dist/index.mjs +0 -1625
  18. package/dist/index.mjs.map +0 -1
  19. package/sanity.json +0 -8
  20. package/src/actions/DeleteMetadataAction.tsx +0 -93
  21. package/src/actions/DeleteTranslationAction.tsx +0 -102
  22. package/src/actions/DuplicateWithTranslationsAction.tsx +0 -251
  23. package/src/badges/index.tsx +0 -27
  24. package/src/components/BulkPublish/DocumentCheck.tsx +0 -90
  25. package/src/components/BulkPublish/Info.tsx +0 -28
  26. package/src/components/BulkPublish/InfoIcon.tsx +0 -34
  27. package/src/components/BulkPublish/index.tsx +0 -181
  28. package/src/components/ConstrainedBox.tsx +0 -6
  29. package/src/components/DeleteTranslationDialog/DocumentPreview.tsx +0 -19
  30. package/src/components/DeleteTranslationDialog/index.tsx +0 -111
  31. package/src/components/DeleteTranslationDialog/separateReferences.ts +0 -23
  32. package/src/components/DeleteTranslationFooter.tsx +0 -28
  33. package/src/components/DocumentInternationalizationContext.tsx +0 -47
  34. package/src/components/DocumentInternationalizationMenu.tsx +0 -235
  35. package/src/components/LanguageManage.tsx +0 -108
  36. package/src/components/LanguageOption.tsx +0 -259
  37. package/src/components/LanguagePatch.tsx +0 -67
  38. package/src/components/OptimisticallyStrengthen/ReferencePatcher.tsx +0 -50
  39. package/src/components/OptimisticallyStrengthen/index.tsx +0 -34
  40. package/src/components/Warning.tsx +0 -18
  41. package/src/constants.ts +0 -16
  42. package/src/hooks/useLanguageMetadata.tsx +0 -26
  43. package/src/hooks/useOpenInNewPane.tsx +0 -33
  44. package/src/i18n/index.ts +0 -21
  45. package/src/i18n/resources.ts +0 -7
  46. package/src/index.ts +0 -6
  47. package/src/plugin.tsx +0 -239
  48. package/src/schema/translation/metadata.ts +0 -68
  49. package/src/types.ts +0 -97
  50. package/src/utils/createReference.ts +0 -20
  51. package/src/utils/excludePaths.ts +0 -123
  52. package/v2-incompatible.js +0 -11
package/dist/index.js CHANGED
@@ -1,9 +1,27 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var jsxRuntime = require("react/jsx-runtime"), icons = require("@sanity/icons"), ui = require("@sanity/ui"), react = require("react"), sanity = require("sanity"), sanityPluginUtils = require("sanity-plugin-utils"), uuid = require("@sanity/uuid"), router = require("sanity/router"), structure = require("sanity/structure"), mutator = require("@sanity/mutator"), styledComponents = require("styled-components"), sanityPluginInternationalizedArray = require("sanity-plugin-internationalized-array");
1
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
+ import { c } from "react/compiler-runtime";
3
+ import { TrashIcon, CopyIcon, CogIcon, SplitVerticalIcon, CheckmarkIcon, AddIcon, EditIcon, TranslateIcon, InfoOutlineIcon } from "@sanity/icons";
4
+ import { Flex, Spinner, Card, Text, Stack, Grid, Button, useToast, Tooltip, Box, Badge, useClickOutsideEvent, TextInput, Popover, Inline, Dialog } from "@sanity/ui";
5
+ import { useEffect, createContext, use, useContext, useState, useRef } from "react";
6
+ import { useSchema, Preview, useClient, useWorkspace, defineLocaleResourceBundle, useDocumentStore, useDocumentOperation, useDocumentPairPermissions, DEFAULT_STUDIO_CLIENT_OPTIONS, useTranslation, useCurrentUser, InsufficientPermissionsMessage, isDocumentSchemaType, pathToString, useEditState, useValidationStatus, TextWithTone, PatchEvent, unset, defineType, defineField, definePlugin, isSanityDocument } from "sanity";
7
+ import { LANGUAGE_FIELD_NAME, internationalizedArray } from "sanity-plugin-internationalized-array";
8
+ import { Feedback, useListeningQuery } from "sanity-plugin-utils";
9
+ import { uuid } from "@sanity/uuid";
10
+ import { firstValueFrom, filter } from "rxjs";
11
+ import { useRouter } from "sanity/router";
12
+ import { structureLocaleNamespace, usePaneRouter, useDocumentPane } from "sanity/structure";
13
+ import { Mutation, extractWithPath } from "@sanity/mutator";
4
14
  function DocumentPreview(props) {
5
- const schemaType = sanity.useSchema().get(props.type);
6
- return schemaType ? /* @__PURE__ */ jsxRuntime.jsx(sanity.Preview, { value: props.value, schemaType }) : /* @__PURE__ */ jsxRuntime.jsx(sanityPluginUtils.Feedback, { tone: "critical", title: "Schema type not found" });
15
+ const $ = c(7), schema = useSchema();
16
+ let t0;
17
+ $[0] !== props.type || $[1] !== schema ? (t0 = schema.get(props.type), $[0] = props.type, $[1] = schema, $[2] = t0) : t0 = $[2];
18
+ const schemaType = t0;
19
+ if (!schemaType) {
20
+ let t12;
21
+ return $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t12 = /* @__PURE__ */ jsx(Feedback, { tone: "critical", title: "Schema type not found" }), $[3] = t12) : t12 = $[3], t12;
22
+ }
23
+ let t1;
24
+ return $[4] !== props.value || $[5] !== schemaType ? (t1 = /* @__PURE__ */ jsx(Preview, { value: props.value, schemaType }), $[4] = props.value, $[5] = schemaType, $[6] = t1) : t1 = $[6], t1;
7
25
  }
8
26
  const METADATA_SCHEMA_NAME = "translation.metadata", TRANSLATIONS_ARRAY_NAME = "translations", API_VERSION = "2025-02-19", DEFAULT_CONFIG = {
9
27
  supportedLanguages: [],
@@ -20,156 +38,186 @@ function separateReferences(data = []) {
20
38
  const translations = [], otherReferences = [];
21
39
  return data && data.length > 0 && data.forEach((doc) => {
22
40
  doc._type === METADATA_SCHEMA_NAME ? translations.push(doc) : otherReferences.push(doc);
23
- }), { translations, otherReferences };
41
+ }), {
42
+ translations,
43
+ otherReferences
44
+ };
24
45
  }
25
46
  function DeleteTranslationDialog(props) {
26
- const { doc, documentId, setTranslations } = props, { data, loading } = sanityPluginUtils.useListeningQuery(
27
- "*[references($id)]{_id, _type}",
28
- { params: { id: documentId }, initialValue: [] }
29
- ), { translations, otherReferences } = react.useMemo(
30
- () => separateReferences(data),
31
- [data]
32
- );
33
- return react.useEffect(() => {
47
+ const $ = c(33), {
48
+ doc,
49
+ documentId,
50
+ setTranslations
51
+ } = props;
52
+ let t0;
53
+ $[0] !== documentId ? (t0 = {
54
+ id: documentId
55
+ }, $[0] = documentId, $[1] = t0) : t0 = $[1];
56
+ let t1;
57
+ $[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = [], $[2] = t1) : t1 = $[2];
58
+ let t2;
59
+ $[3] !== t0 ? (t2 = {
60
+ params: t0,
61
+ initialValue: t1
62
+ }, $[3] = t0, $[4] = t2) : t2 = $[4];
63
+ const {
64
+ data,
65
+ loading
66
+ } = useListeningQuery("*[references($id)]{_id, _type, translations}", t2), t3 = data;
67
+ let t4;
68
+ $[5] !== t3 ? (t4 = separateReferences(t3), $[5] = t3, $[6] = t4) : t4 = $[6];
69
+ const {
70
+ translations,
71
+ otherReferences
72
+ } = t4;
73
+ let t5, t6;
74
+ if ($[7] !== setTranslations || $[8] !== translations ? (t5 = () => {
34
75
  setTranslations(translations);
35
- }, [setTranslations, translations]), loading ? /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { padding: 4, align: "center", justify: "center", children: /* @__PURE__ */ jsxRuntime.jsx(ui.Spinner, {}) }) : /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 4, children: [
36
- translations && translations.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: "This document is a language-specific version which other translations depend on." }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: "This document does not have connected translations." }),
37
- /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { border: !0, padding: 3, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 4, children: [
38
- /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, weight: "semibold", children: translations && translations.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: "Before this document can be deleted" }) : /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: "This document can now be deleted" }) }),
39
- /* @__PURE__ */ jsxRuntime.jsx(DocumentPreview, { value: doc, type: doc._type }),
40
- translations && translations.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
41
- /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { borderTop: !0 }),
42
- /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, weight: "semibold", children: [
43
- "The reference in",
44
- " ",
45
- translations.length === 1 ? "this translations document" : "these translations documents",
46
- " ",
47
- "must be removed"
48
- ] }),
49
- translations.map((translation) => /* @__PURE__ */ jsxRuntime.jsx(
50
- DocumentPreview,
51
- {
52
- value: translation,
53
- type: translation._type
54
- },
55
- translation._id
56
- ))
57
- ] }) : null,
58
- otherReferences && otherReferences.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
59
- /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { borderTop: !0 }),
60
- /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, weight: "semibold", children: [
61
- otherReferences.length === 1 ? "There is an additional reference" : "There are additional references",
62
- " ",
63
- "to this document"
64
- ] }),
65
- otherReferences.map((reference) => /* @__PURE__ */ jsxRuntime.jsx(
66
- DocumentPreview,
67
- {
68
- value: reference,
69
- type: reference._type
70
- },
71
- reference._id
72
- ))
73
- ] }) : null
74
- ] }) }),
75
- otherReferences.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: "This document has no other references." }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: "You may not be able to delete this document because other documents refer to it." })
76
- ] });
76
+ }, t6 = [setTranslations, translations], $[7] = setTranslations, $[8] = translations, $[9] = t5, $[10] = t6) : (t5 = $[9], t6 = $[10]), useEffect(t5, t6), loading) {
77
+ let t72;
78
+ return $[11] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t72 = /* @__PURE__ */ jsx(Flex, { padding: 4, align: "center", justify: "center", children: /* @__PURE__ */ jsx(Spinner, {}) }), $[11] = t72) : t72 = $[11], t72;
79
+ }
80
+ let t7;
81
+ $[12] !== translations ? (t7 = translations && translations.length > 0 ? /* @__PURE__ */ jsx(Text, { children: "This document is a language-specific version which other translations depend on." }) : /* @__PURE__ */ jsx(Text, { children: "This document does not have connected translations." }), $[12] = translations, $[13] = t7) : t7 = $[13];
82
+ let t8;
83
+ $[14] !== translations ? (t8 = /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: translations && translations.length > 0 ? /* @__PURE__ */ jsx(Fragment, { children: "Before this document can be deleted" }) : /* @__PURE__ */ jsx(Fragment, { children: "This document can now be deleted" }) }), $[14] = translations, $[15] = t8) : t8 = $[15];
84
+ let t9;
85
+ $[16] !== doc ? (t9 = /* @__PURE__ */ jsx(DocumentPreview, { value: doc, type: doc._type }), $[16] = doc, $[17] = t9) : t9 = $[17];
86
+ let t10;
87
+ $[18] !== translations ? (t10 = translations && translations.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
88
+ /* @__PURE__ */ jsx(Card, { borderTop: !0 }),
89
+ /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
90
+ "The reference in",
91
+ " ",
92
+ translations.length === 1 ? "this translations document" : "these translations documents",
93
+ " ",
94
+ "must be removed"
95
+ ] }),
96
+ translations.map(_temp$5)
97
+ ] }) : null, $[18] = translations, $[19] = t10) : t10 = $[19];
98
+ let t11;
99
+ $[20] !== otherReferences ? (t11 = otherReferences && otherReferences.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
100
+ /* @__PURE__ */ jsx(Card, { borderTop: !0 }),
101
+ /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
102
+ otherReferences.length === 1 ? "There is an additional reference" : "There are additional references",
103
+ " ",
104
+ "to this document"
105
+ ] }),
106
+ otherReferences.map(_temp2$3)
107
+ ] }) : null, $[20] = otherReferences, $[21] = t11) : t11 = $[21];
108
+ let t12;
109
+ $[22] !== t10 || $[23] !== t11 || $[24] !== t8 || $[25] !== t9 ? (t12 = /* @__PURE__ */ jsx(Card, { border: !0, padding: 3, children: /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
110
+ t8,
111
+ t9,
112
+ t10,
113
+ t11
114
+ ] }) }), $[22] = t10, $[23] = t11, $[24] = t8, $[25] = t9, $[26] = t12) : t12 = $[26];
115
+ let t13;
116
+ $[27] !== otherReferences.length ? (t13 = otherReferences.length === 0 ? /* @__PURE__ */ jsx(Text, { children: "This document has no other references." }) : /* @__PURE__ */ jsx(Text, { children: "You may not be able to delete this document because other documents refer to it." }), $[27] = otherReferences.length, $[28] = t13) : t13 = $[28];
117
+ let t14;
118
+ return $[29] !== t12 || $[30] !== t13 || $[31] !== t7 ? (t14 = /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
119
+ t7,
120
+ t12,
121
+ t13
122
+ ] }), $[29] = t12, $[30] = t13, $[31] = t7, $[32] = t14) : t14 = $[32], t14;
77
123
  }
78
- function DeleteTranslationFooter(props) {
79
- const { translations, onClose, onProceed } = props;
80
- return /* @__PURE__ */ jsxRuntime.jsxs(ui.Grid, { columns: 2, gap: 2, children: [
81
- /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { text: "Cancel", onClick: onClose, mode: "ghost" }),
82
- /* @__PURE__ */ jsxRuntime.jsx(
83
- ui.Button,
84
- {
85
- text: translations && translations.length > 0 ? "Unset translation reference" : "Delete document",
86
- onClick: onProceed,
87
- tone: "critical"
88
- }
89
- )
90
- ] });
124
+ function _temp2$3(reference) {
125
+ return /* @__PURE__ */ jsx(DocumentPreview, { value: reference, type: reference._type }, reference._id);
91
126
  }
92
- const isPromise = (promise) => typeof promise == "object" && typeof promise.then == "function", globalCache = [];
93
- function shallowEqualArrays(arrA, arrB, equal = (a, b) => a === b) {
94
- if (arrA === arrB)
95
- return !0;
96
- if (!arrA || !arrB)
97
- return !1;
98
- const len = arrA.length;
99
- if (arrB.length !== len)
100
- return !1;
101
- for (let i = 0; i < len; i++)
102
- if (!equal(arrA[i], arrB[i]))
103
- return !1;
104
- return !0;
127
+ function _temp$5(translation) {
128
+ return /* @__PURE__ */ jsx(DocumentPreview, { value: translation, type: translation._type }, translation._id);
105
129
  }
106
- function query$1(fn, keys = null, preload = !1, config = {}) {
107
- keys === null && (keys = [fn]);
108
- for (const entry2 of globalCache)
109
- if (shallowEqualArrays(keys, entry2.keys, entry2.equal)) {
110
- if (preload)
111
- return;
112
- if (Object.prototype.hasOwnProperty.call(entry2, "error"))
113
- throw entry2.error;
114
- if (Object.prototype.hasOwnProperty.call(entry2, "response"))
115
- return config.lifespan && config.lifespan > 0 && (entry2.timeout && clearTimeout(entry2.timeout), entry2.timeout = setTimeout(entry2.remove, config.lifespan)), entry2.response;
116
- if (!preload)
117
- throw entry2.promise;
118
- }
119
- const entry = {
120
- keys,
121
- equal: config.equal,
122
- remove: () => {
123
- const index = globalCache.indexOf(entry);
124
- index !== -1 && globalCache.splice(index, 1);
125
- },
126
- promise: (
127
- // Execute the promise
128
- (isPromise(fn) ? fn : fn(...keys)).then((response) => {
129
- entry.response = response, config.lifespan && config.lifespan > 0 && (entry.timeout = setTimeout(entry.remove, config.lifespan));
130
- }).catch((error) => entry.error = error)
131
- )
132
- };
133
- if (globalCache.push(entry), !preload)
134
- throw entry.promise;
130
+ function DeleteTranslationFooter(props) {
131
+ const $ = c(8), {
132
+ translations,
133
+ onClose,
134
+ onProceed
135
+ } = props;
136
+ let t0;
137
+ $[0] !== onClose ? (t0 = /* @__PURE__ */ jsx(Button, { text: "Cancel", onClick: onClose, mode: "ghost" }), $[0] = onClose, $[1] = t0) : t0 = $[1];
138
+ const t1 = translations && translations.length > 0 ? "Unset translation reference" : "Delete document";
139
+ let t2;
140
+ $[2] !== onProceed || $[3] !== t1 ? (t2 = /* @__PURE__ */ jsx(Button, { text: t1, onClick: onProceed, tone: "critical" }), $[2] = onProceed, $[3] = t1, $[4] = t2) : t2 = $[4];
141
+ let t3;
142
+ return $[5] !== t0 || $[6] !== t2 ? (t3 = /* @__PURE__ */ jsxs(Grid, { columns: 2, gap: 2, children: [
143
+ t0,
144
+ t2
145
+ ] }), $[5] = t0, $[6] = t2, $[7] = t3) : t3 = $[7], t3;
135
146
  }
136
- const suspend = (fn, keys, config) => query$1(fn, keys, !1, config);
137
- var __defProp$3 = Object.defineProperty, __defProps$2 = Object.defineProperties, __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$3 = Object.getOwnPropertySymbols, __hasOwnProp$3 = Object.prototype.hasOwnProperty, __propIsEnum$3 = Object.prototype.propertyIsEnumerable, __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$3 = (a, b) => {
138
- for (var prop in b || (b = {}))
139
- __hasOwnProp$3.call(b, prop) && __defNormalProp$3(a, prop, b[prop]);
140
- if (__getOwnPropSymbols$3)
141
- for (var prop of __getOwnPropSymbols$3(b))
142
- __propIsEnum$3.call(b, prop) && __defNormalProp$3(a, prop, b[prop]);
143
- return a;
144
- }, __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
145
- const DocumentInternationalizationContext = react.createContext(DEFAULT_CONFIG);
147
+ const DocumentInternationalizationContext = createContext(DEFAULT_CONFIG);
146
148
  function useDocumentInternationalizationContext() {
147
- return react.useContext(DocumentInternationalizationContext);
149
+ return useContext(DocumentInternationalizationContext);
150
+ }
151
+ const promiseCache = /* @__PURE__ */ new Map();
152
+ function createCacheKey(workspaceId) {
153
+ return `languages-${workspaceId}`;
154
+ }
155
+ function createOrGetPromise(fn, cacheKey) {
156
+ const cached = promiseCache.get(cacheKey);
157
+ if (cached)
158
+ return cached;
159
+ const promise = fn();
160
+ return promiseCache.set(cacheKey, promise), promise;
148
161
  }
149
162
  function DocumentInternationalizationProvider(props) {
150
- const { pluginConfig } = props, client = sanity.useClient({ apiVersion: pluginConfig.apiVersion }), workspace = sanity.useWorkspace(), supportedLanguages = Array.isArray(pluginConfig.supportedLanguages) ? pluginConfig.supportedLanguages : (
151
- // eslint-disable-next-line require-await
152
- suspend(async () => typeof pluginConfig.supportedLanguages == "function" ? pluginConfig.supportedLanguages(client) : pluginConfig.supportedLanguages, [workspace])
153
- );
154
- return /* @__PURE__ */ jsxRuntime.jsx(
155
- DocumentInternationalizationContext.Provider,
156
- {
157
- value: __spreadProps$2(__spreadValues$3({}, pluginConfig), { supportedLanguages }),
158
- children: props.renderDefault(props)
163
+ const $ = c(18), {
164
+ pluginConfig
165
+ } = props;
166
+ let t0;
167
+ $[0] !== pluginConfig.apiVersion ? (t0 = {
168
+ apiVersion: pluginConfig.apiVersion
169
+ }, $[0] = pluginConfig.apiVersion, $[1] = t0) : t0 = $[1];
170
+ const client = useClient(t0), workspaceId = useWorkspace().name ?? "";
171
+ let t1;
172
+ $[2] !== workspaceId ? (t1 = createCacheKey(workspaceId), $[2] = workspaceId, $[3] = t1) : t1 = $[3];
173
+ const cacheKey = t1;
174
+ let t2;
175
+ bb0: {
176
+ if (Array.isArray(pluginConfig.supportedLanguages)) {
177
+ t2 = null;
178
+ break bb0;
159
179
  }
160
- );
180
+ let t32;
181
+ $[4] !== client || $[5] !== pluginConfig ? (t32 = async () => typeof pluginConfig.supportedLanguages == "function" ? pluginConfig.supportedLanguages(client) : pluginConfig.supportedLanguages, $[4] = client, $[5] = pluginConfig, $[6] = t32) : t32 = $[6];
182
+ let t42;
183
+ $[7] !== cacheKey || $[8] !== t32 ? (t42 = createOrGetPromise(t32, cacheKey), $[7] = cacheKey, $[8] = t32, $[9] = t42) : t42 = $[9], t2 = t42;
184
+ }
185
+ const languagesPromise = t2, supportedLanguages = languagesPromise ? use(languagesPromise) : pluginConfig.supportedLanguages;
186
+ let t3;
187
+ $[10] !== pluginConfig || $[11] !== supportedLanguages ? (t3 = {
188
+ ...pluginConfig,
189
+ supportedLanguages
190
+ }, $[10] = pluginConfig, $[11] = supportedLanguages, $[12] = t3) : t3 = $[12];
191
+ let t4;
192
+ $[13] !== props ? (t4 = props.renderDefault(props), $[13] = props, $[14] = t4) : t4 = $[14];
193
+ let t5;
194
+ return $[15] !== t3 || $[16] !== t4 ? (t5 = /* @__PURE__ */ jsx(DocumentInternationalizationContext.Provider, { value: t3, children: t4 }), $[15] = t3, $[16] = t4, $[17] = t5) : t5 = $[17], t5;
161
195
  }
162
- const DeleteTranslationAction = (props) => {
163
- const { id: documentId, published, draft } = props, doc = draft || published, { languageField } = useDocumentInternationalizationContext(), [isDialogOpen, setDialogOpen] = react.useState(!1), [translations, setTranslations] = react.useState([]), onClose = react.useCallback(() => setDialogOpen(!1), []), documentLanguage = doc ? doc[languageField] : null, toast = ui.useToast(), client = sanity.useClient({ apiVersion: API_VERSION }), onProceed = react.useCallback(() => {
196
+ const useDeleteTranslationAction = (props) => {
197
+ const $ = c(19), {
198
+ id: documentId,
199
+ published,
200
+ draft
201
+ } = props, doc = draft || published, {
202
+ languageField
203
+ } = useDocumentInternationalizationContext(), [isDialogOpen, setDialogOpen] = useState(!1);
204
+ let t0;
205
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = [], $[0] = t0) : t0 = $[0];
206
+ const [translations, setTranslations] = useState(t0);
207
+ let t1;
208
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = () => setDialogOpen(!1), $[1] = t1) : t1 = $[1];
209
+ const onClose = t1, rawDocumentLanguage = doc ? doc[languageField] : null, documentLanguage = typeof rawDocumentLanguage == "string" ? rawDocumentLanguage : null, toast = useToast();
210
+ let t2;
211
+ $[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = {
212
+ apiVersion: API_VERSION
213
+ }, $[2] = t2) : t2 = $[2];
214
+ const client = useClient(t2);
215
+ let t3;
216
+ $[3] !== client || $[4] !== documentId || $[5] !== documentLanguage || $[6] !== toast || $[7] !== translations ? (t3 = () => {
164
217
  const tx = client.transaction();
165
218
  let operation = "DELETE";
166
219
  documentLanguage && translations.length > 0 ? (operation = "UNSET", translations.forEach((translation) => {
167
- tx.patch(
168
- translation._id,
169
- (patch) => patch.unset([
170
- `${TRANSLATIONS_ARRAY_NAME}[_key == "${documentLanguage}"]`
171
- ])
172
- );
220
+ tx.patch(translation._id, (patch) => patch.unset([`${TRANSLATIONS_ARRAY_NAME}[${LANGUAGE_FIELD_NAME} == "${documentLanguage}"]`]));
173
221
  })) : (tx.delete(documentId), tx.delete(`drafts.${documentId}`)), tx.commit().then(() => {
174
222
  operation === "DELETE" && onClose(), toast.push({
175
223
  status: "success",
@@ -179,588 +227,296 @@ const DeleteTranslationAction = (props) => {
179
227
  }).catch((err) => {
180
228
  toast.push({
181
229
  status: "error",
182
- title: operation === "unset" ? "Failed to unset translation reference" : "Failed to delete document",
230
+ title: operation === "UNSET" ? "Failed to unset translation reference" : "Failed to delete document",
183
231
  description: err.message
184
232
  });
185
233
  });
186
- }, [client, documentLanguage, translations, documentId, onClose, toast]);
187
- return {
234
+ }, $[3] = client, $[4] = documentId, $[5] = documentLanguage, $[6] = toast, $[7] = translations, $[8] = t3) : t3 = $[8];
235
+ const onProceed = t3, t4 = !doc || !documentLanguage;
236
+ let t5;
237
+ $[9] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = () => {
238
+ setDialogOpen(!0);
239
+ }, $[9] = t5) : t5 = $[9];
240
+ let t6;
241
+ $[10] !== doc || $[11] !== documentId || $[12] !== isDialogOpen || $[13] !== onProceed || $[14] !== translations ? (t6 = isDialogOpen && {
242
+ type: "dialog",
243
+ onClose,
244
+ header: "Delete translation",
245
+ content: doc ? /* @__PURE__ */ jsx(DeleteTranslationDialog, { doc, documentId, setTranslations }) : null,
246
+ footer: /* @__PURE__ */ jsx(DeleteTranslationFooter, { onClose, onProceed, translations })
247
+ }, $[10] = doc, $[11] = documentId, $[12] = isDialogOpen, $[13] = onProceed, $[14] = translations, $[15] = t6) : t6 = $[15];
248
+ let t7;
249
+ return $[16] !== t4 || $[17] !== t6 ? (t7 = {
188
250
  label: "Delete translation...",
189
- disabled: !doc || !documentLanguage,
190
- icon: icons.TrashIcon,
251
+ disabled: t4,
252
+ icon: TrashIcon,
191
253
  tone: "critical",
192
- onHandle: () => {
193
- setDialogOpen(!0);
194
- },
195
- dialog: isDialogOpen && {
196
- type: "dialog",
197
- onClose,
198
- header: "Delete translation",
199
- content: doc ? /* @__PURE__ */ jsxRuntime.jsx(
200
- DeleteTranslationDialog,
201
- {
202
- doc,
203
- documentId,
204
- setTranslations
205
- }
206
- ) : null,
207
- footer: /* @__PURE__ */ jsxRuntime.jsx(
208
- DeleteTranslationFooter,
209
- {
210
- onClose,
211
- onProceed,
212
- translations
213
- }
214
- )
215
- }
216
- };
217
- };
218
- var extendStatics = function(d, b) {
219
- return extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
220
- d2.__proto__ = b2;
221
- } || function(d2, b2) {
222
- for (var p in b2)
223
- Object.prototype.hasOwnProperty.call(b2, p) && (d2[p] = b2[p]);
224
- }, extendStatics(d, b);
225
- };
226
- function __extends(d, b) {
227
- if (typeof b != "function" && b !== null)
228
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
229
- extendStatics(d, b);
230
- function __() {
231
- this.constructor = d;
232
- }
233
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
234
- }
235
- function __values(o) {
236
- var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
237
- if (m)
238
- return m.call(o);
239
- if (o && typeof o.length == "number")
240
- return {
241
- next: function() {
242
- return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
243
- }
244
- };
245
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
246
- }
247
- function __read(o, n) {
248
- var m = typeof Symbol == "function" && o[Symbol.iterator];
249
- if (!m)
250
- return o;
251
- var i = m.call(o), r, ar = [], e;
252
- try {
253
- for (; (n === void 0 || n-- > 0) && !(r = i.next()).done; )
254
- ar.push(r.value);
255
- } catch (error) {
256
- e = { error };
257
- } finally {
258
- try {
259
- r && !r.done && (m = i.return) && m.call(i);
260
- } finally {
261
- if (e)
262
- throw e.error;
263
- }
264
- }
265
- return ar;
266
- }
267
- function __spreadArray(to, from, pack) {
268
- if (pack || arguments.length === 2)
269
- for (var i = 0, l = from.length, ar; i < l; i++)
270
- (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
271
- return to.concat(ar || Array.prototype.slice.call(from));
272
- }
273
- function isFunction(value) {
274
- return typeof value == "function";
275
- }
276
- function createErrorClass(createImpl) {
277
- var _super = function(instance) {
278
- Error.call(instance), instance.stack = new Error().stack;
279
- }, ctorFunc = createImpl(_super);
280
- return ctorFunc.prototype = Object.create(Error.prototype), ctorFunc.prototype.constructor = ctorFunc, ctorFunc;
281
- }
282
- var UnsubscriptionError = createErrorClass(function(_super) {
283
- return function(errors) {
284
- _super(this), this.message = errors ? errors.length + ` errors occurred during unsubscription:
285
- ` + errors.map(function(err, i) {
286
- return i + 1 + ") " + err.toString();
287
- }).join(`
288
- `) : "", this.name = "UnsubscriptionError", this.errors = errors;
289
- };
290
- });
291
- function arrRemove(arr, item) {
292
- if (arr) {
293
- var index = arr.indexOf(item);
294
- 0 <= index && arr.splice(index, 1);
295
- }
296
- }
297
- var Subscription = function() {
298
- function Subscription2(initialTeardown) {
299
- this.initialTeardown = initialTeardown, this.closed = !1, this._parentage = null, this._finalizers = null;
300
- }
301
- return Subscription2.prototype.unsubscribe = function() {
302
- var e_1, _a, e_2, _b, errors;
303
- if (!this.closed) {
304
- this.closed = !0;
305
- var _parentage = this._parentage;
306
- if (_parentage)
307
- if (this._parentage = null, Array.isArray(_parentage))
308
- try {
309
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
310
- var parent_1 = _parentage_1_1.value;
311
- parent_1.remove(this);
312
- }
313
- } catch (e_1_1) {
314
- e_1 = { error: e_1_1 };
315
- } finally {
316
- try {
317
- _parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return) && _a.call(_parentage_1);
318
- } finally {
319
- if (e_1)
320
- throw e_1.error;
321
- }
322
- }
323
- else
324
- _parentage.remove(this);
325
- var initialFinalizer = this.initialTeardown;
326
- if (isFunction(initialFinalizer))
327
- try {
328
- initialFinalizer();
329
- } catch (e) {
330
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
331
- }
332
- var _finalizers = this._finalizers;
333
- if (_finalizers) {
334
- this._finalizers = null;
335
- try {
336
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
337
- var finalizer = _finalizers_1_1.value;
338
- try {
339
- execFinalizer(finalizer);
340
- } catch (err) {
341
- errors = errors != null ? errors : [], err instanceof UnsubscriptionError ? errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)) : errors.push(err);
342
- }
343
- }
344
- } catch (e_2_1) {
345
- e_2 = { error: e_2_1 };
346
- } finally {
347
- try {
348
- _finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return) && _b.call(_finalizers_1);
349
- } finally {
350
- if (e_2)
351
- throw e_2.error;
352
- }
353
- }
354
- }
355
- if (errors)
356
- throw new UnsubscriptionError(errors);
357
- }
358
- }, Subscription2.prototype.add = function(teardown) {
359
- var _a;
360
- if (teardown && teardown !== this)
361
- if (this.closed)
362
- execFinalizer(teardown);
363
- else {
364
- if (teardown instanceof Subscription2) {
365
- if (teardown.closed || teardown._hasParent(this))
366
- return;
367
- teardown._addParent(this);
368
- }
369
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
370
- }
371
- }, Subscription2.prototype._hasParent = function(parent) {
372
- var _parentage = this._parentage;
373
- return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
374
- }, Subscription2.prototype._addParent = function(parent) {
375
- var _parentage = this._parentage;
376
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
377
- }, Subscription2.prototype._removeParent = function(parent) {
378
- var _parentage = this._parentage;
379
- _parentage === parent ? this._parentage = null : Array.isArray(_parentage) && arrRemove(_parentage, parent);
380
- }, Subscription2.prototype.remove = function(teardown) {
381
- var _finalizers = this._finalizers;
382
- _finalizers && arrRemove(_finalizers, teardown), teardown instanceof Subscription2 && teardown._removeParent(this);
383
- }, Subscription2.EMPTY = function() {
384
- var empty = new Subscription2();
385
- return empty.closed = !0, empty;
386
- }(), Subscription2;
387
- }();
388
- function isSubscription(value) {
389
- return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
390
- }
391
- function execFinalizer(finalizer) {
392
- isFunction(finalizer) ? finalizer() : finalizer.unsubscribe();
393
- }
394
- var timeoutProvider = {
395
- setTimeout: function(handler, timeout) {
396
- for (var args = [], _i = 2; _i < arguments.length; _i++)
397
- args[_i - 2] = arguments[_i];
398
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
399
- },
400
- clearTimeout: function(handle) {
401
- return clearTimeout(handle);
402
- },
403
- delegate: void 0
254
+ onHandle: t5,
255
+ dialog: t6
256
+ }, $[16] = t4, $[17] = t6, $[18] = t7) : t7 = $[18], t7;
404
257
  };
405
- function reportUnhandledError(err) {
406
- timeoutProvider.setTimeout(function() {
407
- throw err;
408
- });
409
- }
410
- function noop() {
411
- }
412
- var Subscriber = function(_super) {
413
- __extends(Subscriber2, _super);
414
- function Subscriber2(destination) {
415
- var _this = _super.call(this) || this;
416
- return _this.isStopped = !1, destination ? (_this.destination = destination, isSubscription(destination) && destination.add(_this)) : _this.destination = EMPTY_OBSERVER, _this;
417
- }
418
- return Subscriber2.create = function(next, error, complete) {
419
- return new SafeSubscriber(next, error, complete);
420
- }, Subscriber2.prototype.next = function(value) {
421
- this.isStopped || this._next(value);
422
- }, Subscriber2.prototype.error = function(err) {
423
- this.isStopped || (this.isStopped = !0, this._error(err));
424
- }, Subscriber2.prototype.complete = function() {
425
- this.isStopped || (this.isStopped = !0, this._complete());
426
- }, Subscriber2.prototype.unsubscribe = function() {
427
- this.closed || (this.isStopped = !0, _super.prototype.unsubscribe.call(this), this.destination = null);
428
- }, Subscriber2.prototype._next = function(value) {
429
- this.destination.next(value);
430
- }, Subscriber2.prototype._error = function(err) {
431
- try {
432
- this.destination.error(err);
433
- } finally {
434
- this.unsubscribe();
435
- }
436
- }, Subscriber2.prototype._complete = function() {
437
- try {
438
- this.destination.complete();
439
- } finally {
440
- this.unsubscribe();
441
- }
442
- }, Subscriber2;
443
- }(Subscription), ConsumerObserver = function() {
444
- function ConsumerObserver2(partialObserver) {
445
- this.partialObserver = partialObserver;
446
- }
447
- return ConsumerObserver2.prototype.next = function(value) {
448
- var partialObserver = this.partialObserver;
449
- if (partialObserver.next)
450
- try {
451
- partialObserver.next(value);
452
- } catch (error) {
453
- handleUnhandledError(error);
454
- }
455
- }, ConsumerObserver2.prototype.error = function(err) {
456
- var partialObserver = this.partialObserver;
457
- if (partialObserver.error)
458
- try {
459
- partialObserver.error(err);
460
- } catch (error) {
461
- handleUnhandledError(error);
462
- }
463
- else
464
- handleUnhandledError(err);
465
- }, ConsumerObserver2.prototype.complete = function() {
466
- var partialObserver = this.partialObserver;
467
- if (partialObserver.complete)
468
- try {
469
- partialObserver.complete();
470
- } catch (error) {
471
- handleUnhandledError(error);
472
- }
473
- }, ConsumerObserver2;
474
- }(), SafeSubscriber = function(_super) {
475
- __extends(SafeSubscriber2, _super);
476
- function SafeSubscriber2(observerOrNext, error, complete) {
477
- var _this = _super.call(this) || this, partialObserver;
478
- return isFunction(observerOrNext) || !observerOrNext ? partialObserver = {
479
- next: observerOrNext != null ? observerOrNext : void 0,
480
- error: error != null ? error : void 0,
481
- complete: complete != null ? complete : void 0
482
- } : partialObserver = observerOrNext, _this.destination = new ConsumerObserver(partialObserver), _this;
483
- }
484
- return SafeSubscriber2;
485
- }(Subscriber);
486
- function handleUnhandledError(error) {
487
- reportUnhandledError(error);
488
- }
489
- function defaultErrorHandler(err) {
490
- throw err;
491
- }
492
- var EMPTY_OBSERVER = {
493
- closed: !0,
494
- next: noop,
495
- error: defaultErrorHandler,
496
- complete: noop
497
- };
498
- function hasLift(source) {
499
- return isFunction(source == null ? void 0 : source.lift);
500
- }
501
- function operate(init) {
502
- return function(source) {
503
- if (hasLift(source))
504
- return source.lift(function(liftedSource) {
505
- try {
506
- return init(liftedSource, this);
507
- } catch (err) {
508
- this.error(err);
509
- }
510
- });
511
- throw new TypeError("Unable to lift unknown Observable type");
512
- };
513
- }
514
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
515
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
516
- }
517
- var OperatorSubscriber = function(_super) {
518
- __extends(OperatorSubscriber2, _super);
519
- function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
520
- var _this = _super.call(this, destination) || this;
521
- return _this.onFinalize = onFinalize, _this.shouldUnsubscribe = shouldUnsubscribe, _this._next = onNext ? function(value) {
522
- try {
523
- onNext(value);
524
- } catch (err) {
525
- destination.error(err);
526
- }
527
- } : _super.prototype._next, _this._error = onError ? function(err) {
528
- try {
529
- onError(err);
530
- } catch (err2) {
531
- destination.error(err2);
532
- } finally {
533
- this.unsubscribe();
534
- }
535
- } : _super.prototype._error, _this._complete = onComplete ? function() {
536
- try {
537
- onComplete();
538
- } catch (err) {
539
- destination.error(err);
540
- } finally {
541
- this.unsubscribe();
542
- }
543
- } : _super.prototype._complete, _this;
544
- }
545
- return OperatorSubscriber2.prototype.unsubscribe = function() {
546
- var _a;
547
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
548
- var closed_1 = this.closed;
549
- _super.prototype.unsubscribe.call(this), !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 || _a.call(this));
550
- }
551
- }, OperatorSubscriber2;
552
- }(Subscriber), EmptyError = createErrorClass(function(_super) {
553
- return function() {
554
- _super(this), this.name = "EmptyError", this.message = "no elements in sequence";
555
- };
556
- });
557
- function firstValueFrom(source, config) {
558
- return new Promise(function(resolve, reject) {
559
- var subscriber = new SafeSubscriber({
560
- next: function(value) {
561
- resolve(value), subscriber.unsubscribe();
562
- },
563
- error: reject,
564
- complete: function() {
565
- reject(new EmptyError());
566
- }
567
- });
568
- source.subscribe(subscriber);
569
- });
570
- }
571
- function filter(predicate, thisArg) {
572
- return operate(function(source, subscriber) {
573
- var index = 0;
574
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
575
- return predicate.call(thisArg, value, index++) && subscriber.next(value);
576
- }));
577
- });
578
- }
579
- const query = `*[_type == $translationSchema && $id in translations[].value._ref]{
258
+ useDeleteTranslationAction.action = "deleteTranslation";
259
+ useDeleteTranslationAction.displayName = "DeleteTranslationAction";
260
+ const DeleteTranslationAction = (props) => useDeleteTranslationAction(props), query = `*[_type == $translationSchema && $id in translations[].value._ref]{
580
261
  _id,
581
262
  _createdAt,
582
263
  translations
583
264
  }`;
584
265
  function useTranslationMetadata(id) {
585
- const { data, loading, error } = sanityPluginUtils.useListeningQuery(query, {
586
- params: { id, translationSchema: METADATA_SCHEMA_NAME }
587
- });
588
- return { data, loading, error };
266
+ const $ = c(6);
267
+ let t0;
268
+ $[0] !== id ? (t0 = {
269
+ params: {
270
+ id,
271
+ translationSchema: METADATA_SCHEMA_NAME
272
+ }
273
+ }, $[0] = id, $[1] = t0) : t0 = $[1];
274
+ const {
275
+ data,
276
+ loading,
277
+ error
278
+ } = useListeningQuery(query, t0), t1 = data;
279
+ let t2;
280
+ return $[2] !== error || $[3] !== loading || $[4] !== t1 ? (t2 = {
281
+ data: t1,
282
+ loading,
283
+ error
284
+ }, $[2] = error, $[3] = loading, $[4] = t1, $[5] = t2) : t2 = $[5], t2;
589
285
  }
590
- const documenti18nLocaleNamespace = "document-internationalization", documentInternationalizationUsEnglishLocaleBundle = sanity.defineLocaleResourceBundle({
286
+ const documenti18nLocaleNamespace = "document-internationalization", documentInternationalizationUsEnglishLocaleBundle = defineLocaleResourceBundle({
591
287
  locale: "en-US",
592
288
  namespace: documenti18nLocaleNamespace,
593
- resources: () => Promise.resolve().then(function() {
594
- return require("./_chunks-cjs/resources.js");
595
- })
289
+ resources: () => import("./_chunks-es/resources.js")
596
290
  }), DISABLED_REASON_KEY = {
597
291
  METADATA_NOT_FOUND: "action.duplicate.disabled.missing-metadata",
598
292
  MULTIPLE_METADATA: "action.duplicate.disabled.multiple-metadata",
599
293
  NOTHING_TO_DUPLICATE: "action.duplicate.disabled.nothing-to-duplicate",
600
294
  NOT_READY: "action.duplicate.disabled.not-ready"
601
- }, DuplicateWithTranslationsAction = ({
602
- id,
603
- type,
604
- onComplete
605
- }) => {
606
- const documentStore = sanity.useDocumentStore(), { duplicate } = sanity.useDocumentOperation(id, type), { navigateIntent } = router.useRouter(), [isDuplicating, setDuplicating] = react.useState(!1), [permissions, isPermissionsLoading] = sanity.useDocumentPairPermissions({
295
+ }, useDuplicateWithTranslationsAction = (t0) => {
296
+ const $ = c(44), {
297
+ id,
298
+ type,
299
+ onComplete
300
+ } = t0, documentStore = useDocumentStore(), {
301
+ duplicate
302
+ } = useDocumentOperation(id, type), {
303
+ navigateIntent
304
+ } = useRouter(), [isDuplicating, setDuplicating] = useState(!1);
305
+ let t1;
306
+ $[0] !== id || $[1] !== type ? (t1 = {
607
307
  id,
608
308
  type,
609
309
  permission: "duplicate"
610
- }), { data, loading: isMetadataDocumentLoading } = useTranslationMetadata(id), hasOneMetadataDocument = react.useMemo(() => Array.isArray(data) && data.length <= 1, [data]), metadataDocument = Array.isArray(data) && data.length ? data[0] : null, client = sanity.useClient(sanity.DEFAULT_STUDIO_CLIENT_OPTIONS), toast = ui.useToast(), { t: s } = sanity.useTranslation(structure.structureLocaleNamespace), { t: d } = sanity.useTranslation(documenti18nLocaleNamespace), currentUser = sanity.useCurrentUser(), handle = react.useCallback(async () => {
611
- setDuplicating(!0);
612
- try {
310
+ }, $[0] = id, $[1] = type, $[2] = t1) : t1 = $[2];
311
+ const [permissions, isPermissionsLoading] = useDocumentPairPermissions(t1), {
312
+ data,
313
+ loading: isMetadataDocumentLoading
314
+ } = useTranslationMetadata(id), hasOneMetadataDocument = Array.isArray(data) && data.length <= 1, metadataDocument = Array.isArray(data) && data.length ? data[0] : null, client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS), toast = useToast(), {
315
+ t: s
316
+ } = useTranslation(structureLocaleNamespace), {
317
+ t: d
318
+ } = useTranslation(documenti18nLocaleNamespace), currentUser = useCurrentUser();
319
+ let t2;
320
+ $[3] !== client || $[4] !== documentStore.pair || $[5] !== metadataDocument || $[6] !== navigateIntent || $[7] !== onComplete || $[8] !== toast || $[9] !== type ? (t2 = () => {
321
+ setDuplicating(!0), (async function() {
613
322
  if (!metadataDocument)
614
- throw new Error("Metadata document not found");
323
+ return Promise.reject(new Error("Metadata document not found"));
324
+ const translationsArray = metadataDocument[TRANSLATIONS_ARRAY_NAME];
325
+ if (!translationsArray || translationsArray.length === 0)
326
+ return Promise.reject(new Error("No translations found in metadata document"));
615
327
  const translations = /* @__PURE__ */ new Map();
616
- await Promise.all(
617
- metadataDocument[TRANSLATIONS_ARRAY_NAME].map(async (translation) => {
618
- var _a;
619
- const dupeId2 = uuid.uuid(), locale = translation._key, docId = (_a = translation.value) == null ? void 0 : _a._ref;
620
- if (!docId)
621
- throw new Error("Translation document not found");
622
- const { duplicate: duplicateTranslation } = await firstValueFrom(
623
- documentStore.pair.editOperations(docId, type).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
624
- );
625
- if (duplicateTranslation.disabled)
626
- throw new Error("Cannot duplicate document");
627
- const duplicateTranslationSuccess = firstValueFrom(
628
- documentStore.pair.operationEvents(docId, type).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
629
- );
630
- duplicateTranslation.execute(dupeId2), await duplicateTranslationSuccess, translations.set(locale, dupeId2);
631
- })
632
- );
633
- const { duplicate: duplicateMetadata } = await firstValueFrom(
634
- documentStore.pair.editOperations(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((op) => op.duplicate.disabled !== "NOT_READY"))
635
- );
328
+ await Promise.all(translationsArray.map(async (translation) => {
329
+ const dupeId = uuid(), locale = translation[LANGUAGE_FIELD_NAME], docId = translation.value?._ref;
330
+ if (typeof locale != "string" || locale.trim().length === 0)
331
+ return Promise.reject(new Error("Invalid locale for translation"));
332
+ if (!docId)
333
+ return Promise.reject(new Error("Translation document not found"));
334
+ const {
335
+ duplicate: duplicateTranslation
336
+ } = await firstValueFrom(documentStore.pair.editOperations(docId, type).pipe(filter(_temp$4)));
337
+ if (duplicateTranslation.disabled)
338
+ return Promise.reject(new Error("Cannot duplicate document"));
339
+ const duplicateTranslationSuccess = firstValueFrom(documentStore.pair.operationEvents(docId, type).pipe(filter(_temp2$2)));
340
+ duplicateTranslation.execute(dupeId), await duplicateTranslationSuccess, translations.set(locale, dupeId);
341
+ }));
342
+ const {
343
+ duplicate: duplicateMetadata
344
+ } = await firstValueFrom(documentStore.pair.editOperations(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter(_temp3)));
636
345
  if (duplicateMetadata.disabled)
637
- throw new Error("Cannot duplicate document");
638
- const duplicateMetadataSuccess = firstValueFrom(
639
- documentStore.pair.operationEvents(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter((e) => e.op === "duplicate" && e.type === "success"))
640
- ), dupeId = uuid.uuid();
641
- duplicateMetadata.execute(dupeId), await duplicateMetadataSuccess;
346
+ return Promise.reject(new Error("Cannot duplicate document"));
347
+ const duplicateMetadataSuccess = firstValueFrom(documentStore.pair.operationEvents(metadataDocument._id, METADATA_SCHEMA_NAME).pipe(filter(_temp4))), dupeId_0 = uuid();
348
+ duplicateMetadata.execute(dupeId_0), await duplicateMetadataSuccess;
642
349
  const patch = {
643
- set: Object.fromEntries(
644
- Array.from(translations.entries()).map(([locale, documentId]) => [
645
- `${TRANSLATIONS_ARRAY_NAME}[_key == "${locale}"].value._ref`,
646
- documentId
647
- ])
648
- )
350
+ set: Object.fromEntries(Array.from(translations.entries()).map(_temp5))
649
351
  };
650
- await client.transaction().patch(dupeId, patch).commit(), navigateIntent("edit", {
352
+ await client.transaction().patch(dupeId_0, patch).commit(), navigateIntent("edit", {
651
353
  id: Array.from(translations.values()).at(0),
652
354
  type
653
355
  }), onComplete();
654
- } catch (error) {
356
+ })().catch((error) => {
655
357
  console.error(error), toast.push({
656
358
  status: "error",
657
359
  title: "Error duplicating document",
658
360
  description: error instanceof Error ? error.message : "Failed to duplicate document"
659
361
  });
660
- } finally {
362
+ }).finally(() => {
661
363
  setDuplicating(!1);
364
+ });
365
+ }, $[3] = client, $[4] = documentStore.pair, $[5] = metadataDocument, $[6] = navigateIntent, $[7] = onComplete, $[8] = toast, $[9] = type, $[10] = t2) : t2 = $[10];
366
+ const handle = t2;
367
+ let t3;
368
+ bb0: {
369
+ if (!isPermissionsLoading && !permissions?.granted) {
370
+ let t42;
371
+ $[11] !== d ? (t42 = d("action.duplicate.label"), $[11] = d, $[12] = t42) : t42 = $[12];
372
+ let t52;
373
+ $[13] !== currentUser ? (t52 = /* @__PURE__ */ jsx(InsufficientPermissionsMessage, { context: "duplicate-document", currentUser }), $[13] = currentUser, $[14] = t52) : t52 = $[14];
374
+ let t62;
375
+ $[15] !== t42 || $[16] !== t52 ? (t62 = {
376
+ icon: CopyIcon,
377
+ disabled: !0,
378
+ label: t42,
379
+ title: t52
380
+ }, $[15] = t42, $[16] = t52, $[17] = t62) : t62 = $[17], t3 = t62;
381
+ break bb0;
662
382
  }
663
- }, [
664
- client,
665
- documentStore.pair,
666
- metadataDocument,
667
- navigateIntent,
668
- onComplete,
669
- toast,
670
- type
671
- ]);
672
- return react.useMemo(() => !isPermissionsLoading && !(permissions != null && permissions.granted) ? {
673
- icon: icons.CopyIcon,
674
- disabled: !0,
675
- label: d("action.duplicate.label"),
676
- title: /* @__PURE__ */ jsxRuntime.jsx(
677
- sanity.InsufficientPermissionsMessage,
678
- {
679
- context: "duplicate-document",
680
- currentUser
681
- }
682
- )
683
- } : !isMetadataDocumentLoading && !metadataDocument ? {
684
- icon: icons.CopyIcon,
685
- disabled: !0,
686
- label: d("action.duplicate.label"),
687
- title: d(DISABLED_REASON_KEY.METADATA_NOT_FOUND)
688
- } : hasOneMetadataDocument ? {
689
- icon: icons.CopyIcon,
690
- disabled: isDuplicating || !!duplicate.disabled || isPermissionsLoading || isMetadataDocumentLoading,
691
- label: isDuplicating ? s("action.duplicate.running.label") : d("action.duplicate.label"),
692
- title: duplicate.disabled ? s(DISABLED_REASON_KEY[duplicate.disabled]) : "",
693
- onHandle: handle
694
- } : {
695
- icon: icons.CopyIcon,
696
- disabled: !0,
697
- label: d("action.duplicate.label"),
698
- title: d(DISABLED_REASON_KEY.MULTIPLE_METADATA)
699
- }, [
700
- currentUser,
701
- duplicate.disabled,
702
- handle,
703
- hasOneMetadataDocument,
704
- isDuplicating,
705
- isMetadataDocumentLoading,
706
- isPermissionsLoading,
707
- metadataDocument,
708
- permissions == null ? void 0 : permissions.granted,
709
- s,
710
- d
711
- ]);
383
+ if (!isMetadataDocumentLoading && !metadataDocument) {
384
+ let t42;
385
+ $[18] !== d ? (t42 = d("action.duplicate.label"), $[18] = d, $[19] = t42) : t42 = $[19];
386
+ let t52;
387
+ $[20] !== d ? (t52 = d(DISABLED_REASON_KEY.METADATA_NOT_FOUND), $[20] = d, $[21] = t52) : t52 = $[21];
388
+ let t62;
389
+ $[22] !== t42 || $[23] !== t52 ? (t62 = {
390
+ icon: CopyIcon,
391
+ disabled: !0,
392
+ label: t42,
393
+ title: t52
394
+ }, $[22] = t42, $[23] = t52, $[24] = t62) : t62 = $[24], t3 = t62;
395
+ break bb0;
396
+ }
397
+ if (!hasOneMetadataDocument) {
398
+ let t42;
399
+ $[25] !== d ? (t42 = d("action.duplicate.label"), $[25] = d, $[26] = t42) : t42 = $[26];
400
+ let t52;
401
+ $[27] !== d ? (t52 = d(DISABLED_REASON_KEY.MULTIPLE_METADATA), $[27] = d, $[28] = t52) : t52 = $[28];
402
+ let t62;
403
+ $[29] !== t42 || $[30] !== t52 ? (t62 = {
404
+ icon: CopyIcon,
405
+ disabled: !0,
406
+ label: t42,
407
+ title: t52
408
+ }, $[29] = t42, $[30] = t52, $[31] = t62) : t62 = $[31], t3 = t62;
409
+ break bb0;
410
+ }
411
+ const t4 = isDuplicating || !!duplicate.disabled || isPermissionsLoading || isMetadataDocumentLoading;
412
+ let t5;
413
+ $[32] !== d || $[33] !== isDuplicating || $[34] !== s ? (t5 = isDuplicating ? s("action.duplicate.running.label") : d("action.duplicate.label"), $[32] = d, $[33] = isDuplicating, $[34] = s, $[35] = t5) : t5 = $[35];
414
+ let t6;
415
+ $[36] !== duplicate.disabled || $[37] !== s ? (t6 = duplicate.disabled ? s(DISABLED_REASON_KEY[duplicate.disabled]) : "", $[36] = duplicate.disabled, $[37] = s, $[38] = t6) : t6 = $[38];
416
+ let t7;
417
+ $[39] !== handle || $[40] !== t4 || $[41] !== t5 || $[42] !== t6 ? (t7 = {
418
+ icon: CopyIcon,
419
+ disabled: t4,
420
+ label: t5,
421
+ title: t6,
422
+ onHandle: handle
423
+ }, $[39] = handle, $[40] = t4, $[41] = t5, $[42] = t6, $[43] = t7) : t7 = $[43], t3 = t7;
424
+ }
425
+ return t3;
712
426
  };
427
+ useDuplicateWithTranslationsAction.action = "duplicate";
428
+ useDuplicateWithTranslationsAction.displayName = "DuplicateWithTranslationsAction";
429
+ const DuplicateWithTranslationsAction = (props) => useDuplicateWithTranslationsAction(props);
713
430
  DuplicateWithTranslationsAction.action = "duplicate";
714
431
  DuplicateWithTranslationsAction.displayName = "DuplicateWithTranslationsAction";
432
+ function _temp$4(op) {
433
+ return op.duplicate.disabled !== "NOT_READY";
434
+ }
435
+ function _temp2$2(e) {
436
+ return e.op === "duplicate" && e.type === "success";
437
+ }
438
+ function _temp3(op_0) {
439
+ return op_0.duplicate.disabled !== "NOT_READY";
440
+ }
441
+ function _temp4(e_0) {
442
+ return e_0.op === "duplicate" && e_0.type === "success";
443
+ }
444
+ function _temp5(t0) {
445
+ const [locale_0, documentId] = t0;
446
+ return [`${TRANSLATIONS_ARRAY_NAME}[${LANGUAGE_FIELD_NAME} == "${locale_0}"].value._ref`, documentId];
447
+ }
715
448
  function useOpenInNewPane(id, type) {
716
- const routerContext = react.useContext(router.RouterContext), { routerPanesState, groupIndex } = structure.usePaneRouter();
717
- return react.useCallback(() => {
718
- if (!routerContext || !id || !type)
449
+ const $ = c(6), router = useRouter(), {
450
+ routerPanesState,
451
+ groupIndex
452
+ } = usePaneRouter();
453
+ let t0;
454
+ return $[0] !== groupIndex || $[1] !== id || $[2] !== router || $[3] !== routerPanesState || $[4] !== type ? (t0 = () => {
455
+ if (!id || !type)
719
456
  return;
720
457
  if (!routerPanesState.length) {
721
- routerContext.navigateIntent("edit", { id, type });
458
+ router.navigateIntent("edit", {
459
+ id,
460
+ type
461
+ });
722
462
  return;
723
463
  }
724
464
  const panes = [...routerPanesState];
725
- panes.splice(groupIndex + 1, 0, [
726
- {
727
- id,
728
- params: { type }
465
+ panes.splice(groupIndex + 1, 0, [{
466
+ id,
467
+ params: {
468
+ type
729
469
  }
730
- ]);
731
- const href = routerContext.resolvePathFromState({ panes });
732
- routerContext.navigateUrl({ path: href });
733
- }, [id, type, routerContext, routerPanesState, groupIndex]);
470
+ }]);
471
+ const href = router.resolvePathFromState({
472
+ panes
473
+ });
474
+ router.navigateUrl({
475
+ path: href
476
+ });
477
+ }, $[0] = groupIndex, $[1] = id, $[2] = router, $[3] = routerPanesState, $[4] = type, $[5] = t0) : t0 = $[5], t0;
734
478
  }
735
- var __defProp$2 = Object.defineProperty, __getOwnPropSymbols$2 = Object.getOwnPropertySymbols, __hasOwnProp$2 = Object.prototype.hasOwnProperty, __propIsEnum$2 = Object.prototype.propertyIsEnumerable, __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$2 = (a, b) => {
736
- for (var prop in b || (b = {}))
737
- __hasOwnProp$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
738
- if (__getOwnPropSymbols$2)
739
- for (var prop of __getOwnPropSymbols$2(b))
740
- __propIsEnum$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
741
- return a;
742
- };
743
- function createReference(key, ref, type, strengthenOnPublish = !0) {
479
+ function createReference(language, ref, type, strengthenOnPublish = !0) {
744
480
  return {
745
- _key: key,
481
+ // TODO: Update in next major version when we migrate to the new format
482
+ // ...(LANGUAGE_FIELD_NAME === "_key"? {} : {_key: createRandomKey()} )
483
+ [LANGUAGE_FIELD_NAME]: language,
746
484
  _type: "internationalizedArrayReferenceValue",
747
- value: __spreadValues$2({
485
+ value: {
748
486
  _type: "reference",
749
487
  _ref: ref,
750
- _weak: !0
751
- }, strengthenOnPublish ? { _strengthenOnPublish: { type } } : {})
488
+ _weak: !0,
489
+ // If the user has configured weakReferences, we won't want to strengthen them
490
+ ...strengthenOnPublish ? {
491
+ _strengthenOnPublish: {
492
+ type
493
+ }
494
+ } : {}
495
+ }
752
496
  };
753
497
  }
754
498
  function LanguageManage(props) {
755
- const { id, metadataId, schemaType, documentId, sourceLanguageId } = props, open = useOpenInNewPane(id, METADATA_SCHEMA_NAME), openCreated = useOpenInNewPane(metadataId, METADATA_SCHEMA_NAME), { allowCreateMetaDoc, apiVersion, weakReferences } = useDocumentInternationalizationContext(), client = sanity.useClient({ apiVersion }), [userHasClicked, setUserHasClicked] = react.useState(!1), canCreate = !id && !!metadataId && allowCreateMetaDoc, handleClick = react.useCallback(() => {
499
+ const $ = c(21), {
500
+ id,
501
+ metadataId,
502
+ schemaType,
503
+ documentId,
504
+ sourceLanguageId
505
+ } = props, open = useOpenInNewPane(id, METADATA_SCHEMA_NAME), openCreated = useOpenInNewPane(metadataId, METADATA_SCHEMA_NAME), {
506
+ allowCreateMetaDoc,
507
+ apiVersion,
508
+ weakReferences
509
+ } = useDocumentInternationalizationContext();
510
+ let t0;
511
+ $[0] !== apiVersion ? (t0 = {
512
+ apiVersion
513
+ }, $[0] = apiVersion, $[1] = t0) : t0 = $[1];
514
+ const client = useClient(t0), [userHasClicked, setUserHasClicked] = useState(!1), canCreate = !id && !!metadataId && allowCreateMetaDoc;
515
+ let t1;
516
+ $[2] !== client || $[3] !== documentId || $[4] !== id || $[5] !== metadataId || $[6] !== open || $[7] !== openCreated || $[8] !== schemaType.name || $[9] !== sourceLanguageId || $[10] !== weakReferences ? (t1 = () => {
756
517
  if (!id && metadataId && sourceLanguageId) {
757
518
  setUserHasClicked(!0);
758
- const transaction = client.transaction(), sourceReference = createReference(
759
- sourceLanguageId,
760
- documentId,
761
- schemaType.name,
762
- !weakReferences
763
- ), newMetadataDocument = {
519
+ const transaction = client.transaction(), sourceReference = createReference(sourceLanguageId, documentId, schemaType.name, !weakReferences), newMetadataDocument = {
764
520
  _id: metadataId,
765
521
  _type: METADATA_SCHEMA_NAME,
766
522
  schemaTypes: [schemaType.name],
@@ -773,66 +529,37 @@ function LanguageManage(props) {
773
529
  });
774
530
  } else
775
531
  open();
776
- }, [
777
- id,
778
- metadataId,
779
- sourceLanguageId,
780
- client,
781
- documentId,
782
- schemaType.name,
783
- weakReferences,
784
- openCreated,
785
- open
786
- ]);
787
- return /* @__PURE__ */ jsxRuntime.jsx(
788
- ui.Tooltip,
789
- {
790
- animate: !0,
791
- content: /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: "Document has no other translations" }) }),
792
- fallbackPlacements: ["right", "left"],
793
- placement: "top",
794
- portal: !0,
795
- disabled: !!id || canCreate,
796
- children: /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { children: /* @__PURE__ */ jsxRuntime.jsx(
797
- ui.Button,
798
- {
799
- disabled: !id && !canCreate || canCreate && !sourceLanguageId || userHasClicked,
800
- mode: "ghost",
801
- text: "Manage Translations",
802
- icon: icons.CogIcon,
803
- loading: userHasClicked,
804
- onClick: handleClick
805
- }
806
- ) })
807
- }
808
- );
532
+ }, $[2] = client, $[3] = documentId, $[4] = id, $[5] = metadataId, $[6] = open, $[7] = openCreated, $[8] = schemaType.name, $[9] = sourceLanguageId, $[10] = weakReferences, $[11] = t1) : t1 = $[11];
533
+ const handleClick = t1, disabled = !id && !canCreate || canCreate && !sourceLanguageId || userHasClicked;
534
+ let t2, t3;
535
+ $[12] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "Document has no other translations" }) }), t3 = ["right", "left"], $[12] = t2, $[13] = t3) : (t2 = $[12], t3 = $[13]);
536
+ const t4 = !!id || canCreate;
537
+ let t5;
538
+ $[14] !== disabled || $[15] !== handleClick || $[16] !== userHasClicked ? (t5 = /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(Button, { disabled, mode: "ghost", text: "Manage Translations", icon: CogIcon, loading: userHasClicked, onClick: handleClick }) }), $[14] = disabled, $[15] = handleClick, $[16] = userHasClicked, $[17] = t5) : t5 = $[17];
539
+ let t6;
540
+ return $[18] !== t4 || $[19] !== t5 ? (t6 = /* @__PURE__ */ jsx(Tooltip, { animate: !0, content: t2, fallbackPlacements: t3, placement: "top", portal: !0, disabled: t4, children: t5 }), $[18] = t4, $[19] = t5, $[20] = t6) : t6 = $[20], t6;
809
541
  }
810
542
  function removeExcludedPaths(doc, schemaType) {
811
- if (!sanity.isDocumentSchemaType(schemaType) || !doc)
543
+ if (!isDocumentSchemaType(schemaType) || !doc)
812
544
  return doc;
813
- const pathsToExclude = extractPaths(doc, schemaType, []).filter(
814
- (field) => {
815
- var _a, _b, _c;
816
- return ((_c = (_b = (_a = field.schemaType) == null ? void 0 : _a.options) == null ? void 0 : _b.documentInternationalization) == null ? void 0 : _c.exclude) === !0;
817
- }
818
- ).map((field) => sanity.pathToString(field.path));
819
- return new mutator.Mutation({
820
- mutations: [
821
- {
822
- patch: {
823
- id: doc._id,
824
- unset: pathsToExclude
825
- }
545
+ const pathsToExclude = extractPaths(doc, schemaType, []).filter((field) => field.schemaType?.options?.documentInternationalization?.exclude === !0).map((field) => pathToString(field.path));
546
+ return new Mutation({
547
+ mutations: [{
548
+ patch: {
549
+ id: doc._id,
550
+ unset: pathsToExclude
826
551
  }
827
- ]
552
+ }]
828
553
  }).apply(doc);
829
554
  }
830
555
  function extractPaths(doc, schemaType, path) {
831
- return schemaType.fields.reduce((acc, field) => {
832
- var _a, _b;
833
- const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _a : {};
834
- if (!value)
835
- return acc;
556
+ const result = [];
557
+ for (const field of schemaType.fields) {
558
+ const fieldPath = [...path, field.name], fieldSchema = field.type, {
559
+ value
560
+ } = extractWithPath(pathToString(fieldPath), doc)[0] ?? {};
561
+ if (value == null)
562
+ continue;
836
563
  const thisFieldWithPath = {
837
564
  path: fieldPath,
838
565
  name: field.name,
@@ -841,44 +568,35 @@ function extractPaths(doc, schemaType, path) {
841
568
  };
842
569
  if (fieldSchema.jsonType === "object") {
843
570
  const innerFields = extractPaths(doc, fieldSchema, fieldPath);
844
- return [...acc, thisFieldWithPath, ...innerFields];
571
+ result.push(thisFieldWithPath, ...innerFields);
845
572
  } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
846
- const { value: arrayValue } = (_b = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _b : {};
847
- let arrayPaths = [];
848
- if (arrayValue != null && arrayValue.length)
573
+ const {
574
+ value: arrayValue
575
+ } = extractWithPath(pathToString(fieldPath), doc)[0] ?? {};
576
+ if (result.push(thisFieldWithPath), arrayValue?.length)
849
577
  for (const item of arrayValue) {
850
- const itemPath = [...fieldPath, { _key: item._key }];
578
+ if (!item._key) continue;
579
+ const itemPath = [...fieldPath, {
580
+ _key: item._key
581
+ }];
851
582
  let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
852
- if (item._type || (itemSchema = fieldSchema.of[0]), item._key && itemSchema) {
853
- const innerFields = extractPaths(
854
- doc,
855
- itemSchema,
856
- itemPath
857
- ), arrayMember = {
583
+ if (item._type || (itemSchema = fieldSchema.of[0]), itemSchema) {
584
+ const innerFields = extractPaths(doc, itemSchema, itemPath), arrayMember = {
858
585
  path: itemPath,
859
586
  name: item._key,
860
587
  schemaType: itemSchema,
861
588
  value: item
862
589
  };
863
- arrayPaths = [...arrayPaths, arrayMember, ...innerFields];
590
+ result.push(arrayMember, ...innerFields);
864
591
  }
865
592
  }
866
- return [...acc, thisFieldWithPath, ...arrayPaths];
867
- }
868
- return [...acc, thisFieldWithPath];
869
- }, []);
593
+ } else
594
+ result.push(thisFieldWithPath);
595
+ }
596
+ return result;
870
597
  }
871
- var __defProp$1 = Object.defineProperty, __defProps$1 = Object.defineProperties, __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$1 = Object.getOwnPropertySymbols, __hasOwnProp$1 = Object.prototype.hasOwnProperty, __propIsEnum$1 = Object.prototype.propertyIsEnumerable, __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$1 = (a, b) => {
872
- for (var prop in b || (b = {}))
873
- __hasOwnProp$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
874
- if (__getOwnPropSymbols$1)
875
- for (var prop of __getOwnPropSymbols$1(b))
876
- __propIsEnum$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
877
- return a;
878
- }, __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
879
598
  function LanguageOption(props) {
880
- var _a;
881
- const {
599
+ const $ = c(45), {
882
600
  language,
883
601
  schemaType,
884
602
  documentId,
@@ -887,11 +605,25 @@ function LanguageOption(props) {
887
605
  sourceLanguageId,
888
606
  metadata: metadata2,
889
607
  metadataId
890
- } = props, [userHasClicked, setUserHasClicked] = react.useState(!1), disabled = props.disabled || userHasClicked || current || !source || !sourceLanguageId || !metadataId, translation = metadata2 != null && metadata2.translations.length ? metadata2.translations.find((t) => t._key === language.id) : void 0, { apiVersion, languageField, weakReferences, callback } = useDocumentInternationalizationContext(), client = sanity.useClient({ apiVersion }), toast = ui.useToast(), open = useOpenInNewPane((_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref, schemaType.name), handleOpen = react.useCallback(() => open(), [open]);
891
- react.useEffect(() => {
892
- setUserHasClicked(!1);
893
- }, [!!translation]);
894
- const handleCreate = react.useCallback(async () => {
608
+ } = props, [userHasClicked, setUserHasClicked] = useState(!1), disabled = props.disabled || userHasClicked || current || !source || !sourceLanguageId || !metadataId;
609
+ let t0;
610
+ $[0] !== language.id || $[1] !== metadata2 ? (t0 = metadata2?.translations.length ? metadata2.translations.find((t) => t._key === language.id) : void 0, $[0] = language.id, $[1] = metadata2, $[2] = t0) : t0 = $[2];
611
+ const translation = t0, {
612
+ apiVersion,
613
+ languageField,
614
+ weakReferences,
615
+ callback
616
+ } = useDocumentInternationalizationContext();
617
+ let t1;
618
+ $[3] !== apiVersion ? (t1 = {
619
+ apiVersion
620
+ }, $[3] = apiVersion, $[4] = t1) : t1 = $[4];
621
+ const client = useClient(t1), toast = useToast(), open = useOpenInNewPane(translation?.value?._ref, schemaType.name);
622
+ let t2;
623
+ $[5] !== open ? (t2 = () => open(), $[5] = open, $[6] = t2) : t2 = $[6];
624
+ const handleOpen = t2;
625
+ let t3;
626
+ $[7] !== callback || $[8] !== client || $[9] !== documentId || $[10] !== language.id || $[11] !== language.title || $[12] !== languageField || $[13] !== metadata2?._createdAt || $[14] !== metadataId || $[15] !== schemaType || $[16] !== source || $[17] !== sourceLanguageId || $[18] !== toast || $[19] !== weakReferences ? (t3 = async () => {
895
627
  if (!source)
896
628
  throw new Error("Cannot create translation without source document");
897
629
  if (!sourceLanguageId)
@@ -899,105 +631,91 @@ function LanguageOption(props) {
899
631
  if (!metadataId)
900
632
  throw new Error("Cannot create translation without a metadata ID");
901
633
  setUserHasClicked(!0);
902
- const transaction = client.transaction(), newTranslationDocumentId = uuid.uuid();
903
- let newTranslationDocument = __spreadProps$1(__spreadValues$1({}, source), {
634
+ const transaction = client.transaction(), newTranslationDocumentId = uuid();
635
+ let newTranslationDocument = {
636
+ ...source,
904
637
  _id: `drafts.${newTranslationDocumentId}`,
905
- // 2. Update language of the translation
906
638
  [languageField]: language.id
907
- });
908
- newTranslationDocument = removeExcludedPaths(
909
- newTranslationDocument,
910
- schemaType
911
- ), transaction.create(newTranslationDocument);
912
- const sourceReference = createReference(
913
- sourceLanguageId,
914
- documentId,
915
- schemaType.name,
916
- !weakReferences
917
- ), newTranslationReference = createReference(
918
- language.id,
919
- newTranslationDocumentId,
920
- schemaType.name,
921
- !weakReferences
922
- ), newMetadataDocument = {
639
+ };
640
+ newTranslationDocument = removeExcludedPaths(newTranslationDocument, schemaType), transaction.create(newTranslationDocument);
641
+ const sourceReference = createReference(sourceLanguageId, documentId, schemaType.name, !weakReferences), newTranslationReference = createReference(language.id, newTranslationDocumentId, schemaType.name, !weakReferences), newMetadataDocument = {
923
642
  _id: metadataId,
924
643
  _type: METADATA_SCHEMA_NAME,
925
644
  schemaTypes: [schemaType.name],
926
645
  translations: [sourceReference]
927
646
  };
928
647
  transaction.createIfNotExists(newMetadataDocument);
929
- const metadataPatch = client.patch(metadataId).setIfMissing({ translations: [sourceReference] }).insert("after", "translations[-1]", [newTranslationReference]);
648
+ const metadataPatch = client.patch(metadataId).setIfMissing({
649
+ translations: [sourceReference]
650
+ }).insert("after", "translations[-1]", [newTranslationReference]);
930
651
  transaction.patch(metadataPatch), transaction.commit().then(() => {
931
- const metadataExisted = !!(metadata2 != null && metadata2._createdAt);
932
- return callback == null || callback({
933
- client,
934
- sourceLanguageId,
935
- sourceDocument: source,
936
- newDocument: newTranslationDocument,
937
- destinationLanguageId: language.id,
938
- metaDocumentId: metadataId
939
- }).catch((err) => {
940
- toast.push({
941
- status: "error",
942
- title: "Callback",
943
- description: `Error while running callback - ${err}.`
944
- });
945
- }), toast.push({
652
+ const metadataExisted = !!metadata2?._createdAt;
653
+ if (toast.push({
946
654
  status: "success",
947
655
  title: `Created "${language.title}" translation`,
948
656
  description: metadataExisted ? "Updated Translations Metadata" : "Created Translations Metadata"
949
- });
657
+ }), setUserHasClicked(!1), callback)
658
+ return callback({
659
+ client,
660
+ sourceLanguageId,
661
+ sourceDocument: source,
662
+ newDocument: newTranslationDocument,
663
+ destinationLanguageId: language.id,
664
+ metaDocumentId: metadataId
665
+ });
950
666
  }).catch((err) => (console.error(err), setUserHasClicked(!1), toast.push({
951
667
  status: "error",
952
668
  title: "Error creating translation",
953
669
  description: err.message
954
670
  })));
955
- }, [
956
- client,
957
- documentId,
958
- language.id,
959
- language.title,
960
- languageField,
961
- metadata2 == null ? void 0 : metadata2._createdAt,
962
- metadataId,
963
- schemaType,
964
- source,
965
- sourceLanguageId,
966
- toast,
967
- weakReferences,
968
- callback
969
- ]);
671
+ }, $[7] = callback, $[8] = client, $[9] = documentId, $[10] = language.id, $[11] = language.title, $[12] = languageField, $[13] = metadata2?._createdAt, $[14] = metadataId, $[15] = schemaType, $[16] = source, $[17] = sourceLanguageId, $[18] = toast, $[19] = weakReferences, $[20] = t3) : t3 = $[20];
672
+ const handleCreate = t3;
970
673
  let message;
971
- return current ? message = "Current document" : translation ? message = `Open ${language.title} translation` : translation || (message = `Create new ${language.title} translation`), /* @__PURE__ */ jsxRuntime.jsx(
972
- ui.Tooltip,
973
- {
974
- animate: !0,
975
- content: /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: message }) }),
976
- fallbackPlacements: ["right", "left"],
977
- placement: "top",
978
- portal: !0,
979
- children: /* @__PURE__ */ jsxRuntime.jsx(
980
- ui.Button,
981
- {
982
- onClick: translation ? handleOpen : handleCreate,
983
- mode: current && disabled ? "default" : "bleed",
984
- disabled,
985
- children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { gap: 3, align: "center", children: [
986
- disabled && !current ? /* @__PURE__ */ jsxRuntime.jsx(ui.Spinner, {}) : /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 2, children: translation ? /* @__PURE__ */ jsxRuntime.jsx(icons.SplitVerticalIcon, {}) : current ? /* @__PURE__ */ jsxRuntime.jsx(icons.CheckmarkIcon, {}) : /* @__PURE__ */ jsxRuntime.jsx(icons.AddIcon, {}) }),
987
- /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { flex: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: language.title }) }),
988
- /* @__PURE__ */ jsxRuntime.jsx(ui.Badge, { tone: disabled || current ? "default" : "primary", children: language.id })
989
- ] })
990
- }
991
- )
992
- }
993
- );
674
+ current ? message = "Current document" : translation ? message = `Open ${language.title} translation` : translation || (message = `Create new ${language.title} translation`);
675
+ let t4;
676
+ $[21] !== message ? (t4 = /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: message }) }), $[21] = message, $[22] = t4) : t4 = $[22];
677
+ let t5;
678
+ $[23] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = ["right", "left"], $[23] = t5) : t5 = $[23];
679
+ const t6 = translation ? handleOpen : handleCreate, t7 = current && disabled ? "default" : "bleed";
680
+ let t8;
681
+ $[24] !== current || $[25] !== disabled || $[26] !== translation ? (t8 = disabled && !current ? /* @__PURE__ */ jsx(Spinner, {}) : /* @__PURE__ */ jsx(Text, { size: 2, children: translation ? /* @__PURE__ */ jsx(SplitVerticalIcon, {}) : current ? /* @__PURE__ */ jsx(CheckmarkIcon, {}) : /* @__PURE__ */ jsx(AddIcon, {}) }), $[24] = current, $[25] = disabled, $[26] = translation, $[27] = t8) : t8 = $[27];
682
+ let t9;
683
+ $[28] !== language.title ? (t9 = /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }), $[28] = language.title, $[29] = t9) : t9 = $[29];
684
+ const t10 = disabled || current ? "default" : "primary";
685
+ let t11;
686
+ $[30] !== language.id || $[31] !== t10 ? (t11 = /* @__PURE__ */ jsx(Badge, { tone: t10, children: language.id }), $[30] = language.id, $[31] = t10, $[32] = t11) : t11 = $[32];
687
+ let t12;
688
+ $[33] !== t11 || $[34] !== t8 || $[35] !== t9 ? (t12 = /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
689
+ t8,
690
+ t9,
691
+ t11
692
+ ] }), $[33] = t11, $[34] = t8, $[35] = t9, $[36] = t12) : t12 = $[36];
693
+ let t13;
694
+ $[37] !== disabled || $[38] !== t12 || $[39] !== t6 || $[40] !== t7 ? (t13 = /* @__PURE__ */ jsx(Button, { onClick: t6, mode: t7, disabled, children: t12 }), $[37] = disabled, $[38] = t12, $[39] = t6, $[40] = t7, $[41] = t13) : t13 = $[41];
695
+ let t14;
696
+ return $[42] !== t13 || $[43] !== t4 ? (t14 = /* @__PURE__ */ jsx(Tooltip, { animate: !0, content: t4, fallbackPlacements: t5, placement: "top", portal: !0, children: t13 }), $[42] = t13, $[43] = t4, $[44] = t14) : t14 = $[44], t14;
994
697
  }
995
698
  function LanguagePatch(props) {
996
- const { language, source } = props, { apiVersion, languageField } = useDocumentInternationalizationContext(), disabled = props.disabled || !source, client = sanity.useClient({ apiVersion }), toast = ui.useToast(), handleClick = react.useCallback(() => {
699
+ const $ = c(21), {
700
+ language,
701
+ source
702
+ } = props, {
703
+ apiVersion,
704
+ languageField
705
+ } = useDocumentInternationalizationContext(), disabled = props.disabled || !source;
706
+ let t0;
707
+ $[0] !== apiVersion ? (t0 = {
708
+ apiVersion
709
+ }, $[0] = apiVersion, $[1] = t0) : t0 = $[1];
710
+ const client = useClient(t0), toast = useToast();
711
+ let t1;
712
+ $[2] !== client || $[3] !== language.id || $[4] !== language.title || $[5] !== languageField || $[6] !== source || $[7] !== toast ? (t1 = () => {
997
713
  if (!source)
998
714
  throw new Error("Cannot patch missing document");
999
715
  const currentId = source._id;
1000
- client.patch(currentId).set({ [languageField]: language.id }).commit().then(() => {
716
+ client.patch(currentId).set({
717
+ [languageField]: language.id
718
+ }).commit().then(() => {
1001
719
  toast.push({
1002
720
  title: `Set document language to ${language.title}`,
1003
721
  status: "success"
@@ -1006,152 +724,148 @@ function LanguagePatch(props) {
1006
724
  title: `Failed to set document language to ${language.title}`,
1007
725
  status: "error"
1008
726
  })));
1009
- }, [source, client, languageField, language, toast]);
1010
- return /* @__PURE__ */ jsxRuntime.jsx(
1011
- ui.Button,
1012
- {
1013
- mode: "bleed",
1014
- onClick: handleClick,
1015
- disabled,
1016
- justify: "flex-start",
1017
- children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { gap: 3, align: "center", children: [
1018
- /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 2, children: /* @__PURE__ */ jsxRuntime.jsx(icons.EditIcon, {}) }),
1019
- /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { flex: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: language.title }) }),
1020
- /* @__PURE__ */ jsxRuntime.jsx(ui.Badge, { children: language.id })
1021
- ] })
1022
- }
1023
- );
727
+ }, $[2] = client, $[3] = language.id, $[4] = language.title, $[5] = languageField, $[6] = source, $[7] = toast, $[8] = t1) : t1 = $[8];
728
+ const handleClick = t1;
729
+ let t2;
730
+ $[9] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = /* @__PURE__ */ jsx(Text, { size: 2, children: /* @__PURE__ */ jsx(EditIcon, {}) }), $[9] = t2) : t2 = $[9];
731
+ let t3;
732
+ $[10] !== language.title ? (t3 = /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Text, { children: language.title }) }), $[10] = language.title, $[11] = t3) : t3 = $[11];
733
+ let t4;
734
+ $[12] !== language.id ? (t4 = /* @__PURE__ */ jsx(Badge, { children: language.id }), $[12] = language.id, $[13] = t4) : t4 = $[13];
735
+ let t5;
736
+ $[14] !== t3 || $[15] !== t4 ? (t5 = /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
737
+ t2,
738
+ t3,
739
+ t4
740
+ ] }), $[14] = t3, $[15] = t4, $[16] = t5) : t5 = $[16];
741
+ let t6;
742
+ return $[17] !== disabled || $[18] !== handleClick || $[19] !== t5 ? (t6 = /* @__PURE__ */ jsx(Button, { mode: "bleed", onClick: handleClick, disabled, justify: "flex-start", children: t5 }), $[17] = disabled, $[18] = handleClick, $[19] = t5, $[20] = t6) : t6 = $[20], t6;
1024
743
  }
1025
- var ConstrainedBox = styledComponents.styled(ui.Box)`
1026
- max-width: 280px;
1027
- `;
1028
- function Warning({ children }) {
1029
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { tone: "caution", padding: 3, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { justify: "center", children: /* @__PURE__ */ jsxRuntime.jsx(ConstrainedBox, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, align: "center", children }) }) }) });
744
+ function ConstrainedBox(t0) {
745
+ const $ = c(3), {
746
+ children
747
+ } = t0;
748
+ let t1;
749
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
750
+ maxWidth: 280
751
+ }, $[0] = t1) : t1 = $[0];
752
+ let t2;
753
+ return $[1] !== children ? (t2 = /* @__PURE__ */ jsx(Box, { style: t1, children }), $[1] = children, $[2] = t2) : t2 = $[2], t2;
754
+ }
755
+ function Warning(t0) {
756
+ const $ = c(2), {
757
+ children
758
+ } = t0;
759
+ let t1;
760
+ return $[0] !== children ? (t1 = /* @__PURE__ */ jsx(Card, { tone: "caution", padding: 3, children: /* @__PURE__ */ jsx(Flex, { justify: "center", children: /* @__PURE__ */ jsx(ConstrainedBox, { children: /* @__PURE__ */ jsx(Text, { size: 1, align: "center", children }) }) }) }), $[0] = children, $[1] = t1) : t1 = $[1], t1;
1030
761
  }
1031
762
  function DocumentInternationalizationMenu(props) {
1032
- const { documentId } = props, schemaType = props.schemaType, { languageField, supportedLanguages } = useDocumentInternationalizationContext(), [query2, setQuery] = react.useState(""), handleQuery = react.useCallback((event) => {
763
+ const $ = c(36), {
764
+ documentId
765
+ } = props, schemaType = props.schemaType, {
766
+ languageField,
767
+ supportedLanguages
768
+ } = useDocumentInternationalizationContext(), [query2, setQuery] = useState("");
769
+ let t0;
770
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = (event) => {
1033
771
  event.currentTarget.value ? setQuery(event.currentTarget.value) : setQuery("");
1034
- }, []), [open, setOpen] = react.useState(!1), handleClick = react.useCallback(() => setOpen((o) => !o), []), [button, setButton] = react.useState(null), [popover, setPopover] = react.useState(null), handleClickOutside = react.useCallback(() => setOpen(!1), []);
1035
- ui.useClickOutside(handleClickOutside, [button, popover]);
1036
- const { data, loading, error } = useTranslationMetadata(documentId), metadata2 = Array.isArray(data) && data.length ? data[0] : null, metadataId = react.useMemo(() => {
1037
- var _a;
1038
- return loading ? null : (_a = metadata2 == null ? void 0 : metadata2._id) != null ? _a : uuid.uuid();
1039
- }, [loading, metadata2 == null ? void 0 : metadata2._id]), { draft, published } = sanity.useEditState(documentId, schemaType.name), source = draft || published, documentIsInOneMetadataDocument = react.useMemo(() => Array.isArray(data) && data.length <= 1, [data]), sourceLanguageId = source == null ? void 0 : source[languageField], sourceLanguageIsValid = supportedLanguages.some(
1040
- (l) => l.id === sourceLanguageId
1041
- ), allLanguagesAreValid = react.useMemo(() => {
1042
- const valid = supportedLanguages.every((l) => l.id && l.title);
1043
- return valid || console.warn(
1044
- 'Not all languages are valid. It should be an array of objects with an "id" and "title" property. Or a function that returns an array of objects with an "id" and "title" property.',
1045
- supportedLanguages
1046
- ), valid;
1047
- }, [supportedLanguages]), content = /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 1, children: error ? /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { tone: "critical", padding: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: "There was an error returning translations metadata" }) }) : /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 1, children: [
1048
- /* @__PURE__ */ jsxRuntime.jsx(
1049
- LanguageManage,
1050
- {
1051
- id: metadata2 == null ? void 0 : metadata2._id,
1052
- documentId,
1053
- metadataId,
1054
- schemaType,
1055
- sourceLanguageId
1056
- }
1057
- ),
1058
- supportedLanguages.length > 4 ? /* @__PURE__ */ jsxRuntime.jsx(
1059
- ui.TextInput,
1060
- {
1061
- onChange: handleQuery,
1062
- value: query2,
1063
- placeholder: "Filter languages"
1064
- }
1065
- ) : null,
1066
- supportedLanguages.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1067
- loading ? null : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1068
- data && documentIsInOneMetadataDocument ? null : /* @__PURE__ */ jsxRuntime.jsx(Warning, { children: "This document has been found in more than one Translations Metadata documents" }),
1069
- allLanguagesAreValid ? null : /* @__PURE__ */ jsxRuntime.jsx(Warning, { children: "Not all language objects are valid. See the console." }),
1070
- sourceLanguageId ? null : /* @__PURE__ */ jsxRuntime.jsxs(Warning, { children: [
1071
- "Choose a language to apply to",
1072
- " ",
1073
- /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "this Document" })
772
+ }, $[0] = t0) : t0 = $[0];
773
+ const handleQuery = t0, [open, setOpen] = useState(!1);
774
+ let t1;
775
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = () => setOpen(_temp$3), $[1] = t1) : t1 = $[1];
776
+ const handleClick = t1, buttonRef = useRef(null), popoverRef = useRef(null);
777
+ let t2;
778
+ $[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = () => setOpen(!1), $[2] = t2) : t2 = $[2];
779
+ const handleClickOutside = t2;
780
+ let t3;
781
+ $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = () => [buttonRef.current, popoverRef.current], $[3] = t3) : t3 = $[3], useClickOutsideEvent(handleClickOutside, t3);
782
+ const {
783
+ data,
784
+ loading,
785
+ error
786
+ } = useTranslationMetadata(documentId), metadata2 = Array.isArray(data) && data.length ? data[0] : null;
787
+ let t4;
788
+ bb0: {
789
+ if (loading) {
790
+ t4 = null;
791
+ break bb0;
792
+ }
793
+ let t52;
794
+ $[4] !== metadata2?._id ? (t52 = metadata2?._id ?? uuid(), $[4] = metadata2?._id, $[5] = t52) : t52 = $[5], t4 = t52;
795
+ }
796
+ const metadataId = t4, {
797
+ draft,
798
+ published
799
+ } = useEditState(documentId, schemaType.name), source = draft || published, documentIsInOneMetadataDocument = Array.isArray(data) && data.length <= 1, rawLanguageValue = source?.[languageField], sourceLanguageId = typeof rawLanguageValue == "string" ? rawLanguageValue : void 0;
800
+ let t5;
801
+ if ($[6] !== sourceLanguageId || $[7] !== supportedLanguages) {
802
+ let t62;
803
+ $[9] !== sourceLanguageId ? (t62 = (l) => l.id === sourceLanguageId, $[9] = sourceLanguageId, $[10] = t62) : t62 = $[10], t5 = supportedLanguages.some(t62), $[6] = sourceLanguageId, $[7] = supportedLanguages, $[8] = t5;
804
+ } else
805
+ t5 = $[8];
806
+ const sourceLanguageIsValid = t5;
807
+ let t6;
808
+ $[11] !== supportedLanguages ? (t6 = supportedLanguages.every(_temp2$1), $[11] = supportedLanguages, $[12] = t6) : t6 = $[12];
809
+ const valid = t6;
810
+ valid || console.warn('Not all languages are valid. It should be an array of objects with an "id" and "title" property. Or a function that returns an array of objects with an "id" and "title" property.', supportedLanguages);
811
+ const allLanguagesAreValid = valid;
812
+ let t7;
813
+ $[13] !== allLanguagesAreValid || $[14] !== data || $[15] !== documentId || $[16] !== documentIsInOneMetadataDocument || $[17] !== error || $[18] !== loading || $[19] !== metadata2 || $[20] !== metadataId || $[21] !== query2 || $[22] !== schemaType || $[23] !== source || $[24] !== sourceLanguageId || $[25] !== sourceLanguageIsValid || $[26] !== supportedLanguages ? (t7 = /* @__PURE__ */ jsx(Box, { padding: 1, children: error ? /* @__PURE__ */ jsx(Card, { tone: "critical", padding: 1, children: /* @__PURE__ */ jsx(Text, { children: "There was an error returning translations metadata" }) }) : /* @__PURE__ */ jsxs(Stack, { space: 1, children: [
814
+ /* @__PURE__ */ jsx(LanguageManage, { id: metadata2?._id, documentId, metadataId, schemaType, sourceLanguageId }),
815
+ supportedLanguages.length > 4 ? /* @__PURE__ */ jsx(TextInput, { onChange: handleQuery, value: query2, placeholder: "Filter languages" }) : null,
816
+ supportedLanguages.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
817
+ loading ? null : /* @__PURE__ */ jsxs(Fragment, { children: [
818
+ data && documentIsInOneMetadataDocument ? null : /* @__PURE__ */ jsx(Warning, { children: "This document has been found in more than one Translations Metadata document" }),
819
+ allLanguagesAreValid ? null : /* @__PURE__ */ jsx(Warning, { children: "Not all language objects are valid. See the console." }),
820
+ sourceLanguageId ? null : /* @__PURE__ */ jsxs(Warning, { children: [
821
+ "Choose a language to apply to ",
822
+ /* @__PURE__ */ jsx("strong", { children: "this Document" })
1074
823
  ] }),
1075
- sourceLanguageId && !sourceLanguageIsValid ? /* @__PURE__ */ jsxRuntime.jsxs(Warning, { children: [
824
+ sourceLanguageId && !sourceLanguageIsValid ? /* @__PURE__ */ jsxs(Warning, { children: [
1076
825
  "Select a supported language. Current language value:",
1077
826
  " ",
1078
- /* @__PURE__ */ jsxRuntime.jsx("code", { children: sourceLanguageId })
827
+ /* @__PURE__ */ jsx("code", { children: sourceLanguageId })
1079
828
  ] }) : null
1080
829
  ] }),
1081
- supportedLanguages.filter((language) => query2 ? language.title.toLowerCase().includes(query2.toLowerCase()) : !0).map(
1082
- (language) => {
1083
- var _a;
1084
- return !loading && sourceLanguageId && sourceLanguageIsValid ? (
1085
- // Button to duplicate this document to a new translation
1086
- // And either create or update the metadata document
1087
- /* @__PURE__ */ jsxRuntime.jsx(
1088
- LanguageOption,
1089
- {
1090
- language,
1091
- schemaType,
1092
- documentId,
1093
- disabled: loading || !allLanguagesAreValid,
1094
- current: language.id === sourceLanguageId,
1095
- metadata: metadata2,
1096
- metadataId,
1097
- source,
1098
- sourceLanguageId
1099
- },
1100
- language.id
1101
- )
1102
- ) : (
1103
- // Button to set a language field on *this* document
1104
- /* @__PURE__ */ jsxRuntime.jsx(
1105
- LanguagePatch,
1106
- {
1107
- source,
1108
- language,
1109
- disabled: (_a = loading || !allLanguagesAreValid || (metadata2 == null ? void 0 : metadata2.translations.filter((t) => {
1110
- var _a2;
1111
- return ((_a2 = t == null ? void 0 : t.value) == null ? void 0 : _a2._ref) !== documentId;
1112
- }).some((t) => t._key === language.id))) != null ? _a : !1
1113
- },
1114
- language.id
1115
- )
1116
- );
1117
- }
1118
- )
830
+ supportedLanguages.filter((language) => query2 ? language.title.toLowerCase().includes(query2.toLowerCase()) : !0).map((language_0) => !loading && sourceLanguageId && sourceLanguageIsValid ? /* @__PURE__ */ jsx(LanguageOption, { language: language_0, schemaType, documentId, disabled: !allLanguagesAreValid, current: language_0.id === sourceLanguageId, metadata: metadata2, metadataId, source, sourceLanguageId }, language_0.id) : /* @__PURE__ */ jsx(LanguagePatch, { source, language: language_0, disabled: (loading || !allLanguagesAreValid || metadata2?.translations.filter((t) => t?.value?._ref !== documentId).some((t_0) => t_0[LANGUAGE_FIELD_NAME] === language_0.id)) ?? !1 }, language_0.id))
1119
831
  ] }) : null
1120
- ] }) }), issueWithTranslations = !loading && sourceLanguageId && !sourceLanguageIsValid;
1121
- return !documentId || !schemaType || !schemaType.name ? null : /* @__PURE__ */ jsxRuntime.jsx(
1122
- ui.Popover,
1123
- {
1124
- animate: !0,
1125
- constrainSize: !0,
1126
- content,
1127
- open,
1128
- portal: !0,
1129
- ref: setPopover,
1130
- overflow: "auto",
1131
- tone: "default",
1132
- children: /* @__PURE__ */ jsxRuntime.jsx(
1133
- ui.Button,
1134
- {
1135
- text: "Translations",
1136
- mode: "bleed",
1137
- disabled: !source,
1138
- tone: !source || loading || !issueWithTranslations ? void 0 : "caution",
1139
- icon: icons.TranslateIcon,
1140
- onClick: handleClick,
1141
- ref: setButton,
1142
- selected: open
1143
- }
1144
- )
1145
- }
1146
- );
832
+ ] }) }), $[13] = allLanguagesAreValid, $[14] = data, $[15] = documentId, $[16] = documentIsInOneMetadataDocument, $[17] = error, $[18] = loading, $[19] = metadata2, $[20] = metadataId, $[21] = query2, $[22] = schemaType, $[23] = source, $[24] = sourceLanguageId, $[25] = sourceLanguageIsValid, $[26] = supportedLanguages, $[27] = t7) : t7 = $[27];
833
+ const content = t7, issueWithTranslations = !loading && sourceLanguageId && !sourceLanguageIsValid;
834
+ if (!documentId || !schemaType || !schemaType.name)
835
+ return null;
836
+ const t8 = !source, t9 = !source || loading || !issueWithTranslations ? void 0 : "caution";
837
+ let t10;
838
+ $[28] !== open || $[29] !== t8 || $[30] !== t9 ? (t10 = /* @__PURE__ */ jsx(Button, { text: "Translations", mode: "bleed", disabled: t8, tone: t9, icon: TranslateIcon, onClick: handleClick, ref: buttonRef, selected: open }), $[28] = open, $[29] = t8, $[30] = t9, $[31] = t10) : t10 = $[31];
839
+ let t11;
840
+ return $[32] !== content || $[33] !== open || $[34] !== t10 ? (t11 = /* @__PURE__ */ jsx(Popover, { animate: !0, constrainSize: !0, content, open, portal: !0, ref: popoverRef, overflow: "auto", tone: "default", children: t10 }), $[32] = content, $[33] = open, $[34] = t10, $[35] = t11) : t11 = $[35], t11;
841
+ }
842
+ function _temp2$1(l_0) {
843
+ return l_0.id && l_0.title;
1147
844
  }
1148
- const DeleteMetadataAction = (props) => {
1149
- const { id: documentId, published, draft, onComplete } = props, doc = draft || published, [isDialogOpen, setDialogOpen] = react.useState(!1), onClose = react.useCallback(() => setDialogOpen(!1), []), translations = react.useMemo(
1150
- () => doc && Array.isArray(doc[TRANSLATIONS_ARRAY_NAME]) ? doc[TRANSLATIONS_ARRAY_NAME] : [],
1151
- [doc]
1152
- ), toast = ui.useToast(), client = sanity.useClient({ apiVersion: API_VERSION }), onProceed = react.useCallback(() => {
845
+ function _temp$3(o) {
846
+ return !o;
847
+ }
848
+ const useDeleteMetadataAction = (props) => {
849
+ const $ = c(17), {
850
+ id: documentId,
851
+ published,
852
+ draft
853
+ } = props, doc = draft || published, [isDialogOpen, setDialogOpen] = useState(!1);
854
+ let t0;
855
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = () => setDialogOpen(!1), $[0] = t0) : t0 = $[0];
856
+ const onClose = t0;
857
+ let t1;
858
+ $[1] !== doc ? (t1 = doc && Array.isArray(doc[TRANSLATIONS_ARRAY_NAME]) ? doc[TRANSLATIONS_ARRAY_NAME] : [], $[1] = doc, $[2] = t1) : t1 = $[2];
859
+ const translations = t1, toast = useToast();
860
+ let t2;
861
+ $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = {
862
+ apiVersion: API_VERSION
863
+ }, $[3] = t2) : t2 = $[3];
864
+ const client = useClient(t2);
865
+ let t3;
866
+ $[4] !== client || $[5] !== documentId || $[6] !== toast || $[7] !== translations ? (t3 = () => {
1153
867
  const tx = client.transaction();
1154
- tx.patch(documentId, (patch) => patch.unset([TRANSLATIONS_ARRAY_NAME])), translations.length > 0 && translations.forEach((translation) => {
868
+ tx.patch(documentId, _temp$2), translations.length > 0 && translations.forEach((translation) => {
1155
869
  tx.delete(translation.value._ref), tx.delete(`drafts.${translation.value._ref}`);
1156
870
  }), tx.delete(documentId), tx.delete(`drafts.${documentId}`), tx.commit().then(() => {
1157
871
  onClose(), toast.push({
@@ -1165,113 +879,168 @@ const DeleteMetadataAction = (props) => {
1165
879
  description: err.message
1166
880
  });
1167
881
  });
1168
- }, [client, translations, documentId, onClose, toast]);
1169
- return {
882
+ }, $[4] = client, $[5] = documentId, $[6] = toast, $[7] = translations, $[8] = t3) : t3 = $[8];
883
+ const onProceed = t3, t4 = !doc || !translations.length;
884
+ let t5;
885
+ $[9] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = () => {
886
+ setDialogOpen(!0);
887
+ }, $[9] = t5) : t5 = $[9];
888
+ let t6;
889
+ $[10] !== isDialogOpen || $[11] !== onProceed || $[12] !== translations ? (t6 = isDialogOpen && {
890
+ type: "confirm",
891
+ onCancel: onClose,
892
+ onConfirm: () => {
893
+ onProceed(), onClose();
894
+ },
895
+ tone: "critical",
896
+ message: translations.length === 1 ? "Delete 1 translation and this document" : `Delete all ${translations.length} translations and this document`
897
+ }, $[10] = isDialogOpen, $[11] = onProceed, $[12] = translations, $[13] = t6) : t6 = $[13];
898
+ let t7;
899
+ return $[14] !== t4 || $[15] !== t6 ? (t7 = {
1170
900
  label: "Delete all translations",
1171
- disabled: !doc || !translations.length,
1172
- icon: icons.TrashIcon,
901
+ disabled: t4,
902
+ icon: TrashIcon,
1173
903
  tone: "critical",
1174
- onHandle: () => {
1175
- setDialogOpen(!0);
1176
- },
1177
- dialog: isDialogOpen && {
1178
- type: "confirm",
1179
- onCancel: onComplete,
1180
- onConfirm: () => {
1181
- onProceed(), onComplete();
1182
- },
1183
- tone: "critical",
1184
- message: translations.length === 1 ? "Delete 1 translation and this document" : `Delete all ${translations.length} translations and this document`
1185
- }
1186
- };
904
+ onHandle: t5,
905
+ dialog: t6
906
+ }, $[14] = t4, $[15] = t6, $[16] = t7) : t7 = $[16], t7;
1187
907
  };
908
+ function _temp$2(patch) {
909
+ return patch.unset([TRANSLATIONS_ARRAY_NAME]);
910
+ }
1188
911
  function LanguageBadge(props) {
1189
- var _a, _b;
1190
- const source = (props == null ? void 0 : props.draft) || (props == null ? void 0 : props.published), { languageField, supportedLanguages } = useDocumentInternationalizationContext(), languageId = source == null ? void 0 : source[languageField];
1191
- if (!languageId)
912
+ const source = props?.draft || props?.published, {
913
+ languageField,
914
+ supportedLanguages
915
+ } = useDocumentInternationalizationContext(), languageId = source?.[languageField];
916
+ if (!languageId || typeof languageId != "string")
1192
917
  return null;
1193
918
  const language = Array.isArray(supportedLanguages) ? supportedLanguages.find((l) => l.id === languageId) : null;
1194
919
  return {
1195
- label: (_a = language == null ? void 0 : language.id) != null ? _a : String(languageId),
1196
- title: (_b = language == null ? void 0 : language.title) != null ? _b : void 0,
920
+ label: language?.id ?? languageId,
921
+ title: language?.title ?? void 0,
1197
922
  color: "primary"
1198
923
  };
1199
924
  }
1200
925
  function DocumentCheck(props) {
1201
- const {
926
+ const $ = c(25), {
1202
927
  id,
1203
928
  onCheckComplete,
1204
929
  addInvalidId,
1205
930
  removeInvalidId,
1206
931
  addDraftId,
1207
932
  removeDraftId
1208
- } = props, editState = sanity.useEditState(id, ""), { isValidating, validation } = sanity.useValidationStatus(id, ""), schema = sanity.useSchema(), validationHasErrors = react.useMemo(() => !isValidating && validation.length > 0 && validation.some((item) => item.level === "error"), [isValidating, validation]);
1209
- if (react.useEffect(() => {
1210
- validationHasErrors ? addInvalidId(id) : removeInvalidId(id), editState.draft ? addDraftId(id) : removeDraftId(id), isValidating || onCheckComplete(id);
1211
- }, [
1212
- addDraftId,
1213
- addInvalidId,
1214
- editState.draft,
1215
- id,
933
+ } = props, editState = useEditState(id, ""), documentType = editState.draft?._type ?? editState.published?._type ?? "", {
1216
934
  isValidating,
1217
- onCheckComplete,
1218
- removeDraftId,
1219
- removeInvalidId,
1220
- validationHasErrors
1221
- ]), !editState.draft)
935
+ validation: t0
936
+ } = useValidationStatus(id, documentType, !1);
937
+ let t1;
938
+ $[0] !== t0 ? (t1 = t0 === void 0 ? [] : t0, $[0] = t0, $[1] = t1) : t1 = $[1];
939
+ const validation = t1, schema = useSchema();
940
+ let t2;
941
+ $[2] !== isValidating || $[3] !== validation ? (t2 = !isValidating && validation.some(_temp$1), $[2] = isValidating, $[3] = validation, $[4] = t2) : t2 = $[4];
942
+ const validationHasErrors = t2;
943
+ let t3, t4;
944
+ if ($[5] !== addDraftId || $[6] !== addInvalidId || $[7] !== editState.draft || $[8] !== id || $[9] !== isValidating || $[10] !== onCheckComplete || $[11] !== removeDraftId || $[12] !== removeInvalidId || $[13] !== validationHasErrors ? (t3 = () => {
945
+ validationHasErrors ? addInvalidId(id) : removeInvalidId(id), editState.draft ? addDraftId(id) : removeDraftId(id), isValidating || onCheckComplete(id);
946
+ }, t4 = [addDraftId, addInvalidId, editState.draft, id, isValidating, onCheckComplete, removeDraftId, removeInvalidId, validationHasErrors], $[5] = addDraftId, $[6] = addInvalidId, $[7] = editState.draft, $[8] = id, $[9] = isValidating, $[10] = onCheckComplete, $[11] = removeDraftId, $[12] = removeInvalidId, $[13] = validationHasErrors, $[14] = t3, $[15] = t4) : (t3 = $[14], t4 = $[15]), useEffect(t3, t4), !editState.draft)
1222
947
  return null;
1223
- const schemaType = schema.get(editState.draft._type);
1224
- return /* @__PURE__ */ jsxRuntime.jsx(
1225
- ui.Card,
1226
- {
1227
- border: !0,
1228
- padding: 2,
1229
- tone: validationHasErrors ? "critical" : "positive",
1230
- children: editState.draft && schemaType ? /* @__PURE__ */ jsxRuntime.jsx(
1231
- sanity.Preview,
1232
- {
1233
- layout: "default",
1234
- value: editState.draft,
1235
- schemaType
1236
- }
1237
- ) : /* @__PURE__ */ jsxRuntime.jsx(ui.Spinner, {})
1238
- }
1239
- );
948
+ let t5;
949
+ $[16] !== editState.draft._type || $[17] !== schema ? (t5 = schema.get(editState.draft._type), $[16] = editState.draft._type, $[17] = schema, $[18] = t5) : t5 = $[18];
950
+ const schemaType = t5, t6 = validationHasErrors ? "critical" : "positive";
951
+ let t7;
952
+ $[19] !== editState.draft || $[20] !== schemaType ? (t7 = editState.draft && schemaType ? /* @__PURE__ */ jsx(Preview, { layout: "default", value: editState.draft, schemaType }) : /* @__PURE__ */ jsx(Spinner, {}), $[19] = editState.draft, $[20] = schemaType, $[21] = t7) : t7 = $[21];
953
+ let t8;
954
+ return $[22] !== t6 || $[23] !== t7 ? (t8 = /* @__PURE__ */ jsx(Card, { border: !0, padding: 2, tone: t6, children: t7 }), $[22] = t6, $[23] = t7, $[24] = t8) : t8 = $[24], t8;
955
+ }
956
+ function _temp$1(item) {
957
+ return item.level === "error";
1240
958
  }
1241
959
  function InfoIcon(props) {
1242
- const { text, icon, tone, children } = props;
1243
- return /* @__PURE__ */ jsxRuntime.jsx(
1244
- ui.Tooltip,
1245
- {
1246
- animate: !0,
1247
- portal: !0,
1248
- content: children ? /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, children: text }) }),
1249
- children: /* @__PURE__ */ jsxRuntime.jsx(sanity.TextWithTone, { tone, size: 1, children: /* @__PURE__ */ jsxRuntime.jsx(icon, {}) })
1250
- }
1251
- );
960
+ const $ = c(11), {
961
+ text,
962
+ icon,
963
+ tone,
964
+ children
965
+ } = props, Icon = icon;
966
+ let t0;
967
+ $[0] !== children || $[1] !== text ? (t0 = children ? /* @__PURE__ */ jsx(Fragment, { children }) : /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: text }) }), $[0] = children, $[1] = text, $[2] = t0) : t0 = $[2];
968
+ let t1;
969
+ $[3] !== Icon ? (t1 = /* @__PURE__ */ jsx(Icon, {}), $[3] = Icon, $[4] = t1) : t1 = $[4];
970
+ let t2;
971
+ $[5] !== t1 || $[6] !== tone ? (t2 = /* @__PURE__ */ jsx(TextWithTone, { tone, size: 1, children: t1 }), $[5] = t1, $[6] = tone, $[7] = t2) : t2 = $[7];
972
+ let t3;
973
+ return $[8] !== t0 || $[9] !== t2 ? (t3 = /* @__PURE__ */ jsx(Tooltip, { animate: !0, portal: !0, content: t0, children: t2 }), $[8] = t0, $[9] = t2, $[10] = t3) : t3 = $[10], t3;
1252
974
  }
1253
975
  function Info() {
1254
- return /* @__PURE__ */ jsxRuntime.jsx(InfoIcon, { icon: icons.InfoOutlineIcon, tone: "primary", children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { padding: 3, space: 4, style: { maxWidth: 250 }, children: [
1255
- /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, children: "Bulk publishing uses the Scheduling API." }) }),
1256
- /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, children: "Customized Document Actions in the Studio will not execute. Webhooks will execute." }) }),
1257
- /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, children: "Validation is checked before rendering the button below, but the Scheduling API will not check for \u2013 or enforce \u2013 validation." }) })
1258
- ] }) });
976
+ const $ = c(4);
977
+ let t0;
978
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
979
+ maxWidth: 250
980
+ }, $[0] = t0) : t0 = $[0];
981
+ let t1;
982
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Bulk publishing uses the Scheduling API." }) }), $[1] = t1) : t1 = $[1];
983
+ let t2;
984
+ $[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Customized Document Actions in the Studio will not execute. Webhooks will execute." }) }), $[2] = t2) : t2 = $[2];
985
+ let t3;
986
+ return $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = /* @__PURE__ */ jsx(InfoIcon, { icon: InfoOutlineIcon, tone: "primary", children: /* @__PURE__ */ jsxs(Stack, { padding: 3, space: 4, style: t0, children: [
987
+ t1,
988
+ t2,
989
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Validation is checked before rendering the button below, but the Scheduling API will not check for \u2013 or enforce \u2013 validation." }) })
990
+ ] }) }), $[3] = t3) : t3 = $[3], t3;
1259
991
  }
1260
992
  function BulkPublish(props) {
1261
- const { translations } = props, client = sanity.useClient({ apiVersion: API_VERSION }), { projectId, dataset } = sanity.useWorkspace(), toast = ui.useToast(), [invalidIds, setInvalidIds] = react.useState(null), [checkedIds, setCheckedIds] = react.useState([]), onCheckComplete = react.useCallback((id) => {
993
+ const $ = c(23), {
994
+ translations
995
+ } = props;
996
+ let t0;
997
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
998
+ apiVersion: API_VERSION
999
+ }, $[0] = t0) : t0 = $[0];
1000
+ const client = useClient(t0), {
1001
+ projectId,
1002
+ dataset
1003
+ } = useWorkspace(), toast = useToast(), [invalidIds, setInvalidIds] = useState(null);
1004
+ let t1;
1005
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = [], $[1] = t1) : t1 = $[1];
1006
+ const [checkedIds, setCheckedIds] = useState(t1);
1007
+ let t2;
1008
+ $[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = (id) => {
1262
1009
  setCheckedIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
1263
- }, []), [open, setOpen] = react.useState(!1), onOpen = react.useCallback(() => setOpen(!0), []), onClose = react.useCallback(() => setOpen(!1), []), addInvalidId = react.useCallback((id) => {
1264
- setInvalidIds((ids) => ids ? Array.from(/* @__PURE__ */ new Set([...ids, id])) : [id]);
1265
- }, []), removeInvalidId = react.useCallback((id) => {
1266
- setInvalidIds((ids) => ids ? ids.filter((i) => i !== id) : []);
1267
- }, []), [draftIds, setDraftIds] = react.useState([]), addDraftId = react.useCallback((id) => {
1268
- setDraftIds((ids) => Array.from(/* @__PURE__ */ new Set([...ids, id])));
1269
- }, []), removeDraftId = react.useCallback((id) => {
1270
- setDraftIds((ids) => ids.filter((i) => i !== id));
1271
- }, []), handleBulkPublish = react.useCallback(() => {
1272
- const body = translations.map((translation) => ({
1273
- documentId: translation.value._ref
1274
- }));
1010
+ }, $[2] = t2) : t2 = $[2];
1011
+ const onCheckComplete = t2, [open, setOpen] = useState(!1);
1012
+ let t3;
1013
+ $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = () => setOpen(!0), $[3] = t3) : t3 = $[3];
1014
+ const onOpen = t3;
1015
+ let t4;
1016
+ $[4] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t4 = () => setOpen(!1), $[4] = t4) : t4 = $[4];
1017
+ const onClose = t4;
1018
+ let t5;
1019
+ $[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = (id_0) => {
1020
+ setInvalidIds((ids_0) => ids_0 ? Array.from(/* @__PURE__ */ new Set([...ids_0, id_0])) : [id_0]);
1021
+ }, $[5] = t5) : t5 = $[5];
1022
+ const addInvalidId = t5;
1023
+ let t6;
1024
+ $[6] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t6 = (id_1) => {
1025
+ setInvalidIds((ids_1) => ids_1 ? ids_1.filter((i) => i !== id_1) : []);
1026
+ }, $[6] = t6) : t6 = $[6];
1027
+ const removeInvalidId = t6;
1028
+ let t7;
1029
+ $[7] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t7 = [], $[7] = t7) : t7 = $[7];
1030
+ const [draftIds, setDraftIds] = useState(t7);
1031
+ let t8;
1032
+ $[8] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t8 = (id_2) => {
1033
+ setDraftIds((ids_2) => Array.from(/* @__PURE__ */ new Set([...ids_2, id_2])));
1034
+ }, $[8] = t8) : t8 = $[8];
1035
+ const addDraftId = t8;
1036
+ let t9;
1037
+ $[9] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t9 = (id_3) => {
1038
+ setDraftIds((ids_3) => ids_3.filter((i_0) => i_0 !== id_3));
1039
+ }, $[9] = t9) : t9 = $[9];
1040
+ const removeDraftId = t9;
1041
+ let t10;
1042
+ $[10] !== client || $[11] !== dataset || $[12] !== projectId || $[13] !== toast || $[14] !== translations ? (t10 = () => {
1043
+ const body = translations.map(_temp);
1275
1044
  client.request({
1276
1045
  uri: `/publish/${projectId}/${dataset}`,
1277
1046
  method: "POST",
@@ -1289,328 +1058,297 @@ function BulkPublish(props) {
1289
1058
  description: "Bulk publish failed"
1290
1059
  });
1291
1060
  });
1292
- }, [translations, client, projectId, dataset, toast]), disabled = (
1293
- // Not all documents have been checked
1294
- checkedIds.length !== translations.length || // Some document(s) are invalid
1295
- !!(invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0) || // No documents are drafts
1296
- !draftIds.length
1297
- );
1298
- return (translations == null ? void 0 : translations.length) > 0 ? /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { padding: 4, border: !0, radius: 2, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 3, children: [
1299
- /* @__PURE__ */ jsxRuntime.jsxs(ui.Inline, { space: 3, children: [
1300
- /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { weight: "bold", size: 1, children: "Bulk publishing" }),
1301
- /* @__PURE__ */ jsxRuntime.jsx(Info, {})
1061
+ }, $[10] = client, $[11] = dataset, $[12] = projectId, $[13] = toast, $[14] = translations, $[15] = t10) : t10 = $[15];
1062
+ const handleBulkPublish = t10, disabled = checkedIds.length !== translations.length || !!(invalidIds && invalidIds?.length > 0) || !draftIds.length;
1063
+ let t11;
1064
+ return $[16] !== disabled || $[17] !== draftIds || $[18] !== handleBulkPublish || $[19] !== invalidIds || $[20] !== open || $[21] !== translations ? (t11 = translations?.length > 0 ? /* @__PURE__ */ jsx(Card, { padding: 4, border: !0, radius: 2, children: /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
1065
+ /* @__PURE__ */ jsxs(Inline, { space: 3, children: [
1066
+ /* @__PURE__ */ jsx(Text, { weight: "bold", size: 1, children: "Bulk publishing" }),
1067
+ /* @__PURE__ */ jsx(Info, {})
1302
1068
  ] }),
1303
- /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { children: /* @__PURE__ */ jsxRuntime.jsx(
1304
- ui.Button,
1305
- {
1306
- onClick: onOpen,
1307
- text: "Prepare bulk publishing",
1308
- mode: "ghost"
1309
- }
1310
- ) }),
1311
- open && /* @__PURE__ */ jsxRuntime.jsx(
1312
- ui.Dialog,
1313
- {
1314
- animate: !0,
1315
- header: "Bulk publishing",
1316
- id: "bulk-publish-dialog",
1317
- onClose,
1318
- zOffset: 1e3,
1319
- width: 3,
1320
- children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 4, padding: 4, children: [
1321
- draftIds.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 2, children: [
1322
- /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, children: [
1323
- "There",
1324
- " ",
1325
- draftIds.length === 1 ? "is 1 draft document" : `are ${draftIds.length} draft documents`,
1326
- "."
1327
- ] }),
1328
- invalidIds && invalidIds.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(sanity.TextWithTone, { tone: "critical", size: 1, children: [
1329
- invalidIds && invalidIds.length === 1 ? "1 draft document has" : `${invalidIds && invalidIds.length} draft documents have`,
1330
- " ",
1331
- "validation issues that must addressed first"
1332
- ] }) : /* @__PURE__ */ jsxRuntime.jsx(sanity.TextWithTone, { tone: "positive", size: 1, children: "All drafts are valid and can be bulk published" })
1333
- ] }) : null,
1334
- /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { space: 1, children: translations.filter((translation) => {
1335
- var _a;
1336
- return (_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref;
1337
- }).map((translation) => /* @__PURE__ */ jsxRuntime.jsx(
1338
- DocumentCheck,
1339
- {
1340
- id: translation.value._ref,
1341
- onCheckComplete,
1342
- addInvalidId,
1343
- removeInvalidId,
1344
- addDraftId,
1345
- removeDraftId
1346
- },
1347
- translation._key
1348
- )) }),
1349
- draftIds.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
1350
- ui.Button,
1351
- {
1352
- mode: "ghost",
1353
- tone: invalidIds && (invalidIds == null ? void 0 : invalidIds.length) > 0 ? "caution" : "positive",
1354
- text: draftIds.length === 1 ? "Publish draft document" : `Bulk publish ${draftIds.length} draft documents`,
1355
- onClick: handleBulkPublish,
1356
- disabled
1357
- }
1358
- ) : /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: "No draft documents to publish" })
1359
- ] })
1360
- }
1361
- )
1362
- ] }) }) : null;
1069
+ /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(Button, { onClick: onOpen, text: "Prepare bulk publishing", mode: "ghost" }) }),
1070
+ open && /* @__PURE__ */ jsx(Dialog, { animate: !0, header: "Bulk publishing", id: "bulk-publish-dialog", onClose, zOffset: 1e3, width: 3, children: /* @__PURE__ */ jsxs(Stack, { space: 4, padding: 4, children: [
1071
+ draftIds.length > 0 ? /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
1072
+ /* @__PURE__ */ jsxs(Text, { size: 1, children: [
1073
+ "There",
1074
+ " ",
1075
+ draftIds.length === 1 ? "is 1 draft document" : `are ${draftIds.length} draft documents`,
1076
+ "."
1077
+ ] }),
1078
+ invalidIds && invalidIds.length > 0 ? /* @__PURE__ */ jsxs(TextWithTone, { tone: "critical", size: 1, children: [
1079
+ invalidIds.length === 1 ? "1 draft document has" : `${invalidIds.length} draft documents have`,
1080
+ " ",
1081
+ "validation issues that must be addressed first"
1082
+ ] }) : /* @__PURE__ */ jsx(TextWithTone, { tone: "positive", size: 1, children: "All drafts are valid and can be bulk published" })
1083
+ ] }) : null,
1084
+ /* @__PURE__ */ jsx(Stack, { space: 1, children: translations.filter(_temp2).map((translation_1) => /* @__PURE__ */ jsx(DocumentCheck, { id: translation_1.value._ref, onCheckComplete, addInvalidId, removeInvalidId, addDraftId, removeDraftId }, translation_1._key)) }),
1085
+ draftIds.length > 0 ? /* @__PURE__ */ jsx(Button, { mode: "ghost", tone: invalidIds && invalidIds?.length > 0 ? "caution" : "positive", text: draftIds.length === 1 ? "Publish draft document" : `Bulk publish ${draftIds.length} draft documents`, onClick: handleBulkPublish, disabled }) : /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "No draft documents to publish" })
1086
+ ] }) })
1087
+ ] }) }) : null, $[16] = disabled, $[17] = draftIds, $[18] = handleBulkPublish, $[19] = invalidIds, $[20] = open, $[21] = translations, $[22] = t11) : t11 = $[22], t11;
1088
+ }
1089
+ function _temp2(translation_0) {
1090
+ return translation_0?.value?._ref;
1091
+ }
1092
+ function _temp(translation) {
1093
+ return {
1094
+ documentId: translation.value._ref
1095
+ };
1363
1096
  }
1364
1097
  function ReferencePatcher(props) {
1365
- const { translation, documentType, metadataId } = props, editState = sanity.useEditState(translation.value._ref, documentType), client = sanity.useClient({ apiVersion: API_VERSION }), { onChange } = structure.useDocumentPane();
1366
- return react.useEffect(() => {
1367
- if (
1368
- // We have a reference
1369
- translation.value._ref && // It's still weak and not-yet-strengthened
1370
- translation.value._weak && // We also want to keep this check because maybe the user *configured* weak refs
1371
- translation.value._strengthenOnPublish && // The referenced document has just been published
1372
- !editState.draft && editState.published && editState.ready
1373
- ) {
1374
- const referencePathBase = [
1375
- "translations",
1376
- { _key: translation._key },
1377
- "value"
1378
- ];
1379
- onChange(
1380
- new sanity.PatchEvent([
1381
- sanity.unset([...referencePathBase, "_weak"]),
1382
- sanity.unset([...referencePathBase, "_strengthenOnPublish"])
1383
- ])
1384
- );
1098
+ const $ = c(14), {
1099
+ translation,
1100
+ documentType,
1101
+ metadataId
1102
+ } = props, editState = useEditState(translation.value._ref, documentType);
1103
+ let t0;
1104
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
1105
+ apiVersion: API_VERSION
1106
+ }, $[0] = t0) : t0 = $[0];
1107
+ const client = useClient(t0), {
1108
+ onChange
1109
+ } = useDocumentPane();
1110
+ let t1;
1111
+ $[1] !== editState || $[2] !== onChange || $[3] !== translation._key || $[4] !== translation.value._ref || $[5] !== translation.value._strengthenOnPublish || $[6] !== translation.value._weak ? (t1 = () => {
1112
+ if (translation.value._ref && translation.value._weak && translation.value._strengthenOnPublish && !editState.draft && editState.published && editState.ready) {
1113
+ const referencePathBase = ["translations", {
1114
+ _key: translation._key
1115
+ }, "value"];
1116
+ onChange(new PatchEvent([unset([...referencePathBase, "_weak"]), unset([...referencePathBase, "_strengthenOnPublish"])]));
1385
1117
  }
1386
- }, [translation, editState, metadataId, client, onChange]), null;
1118
+ }, $[1] = editState, $[2] = onChange, $[3] = translation._key, $[4] = translation.value._ref, $[5] = translation.value._strengthenOnPublish, $[6] = translation.value._weak, $[7] = t1) : t1 = $[7];
1119
+ let t2;
1120
+ return $[8] !== client || $[9] !== editState || $[10] !== metadataId || $[11] !== onChange || $[12] !== translation ? (t2 = [translation, editState, metadataId, client, onChange], $[8] = client, $[9] = editState, $[10] = metadataId, $[11] = onChange, $[12] = translation, $[13] = t2) : t2 = $[13], useEffect(t1, t2), null;
1387
1121
  }
1388
1122
  function OptimisticallyStrengthen(props) {
1389
- const { translations = [], metadataId } = props;
1390
- return translations.length ? /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: translations.map(
1391
- (translation) => {
1392
- var _a;
1393
- return (_a = translation.value._strengthenOnPublish) != null && _a.type ? /* @__PURE__ */ jsxRuntime.jsx(
1394
- ReferencePatcher,
1395
- {
1396
- translation,
1397
- documentType: translation.value._strengthenOnPublish.type,
1398
- metadataId
1399
- },
1400
- translation._key
1401
- ) : null;
1402
- }
1403
- ) }) : null;
1123
+ const $ = c(9), {
1124
+ translations: t0,
1125
+ metadataId
1126
+ } = props;
1127
+ let t1;
1128
+ $[0] !== t0 ? (t1 = t0 === void 0 ? [] : t0, $[0] = t0, $[1] = t1) : t1 = $[1];
1129
+ const translations = t1;
1130
+ if (!translations.length)
1131
+ return null;
1132
+ let t2;
1133
+ if ($[2] !== metadataId || $[3] !== translations) {
1134
+ let t32;
1135
+ $[5] !== metadataId ? (t32 = (translation) => translation.value._strengthenOnPublish?.type ? /* @__PURE__ */ jsx(ReferencePatcher, { translation, documentType: translation.value._strengthenOnPublish.type, metadataId }, translation._key) : null, $[5] = metadataId, $[6] = t32) : t32 = $[6], t2 = translations.map(t32), $[2] = metadataId, $[3] = translations, $[4] = t2;
1136
+ } else
1137
+ t2 = $[4];
1138
+ let t3;
1139
+ return $[7] !== t2 ? (t3 = /* @__PURE__ */ jsx(Fragment, { children: t2 }), $[7] = t2, $[8] = t3) : t3 = $[8], t3;
1404
1140
  }
1405
- var metadata = (schemaTypes, metadataFields) => sanity.defineType({
1141
+ var metadata = (schemaTypes, metadataFields) => defineType({
1406
1142
  type: "document",
1407
1143
  name: METADATA_SCHEMA_NAME,
1408
1144
  title: "Translation metadata",
1409
- icon: icons.TranslateIcon,
1145
+ icon: TranslateIcon,
1410
1146
  liveEdit: !0,
1411
- fields: [
1412
- sanity.defineField({
1413
- name: TRANSLATIONS_ARRAY_NAME,
1414
- type: "internationalizedArrayReference"
1415
- }),
1416
- sanity.defineField({
1417
- name: "schemaTypes",
1418
- description: "Optional: Used to filter the reference fields above so all translations share the same types.",
1419
- type: "array",
1420
- of: [{ type: "string" }],
1421
- options: { list: schemaTypes },
1422
- readOnly: ({ value }) => !!value
1423
- }),
1424
- ...metadataFields
1425
- ],
1147
+ fields: [defineField({
1148
+ name: TRANSLATIONS_ARRAY_NAME,
1149
+ type: "internationalizedArrayReference"
1150
+ }), defineField({
1151
+ name: "schemaTypes",
1152
+ description: "Optional: Used to filter the reference fields above so all translations share the same types.",
1153
+ type: "array",
1154
+ of: [{
1155
+ type: "string"
1156
+ }],
1157
+ options: {
1158
+ list: schemaTypes
1159
+ },
1160
+ readOnly: ({
1161
+ value
1162
+ }) => !!value
1163
+ }), ...metadataFields],
1426
1164
  preview: {
1427
1165
  select: {
1428
1166
  translations: TRANSLATIONS_ARRAY_NAME,
1429
1167
  documentSchemaTypes: "schemaTypes"
1430
1168
  },
1431
1169
  prepare(selection) {
1432
- const { translations = [], documentSchemaTypes = [] } = selection, title = translations.length === 1 ? "1 Translation" : `${translations.length} Translations`, languageKeys = translations.length ? translations.map((t) => t._key.toUpperCase()).join(", ") : "", subtitle = [
1433
- languageKeys ? `(${languageKeys})` : null,
1434
- documentSchemaTypes != null && documentSchemaTypes.length ? documentSchemaTypes.map((s) => s).join(", ") : ""
1435
- ].filter(Boolean).join(" ");
1170
+ const {
1171
+ translations = [],
1172
+ documentSchemaTypes = []
1173
+ } = selection, title = translations.length === 1 ? "1 Translation" : `${translations.length} Translations`, languageKeys = translations.length ? translations.map((t) => t[LANGUAGE_FIELD_NAME].toUpperCase()).join(", ") : "", subtitle = [languageKeys ? `(${languageKeys})` : null, documentSchemaTypes?.length ? documentSchemaTypes.map((s) => s).join(", ") : ""].filter(Boolean).join(" ");
1436
1174
  return {
1437
1175
  title,
1438
1176
  subtitle
1439
1177
  };
1440
1178
  }
1441
1179
  }
1442
- }), __defProp = Object.defineProperty, __defProps = Object.defineProperties, __getOwnPropDescs = Object.getOwnPropertyDescriptors, __getOwnPropSymbols = Object.getOwnPropertySymbols, __hasOwnProp = Object.prototype.hasOwnProperty, __propIsEnum = Object.prototype.propertyIsEnumerable, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues = (a, b) => {
1443
- for (var prop in b || (b = {}))
1444
- __hasOwnProp.call(b, prop) && __defNormalProp(a, prop, b[prop]);
1445
- if (__getOwnPropSymbols)
1446
- for (var prop of __getOwnPropSymbols(b))
1447
- __propIsEnum.call(b, prop) && __defNormalProp(a, prop, b[prop]);
1448
- return a;
1449
- }, __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1450
- const documentInternationalization = sanity.definePlugin(
1451
- (config) => {
1452
- const pluginConfig = __spreadValues(__spreadValues({}, DEFAULT_CONFIG), config), {
1453
- supportedLanguages,
1454
- schemaTypes,
1455
- languageField,
1456
- bulkPublish,
1457
- metadataFields
1458
- } = pluginConfig;
1459
- if (schemaTypes.length === 0)
1460
- throw new Error(
1461
- "You must specify at least one schema type on which to enable document internationalization. Update the `schemaTypes` option in the documentInternationalization() configuration."
1462
- );
1463
- return {
1464
- name: "@sanity/document-internationalization",
1465
- studio: {
1466
- components: {
1467
- layout: (props) => DocumentInternationalizationProvider(__spreadProps(__spreadValues({}, props), { pluginConfig }))
1468
- }
1469
- },
1470
- i18n: {
1471
- bundles: [documentInternationalizationUsEnglishLocaleBundle]
1472
- },
1473
- // Adds:
1474
- // - A bulk-publishing UI component to the form
1475
- // - Will only work for projects on a compatible plan
1476
- form: {
1477
- components: {
1478
- input: (props) => {
1479
- var _a, _b, _c;
1480
- if (props.id === "root" && props.schemaType.name === METADATA_SCHEMA_NAME && sanity.isSanityDocument(props == null ? void 0 : props.value)) {
1481
- const metadataId = (_a = props == null ? void 0 : props.value) == null ? void 0 : _a._id, translations = (_c = (_b = props == null ? void 0 : props.value) == null ? void 0 : _b.translations) != null ? _c : [], weakAndTypedTranslations = translations.filter(
1482
- ({ value }) => (value == null ? void 0 : value._weak) && value._strengthenOnPublish
1483
- );
1484
- return /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 5, children: [
1485
- bulkPublish ? /* @__PURE__ */ jsxRuntime.jsx(BulkPublish, { translations }) : null,
1486
- weakAndTypedTranslations.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
1487
- OptimisticallyStrengthen,
1488
- {
1489
- metadataId,
1490
- translations: weakAndTypedTranslations
1491
- }
1492
- ) : null,
1493
- props.renderDefault(props)
1494
- ] });
1495
- }
1496
- return props.renderDefault(props);
1180
+ });
1181
+ const documentInternationalization = definePlugin((config) => {
1182
+ const pluginConfig = {
1183
+ ...DEFAULT_CONFIG,
1184
+ ...config
1185
+ }, {
1186
+ supportedLanguages,
1187
+ schemaTypes,
1188
+ languageField,
1189
+ bulkPublish,
1190
+ metadataFields
1191
+ } = pluginConfig;
1192
+ if (schemaTypes.length === 0)
1193
+ throw new Error("You must specify at least one schema type on which to enable document internationalization. Update the `schemaTypes` option in the documentInternationalization() configuration.");
1194
+ return {
1195
+ name: "@sanity/document-internationalization",
1196
+ studio: {
1197
+ components: {
1198
+ layout: (props) => /* @__PURE__ */ jsx(DocumentInternationalizationProvider, { ...props, pluginConfig })
1199
+ }
1200
+ },
1201
+ i18n: {
1202
+ bundles: [documentInternationalizationUsEnglishLocaleBundle]
1203
+ },
1204
+ // Adds:
1205
+ // - A bulk-publishing UI component to the form
1206
+ // - Will only work for projects on a compatible plan
1207
+ form: {
1208
+ components: {
1209
+ input: (props) => {
1210
+ if (props.id === "root" && props.schemaType.name === METADATA_SCHEMA_NAME && isSanityDocument(props?.value)) {
1211
+ const metadataId = props?.value?._id, translations = (
1212
+ // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
1213
+ props?.value?.translations ?? []
1214
+ ), weakAndTypedTranslations = translations.filter(({
1215
+ value
1216
+ }) => value?._weak && value._strengthenOnPublish);
1217
+ return /* @__PURE__ */ jsxs(Stack, { space: 5, children: [
1218
+ bulkPublish ? /* @__PURE__ */ jsx(BulkPublish, { translations }) : null,
1219
+ weakAndTypedTranslations.length > 0 ? /* @__PURE__ */ jsx(OptimisticallyStrengthen, { metadataId, translations: weakAndTypedTranslations }) : null,
1220
+ props.renderDefault(props)
1221
+ ] });
1497
1222
  }
1223
+ return props.renderDefault(props);
1498
1224
  }
1225
+ }
1226
+ },
1227
+ // Adds:
1228
+ // - The `Translations` dropdown to the editing form
1229
+ // - `Badges` to documents with a language value
1230
+ // - The `DeleteMetadataAction` action to the metadata document type
1231
+ document: {
1232
+ unstable_languageFilter: (prev, ctx) => {
1233
+ const {
1234
+ schemaType,
1235
+ documentId
1236
+ } = ctx;
1237
+ return schemaTypes.includes(schemaType) && documentId ? [...prev, (props) => DocumentInternationalizationMenu({
1238
+ ...props,
1239
+ documentId
1240
+ })] : prev;
1499
1241
  },
1500
- // Adds:
1501
- // - The `Translations` dropdown to the editing form
1502
- // - `Badges` to documents with a language value
1503
- // - The `DeleteMetadataAction` action to the metadata document type
1504
- document: {
1505
- unstable_languageFilter: (prev, ctx) => {
1506
- const { schemaType, documentId } = ctx;
1507
- return schemaTypes.includes(schemaType) && documentId ? [
1508
- ...prev,
1509
- (props) => DocumentInternationalizationMenu(__spreadProps(__spreadValues({}, props), { documentId }))
1510
- ] : prev;
1511
- },
1512
- badges: (prev, { schemaType }) => schemaTypes.includes(schemaType) ? [(props) => LanguageBadge(props), ...prev] : prev,
1513
- actions: (prev, { schemaType }) => schemaType === METADATA_SCHEMA_NAME ? [...prev, DeleteMetadataAction] : prev
1514
- },
1515
- // Adds:
1516
- // - The `Translations metadata` document type to the schema
1517
- schema: {
1518
- // Create the metadata document type
1519
- types: [metadata(schemaTypes, metadataFields)],
1520
- // For every schema type this plugin is enabled on
1521
- // Create an initial value template to set the language
1522
- templates: (prev, { schema }) => {
1523
- if (!Array.isArray(supportedLanguages))
1524
- return prev;
1525
- const parameterizedTemplates = schemaTypes.map((schemaType) => {
1526
- var _a, _b;
1527
- return {
1528
- id: `${schemaType}-parameterized`,
1529
- title: `${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}: with Language`,
1530
- schemaType,
1531
- parameters: [
1532
- { name: "languageId", title: "Language ID", type: "string" }
1533
- ],
1534
- value: ({ languageId }) => ({
1535
- [languageField]: languageId
1536
- })
1537
- };
1538
- }), staticTemplates = schemaTypes.flatMap((schemaType) => supportedLanguages.map((language) => {
1539
- var _a, _b;
1540
- return {
1541
- id: `${schemaType}-${language.id}`,
1542
- title: `${language.title} ${(_b = (_a = schema == null ? void 0 : schema.get(schemaType)) == null ? void 0 : _a.title) != null ? _b : schemaType}`,
1543
- schemaType,
1544
- value: {
1545
- [languageField]: language.id
1546
- }
1547
- };
1548
- }));
1549
- return [...prev, ...parameterizedTemplates, ...staticTemplates];
1550
- }
1551
- },
1552
- // Uses:
1553
- // - `sanity-plugin-internationalized-array` to maintain the translations array
1554
- plugins: [
1555
- // Translation metadata stores its references using this plugin
1556
- // It cuts down on attribute usage and gives UI conveniences to add new translations
1557
- sanityPluginInternationalizedArray.internationalizedArray({
1558
- apiVersion: pluginConfig.apiVersion,
1559
- languages: supportedLanguages,
1560
- fieldTypes: [
1561
- sanity.defineField(
1562
- {
1563
- name: "reference",
1564
- type: "reference",
1565
- to: schemaTypes.map((type) => ({ type })),
1566
- weak: pluginConfig.weakReferences,
1567
- // Reference filters don't actually enforce validation!
1568
- validation: (Rule) => (
1569
- // @ts-expect-error - fix typings
1570
- Rule.custom(async (item, context) => {
1571
- var _a;
1572
- if (!((_a = item == null ? void 0 : item.value) != null && _a._ref) || !(item != null && item._key))
1573
- return !0;
1574
- const valueLanguage = await context.getClient({ apiVersion: API_VERSION }).fetch(
1575
- `*[_id in [$ref, $draftRef]][0].${languageField}`,
1576
- {
1577
- ref: item.value._ref,
1578
- draftRef: `drafts.${item.value._ref}`
1579
- }
1580
- );
1581
- return valueLanguage && valueLanguage === item._key ? !0 : "Referenced document does not have the correct language value";
1582
- })
1583
- ),
1584
- options: {
1585
- // @ts-expect-error - Update type once it knows the values of this filter
1586
- filter: ({ parent, document }) => {
1587
- if (!parent)
1588
- return null;
1589
- const language = (Array.isArray(parent) ? parent : [parent]).find((p) => p._key);
1590
- return language != null && language._key ? document.schemaTypes ? {
1591
- filter: `_type in $schemaTypes && ${languageField} == $language`,
1592
- params: {
1593
- schemaTypes: document.schemaTypes,
1594
- language: language._key
1595
- }
1596
- } : {
1597
- filter: `${languageField} == $language`,
1598
- params: { language: language._key }
1599
- } : null;
1600
- }
1242
+ badges: (prev, {
1243
+ schemaType
1244
+ }) => schemaTypes.includes(schemaType) ? [(props) => LanguageBadge(props), ...prev] : prev,
1245
+ actions: (prev, {
1246
+ schemaType
1247
+ }) => schemaType === METADATA_SCHEMA_NAME ? [...prev, useDeleteMetadataAction] : prev
1248
+ },
1249
+ // Adds:
1250
+ // - The `Translations metadata` document type to the schema
1251
+ schema: {
1252
+ // Create the metadata document type
1253
+ types: [metadata(schemaTypes, metadataFields)],
1254
+ // For every schema type this plugin is enabled on
1255
+ // Create an initial value template to set the language
1256
+ templates: (prev, {
1257
+ schema
1258
+ }) => {
1259
+ if (!Array.isArray(supportedLanguages))
1260
+ return prev;
1261
+ const parameterizedTemplates = schemaTypes.map((schemaType) => ({
1262
+ id: `${schemaType}-parameterized`,
1263
+ title: `${schema?.get(schemaType)?.title ?? schemaType}: with Language`,
1264
+ schemaType,
1265
+ parameters: [{
1266
+ name: "languageId",
1267
+ title: "Language ID",
1268
+ type: "string"
1269
+ }],
1270
+ value: ({
1271
+ languageId
1272
+ }) => ({
1273
+ [languageField]: languageId
1274
+ })
1275
+ })), staticTemplates = schemaTypes.flatMap((schemaType) => supportedLanguages.map((language) => ({
1276
+ id: `${schemaType}-${language.id}`,
1277
+ title: `${language.title} ${schema?.get(schemaType)?.title ?? schemaType}`,
1278
+ schemaType,
1279
+ value: {
1280
+ [languageField]: language.id
1281
+ }
1282
+ })));
1283
+ return [...prev, ...parameterizedTemplates, ...staticTemplates];
1284
+ }
1285
+ },
1286
+ // Uses:
1287
+ // - `sanity-plugin-internationalized-array` to maintain the translations array
1288
+ plugins: [
1289
+ // Translation metadata stores its references using this plugin
1290
+ // It cuts down on attribute usage and gives UI conveniences to add new translations
1291
+ internationalizedArray({
1292
+ apiVersion: pluginConfig.apiVersion,
1293
+ languages: supportedLanguages,
1294
+ fieldTypes: [defineField({
1295
+ name: "reference",
1296
+ type: "reference",
1297
+ to: schemaTypes.map((type) => ({
1298
+ type
1299
+ })),
1300
+ weak: pluginConfig.weakReferences,
1301
+ // Reference filters don't actually enforce validation!
1302
+ validation: (Rule) => (
1303
+ // @ts-expect-error - fix typings
1304
+ Rule.custom(async (item, context) => {
1305
+ if (!item?.value?._ref || !item?._key)
1306
+ return !0;
1307
+ const valueLanguage = await context.getClient({
1308
+ apiVersion: API_VERSION
1309
+ }).fetch(`*[_id in [$ref, $draftRef]][0].${languageField}`, {
1310
+ ref: item.value._ref,
1311
+ draftRef: `drafts.${item.value._ref}`
1312
+ });
1313
+ return valueLanguage && valueLanguage === item._key ? !0 : "Referenced document does not have the correct language value";
1314
+ })
1315
+ ),
1316
+ options: {
1317
+ // @ts-expect-error - Update type once it knows the values of this filter
1318
+ filter: ({
1319
+ parent,
1320
+ document
1321
+ }) => {
1322
+ if (!parent) return null;
1323
+ const language = (Array.isArray(parent) ? parent : [parent]).find((p) => p._key);
1324
+ return language?._key ? document.schemaTypes ? {
1325
+ filter: `_type in $schemaTypes && ${languageField} == $language`,
1326
+ params: {
1327
+ schemaTypes: document.schemaTypes,
1328
+ language: language._key
1601
1329
  }
1602
- },
1603
- { strict: !1 }
1604
- )
1605
- ]
1606
- })
1607
- ]
1608
- };
1609
- }
1610
- );
1611
- exports.DeleteTranslationAction = DeleteTranslationAction;
1612
- exports.DocumentInternationalizationMenu = DocumentInternationalizationMenu;
1613
- exports.DuplicateWithTranslationsAction = DuplicateWithTranslationsAction;
1614
- exports.documentInternationalization = documentInternationalization;
1615
- exports.useDocumentInternationalizationContext = useDocumentInternationalizationContext;
1330
+ } : {
1331
+ filter: `${languageField} == $language`,
1332
+ params: {
1333
+ language: language._key
1334
+ }
1335
+ } : null;
1336
+ }
1337
+ }
1338
+ }, {
1339
+ strict: !1
1340
+ })]
1341
+ })
1342
+ ]
1343
+ };
1344
+ });
1345
+ export {
1346
+ DeleteTranslationAction,
1347
+ DocumentInternationalizationMenu,
1348
+ DuplicateWithTranslationsAction,
1349
+ documentInternationalization,
1350
+ useDeleteTranslationAction,
1351
+ useDocumentInternationalizationContext,
1352
+ useDuplicateWithTranslationsAction
1353
+ };
1616
1354
  //# sourceMappingURL=index.js.map