@sanity/orderable-document-list 1.2.2 → 1.2.3

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