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