sanity-plugin-workflow 1.0.6 → 2.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 (52) hide show
  1. package/README.md +2 -17
  2. package/dist/index.d.ts +17 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.js +1647 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +30 -69
  7. package/lib/index.d.ts +0 -20
  8. package/lib/index.esm.js +0 -2135
  9. package/lib/index.esm.js.map +0 -1
  10. package/lib/index.js +0 -2147
  11. package/lib/index.js.map +0 -1
  12. package/sanity.json +0 -8
  13. package/src/actions/AssignWorkflow.tsx +0 -47
  14. package/src/actions/BeginWorkflow.tsx +0 -63
  15. package/src/actions/CompleteWorkflow.tsx +0 -64
  16. package/src/actions/UpdateWorkflow.tsx +0 -126
  17. package/src/badges/AssigneesBadge.tsx +0 -53
  18. package/src/badges/StateBadge.tsx +0 -28
  19. package/src/components/DocumentCard/AvatarGroup.tsx +0 -43
  20. package/src/components/DocumentCard/CompleteButton.tsx +0 -56
  21. package/src/components/DocumentCard/EditButton.tsx +0 -28
  22. package/src/components/DocumentCard/Field.tsx +0 -38
  23. package/src/components/DocumentCard/Validate.tsx +0 -21
  24. package/src/components/DocumentCard/ValidationStatus.tsx +0 -37
  25. package/src/components/DocumentCard/core/DraftStatus.tsx +0 -32
  26. package/src/components/DocumentCard/core/PublishedStatus.tsx +0 -39
  27. package/src/components/DocumentCard/core/TimeAgo.tsx +0 -11
  28. package/src/components/DocumentCard/index.tsx +0 -200
  29. package/src/components/DocumentList.tsx +0 -169
  30. package/src/components/Filters.tsx +0 -174
  31. package/src/components/FloatingCard.tsx +0 -36
  32. package/src/components/StateTitle/Status.tsx +0 -27
  33. package/src/components/StateTitle/index.tsx +0 -78
  34. package/src/components/UserAssignment.tsx +0 -121
  35. package/src/components/UserAssignmentInput.tsx +0 -27
  36. package/src/components/UserDisplay.tsx +0 -57
  37. package/src/components/Verify.tsx +0 -297
  38. package/src/components/WorkflowContext.tsx +0 -71
  39. package/src/components/WorkflowSignal.tsx +0 -30
  40. package/src/components/WorkflowTool.tsx +0 -437
  41. package/src/constants/index.ts +0 -31
  42. package/src/helpers/arraysContainMatchingString.ts +0 -6
  43. package/src/helpers/filterItemsAndSort.ts +0 -41
  44. package/src/helpers/generateMultipleOrderRanks.ts +0 -80
  45. package/src/helpers/initialRank.ts +0 -13
  46. package/src/hooks/useWorkflowDocuments.tsx +0 -167
  47. package/src/hooks/useWorkflowMetadata.tsx +0 -49
  48. package/src/index.ts +0 -97
  49. package/src/schema/workflow/workflow.metadata.ts +0 -68
  50. package/src/tools/index.ts +0 -15
  51. package/src/types/index.ts +0 -71
  52. package/v2-incompatible.js +0 -11
package/dist/index.js ADDED
@@ -0,0 +1,1647 @@
1
+ import { useClient, useCurrentUser, useValidationStatus, useSchema, Preview, useFormValue, defineType, defineField, UserAvatar, useTimeAgo, TextWithTone, definePlugin, isObjectInputProps } from "sanity";
2
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
3
+ import { UsersIcon, SplitVerticalIcon, CheckmarkIcon, ArrowRightIcon, ArrowLeftIcon, EditIcon, AddIcon, PublishIcon, ErrorOutlineIcon, WarningOutlineIcon, DragHandleIcon, UserIcon, ResetIcon, InfoOutlineIcon } from "@sanity/icons";
4
+ import { createContext, useContext, useState, useCallback, useEffect, useMemo, useRef } from "react";
5
+ import { UserSelectMenu, useListeningQuery, useProjectUsers, Feedback } from "sanity-plugin-utils";
6
+ import { c } from "react-compiler-runtime";
7
+ import { useToast, Button, Spinner, Card, Flex, Box, Text, useClickOutside, Grid, Popover, Tooltip, useTheme, Stack, MenuButton, Menu, Badge, Container } from "@sanity/ui";
8
+ import { LexoRank } from "lexorank";
9
+ import { useRouter } from "sanity/router";
10
+ import { Draggable, Droppable, DragDropContext } from "@hello-pangea/dnd";
11
+ import { useVirtualizer } from "@tanstack/react-virtual";
12
+ import { styled, css } from "styled-components";
13
+ import { AnimatePresence, motion } from "framer-motion";
14
+ const API_VERSION = "2023-01-01", DEFAULT_CONFIG = {
15
+ schemaTypes: [],
16
+ states: [{
17
+ id: "inReview",
18
+ title: "In review",
19
+ color: "primary",
20
+ roles: ["editor", "administrator"],
21
+ transitions: ["changesRequested", "approved"]
22
+ }, {
23
+ id: "changesRequested",
24
+ title: "Changes requested",
25
+ color: "warning",
26
+ roles: ["editor", "administrator"],
27
+ transitions: ["approved"]
28
+ }, {
29
+ id: "approved",
30
+ title: "Approved",
31
+ color: "success",
32
+ roles: ["administrator"],
33
+ transitions: ["changesRequested"],
34
+ requireAssignment: !0
35
+ }]
36
+ };
37
+ function UserAssignment(props) {
38
+ const $ = c(24), {
39
+ assignees,
40
+ userList,
41
+ documentId
42
+ } = props;
43
+ let t0;
44
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
45
+ apiVersion: API_VERSION
46
+ }, $[0] = t0) : t0 = $[0];
47
+ const client = useClient(t0), toast = useToast();
48
+ let t1;
49
+ $[1] !== client || $[2] !== documentId || $[3] !== toast || $[4] !== userList ? (t1 = (userId) => {
50
+ const user = userList.find((u) => u.id === userId);
51
+ return !userId || !user ? toast.push({
52
+ status: "error",
53
+ title: "Could not find User"
54
+ }) : client.patch(`workflow-metadata.${documentId}`).setIfMissing({
55
+ assignees: []
56
+ }).insert("after", "assignees[-1]", [userId]).commit().then(() => toast.push({
57
+ title: `Added ${user.displayName} to assignees`,
58
+ status: "success"
59
+ })).catch((err) => (console.error(err), toast.push({
60
+ title: "Failed to add assignee",
61
+ description: userId,
62
+ status: "error"
63
+ })));
64
+ }, $[1] = client, $[2] = documentId, $[3] = toast, $[4] = userList, $[5] = t1) : t1 = $[5];
65
+ const addAssignee = t1;
66
+ let t2;
67
+ $[6] !== client || $[7] !== documentId || $[8] !== toast || $[9] !== userList ? (t2 = (userId_0) => {
68
+ const user_0 = userList.find((u_0) => u_0.id === userId_0);
69
+ return !userId_0 || !user_0 ? toast.push({
70
+ status: "error",
71
+ title: "Could not find User"
72
+ }) : client.patch(`workflow-metadata.${documentId}`).unset([`assignees[@ == "${userId_0}"]`]).commit().then(() => toast.push({
73
+ title: `Removed ${user_0.displayName} from assignees`,
74
+ status: "success"
75
+ })).catch((err_0) => (console.error(err_0), toast.push({
76
+ title: "Failed to remove assignee",
77
+ description: documentId,
78
+ status: "error"
79
+ })));
80
+ }, $[6] = client, $[7] = documentId, $[8] = toast, $[9] = userList, $[10] = t2) : t2 = $[10];
81
+ const removeAssignee = t2;
82
+ let t3;
83
+ $[11] !== client || $[12] !== documentId || $[13] !== toast ? (t3 = () => client.patch(`workflow-metadata.${documentId}`).unset(["assignees"]).commit().then(() => toast.push({
84
+ title: "Cleared assignees",
85
+ status: "success"
86
+ })).catch((err_1) => (console.error(err_1), toast.push({
87
+ title: "Failed to clear assignees",
88
+ description: documentId,
89
+ status: "error"
90
+ }))), $[11] = client, $[12] = documentId, $[13] = toast, $[14] = t3) : t3 = $[14];
91
+ const clearAssignees = t3;
92
+ let t4;
93
+ $[15] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t4 = {
94
+ maxHeight: 300
95
+ }, $[15] = t4) : t4 = $[15];
96
+ let t5;
97
+ $[16] !== assignees ? (t5 = assignees || [], $[16] = assignees, $[17] = t5) : t5 = $[17];
98
+ let t6;
99
+ return $[18] !== addAssignee || $[19] !== clearAssignees || $[20] !== removeAssignee || $[21] !== t5 || $[22] !== userList ? (t6 = /* @__PURE__ */ jsx(UserSelectMenu, { style: t4, value: t5, userList, onAdd: addAssignee, onClear: clearAssignees, onRemove: removeAssignee }), $[18] = addAssignee, $[19] = clearAssignees, $[20] = removeAssignee, $[21] = t5, $[22] = userList, $[23] = t6) : t6 = $[23], t6;
100
+ }
101
+ function useWorkflowMetadata(ids) {
102
+ const $ = c(12);
103
+ let t0;
104
+ $[0] !== ids ? (t0 = {
105
+ ids
106
+ }, $[0] = ids, $[1] = t0) : t0 = $[1];
107
+ let t1;
108
+ $[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
109
+ apiVersion: API_VERSION
110
+ }, $[2] = t1) : t1 = $[2];
111
+ let t2;
112
+ $[3] !== t0 ? (t2 = {
113
+ params: t0,
114
+ options: t1
115
+ }, $[3] = t0, $[4] = t2) : t2 = $[4];
116
+ const {
117
+ data: _rawData,
118
+ loading,
119
+ error
120
+ } = useListeningQuery(`*[_type == "workflow.metadata" && documentId in $ids]{
121
+ _id,
122
+ _type,
123
+ _rev,
124
+ assignees,
125
+ documentId,
126
+ state,
127
+ orderRank
128
+ }`, t2), rawData = _rawData;
129
+ let t3;
130
+ bb0: {
131
+ if (!rawData || rawData.length === 0) {
132
+ let t43;
133
+ $[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t43 = {}, $[5] = t43) : t43 = $[5], t3 = t43;
134
+ break bb0;
135
+ }
136
+ let t42;
137
+ $[6] !== rawData ? (t42 = rawData.reduce(_temp$6, {}), $[6] = rawData, $[7] = t42) : t42 = $[7], t3 = t42;
138
+ }
139
+ const keyedMetadata = t3;
140
+ let t4;
141
+ return $[8] !== error || $[9] !== keyedMetadata || $[10] !== loading ? (t4 = {
142
+ data: keyedMetadata,
143
+ loading,
144
+ error
145
+ }, $[8] = error, $[9] = keyedMetadata, $[10] = loading, $[11] = t4) : t4 = $[11], t4;
146
+ }
147
+ function _temp$6(acc, cur) {
148
+ return {
149
+ ...acc,
150
+ [cur.documentId]: cur
151
+ };
152
+ }
153
+ const WorkflowContext = createContext({
154
+ data: {},
155
+ loading: !1,
156
+ error: !1,
157
+ ids: [],
158
+ addId: () => null,
159
+ removeId: () => null,
160
+ ...DEFAULT_CONFIG
161
+ });
162
+ function useWorkflowContext(id) {
163
+ const $ = c(3), current = useContext(WorkflowContext), t0 = id ? current.data[id] : null;
164
+ let t1;
165
+ return $[0] !== current || $[1] !== t0 ? (t1 = {
166
+ ...current,
167
+ metadata: t0
168
+ }, $[0] = current, $[1] = t0, $[2] = t1) : t1 = $[2], t1;
169
+ }
170
+ function WorkflowProvider(props) {
171
+ const $ = c(15);
172
+ let t0;
173
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = [], $[0] = t0) : t0 = $[0];
174
+ const [ids, setIds] = useState(t0);
175
+ let t1;
176
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = (id) => setIds((current) => current.includes(id) ? current : [...current, id]), $[1] = t1) : t1 = $[1];
177
+ const addId = t1;
178
+ let t2;
179
+ $[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = (id_0) => setIds((current_0) => current_0.filter((i) => i !== id_0)), $[2] = t2) : t2 = $[2];
180
+ const removeId = t2, {
181
+ data,
182
+ loading,
183
+ error
184
+ } = useWorkflowMetadata(ids);
185
+ let t3;
186
+ $[3] !== data || $[4] !== error || $[5] !== ids || $[6] !== loading || $[7] !== props.workflow.schemaTypes || $[8] !== props.workflow.states ? (t3 = {
187
+ data,
188
+ loading,
189
+ error,
190
+ ids,
191
+ addId,
192
+ removeId,
193
+ states: props.workflow.states,
194
+ schemaTypes: props.workflow.schemaTypes
195
+ }, $[3] = data, $[4] = error, $[5] = ids, $[6] = loading, $[7] = props.workflow.schemaTypes, $[8] = props.workflow.states, $[9] = t3) : t3 = $[9];
196
+ let t4;
197
+ $[10] !== props ? (t4 = props.renderDefault(props), $[10] = props, $[11] = t4) : t4 = $[11];
198
+ let t5;
199
+ return $[12] !== t3 || $[13] !== t4 ? (t5 = /* @__PURE__ */ jsx(WorkflowContext.Provider, { value: t3, children: t4 }), $[12] = t3, $[13] = t4, $[14] = t5) : t5 = $[14], t5;
200
+ }
201
+ function AssignWorkflow(props) {
202
+ const {
203
+ id
204
+ } = props, {
205
+ metadata: metadata2,
206
+ loading,
207
+ error
208
+ } = useWorkflowContext(id), [isDialogOpen, setDialogOpen] = useState(!1), userList = useProjectUsers({
209
+ apiVersion: API_VERSION
210
+ });
211
+ return error && console.error(error), metadata2 ? {
212
+ icon: UsersIcon,
213
+ type: "dialog",
214
+ disabled: !metadata2 || loading || error,
215
+ label: "Assign",
216
+ title: metadata2 ? null : "Document is not in Workflow",
217
+ dialog: isDialogOpen && {
218
+ type: "popover",
219
+ onClose: () => {
220
+ setDialogOpen(!1);
221
+ },
222
+ content: /* @__PURE__ */ jsx(UserAssignment, { userList, assignees: metadata2?.assignees?.length > 0 ? metadata2.assignees : [], documentId: id })
223
+ },
224
+ onHandle: () => {
225
+ setDialogOpen(!0);
226
+ }
227
+ } : null;
228
+ }
229
+ function BeginWorkflow(props) {
230
+ const {
231
+ id,
232
+ draft
233
+ } = props, {
234
+ metadata: metadata2,
235
+ loading,
236
+ error,
237
+ states
238
+ } = useWorkflowContext(id), client = useClient({
239
+ apiVersion: API_VERSION
240
+ }), toast = useToast(), [beginning, setBeginning] = useState(!1), [complete, setComplete] = useState(!1);
241
+ error && console.error(error);
242
+ const handle = useCallback(async () => {
243
+ setBeginning(!0);
244
+ const lowestOrderFirstState = await client.fetch('*[_type == "workflow.metadata" && state == $state]|order(orderRank)[0].orderRank', {
245
+ state: states?.[0]?.id
246
+ });
247
+ await client.createIfNotExists({
248
+ _id: `workflow-metadata.${id}`,
249
+ _type: "workflow.metadata",
250
+ documentId: id,
251
+ state: states?.[0]?.id,
252
+ orderRank: lowestOrderFirstState ? LexoRank.parse(lowestOrderFirstState).genNext().toString() : LexoRank.min().toString()
253
+ }).then(() => {
254
+ toast.push({
255
+ status: "success",
256
+ title: "Workflow started",
257
+ description: `Document is now "${states?.[0]?.title}"`
258
+ }), setBeginning(!1), setComplete(!0);
259
+ });
260
+ }, [id, states, client, toast]);
261
+ return !draft || complete || metadata2 ? null : {
262
+ icon: SplitVerticalIcon,
263
+ type: "dialog",
264
+ disabled: metadata2 || loading || error || beginning || complete,
265
+ label: beginning ? "Beginning..." : "Begin Workflow",
266
+ onHandle: async () => {
267
+ await handle();
268
+ }
269
+ };
270
+ }
271
+ const handleDeleteMetadata = async (client, toast, id) => {
272
+ try {
273
+ await client.delete(`workflow-metadata.${id}`), toast.push({
274
+ status: "success",
275
+ title: "Workflow completed"
276
+ });
277
+ } catch (error) {
278
+ console.error(error), toast.push({
279
+ status: "error",
280
+ title: "Could not complete Workflow"
281
+ });
282
+ }
283
+ };
284
+ function CompleteWorkflow(props) {
285
+ const {
286
+ id
287
+ } = props, {
288
+ metadata: metadata2,
289
+ loading,
290
+ error,
291
+ states
292
+ } = useWorkflowContext(id), client = useClient({
293
+ apiVersion: API_VERSION
294
+ }), toast = useToast();
295
+ error && console.error(error);
296
+ const handle = useCallback(async () => {
297
+ await handleDeleteMetadata(client, toast, id);
298
+ }, [client, toast, id]);
299
+ if (!metadata2)
300
+ return null;
301
+ const isLastState = states.find((s) => s.id === metadata2.state)?.id === states?.[states?.length - 1]?.id;
302
+ return {
303
+ icon: CheckmarkIcon,
304
+ type: "dialog",
305
+ disabled: loading || error || !isLastState,
306
+ label: "Complete Workflow",
307
+ title: isLastState ? "Removes the document from the Workflow process" : "Cannot remove from workflow until in the last state",
308
+ onHandle: async () => {
309
+ await handle(), props.onComplete();
310
+ },
311
+ color: "positive"
312
+ };
313
+ }
314
+ function arraysContainMatchingString(one, two) {
315
+ return one.some((item) => two.includes(item));
316
+ }
317
+ function UpdateWorkflow(props, actionState) {
318
+ const {
319
+ id,
320
+ type
321
+ } = props, user = useCurrentUser(), client = useClient({
322
+ apiVersion: API_VERSION
323
+ }), toast = useToast(), currentUser = useCurrentUser(), {
324
+ metadata: metadata2,
325
+ loading,
326
+ error,
327
+ states
328
+ } = useWorkflowContext(id), currentState = states.find((s) => s.id === metadata2?.state), {
329
+ assignees = []
330
+ } = metadata2 ?? {}, {
331
+ validation,
332
+ isValidating
333
+ } = useValidationStatus(id, type), hasValidationErrors = currentState?.requireValidation && !isValidating && validation?.length > 0 && validation.find((v) => v.level === "error");
334
+ error && console.error(error);
335
+ const onHandle = (documentId, newState) => {
336
+ client.patch(`workflow-metadata.${documentId}`).set({
337
+ state: newState.id
338
+ }).commit().then(() => {
339
+ props.onComplete(), toast.push({
340
+ status: "success",
341
+ title: `Document state now "${newState.title}"`
342
+ });
343
+ }).catch((err) => {
344
+ props.onComplete(), console.error(err), toast.push({
345
+ status: "error",
346
+ title: "Document state update failed"
347
+ });
348
+ });
349
+ };
350
+ if (!metadata2 || currentState && currentState.id === actionState.id)
351
+ return null;
352
+ const currentStateIndex = states.findIndex((s) => s.id === currentState?.id), direction = states.findIndex((s) => s.id === actionState.id) > currentStateIndex ? "promote" : "demote", DirectionIcon = direction === "promote" ? ArrowRightIcon : ArrowLeftIcon, directionLabel = direction === "promote" ? "Promote" : "Demote", userRoleCanUpdateState = user?.roles?.length && actionState?.roles?.length ? (
353
+ // If the Action state is limited to specific roles
354
+ // check that the current user has one of those roles
355
+ arraysContainMatchingString(user.roles.map((r) => r.name), actionState.roles)
356
+ ) : (
357
+ // No roles specified on the next state, so anyone can update
358
+ actionState?.roles?.length !== 0
359
+ ), actionStateIsAValidTransition = currentState?.id && currentState?.transitions?.length ? (
360
+ // If the Current State limits transitions to specific States
361
+ // Check that the Action State is in Current State's transitions array
362
+ currentState.transitions.includes(actionState.id)
363
+ ) : (
364
+ // Otherwise this isn't a problem
365
+ !0
366
+ ), userAssignmentCanUpdateState = actionState.requireAssignment ? (
367
+ // If the Action State requires assigned users
368
+ // Check the current user ID is in the assignees array
369
+ currentUser && assignees?.length && assignees.includes(currentUser.id)
370
+ ) : (
371
+ // Otherwise this isn't a problem
372
+ !0
373
+ );
374
+ let title = `${directionLabel} State to "${actionState.title}"`;
375
+ return userRoleCanUpdateState ? actionStateIsAValidTransition ? userAssignmentCanUpdateState ? currentState?.requireValidation && isValidating ? title = `Document is validating, cannot ${directionLabel} State to "${actionState.title}"` : hasValidationErrors && (title = `Document has validation errors, cannot ${directionLabel} State to "${actionState.title}"`) : title = `You must be assigned to the document to ${directionLabel} State to "${actionState.title}"` : title = `You cannot ${directionLabel} State to "${actionState.title}" from "${currentState?.title}"` : title = `Your User role cannot ${directionLabel} State to "${actionState.title}"`, {
376
+ icon: DirectionIcon,
377
+ disabled: loading || error || currentState?.requireValidation && isValidating || hasValidationErrors || !currentState || !userRoleCanUpdateState || !actionStateIsAValidTransition || !userAssignmentCanUpdateState,
378
+ title,
379
+ label: actionState.title,
380
+ onHandle: () => onHandle(id, actionState)
381
+ };
382
+ }
383
+ function AssigneesBadge(documentId, currentUser) {
384
+ const {
385
+ metadata: metadata2,
386
+ loading,
387
+ error
388
+ } = useWorkflowContext(documentId), userList = useProjectUsers({
389
+ apiVersion: API_VERSION
390
+ });
391
+ if (loading || error || !metadata2)
392
+ return error && console.error(error), null;
393
+ if (!metadata2?.assignees?.length)
394
+ return {
395
+ label: "Unassigned"
396
+ };
397
+ const {
398
+ assignees
399
+ } = metadata2 ?? [], hasMe = currentUser ? assignees.some((assignee) => assignee === currentUser.id) : !1, assigneesCount = hasMe ? assignees.length - 1 : assignees.length, title = userList.filter((user) => assignees.includes(user.id)).map((user) => user.displayName).join(", ");
400
+ let label;
401
+ return hasMe && assigneesCount === 0 ? label = "Assigned to Me" : hasMe && assigneesCount > 0 ? label = `Me and ${assigneesCount} ${assigneesCount === 1 ? "other" : "others"}` : label = `${assigneesCount} assigned`, {
402
+ label,
403
+ title,
404
+ color: "primary"
405
+ };
406
+ }
407
+ function StateBadge(documentId) {
408
+ const {
409
+ metadata: metadata2,
410
+ loading,
411
+ error,
412
+ states
413
+ } = useWorkflowContext(documentId), state = states.find((s) => s.id === metadata2?.state);
414
+ return loading || error ? (error && console.error(error), null) : state ? {
415
+ label: state.title,
416
+ // title: state.title,
417
+ color: state?.color
418
+ } : null;
419
+ }
420
+ function WorkflowSignal(props) {
421
+ const $ = c(9);
422
+ let t0;
423
+ $[0] !== props.value ? (t0 = props?.value?._id ? props.value._id.replace("drafts.", "") : null, $[0] = props.value, $[1] = t0) : t0 = $[1];
424
+ const documentId = t0, {
425
+ addId,
426
+ removeId
427
+ } = useWorkflowContext();
428
+ let t1, t2;
429
+ $[2] !== addId || $[3] !== documentId || $[4] !== removeId ? (t1 = () => (documentId && addId(documentId), () => {
430
+ documentId && removeId(documentId);
431
+ }), t2 = [documentId, addId, removeId], $[2] = addId, $[3] = documentId, $[4] = removeId, $[5] = t1, $[6] = t2) : (t1 = $[5], t2 = $[6]), useEffect(t1, t2);
432
+ let t3;
433
+ return $[7] !== props ? (t3 = props.renderDefault(props), $[7] = props, $[8] = t3) : t3 = $[8], t3;
434
+ }
435
+ function EditButton(props) {
436
+ const $ = c(7), {
437
+ id,
438
+ type,
439
+ disabled: t0
440
+ } = props, disabled = t0 === void 0 ? !1 : t0, {
441
+ navigateIntent
442
+ } = useRouter();
443
+ let t1;
444
+ $[0] !== id || $[1] !== navigateIntent || $[2] !== type ? (t1 = () => navigateIntent("edit", {
445
+ id,
446
+ type
447
+ }), $[0] = id, $[1] = navigateIntent, $[2] = type, $[3] = t1) : t1 = $[3];
448
+ let t2;
449
+ return $[4] !== disabled || $[5] !== t1 ? (t2 = /* @__PURE__ */ jsx(Button, { onClick: t1, mode: "ghost", fontSize: 1, padding: 2, tabIndex: -1, icon: EditIcon, text: "Edit", disabled }), $[4] = disabled, $[5] = t1, $[6] = t2) : t2 = $[6], t2;
450
+ }
451
+ function Field(props) {
452
+ const $ = c(17), schema = useSchema(), t0 = String(props.value), t1 = `drafts.${String(props.value)}`;
453
+ let t2;
454
+ $[0] !== t0 || $[1] !== t1 ? (t2 = {
455
+ params: {
456
+ id: t0,
457
+ draftId: t1
458
+ }
459
+ }, $[0] = t0, $[1] = t1, $[2] = t2) : t2 = $[2];
460
+ const {
461
+ data: _data,
462
+ loading,
463
+ error
464
+ } = useListeningQuery("*[_id in [$id, $draftId]]|order(_updatedAt)[0]", t2), data = _data;
465
+ if (loading) {
466
+ let t32;
467
+ return $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t32 = /* @__PURE__ */ jsx(Spinner, {}), $[3] = t32) : t32 = $[3], t32;
468
+ }
469
+ let t3;
470
+ $[4] !== data?._type || $[5] !== schema ? (t3 = schema.get(data?._type ?? ""), $[4] = data?._type, $[5] = schema, $[6] = t3) : t3 = $[6];
471
+ const schemaType = t3;
472
+ if (error || !data?._type || !schemaType) {
473
+ let t42;
474
+ return $[7] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t42 = /* @__PURE__ */ jsx(Feedback, { tone: "critical", title: "Error with query" }), $[7] = t42) : t42 = $[7], t42;
475
+ }
476
+ let t4;
477
+ $[8] !== data || $[9] !== schemaType ? (t4 = /* @__PURE__ */ jsx(Preview, { layout: "default", value: data, schemaType }), $[8] = data, $[9] = schemaType, $[10] = t4) : t4 = $[10];
478
+ let t5;
479
+ $[11] !== data._id || $[12] !== data._type ? (t5 = /* @__PURE__ */ jsx(EditButton, { id: data._id, type: data._type }), $[11] = data._id, $[12] = data._type, $[13] = t5) : t5 = $[13];
480
+ let t6;
481
+ return $[14] !== t4 || $[15] !== t5 ? (t6 = /* @__PURE__ */ jsx(Card, { border: !0, padding: 2, children: /* @__PURE__ */ jsxs(Flex, { align: "center", justify: "space-between", gap: 2, children: [
482
+ t4,
483
+ t5
484
+ ] }) }), $[14] = t4, $[15] = t5, $[16] = t6) : t6 = $[16], t6;
485
+ }
486
+ const UserAssignmentInput = (props) => {
487
+ const $ = c(8);
488
+ let t0;
489
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = ["documentId"], $[0] = t0) : t0 = $[0];
490
+ const documentId = useFormValue(t0);
491
+ let t1;
492
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
493
+ apiVersion: API_VERSION
494
+ }, $[1] = t1) : t1 = $[1];
495
+ const userList = useProjectUsers(t1);
496
+ let t2;
497
+ $[2] !== props.value ? (t2 = Array.isArray(props?.value) && props?.value?.length ? props.value.map(_temp$5) : [], $[2] = props.value, $[3] = t2) : t2 = $[3];
498
+ const stringValue = t2, t3 = String(documentId);
499
+ let t4;
500
+ return $[4] !== stringValue || $[5] !== t3 || $[6] !== userList ? (t4 = /* @__PURE__ */ jsx(Card, { border: !0, padding: 1, children: /* @__PURE__ */ jsx(UserAssignment, { userList, assignees: stringValue, documentId: t3 }) }), $[4] = stringValue, $[5] = t3, $[6] = userList, $[7] = t4) : t4 = $[7], t4;
501
+ };
502
+ function _temp$5(item) {
503
+ return String(item);
504
+ }
505
+ function initialRank(lastRankValue = "") {
506
+ return (lastRankValue && typeof lastRankValue == "string" ? LexoRank.parse(lastRankValue) : LexoRank.min()).genNext().genNext().value;
507
+ }
508
+ var metadata = (states) => defineType({
509
+ type: "document",
510
+ name: "workflow.metadata",
511
+ title: "Workflow metadata",
512
+ liveEdit: !0,
513
+ fields: [defineField({
514
+ name: "state",
515
+ description: `The current "State" of the document. Field is read only as changing it would not fire the state's "operation" setting. These are fired in the Document Actions and in the custom Tool.`,
516
+ readOnly: !0,
517
+ type: "string",
518
+ options: {
519
+ list: states.length ? states.map((state) => ({
520
+ value: state.id,
521
+ title: state.title
522
+ })) : [],
523
+ layout: "radio"
524
+ }
525
+ }), defineField({
526
+ name: "documentId",
527
+ title: "Document ID",
528
+ description: "Used to help identify the target document that this metadata is tracking state for.",
529
+ type: "string",
530
+ readOnly: !0,
531
+ components: {
532
+ input: Field
533
+ }
534
+ }), defineField({
535
+ name: "orderRank",
536
+ description: "Used to maintain order position of cards in the Tool.",
537
+ type: "string",
538
+ readOnly: !0,
539
+ initialValue: async (_, {
540
+ getClient
541
+ }) => {
542
+ const lastDocOrderRank = await getClient({
543
+ apiVersion: API_VERSION
544
+ }).fetch("*[_type == $type]|order(@[$order] desc)[0][$order]", {
545
+ order: "orderRank",
546
+ type: "workflow.metadata"
547
+ });
548
+ return initialRank(lastDocOrderRank);
549
+ }
550
+ }), defineField({
551
+ type: "array",
552
+ name: "assignees",
553
+ of: [{
554
+ type: "string"
555
+ }],
556
+ components: {
557
+ input: UserAssignmentInput
558
+ }
559
+ })]
560
+ });
561
+ function filterItemsAndSort(items, stateId, selectedUsers = [], selectedSchemaTypes = []) {
562
+ return items.filter((item) => item?._id).filter((item) => item?._metadata?.state === stateId).filter((item) => selectedUsers.length && item._metadata?.assignees?.length ? item._metadata?.assignees.some((assignee) => selectedUsers.includes(assignee)) : !selectedUsers.length).filter((item) => selectedSchemaTypes ? selectedSchemaTypes.length ? selectedSchemaTypes.includes(item._type) : !1 : !0).sort((a, b) => {
563
+ const aOrderRank = a._metadata?.orderRank || "0", bOrderRank = b._metadata?.orderRank || "0";
564
+ return aOrderRank.localeCompare(bOrderRank);
565
+ });
566
+ }
567
+ const QUERY = (
568
+ /* groq */
569
+ `*[_type == "workflow.metadata"]|order(orderRank){
570
+ "_metadata": {
571
+ _rev,
572
+ assignees,
573
+ documentId,
574
+ state,
575
+ orderRank,
576
+ "draftDocumentId": "drafts." + documentId,
577
+ }
578
+ }{
579
+ ...,
580
+ ...(
581
+ *[_id == ^._metadata.documentId || _id == ^._metadata.draftDocumentId]|order(_updatedAt)[0]{
582
+ _id,
583
+ _type,
584
+ _rev,
585
+ _updatedAt
586
+ }
587
+ )
588
+ }`
589
+ );
590
+ function useWorkflowDocuments(schemaTypes) {
591
+ const $ = c(23), toast = useToast();
592
+ let t0;
593
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
594
+ apiVersion: API_VERSION
595
+ }, $[0] = t0) : t0 = $[0];
596
+ const client = useClient(t0);
597
+ let t1;
598
+ $[1] !== schemaTypes ? (t1 = {
599
+ schemaTypes
600
+ }, $[1] = schemaTypes, $[2] = t1) : t1 = $[2];
601
+ let t2;
602
+ $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = [], $[3] = t2) : t2 = $[3];
603
+ let t3;
604
+ $[4] !== t1 ? (t3 = {
605
+ params: t1,
606
+ initialValue: t2
607
+ }, $[4] = t1, $[5] = t3) : t3 = $[5];
608
+ const {
609
+ data: _data,
610
+ loading,
611
+ error
612
+ } = useListeningQuery(QUERY, t3), data = _data;
613
+ let t4;
614
+ $[6] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t4 = [], $[6] = t4) : t4 = $[6];
615
+ const [localDocuments, setLocalDocuments] = useState(t4);
616
+ let t5, t6;
617
+ $[7] !== data ? (t5 = () => {
618
+ data && setLocalDocuments(data);
619
+ }, t6 = [data], $[7] = data, $[8] = t5, $[9] = t6) : (t5 = $[8], t6 = $[9]), useEffect(t5, t6);
620
+ let t7;
621
+ $[10] !== client || $[11] !== localDocuments || $[12] !== toast ? (t7 = async (draggedId, destination, states, newOrder) => {
622
+ const currentLocalData = localDocuments, newLocalDocuments = localDocuments.map((item) => item?._metadata?.documentId === draggedId ? {
623
+ ...item,
624
+ _metadata: {
625
+ ...item._metadata,
626
+ state: destination.droppableId,
627
+ orderRank: newOrder,
628
+ optimistic: !0
629
+ }
630
+ } : item);
631
+ setLocalDocuments(newLocalDocuments);
632
+ const newStateId = destination.droppableId, newState = states.find((s) => s.id === newStateId), document = localDocuments.find((d) => d?._metadata?.documentId === draggedId);
633
+ if (!newState?.id)
634
+ return toast.push({
635
+ title: `Could not find target state ${newStateId}`,
636
+ status: "error"
637
+ }), null;
638
+ if (!document)
639
+ return toast.push({
640
+ title: "Could not find dragged document in data",
641
+ status: "error"
642
+ }), null;
643
+ const {
644
+ _id,
645
+ _type
646
+ } = document, {
647
+ documentId,
648
+ _rev
649
+ } = document._metadata || {};
650
+ return await client.patch(`workflow-metadata.${documentId}`).ifRevisionId(_rev).set({
651
+ state: newStateId,
652
+ orderRank: newOrder
653
+ }).commit().then((res) => (toast.push({
654
+ title: newState.id === document._metadata.state ? `Reordered in "${newState?.title ?? newStateId}"` : `Moved to "${newState?.title ?? newStateId}"`,
655
+ status: "success"
656
+ }), res)).catch((err) => (setLocalDocuments(currentLocalData), toast.push({
657
+ title: `Failed to move to "${newState?.title ?? newStateId}"`,
658
+ description: err.message,
659
+ status: "error"
660
+ }), null)), {
661
+ _id,
662
+ _type,
663
+ documentId,
664
+ state: newState
665
+ };
666
+ }, $[10] = client, $[11] = localDocuments, $[12] = toast, $[13] = t7) : t7 = $[13];
667
+ const move = t7;
668
+ let t8;
669
+ $[14] !== error || $[15] !== loading || $[16] !== localDocuments ? (t8 = {
670
+ data: localDocuments,
671
+ loading,
672
+ error
673
+ }, $[14] = error, $[15] = loading, $[16] = localDocuments, $[17] = t8) : t8 = $[17];
674
+ let t9;
675
+ $[18] !== move ? (t9 = {
676
+ move
677
+ }, $[18] = move, $[19] = t9) : t9 = $[19];
678
+ let t10;
679
+ return $[20] !== t8 || $[21] !== t9 ? (t10 = {
680
+ workflowData: t8,
681
+ operations: t9
682
+ }, $[20] = t8, $[21] = t9, $[22] = t10) : t10 = $[22], t10;
683
+ }
684
+ function AvatarGroup(props) {
685
+ const $ = c(23), currentUser = useCurrentUser(), {
686
+ users,
687
+ max: t0
688
+ } = props, max = t0 === void 0 ? 4 : t0, len = users?.length;
689
+ let t1;
690
+ $[0] !== currentUser || $[1] !== users ? (t1 = currentUser?.id ? users.find((u) => u.id === currentUser.id) : void 0, $[0] = currentUser, $[1] = users, $[2] = t1) : t1 = $[2];
691
+ let t2;
692
+ if ($[3] !== currentUser?.id || $[4] !== max || $[5] !== users) {
693
+ let t32;
694
+ $[7] !== currentUser?.id ? (t32 = (u_0) => u_0.id !== currentUser?.id, $[7] = currentUser?.id, $[8] = t32) : t32 = $[8], t2 = users.filter(t32).slice(0, max - 1), $[3] = currentUser?.id, $[4] = max, $[5] = users, $[6] = t2;
695
+ } else
696
+ t2 = $[6];
697
+ let t3;
698
+ $[9] !== t1 || $[10] !== t2 ? (t3 = {
699
+ me: t1,
700
+ visibleUsers: t2
701
+ }, $[9] = t1, $[10] = t2, $[11] = t3) : t3 = $[11];
702
+ const {
703
+ me,
704
+ visibleUsers
705
+ } = t3;
706
+ if (!users?.length)
707
+ return null;
708
+ let t4;
709
+ $[12] !== me ? (t4 = me ? /* @__PURE__ */ jsx(UserAvatar, { user: me }) : null, $[12] = me, $[13] = t4) : t4 = $[13];
710
+ let t5;
711
+ $[14] !== visibleUsers ? (t5 = visibleUsers.map(_temp$4), $[14] = visibleUsers, $[15] = t5) : t5 = $[15];
712
+ let t6;
713
+ $[16] !== len || $[17] !== max ? (t6 = len > max && /* @__PURE__ */ jsx(Box, { paddingLeft: 2, children: /* @__PURE__ */ jsxs(Text, { size: 1, children: [
714
+ "+",
715
+ len - max
716
+ ] }) }), $[16] = len, $[17] = max, $[18] = t6) : t6 = $[18];
717
+ let t7;
718
+ return $[19] !== t4 || $[20] !== t5 || $[21] !== t6 ? (t7 = /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 1, children: [
719
+ t4,
720
+ t5,
721
+ t6
722
+ ] }), $[19] = t4, $[20] = t5, $[21] = t6, $[22] = t7) : t7 = $[22], t7;
723
+ }
724
+ function _temp$4(user) {
725
+ return /* @__PURE__ */ jsx(Box, { style: {
726
+ marginRight: -8
727
+ }, children: /* @__PURE__ */ jsx(UserAvatar, { user }) }, user.id);
728
+ }
729
+ function UserDisplay(props) {
730
+ const $ = c(17), {
731
+ assignees,
732
+ userList,
733
+ documentId,
734
+ disabled: t0
735
+ } = props, disabled = t0 === void 0 ? !1 : t0, [button] = useState(null), [popover, setPopover] = useState(null), [isOpen, setIsOpen] = useState(!1);
736
+ let t1;
737
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = () => setIsOpen(!1), $[0] = t1) : t1 = $[0];
738
+ const close = t1;
739
+ let t2;
740
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = () => setIsOpen(!0), $[1] = t2) : t2 = $[1];
741
+ const open = t2;
742
+ let t3;
743
+ $[2] !== button || $[3] !== popover ? (t3 = [button, popover], $[2] = button, $[3] = popover, $[4] = t3) : t3 = $[4], useClickOutside(close, t3);
744
+ let t4;
745
+ $[5] !== assignees || $[6] !== documentId || $[7] !== userList ? (t4 = /* @__PURE__ */ jsx(UserAssignment, { userList, assignees, documentId }), $[5] = assignees, $[6] = documentId, $[7] = userList, $[8] = t4) : t4 = $[8];
746
+ let t5;
747
+ $[9] !== assignees || $[10] !== disabled || $[11] !== userList ? (t5 = !assignees || assignees.length === 0 ? /* @__PURE__ */ jsx(Button, { onClick: open, fontSize: 1, padding: 2, tabIndex: -1, icon: AddIcon, text: "Assign", tone: "positive", mode: "ghost", disabled }) : /* @__PURE__ */ jsx(Grid, { children: /* @__PURE__ */ jsx(Button, { onClick: open, padding: 0, mode: "bleed", disabled, children: /* @__PURE__ */ jsx(AvatarGroup, { users: userList.filter((u) => assignees.includes(u.id)) }) }) }), $[9] = assignees, $[10] = disabled, $[11] = userList, $[12] = t5) : t5 = $[12];
748
+ let t6;
749
+ return $[13] !== isOpen || $[14] !== t4 || $[15] !== t5 ? (t6 = /* @__PURE__ */ jsx(Popover, { ref: setPopover, content: t4, portal: !0, open: isOpen, children: t5 }), $[13] = isOpen, $[14] = t4, $[15] = t5, $[16] = t6) : t6 = $[16], t6;
750
+ }
751
+ function CompleteButton(props) {
752
+ const $ = c(9), {
753
+ documentId,
754
+ disabled: t0
755
+ } = props, disabled = t0 === void 0 ? !1 : t0;
756
+ let t1;
757
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
758
+ apiVersion: API_VERSION
759
+ }, $[0] = t1) : t1 = $[0];
760
+ const client = useClient(t1), toast = useToast();
761
+ let t2;
762
+ $[1] !== client || $[2] !== toast ? (t2 = async (event) => {
763
+ const id = event.currentTarget.value;
764
+ id && await handleDeleteMetadata(client, toast, id);
765
+ }, $[1] = client, $[2] = toast, $[3] = t2) : t2 = $[3];
766
+ const handleComplete = t2;
767
+ let t3;
768
+ $[4] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: "Remove this document from Workflow" }) }), $[4] = t3) : t3 = $[4];
769
+ let t4;
770
+ return $[5] !== disabled || $[6] !== documentId || $[7] !== handleComplete ? (t4 = /* @__PURE__ */ jsx(Tooltip, { portal: !0, content: t3, children: /* @__PURE__ */ jsx(Button, { value: documentId, onClick: handleComplete, text: "Complete", icon: CheckmarkIcon, tone: "positive", mode: "ghost", fontSize: 1, padding: 2, tabIndex: -1, disabled }) }), $[5] = disabled, $[6] = documentId, $[7] = handleComplete, $[8] = t4) : t4 = $[8], t4;
771
+ }
772
+ function TimeAgo(t0) {
773
+ const $ = c(2), {
774
+ time
775
+ } = t0, timeAgo = useTimeAgo(time);
776
+ let t1;
777
+ return $[0] !== timeAgo ? (t1 = /* @__PURE__ */ jsxs("span", { title: timeAgo, children: [
778
+ timeAgo,
779
+ " ago"
780
+ ] }), $[0] = timeAgo, $[1] = t1) : t1 = $[1], t1;
781
+ }
782
+ function DraftStatus(props) {
783
+ const $ = c(10), {
784
+ document
785
+ } = props, updatedAt = document && "_updatedAt" in document && document._updatedAt;
786
+ let t0;
787
+ $[0] !== document || $[1] !== updatedAt ? (t0 = /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: document ? /* @__PURE__ */ jsxs(Fragment, { children: [
788
+ "Edited ",
789
+ updatedAt && /* @__PURE__ */ jsx(TimeAgo, { time: updatedAt })
790
+ ] }) : /* @__PURE__ */ jsx(Fragment, { children: "No unpublished edits" }) }) }), $[0] = document, $[1] = updatedAt, $[2] = t0) : t0 = $[2];
791
+ const t1 = !document, t2 = !document;
792
+ let t3;
793
+ $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = /* @__PURE__ */ jsx(EditIcon, {}), $[3] = t3) : t3 = $[3];
794
+ let t4;
795
+ $[4] !== t1 || $[5] !== t2 ? (t4 = /* @__PURE__ */ jsx(TextWithTone, { tone: "caution", dimmed: t1, muted: t2, size: 1, children: t3 }), $[4] = t1, $[5] = t2, $[6] = t4) : t4 = $[6];
796
+ let t5;
797
+ return $[7] !== t0 || $[8] !== t4 ? (t5 = /* @__PURE__ */ jsx(Tooltip, { portal: !0, content: t0, children: t4 }), $[7] = t0, $[8] = t4, $[9] = t5) : t5 = $[9], t5;
798
+ }
799
+ function PublishedStatus(props) {
800
+ const $ = c(10), {
801
+ document
802
+ } = props, updatedAt = document && "_updatedAt" in document && document._updatedAt;
803
+ let t0;
804
+ $[0] !== document || $[1] !== updatedAt ? (t0 = /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: document ? /* @__PURE__ */ jsxs(Fragment, { children: [
805
+ "Published ",
806
+ updatedAt && /* @__PURE__ */ jsx(TimeAgo, { time: updatedAt })
807
+ ] }) : /* @__PURE__ */ jsx(Fragment, { children: "Not published" }) }) }), $[0] = document, $[1] = updatedAt, $[2] = t0) : t0 = $[2];
808
+ const t1 = !document, t2 = !document;
809
+ let t3;
810
+ $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = /* @__PURE__ */ jsx(PublishIcon, {}), $[3] = t3) : t3 = $[3];
811
+ let t4;
812
+ $[4] !== t1 || $[5] !== t2 ? (t4 = /* @__PURE__ */ jsx(TextWithTone, { tone: "positive", dimmed: t1, muted: t2, size: 1, children: t3 }), $[4] = t1, $[5] = t2, $[6] = t4) : t4 = $[6];
813
+ let t5;
814
+ return $[7] !== t0 || $[8] !== t4 ? (t5 = /* @__PURE__ */ jsx(Tooltip, { portal: !0, content: t0, children: t4 }), $[7] = t0, $[8] = t4, $[9] = t5) : t5 = $[9], t5;
815
+ }
816
+ function Validate(props) {
817
+ const $ = c(7), {
818
+ documentId,
819
+ type,
820
+ onChange
821
+ } = props, {
822
+ isValidating,
823
+ validation: t0
824
+ } = useValidationStatus(documentId, type);
825
+ let t1;
826
+ $[0] !== t0 ? (t1 = t0 === void 0 ? [] : t0, $[0] = t0, $[1] = t1) : t1 = $[1];
827
+ const validation = t1;
828
+ let t2, t3;
829
+ return $[2] !== isValidating || $[3] !== onChange || $[4] !== validation ? (t2 = () => {
830
+ onChange({
831
+ isValidating,
832
+ validation
833
+ });
834
+ }, t3 = [onChange, isValidating, validation], $[2] = isValidating, $[3] = onChange, $[4] = validation, $[5] = t2, $[6] = t3) : (t2 = $[5], t3 = $[6]), useEffect(t2, t3), null;
835
+ }
836
+ function ValidationStatus(props) {
837
+ const $ = c(14), {
838
+ validation: t0
839
+ } = props;
840
+ let t1;
841
+ $[0] !== t0 ? (t1 = t0 === void 0 ? [] : t0, $[0] = t0, $[1] = t1) : t1 = $[1];
842
+ const validation = t1;
843
+ if (!validation.length)
844
+ return null;
845
+ let t2;
846
+ $[2] !== validation ? (t2 = validation.some(_temp$3), $[2] = validation, $[3] = t2) : t2 = $[3];
847
+ const hasError = t2, t3 = validation.length === 1 ? "1 validation issue" : `${validation.length} validation issues`;
848
+ let t4;
849
+ $[4] !== t3 ? (t4 = /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: t3 }) }), $[4] = t3, $[5] = t4) : t4 = $[5];
850
+ const t5 = hasError ? "critical" : "caution";
851
+ let t6;
852
+ $[6] !== hasError ? (t6 = hasError ? /* @__PURE__ */ jsx(ErrorOutlineIcon, {}) : /* @__PURE__ */ jsx(WarningOutlineIcon, {}), $[6] = hasError, $[7] = t6) : t6 = $[7];
853
+ let t7;
854
+ $[8] !== t5 || $[9] !== t6 ? (t7 = /* @__PURE__ */ jsx(TextWithTone, { tone: t5, size: 1, children: t6 }), $[8] = t5, $[9] = t6, $[10] = t7) : t7 = $[10];
855
+ let t8;
856
+ return $[11] !== t4 || $[12] !== t7 ? (t8 = /* @__PURE__ */ jsx(Tooltip, { portal: !0, content: t4, children: t7 }), $[11] = t4, $[12] = t7, $[13] = t8) : t8 = $[13], t8;
857
+ }
858
+ function _temp$3(item) {
859
+ return item.level === "error";
860
+ }
861
+ function DocumentCard(props) {
862
+ const $ = c(92), {
863
+ isDragDisabled,
864
+ isPatching,
865
+ userRoleCanDrop,
866
+ isDragging,
867
+ item,
868
+ states,
869
+ toggleInvalidDocumentId,
870
+ userList
871
+ } = props;
872
+ let t0;
873
+ $[0] !== item._metadata ? (t0 = item._metadata ?? {}, $[0] = item._metadata, $[1] = t0) : t0 = $[1];
874
+ const {
875
+ assignees: t1,
876
+ documentId
877
+ } = t0;
878
+ let t2;
879
+ $[2] !== t1 ? (t2 = t1 === void 0 ? [] : t1, $[2] = t1, $[3] = t2) : t2 = $[3];
880
+ const assignees = t2, schema = useSchema();
881
+ let t3;
882
+ if ($[4] !== item._metadata.state || $[5] !== states) {
883
+ let t42;
884
+ $[7] !== item._metadata.state ? (t42 = (s) => s.id === item._metadata?.state, $[7] = item._metadata.state, $[8] = t42) : t42 = $[8], t3 = states.find(t42), $[4] = item._metadata.state, $[5] = states, $[6] = t3;
885
+ } else
886
+ t3 = $[6];
887
+ const state = t3, isDarkMode = useTheme().sanity.color.dark, defaultCardTone = isDarkMode ? "transparent" : "default", t4 = state?.requireValidation ?? !1;
888
+ let t5;
889
+ $[9] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = [], $[9] = t5) : t5 = $[9];
890
+ let t6;
891
+ $[10] !== t4 ? (t6 = {
892
+ isValidating: t4,
893
+ validation: t5
894
+ }, $[10] = t4, $[11] = t6) : t6 = $[11];
895
+ const [optimisticValidation, setOptimisticValidation] = useState(t6), {
896
+ isValidating,
897
+ validation
898
+ } = optimisticValidation;
899
+ let t7;
900
+ $[12] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t7 = (updates) => {
901
+ setOptimisticValidation(updates);
902
+ }, $[12] = t7) : t7 = $[12];
903
+ const handleValidation = t7;
904
+ let t8;
905
+ bb0: {
906
+ let tone = defaultCardTone;
907
+ if (!userRoleCanDrop) {
908
+ t8 = isDarkMode ? "default" : "transparent";
909
+ break bb0;
910
+ }
911
+ if (!documentId) {
912
+ t8 = tone;
913
+ break bb0;
914
+ }
915
+ isPatching && (tone = isDarkMode ? "default" : "transparent"), isDragging && (tone = "positive"), state?.requireValidation && !isValidating && validation.length > 0 && (validation.some(_temp$2) ? tone = "critical" : tone = "caution"), t8 = tone;
916
+ }
917
+ const cardTone = t8;
918
+ let t10, t9;
919
+ $[13] !== documentId || $[14] !== isValidating || $[15] !== toggleInvalidDocumentId || $[16] !== validation ? (t9 = () => {
920
+ !isValidating && validation.length > 0 && validation.some(_temp2$2) ? toggleInvalidDocumentId(documentId, "ADD") : toggleInvalidDocumentId(documentId, "REMOVE");
921
+ }, t10 = [documentId, isValidating, toggleInvalidDocumentId, validation], $[13] = documentId, $[14] = isValidating, $[15] = toggleInvalidDocumentId, $[16] = validation, $[17] = t10, $[18] = t9) : (t10 = $[17], t9 = $[18]), useEffect(t9, t10);
922
+ let t11;
923
+ $[19] !== isValidating || $[20] !== validation ? (t11 = isValidating ? !1 : validation.some(_temp3$2), $[19] = isValidating, $[20] = validation, $[21] = t11) : t11 = $[21];
924
+ const hasError = t11, isLastState = states?.[states?.length - 1]?.id === item._metadata?.state;
925
+ let t12;
926
+ $[22] !== documentId || $[23] !== item._type || $[24] !== state?.requireValidation ? (t12 = state?.requireValidation ? /* @__PURE__ */ jsx(Validate, { documentId, type: item._type, onChange: handleValidation }) : null, $[22] = documentId, $[23] = item._type, $[24] = state?.requireValidation, $[25] = t12) : t12 = $[25];
927
+ const t13 = isDragging ? 3 : 1;
928
+ let t14;
929
+ $[26] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t14 = {
930
+ pointerEvents: "none"
931
+ }, $[26] = t14) : t14 = $[26];
932
+ let t15;
933
+ $[27] !== item._type || $[28] !== schema ? (t15 = schema.get(item._type), $[27] = item._type, $[28] = schema, $[29] = t15) : t15 = $[29];
934
+ const t16 = t15;
935
+ let t17;
936
+ $[30] !== item || $[31] !== t16 ? (t17 = /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Preview, { layout: "default", skipVisibilityCheck: !0, value: item, schemaType: t16 }) }), $[30] = item, $[31] = t16, $[32] = t17) : t17 = $[32];
937
+ let t18;
938
+ $[33] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t18 = {
939
+ flexShrink: 0
940
+ }, $[33] = t18) : t18 = $[33];
941
+ let t19;
942
+ $[34] !== hasError || $[35] !== isDragDisabled || $[36] !== isPatching ? (t19 = hasError || isDragDisabled || isPatching ? null : /* @__PURE__ */ jsx(DragHandleIcon, {}), $[34] = hasError, $[35] = isDragDisabled, $[36] = isPatching, $[37] = t19) : t19 = $[37];
943
+ let t20;
944
+ $[38] !== t19 ? (t20 = /* @__PURE__ */ jsx(Box, { style: t18, children: t19 }), $[38] = t19, $[39] = t20) : t20 = $[39];
945
+ let t21;
946
+ $[40] !== t17 || $[41] !== t20 ? (t21 = /* @__PURE__ */ jsxs(Flex, { align: "center", justify: "space-between", gap: 1, children: [
947
+ t17,
948
+ t20
949
+ ] }), $[40] = t17, $[41] = t20, $[42] = t21) : t21 = $[42];
950
+ let t22;
951
+ $[43] !== cardTone || $[44] !== t21 ? (t22 = /* @__PURE__ */ jsx(Card, { borderBottom: !0, radius: 2, paddingRight: 2, tone: cardTone, style: t14, children: t21 }), $[43] = cardTone, $[44] = t21, $[45] = t22) : t22 = $[45];
952
+ let t23;
953
+ $[46] !== assignees || $[47] !== documentId || $[48] !== userList || $[49] !== userRoleCanDrop ? (t23 = documentId && /* @__PURE__ */ jsx(UserDisplay, { userList, assignees, documentId, disabled: !userRoleCanDrop }), $[46] = assignees, $[47] = documentId, $[48] = userList, $[49] = userRoleCanDrop, $[50] = t23) : t23 = $[50];
954
+ let t24;
955
+ $[51] !== t23 ? (t24 = /* @__PURE__ */ jsx(Box, { flex: 1, children: t23 }), $[51] = t23, $[52] = t24) : t24 = $[52];
956
+ let t25;
957
+ $[53] !== validation ? (t25 = validation.length > 0 ? /* @__PURE__ */ jsx(ValidationStatus, { validation }) : null, $[53] = validation, $[54] = t25) : t25 = $[54];
958
+ let t26, t27;
959
+ $[55] !== item ? (t26 = /* @__PURE__ */ jsx(DraftStatus, { document: item }), t27 = /* @__PURE__ */ jsx(PublishedStatus, { document: item }), $[55] = item, $[56] = t26, $[57] = t27) : (t26 = $[56], t27 = $[57]);
960
+ const t28 = !userRoleCanDrop;
961
+ let t29;
962
+ $[58] !== item._id || $[59] !== item._type || $[60] !== t28 ? (t29 = /* @__PURE__ */ jsx(EditButton, { id: item._id, type: item._type, disabled: t28 }), $[58] = item._id, $[59] = item._type, $[60] = t28, $[61] = t29) : t29 = $[61];
963
+ let t30;
964
+ $[62] !== documentId || $[63] !== isLastState || $[64] !== states.length || $[65] !== userRoleCanDrop ? (t30 = isLastState && states.length <= 3 ? /* @__PURE__ */ jsx(CompleteButton, { documentId, disabled: !userRoleCanDrop }) : null, $[62] = documentId, $[63] = isLastState, $[64] = states.length, $[65] = userRoleCanDrop, $[66] = t30) : t30 = $[66];
965
+ let t31;
966
+ $[67] !== t24 || $[68] !== t25 || $[69] !== t26 || $[70] !== t27 || $[71] !== t29 || $[72] !== t30 ? (t31 = /* @__PURE__ */ jsxs(Flex, { align: "center", justify: "space-between", gap: 3, children: [
967
+ t24,
968
+ t25,
969
+ t26,
970
+ t27,
971
+ t29,
972
+ t30
973
+ ] }), $[67] = t24, $[68] = t25, $[69] = t26, $[70] = t27, $[71] = t29, $[72] = t30, $[73] = t31) : t31 = $[73];
974
+ let t32;
975
+ $[74] !== documentId || $[75] !== isLastState || $[76] !== states.length || $[77] !== userRoleCanDrop ? (t32 = isLastState && states.length > 3 ? /* @__PURE__ */ jsx(Stack, { paddingTop: 2, children: /* @__PURE__ */ jsx(CompleteButton, { documentId, disabled: !userRoleCanDrop }) }) : null, $[74] = documentId, $[75] = isLastState, $[76] = states.length, $[77] = userRoleCanDrop, $[78] = t32) : t32 = $[78];
976
+ let t33;
977
+ $[79] !== t31 || $[80] !== t32 ? (t33 = /* @__PURE__ */ jsxs(Card, { padding: 2, radius: 2, tone: "inherit", children: [
978
+ t31,
979
+ t32
980
+ ] }), $[79] = t31, $[80] = t32, $[81] = t33) : t33 = $[81];
981
+ let t34;
982
+ $[82] !== t22 || $[83] !== t33 ? (t34 = /* @__PURE__ */ jsxs(Stack, { children: [
983
+ t22,
984
+ t33
985
+ ] }), $[82] = t22, $[83] = t33, $[84] = t34) : t34 = $[84];
986
+ let t35;
987
+ $[85] !== cardTone || $[86] !== t13 || $[87] !== t34 ? (t35 = /* @__PURE__ */ jsx(Box, { paddingBottom: 3, paddingX: 3, children: /* @__PURE__ */ jsx(Card, { radius: 2, shadow: t13, tone: cardTone, children: t34 }) }), $[85] = cardTone, $[86] = t13, $[87] = t34, $[88] = t35) : t35 = $[88];
988
+ let t36;
989
+ return $[89] !== t12 || $[90] !== t35 ? (t36 = /* @__PURE__ */ jsxs(Fragment, { children: [
990
+ t12,
991
+ t35
992
+ ] }), $[89] = t12, $[90] = t35, $[91] = t36) : t36 = $[91], t36;
993
+ }
994
+ function _temp3$2(v_1) {
995
+ return v_1.level === "error";
996
+ }
997
+ function _temp2$2(v_0) {
998
+ return v_0.level === "error";
999
+ }
1000
+ function _temp$2(v) {
1001
+ return v.level === "error";
1002
+ }
1003
+ function getStyle(draggableStyle, virtualItem) {
1004
+ let transform = `translateY(${virtualItem.start}px)`;
1005
+ if (draggableStyle && draggableStyle.transform) {
1006
+ const draggableTransformY = parseInt(draggableStyle.transform.split(",")[1].split("px")[0], 10);
1007
+ transform = `translateY(${virtualItem.start + draggableTransformY}px)`;
1008
+ }
1009
+ return {
1010
+ position: "absolute",
1011
+ top: 0,
1012
+ left: 0,
1013
+ width: "100%",
1014
+ height: `${virtualItem.size}px`,
1015
+ transform
1016
+ };
1017
+ }
1018
+ function DocumentList(props) {
1019
+ const {
1020
+ data = [],
1021
+ invalidDocumentIds,
1022
+ patchingIds,
1023
+ selectedSchemaTypes,
1024
+ selectedUserIds,
1025
+ state,
1026
+ states,
1027
+ toggleInvalidDocumentId,
1028
+ user,
1029
+ userList,
1030
+ userRoleCanDrop
1031
+ } = props, dataFiltered = useMemo(() => data.length ? filterItemsAndSort(data, state.id, selectedUserIds, selectedSchemaTypes) : [], [data, selectedSchemaTypes, selectedUserIds, state.id]), parentRef = useRef(null), virtualizer = useVirtualizer({
1032
+ count: dataFiltered.length,
1033
+ getScrollElement: () => parentRef.current,
1034
+ getItemKey: (index) => dataFiltered[index]?._metadata?.documentId ?? index,
1035
+ estimateSize: () => 115,
1036
+ overscan: 7,
1037
+ measureElement: (element) => element.getBoundingClientRect().height || 115
1038
+ });
1039
+ return !data.length || !dataFiltered.length ? null : /* @__PURE__ */ jsx("div", { ref: parentRef, style: {
1040
+ height: "100%",
1041
+ overflow: "auto",
1042
+ // Smooths scrollbar behaviour
1043
+ overflowAnchor: "none",
1044
+ scrollBehavior: "auto",
1045
+ paddingTop: 1
1046
+ }, children: /* @__PURE__ */ jsx("div", { style: {
1047
+ height: `${virtualizer.getTotalSize()}px`,
1048
+ width: "100%",
1049
+ position: "relative"
1050
+ }, children: virtualizer.getVirtualItems().map((virtualItem) => {
1051
+ const item = dataFiltered[virtualItem.index], {
1052
+ documentId,
1053
+ assignees
1054
+ } = item?._metadata ?? {}, isInvalid = invalidDocumentIds.includes(documentId), meInAssignees = user?.id ? assignees?.includes(user.id) : !1, isDragDisabled = patchingIds.includes(documentId) || !userRoleCanDrop || isInvalid || !(!state.requireAssignment || state.requireAssignment && meInAssignees);
1055
+ return /* @__PURE__ */ jsx(Draggable, { draggableId: documentId, index: virtualItem.index, isDragDisabled, children: (draggableProvided, draggableSnapshot) => /* @__PURE__ */ jsx("div", { ref: draggableProvided.innerRef, ...draggableProvided.draggableProps, ...draggableProvided.dragHandleProps, style: getStyle(draggableProvided.draggableProps.style, virtualItem), children: /* @__PURE__ */ jsx("div", { ref: virtualizer.measureElement, "data-index": virtualItem.index, children: /* @__PURE__ */ jsx(DocumentCard, { userRoleCanDrop, isDragDisabled, isPatching: patchingIds.includes(documentId), isDragging: draggableSnapshot.isDragging, item, toggleInvalidDocumentId, userList, states }) }) }) }, virtualItem.key);
1056
+ }) }) });
1057
+ }
1058
+ function Filters(props) {
1059
+ const $ = c(27), {
1060
+ uniqueAssignedUsers: t0,
1061
+ selectedUserIds,
1062
+ schemaTypes,
1063
+ selectedSchemaTypes,
1064
+ toggleSelectedUser,
1065
+ resetSelectedUsers,
1066
+ toggleSelectedSchemaType
1067
+ } = props, uniqueAssignedUsers = t0 === void 0 ? [] : t0, currentUser = useCurrentUser(), schema = useSchema();
1068
+ let t1;
1069
+ $[0] !== selectedUserIds || $[1] !== toggleSelectedUser ? (t1 = (id) => {
1070
+ selectedUserIds.includes(id) || toggleSelectedUser(id);
1071
+ }, $[0] = selectedUserIds, $[1] = toggleSelectedUser, $[2] = t1) : t1 = $[2];
1072
+ const onAdd = t1;
1073
+ let t2;
1074
+ $[3] !== selectedUserIds || $[4] !== toggleSelectedUser ? (t2 = (id_0) => {
1075
+ selectedUserIds.includes(id_0) && toggleSelectedUser(id_0);
1076
+ }, $[3] = selectedUserIds, $[4] = toggleSelectedUser, $[5] = t2) : t2 = $[5];
1077
+ const onRemove = t2;
1078
+ let t3;
1079
+ $[6] !== resetSelectedUsers ? (t3 = () => {
1080
+ resetSelectedUsers();
1081
+ }, $[6] = resetSelectedUsers, $[7] = t3) : t3 = $[7];
1082
+ const onClear = t3;
1083
+ if (uniqueAssignedUsers.length === 0 && schemaTypes.length < 2)
1084
+ return null;
1085
+ const meInUniqueAssignees = currentUser?.id && uniqueAssignedUsers.find((u) => u.id === currentUser.id);
1086
+ let t4;
1087
+ $[8] !== currentUser?.id ? (t4 = (u_0) => u_0.id !== currentUser?.id, $[8] = currentUser?.id, $[9] = t4) : t4 = $[9];
1088
+ const uniqueAssigneesNotMe = uniqueAssignedUsers.filter(t4), T0 = Card, t5 = "primary", t6 = 2, t7 = !0;
1089
+ let t8;
1090
+ $[10] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t8 = {
1091
+ overflowX: "hidden"
1092
+ }, $[10] = t8) : t8 = $[10];
1093
+ const T1 = Flex, t9 = "center", T2 = Flex, t10 = "center", t11 = 1, t12 = 1, t13 = uniqueAssignedUsers.length > 5 ? /* @__PURE__ */ jsx(Card, { tone: "default", children: /* @__PURE__ */ jsx(MenuButton, { button: /* @__PURE__ */ jsx(Button, { padding: 3, fontSize: 1, text: "Filter Assignees", tone: "primary", icon: UserIcon }), id: "user-filters", menu: /* @__PURE__ */ jsx(Menu, { children: /* @__PURE__ */ jsx(UserSelectMenu, { value: selectedUserIds, userList: uniqueAssignedUsers, onAdd, onRemove, onClear, labels: {
1094
+ addMe: "Filter mine",
1095
+ removeMe: "Clear mine",
1096
+ clear: "Clear filters"
1097
+ } }) }), popover: {
1098
+ portal: !0
1099
+ } }) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1100
+ meInUniqueAssignees ? /* @__PURE__ */ jsxs(Fragment, { children: [
1101
+ /* @__PURE__ */ jsx(Button, { padding: 0, mode: selectedUserIds.includes(currentUser.id) ? "default" : "bleed", onClick: () => toggleSelectedUser(currentUser.id), children: /* @__PURE__ */ jsx(Flex, { padding: 1, align: "center", justify: "center", children: /* @__PURE__ */ jsx(UserAvatar, { user: currentUser.id, size: 1, withTooltip: !0 }) }) }),
1102
+ /* @__PURE__ */ jsx(Card, { borderRight: !0, style: {
1103
+ height: 30
1104
+ }, tone: "inherit" })
1105
+ ] }) : null,
1106
+ uniqueAssigneesNotMe.map((user) => /* @__PURE__ */ jsx(Button, { padding: 0, mode: selectedUserIds.includes(user.id) ? "default" : "bleed", onClick: () => toggleSelectedUser(user.id), children: /* @__PURE__ */ jsx(Flex, { padding: 1, align: "center", justify: "center", children: /* @__PURE__ */ jsx(UserAvatar, { user, size: 1, withTooltip: !0 }) }) }, user.id)),
1107
+ selectedUserIds.length > 0 ? /* @__PURE__ */ jsx(Button, { padding: 3, fontSize: 1, text: "Clear", onClick: resetSelectedUsers, mode: "ghost", icon: ResetIcon }) : null
1108
+ ] });
1109
+ let t14;
1110
+ $[11] !== T2 || $[12] !== t13 ? (t14 = /* @__PURE__ */ jsx(T2, { align: t10, gap: t11, flex: t12, children: t13 }), $[11] = T2, $[12] = t13, $[13] = t14) : t14 = $[13];
1111
+ let t15;
1112
+ $[14] !== schema || $[15] !== schemaTypes || $[16] !== selectedSchemaTypes || $[17] !== toggleSelectedSchemaType ? (t15 = schemaTypes.length > 1 ? /* @__PURE__ */ jsx(Flex, { align: "center", gap: 1, children: schemaTypes.map((typeName) => {
1113
+ const schemaType = schema.get(typeName);
1114
+ return schemaType ? /* @__PURE__ */ jsx(Button, { padding: 3, fontSize: 1, text: schemaType?.title ?? typeName, icon: schemaType?.icon ?? void 0, mode: selectedSchemaTypes.includes(typeName) ? "default" : "ghost", onClick: () => toggleSelectedSchemaType(typeName) }, typeName) : null;
1115
+ }) }) : null, $[14] = schema, $[15] = schemaTypes, $[16] = selectedSchemaTypes, $[17] = toggleSelectedSchemaType, $[18] = t15) : t15 = $[18];
1116
+ let t16;
1117
+ $[19] !== T1 || $[20] !== t14 || $[21] !== t15 ? (t16 = /* @__PURE__ */ jsxs(T1, { align: t9, children: [
1118
+ t14,
1119
+ t15
1120
+ ] }), $[19] = T1, $[20] = t14, $[21] = t15, $[22] = t16) : t16 = $[22];
1121
+ let t17;
1122
+ return $[23] !== T0 || $[24] !== t16 || $[25] !== t8 ? (t17 = /* @__PURE__ */ jsx(T0, { tone: t5, padding: t6, borderBottom: t7, style: t8, children: t16 }), $[23] = T0, $[24] = t16, $[25] = t8, $[26] = t17) : t17 = $[26], t17;
1123
+ }
1124
+ function Status(props) {
1125
+ const $ = c(7), {
1126
+ text,
1127
+ icon
1128
+ } = props, Icon = icon;
1129
+ let t0;
1130
+ $[0] !== text ? (t0 = /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: text }) }), $[0] = text, $[1] = t0) : t0 = $[1];
1131
+ let t1;
1132
+ $[2] !== Icon ? (t1 = /* @__PURE__ */ jsx(Text, { size: 1, children: /* @__PURE__ */ jsx(Icon, {}) }), $[2] = Icon, $[3] = t1) : t1 = $[3];
1133
+ let t2;
1134
+ return $[4] !== t0 || $[5] !== t1 ? (t2 = /* @__PURE__ */ jsx(Tooltip, { portal: !0, content: t0, children: t1 }), $[4] = t0, $[5] = t1, $[6] = t2) : t2 = $[6], t2;
1135
+ }
1136
+ const StyledStickyCard = /* @__PURE__ */ styled(Card).withConfig({
1137
+ displayName: "StyledStickyCard",
1138
+ componentId: "sc-akqrc2-0"
1139
+ })(() => css`
1140
+ position: sticky;
1141
+ top: 0;
1142
+ z-index: 1;
1143
+ `);
1144
+ function StateTitle(props) {
1145
+ const $ = c(18), {
1146
+ state,
1147
+ requireAssignment,
1148
+ userRoleCanDrop,
1149
+ isDropDisabled,
1150
+ draggingFrom,
1151
+ documentCount
1152
+ } = props;
1153
+ let tone = "default";
1154
+ const isSource = draggingFrom === state.id;
1155
+ draggingFrom && (tone = isDropDisabled || isSource ? "default" : "positive");
1156
+ const t0 = draggingFrom && !isDropDisabled || isSource ? "default" : "outline", t1 = !userRoleCanDrop || isDropDisabled;
1157
+ let t2;
1158
+ $[0] !== state.title || $[1] !== t0 || $[2] !== t1 || $[3] !== tone ? (t2 = /* @__PURE__ */ jsx(Badge, { mode: t0, tone, muted: t1, children: state.title }), $[0] = state.title, $[1] = t0, $[2] = t1, $[3] = tone, $[4] = t2) : t2 = $[4];
1159
+ let t3;
1160
+ $[5] !== userRoleCanDrop ? (t3 = userRoleCanDrop ? null : /* @__PURE__ */ jsx(Status, { text: "You do not have permissions to move documents to this State", icon: InfoOutlineIcon }), $[5] = userRoleCanDrop, $[6] = t3) : t3 = $[6];
1161
+ let t4;
1162
+ $[7] !== requireAssignment ? (t4 = requireAssignment ? /* @__PURE__ */ jsx(Status, { text: "You must be assigned to the document to move documents to this State", icon: UserIcon }) : null, $[7] = requireAssignment, $[8] = t4) : t4 = $[8];
1163
+ let t5;
1164
+ $[9] !== documentCount ? (t5 = documentCount > 0 ? /* @__PURE__ */ jsx(Text, { weight: "semibold", align: "right", size: 1, children: documentCount }) : null, $[9] = documentCount, $[10] = t5) : t5 = $[10];
1165
+ let t6;
1166
+ $[11] !== t5 ? (t6 = /* @__PURE__ */ jsx(Box, { flex: 1, children: t5 }), $[11] = t5, $[12] = t6) : t6 = $[12];
1167
+ let t7;
1168
+ return $[13] !== t2 || $[14] !== t3 || $[15] !== t4 || $[16] !== t6 ? (t7 = /* @__PURE__ */ jsx(StyledStickyCard, { paddingY: 4, padding: 3, tone: "inherit", children: /* @__PURE__ */ jsxs(Flex, { gap: 3, align: "center", children: [
1169
+ t2,
1170
+ t3,
1171
+ t4,
1172
+ t6
1173
+ ] }) }), $[13] = t2, $[14] = t3, $[15] = t4, $[16] = t6, $[17] = t7) : t7 = $[17], t7;
1174
+ }
1175
+ function generateMiddleValue(ranks) {
1176
+ if (!ranks.some((rank) => !rank))
1177
+ return ranks;
1178
+ const firstUndefined = ranks.findIndex((rank) => !rank), firstDefinedAfter = ranks.findIndex((rank, index) => rank && index > firstUndefined), firstDefinedBefore = ranks.findLastIndex((rank, index) => rank && index < firstUndefined);
1179
+ if (firstDefinedAfter === -1 || firstDefinedBefore === -1)
1180
+ throw new Error(`Unable to generate middle value between indexes ${firstDefinedBefore} and ${firstDefinedAfter}`);
1181
+ const beforeRank = ranks[firstDefinedBefore], afterRank = ranks[firstDefinedAfter];
1182
+ if (!beforeRank || typeof beforeRank > "u" || !afterRank || typeof afterRank > "u")
1183
+ throw new Error(`Unable to generate middle value between indexes ${firstDefinedBefore} and ${firstDefinedAfter}`);
1184
+ const between = beforeRank.between(afterRank), middle = Math.floor((firstDefinedAfter + firstDefinedBefore) / 2);
1185
+ if (ranks[middle])
1186
+ throw new Error(`Should not have overwritten value at index ${middle}`);
1187
+ return ranks[middle] = between, ranks;
1188
+ }
1189
+ function generateMultipleOrderRanks(count, start, end) {
1190
+ let ranks = [...Array(count)];
1191
+ const rankStart = start ?? LexoRank.min().genNext().genNext(), rankEnd = end ?? LexoRank.max().genPrev().genPrev();
1192
+ ranks[0] = rankStart, ranks[count - 1] = rankEnd;
1193
+ for (let i = 0; i < count; i++)
1194
+ ranks = generateMiddleValue(ranks);
1195
+ return ranks.sort((a, b) => a.toString().localeCompare(b.toString()));
1196
+ }
1197
+ const StyledFloatingCard = /* @__PURE__ */ styled(Card).withConfig({
1198
+ displayName: "StyledFloatingCard",
1199
+ componentId: "sc-ywzruw-0"
1200
+ })(() => css`
1201
+ position: fixed;
1202
+ bottom: 0;
1203
+ left: 0;
1204
+ z-index: 1000;
1205
+ `);
1206
+ function FloatingCard(t0) {
1207
+ const $ = c(7), {
1208
+ children
1209
+ } = t0;
1210
+ let t1;
1211
+ $[0] !== children ? (t1 = Array.isArray(children) ? children.some(Boolean) : !!children, $[0] = children, $[1] = t1) : t1 = $[1];
1212
+ const childrenHaveValues = t1;
1213
+ let t2;
1214
+ $[2] !== children || $[3] !== childrenHaveValues ? (t2 = childrenHaveValues ? /* @__PURE__ */ jsx(motion.div, { initial: {
1215
+ opacity: 0
1216
+ }, animate: {
1217
+ opacity: 1
1218
+ }, exit: {
1219
+ opacity: 0
1220
+ }, children: /* @__PURE__ */ jsx(StyledFloatingCard, { shadow: 3, padding: 3, margin: 3, radius: 3, children: /* @__PURE__ */ jsx(Grid, { gap: 2, children }) }) }, "floater") : null, $[2] = children, $[3] = childrenHaveValues, $[4] = t2) : t2 = $[4];
1221
+ let t3;
1222
+ return $[5] !== t2 ? (t3 = /* @__PURE__ */ jsx(AnimatePresence, { children: t2 }), $[5] = t2, $[6] = t3) : t3 = $[6], t3;
1223
+ }
1224
+ function Verify(props) {
1225
+ const $ = c(56), {
1226
+ data,
1227
+ userList,
1228
+ states
1229
+ } = props;
1230
+ let t0;
1231
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
1232
+ apiVersion: API_VERSION
1233
+ }, $[0] = t0) : t0 = $[0];
1234
+ const client = useClient(t0), toast = useToast();
1235
+ let t1;
1236
+ $[1] !== data || $[2] !== states ? (t1 = data?.length ? data.reduce((acc, cur) => {
1237
+ const {
1238
+ documentId,
1239
+ state
1240
+ } = cur._metadata ?? {};
1241
+ return !states.find((s) => s.id === state) && documentId ? [...acc, documentId] : acc;
1242
+ }, []) : [], $[1] = data, $[2] = states, $[3] = t1) : t1 = $[3];
1243
+ const documentsWithoutValidMetadataIds = t1;
1244
+ let t2;
1245
+ $[4] !== data || $[5] !== userList ? (t2 = data?.length && userList?.length ? data.reduce((acc_0, cur_0) => {
1246
+ const {
1247
+ documentId: documentId_0,
1248
+ assignees
1249
+ } = cur_0._metadata ?? {};
1250
+ return !(!assignees?.length || assignees?.every((a) => userList.find((u) => u.id === a))) && documentId_0 ? [...acc_0, documentId_0] : acc_0;
1251
+ }, []) : [], $[4] = data, $[5] = userList, $[6] = t2) : t2 = $[6];
1252
+ const documentsWithInvalidUserIds = t2;
1253
+ let t3;
1254
+ $[7] !== data ? (t3 = data?.length ? data.reduce(_temp$1, []) : [], $[7] = data, $[8] = t3) : t3 = $[8];
1255
+ const documentsWithoutOrderIds = t3;
1256
+ let t4;
1257
+ $[9] !== data ? (t4 = data?.length ? data.reduce((acc_2, cur_2) => {
1258
+ const {
1259
+ documentId: documentId_2,
1260
+ orderRank: orderRank_0
1261
+ } = cur_2._metadata ?? {};
1262
+ return orderRank_0 && data.filter((d) => d._metadata?.orderRank === orderRank_0).length > 1 && documentId_2 ? [...acc_2, documentId_2] : acc_2;
1263
+ }, []) : [], $[9] = data, $[10] = t4) : t4 = $[10];
1264
+ const documentsWithDuplicatedOrderIds = t4;
1265
+ let t5;
1266
+ $[11] !== client || $[12] !== states?.[0]?.id || $[13] !== toast ? (t5 = async (ids) => {
1267
+ toast.push({
1268
+ title: "Correcting...",
1269
+ status: "info"
1270
+ }), await ids.reduce((item, documentId_3) => item.patch(`workflow-metadata.${documentId_3}`, {
1271
+ set: {
1272
+ state: states?.[0]?.id
1273
+ }
1274
+ }), client.transaction()).commit(), toast.push({
1275
+ title: `Corrected ${ids.length === 1 ? "1 Document" : `${ids.length} Documents`}`,
1276
+ status: "success"
1277
+ });
1278
+ }, $[11] = client, $[12] = states?.[0]?.id, $[13] = toast, $[14] = t5) : t5 = $[14];
1279
+ const correctDocuments = t5;
1280
+ let t6;
1281
+ $[15] !== client || $[16] !== data || $[17] !== toast || $[18] !== userList ? (t6 = async (ids_0) => {
1282
+ toast.push({
1283
+ title: "Removing users...",
1284
+ status: "info"
1285
+ }), await ids_0.reduce((item_0, documentId_4) => {
1286
+ const {
1287
+ assignees: assignees_0
1288
+ } = data.find((d_0) => d_0._id === documentId_4)?._metadata ?? {}, validAssignees = assignees_0?.length ? assignees_0.filter((a_0) => userList.find((u_0) => u_0.id === a_0)?.id) : [];
1289
+ return item_0.patch(`workflow-metadata.${documentId_4}`, {
1290
+ set: {
1291
+ assignees: validAssignees
1292
+ }
1293
+ });
1294
+ }, client.transaction()).commit(), toast.push({
1295
+ title: `Corrected ${ids_0.length === 1 ? "1 Document" : `${ids_0.length} Documents`}`,
1296
+ status: "success"
1297
+ });
1298
+ }, $[15] = client, $[16] = data, $[17] = toast, $[18] = userList, $[19] = t6) : t6 = $[19];
1299
+ const removeUsersFromDocuments = t6;
1300
+ let t7;
1301
+ $[20] !== client || $[21] !== data || $[22] !== toast ? (t7 = async (ids_1) => {
1302
+ toast.push({
1303
+ title: "Adding ordering...",
1304
+ status: "info"
1305
+ });
1306
+ const [firstOrder, secondOrder] = [...data].slice(0, 2).map(_temp2$1), minLexo = firstOrder ? LexoRank.parse(firstOrder) : void 0, maxLexo = secondOrder ? LexoRank.parse(secondOrder) : void 0, ranks = generateMultipleOrderRanks(ids_1.length, minLexo, maxLexo), tx_1 = client.transaction();
1307
+ for (let index = 0; index < ids_1.length; index = index + 1, index)
1308
+ tx_1.patch(`workflow-metadata.${ids_1[index]}`, {
1309
+ set: {
1310
+ orderRank: ranks[index].toString()
1311
+ }
1312
+ });
1313
+ await tx_1.commit(), toast.push({
1314
+ title: `Added order to ${ids_1.length === 1 ? "1 Document" : `${ids_1.length} Documents`}`,
1315
+ status: "success"
1316
+ });
1317
+ }, $[20] = client, $[21] = data, $[22] = toast, $[23] = t7) : t7 = $[23];
1318
+ const addOrderToDocuments = t7;
1319
+ let t8;
1320
+ $[24] !== client || $[25] !== toast ? (t8 = async (ids_2) => {
1321
+ toast.push({
1322
+ title: "Adding ordering...",
1323
+ status: "info"
1324
+ });
1325
+ const ranks_0 = generateMultipleOrderRanks(ids_2.length), tx_2 = client.transaction();
1326
+ for (let index_0 = 0; index_0 < ids_2.length; index_0 = index_0 + 1, index_0)
1327
+ tx_2.patch(`workflow-metadata.${ids_2[index_0]}`, {
1328
+ set: {
1329
+ orderRank: ranks_0[index_0].toString()
1330
+ }
1331
+ });
1332
+ await tx_2.commit(), toast.push({
1333
+ title: `Added order to ${ids_2.length === 1 ? "1 Document" : `${ids_2.length} Documents`}`,
1334
+ status: "success"
1335
+ });
1336
+ }, $[24] = client, $[25] = toast, $[26] = t8) : t8 = $[26];
1337
+ const resetOrderOfAllDocuments = t8;
1338
+ let t9;
1339
+ $[27] !== data ? (t9 = data.length ? data.filter(_temp3$1).map(_temp4$1) : [], $[27] = data, $[28] = t9) : t9 = $[28];
1340
+ const orphanedMetadataDocumentIds = t9;
1341
+ let t10;
1342
+ $[29] !== client || $[30] !== orphanedMetadataDocumentIds || $[31] !== toast ? (t10 = async () => {
1343
+ toast.push({
1344
+ title: "Removing orphaned metadata...",
1345
+ status: "info"
1346
+ });
1347
+ const tx_3 = client.transaction();
1348
+ orphanedMetadataDocumentIds.forEach((id) => {
1349
+ tx_3.delete(`workflow-metadata.${id}`);
1350
+ }), await tx_3.commit(), toast.push({
1351
+ title: `Removed ${orphanedMetadataDocumentIds.length} orphaned metadata documents`,
1352
+ status: "success"
1353
+ });
1354
+ }, $[29] = client, $[30] = orphanedMetadataDocumentIds, $[31] = toast, $[32] = t10) : t10 = $[32];
1355
+ const handleOrphans = t10;
1356
+ let t11;
1357
+ $[33] !== correctDocuments || $[34] !== documentsWithoutValidMetadataIds ? (t11 = documentsWithoutValidMetadataIds.length > 0 ? /* @__PURE__ */ jsx(Button, { tone: "caution", mode: "ghost", onClick: () => correctDocuments(documentsWithoutValidMetadataIds), text: documentsWithoutValidMetadataIds.length === 1 ? "Correct 1 Document State" : `Correct ${documentsWithoutValidMetadataIds.length} Document States` }) : null, $[33] = correctDocuments, $[34] = documentsWithoutValidMetadataIds, $[35] = t11) : t11 = $[35];
1358
+ let t12;
1359
+ $[36] !== documentsWithInvalidUserIds || $[37] !== removeUsersFromDocuments ? (t12 = documentsWithInvalidUserIds.length > 0 ? /* @__PURE__ */ jsx(Button, { tone: "caution", mode: "ghost", onClick: () => removeUsersFromDocuments(documentsWithInvalidUserIds), text: documentsWithInvalidUserIds.length === 1 ? "Remove Invalid Users from 1 Document" : `Remove Invalid Users from ${documentsWithInvalidUserIds.length} Documents` }) : null, $[36] = documentsWithInvalidUserIds, $[37] = removeUsersFromDocuments, $[38] = t12) : t12 = $[38];
1360
+ let t13;
1361
+ $[39] !== addOrderToDocuments || $[40] !== documentsWithoutOrderIds ? (t13 = documentsWithoutOrderIds.length > 0 ? /* @__PURE__ */ jsx(Button, { tone: "caution", mode: "ghost", onClick: () => addOrderToDocuments(documentsWithoutOrderIds), text: documentsWithoutOrderIds.length === 1 ? "Set Order for 1 Document" : `Set Order for ${documentsWithoutOrderIds.length} Documents` }) : null, $[39] = addOrderToDocuments, $[40] = documentsWithoutOrderIds, $[41] = t13) : t13 = $[41];
1362
+ let t14;
1363
+ $[42] !== addOrderToDocuments || $[43] !== data || $[44] !== documentsWithDuplicatedOrderIds || $[45] !== resetOrderOfAllDocuments ? (t14 = documentsWithDuplicatedOrderIds.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
1364
+ /* @__PURE__ */ jsx(Button, { tone: "caution", mode: "ghost", onClick: () => addOrderToDocuments(documentsWithDuplicatedOrderIds), text: documentsWithDuplicatedOrderIds.length === 1 ? "Set Unique Order for 1 Document" : `Set Unique Order for ${documentsWithDuplicatedOrderIds.length} Documents` }),
1365
+ /* @__PURE__ */ jsx(Button, { tone: "caution", mode: "ghost", onClick: () => resetOrderOfAllDocuments(data.map(_temp5$1)), text: data.length === 1 ? "Reset Order for 1 Document" : `Reset Order for all ${data.length} Documents` })
1366
+ ] }) : null, $[42] = addOrderToDocuments, $[43] = data, $[44] = documentsWithDuplicatedOrderIds, $[45] = resetOrderOfAllDocuments, $[46] = t14) : t14 = $[46];
1367
+ let t15;
1368
+ $[47] !== handleOrphans || $[48] !== orphanedMetadataDocumentIds.length ? (t15 = orphanedMetadataDocumentIds.length > 0 ? /* @__PURE__ */ jsx(Button, { text: "Cleanup orphaned metadata", onClick: handleOrphans, tone: "caution", mode: "ghost" }) : null, $[47] = handleOrphans, $[48] = orphanedMetadataDocumentIds.length, $[49] = t15) : t15 = $[49];
1369
+ let t16;
1370
+ return $[50] !== t11 || $[51] !== t12 || $[52] !== t13 || $[53] !== t14 || $[54] !== t15 ? (t16 = /* @__PURE__ */ jsxs(FloatingCard, { children: [
1371
+ t11,
1372
+ t12,
1373
+ t13,
1374
+ t14,
1375
+ t15
1376
+ ] }), $[50] = t11, $[51] = t12, $[52] = t13, $[53] = t14, $[54] = t15, $[55] = t16) : t16 = $[55], t16;
1377
+ }
1378
+ function _temp5$1(doc_1) {
1379
+ return String(doc_1._metadata?.documentId);
1380
+ }
1381
+ function _temp4$1(doc_0) {
1382
+ return doc_0._metadata.documentId;
1383
+ }
1384
+ function _temp3$1(doc) {
1385
+ return !doc?._id;
1386
+ }
1387
+ function _temp2$1(d_1) {
1388
+ return d_1._metadata?.orderRank;
1389
+ }
1390
+ function _temp$1(acc_1, cur_1) {
1391
+ const {
1392
+ documentId: documentId_1,
1393
+ orderRank
1394
+ } = cur_1._metadata ?? {};
1395
+ return !orderRank && documentId_1 ? [...acc_1, documentId_1] : acc_1;
1396
+ }
1397
+ function WorkflowTool(props) {
1398
+ const $ = c(58);
1399
+ let t0;
1400
+ $[0] !== props.tool?.options ? (t0 = props?.tool?.options ?? {}, $[0] = props.tool?.options, $[1] = t0) : t0 = $[1];
1401
+ const {
1402
+ schemaTypes: t1,
1403
+ states: t2
1404
+ } = t0;
1405
+ let t3;
1406
+ $[2] !== t1 ? (t3 = t1 === void 0 ? [] : t1, $[2] = t1, $[3] = t3) : t3 = $[3];
1407
+ const schemaTypes = t3;
1408
+ let t4;
1409
+ $[4] !== t2 ? (t4 = t2 === void 0 ? [] : t2, $[4] = t2, $[5] = t4) : t4 = $[5];
1410
+ const states = t4, defaultCardTone = useTheme().sanity.color.dark ? "default" : "transparent", toast = useToast();
1411
+ let t5;
1412
+ $[6] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = {
1413
+ apiVersion: API_VERSION
1414
+ }, $[6] = t5) : t5 = $[6];
1415
+ const userList = useProjectUsers(t5), user = useCurrentUser(), userRoleNames = user?.roles?.length ? user?.roles.map(_temp) : [], {
1416
+ workflowData,
1417
+ operations
1418
+ } = useWorkflowDocuments(schemaTypes);
1419
+ let t6;
1420
+ $[7] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t6 = [], $[7] = t6) : t6 = $[7];
1421
+ const [patchingIds, setPatchingIds] = useState(t6), {
1422
+ data,
1423
+ loading,
1424
+ error
1425
+ } = workflowData, {
1426
+ move
1427
+ } = operations;
1428
+ let t7;
1429
+ $[8] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t7 = [], $[8] = t7) : t7 = $[8];
1430
+ const [undroppableStates, setUndroppableStates] = useState(t7), [draggingFrom, setDraggingFrom] = useState("");
1431
+ let t8;
1432
+ $[9] !== data || $[10] !== states || $[11] !== user ? (t8 = (start) => {
1433
+ const {
1434
+ draggableId,
1435
+ source
1436
+ } = start, {
1437
+ droppableId: currentStateId
1438
+ } = source;
1439
+ setDraggingFrom(currentStateId);
1440
+ const document = data.find((item) => item._metadata?.documentId === draggableId), state = states.find((s) => s.id === currentStateId);
1441
+ if (!document || !state)
1442
+ return;
1443
+ const undroppableStateIds = [], statesThatRequireAssignmentIds = states.filter(_temp2).map(_temp3);
1444
+ if (statesThatRequireAssignmentIds.length) {
1445
+ const documentAssignees = document._metadata?.assignees ?? [];
1446
+ user?.id && documentAssignees.includes(user.id) || undroppableStateIds.push(...statesThatRequireAssignmentIds);
1447
+ }
1448
+ const statesThatCannotBeTransitionedToIds = state.transitions && state.transitions.length ? states.filter((s_2) => !state.transitions?.includes(s_2.id)).map(_temp4) : [];
1449
+ statesThatCannotBeTransitionedToIds.length && undroppableStateIds.push(...statesThatCannotBeTransitionedToIds);
1450
+ const undroppableExceptSelf = undroppableStateIds.filter((id) => id !== currentStateId);
1451
+ undroppableExceptSelf.length && setUndroppableStates(undroppableExceptSelf);
1452
+ }, $[9] = data, $[10] = states, $[11] = user, $[12] = t8) : t8 = $[12];
1453
+ const handleDragStart = t8;
1454
+ let t9;
1455
+ $[13] !== data || $[14] !== move || $[15] !== patchingIds || $[16] !== states || $[17] !== toast ? (t9 = async (result) => {
1456
+ setUndroppableStates([]), setDraggingFrom("");
1457
+ const {
1458
+ draggableId: draggableId_0,
1459
+ source: source_0,
1460
+ destination
1461
+ } = result;
1462
+ if (!destination || destination.droppableId === source_0.droppableId && destination.index === source_0.index)
1463
+ return;
1464
+ const destinationStateItems = [...filterItemsAndSort(data, destination.droppableId, [], null)], destinationStateIndex = states.findIndex((s_4) => s_4.id === destination.droppableId), globalStateMinimumRank = data?.[0]?._metadata.orderRank, globalStateMaximumRank = data?.[data?.length - 1]?._metadata.orderRank;
1465
+ let newOrder;
1466
+ if (!destinationStateItems.length)
1467
+ destinationStateIndex === 0 ? newOrder = LexoRank.min().toString() : newOrder = LexoRank.min().genNext().toString();
1468
+ else if (destination.index === 0) {
1469
+ const firstItemOrderRank = [...destinationStateItems].shift()?._metadata?.orderRank;
1470
+ firstItemOrderRank && typeof firstItemOrderRank == "string" ? newOrder = LexoRank.parse(firstItemOrderRank).genPrev().toString() : destinationStateIndex === 0 ? newOrder = LexoRank.min().toString() : newOrder = LexoRank.parse(globalStateMinimumRank).between(LexoRank.min()).toString();
1471
+ } else if (destination.index + 1 === destinationStateItems.length) {
1472
+ const lastItemOrderRank = [...destinationStateItems].pop()?._metadata?.orderRank;
1473
+ lastItemOrderRank && typeof lastItemOrderRank == "string" ? newOrder = LexoRank.parse(lastItemOrderRank).genNext().toString() : destinationStateIndex === states.length - 1 ? newOrder = LexoRank.max().toString() : newOrder = LexoRank.parse(globalStateMaximumRank).between(LexoRank.min()).toString();
1474
+ } else {
1475
+ const itemBeforeRank = destinationStateItems[destination.index - 1]?._metadata?.orderRank;
1476
+ let itemBeforeRankParsed;
1477
+ itemBeforeRank ? itemBeforeRankParsed = LexoRank.parse(itemBeforeRank) : destinationStateIndex === 0 ? itemBeforeRankParsed = LexoRank.min() : itemBeforeRankParsed = LexoRank.parse(globalStateMinimumRank);
1478
+ const itemAfterRank = destinationStateItems[destination.index]?._metadata?.orderRank;
1479
+ let itemAfterRankParsed;
1480
+ itemAfterRank ? itemAfterRankParsed = LexoRank.parse(itemAfterRank) : destinationStateIndex === states.length - 1 ? itemAfterRankParsed = LexoRank.max() : itemAfterRankParsed = LexoRank.parse(globalStateMaximumRank), newOrder = itemBeforeRankParsed.between(itemAfterRankParsed).toString();
1481
+ }
1482
+ setPatchingIds([...patchingIds, draggableId_0]), toast.push({
1483
+ status: "info",
1484
+ title: "Updating document state..."
1485
+ }), await move(draggableId_0, destination, states, newOrder), setPatchingIds((ids) => ids.filter((id_0) => id_0 !== draggableId_0));
1486
+ }, $[13] = data, $[14] = move, $[15] = patchingIds, $[16] = states, $[17] = toast, $[18] = t9) : t9 = $[18];
1487
+ const handleDragEnd = t9;
1488
+ let t10;
1489
+ if ($[19] !== data || $[20] !== userList) {
1490
+ const uniqueUserIds = data.reduce(_temp5, []);
1491
+ t10 = userList.filter((u) => uniqueUserIds.includes(u.id)), $[19] = data, $[20] = userList, $[21] = t10;
1492
+ } else
1493
+ t10 = $[21];
1494
+ const uniqueAssignedUsers = t10;
1495
+ let t11;
1496
+ $[22] !== uniqueAssignedUsers ? (t11 = uniqueAssignedUsers.map(_temp6), $[22] = uniqueAssignedUsers, $[23] = t11) : t11 = $[23];
1497
+ const [selectedUserIds, setSelectedUserIds] = useState(t11);
1498
+ let t12;
1499
+ $[24] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t12 = (userId) => {
1500
+ setSelectedUserIds((prev) => prev.includes(userId) ? prev.filter((u_1) => u_1 !== userId) : [...prev, userId]);
1501
+ }, $[24] = t12) : t12 = $[24];
1502
+ const toggleSelectedUser = t12;
1503
+ let t13;
1504
+ $[25] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t13 = () => {
1505
+ setSelectedUserIds([]);
1506
+ }, $[25] = t13) : t13 = $[25];
1507
+ const resetSelectedUsers = t13, [selectedSchemaTypes, setSelectedSchemaTypes] = useState(schemaTypes);
1508
+ let t14;
1509
+ $[26] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t14 = (schemaType) => {
1510
+ setSelectedSchemaTypes((prev_0) => prev_0.includes(schemaType) ? prev_0.filter((u_2) => u_2 !== schemaType) : [...prev_0, schemaType]);
1511
+ }, $[26] = t14) : t14 = $[26];
1512
+ const toggleSelectedSchemaType = t14;
1513
+ let t15;
1514
+ $[27] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t15 = [], $[27] = t15) : t15 = $[27];
1515
+ const [invalidDocumentIds, setInvalidDocumentIds] = useState(t15);
1516
+ let t16;
1517
+ $[28] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t16 = (docId, action) => {
1518
+ setInvalidDocumentIds((prev_1) => action === "ADD" ? [...prev_1, docId] : prev_1.filter((id_1) => id_1 !== docId));
1519
+ }, $[28] = t16) : t16 = $[28];
1520
+ const toggleInvalidDocumentId = t16;
1521
+ let t17;
1522
+ $[29] !== data || $[30] !== states || $[31] !== userList ? (t17 = (provided, snapshot, rubric) => {
1523
+ const item_1 = data.find((doc) => doc?._metadata?.documentId === rubric.draggableId);
1524
+ return /* @__PURE__ */ jsx("div", { ...provided.draggableProps, ...provided.dragHandleProps, ref: provided.innerRef, children: item_1 ? /* @__PURE__ */ jsx(DocumentCard, { isDragDisabled: !1, isPatching: !1, userRoleCanDrop: !0, isDragging: snapshot.isDragging, item: item_1, states, toggleInvalidDocumentId, userList }) : /* @__PURE__ */ jsx(Feedback, { title: "Item not found", tone: "caution" }) });
1525
+ }, $[29] = data, $[30] = states, $[31] = userList, $[32] = t17) : t17 = $[32];
1526
+ const Clone = t17;
1527
+ if (!states?.length) {
1528
+ let t182;
1529
+ return $[33] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t182 = /* @__PURE__ */ jsx(Container, { width: 1, padding: 5, children: /* @__PURE__ */ jsx(Feedback, { tone: "caution", title: "Plugin options error", description: "No States defined in plugin config" }) }), $[33] = t182) : t182 = $[33], t182;
1530
+ }
1531
+ if (error && !data.length) {
1532
+ let t182;
1533
+ return $[34] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t182 = /* @__PURE__ */ jsx(Container, { width: 1, padding: 5, children: /* @__PURE__ */ jsx(Feedback, { tone: "critical", title: "Error querying for Workflow documents" }) }), $[34] = t182) : t182 = $[34], t182;
1534
+ }
1535
+ const T0 = Flex, t18 = "column", t19 = "fill", t20 = "hidden";
1536
+ let t21;
1537
+ $[35] !== data || $[36] !== states || $[37] !== userList ? (t21 = /* @__PURE__ */ jsx(Verify, { data, userList, states }), $[35] = data, $[36] = states, $[37] = userList, $[38] = t21) : t21 = $[38];
1538
+ let t22;
1539
+ $[39] !== schemaTypes || $[40] !== selectedSchemaTypes || $[41] !== selectedUserIds || $[42] !== uniqueAssignedUsers ? (t22 = /* @__PURE__ */ jsx(Filters, { uniqueAssignedUsers, selectedUserIds, toggleSelectedUser, resetSelectedUsers, schemaTypes, selectedSchemaTypes, toggleSelectedSchemaType }), $[39] = schemaTypes, $[40] = selectedSchemaTypes, $[41] = selectedUserIds, $[42] = uniqueAssignedUsers, $[43] = t22) : t22 = $[43];
1540
+ const T1 = DragDropContext, T2 = Grid, t23 = states.length, t24 = "fill", t25 = states.map((state_0, stateIndex) => {
1541
+ const userRoleCanDrop = state_0?.roles?.length ? arraysContainMatchingString(state_0.roles, userRoleNames) : !0, isDropDisabled = !userRoleCanDrop || undroppableStates.includes(state_0.id);
1542
+ return /* @__PURE__ */ jsx(Card, { borderLeft: stateIndex > 0, tone: defaultCardTone, children: /* @__PURE__ */ jsxs(Flex, { direction: "column", height: "fill", children: [
1543
+ /* @__PURE__ */ jsx(StateTitle, { state: state_0, requireAssignment: state_0.requireAssignment ?? !1, userRoleCanDrop, isDropDisabled, draggingFrom, documentCount: filterItemsAndSort(data, state_0.id, selectedUserIds, selectedSchemaTypes).length }),
1544
+ /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Droppable, { droppableId: state_0.id, isDropDisabled, mode: "virtual", renderClone: Clone, children: (provided_0, snapshot_0) => /* @__PURE__ */ jsxs(Card, { ref: provided_0.innerRef, tone: snapshot_0.isDraggingOver ? "primary" : defaultCardTone, height: "fill", children: [
1545
+ loading ? /* @__PURE__ */ jsx(Flex, { padding: 5, align: "center", justify: "center", children: /* @__PURE__ */ jsx(Spinner, { muted: !0 }) }) : null,
1546
+ /* @__PURE__ */ jsx(DocumentList, { data, invalidDocumentIds, patchingIds, selectedSchemaTypes, selectedUserIds, state: state_0, states, toggleInvalidDocumentId, user, userList, userRoleCanDrop })
1547
+ ] }) }) })
1548
+ ] }) }, state_0.id);
1549
+ });
1550
+ let t26;
1551
+ $[44] !== T2 || $[45] !== states.length || $[46] !== t25 ? (t26 = /* @__PURE__ */ jsx(T2, { columns: t23, height: t24, children: t25 }), $[44] = T2, $[45] = states.length, $[46] = t25, $[47] = t26) : t26 = $[47];
1552
+ let t27;
1553
+ $[48] !== T1 || $[49] !== handleDragEnd || $[50] !== handleDragStart || $[51] !== t26 ? (t27 = /* @__PURE__ */ jsx(T1, { onDragStart: handleDragStart, onDragEnd: handleDragEnd, children: t26 }), $[48] = T1, $[49] = handleDragEnd, $[50] = handleDragStart, $[51] = t26, $[52] = t27) : t27 = $[52];
1554
+ let t28;
1555
+ return $[53] !== T0 || $[54] !== t21 || $[55] !== t22 || $[56] !== t27 ? (t28 = /* @__PURE__ */ jsxs(T0, { direction: t18, height: t19, overflow: t20, children: [
1556
+ t21,
1557
+ t22,
1558
+ t27
1559
+ ] }), $[53] = T0, $[54] = t21, $[55] = t22, $[56] = t27, $[57] = t28) : t28 = $[57], t28;
1560
+ }
1561
+ function _temp6(u_0) {
1562
+ return u_0.id;
1563
+ }
1564
+ function _temp5(acc, item_0) {
1565
+ const {
1566
+ assignees: t0
1567
+ } = item_0._metadata ?? {}, assignees = t0 === void 0 ? [] : t0, newAssignees = assignees?.length ? assignees.filter((a) => !acc.includes(a)) : [];
1568
+ return newAssignees.length ? [...acc, ...newAssignees] : acc;
1569
+ }
1570
+ function _temp4(s_3) {
1571
+ return s_3.id;
1572
+ }
1573
+ function _temp3(s_1) {
1574
+ return s_1.id;
1575
+ }
1576
+ function _temp2(s_0) {
1577
+ return s_0.requireAssignment;
1578
+ }
1579
+ function _temp(r) {
1580
+ return r.name;
1581
+ }
1582
+ const workflowTool = (options) => ({
1583
+ name: "workflow",
1584
+ title: "Workflow",
1585
+ component: WorkflowTool,
1586
+ icon: SplitVerticalIcon,
1587
+ options
1588
+ }), workflow = definePlugin((config = DEFAULT_CONFIG) => {
1589
+ const {
1590
+ schemaTypes,
1591
+ states
1592
+ } = {
1593
+ ...DEFAULT_CONFIG,
1594
+ ...config
1595
+ };
1596
+ if (!states?.length)
1597
+ throw new Error('Workflow plugin: Missing "states" in config');
1598
+ if (!schemaTypes?.length)
1599
+ throw new Error('Workflow plugin: Missing "schemaTypes" in config');
1600
+ return {
1601
+ name: "sanity-plugin-workflow",
1602
+ schema: {
1603
+ types: [metadata(states)]
1604
+ },
1605
+ // TODO: Remove 'workflow.metadata' from list of new document types
1606
+ // ...
1607
+ studio: {
1608
+ components: {
1609
+ layout: (props) => WorkflowProvider({
1610
+ ...props,
1611
+ workflow: {
1612
+ schemaTypes,
1613
+ states
1614
+ }
1615
+ })
1616
+ }
1617
+ },
1618
+ form: {
1619
+ components: {
1620
+ input: (props) => props.id === "root" && isObjectInputProps(props) && schemaTypes.includes(props.schemaType.name) ? WorkflowSignal(props) : props.renderDefault(props)
1621
+ }
1622
+ },
1623
+ document: {
1624
+ actions: (prev, context) => schemaTypes.includes(context.schemaType) ? [(props) => BeginWorkflow(props), (props) => AssignWorkflow(props), ...states.map((state) => (props) => UpdateWorkflow(props, state)), (props) => CompleteWorkflow(props), ...prev] : prev,
1625
+ badges: (prev, context) => {
1626
+ if (!schemaTypes.includes(context.schemaType))
1627
+ return prev;
1628
+ const {
1629
+ documentId,
1630
+ currentUser
1631
+ } = context;
1632
+ return documentId ? [() => StateBadge(documentId), () => AssigneesBadge(documentId, currentUser), ...prev] : prev;
1633
+ }
1634
+ },
1635
+ tools: [
1636
+ // TODO: These configs could be read from Context
1637
+ workflowTool({
1638
+ schemaTypes,
1639
+ states
1640
+ })
1641
+ ]
1642
+ };
1643
+ });
1644
+ export {
1645
+ workflow
1646
+ };
1647
+ //# sourceMappingURL=index.js.map