@sanity/document-internationalization 2.1.2 → 3.0.0

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