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