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/lib/index.esm.js DELETED
@@ -1,2135 +0,0 @@
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 React, { useMemo, createContext, useContext, useState, useCallback, useEffect, useRef } from 'react';
5
- import { UserSelectMenu, useListeningQuery, useProjectUsers, Feedback } from 'sanity-plugin-utils';
6
- import { useToast, Button, Spinner, Card, Flex, Box, Text, useClickOutside, Popover, Grid, Tooltip, useTheme, Stack, MenuButton, Menu, Badge, Container } from '@sanity/ui';
7
- import { LexoRank } from 'lexorank';
8
- import { useRouter } from 'sanity/router';
9
- import { Draggable, DragDropContext, Droppable } from '@hello-pangea/dnd';
10
- import groq from 'groq';
11
- import { useVirtualizer } from '@tanstack/react-virtual';
12
- import { styled, css } from 'styled-components';
13
- import { AnimatePresence, motion } from 'framer-motion';
14
- function defineStates(states) {
15
- return states;
16
- }
17
- const API_VERSION = "2023-01-01";
18
- const DEFAULT_CONFIG = {
19
- schemaTypes: [],
20
- states: defineStates([{
21
- id: "inReview",
22
- title: "In review",
23
- color: "primary",
24
- roles: ["editor", "administrator"],
25
- transitions: ["changesRequested", "approved"]
26
- }, {
27
- id: "changesRequested",
28
- title: "Changes requested",
29
- color: "warning",
30
- roles: ["editor", "administrator"],
31
- transitions: ["approved"]
32
- }, {
33
- id: "approved",
34
- title: "Approved",
35
- color: "success",
36
- roles: ["administrator"],
37
- transitions: ["changesRequested"],
38
- requireAssignment: true
39
- }])
40
- };
41
- function UserAssignment(props) {
42
- const {
43
- assignees,
44
- userList,
45
- documentId
46
- } = props;
47
- const client = useClient({
48
- apiVersion: API_VERSION
49
- });
50
- const toast = useToast();
51
- const addAssignee = React.useCallback(userId => {
52
- const user = userList.find(u => u.id === userId);
53
- if (!userId || !user) {
54
- return toast.push({
55
- status: "error",
56
- title: "Could not find User"
57
- });
58
- }
59
- return client.patch("workflow-metadata.".concat(documentId)).setIfMissing({
60
- assignees: []
61
- }).insert("after", "assignees[-1]", [userId]).commit().then(() => {
62
- return toast.push({
63
- title: "Added ".concat(user.displayName, " to assignees"),
64
- status: "success"
65
- });
66
- }).catch(err => {
67
- console.error(err);
68
- return toast.push({
69
- title: "Failed to add assignee",
70
- description: userId,
71
- status: "error"
72
- });
73
- });
74
- }, [documentId, client, toast, userList]);
75
- const removeAssignee = React.useCallback(userId => {
76
- const user = userList.find(u => u.id === userId);
77
- if (!userId || !user) {
78
- return toast.push({
79
- status: "error",
80
- title: "Could not find User"
81
- });
82
- }
83
- return client.patch("workflow-metadata.".concat(documentId)).unset(['assignees[@ == "'.concat(userId, '"]')]).commit().then(() => {
84
- return toast.push({
85
- title: "Removed ".concat(user.displayName, " from assignees"),
86
- status: "success"
87
- });
88
- }).catch(err => {
89
- console.error(err);
90
- return toast.push({
91
- title: "Failed to remove assignee",
92
- description: documentId,
93
- status: "error"
94
- });
95
- });
96
- }, [client, toast, documentId, userList]);
97
- const clearAssignees = React.useCallback(() => {
98
- return client.patch("workflow-metadata.".concat(documentId)).unset(["assignees"]).commit().then(() => {
99
- return toast.push({
100
- title: "Cleared assignees",
101
- status: "success"
102
- });
103
- }).catch(err => {
104
- console.error(err);
105
- return toast.push({
106
- title: "Failed to clear assignees",
107
- description: documentId,
108
- status: "error"
109
- });
110
- });
111
- }, [client, toast, documentId]);
112
- return /* @__PURE__ */jsx(UserSelectMenu, {
113
- style: {
114
- maxHeight: 300
115
- },
116
- value: assignees || [],
117
- userList,
118
- onAdd: addAssignee,
119
- onClear: clearAssignees,
120
- onRemove: removeAssignee
121
- });
122
- }
123
- function useWorkflowMetadata(ids) {
124
- const {
125
- data: rawData,
126
- loading,
127
- error
128
- } = useListeningQuery('*[_type == "workflow.metadata" && documentId in $ids]{\n _id,\n _type,\n _rev,\n assignees,\n documentId,\n state,\n orderRank\n }', {
129
- params: {
130
- ids
131
- },
132
- options: {
133
- apiVersion: API_VERSION
134
- }
135
- });
136
- const keyedMetadata = useMemo(() => {
137
- if (!rawData || rawData.length === 0) return {};
138
- return rawData.reduce((acc, cur) => {
139
- return {
140
- ...acc,
141
- [cur.documentId]: cur
142
- };
143
- }, {});
144
- }, [rawData]);
145
- return {
146
- data: keyedMetadata,
147
- loading,
148
- error
149
- };
150
- }
151
- const WorkflowContext = createContext({
152
- data: {},
153
- loading: false,
154
- error: false,
155
- ids: [],
156
- addId: () => null,
157
- removeId: () => null,
158
- ...DEFAULT_CONFIG
159
- });
160
- function useWorkflowContext(id) {
161
- const current = useContext(WorkflowContext);
162
- return {
163
- ...current,
164
- metadata: id ? current.data[id] : null
165
- };
166
- }
167
- function WorkflowProvider(props) {
168
- const [ids, setIds] = useState([]);
169
- const addId = useCallback(id => setIds(current => current.includes(id) ? current : [...current, id]), []);
170
- const removeId = useCallback(id => setIds(current => current.filter(i => i !== id)), []);
171
- const {
172
- data,
173
- loading,
174
- error
175
- } = useWorkflowMetadata(ids);
176
- return /* @__PURE__ */jsx(WorkflowContext.Provider, {
177
- value: {
178
- data,
179
- loading,
180
- error,
181
- ids,
182
- addId,
183
- removeId,
184
- states: props.workflow.states,
185
- schemaTypes: props.workflow.schemaTypes
186
- },
187
- children: props.renderDefault(props)
188
- });
189
- }
190
- function AssignWorkflow(props) {
191
- var _a;
192
- const {
193
- id
194
- } = props;
195
- const {
196
- metadata,
197
- loading,
198
- error
199
- } = useWorkflowContext(id);
200
- const [isDialogOpen, setDialogOpen] = useState(false);
201
- const userList = useProjectUsers({
202
- apiVersion: API_VERSION
203
- });
204
- if (error) {
205
- console.error(error);
206
- }
207
- if (!metadata) {
208
- return null;
209
- }
210
- return {
211
- icon: UsersIcon,
212
- type: "dialog",
213
- disabled: !metadata || loading || error,
214
- label: "Assign",
215
- title: metadata ? null : "Document is not in Workflow",
216
- dialog: isDialogOpen && {
217
- type: "popover",
218
- onClose: () => {
219
- setDialogOpen(false);
220
- },
221
- content: /* @__PURE__ */jsx(UserAssignment, {
222
- userList,
223
- assignees: ((_a = metadata == null ? void 0 : metadata.assignees) == null ? void 0 : _a.length) > 0 ? metadata.assignees : [],
224
- documentId: id
225
- })
226
- },
227
- onHandle: () => {
228
- setDialogOpen(true);
229
- }
230
- };
231
- }
232
- function BeginWorkflow(props) {
233
- const {
234
- id,
235
- draft
236
- } = props;
237
- const {
238
- metadata,
239
- loading,
240
- error,
241
- states
242
- } = useWorkflowContext(id);
243
- const client = useClient({
244
- apiVersion: API_VERSION
245
- });
246
- const toast = useToast();
247
- const [beginning, setBeginning] = useState(false);
248
- const [complete, setComplete] = useState(false);
249
- if (error) {
250
- console.error(error);
251
- }
252
- const handle = useCallback(async () => {
253
- setBeginning(true);
254
- const lowestOrderFirstState = await client.fetch('*[_type == "workflow.metadata" && state == $state]|order(orderRank)[0].orderRank', {
255
- state: states[0].id
256
- });
257
- client.createIfNotExists({
258
- _id: "workflow-metadata.".concat(id),
259
- _type: "workflow.metadata",
260
- documentId: id,
261
- state: states[0].id,
262
- orderRank: lowestOrderFirstState ? LexoRank.parse(lowestOrderFirstState).genNext().toString() : LexoRank.min().toString()
263
- }).then(() => {
264
- toast.push({
265
- status: "success",
266
- title: "Workflow started",
267
- description: 'Document is now "'.concat(states[0].title, '"')
268
- });
269
- setBeginning(false);
270
- setComplete(true);
271
- });
272
- }, [id, states, client, toast]);
273
- if (!draft || complete || metadata) {
274
- return null;
275
- }
276
- return {
277
- icon: SplitVerticalIcon,
278
- type: "dialog",
279
- disabled: metadata || loading || error || beginning || complete,
280
- label: beginning ? "Beginning..." : "Begin Workflow",
281
- onHandle: () => {
282
- handle();
283
- }
284
- };
285
- }
286
- const handleDeleteMetadata = async (client, toast, id) => {
287
- try {
288
- await client.delete("workflow-metadata.".concat(id));
289
- toast.push({
290
- status: "success",
291
- title: "Workflow completed"
292
- });
293
- } catch (error) {
294
- console.error(error);
295
- toast.push({
296
- status: "error",
297
- title: "Could not complete Workflow"
298
- });
299
- }
300
- };
301
- function CompleteWorkflow(props) {
302
- const {
303
- id
304
- } = props;
305
- const {
306
- metadata,
307
- loading,
308
- error,
309
- states
310
- } = useWorkflowContext(id);
311
- const client = useClient({
312
- apiVersion: API_VERSION
313
- });
314
- const toast = useToast();
315
- if (error) {
316
- console.error(error);
317
- }
318
- const handle = useCallback(async () => {
319
- await handleDeleteMetadata(client, toast, id);
320
- }, [client, toast, id]);
321
- if (!metadata) {
322
- return null;
323
- }
324
- const state = states.find(s => s.id === metadata.state);
325
- const isLastState = (state == null ? void 0 : state.id) === states[states.length - 1].id;
326
- return {
327
- icon: CheckmarkIcon,
328
- type: "dialog",
329
- disabled: loading || error || !isLastState,
330
- label: "Complete Workflow",
331
- title: isLastState ? "Removes the document from the Workflow process" : "Cannot remove from workflow until in the last state",
332
- onHandle: async () => {
333
- await handle();
334
- props.onComplete();
335
- },
336
- color: "positive"
337
- };
338
- }
339
- function arraysContainMatchingString(one, two) {
340
- return one.some(item => two.includes(item));
341
- }
342
- function UpdateWorkflow(props, actionState) {
343
- var _a, _b, _c, _d;
344
- const {
345
- id,
346
- type
347
- } = props;
348
- const user = useCurrentUser();
349
- const client = useClient({
350
- apiVersion: API_VERSION
351
- });
352
- const toast = useToast();
353
- const currentUser = useCurrentUser();
354
- const {
355
- metadata,
356
- loading,
357
- error,
358
- states
359
- } = useWorkflowContext(id);
360
- const currentState = states.find(s => s.id === (metadata == null ? void 0 : metadata.state));
361
- const {
362
- assignees = []
363
- } = metadata != null ? metadata : {};
364
- const {
365
- validation,
366
- isValidating
367
- } = useValidationStatus(id, type);
368
- const hasValidationErrors = (currentState == null ? void 0 : currentState.requireValidation) && !isValidating && (validation == null ? void 0 : validation.length) > 0 && validation.find(v => v.level === "error");
369
- if (error) {
370
- console.error(error);
371
- }
372
- const onHandle = (documentId, newState) => {
373
- client.patch("workflow-metadata.".concat(documentId)).set({
374
- state: newState.id
375
- }).commit().then(() => {
376
- props.onComplete();
377
- toast.push({
378
- status: "success",
379
- title: 'Document state now "'.concat(newState.title, '"')
380
- });
381
- }).catch(err => {
382
- props.onComplete();
383
- console.error(err);
384
- toast.push({
385
- status: "error",
386
- title: "Document state update failed"
387
- });
388
- });
389
- };
390
- if (!metadata || currentState && currentState.id === actionState.id) {
391
- return null;
392
- }
393
- const currentStateIndex = states.findIndex(s => s.id === (currentState == null ? void 0 : currentState.id));
394
- const actionStateIndex = states.findIndex(s => s.id === actionState.id);
395
- const direction = actionStateIndex > currentStateIndex ? "promote" : "demote";
396
- const DirectionIcon = direction === "promote" ? ArrowRightIcon : ArrowLeftIcon;
397
- const directionLabel = direction === "promote" ? "Promote" : "Demote";
398
- const userRoleCanUpdateState = ((_a = user == null ? void 0 : user.roles) == null ? void 0 : _a.length) && ((_b = actionState == null ? void 0 : actionState.roles) == null ? void 0 : _b.length) ?
399
- // If the Action state is limited to specific roles
400
- // check that the current user has one of those roles
401
- arraysContainMatchingString(user.roles.map(r => r.name), actionState.roles) :
402
- // No roles specified on the next state, so anyone can update
403
- ((_c = actionState == null ? void 0 : actionState.roles) == null ? void 0 : _c.length) !== 0;
404
- const actionStateIsAValidTransition = (currentState == null ? void 0 : currentState.id) && ((_d = currentState == null ? void 0 : currentState.transitions) == null ? void 0 : _d.length) ?
405
- // If the Current State limits transitions to specific States
406
- // Check that the Action State is in Current State's transitions array
407
- currentState.transitions.includes(actionState.id) :
408
- // Otherwise this isn't a problem
409
- true;
410
- const userAssignmentCanUpdateState = actionState.requireAssignment ?
411
- // If the Action State requires assigned users
412
- // Check the current user ID is in the assignees array
413
- currentUser && (assignees == null ? void 0 : assignees.length) && assignees.includes(currentUser.id) :
414
- // Otherwise this isn't a problem
415
- true;
416
- let title = "".concat(directionLabel, ' State to "').concat(actionState.title, '"');
417
- if (!userRoleCanUpdateState) {
418
- title = "Your User role cannot ".concat(directionLabel, ' State to "').concat(actionState.title, '"');
419
- } else if (!actionStateIsAValidTransition) {
420
- title = "You cannot ".concat(directionLabel, ' State to "').concat(actionState.title, '" from "').concat(currentState == null ? void 0 : currentState.title, '"');
421
- } else if (!userAssignmentCanUpdateState) {
422
- title = "You must be assigned to the document to ".concat(directionLabel, ' State to "').concat(actionState.title, '"');
423
- } else if ((currentState == null ? void 0 : currentState.requireValidation) && isValidating) {
424
- title = "Document is validating, cannot ".concat(directionLabel, ' State to "').concat(actionState.title, '"');
425
- } else if (hasValidationErrors) {
426
- title = "Document has validation errors, cannot ".concat(directionLabel, ' State to "').concat(actionState.title, '"');
427
- }
428
- return {
429
- icon: DirectionIcon,
430
- disabled: loading || error || (currentState == null ? void 0 : currentState.requireValidation) && isValidating || hasValidationErrors || !currentState || !userRoleCanUpdateState || !actionStateIsAValidTransition || !userAssignmentCanUpdateState,
431
- title,
432
- label: actionState.title,
433
- onHandle: () => onHandle(id, actionState)
434
- };
435
- }
436
- function AssigneesBadge(documentId, currentUser) {
437
- var _a;
438
- const {
439
- metadata,
440
- loading,
441
- error
442
- } = useWorkflowContext(documentId);
443
- const userList = useProjectUsers({
444
- apiVersion: API_VERSION
445
- });
446
- if (loading || error || !metadata) {
447
- if (error) {
448
- console.error(error);
449
- }
450
- return null;
451
- }
452
- if (!((_a = metadata == null ? void 0 : metadata.assignees) == null ? void 0 : _a.length)) {
453
- return {
454
- label: "Unassigned"
455
- };
456
- }
457
- const {
458
- assignees
459
- } = metadata != null ? metadata : [];
460
- const hasMe = currentUser ? assignees.some(assignee => assignee === currentUser.id) : false;
461
- const assigneesCount = hasMe ? assignees.length - 1 : assignees.length;
462
- const assigneeUsers = userList.filter(user => assignees.includes(user.id));
463
- const title = assigneeUsers.map(user => user.displayName).join(", ");
464
- let label;
465
- if (hasMe && assigneesCount === 0) {
466
- label = "Assigned to Me";
467
- } else if (hasMe && assigneesCount > 0) {
468
- label = "Me and ".concat(assigneesCount, " ").concat(assigneesCount === 1 ? "other" : "others");
469
- } else {
470
- label = "".concat(assigneesCount, " assigned");
471
- }
472
- return {
473
- label,
474
- title,
475
- color: "primary"
476
- };
477
- }
478
- function StateBadge(documentId) {
479
- const {
480
- metadata,
481
- loading,
482
- error,
483
- states
484
- } = useWorkflowContext(documentId);
485
- const state = states.find(s => s.id === (metadata == null ? void 0 : metadata.state));
486
- if (loading || error) {
487
- if (error) {
488
- console.error(error);
489
- }
490
- return null;
491
- }
492
- if (!state) {
493
- return null;
494
- }
495
- return {
496
- label: state.title,
497
- // title: state.title,
498
- color: state == null ? void 0 : state.color
499
- };
500
- }
501
- function WorkflowSignal(props) {
502
- var _a;
503
- const documentId = ((_a = props == null ? void 0 : props.value) == null ? void 0 : _a._id) ? props.value._id.replace("drafts.", "") : null;
504
- const {
505
- addId,
506
- removeId
507
- } = useWorkflowContext();
508
- useEffect(() => {
509
- if (documentId) {
510
- addId(documentId);
511
- }
512
- return () => {
513
- if (documentId) {
514
- removeId(documentId);
515
- }
516
- };
517
- }, [documentId, addId, removeId]);
518
- return props.renderDefault(props);
519
- }
520
- function EditButton(props) {
521
- const {
522
- id,
523
- type,
524
- disabled = false
525
- } = props;
526
- const {
527
- navigateIntent
528
- } = useRouter();
529
- return /* @__PURE__ */jsx(Button, {
530
- onClick: () => navigateIntent("edit", {
531
- id,
532
- type
533
- }),
534
- mode: "ghost",
535
- fontSize: 1,
536
- padding: 2,
537
- tabIndex: -1,
538
- icon: EditIcon,
539
- text: "Edit",
540
- disabled
541
- });
542
- }
543
- function Field(props) {
544
- var _a;
545
- const schema = useSchema();
546
- const {
547
- data,
548
- loading,
549
- error
550
- } = useListeningQuery("*[_id in [$id, $draftId]]|order(_updatedAt)[0]", {
551
- params: {
552
- id: String(props.value),
553
- draftId: "drafts.".concat(String(props.value))
554
- }
555
- });
556
- if (loading) {
557
- return /* @__PURE__ */jsx(Spinner, {});
558
- }
559
- const schemaType = schema.get((_a = data == null ? void 0 : data._type) != null ? _a : "");
560
- if (error || !(data == null ? void 0 : data._type) || !schemaType) {
561
- return /* @__PURE__ */jsx(Feedback, {
562
- tone: "critical",
563
- title: "Error with query"
564
- });
565
- }
566
- return /* @__PURE__ */jsx(Card, {
567
- border: true,
568
- padding: 2,
569
- children: /* @__PURE__ */jsxs(Flex, {
570
- align: "center",
571
- justify: "space-between",
572
- gap: 2,
573
- children: [/* @__PURE__ */jsx(Preview, {
574
- layout: "default",
575
- value: data,
576
- schemaType
577
- }), /* @__PURE__ */jsx(EditButton, {
578
- id: data._id,
579
- type: data._type
580
- })]
581
- })
582
- });
583
- }
584
- const UserAssignmentInput = props => {
585
- var _a;
586
- const documentId = useFormValue(["documentId"]);
587
- const userList = useProjectUsers({
588
- apiVersion: API_VERSION
589
- });
590
- const stringValue = Array.isArray(props == null ? void 0 : props.value) && ((_a = props == null ? void 0 : props.value) == null ? void 0 : _a.length) ? props.value.map(item => String(item)) : [];
591
- return /* @__PURE__ */jsx(Card, {
592
- border: true,
593
- padding: 1,
594
- children: /* @__PURE__ */jsx(UserAssignment, {
595
- userList,
596
- assignees: stringValue,
597
- documentId: String(documentId)
598
- })
599
- });
600
- };
601
- function initialRank() {
602
- let lastRankValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
603
- const lastRank = lastRankValue && typeof lastRankValue === "string" ? LexoRank.parse(lastRankValue) : LexoRank.min();
604
- const nextRank = lastRank.genNext().genNext();
605
- return nextRank.value;
606
- }
607
- var metadata = states => defineType({
608
- type: "document",
609
- name: "workflow.metadata",
610
- title: "Workflow metadata",
611
- liveEdit: true,
612
- fields: [defineField({
613
- name: "state",
614
- 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.',
615
- readOnly: true,
616
- type: "string",
617
- options: {
618
- list: states.length ? states.map(state => ({
619
- value: state.id,
620
- title: state.title
621
- })) : [],
622
- layout: "radio"
623
- }
624
- }), defineField({
625
- name: "documentId",
626
- title: "Document ID",
627
- description: "Used to help identify the target document that this metadata is tracking state for.",
628
- type: "string",
629
- readOnly: true,
630
- components: {
631
- input: Field
632
- }
633
- }), defineField({
634
- name: "orderRank",
635
- description: "Used to maintain order position of cards in the Tool.",
636
- type: "string",
637
- readOnly: true,
638
- initialValue: async (p, _ref) => {
639
- let {
640
- getClient
641
- } = _ref;
642
- const lastDocOrderRank = await getClient({
643
- apiVersion: API_VERSION
644
- }).fetch("*[_type == $type]|order(@[$order] desc)[0][$order]", {
645
- order: "orderRank",
646
- type: "workflow.metadata"
647
- });
648
- return initialRank(lastDocOrderRank);
649
- }
650
- }), defineField({
651
- type: "array",
652
- name: "assignees",
653
- of: [{
654
- type: "string"
655
- }],
656
- components: {
657
- input: UserAssignmentInput
658
- }
659
- })]
660
- });
661
- function filterItemsAndSort(items, stateId) {
662
- let selectedUsers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
663
- let selectedSchemaTypes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
664
- return items.filter(item => item == null ? void 0 : item._id).filter(item => {
665
- var _a;
666
- return ((_a = item == null ? void 0 : item._metadata) == null ? void 0 : _a.state) === stateId;
667
- }).filter(item => {
668
- var _a, _b, _c;
669
- return selectedUsers.length && ((_b = (_a = item._metadata) == null ? void 0 : _a.assignees) == null ? void 0 : _b.length) ? (_c = item._metadata) == null ? void 0 : _c.assignees.some(assignee => selectedUsers.includes(assignee)) : !selectedUsers.length;
670
- }).filter(item => {
671
- if (!selectedSchemaTypes) {
672
- return true;
673
- }
674
- return selectedSchemaTypes.length ? selectedSchemaTypes.includes(item._type) : false;
675
- }).sort((a, b) => {
676
- var _a, _b;
677
- const aOrderRank = ((_a = a._metadata) == null ? void 0 : _a.orderRank) || "0";
678
- const bOrderRank = ((_b = b._metadata) == null ? void 0 : _b.orderRank) || "0";
679
- return aOrderRank.localeCompare(bOrderRank);
680
- });
681
- }
682
- var __freeze$2 = Object.freeze;
683
- var __defProp$2 = Object.defineProperty;
684
- var __template$2 = (cooked, raw) => __freeze$2(__defProp$2(cooked, "raw", {
685
- value: __freeze$2(raw || cooked.slice())
686
- }));
687
- var _a$2;
688
- const QUERY = groq(_a$2 || (_a$2 = __template$2(['*[_type == "workflow.metadata"]|order(orderRank){\n "_metadata": {\n _rev,\n assignees,\n documentId,\n state,\n orderRank,\n "draftDocumentId": "drafts." + documentId,\n }\n}{\n ...,\n ...(\n *[_id == ^._metadata.documentId || _id == ^._metadata.draftDocumentId]|order(_updatedAt)[0]{ \n _id, \n _type, \n _rev, \n _updatedAt \n }\n )\n}'])));
689
- function useWorkflowDocuments(schemaTypes) {
690
- const toast = useToast();
691
- const client = useClient({
692
- apiVersion: API_VERSION
693
- });
694
- const {
695
- data,
696
- loading,
697
- error
698
- } = useListeningQuery(QUERY, {
699
- params: {
700
- schemaTypes
701
- },
702
- initialValue: []
703
- });
704
- const [localDocuments, setLocalDocuments] = React.useState([]);
705
- React.useEffect(() => {
706
- if (data) {
707
- setLocalDocuments(data);
708
- }
709
- }, [data]);
710
- const move = React.useCallback(async (draggedId, destination, states, newOrder) => {
711
- const currentLocalData = localDocuments;
712
- const newLocalDocuments = localDocuments.map(item => {
713
- var _a2;
714
- if (((_a2 = item == null ? void 0 : item._metadata) == null ? void 0 : _a2.documentId) === draggedId) {
715
- return {
716
- ...item,
717
- _metadata: {
718
- ...item._metadata,
719
- state: destination.droppableId,
720
- orderRank: newOrder,
721
- // This value won't be written to the document
722
- // It's done so that un/publish operations don't happen twice
723
- // Because a moved document's card will update once optimistically
724
- // and then again when the document is updated
725
- optimistic: true
726
- }
727
- };
728
- }
729
- return item;
730
- });
731
- setLocalDocuments(newLocalDocuments);
732
- const newStateId = destination.droppableId;
733
- const newState = states.find(s => s.id === newStateId);
734
- const document = localDocuments.find(d => {
735
- var _a2;
736
- return ((_a2 = d == null ? void 0 : d._metadata) == null ? void 0 : _a2.documentId) === draggedId;
737
- });
738
- if (!(newState == null ? void 0 : newState.id)) {
739
- toast.push({
740
- title: "Could not find target state ".concat(newStateId),
741
- status: "error"
742
- });
743
- return null;
744
- }
745
- if (!document) {
746
- toast.push({
747
- title: "Could not find dragged document in data",
748
- status: "error"
749
- });
750
- return null;
751
- }
752
- const {
753
- _id,
754
- _type
755
- } = document;
756
- const {
757
- documentId,
758
- _rev
759
- } = document._metadata || {};
760
- await client.patch("workflow-metadata.".concat(documentId)).ifRevisionId(_rev).set({
761
- state: newStateId,
762
- orderRank: newOrder
763
- }).commit().then(res => {
764
- var _a2, _b;
765
- toast.push({
766
- title: newState.id === document._metadata.state ? 'Reordered in "'.concat((_a2 = newState == null ? void 0 : newState.title) != null ? _a2 : newStateId, '"') : 'Moved to "'.concat((_b = newState == null ? void 0 : newState.title) != null ? _b : newStateId, '"'),
767
- status: "success"
768
- });
769
- return res;
770
- }).catch(err => {
771
- var _a2;
772
- setLocalDocuments(currentLocalData);
773
- toast.push({
774
- title: 'Failed to move to "'.concat((_a2 = newState == null ? void 0 : newState.title) != null ? _a2 : newStateId, '"'),
775
- description: err.message,
776
- status: "error"
777
- });
778
- return null;
779
- });
780
- return {
781
- _id,
782
- _type,
783
- documentId,
784
- state: newState
785
- };
786
- }, [client, toast, localDocuments]);
787
- return {
788
- workflowData: {
789
- data: localDocuments,
790
- loading,
791
- error
792
- },
793
- operations: {
794
- move
795
- }
796
- };
797
- }
798
- function AvatarGroup(props) {
799
- const currentUser = useCurrentUser();
800
- const {
801
- users,
802
- max = 4
803
- } = props;
804
- const len = users == null ? void 0 : users.length;
805
- const {
806
- me,
807
- visibleUsers
808
- } = React.useMemo(() => {
809
- return {
810
- me: (currentUser == null ? void 0 : currentUser.id) ? users.find(u => u.id === currentUser.id) : void 0,
811
- visibleUsers: users.filter(u => u.id !== (currentUser == null ? void 0 : currentUser.id)).slice(0, max - 1)
812
- };
813
- }, [users, max, currentUser]);
814
- if (!(users == null ? void 0 : users.length)) {
815
- return null;
816
- }
817
- return /* @__PURE__ */jsxs(Flex, {
818
- align: "center",
819
- gap: 1,
820
- children: [me ? /* @__PURE__ */jsx(UserAvatar, {
821
- user: me
822
- }) : null, visibleUsers.map(user => /* @__PURE__ */jsx(Box, {
823
- style: {
824
- marginRight: -8
825
- },
826
- children: /* @__PURE__ */jsx(UserAvatar, {
827
- user
828
- })
829
- }, user.id)), len > max && /* @__PURE__ */jsx(Box, {
830
- paddingLeft: 2,
831
- children: /* @__PURE__ */jsxs(Text, {
832
- size: 1,
833
- children: ["+", len - max]
834
- })
835
- })]
836
- });
837
- }
838
- function UserDisplay(props) {
839
- const {
840
- assignees,
841
- userList,
842
- documentId,
843
- disabled = false
844
- } = props;
845
- const [button] = React.useState(null);
846
- const [popover, setPopover] = React.useState(null);
847
- const [isOpen, setIsOpen] = React.useState(false);
848
- const close = React.useCallback(() => setIsOpen(false), []);
849
- const open = React.useCallback(() => setIsOpen(true), []);
850
- useClickOutside(close, [button, popover]);
851
- return /* @__PURE__ */jsx(Popover, {
852
- ref: setPopover,
853
- content: /* @__PURE__ */jsx(UserAssignment, {
854
- userList,
855
- assignees,
856
- documentId
857
- }),
858
- portal: true,
859
- open: isOpen,
860
- children: !assignees || assignees.length === 0 ? /* @__PURE__ */jsx(Button, {
861
- onClick: open,
862
- fontSize: 1,
863
- padding: 2,
864
- tabIndex: -1,
865
- icon: AddIcon,
866
- text: "Assign",
867
- tone: "positive",
868
- mode: "ghost",
869
- disabled
870
- }) : /* @__PURE__ */jsx(Grid, {
871
- children: /* @__PURE__ */jsx(Button, {
872
- onClick: open,
873
- padding: 0,
874
- mode: "bleed",
875
- disabled,
876
- children: /* @__PURE__ */jsx(AvatarGroup, {
877
- users: userList.filter(u => assignees.includes(u.id))
878
- })
879
- })
880
- })
881
- });
882
- }
883
- function CompleteButton(props) {
884
- const {
885
- documentId,
886
- disabled = false
887
- } = props;
888
- const client = useClient({
889
- apiVersion: API_VERSION
890
- });
891
- const toast = useToast();
892
- const handleComplete = React.useCallback(event => {
893
- const id = event.currentTarget.value;
894
- if (!id) {
895
- return;
896
- }
897
- handleDeleteMetadata(client, toast, id);
898
- }, [client, toast]);
899
- return /* @__PURE__ */jsx(Tooltip, {
900
- portal: true,
901
- content: /* @__PURE__ */jsx(Box, {
902
- padding: 2,
903
- children: /* @__PURE__ */jsx(Text, {
904
- size: 1,
905
- children: "Remove this document from Workflow"
906
- })
907
- }),
908
- children: /* @__PURE__ */jsx(Button, {
909
- value: documentId,
910
- onClick: handleComplete,
911
- text: "Complete",
912
- icon: CheckmarkIcon,
913
- tone: "positive",
914
- mode: "ghost",
915
- fontSize: 1,
916
- padding: 2,
917
- tabIndex: -1,
918
- disabled
919
- })
920
- });
921
- }
922
- function TimeAgo(_ref2) {
923
- let {
924
- time
925
- } = _ref2;
926
- const timeAgo = useTimeAgo(time);
927
- return /* @__PURE__ */jsxs("span", {
928
- title: timeAgo,
929
- children: [timeAgo, " ago"]
930
- });
931
- }
932
- function DraftStatus(props) {
933
- const {
934
- document
935
- } = props;
936
- const updatedAt = document && "_updatedAt" in document && document._updatedAt;
937
- return /* @__PURE__ */jsx(Tooltip, {
938
- portal: true,
939
- content: /* @__PURE__ */jsx(Box, {
940
- padding: 2,
941
- children: /* @__PURE__ */jsx(Text, {
942
- size: 1,
943
- children: document ? /* @__PURE__ */jsxs(Fragment, {
944
- children: ["Edited ", updatedAt && /* @__PURE__ */jsx(TimeAgo, {
945
- time: updatedAt
946
- })]
947
- }) : /* @__PURE__ */jsx(Fragment, {
948
- children: "No unpublished edits"
949
- })
950
- })
951
- }),
952
- children: /* @__PURE__ */jsx(TextWithTone, {
953
- tone: "caution",
954
- dimmed: !document,
955
- muted: !document,
956
- size: 1,
957
- children: /* @__PURE__ */jsx(EditIcon, {})
958
- })
959
- });
960
- }
961
- function PublishedStatus(props) {
962
- const {
963
- document
964
- } = props;
965
- const updatedAt = document && "_updatedAt" in document && document._updatedAt;
966
- return /* @__PURE__ */jsx(Tooltip, {
967
- portal: true,
968
- content: /* @__PURE__ */jsx(Box, {
969
- padding: 2,
970
- children: /* @__PURE__ */jsx(Text, {
971
- size: 1,
972
- children: document ? /* @__PURE__ */jsxs(Fragment, {
973
- children: ["Published ", updatedAt && /* @__PURE__ */jsx(TimeAgo, {
974
- time: updatedAt
975
- })]
976
- }) : /* @__PURE__ */jsx(Fragment, {
977
- children: "Not published"
978
- })
979
- })
980
- }),
981
- children: /* @__PURE__ */jsx(TextWithTone, {
982
- tone: "positive",
983
- dimmed: !document,
984
- muted: !document,
985
- size: 1,
986
- children: /* @__PURE__ */jsx(PublishIcon, {})
987
- })
988
- });
989
- }
990
- function Validate(props) {
991
- const {
992
- documentId,
993
- type,
994
- onChange
995
- } = props;
996
- const {
997
- isValidating,
998
- validation = []
999
- } = useValidationStatus(documentId, type);
1000
- useEffect(() => {
1001
- onChange({
1002
- isValidating,
1003
- validation
1004
- });
1005
- }, [onChange, isValidating, validation]);
1006
- return null;
1007
- }
1008
- function ValidationStatus(props) {
1009
- const {
1010
- validation = []
1011
- } = props;
1012
- if (!validation.length) {
1013
- return null;
1014
- }
1015
- const hasError = validation.some(item => item.level === "error");
1016
- return /* @__PURE__ */jsx(Tooltip, {
1017
- portal: true,
1018
- content: /* @__PURE__ */jsx(Box, {
1019
- padding: 2,
1020
- children: /* @__PURE__ */jsx(Text, {
1021
- size: 1,
1022
- children: validation.length === 1 ? "1 validation issue" : "".concat(validation.length, " validation issues")
1023
- })
1024
- }),
1025
- children: /* @__PURE__ */jsx(TextWithTone, {
1026
- tone: hasError ? "critical" : "caution",
1027
- size: 1,
1028
- children: hasError ? /* @__PURE__ */jsx(ErrorOutlineIcon, {}) : /* @__PURE__ */jsx(WarningOutlineIcon, {})
1029
- })
1030
- });
1031
- }
1032
- function DocumentCard(props) {
1033
- var _a, _b;
1034
- const {
1035
- isDragDisabled,
1036
- isPatching,
1037
- userRoleCanDrop,
1038
- isDragging,
1039
- item,
1040
- states,
1041
- toggleInvalidDocumentId,
1042
- userList
1043
- } = props;
1044
- const {
1045
- assignees = [],
1046
- documentId
1047
- } = (_a = item._metadata) != null ? _a : {};
1048
- const schema = useSchema();
1049
- const state = states.find(s => {
1050
- var _a2;
1051
- return s.id === ((_a2 = item._metadata) == null ? void 0 : _a2.state);
1052
- });
1053
- const isDarkMode = useTheme().sanity.color.dark;
1054
- const defaultCardTone = isDarkMode ? "transparent" : "default";
1055
- const [optimisticValidation, setOptimisticValidation] = useState({
1056
- isValidating: (_b = state == null ? void 0 : state.requireValidation) != null ? _b : false,
1057
- validation: []
1058
- });
1059
- const {
1060
- isValidating,
1061
- validation
1062
- } = optimisticValidation;
1063
- const handleValidation = useCallback(updates => {
1064
- setOptimisticValidation(updates);
1065
- }, []);
1066
- const cardTone = useMemo(() => {
1067
- let tone = defaultCardTone;
1068
- if (!userRoleCanDrop) return isDarkMode ? "default" : "transparent";
1069
- if (!documentId) return tone;
1070
- if (isPatching) tone = isDarkMode ? "default" : "transparent";
1071
- if (isDragging) tone = "positive";
1072
- if ((state == null ? void 0 : state.requireValidation) && !isValidating && validation.length > 0) {
1073
- if (validation.some(v => v.level === "error")) {
1074
- tone = "critical";
1075
- } else {
1076
- tone = "caution";
1077
- }
1078
- }
1079
- return tone;
1080
- }, [defaultCardTone, userRoleCanDrop, isPatching, isDarkMode, documentId, isDragging, isValidating, validation, state == null ? void 0 : state.requireValidation]);
1081
- useEffect(() => {
1082
- if (!isValidating && validation.length > 0) {
1083
- if (validation.some(v => v.level === "error")) {
1084
- toggleInvalidDocumentId(documentId, "ADD");
1085
- } else {
1086
- toggleInvalidDocumentId(documentId, "REMOVE");
1087
- }
1088
- } else {
1089
- toggleInvalidDocumentId(documentId, "REMOVE");
1090
- }
1091
- }, [documentId, isValidating, toggleInvalidDocumentId, validation]);
1092
- const hasError = useMemo(() => isValidating ? false : validation.some(v => v.level === "error"), [isValidating, validation]);
1093
- const isLastState = useMemo(() => {
1094
- var _a2;
1095
- return states[states.length - 1].id === ((_a2 = item._metadata) == null ? void 0 : _a2.state);
1096
- }, [states, item._metadata.state]);
1097
- return /* @__PURE__ */jsxs(Fragment, {
1098
- children: [(state == null ? void 0 : state.requireValidation) ? /* @__PURE__ */jsx(Validate, {
1099
- documentId,
1100
- type: item._type,
1101
- onChange: handleValidation
1102
- }) : null, /* @__PURE__ */jsx(Box, {
1103
- paddingBottom: 3,
1104
- paddingX: 3,
1105
- children: /* @__PURE__ */jsx(Card, {
1106
- radius: 2,
1107
- shadow: isDragging ? 3 : 1,
1108
- tone: cardTone,
1109
- children: /* @__PURE__ */jsxs(Stack, {
1110
- children: [/* @__PURE__ */jsx(Card, {
1111
- borderBottom: true,
1112
- radius: 2,
1113
- paddingRight: 2,
1114
- tone: cardTone,
1115
- style: {
1116
- pointerEvents: "none"
1117
- },
1118
- children: /* @__PURE__ */jsxs(Flex, {
1119
- align: "center",
1120
- justify: "space-between",
1121
- gap: 1,
1122
- children: [/* @__PURE__ */jsx(Box, {
1123
- flex: 1,
1124
- children: /* @__PURE__ */jsx(Preview, {
1125
- layout: "default",
1126
- skipVisibilityCheck: true,
1127
- value: item,
1128
- schemaType: schema.get(item._type)
1129
- })
1130
- }), /* @__PURE__ */jsx(Box, {
1131
- style: {
1132
- flexShrink: 0
1133
- },
1134
- children: hasError || isDragDisabled || isPatching ? null : /* @__PURE__ */jsx(DragHandleIcon, {})
1135
- })]
1136
- })
1137
- }), /* @__PURE__ */jsxs(Card, {
1138
- padding: 2,
1139
- radius: 2,
1140
- tone: "inherit",
1141
- children: [/* @__PURE__ */jsxs(Flex, {
1142
- align: "center",
1143
- justify: "space-between",
1144
- gap: 3,
1145
- children: [/* @__PURE__ */jsx(Box, {
1146
- flex: 1,
1147
- children: documentId && /* @__PURE__ */jsx(UserDisplay, {
1148
- userList,
1149
- assignees,
1150
- documentId,
1151
- disabled: !userRoleCanDrop
1152
- })
1153
- }), validation.length > 0 ? /* @__PURE__ */jsx(ValidationStatus, {
1154
- validation
1155
- }) : null, /* @__PURE__ */jsx(DraftStatus, {
1156
- document: item
1157
- }), /* @__PURE__ */jsx(PublishedStatus, {
1158
- document: item
1159
- }), /* @__PURE__ */jsx(EditButton, {
1160
- id: item._id,
1161
- type: item._type,
1162
- disabled: !userRoleCanDrop
1163
- }), isLastState && states.length <= 3 ? /* @__PURE__ */jsx(CompleteButton, {
1164
- documentId,
1165
- disabled: !userRoleCanDrop
1166
- }) : null]
1167
- }), isLastState && states.length > 3 ? /* @__PURE__ */jsx(Stack, {
1168
- paddingTop: 2,
1169
- children: /* @__PURE__ */jsx(CompleteButton, {
1170
- documentId,
1171
- disabled: !userRoleCanDrop
1172
- })
1173
- }) : null]
1174
- })]
1175
- })
1176
- })
1177
- })]
1178
- });
1179
- }
1180
- function getStyle(draggableStyle, virtualItem) {
1181
- let transform = "translateY(".concat(virtualItem.start, "px)");
1182
- if (draggableStyle && draggableStyle.transform) {
1183
- const draggableTransformY = parseInt(draggableStyle.transform.split(",")[1].split("px")[0], 10);
1184
- transform = "translateY(".concat(virtualItem.start + draggableTransformY, "px)");
1185
- }
1186
- return {
1187
- position: "absolute",
1188
- top: 0,
1189
- left: 0,
1190
- width: "100%",
1191
- height: "".concat(virtualItem.size, "px"),
1192
- transform
1193
- };
1194
- }
1195
- function DocumentList(props) {
1196
- const {
1197
- data = [],
1198
- invalidDocumentIds,
1199
- patchingIds,
1200
- selectedSchemaTypes,
1201
- selectedUserIds,
1202
- state,
1203
- states,
1204
- toggleInvalidDocumentId,
1205
- user,
1206
- userList,
1207
- userRoleCanDrop
1208
- } = props;
1209
- const dataFiltered = useMemo(() => {
1210
- return data.length ? filterItemsAndSort(data, state.id, selectedUserIds, selectedSchemaTypes) : [];
1211
- }, [data, selectedSchemaTypes, selectedUserIds, state.id]);
1212
- const parentRef = useRef(null);
1213
- const virtualizer = useVirtualizer({
1214
- count: dataFiltered.length,
1215
- getScrollElement: () => parentRef.current,
1216
- getItemKey: index => {
1217
- var _a, _b, _c;
1218
- return (_c = (_b = (_a = dataFiltered[index]) == null ? void 0 : _a._metadata) == null ? void 0 : _b.documentId) != null ? _c : index;
1219
- },
1220
- estimateSize: () => 115,
1221
- overscan: 7,
1222
- measureElement: element => {
1223
- return element.getBoundingClientRect().height || 115;
1224
- }
1225
- });
1226
- if (!data.length || !dataFiltered.length) {
1227
- return null;
1228
- }
1229
- return /* @__PURE__ */jsx("div", {
1230
- ref: parentRef,
1231
- style: {
1232
- height: "100%",
1233
- overflow: "auto",
1234
- // Smooths scrollbar behaviour
1235
- overflowAnchor: "none",
1236
- scrollBehavior: "auto",
1237
- paddingTop: 1
1238
- },
1239
- children: /* @__PURE__ */jsx("div", {
1240
- style: {
1241
- height: "".concat(virtualizer.getTotalSize(), "px"),
1242
- width: "100%",
1243
- position: "relative"
1244
- },
1245
- children: virtualizer.getVirtualItems().map(virtualItem => {
1246
- var _a;
1247
- const item = dataFiltered[virtualItem.index];
1248
- const {
1249
- documentId,
1250
- assignees
1251
- } = (_a = item == null ? void 0 : item._metadata) != null ? _a : {};
1252
- const isInvalid = invalidDocumentIds.includes(documentId);
1253
- const meInAssignees = (user == null ? void 0 : user.id) ? assignees == null ? void 0 : assignees.includes(user.id) : false;
1254
- const isDragDisabled = patchingIds.includes(documentId) || !userRoleCanDrop || isInvalid || !(state.requireAssignment ? state.requireAssignment && meInAssignees : true);
1255
- return /* @__PURE__ */jsx(Draggable, {
1256
- draggableId: documentId,
1257
- index: virtualItem.index,
1258
- isDragDisabled,
1259
- children: (draggableProvided, draggableSnapshot) => /* @__PURE__ */jsx("div", {
1260
- ref: draggableProvided.innerRef,
1261
- ...draggableProvided.draggableProps,
1262
- ...draggableProvided.dragHandleProps,
1263
- style: getStyle(draggableProvided.draggableProps.style, virtualItem),
1264
- children: /* @__PURE__ */jsx("div", {
1265
- ref: virtualizer.measureElement,
1266
- "data-index": virtualItem.index,
1267
- children: /* @__PURE__ */jsx(DocumentCard, {
1268
- userRoleCanDrop,
1269
- isDragDisabled,
1270
- isPatching: patchingIds.includes(documentId),
1271
- isDragging: draggableSnapshot.isDragging,
1272
- item,
1273
- toggleInvalidDocumentId,
1274
- userList,
1275
- states
1276
- })
1277
- })
1278
- })
1279
- }, virtualItem.key);
1280
- })
1281
- })
1282
- });
1283
- }
1284
- function Filters(props) {
1285
- const {
1286
- uniqueAssignedUsers = [],
1287
- selectedUserIds,
1288
- schemaTypes,
1289
- selectedSchemaTypes,
1290
- toggleSelectedUser,
1291
- resetSelectedUsers,
1292
- toggleSelectedSchemaType
1293
- } = props;
1294
- const currentUser = useCurrentUser();
1295
- const schema = useSchema();
1296
- const onAdd = useCallback(id => {
1297
- if (!selectedUserIds.includes(id)) {
1298
- toggleSelectedUser(id);
1299
- }
1300
- }, [selectedUserIds, toggleSelectedUser]);
1301
- const onRemove = useCallback(id => {
1302
- if (selectedUserIds.includes(id)) {
1303
- toggleSelectedUser(id);
1304
- }
1305
- }, [selectedUserIds, toggleSelectedUser]);
1306
- const onClear = useCallback(() => {
1307
- resetSelectedUsers();
1308
- }, [resetSelectedUsers]);
1309
- if (uniqueAssignedUsers.length === 0 && schemaTypes.length < 2) {
1310
- return null;
1311
- }
1312
- const meInUniqueAssignees = (currentUser == null ? void 0 : currentUser.id) && uniqueAssignedUsers.find(u => u.id === currentUser.id);
1313
- const uniqueAssigneesNotMe = uniqueAssignedUsers.filter(u => u.id !== (currentUser == null ? void 0 : currentUser.id));
1314
- return /* @__PURE__ */jsx(Card, {
1315
- tone: "primary",
1316
- padding: 2,
1317
- borderBottom: true,
1318
- style: {
1319
- overflowX: "hidden"
1320
- },
1321
- children: /* @__PURE__ */jsxs(Flex, {
1322
- align: "center",
1323
- children: [/* @__PURE__ */jsx(Flex, {
1324
- align: "center",
1325
- gap: 1,
1326
- flex: 1,
1327
- children: uniqueAssignedUsers.length > 5 ? /* @__PURE__ */jsx(Card, {
1328
- tone: "default",
1329
- children: /* @__PURE__ */jsx(MenuButton, {
1330
- button: /* @__PURE__ */jsx(Button, {
1331
- padding: 3,
1332
- fontSize: 1,
1333
- text: "Filter Assignees",
1334
- tone: "primary",
1335
- icon: UserIcon
1336
- }),
1337
- id: "user-filters",
1338
- menu: /* @__PURE__ */jsx(Menu, {
1339
- children: /* @__PURE__ */jsx(UserSelectMenu, {
1340
- value: selectedUserIds,
1341
- userList: uniqueAssignedUsers,
1342
- onAdd,
1343
- onRemove,
1344
- onClear,
1345
- labels: {
1346
- addMe: "Filter mine",
1347
- removeMe: "Clear mine",
1348
- clear: "Clear filters"
1349
- }
1350
- })
1351
- }),
1352
- popover: {
1353
- portal: true
1354
- }
1355
- })
1356
- }) : /* @__PURE__ */jsxs(Fragment, {
1357
- children: [meInUniqueAssignees ? /* @__PURE__ */jsxs(Fragment, {
1358
- children: [/* @__PURE__ */jsx(Button, {
1359
- padding: 0,
1360
- mode: selectedUserIds.includes(currentUser.id) ? "default" : "bleed",
1361
- onClick: () => toggleSelectedUser(currentUser.id),
1362
- children: /* @__PURE__ */jsx(Flex, {
1363
- padding: 1,
1364
- align: "center",
1365
- justify: "center",
1366
- children: /* @__PURE__ */jsx(UserAvatar, {
1367
- user: currentUser.id,
1368
- size: 1,
1369
- withTooltip: true
1370
- })
1371
- })
1372
- }), /* @__PURE__ */jsx(Card, {
1373
- borderRight: true,
1374
- style: {
1375
- height: 30
1376
- },
1377
- tone: "inherit"
1378
- })]
1379
- }) : null, uniqueAssigneesNotMe.map(user => /* @__PURE__ */jsx(Button, {
1380
- padding: 0,
1381
- mode: selectedUserIds.includes(user.id) ? "default" : "bleed",
1382
- onClick: () => toggleSelectedUser(user.id),
1383
- children: /* @__PURE__ */jsx(Flex, {
1384
- padding: 1,
1385
- align: "center",
1386
- justify: "center",
1387
- children: /* @__PURE__ */jsx(UserAvatar, {
1388
- user,
1389
- size: 1,
1390
- withTooltip: true
1391
- })
1392
- })
1393
- }, user.id)), selectedUserIds.length > 0 ? /* @__PURE__ */jsx(Button, {
1394
- padding: 3,
1395
- fontSize: 1,
1396
- text: "Clear",
1397
- onClick: resetSelectedUsers,
1398
- mode: "ghost",
1399
- icon: ResetIcon
1400
- }) : null]
1401
- })
1402
- }), schemaTypes.length > 1 ? /* @__PURE__ */jsx(Flex, {
1403
- align: "center",
1404
- gap: 1,
1405
- children: schemaTypes.map(typeName => {
1406
- var _a, _b;
1407
- const schemaType = schema.get(typeName);
1408
- if (!schemaType) {
1409
- return null;
1410
- }
1411
- return /* @__PURE__ */jsx(Button, {
1412
- padding: 3,
1413
- fontSize: 1,
1414
- text: (_a = schemaType == null ? void 0 : schemaType.title) != null ? _a : typeName,
1415
- icon: (_b = schemaType == null ? void 0 : schemaType.icon) != null ? _b : void 0,
1416
- mode: selectedSchemaTypes.includes(typeName) ? "default" : "ghost",
1417
- onClick: () => toggleSelectedSchemaType(typeName)
1418
- }, typeName);
1419
- })
1420
- }) : null]
1421
- })
1422
- });
1423
- }
1424
- function Status(props) {
1425
- const {
1426
- text,
1427
- icon
1428
- } = props;
1429
- const Icon = icon;
1430
- return /* @__PURE__ */jsx(Tooltip, {
1431
- portal: true,
1432
- content: /* @__PURE__ */jsx(Box, {
1433
- padding: 2,
1434
- children: /* @__PURE__ */jsx(Text, {
1435
- size: 1,
1436
- children: text
1437
- })
1438
- }),
1439
- children: /* @__PURE__ */jsx(Text, {
1440
- size: 1,
1441
- children: /* @__PURE__ */jsx(Icon, {})
1442
- })
1443
- });
1444
- }
1445
- var __freeze$1 = Object.freeze;
1446
- var __defProp$1 = Object.defineProperty;
1447
- var __template$1 = (cooked, raw) => __freeze$1(__defProp$1(cooked, "raw", {
1448
- value: __freeze$1(raw || cooked.slice())
1449
- }));
1450
- var _a$1;
1451
- const StyledStickyCard = styled(Card)(() => css(_a$1 || (_a$1 = __template$1(["\n position: sticky;\n top: 0;\n z-index: 1;\n "]))));
1452
- function StateTitle(props) {
1453
- const {
1454
- state,
1455
- requireAssignment,
1456
- userRoleCanDrop,
1457
- isDropDisabled,
1458
- draggingFrom,
1459
- documentCount
1460
- } = props;
1461
- let tone = "default";
1462
- const isSource = draggingFrom === state.id;
1463
- if (draggingFrom) {
1464
- tone = isDropDisabled || isSource ? "default" : "positive";
1465
- }
1466
- return /* @__PURE__ */jsx(StyledStickyCard, {
1467
- paddingY: 4,
1468
- padding: 3,
1469
- tone: "inherit",
1470
- children: /* @__PURE__ */jsxs(Flex, {
1471
- gap: 3,
1472
- align: "center",
1473
- children: [/* @__PURE__ */jsx(Badge, {
1474
- mode: draggingFrom && !isDropDisabled || isSource ? "default" : "outline",
1475
- tone,
1476
- muted: !userRoleCanDrop || isDropDisabled,
1477
- children: state.title
1478
- }), userRoleCanDrop ? null : /* @__PURE__ */jsx(Status, {
1479
- text: "You do not have permissions to move documents to this State",
1480
- icon: InfoOutlineIcon
1481
- }), requireAssignment ? /* @__PURE__ */jsx(Status, {
1482
- text: "You must be assigned to the document to move documents to this State",
1483
- icon: UserIcon
1484
- }) : null, /* @__PURE__ */jsx(Box, {
1485
- flex: 1,
1486
- children: documentCount > 0 ? /* @__PURE__ */jsx(Text, {
1487
- weight: "semibold",
1488
- align: "right",
1489
- size: 1,
1490
- children: documentCount
1491
- }) : null
1492
- })]
1493
- })
1494
- });
1495
- }
1496
- function generateMiddleValue(ranks) {
1497
- if (!ranks.some(rank => !rank)) {
1498
- return ranks;
1499
- }
1500
- const firstUndefined = ranks.findIndex(rank => !rank);
1501
- const firstDefinedAfter = ranks.findIndex((rank, index) => rank && index > firstUndefined);
1502
- const firstDefinedBefore = ranks.findLastIndex((rank, index) => rank && index < firstUndefined);
1503
- if (firstDefinedAfter === -1 || firstDefinedBefore === -1) {
1504
- throw new Error("Unable to generate middle value between indexes ".concat(firstDefinedBefore, " and ").concat(firstDefinedAfter));
1505
- }
1506
- const beforeRank = ranks[firstDefinedBefore];
1507
- const afterRank = ranks[firstDefinedAfter];
1508
- if (!beforeRank || typeof beforeRank === "undefined" || !afterRank || typeof afterRank === "undefined") {
1509
- throw new Error("Unable to generate middle value between indexes ".concat(firstDefinedBefore, " and ").concat(firstDefinedAfter));
1510
- }
1511
- const between = beforeRank.between(afterRank);
1512
- const middle = Math.floor((firstDefinedAfter + firstDefinedBefore) / 2);
1513
- if (ranks[middle]) {
1514
- throw new Error("Should not have overwritten value at index ".concat(middle));
1515
- }
1516
- ranks[middle] = between;
1517
- return ranks;
1518
- }
1519
- function generateMultipleOrderRanks(count, start, end) {
1520
- let ranks = [...Array(count)];
1521
- const rankStart = start != null ? start : LexoRank.min().genNext().genNext();
1522
- const rankEnd = end != null ? end : LexoRank.max().genPrev().genPrev();
1523
- ranks[0] = rankStart;
1524
- ranks[count - 1] = rankEnd;
1525
- for (let i = 0; i < count; i++) {
1526
- ranks = generateMiddleValue(ranks);
1527
- }
1528
- return ranks.sort((a, b) => a.toString().localeCompare(b.toString()));
1529
- }
1530
- var __freeze = Object.freeze;
1531
- var __defProp = Object.defineProperty;
1532
- var __template = (cooked, raw) => __freeze(__defProp(cooked, "raw", {
1533
- value: __freeze(raw || cooked.slice())
1534
- }));
1535
- var _a;
1536
- const StyledFloatingCard = styled(Card)(() => css(_a || (_a = __template(["\n position: fixed;\n bottom: 0;\n left: 0;\n z-index: 1000;\n "]))));
1537
- function FloatingCard(_ref3) {
1538
- let {
1539
- children
1540
- } = _ref3;
1541
- const childrenHaveValues = Array.isArray(children) ? children.some(Boolean) : Boolean(children);
1542
- return /* @__PURE__ */jsx(AnimatePresence, {
1543
- children: childrenHaveValues ? /* @__PURE__ */jsx(motion.div, {
1544
- initial: {
1545
- opacity: 0
1546
- },
1547
- animate: {
1548
- opacity: 1
1549
- },
1550
- exit: {
1551
- opacity: 0
1552
- },
1553
- children: /* @__PURE__ */jsx(StyledFloatingCard, {
1554
- shadow: 3,
1555
- padding: 3,
1556
- margin: 3,
1557
- radius: 3,
1558
- children: /* @__PURE__ */jsx(Grid, {
1559
- gap: 2,
1560
- children
1561
- })
1562
- })
1563
- }, "floater") : null
1564
- });
1565
- }
1566
- function Verify(props) {
1567
- const {
1568
- data,
1569
- userList,
1570
- states
1571
- } = props;
1572
- const client = useClient({
1573
- apiVersion: API_VERSION
1574
- });
1575
- const toast = useToast();
1576
- const documentsWithoutValidMetadataIds = (data == null ? void 0 : data.length) ? data.reduce((acc, cur) => {
1577
- var _a;
1578
- const {
1579
- documentId,
1580
- state
1581
- } = (_a = cur._metadata) != null ? _a : {};
1582
- const stateExists = states.find(s => s.id === state);
1583
- return !stateExists && documentId ? [...acc, documentId] : acc;
1584
- }, []) : [];
1585
- const documentsWithInvalidUserIds = (data == null ? void 0 : data.length) && (userList == null ? void 0 : userList.length) ? data.reduce((acc, cur) => {
1586
- var _a;
1587
- const {
1588
- documentId,
1589
- assignees
1590
- } = (_a = cur._metadata) != null ? _a : {};
1591
- const allAssigneesExist = (assignees == null ? void 0 : assignees.length) ? assignees == null ? void 0 : assignees.every(a => userList.find(u => u.id === a)) : true;
1592
- return !allAssigneesExist && documentId ? [...acc, documentId] : acc;
1593
- }, []) : [];
1594
- const documentsWithoutOrderIds = (data == null ? void 0 : data.length) ? data.reduce((acc, cur) => {
1595
- var _a;
1596
- const {
1597
- documentId,
1598
- orderRank
1599
- } = (_a = cur._metadata) != null ? _a : {};
1600
- return !orderRank && documentId ? [...acc, documentId] : acc;
1601
- }, []) : [];
1602
- const documentsWithDuplicatedOrderIds = (data == null ? void 0 : data.length) ? data.reduce((acc, cur) => {
1603
- var _a;
1604
- const {
1605
- documentId,
1606
- orderRank
1607
- } = (_a = cur._metadata) != null ? _a : {};
1608
- return orderRank && data.filter(d => {
1609
- var _a2;
1610
- return ((_a2 = d._metadata) == null ? void 0 : _a2.orderRank) === orderRank;
1611
- }).length > 1 && documentId ? [...acc, documentId] : acc;
1612
- }, []) : [];
1613
- const correctDocuments = React.useCallback(async ids => {
1614
- toast.push({
1615
- title: "Correcting...",
1616
- status: "info"
1617
- });
1618
- const tx = ids.reduce((item, documentId) => {
1619
- return item.patch("workflow-metadata.".concat(documentId), {
1620
- set: {
1621
- state: states[0].id
1622
- }
1623
- });
1624
- }, client.transaction());
1625
- await tx.commit();
1626
- toast.push({
1627
- title: "Corrected ".concat(ids.length === 1 ? "1 Document" : "".concat(ids.length, " Documents")),
1628
- status: "success"
1629
- });
1630
- }, [client, states, toast]);
1631
- const removeUsersFromDocuments = React.useCallback(async ids => {
1632
- toast.push({
1633
- title: "Removing users...",
1634
- status: "info"
1635
- });
1636
- const tx = ids.reduce((item, documentId) => {
1637
- var _a, _b;
1638
- const {
1639
- assignees
1640
- } = (_b = (_a = data.find(d => d._id === documentId)) == null ? void 0 : _a._metadata) != null ? _b : {};
1641
- const validAssignees = (assignees == null ? void 0 : assignees.length) ?
1642
- // eslint-disable-next-line max-nested-callbacks
1643
- assignees.filter(a => {
1644
- var _a2;
1645
- return (_a2 = userList.find(u => u.id === a)) == null ? void 0 : _a2.id;
1646
- }) : [];
1647
- return item.patch("workflow-metadata.".concat(documentId), {
1648
- set: {
1649
- assignees: validAssignees
1650
- }
1651
- });
1652
- }, client.transaction());
1653
- await tx.commit();
1654
- toast.push({
1655
- title: "Corrected ".concat(ids.length === 1 ? "1 Document" : "".concat(ids.length, " Documents")),
1656
- status: "success"
1657
- });
1658
- }, [client, data, toast, userList]);
1659
- const addOrderToDocuments = React.useCallback(async ids => {
1660
- toast.push({
1661
- title: "Adding ordering...",
1662
- status: "info"
1663
- });
1664
- const [firstOrder, secondOrder] = [...data].slice(0, 2).map(d => {
1665
- var _a;
1666
- return (_a = d._metadata) == null ? void 0 : _a.orderRank;
1667
- });
1668
- const minLexo = firstOrder ? LexoRank.parse(firstOrder) : void 0;
1669
- const maxLexo = secondOrder ? LexoRank.parse(secondOrder) : void 0;
1670
- const ranks = generateMultipleOrderRanks(ids.length, minLexo, maxLexo);
1671
- const tx = client.transaction();
1672
- for (let index = 0; index < ids.length; index += 1) {
1673
- tx.patch("workflow-metadata.".concat(ids[index]), {
1674
- set: {
1675
- orderRank: ranks[index].toString()
1676
- }
1677
- });
1678
- }
1679
- await tx.commit();
1680
- toast.push({
1681
- title: "Added order to ".concat(ids.length === 1 ? "1 Document" : "".concat(ids.length, " Documents")),
1682
- status: "success"
1683
- });
1684
- }, [data, client, toast]);
1685
- const resetOrderOfAllDocuments = React.useCallback(async ids => {
1686
- toast.push({
1687
- title: "Adding ordering...",
1688
- status: "info"
1689
- });
1690
- const ranks = generateMultipleOrderRanks(ids.length);
1691
- const tx = client.transaction();
1692
- for (let index = 0; index < ids.length; index += 1) {
1693
- tx.patch("workflow-metadata.".concat(ids[index]), {
1694
- set: {
1695
- orderRank: ranks[index].toString()
1696
- }
1697
- });
1698
- }
1699
- await tx.commit();
1700
- toast.push({
1701
- title: "Added order to ".concat(ids.length === 1 ? "1 Document" : "".concat(ids.length, " Documents")),
1702
- status: "success"
1703
- });
1704
- }, [data, client, toast]);
1705
- const orphanedMetadataDocumentIds = React.useMemo(() => {
1706
- return data.length ? data.filter(doc => !(doc == null ? void 0 : doc._id)).map(doc => doc._metadata.documentId) : [];
1707
- }, [data]);
1708
- const handleOrphans = React.useCallback(() => {
1709
- toast.push({
1710
- title: "Removing orphaned metadata...",
1711
- status: "info"
1712
- });
1713
- const tx = client.transaction();
1714
- orphanedMetadataDocumentIds.forEach(id => {
1715
- tx.delete("workflow-metadata.".concat(id));
1716
- });
1717
- tx.commit();
1718
- toast.push({
1719
- title: "Removed ".concat(orphanedMetadataDocumentIds.length, " orphaned metadata documents"),
1720
- status: "success"
1721
- });
1722
- }, [client, orphanedMetadataDocumentIds, toast]);
1723
- return /* @__PURE__ */jsxs(FloatingCard, {
1724
- children: [documentsWithoutValidMetadataIds.length > 0 ? /* @__PURE__ */jsx(Button, {
1725
- tone: "caution",
1726
- mode: "ghost",
1727
- onClick: () => correctDocuments(documentsWithoutValidMetadataIds),
1728
- text: documentsWithoutValidMetadataIds.length === 1 ? "Correct 1 Document State" : "Correct ".concat(documentsWithoutValidMetadataIds.length, " Document States")
1729
- }) : null, documentsWithInvalidUserIds.length > 0 ? /* @__PURE__ */jsx(Button, {
1730
- tone: "caution",
1731
- mode: "ghost",
1732
- onClick: () => removeUsersFromDocuments(documentsWithInvalidUserIds),
1733
- text: documentsWithInvalidUserIds.length === 1 ? "Remove Invalid Users from 1 Document" : "Remove Invalid Users from ".concat(documentsWithInvalidUserIds.length, " Documents")
1734
- }) : null, documentsWithoutOrderIds.length > 0 ? /* @__PURE__ */jsx(Button, {
1735
- tone: "caution",
1736
- mode: "ghost",
1737
- onClick: () => addOrderToDocuments(documentsWithoutOrderIds),
1738
- text: documentsWithoutOrderIds.length === 1 ? "Set Order for 1 Document" : "Set Order for ".concat(documentsWithoutOrderIds.length, " Documents")
1739
- }) : null, documentsWithDuplicatedOrderIds.length > 0 ? /* @__PURE__ */jsxs(Fragment, {
1740
- children: [/* @__PURE__ */jsx(Button, {
1741
- tone: "caution",
1742
- mode: "ghost",
1743
- onClick: () => addOrderToDocuments(documentsWithDuplicatedOrderIds),
1744
- text: documentsWithDuplicatedOrderIds.length === 1 ? "Set Unique Order for 1 Document" : "Set Unique Order for ".concat(documentsWithDuplicatedOrderIds.length, " Documents")
1745
- }), /* @__PURE__ */jsx(Button, {
1746
- tone: "caution",
1747
- mode: "ghost",
1748
- onClick: () => resetOrderOfAllDocuments(data.map(doc => {
1749
- var _a;
1750
- return String((_a = doc._metadata) == null ? void 0 : _a.documentId);
1751
- })),
1752
- text: data.length === 1 ? "Reset Order for 1 Document" : "Reset Order for all ".concat(data.length, " Documents")
1753
- })]
1754
- }) : null, orphanedMetadataDocumentIds.length > 0 ? /* @__PURE__ */jsx(Button, {
1755
- text: "Cleanup orphaned metadata",
1756
- onClick: handleOrphans,
1757
- tone: "caution",
1758
- mode: "ghost"
1759
- }) : null]
1760
- });
1761
- }
1762
- function WorkflowTool(props) {
1763
- var _a, _b, _c;
1764
- const {
1765
- schemaTypes = [],
1766
- states = []
1767
- } = (_b = (_a = props == null ? void 0 : props.tool) == null ? void 0 : _a.options) != null ? _b : {};
1768
- const isDarkMode = useTheme().sanity.color.dark;
1769
- const defaultCardTone = isDarkMode ? "default" : "transparent";
1770
- const toast = useToast();
1771
- const userList = useProjectUsers({
1772
- apiVersion: API_VERSION
1773
- });
1774
- const user = useCurrentUser();
1775
- const userRoleNames = ((_c = user == null ? void 0 : user.roles) == null ? void 0 : _c.length) ? user == null ? void 0 : user.roles.map(r => r.name) : [];
1776
- const {
1777
- workflowData,
1778
- operations
1779
- } = useWorkflowDocuments(schemaTypes);
1780
- const [patchingIds, setPatchingIds] = React.useState([]);
1781
- const {
1782
- data,
1783
- loading,
1784
- error
1785
- } = workflowData;
1786
- const {
1787
- move
1788
- } = operations;
1789
- const [undroppableStates, setUndroppableStates] = React.useState([]);
1790
- const [draggingFrom, setDraggingFrom] = React.useState("");
1791
- const handleDragStart = React.useCallback(start => {
1792
- var _a2, _b2;
1793
- const {
1794
- draggableId,
1795
- source
1796
- } = start;
1797
- const {
1798
- droppableId: currentStateId
1799
- } = source;
1800
- setDraggingFrom(currentStateId);
1801
- const document = data.find(item => {
1802
- var _a3;
1803
- return ((_a3 = item._metadata) == null ? void 0 : _a3.documentId) === draggableId;
1804
- });
1805
- const state = states.find(s => s.id === currentStateId);
1806
- if (!document || !state) return;
1807
- const undroppableStateIds = [];
1808
- const statesThatRequireAssignmentIds = states.filter(s => s.requireAssignment).map(s => s.id);
1809
- if (statesThatRequireAssignmentIds.length) {
1810
- const documentAssignees = (_b2 = (_a2 = document._metadata) == null ? void 0 : _a2.assignees) != null ? _b2 : [];
1811
- const userIsAssignedToDocument = (user == null ? void 0 : user.id) ? documentAssignees.includes(user.id) : false;
1812
- if (!userIsAssignedToDocument) {
1813
- undroppableStateIds.push(...statesThatRequireAssignmentIds);
1814
- }
1815
- }
1816
- const statesThatCannotBeTransitionedToIds = state.transitions && state.transitions.length ? states.filter(s => {
1817
- var _a3;
1818
- return !((_a3 = state.transitions) == null ? void 0 : _a3.includes(s.id));
1819
- }).map(s => s.id) : [];
1820
- if (statesThatCannotBeTransitionedToIds.length) {
1821
- undroppableStateIds.push(...statesThatCannotBeTransitionedToIds);
1822
- }
1823
- const undroppableExceptSelf = undroppableStateIds.filter(id => id !== currentStateId);
1824
- if (undroppableExceptSelf.length) {
1825
- setUndroppableStates(undroppableExceptSelf);
1826
- }
1827
- }, [data, states, user]);
1828
- const handleDragEnd = React.useCallback(async result => {
1829
- var _a2, _b2, _c2, _d, _e, _f;
1830
- setUndroppableStates([]);
1831
- setDraggingFrom("");
1832
- const {
1833
- draggableId,
1834
- source,
1835
- destination
1836
- } = result;
1837
- if (
1838
- // No destination?
1839
- !destination ||
1840
- // No change in position?
1841
- destination.droppableId === source.droppableId && destination.index === source.index) {
1842
- return;
1843
- }
1844
- const destinationStateItems = [...filterItemsAndSort(data, destination.droppableId, [], null)];
1845
- const destinationStateIndex = states.findIndex(s => s.id === destination.droppableId);
1846
- const globalStateMinimumRank = data[0]._metadata.orderRank;
1847
- const globalStateMaximumRank = data[data.length - 1]._metadata.orderRank;
1848
- let newOrder;
1849
- if (!destinationStateItems.length) {
1850
- if (destinationStateIndex === 0) {
1851
- newOrder = LexoRank.min().toString();
1852
- } else {
1853
- newOrder = LexoRank.min().genNext().toString();
1854
- }
1855
- } else if (destination.index === 0) {
1856
- const firstItemOrderRank = (_b2 = (_a2 = [...destinationStateItems].shift()) == null ? void 0 : _a2._metadata) == null ? void 0 : _b2.orderRank;
1857
- if (firstItemOrderRank && typeof firstItemOrderRank === "string") {
1858
- newOrder = LexoRank.parse(firstItemOrderRank).genPrev().toString();
1859
- } else if (destinationStateIndex === 0) {
1860
- newOrder = LexoRank.min().toString();
1861
- } else {
1862
- newOrder = LexoRank.parse(globalStateMinimumRank).between(LexoRank.min()).toString();
1863
- }
1864
- } else if (destination.index + 1 === destinationStateItems.length) {
1865
- const lastItemOrderRank = (_d = (_c2 = [...destinationStateItems].pop()) == null ? void 0 : _c2._metadata) == null ? void 0 : _d.orderRank;
1866
- if (lastItemOrderRank && typeof lastItemOrderRank === "string") {
1867
- newOrder = LexoRank.parse(lastItemOrderRank).genNext().toString();
1868
- } else if (destinationStateIndex === states.length - 1) {
1869
- newOrder = LexoRank.max().toString();
1870
- } else {
1871
- newOrder = LexoRank.parse(globalStateMaximumRank).between(LexoRank.min()).toString();
1872
- }
1873
- } else {
1874
- const itemBefore = destinationStateItems[destination.index - 1];
1875
- const itemBeforeRank = (_e = itemBefore == null ? void 0 : itemBefore._metadata) == null ? void 0 : _e.orderRank;
1876
- let itemBeforeRankParsed;
1877
- if (itemBeforeRank) {
1878
- itemBeforeRankParsed = LexoRank.parse(itemBeforeRank);
1879
- } else if (destinationStateIndex === 0) {
1880
- itemBeforeRankParsed = LexoRank.min();
1881
- } else {
1882
- itemBeforeRankParsed = LexoRank.parse(globalStateMinimumRank);
1883
- }
1884
- const itemAfter = destinationStateItems[destination.index];
1885
- const itemAfterRank = (_f = itemAfter == null ? void 0 : itemAfter._metadata) == null ? void 0 : _f.orderRank;
1886
- let itemAfterRankParsed;
1887
- if (itemAfterRank) {
1888
- itemAfterRankParsed = LexoRank.parse(itemAfterRank);
1889
- } else if (destinationStateIndex === states.length - 1) {
1890
- itemAfterRankParsed = LexoRank.max();
1891
- } else {
1892
- itemAfterRankParsed = LexoRank.parse(globalStateMaximumRank);
1893
- }
1894
- newOrder = itemBeforeRankParsed.between(itemAfterRankParsed).toString();
1895
- }
1896
- setPatchingIds([...patchingIds, draggableId]);
1897
- toast.push({
1898
- status: "info",
1899
- title: "Updating document state..."
1900
- });
1901
- await move(draggableId, destination, states, newOrder);
1902
- setPatchingIds(ids => ids.filter(id => id !== draggableId));
1903
- }, [data, patchingIds, toast, move, states]);
1904
- const uniqueAssignedUsers = React.useMemo(() => {
1905
- const uniqueUserIds = data.reduce((acc, item) => {
1906
- var _a2;
1907
- const {
1908
- assignees = []
1909
- } = (_a2 = item._metadata) != null ? _a2 : {};
1910
- const newAssignees = (assignees == null ? void 0 : assignees.length) ? assignees.filter(a => !acc.includes(a)) : [];
1911
- return newAssignees.length ? [...acc, ...newAssignees] : acc;
1912
- }, []);
1913
- return userList.filter(u => uniqueUserIds.includes(u.id));
1914
- }, [data, userList]);
1915
- const [selectedUserIds, setSelectedUserIds] = React.useState(uniqueAssignedUsers.map(u => u.id));
1916
- const toggleSelectedUser = React.useCallback(userId => {
1917
- setSelectedUserIds(prev => prev.includes(userId) ? prev.filter(u => u !== userId) : [...prev, userId]);
1918
- }, []);
1919
- const resetSelectedUsers = React.useCallback(() => {
1920
- setSelectedUserIds([]);
1921
- }, []);
1922
- const [selectedSchemaTypes, setSelectedSchemaTypes] = React.useState(schemaTypes);
1923
- const toggleSelectedSchemaType = React.useCallback(schemaType => {
1924
- setSelectedSchemaTypes(prev => prev.includes(schemaType) ? prev.filter(u => u !== schemaType) : [...prev, schemaType]);
1925
- }, []);
1926
- const [invalidDocumentIds, setInvalidDocumentIds] = React.useState([]);
1927
- const toggleInvalidDocumentId = React.useCallback((docId, action) => {
1928
- setInvalidDocumentIds(prev => action === "ADD" ? [...prev, docId] : prev.filter(id => id !== docId));
1929
- }, []);
1930
- const Clone = React.useCallback((provided, snapshot, rubric) => {
1931
- const item = data.find(doc => {
1932
- var _a2;
1933
- return ((_a2 = doc == null ? void 0 : doc._metadata) == null ? void 0 : _a2.documentId) === rubric.draggableId;
1934
- });
1935
- return /* @__PURE__ */jsx("div", {
1936
- ...provided.draggableProps,
1937
- ...provided.dragHandleProps,
1938
- ref: provided.innerRef,
1939
- children: item ? /* @__PURE__ */jsx(DocumentCard, {
1940
- isDragDisabled: false,
1941
- isPatching: false,
1942
- userRoleCanDrop: true,
1943
- isDragging: snapshot.isDragging,
1944
- item,
1945
- states,
1946
- toggleInvalidDocumentId,
1947
- userList
1948
- }) : /* @__PURE__ */jsx(Feedback, {
1949
- title: "Item not found",
1950
- tone: "caution"
1951
- })
1952
- });
1953
- }, [data, states, toggleInvalidDocumentId, userList]);
1954
- if (!(states == null ? void 0 : states.length)) {
1955
- return /* @__PURE__ */jsx(Container, {
1956
- width: 1,
1957
- padding: 5,
1958
- children: /* @__PURE__ */jsx(Feedback, {
1959
- tone: "caution",
1960
- title: "Plugin options error",
1961
- description: "No States defined in plugin config"
1962
- })
1963
- });
1964
- }
1965
- if (error && !data.length) {
1966
- return /* @__PURE__ */jsx(Container, {
1967
- width: 1,
1968
- padding: 5,
1969
- children: /* @__PURE__ */jsx(Feedback, {
1970
- tone: "critical",
1971
- title: "Error querying for Workflow documents"
1972
- })
1973
- });
1974
- }
1975
- return /* @__PURE__ */jsxs(Flex, {
1976
- direction: "column",
1977
- height: "fill",
1978
- overflow: "hidden",
1979
- children: [/* @__PURE__ */jsx(Verify, {
1980
- data,
1981
- userList,
1982
- states
1983
- }), /* @__PURE__ */jsx(Filters, {
1984
- uniqueAssignedUsers,
1985
- selectedUserIds,
1986
- toggleSelectedUser,
1987
- resetSelectedUsers,
1988
- schemaTypes,
1989
- selectedSchemaTypes,
1990
- toggleSelectedSchemaType
1991
- }), /* @__PURE__ */jsx(DragDropContext, {
1992
- onDragStart: handleDragStart,
1993
- onDragEnd: handleDragEnd,
1994
- children: /* @__PURE__ */jsx(Grid, {
1995
- columns: states.length,
1996
- height: "fill",
1997
- children: states.map((state, stateIndex) => {
1998
- var _a2, _b2;
1999
- const userRoleCanDrop = ((_a2 = state == null ? void 0 : state.roles) == null ? void 0 : _a2.length) ? arraysContainMatchingString(state.roles, userRoleNames) : true;
2000
- const isDropDisabled = !userRoleCanDrop || undroppableStates.includes(state.id);
2001
- return /* @__PURE__ */jsx(Card, {
2002
- borderLeft: stateIndex > 0,
2003
- tone: defaultCardTone,
2004
- children: /* @__PURE__ */jsxs(Flex, {
2005
- direction: "column",
2006
- height: "fill",
2007
- children: [/* @__PURE__ */jsx(StateTitle, {
2008
- state,
2009
- requireAssignment: (_b2 = state.requireAssignment) != null ? _b2 : false,
2010
- userRoleCanDrop,
2011
- isDropDisabled,
2012
- draggingFrom,
2013
- documentCount: filterItemsAndSort(data, state.id, selectedUserIds, selectedSchemaTypes).length
2014
- }), /* @__PURE__ */jsx(Box, {
2015
- flex: 1,
2016
- children: /* @__PURE__ */jsx(Droppable, {
2017
- droppableId: state.id,
2018
- isDropDisabled,
2019
- mode: "virtual",
2020
- renderClone: Clone,
2021
- children: (provided, snapshot) => /* @__PURE__ */jsxs(Card, {
2022
- ref: provided.innerRef,
2023
- tone: snapshot.isDraggingOver ? "primary" : defaultCardTone,
2024
- height: "fill",
2025
- children: [loading ? /* @__PURE__ */jsx(Flex, {
2026
- padding: 5,
2027
- align: "center",
2028
- justify: "center",
2029
- children: /* @__PURE__ */jsx(Spinner, {
2030
- muted: true
2031
- })
2032
- }) : null, /* @__PURE__ */jsx(DocumentList, {
2033
- data,
2034
- invalidDocumentIds,
2035
- patchingIds,
2036
- selectedSchemaTypes,
2037
- selectedUserIds,
2038
- state,
2039
- states,
2040
- toggleInvalidDocumentId,
2041
- user,
2042
- userList,
2043
- userRoleCanDrop
2044
- })]
2045
- })
2046
- })
2047
- })]
2048
- })
2049
- }, state.id);
2050
- })
2051
- })
2052
- })]
2053
- });
2054
- }
2055
- const workflowTool = options => ({
2056
- name: "workflow",
2057
- title: "Workflow",
2058
- component: WorkflowTool,
2059
- icon: SplitVerticalIcon,
2060
- options
2061
- });
2062
- const workflow = definePlugin(function () {
2063
- let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_CONFIG;
2064
- const {
2065
- schemaTypes,
2066
- states
2067
- } = {
2068
- ...DEFAULT_CONFIG,
2069
- ...config
2070
- };
2071
- if (!(states == null ? void 0 : states.length)) {
2072
- throw new Error('Workflow plugin: Missing "states" in config');
2073
- }
2074
- if (!(schemaTypes == null ? void 0 : schemaTypes.length)) {
2075
- throw new Error('Workflow plugin: Missing "schemaTypes" in config');
2076
- }
2077
- return {
2078
- name: "sanity-plugin-workflow",
2079
- schema: {
2080
- types: [metadata(states)]
2081
- },
2082
- // TODO: Remove 'workflow.metadata' from list of new document types
2083
- // ...
2084
- studio: {
2085
- components: {
2086
- layout: props => WorkflowProvider({
2087
- ...props,
2088
- workflow: {
2089
- schemaTypes,
2090
- states
2091
- }
2092
- })
2093
- }
2094
- },
2095
- form: {
2096
- components: {
2097
- input: props => {
2098
- if (props.id === "root" && isObjectInputProps(props) && schemaTypes.includes(props.schemaType.name)) {
2099
- return WorkflowSignal(props);
2100
- }
2101
- return props.renderDefault(props);
2102
- }
2103
- }
2104
- },
2105
- document: {
2106
- actions: (prev, context) => {
2107
- if (!schemaTypes.includes(context.schemaType)) {
2108
- return prev;
2109
- }
2110
- return [props => BeginWorkflow(props), props => AssignWorkflow(props), ...states.map(state => props => UpdateWorkflow(props, state)), props => CompleteWorkflow(props), ...prev];
2111
- },
2112
- badges: (prev, context) => {
2113
- if (!schemaTypes.includes(context.schemaType)) {
2114
- return prev;
2115
- }
2116
- const {
2117
- documentId,
2118
- currentUser
2119
- } = context;
2120
- if (!documentId) {
2121
- return prev;
2122
- }
2123
- return [() => StateBadge(documentId), () => AssigneesBadge(documentId, currentUser), ...prev];
2124
- }
2125
- },
2126
- tools: [
2127
- // TODO: These configs could be read from Context
2128
- workflowTool({
2129
- schemaTypes,
2130
- states
2131
- })]
2132
- };
2133
- });
2134
- export { workflow };
2135
- //# sourceMappingURL=index.esm.js.map