@sanity/orderable-document-list 1.0.0-v3-studio.4 → 1.0.0-v3-studio.6

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.
package/lib/index.js CHANGED
@@ -1,825 +1,2 @@
1
- var $3KLdq$sanity = require("sanity");
2
- var $3KLdq$lexorank = require("lexorank");
3
- var $3KLdq$sanityicons = require("@sanity/icons");
4
- var $3KLdq$reactjsxruntime = require("react/jsx-runtime");
5
- var $3KLdq$react = require("react");
6
- var $3KLdq$sanityui = require("@sanity/ui");
7
- var $3KLdq$reactbeautifuldnd = require("react-beautiful-dnd");
8
- var $3KLdq$sanitydesk = require("sanity/desk");
9
-
10
- function $parcel$export(e, n, v, s) {
11
- Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
12
- }
13
- function $parcel$interopDefault(a) {
14
- return a && a.__esModule ? a.default : a;
15
- }
16
-
17
- $parcel$export(module.exports, "orderRankField", () => $cc532e4527e08c0f$export$64a609a9111ff100);
18
- $parcel$export(module.exports, "orderRankOrdering", () => $0a2b7163675b4332$export$db2ff2f898748a67);
19
- $parcel$export(module.exports, "orderableDocumentListDeskItem", () => $9f7e9a421b4d07af$export$3b014deba4b8ca00);
20
-
21
- const $7e21cb9e508f672b$export$64f27603cb09ba16 = `orderRank`;
22
-
23
-
24
-
25
- function $b1e493eff806e5a4$export$2e2bcd8739ae039(lastRankValue = ``) {
26
- const lastRank = lastRankValue ? (0, $3KLdq$lexorank.LexoRank).parse(lastRankValue) : (0, $3KLdq$lexorank.LexoRank).min();
27
- const nextRank = lastRank.genNext().genNext();
28
- return nextRank.value;
29
- }
30
-
31
-
32
- const $cc532e4527e08c0f$export$64a609a9111ff100 = (config)=>{
33
- if (!config?.type) throw new Error(`
34
- type must be provided.
35
- Example: orderRankField({type: 'category'})
36
- `);
37
- const { type: type } = config;
38
- return (0, $3KLdq$sanity.defineField)({
39
- title: "Order Rank",
40
- readOnly: true,
41
- hidden: true,
42
- ...config,
43
- name: (0, $7e21cb9e508f672b$export$64f27603cb09ba16),
44
- type: "string",
45
- initialValue: async (p, { getClient: getClient })=>{
46
- const lastDocOrderRank = await getClient({
47
- apiVersion: "2021-09-01"
48
- }).fetch(`*[_type == $type]|order(@[$order] desc)[0][$order]`, {
49
- type: type,
50
- order: (0, $7e21cb9e508f672b$export$64f27603cb09ba16)
51
- });
52
- return (0, $b1e493eff806e5a4$export$2e2bcd8739ae039)(lastDocOrderRank);
53
- }
54
- });
55
- };
56
-
57
-
58
-
59
- const $0a2b7163675b4332$export$db2ff2f898748a67 = {
60
- title: "Ordered",
61
- name: "ordered",
62
- by: [
63
- {
64
- field: (0, $7e21cb9e508f672b$export$64f27603cb09ba16),
65
- direction: "asc"
66
- }
67
- ]
68
- };
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
- const $ad5dfe08a2c834b7$export$2a2017d0ec5437fa = (0, ($parcel$interopDefault($3KLdq$react))).createContext({});
93
-
94
-
95
- function $8d444d838b27ec52$export$2e2bcd8739ae039({ doc: doc , increment: increment , entities: entities , handleSelect: handleSelect , index: index , isFirst: isFirst , isLast: isLast }) {
96
- const { showIncrements: showIncrements } = (0, $3KLdq$react.useContext)((0, $ad5dfe08a2c834b7$export$2a2017d0ec5437fa));
97
- const schema = (0, $3KLdq$sanity.useSchema)();
98
- return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $3KLdq$sanityui.Flex), {
99
- align: "center",
100
- children: [
101
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Box), {
102
- paddingX: 3,
103
- style: {
104
- flexShrink: 0
105
- },
106
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Text), {
107
- size: 4,
108
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityicons.DragHandleIcon), {})
109
- })
110
- }),
111
- showIncrements && /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $3KLdq$sanityui.Flex), {
112
- style: {
113
- flexShrink: 0
114
- },
115
- align: "center",
116
- gap: 1,
117
- paddingRight: 1,
118
- children: [
119
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Button), {
120
- padding: 2,
121
- mode: "ghost",
122
- onClick: ()=>increment(index, index + -1, doc._id, entities),
123
- disabled: isFirst,
124
- icon: (0, $3KLdq$sanityicons.ChevronUpIcon)
125
- }),
126
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Button), {
127
- padding: 2,
128
- mode: "ghost",
129
- disabled: isLast,
130
- onClick: ()=>increment(index, index + 1, doc._id, entities),
131
- icon: (0, $3KLdq$sanityicons.ChevronDownIcon)
132
- })
133
- ]
134
- }),
135
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Button), {
136
- style: {
137
- width: `100%`
138
- },
139
- padding: 2,
140
- mode: "bleed",
141
- onClick: (e)=>handleSelect(doc._id, index, e.nativeEvent),
142
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Flex), {
143
- flex: 1,
144
- align: "center",
145
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Box), {
146
- flex: 1,
147
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanity.SanityPreview), {
148
- layout: "default",
149
- value: doc,
150
- schemaType: schema.get(doc._type)
151
- })
152
- })
153
- })
154
- })
155
- ]
156
- });
157
- }
158
-
159
-
160
-
161
-
162
- function $460233bd0d4c2ff3$var$lexicographicalSort(a, b) {
163
- if (a[0, $7e21cb9e508f672b$export$64f27603cb09ba16] < b[0, $7e21cb9e508f672b$export$64f27603cb09ba16]) return -1;
164
- if (a[0, $7e21cb9e508f672b$export$64f27603cb09ba16] > b[0, $7e21cb9e508f672b$export$64f27603cb09ba16]) return 1;
165
- return 0;
166
- }
167
- const $460233bd0d4c2ff3$export$1b86f2c90605ffb9 = ({ entities: entities , selectedIds: selectedIds , source: source , destination: destination , debug: debug = false })=>{
168
- const startIndex = source.index;
169
- const endIndex = destination.index;
170
- const isMovingUp = startIndex > endIndex;
171
- const selectedItems = entities.filter((item)=>selectedIds.includes(item._id));
172
- const message = [
173
- `Moved`,
174
- selectedItems.length === 1 ? `1 Document` : `${selectedItems.length} Documents`,
175
- isMovingUp ? `up` : `down`,
176
- `from position`,
177
- `${startIndex + 1} to ${endIndex + 1}`,
178
- ].join(" ");
179
- const { all: all , selected: selected } = entities.reduce((acc, cur, curIndex)=>{
180
- // Selected items get spread in below, so skip them here
181
- if (selectedIds.includes(cur._id)) return {
182
- all: acc.all,
183
- selected: acc.selected
184
- };
185
- // Drop seleced items in
186
- if (curIndex === endIndex) {
187
- const prevIndex = curIndex - 1;
188
- const prevRank = entities[prevIndex]?.[0, $7e21cb9e508f672b$export$64f27603cb09ba16] ? (0, $3KLdq$lexorank.LexoRank).parse(entities[prevIndex]?.[0, $7e21cb9e508f672b$export$64f27603cb09ba16]) : (0, $3KLdq$lexorank.LexoRank).min();
189
- const curRank = (0, $3KLdq$lexorank.LexoRank).parse(entities[curIndex][0, $7e21cb9e508f672b$export$64f27603cb09ba16]);
190
- const nextIndex = curIndex + 1;
191
- const nextRank = entities[nextIndex]?.[0, $7e21cb9e508f672b$export$64f27603cb09ba16] ? (0, $3KLdq$lexorank.LexoRank).parse(entities[nextIndex]?.[0, $7e21cb9e508f672b$export$64f27603cb09ba16]) : (0, $3KLdq$lexorank.LexoRank).max();
192
- let betweenRank = isMovingUp ? prevRank.between(curRank) : curRank.between(nextRank);
193
- // For each selected item, assign a new orderRank between now and next
194
- for(let selectedIndex = 0; selectedIndex < selectedItems.length; selectedIndex += 1){
195
- selectedItems[selectedIndex][0, $7e21cb9e508f672b$export$64f27603cb09ba16] = betweenRank.value;
196
- betweenRank = isMovingUp ? betweenRank.between(curRank) : betweenRank.between(nextRank);
197
- }
198
- return {
199
- // The `all` array gets sorted by order field later anyway
200
- // so that this probably isn't necessary ¯\_(ツ)_/¯
201
- all: isMovingUp ? [
202
- ...acc.all,
203
- ...selectedItems,
204
- cur
205
- ] : [
206
- ...acc.all,
207
- cur,
208
- ...selectedItems
209
- ],
210
- selected: selectedItems
211
- };
212
- }
213
- return {
214
- all: [
215
- ...acc.all,
216
- cur
217
- ],
218
- selected: acc.selected
219
- };
220
- }, {
221
- all: [],
222
- selected: []
223
- });
224
- const patches = selected.map((doc)=>{
225
- return [
226
- doc._id,
227
- {
228
- set: {
229
- [(0, $7e21cb9e508f672b$export$64f27603cb09ba16)]: doc[0, $7e21cb9e508f672b$export$64f27603cb09ba16]
230
- }
231
- },
232
- ];
233
- });
234
- // Safety-check to make sure everything is in order
235
- const allSorted = all.sort($460233bd0d4c2ff3$var$lexicographicalSort);
236
- return {
237
- newOrder: allSorted,
238
- patches: patches,
239
- message: message
240
- };
241
- };
242
-
243
-
244
-
245
-
246
- function $66c7844c36e4ff21$export$8d49af9be9632eba() {
247
- return (0, $3KLdq$sanity.useClient)({
248
- apiVersion: "2021-09-01"
249
- });
250
- }
251
-
252
-
253
- const $9cae087253e865f7$var$getItemStyle = (draggableStyle, itemIsUpdating)=>({
254
- userSelect: "none",
255
- transition: `opacity 500ms ease-in-out`,
256
- opacity: itemIsUpdating ? 0.2 : 1,
257
- pointerEvents: itemIsUpdating ? `none` : undefined,
258
- ...draggableStyle
259
- });
260
- const $9cae087253e865f7$var$cardTone = (settings)=>{
261
- const { isDuplicate: isDuplicate , isGhosting: isGhosting , isDragging: isDragging , isSelected: isSelected } = settings;
262
- if (isGhosting) return `transparent`;
263
- if (isDragging || isSelected) return `primary`;
264
- if (isDuplicate) return `caution`;
265
- return undefined;
266
- };
267
- function $9cae087253e865f7$export$2e2bcd8739ae039({ data: data , type: type , listIsUpdating: listIsUpdating , setListIsUpdating: setListIsUpdating }) {
268
- const toast = (0, $3KLdq$sanityui.useToast)();
269
- const router = (0, $3KLdq$sanitydesk.usePaneRouter)();
270
- const { navigateIntent: navigateIntent } = router;
271
- // Maintains local state order before transaction completes
272
- const [orderedData, setOrderedData] = (0, $3KLdq$react.useState)(data);
273
- // Update local state when documents change from an outside source
274
- (0, $3KLdq$react.useEffect)(()=>{
275
- if (!listIsUpdating) setOrderedData(data);
276
- /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [
277
- data
278
- ]);
279
- const [draggingId, setDraggingId] = (0, $3KLdq$react.useState)(``);
280
- const [selectedIds, setSelectedIds] = (0, $3KLdq$react.useState)([]);
281
- const clearSelected = (0, $3KLdq$react.useCallback)(()=>setSelectedIds([]), [
282
- setSelectedIds
283
- ]);
284
- const handleSelect = (0, $3KLdq$react.useCallback)((clickedId, index, nativeEvent)=>{
285
- const isSelected = selectedIds.includes(clickedId);
286
- const selectMultiple = nativeEvent.shiftKey;
287
- const isUsingWindows = navigator.appVersion.indexOf("Win") !== -1;
288
- const selectAdditional = isUsingWindows ? nativeEvent.ctrlKey : nativeEvent.metaKey;
289
- let updatedIds = [];
290
- // No modifier keys pressed during click:
291
- // - update selected to just this one
292
- // - open document
293
- if (!selectMultiple && !selectAdditional) {
294
- navigateIntent("edit", {
295
- id: clickedId,
296
- type: type
297
- });
298
- return setSelectedIds([
299
- clickedId
300
- ]);
301
- }
302
- // Shift key was held, add id's between last selected and this one
303
- // ...before adding this one
304
- if (selectMultiple && !isSelected) {
305
- const lastSelectedId = selectedIds[selectedIds.length - 1];
306
- const lastSelectedIndex = orderedData.findIndex((item)=>item._id === lastSelectedId);
307
- const firstSelected = index < lastSelectedIndex ? index : lastSelectedIndex;
308
- const lastSelected = index > lastSelectedIndex ? index : lastSelectedIndex;
309
- const betweenIds = orderedData.filter((item, itemIndex)=>itemIndex > firstSelected && itemIndex < lastSelected).map((item)=>item._id);
310
- updatedIds = [
311
- ...selectedIds,
312
- ...betweenIds,
313
- clickedId
314
- ];
315
- } else if (isSelected) // Toggle off a single id
316
- updatedIds = selectedIds.filter((id)=>id !== clickedId);
317
- else // Toggle on a single id
318
- updatedIds = [
319
- ...selectedIds,
320
- clickedId
321
- ];
322
- return setSelectedIds(updatedIds);
323
- }, [
324
- setSelectedIds,
325
- navigateIntent,
326
- orderedData,
327
- selectedIds,
328
- type
329
- ]);
330
- const client = (0, $66c7844c36e4ff21$export$8d49af9be9632eba)();
331
- const transactPatches = (0, $3KLdq$react.useCallback)(async (patches, message)=>{
332
- const transaction = client.transaction();
333
- patches.forEach(([docId, ops])=>transaction.patch(docId, ops));
334
- await transaction.commit().then((updated)=>{
335
- clearSelected();
336
- setDraggingId(``);
337
- setListIsUpdating(false);
338
- toast.push({
339
- title: `${updated.results.length === 1 ? `1 Document` : `${updated.results.length} Documents`} Reordered`,
340
- status: `success`,
341
- description: message
342
- });
343
- }).catch(()=>{
344
- setDraggingId(``);
345
- setListIsUpdating(false);
346
- toast.push({
347
- title: `Reordering failed`,
348
- status: `error`
349
- });
350
- });
351
- }, [
352
- client,
353
- setDraggingId,
354
- clearSelected,
355
- setListIsUpdating,
356
- toast
357
- ]);
358
- const handleDragEnd = (0, $3KLdq$react.useCallback)((result, entities)=>{
359
- setDraggingId(``);
360
- const { source: source , destination: destination , draggableId: draggableId } = result ?? {};
361
- // Don't do anything if nothing changed
362
- if (source?.index === destination?.index) return;
363
- // Don't do anything if we don't have the entitites
364
- if (!entities?.length || !draggableId) return;
365
- // A document can be dragged without being one-of-many-selected
366
- const effectedIds = selectedIds?.length ? selectedIds : [
367
- draggableId
368
- ];
369
- // Don't do anything if we don't have ids to effect
370
- if (!effectedIds?.length) return;
371
- // Update state to update styles + prevent data refetching
372
- setListIsUpdating(true);
373
- setSelectedIds(effectedIds);
374
- const { newOrder: newOrder , patches: patches , message: message } = (0, $460233bd0d4c2ff3$export$1b86f2c90605ffb9)({
375
- entities: entities,
376
- selectedIds: effectedIds,
377
- source: source,
378
- destination: destination
379
- });
380
- // Update local state
381
- if (newOrder?.length) setOrderedData(newOrder);
382
- // Transact new order patches
383
- if (patches?.length) transactPatches(patches, message);
384
- }, [
385
- selectedIds,
386
- setDraggingId,
387
- setSelectedIds,
388
- transactPatches,
389
- setListIsUpdating
390
- ]);
391
- const handleDragStart = (0, $3KLdq$react.useCallback)((start)=>{
392
- const id = start.draggableId;
393
- const selected = selectedIds.includes(id);
394
- // if dragging an item that is not selected - unselect all items
395
- if (!selected) clearSelected();
396
- setDraggingId(id);
397
- }, [
398
- selectedIds,
399
- clearSelected,
400
- setDraggingId
401
- ]);
402
- // Move one document up or down one place, by fake invoking the drag function
403
- const incrementIndex = (0, $3KLdq$react.useCallback)((shiftFrom, shiftTo, id, entities)=>{
404
- const result = {
405
- draggableId: id,
406
- source: {
407
- index: shiftFrom
408
- },
409
- destination: {
410
- index: shiftTo
411
- }
412
- };
413
- return handleDragEnd(result, entities);
414
- }, [
415
- handleDragEnd
416
- ]);
417
- const onWindowKeyDown = (0, $3KLdq$react.useCallback)((event)=>{
418
- if (event.key === "Escape") clearSelected();
419
- }, [
420
- clearSelected
421
- ]);
422
- (0, $3KLdq$react.useEffect)(()=>{
423
- window.addEventListener("keydown", onWindowKeyDown);
424
- return ()=>{
425
- window.removeEventListener("keydown", onWindowKeyDown);
426
- };
427
- }, [
428
- onWindowKeyDown
429
- ]);
430
- // Find all items with duplicate order field
431
- const duplicateOrders = (0, $3KLdq$react.useMemo)(()=>{
432
- if (!orderedData.length) return [];
433
- const orderField = orderedData.map((item)=>item[0, $7e21cb9e508f672b$export$64f27603cb09ba16]);
434
- return orderField.filter((item, index)=>orderField.indexOf(item) !== index);
435
- }, [
436
- orderedData
437
- ]);
438
- const onDragEnd = (0, $3KLdq$react.useCallback)((result)=>handleDragEnd(result, orderedData), [
439
- orderedData,
440
- handleDragEnd
441
- ]);
442
- return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$reactbeautifuldnd.DragDropContext), {
443
- onDragStart: handleDragStart,
444
- onDragEnd: onDragEnd,
445
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$reactbeautifuldnd.Droppable), {
446
- droppableId: "documentSortZone",
447
- children: (provided)=>/*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)("div", {
448
- ...provided.droppableProps,
449
- ref: provided.innerRef,
450
- children: [
451
- orderedData.map((item, index)=>/*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$reactbeautifuldnd.Draggable), {
452
- draggableId: item._id,
453
- index: index,
454
- children: (innerProvided, innerSnapshot)=>{
455
- const isSelected = selectedIds.includes(item._id);
456
- const isDragging = innerSnapshot.isDragging;
457
- const isGhosting = Boolean(!isDragging && draggingId && isSelected);
458
- const isUpdating = listIsUpdating && isSelected;
459
- const isDisabled = Boolean(!item[0, $7e21cb9e508f672b$export$64f27603cb09ba16]);
460
- const isDuplicate = duplicateOrders.includes(item[0, $7e21cb9e508f672b$export$64f27603cb09ba16]);
461
- const tone = $9cae087253e865f7$var$cardTone({
462
- isDuplicate: isDuplicate,
463
- isGhosting: isGhosting,
464
- isDragging: isDragging,
465
- isSelected: isSelected
466
- });
467
- return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("div", {
468
- ref: innerProvided.innerRef,
469
- ...innerProvided.draggableProps,
470
- ...innerProvided.dragHandleProps,
471
- style: isDisabled ? {
472
- opacity: 0.2,
473
- pointerEvents: `none`
474
- } : $9cae087253e865f7$var$getItemStyle(innerProvided.draggableProps.style, isUpdating),
475
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Box), {
476
- paddingBottom: 1,
477
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Card), {
478
- tone: tone,
479
- shadow: isDragging ? 2 : undefined,
480
- radius: 2,
481
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $8d444d838b27ec52$export$2e2bcd8739ae039), {
482
- doc: item,
483
- entities: orderedData,
484
- handleSelect: handleSelect,
485
- increment: incrementIndex,
486
- index: index,
487
- isFirst: index === 0,
488
- isLast: index === orderedData.length - 1
489
- })
490
- })
491
- })
492
- });
493
- }
494
- }, `${item._id}-${item[0, $7e21cb9e508f672b$export$64f27603cb09ba16]}`)),
495
- provided.placeholder
496
- ]
497
- })
498
- })
499
- });
500
- }
501
-
502
-
503
-
504
-
505
-
506
-
507
- function $8f6d54ef8e8d6bcf$export$2e2bcd8739ae039({ children: children }) {
508
- return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Box), {
509
- padding: 3,
510
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Card), {
511
- padding: 4,
512
- radius: 2,
513
- shadow: 1,
514
- tone: "caution",
515
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Text), {
516
- children: children
517
- })
518
- })
519
- });
520
- }
521
-
522
-
523
-
524
- const $d59638856f04a407$var$DEFAULT_PARAMS = {};
525
- function $d59638856f04a407$export$2e2bcd8739ae039({ type: type , filter: filter , params: params = $d59638856f04a407$var$DEFAULT_PARAMS }) {
526
- const [isLoading, setIsLoading] = (0, $3KLdq$react.useState)(true);
527
- const [listIsUpdating, setListIsUpdating] = (0, $3KLdq$react.useState)(false);
528
- const [data, setData] = (0, $3KLdq$react.useState)([]);
529
- const client = (0, $66c7844c36e4ff21$export$8d49af9be9632eba)();
530
- (0, $3KLdq$react.useEffect)(()=>{
531
- const query = `*[_type == $type ${filter ? `&& ${filter}` : ""}]|order(@[$order] asc){
532
- _id, _type, ${(0, $7e21cb9e508f672b$export$64f27603cb09ba16)}
533
- }`;
534
- const queryParams = Object.assign(params, {
535
- type: type,
536
- order: (0, $7e21cb9e508f672b$export$64f27603cb09ba16)
537
- });
538
- let subscription;
539
- // eslint-disable-next-line require-await
540
- const fetchData = async ()=>{
541
- client.fetch(query, queryParams).then((documents)=>{
542
- // Remove published document from list if draft also exists
543
- const filteredDocuments = documents.reduce((acc, cur)=>{
544
- if (!cur._id.startsWith(`drafts.`)) {
545
- // eslint-disable-next-line max-nested-callbacks
546
- const alsoHasDraft = documents.some((doc)=>doc._id === `drafts.${cur._id}`);
547
- return alsoHasDraft ? acc : [
548
- ...acc,
549
- cur
550
- ];
551
- }
552
- return [
553
- ...acc,
554
- cur
555
- ];
556
- }, []);
557
- setData(filteredDocuments);
558
- if (isLoading) setIsLoading(false);
559
- });
560
- };
561
- const prepareData = async ()=>{
562
- setIsLoading(true);
563
- await fetchData();
564
- if (!subscription) subscription = client.listen(query, queryParams).subscribe(()=>fetchData());
565
- };
566
- // Get data but only if a document isn't being patched or we don't yet have data
567
- if (!listIsUpdating && !data.length) prepareData();
568
- return ()=>subscription?.unsubscribe();
569
- /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [
570
- type
571
- ]);
572
- const unorderedDataCount = (0, $3KLdq$react.useMemo)(()=>data.length ? data.filter((doc)=>!doc[0, $7e21cb9e508f672b$export$64f27603cb09ba16]).length : 0, [
573
- data
574
- ]);
575
- if (isLoading) return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Flex), {
576
- style: {
577
- width: `100%`,
578
- height: `100%`
579
- },
580
- align: "center",
581
- justify: "center",
582
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Spinner), {})
583
- });
584
- return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $3KLdq$sanityui.Stack), {
585
- space: 1,
586
- style: {
587
- overflow: `scroll`,
588
- height: `100%`
589
- },
590
- children: [
591
- unorderedDataCount > 0 && /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $8f6d54ef8e8d6bcf$export$2e2bcd8739ae039), {
592
- children: [
593
- unorderedDataCount,
594
- "/",
595
- data.length,
596
- " Documents have no Order. Select",
597
- " ",
598
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("strong", {
599
- children: "Reset Order"
600
- }),
601
- " from the Menu above to fix."
602
- ]
603
- }),
604
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $3KLdq$sanityui.Box), {
605
- padding: 1,
606
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $9cae087253e865f7$export$2e2bcd8739ae039), {
607
- data: data,
608
- type: type,
609
- listIsUpdating: listIsUpdating,
610
- setListIsUpdating: setListIsUpdating
611
- })
612
- })
613
- ]
614
- });
615
- }
616
-
617
-
618
-
619
-
620
-
621
- function $a8b1e0d5707b32a2$export$2e2bcd8739ae039({ type: type , showIncrements: showIncrements , resetOrderTransaction: resetOrderTransaction , filter: filter , params: params }) {
622
- const toast = (0, $3KLdq$sanityui.useToast)();
623
- const schema = (0, $3KLdq$sanity.useSchema)();
624
- (0, $3KLdq$react.useEffect)(()=>{
625
- if (resetOrderTransaction?.title && resetOrderTransaction?.status) toast.push(resetOrderTransaction);
626
- }, [
627
- resetOrderTransaction,
628
- toast
629
- ]);
630
- const schemaIsInvalid = (0, $3KLdq$react.useMemo)(()=>{
631
- // Option not passed
632
- if (!type) return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $3KLdq$reactjsxruntime.Fragment), {
633
- children: [
634
- "No ",
635
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
636
- children: "type"
637
- }),
638
- " was configured"
639
- ]
640
- });
641
- const typeSchema = schema.get(type);
642
- // Schema not found
643
- if (!typeSchema) return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $3KLdq$reactjsxruntime.Fragment), {
644
- children: [
645
- "Schema ",
646
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
647
- children: type
648
- }),
649
- " not found"
650
- ]
651
- });
652
- // Schema lacks an order field
653
- if (!("fields" in typeSchema) || !typeSchema.fields.some((field)=>field?.name === (0, $7e21cb9e508f672b$export$64f27603cb09ba16))) return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $3KLdq$reactjsxruntime.Fragment), {
654
- children: [
655
- "Schema ",
656
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
657
- children: type
658
- }),
659
- " must have an ",
660
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
661
- children: (0, $7e21cb9e508f672b$export$64f27603cb09ba16)
662
- }),
663
- " field of type",
664
- " ",
665
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
666
- children: "string"
667
- })
668
- ]
669
- });
670
- // Schema's order field is not a string
671
- if ("fields" in typeSchema && typeSchema.fields.some((field)=>field?.name === (0, $7e21cb9e508f672b$export$64f27603cb09ba16) && field?.type?.name !== "string")) return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsxs)((0, $3KLdq$reactjsxruntime.Fragment), {
672
- children: [
673
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
674
- children: (0, $7e21cb9e508f672b$export$64f27603cb09ba16)
675
- }),
676
- " field on Schema ",
677
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
678
- children: type
679
- }),
680
- " must be",
681
- " ",
682
- /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)("code", {
683
- children: "string"
684
- }),
685
- " type"
686
- ]
687
- });
688
- return "";
689
- }, [
690
- type,
691
- schema
692
- ]);
693
- if (schemaIsInvalid) return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $8f6d54ef8e8d6bcf$export$2e2bcd8739ae039), {
694
- children: schemaIsInvalid
695
- });
696
- return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $ad5dfe08a2c834b7$export$2a2017d0ec5437fa).Provider, {
697
- value: {
698
- showIncrements: showIncrements
699
- },
700
- children: /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $d59638856f04a407$export$2e2bcd8739ae039), {
701
- type: type,
702
- filter: filter,
703
- params: params
704
- })
705
- });
706
- }
707
-
708
-
709
-
710
-
711
- async function $0448f7faaab547e3$export$ee841d674ca80db0(type = ``, client) {
712
- const query = `*[_type == $type]|order(@[$order] asc)._id`;
713
- const queryParams = {
714
- type: type,
715
- order: (0, $7e21cb9e508f672b$export$64f27603cb09ba16)
716
- };
717
- const documents = await client.fetch(query, queryParams);
718
- if (!documents.length) return null;
719
- const transaction = client.transaction();
720
- let aLexoRank = (0, $3KLdq$lexorank.LexoRank).min();
721
- for(let index = 0; index < documents.length; index += 1){
722
- // Generate next rank before even the first document so there's room to move!
723
- aLexoRank = aLexoRank.genNext().genNext();
724
- transaction.patch(documents[index], {
725
- set: {
726
- [(0, $7e21cb9e508f672b$export$64f27603cb09ba16)]: aLexoRank.value
727
- }
728
- });
729
- }
730
- return transaction.commit().then((update)=>update).catch((err)=>err);
731
- }
732
-
733
-
734
- class $7faf82429f78b250$export$2e2bcd8739ae039 extends (0, $3KLdq$react.Component) {
735
- constructor(props){
736
- super(props);
737
- this.state = {
738
- showIncrements: false,
739
- resetOrderTransaction: {}
740
- };
741
- }
742
- actionHandlers = {
743
- showIncrements: ()=>{
744
- this.setState((state)=>({
745
- showIncrements: !state.showIncrements
746
- }));
747
- },
748
- resetOrder: async ()=>{
749
- this.setState(()=>({
750
- resetOrderTransaction: {
751
- status: `info`,
752
- title: `Reordering started...`,
753
- closable: true
754
- }
755
- }));
756
- const update = await (0, $0448f7faaab547e3$export$ee841d674ca80db0)(this.props.options.type, this.props.options.client);
757
- const reorderWasSuccessful = update?.results?.length;
758
- this.setState(()=>({
759
- resetOrderTransaction: {
760
- status: reorderWasSuccessful ? `success` : `info`,
761
- title: reorderWasSuccessful ? `Reordered ${update.results.length === 1 ? `Document` : `Documents`}` : `Reordering failed`,
762
- closable: true
763
- }
764
- }));
765
- }
766
- };
767
- render() {
768
- const type = this?.props?.options?.type;
769
- if (!type) return null;
770
- return /*#__PURE__*/ (0, $3KLdq$reactjsxruntime.jsx)((0, $a8b1e0d5707b32a2$export$2e2bcd8739ae039), {
771
- filter: this?.props?.options?.filter,
772
- params: this?.props?.options?.params,
773
- type: type,
774
- showIncrements: this.state.showIncrements,
775
- resetOrderTransaction: this.state.resetOrderTransaction
776
- });
777
- }
778
- }
779
-
780
-
781
- function $9f7e9a421b4d07af$export$3b014deba4b8ca00(config) {
782
- if (!config?.type || !config.context || !config.S) throw new Error(`
783
- type, context and S (StructureBuilder) must be provided.
784
- context and S are available when configuring structure.
785
- Example: orderableDocumentListDeskItem({type: 'category'})
786
- `);
787
- const { type: type , filter: filter , params: params , title: title , icon: icon , id: id , context: context , S: S } = config;
788
- const { schema: schema , getClient: getClient } = context;
789
- const client = getClient({
790
- apiVersion: "2021-09-01"
791
- });
792
- const listTitle = title ?? `Orderable ${type}`;
793
- const listId = id ?? `orderable-${type}`;
794
- const listIcon = icon ?? (0, $3KLdq$sanityicons.SortIcon);
795
- const typeTitle = schema.get(type)?.title ?? type;
796
- return S.listItem().title(listTitle).id(listId).icon(listIcon).child(Object.assign(S.documentTypeList(type).serialize(), {
797
- // Prevents the component from re-rendering when switching documents
798
- __preserveInstance: true,
799
- // Prevents the component from NOT re-rendering when switching listItems
800
- key: listId,
801
- type: "component",
802
- component: (0, $7faf82429f78b250$export$2e2bcd8739ae039),
803
- options: {
804
- type: type,
805
- filter: filter,
806
- params: params,
807
- client: client
808
- },
809
- menuItems: [
810
- S.menuItem().title(`Create new ${typeTitle}`).intent({
811
- type: "create",
812
- params: {
813
- type: type
814
- }
815
- }).serialize(),
816
- S.menuItem().title(`Reset Order`).icon((0, $3KLdq$sanityicons.GenerateIcon)).action(`resetOrder`).serialize(),
817
- S.menuItem().title(`Show Increments`).icon((0, $3KLdq$sanityicons.SortIcon)).action(`showIncrements`).serialize(),
818
- ]
819
- })).serialize();
820
- }
821
-
822
-
823
-
824
-
1
+ "use strict";function e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function t(t){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?e(Object(i),!0).forEach((function(e){n(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(exports,"__esModule",{value:!0});var r=require("sanity"),i=require("lexorank"),s=require("@sanity/icons"),o=require("react/jsx-runtime"),a=require("react"),l=require("@sanity/ui"),d=require("react-beautiful-dnd"),c=require("sanity/desk");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}const p={title:"Ordered",name:"ordered",by:[{field:"orderRank",direction:"asc"}]},h=u(a).default.createContext({});function g(e){let{doc:t,increment:n,entities:i,handleSelect:d,index:c,isFirst:u,isLast:p}=e;const{showIncrements:g}=a.useContext(h),f=r.useSchema();return o.jsxs(l.Flex,{align:"center",children:[o.jsx(l.Box,{paddingX:3,style:{flexShrink:0},children:o.jsx(l.Text,{size:4,children:o.jsx(s.DragHandleIcon,{})})}),g&&o.jsxs(l.Flex,{style:{flexShrink:0},align:"center",gap:1,paddingRight:1,children:[o.jsx(l.Button,{padding:2,mode:"ghost",onClick:()=>n(c,c+-1,t._id,i),disabled:u,icon:s.ChevronUpIcon}),o.jsx(l.Button,{padding:2,mode:"ghost",disabled:p,onClick:()=>n(c,c+1,t._id,i),icon:s.ChevronDownIcon})]}),o.jsx(l.Button,{style:{width:"100%"},padding:2,mode:"bleed",onClick:e=>d(t._id,c,e.nativeEvent),children:o.jsx(l.Flex,{flex:1,align:"center",children:o.jsx(l.Box,{flex:1,children:o.jsx(r.SanityPreview,{layout:"default",value:t,schemaType:f.get(t._type)})})})})]})}function f(e,t){return e.orderRank<t.orderRank?-1:e.orderRank>t.orderRank?1:0}function m(){return r.useClient({apiVersion:"2021-09-01"})}function x(e){let{data:n,type:r,listIsUpdating:s,setListIsUpdating:u}=e;const p=l.useToast(),h=c.usePaneRouter(),{navigateIntent:x}=h,[y,v]=a.useState(n);a.useEffect((()=>{s||v(n)}),[n]);const[b,j]=a.useState(""),[k,R]=a.useState([]),w=a.useCallback((()=>R([])),[R]),O=a.useCallback(((e,t,n)=>{const i=k.includes(e),s=n.shiftKey,o=-1!==navigator.appVersion.indexOf("Win")?n.ctrlKey:n.metaKey;let a=[];if(!s&&!o)return x("edit",{id:e,type:r}),R([e]);if(s&&!i){const n=k[k.length-1],r=y.findIndex((e=>e._id===n)),i=t<r?t:r,s=t>r?t:r,o=y.filter(((e,t)=>t>i&&t<s)).map((e=>e._id));a=[...k,...o,e]}else a=i?k.filter((t=>t!==e)):[...k,e];return R(a)}),[R,x,y,k,r]),I=m(),S=a.useCallback((async(e,t)=>{const n=I.transaction();e.forEach((e=>{let[t,r]=e;return n.patch(t,r)})),await n.commit().then((e=>{w(),j(""),u(!1),p.push({title:"".concat(1===e.results.length?"1 Document":"".concat(e.results.length," Documents")," Reordered"),status:"success",description:t})})).catch((()=>{j(""),u(!1),p.push({title:"Reordering failed",status:"error"})}))}),[I,j,w,u,p]),D=a.useCallback(((e,t)=>{j("");const{source:n,destination:r,draggableId:s}=null!=e?e:{};if((null==n?void 0:n.index)===(null==r?void 0:r.index))return;if(!(null==t?void 0:t.length)||!s)return;const o=(null==k?void 0:k.length)?k:[s];if(!(null==o?void 0:o.length))return;u(!0),R(o);const{newOrder:a,patches:l,message:d}=(e=>{let{entities:t,selectedIds:n,source:r,destination:s,debug:o=!1}=e;const a=r.index,l=s.index,d=a>l,c=t.filter((e=>n.includes(e._id))),u=["Moved",1===c.length?"1 Document":"".concat(c.length," Documents"),d?"up":"down","from position","".concat(a+1," to ").concat(l+1)].join(" "),{all:p,selected:h}=t.reduce(((e,r,s)=>{var o,a,u,p;if(n.includes(r._id))return{all:e.all,selected:e.selected};if(s===l){const n=s-1,l=(null==(o=t[n])?void 0:o.orderRank)?i.LexoRank.parse(null==(a=t[n])?void 0:a.orderRank):i.LexoRank.min(),h=i.LexoRank.parse(t[s].orderRank),g=s+1,f=(null==(u=t[g])?void 0:u.orderRank)?i.LexoRank.parse(null==(p=t[g])?void 0:p.orderRank):i.LexoRank.max();let m=d?l.between(h):h.between(f);for(let e=0;e<c.length;e+=1)c[e].orderRank=m.value,m=d?m.between(h):m.between(f);return{all:d?[...e.all,...c,r]:[...e.all,r,...c],selected:c}}return{all:[...e.all,r],selected:e.selected}}),{all:[],selected:[]}),g=h.map((e=>[e._id,{set:{orderRank:e.orderRank}}]));return{newOrder:p.sort(f),patches:g,message:u}})({entities:t,selectedIds:o,source:n,destination:r});(null==a?void 0:a.length)&&v(a),(null==l?void 0:l.length)&&S(l,d)}),[k,j,R,S,u]),_=a.useCallback((e=>{const t=e.draggableId;k.includes(t)||w(),j(t)}),[k,w,j]),C=a.useCallback(((e,t,n,r)=>D({draggableId:n,source:{index:e},destination:{index:t}},r)),[D]),E=a.useCallback((e=>{"Escape"===e.key&&w()}),[w]);a.useEffect((()=>(window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)})),[E]);const L=a.useMemo((()=>{if(!y.length)return[];const e=y.map((e=>e.orderRank));return e.filter(((t,n)=>e.indexOf(t)!==n))}),[y]),P=a.useCallback((e=>D(e,y)),[y,D]);return o.jsx(d.DragDropContext,{onDragStart:_,onDragEnd:P,children:o.jsx(d.Droppable,{droppableId:"documentSortZone",children:e=>o.jsxs("div",t(t({},e.droppableProps),{},{ref:e.innerRef,children:[y.map(((e,n)=>o.jsx(d.Draggable,{draggableId:e._id,index:n,children:(r,i)=>{const a=k.includes(e._id),d=i.isDragging,c=Boolean(!d&&b&&a),u=s&&a,p=Boolean(!e.orderRank),h=(e=>{const{isDuplicate:t,isGhosting:n,isDragging:r,isSelected:i}=e;return n?"transparent":r||i?"primary":t?"caution":void 0})({isDuplicate:L.includes(e.orderRank),isGhosting:c,isDragging:d,isSelected:a});return o.jsx("div",t(t(t({ref:r.innerRef},r.draggableProps),r.dragHandleProps),{},{style:p?{opacity:.2,pointerEvents:"none"}:(f=r.draggableProps.style,m=u,t({userSelect:"none",transition:"opacity 500ms ease-in-out",opacity:m?.2:1,pointerEvents:m?"none":void 0},f)),children:o.jsx(l.Box,{paddingBottom:1,children:o.jsx(l.Card,{tone:h,shadow:d?2:void 0,radius:2,children:o.jsx(g,{doc:e,entities:y,handleSelect:O,increment:C,index:n,isFirst:0===n,isLast:n===y.length-1})})})}));var f,m}},"".concat(e._id,"-").concat(e.orderRank)))),e.placeholder]}))})})}function y(e){let{children:t}=e;return o.jsx(l.Box,{padding:3,children:o.jsx(l.Card,{padding:4,radius:2,shadow:1,tone:"caution",children:o.jsx(l.Text,{children:t})})})}const v={};function b(e){let{type:t,filter:n,params:r=v}=e;const[i,s]=a.useState(!0),[d,c]=a.useState(!1),[u,p]=a.useState([]),h=m();a.useEffect((()=>{const e="*[_type == $type ".concat(n?"&& ".concat(n):"","]|order(@[$order] asc){\n _id, _type, ").concat("orderRank","\n }"),o=Object.assign(r,{type:t,order:"orderRank"});let a;const l=async()=>{h.fetch(e,o).then((e=>{const t=e.reduce(((t,n)=>{if(!n._id.startsWith("drafts.")){return e.some((e=>e._id==="drafts.".concat(n._id)))?t:[...t,n]}return[...t,n]}),[]);p(t),i&&s(!1)}))};return d||u.length||(async()=>{s(!0),await l(),a||(a=h.listen(e,o).subscribe((()=>l())))})(),()=>null==a?void 0:a.unsubscribe()}),[t]);const g=a.useMemo((()=>u.length?u.filter((e=>!e.orderRank)).length:0),[u]);return i?o.jsx(l.Flex,{style:{width:"100%",height:"100%"},align:"center",justify:"center",children:o.jsx(l.Spinner,{})}):o.jsxs(l.Stack,{space:1,style:{overflow:"scroll",height:"100%"},children:[g>0&&o.jsxs(y,{children:[g,"/",u.length," Documents have no Order. Select"," ",o.jsx("strong",{children:"Reset Order"})," from the Menu above to fix."]}),o.jsx(l.Box,{padding:1,children:o.jsx(x,{data:u,type:t,listIsUpdating:d,setListIsUpdating:c})})]})}function j(e){let{type:t,showIncrements:n,resetOrderTransaction:i,filter:s,params:d}=e;const c=l.useToast(),u=r.useSchema();a.useEffect((()=>{(null==i?void 0:i.title)&&(null==i?void 0:i.status)&&c.push(i)}),[i,c]);const p=a.useMemo((()=>{if(!t)return o.jsxs(o.Fragment,{children:["No ",o.jsx("code",{children:"type"})," was configured"]});const e=u.get(t);return e?"fields"in e&&e.fields.some((e=>"orderRank"===(null==e?void 0:e.name)))?"fields"in e&&e.fields.some((e=>{var t;return"orderRank"===(null==e?void 0:e.name)&&"string"!==(null==(t=null==e?void 0:e.type)?void 0:t.name)}))?o.jsxs(o.Fragment,{children:[o.jsx("code",{children:"orderRank"})," field on Schema ",o.jsx("code",{children:t})," must be"," ",o.jsx("code",{children:"string"})," type"]}):"":o.jsxs(o.Fragment,{children:["Schema ",o.jsx("code",{children:t})," must have an ",o.jsx("code",{children:"orderRank"})," field of type"," ",o.jsx("code",{children:"string"})]}):o.jsxs(o.Fragment,{children:["Schema ",o.jsx("code",{children:t})," not found"]})}),[t,u]);return p?o.jsx(y,{children:p}):o.jsx(h.Provider,{value:{showIncrements:n},children:o.jsx(b,{type:t,filter:s,params:d})})}class k extends a.Component{constructor(e){super(e),this.actionHandlers={showIncrements:()=>{this.setState((e=>({showIncrements:!e.showIncrements})))},resetOrder:async()=>{var e;this.setState((()=>({resetOrderTransaction:{status:"info",title:"Reordering started...",closable:!0}})));const t=await async function(){let e=arguments.length>1?arguments[1]:void 0;const t="*[_type == $type]|order(@[$order] asc)._id",n={type:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",order:"orderRank"},r=await e.fetch(t,n);if(!r.length)return null;const s=e.transaction();let o=i.LexoRank.min();for(let e=0;e<r.length;e+=1)o=o.genNext().genNext(),s.patch(r[e],{set:{orderRank:o.value}});return s.commit().then((e=>e)).catch((e=>e))}(this.props.options.type,this.props.options.client),n=null==(e=null==t?void 0:t.results)?void 0:e.length;this.setState((()=>({resetOrderTransaction:{status:n?"success":"info",title:n?"Reordered ".concat(1===t.results.length?"Document":"Documents"):"Reordering failed",closable:!0}})))}},this.state={showIncrements:!1,resetOrderTransaction:{}}}render(){var e,t,n,r,i,s;const a=null==(t=null==(e=null==this?void 0:this.props)?void 0:e.options)?void 0:t.type;return a?o.jsx(j,{filter:null==(r=null==(n=null==this?void 0:this.props)?void 0:n.options)?void 0:r.filter,params:null==(s=null==(i=null==this?void 0:this.props)?void 0:i.options)?void 0:s.params,type:a,showIncrements:this.state.showIncrements,resetOrderTransaction:this.state.resetOrderTransaction}):null}}exports.orderRankField=e=>{if(!(null==e?void 0:e.type))throw new Error("\n type must be provided.\n Example: orderRankField({type: 'category'})\n ");const{type:n}=e;return r.defineField(t(t({title:"Order Rank",readOnly:!0,hidden:!0},e),{},{name:"orderRank",type:"string",initialValue:async(e,t)=>{let{getClient:r}=t;return function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const t=e?i.LexoRank.parse(e):i.LexoRank.min();return t.genNext().genNext().value}(await r({apiVersion:"2021-09-01"}).fetch("*[_type == $type]|order(@[$order] desc)[0][$order]",{type:n,order:"orderRank"}))}}))},exports.orderRankOrdering=p,exports.orderableDocumentListDeskItem=function(e){var t,n;if(!(null==e?void 0:e.type)||!e.context||!e.S)throw new Error("\n type, context and S (StructureBuilder) must be provided.\n context and S are available when configuring structure.\n Example: orderableDocumentListDeskItem({type: 'category'})\n ");const{type:r,filter:i,params:o,title:a,icon:l,id:d,context:c,S:u}=e,{schema:p,getClient:h}=c,g=h({apiVersion:"2021-09-01"}),f=null!=a?a:"Orderable ".concat(r),m=null!=d?d:"orderable-".concat(r),x=null!=l?l:s.SortIcon,y=null!=(n=null==(t=p.get(r))?void 0:t.title)?n:r;return u.listItem().title(f).id(m).icon(x).child(Object.assign(u.documentTypeList(r).serialize(),{__preserveInstance:!0,key:m,type:"component",component:k,options:{type:r,filter:i,params:o,client:g},menuItems:[u.menuItem().title("Create new ".concat(y)).intent({type:"create",params:{type:r}}).serialize(),u.menuItem().title("Reset Order").icon(s.GenerateIcon).action("resetOrder").serialize(),u.menuItem().title("Show Increments").icon(s.SortIcon).action("showIncrements").serialize()]})).serialize()};
825
2
  //# sourceMappingURL=index.js.map