@sanity/orderable-document-list
Version:
Drag-and-drop Document Ordering without leaving the Editing surface
792 lines (790 loc) • 27.7 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var sanity = require('sanity');
var lexorank = require('lexorank');
var icons = require('@sanity/icons');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var ui = require('@sanity/ui');
var sanityPluginUtils = require('sanity-plugin-utils');
var dnd = require('@hello-pangea/dnd');
var structure = require('sanity/structure');
function _interopDefaultCompat(e) {
return e && typeof e === 'object' && 'default' in e ? e : {
default: e
};
}
var React__default = /*#__PURE__*/_interopDefaultCompat(React);
const ORDER_FIELD_NAME = "orderRank";
const API_VERSION = "2021-09-01";
function initialRank() {
let compareRankValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
let newItemPosition = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "after";
const compareRank = compareRankValue ? lexorank.LexoRank.parse(compareRankValue) : lexorank.LexoRank.min();
const rank = newItemPosition === "before" ? compareRank.genPrev().genPrev() : compareRank.genNext().genNext();
return rank.toString();
}
const orderRankField = config => {
if (!(config == null ? void 0 : config.type)) {
throw new Error("\n type must be provided.\n Example: orderRankField({type: 'category'})\n ");
}
const {
type,
newItemPosition = "after"
} = config;
return sanity.defineField({
title: "Order Rank",
readOnly: true,
hidden: true,
...config,
name: ORDER_FIELD_NAME,
type: "string",
initialValue: async (p, _ref) => {
let {
getClient
} = _ref;
const direction = newItemPosition === "before" ? "asc" : "desc";
const lastDocOrderRank = await getClient({
apiVersion: API_VERSION
}).fetch("*[_type == $type]|order(@[$order] ".concat(direction, ")[0][$order]"), {
type,
order: ORDER_FIELD_NAME
});
return initialRank(lastDocOrderRank, newItemPosition);
}
});
};
const orderRankOrdering = {
title: "Ordered",
name: "ordered",
by: [{
field: ORDER_FIELD_NAME,
direction: "asc"
}]
};
const OrderableContext = React__default.default.createContext({});
function Document(_ref2) {
let {
doc,
increment,
entities,
index,
isFirst,
isLast,
dragBadge
} = _ref2;
var _a, _b;
const {
showIncrements
} = React.useContext(OrderableContext);
const schema = sanity.useSchema();
const router = structure.usePaneRouter();
const {
ChildLink,
groupIndex,
routerPanesState
} = router;
const currentDoc = ((_b = (_a = routerPanesState[groupIndex + 1]) == null ? void 0 : _a[0]) == null ? void 0 : _b.id) || false;
const pressed = currentDoc === doc._id || currentDoc === doc._id.replace("drafts.", "");
const selected = pressed && routerPanesState.length === groupIndex + 2;
const Link = React.useMemo(() => function LinkComponent(linkProps) {
return /* @__PURE__ */jsxRuntime.jsx(ChildLink, {
...linkProps,
childId: doc._id
});
}, [ChildLink, doc._id]);
return /* @__PURE__ */jsxRuntime.jsx(sanity.PreviewCard, {
__unstable_focusRing: true,
as: Link,
"data-as": "a",
"data-ui": "PaneItem",
radius: 2,
pressed,
selected,
sizing: "border",
tabIndex: -1,
tone: "inherit",
width: "100%",
flex: 1,
children: /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
align: "center",
children: [/* @__PURE__ */jsxRuntime.jsx(ui.Box, {
paddingX: 2,
style: {
flexShrink: 0
},
children: /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
size: 2,
children: /* @__PURE__ */jsxRuntime.jsx(icons.DragHandleIcon, {
cursor: "grab"
})
})
}), showIncrements && /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
style: {
flexShrink: 0
},
align: "center",
gap: 1,
paddingRight: 1,
children: [/* @__PURE__ */jsxRuntime.jsx(ui.Button, {
padding: 2,
mode: "ghost",
onClick: () => increment(index, index + -1, doc._id, entities),
disabled: isFirst,
icon: icons.ChevronUpIcon
}), /* @__PURE__ */jsxRuntime.jsx(ui.Button, {
padding: 2,
mode: "ghost",
disabled: isLast,
onClick: () => increment(index, index + 1, doc._id, entities),
icon: icons.ChevronDownIcon
})]
}), /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
style: {
width: "100%"
},
children: /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
flex: 1,
align: "center",
children: /* @__PURE__ */jsxRuntime.jsx(sanity.Preview, {
layout: "default",
value: doc,
schemaType: schema.get(doc._type)
})
})
}), dragBadge && /* @__PURE__ */jsxRuntime.jsx(ui.Card, {
tone: "default",
marginRight: 4,
radius: 5,
children: /* @__PURE__ */jsxRuntime.jsx(ui.AvatarCounter, {
count: dragBadge
})
})]
})
});
}
function lexicographicalSort(a, b) {
if (!a[ORDER_FIELD_NAME] || !b[ORDER_FIELD_NAME]) {
return 0;
} else if (a[ORDER_FIELD_NAME] < b[ORDER_FIELD_NAME]) {
return -1;
} else if (a[ORDER_FIELD_NAME] > b[ORDER_FIELD_NAME]) {
return 1;
}
return 0;
}
const reorderDocuments = _ref3 => {
let {
entities,
selectedIds,
source,
destination
} = _ref3;
const startIndex = source.index;
const endIndex = destination.index;
const isMovingUp = startIndex > endIndex;
const selectedItems = entities.filter(item => selectedIds.includes(item._id));
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(" ");
const {
all,
selected
} = entities.reduce((acc, cur, curIndex) => {
var _a, _b, _c, _d;
if (selectedIds.includes(cur._id)) {
return {
all: acc.all,
selected: acc.selected
};
}
if (curIndex === endIndex) {
const prevIndex = curIndex - 1;
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();
const curRank = lexorank.LexoRank.parse(entities[curIndex][ORDER_FIELD_NAME]);
const nextIndex = curIndex + 1;
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();
let betweenRank = isMovingUp ? prevRank.between(curRank) : curRank.between(nextRank);
for (let selectedIndex = 0; selectedIndex < selectedItems.length; selectedIndex += 1) {
selectedItems[selectedIndex][ORDER_FIELD_NAME] = betweenRank.toString();
betweenRank = isMovingUp ? betweenRank.between(curRank) : betweenRank.between(nextRank);
}
return {
// The `all` array gets sorted by order field later anyway
// so that this probably isn't necessary ¯\_(ツ)_/¯
all: isMovingUp ? [...acc.all, ...selectedItems, cur] : [...acc.all, cur, ...selectedItems],
selected: selectedItems
};
}
return {
all: [...acc.all, cur],
selected: acc.selected
};
}, {
all: [],
selected: []
});
const patches = selected.flatMap(doc => {
const docPatches = [[doc._id, {
set: {
[ORDER_FIELD_NAME]: doc[ORDER_FIELD_NAME]
}
}]];
if (doc._id.startsWith("drafts.") && doc.hasPublished) {
docPatches.push([doc._id.replace("drafts.", ""), {
set: {
[ORDER_FIELD_NAME]: doc[ORDER_FIELD_NAME]
}
}]);
}
return docPatches;
});
const allSorted = all.sort(lexicographicalSort);
return {
newOrder: allSorted,
patches,
message
};
};
function useSanityClient() {
return sanity.useClient({
apiVersion: API_VERSION
});
}
const getItemStyle = (draggableStyle, itemIsUpdating) => ({
userSelect: "none",
transition: "opacity 500ms ease-in-out",
opacity: itemIsUpdating ? 0.2 : 1,
pointerEvents: itemIsUpdating ? "none" : void 0,
...draggableStyle
});
const cardTone = settings => {
const {
isDuplicate,
isGhosting,
isDragging,
isSelected
} = settings;
if (isGhosting) return "transparent";
if (isDragging || isSelected) return "primary";
if (isDuplicate) return "caution";
return void 0;
};
function DraggableList(_ref4) {
let {
data,
listIsUpdating,
setListIsUpdating
} = _ref4;
var _a, _b;
const toast = ui.useToast();
const router = structure.usePaneRouter();
const {
groupIndex,
routerPanesState
} = router;
const currentDoc = ((_b = (_a = routerPanesState[groupIndex + 1]) == null ? void 0 : _a[0]) == null ? void 0 : _b.id) || false;
const [orderedData, setOrderedData] = React.useState(data);
React.useEffect(() => {
if (!listIsUpdating) setOrderedData(data);
}, [data]);
const [draggingId, setDraggingId] = React.useState("");
const [selectedIds, setSelectedIds] = React.useState(currentDoc ? [currentDoc] : []);
const clearSelected = React.useCallback(() => setSelectedIds([]), [setSelectedIds]);
const handleSelect = React.useCallback((clickedId, index, nativeEvent) => {
const isSelected = selectedIds.includes(clickedId);
const selectMultiple = nativeEvent.shiftKey;
const isUsingWindows = navigator.appVersion.indexOf("Win") !== -1;
const selectAdditional = isUsingWindows ? nativeEvent.ctrlKey : nativeEvent.metaKey;
let updatedIds = [];
if (!selectMultiple && !selectAdditional) {
return setSelectedIds([clickedId]);
}
if (selectMultiple) {
nativeEvent.preventDefault();
}
if (selectMultiple && !isSelected) {
const lastSelectedId = selectedIds[selectedIds.length - 1];
const lastSelectedIndex = orderedData.findIndex(item => item._id === lastSelectedId);
const firstSelected = index < lastSelectedIndex ? index : lastSelectedIndex;
const lastSelected = index > lastSelectedIndex ? index : lastSelectedIndex;
const betweenIds = orderedData.filter((item, itemIndex) => itemIndex > firstSelected && itemIndex < lastSelected).map(item => item._id);
updatedIds = [...selectedIds, ...betweenIds, clickedId];
} else if (isSelected) {
updatedIds = selectedIds.filter(id => id !== clickedId);
} else {
updatedIds = [...selectedIds, clickedId];
}
return setSelectedIds(updatedIds);
}, [setSelectedIds, orderedData, selectedIds]);
const client = useSanityClient();
const transactPatches = React.useCallback(async (patches, message) => {
const transaction = client.transaction();
patches.forEach(_ref5 => {
let [docId, ops] = _ref5;
return transaction.patch(docId, ops);
});
await transaction.commit().then(updated => {
clearSelected();
setDraggingId("");
setListIsUpdating(false);
toast.push({
title: "".concat(updated.results.length === 1 ? "1 Document" : "".concat(updated.results.length, " Documents"), " Reordered"),
status: "success",
description: message
});
}).catch(() => {
setDraggingId("");
setListIsUpdating(false);
toast.push({
title: "Reordering failed",
status: "error"
});
});
}, [client, setDraggingId, clearSelected, setListIsUpdating, toast]);
const handleDragEnd = React.useCallback((result, entities) => {
setDraggingId("");
const {
source,
destination,
draggableId
} = result != null ? result : {};
if ((source == null ? void 0 : source.index) === (destination == null ? void 0 : destination.index)) return;
if (!(entities == null ? void 0 : entities.length) || !draggableId) return;
const effectedIds = (selectedIds == null ? void 0 : selectedIds.length) ? selectedIds : [draggableId];
if (!(effectedIds == null ? void 0 : effectedIds.length)) return;
setListIsUpdating(true);
setSelectedIds(effectedIds);
const {
newOrder,
patches,
message
} = reorderDocuments({
entities,
selectedIds: effectedIds,
source,
destination
});
if (newOrder == null ? void 0 : newOrder.length) {
setOrderedData(newOrder);
}
if (patches == null ? void 0 : patches.length) {
transactPatches(patches, message);
}
}, [selectedIds, setDraggingId, setSelectedIds, transactPatches, setListIsUpdating]);
const handleDragStart = React.useCallback(start => {
const id = start.draggableId;
const selected = selectedIds.includes(id);
if (!selected) clearSelected();
setDraggingId(id);
}, [selectedIds, clearSelected, setDraggingId]);
const incrementIndex = React.useCallback((shiftFrom, shiftTo, id, entities) => {
const result = {
draggableId: id,
source: {
index: shiftFrom
},
destination: {
index: shiftTo
}
};
return handleDragEnd(result, entities);
}, [handleDragEnd]);
const onWindowKeyDown = React.useCallback(event => {
if (event.key === "Escape") {
clearSelected();
}
}, [clearSelected]);
React.useEffect(() => {
window.addEventListener("keydown", onWindowKeyDown);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [onWindowKeyDown]);
const duplicateOrders = React.useMemo(() => {
if (!orderedData.length) return [];
const orderField = orderedData.map(item => item[ORDER_FIELD_NAME]);
return orderField.filter((item, index) => orderField.indexOf(item) !== index);
}, [orderedData]);
const onDragEnd = React.useCallback(result => handleDragEnd(result, orderedData), [orderedData, handleDragEnd]);
return /* @__PURE__ */jsxRuntime.jsx(dnd.DragDropContext, {
onDragStart: handleDragStart,
onDragEnd,
children: /* @__PURE__ */jsxRuntime.jsx(dnd.Droppable, {
droppableId: "documentSortZone",
children: provided => /* @__PURE__ */jsxRuntime.jsxs("div", {
...provided.droppableProps,
ref: provided.innerRef,
children: [orderedData.map((item, index) => /* @__PURE__ */jsxRuntime.jsx(dnd.Draggable, {
draggableId: item._id,
index,
children: (innerProvided, innerSnapshot) => {
const isSelected = selectedIds.includes(item._id);
const isDragging = innerSnapshot.isDragging;
const isGhosting = Boolean(!isDragging && draggingId && isSelected);
const isUpdating = listIsUpdating && isSelected;
const isDisabled = Boolean(!item[ORDER_FIELD_NAME]);
const isDuplicate = duplicateOrders.includes(item[ORDER_FIELD_NAME]);
const tone = cardTone({
isDuplicate,
isGhosting,
isDragging,
isSelected
});
const selectedCount = selectedIds.length;
const dragBadge = isDragging && selectedCount > 1 ? selectedCount : false;
return /* @__PURE__ */jsxRuntime.jsx("div", {
ref: innerProvided.innerRef,
...innerProvided.draggableProps,
...innerProvided.dragHandleProps,
style: isDisabled ? {
opacity: 0.2,
pointerEvents: "none"
} : getItemStyle(innerProvided.draggableProps.style, isUpdating),
children: /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
paddingBottom: 1,
children: /* @__PURE__ */jsxRuntime.jsx(ui.Card, {
tone,
shadow: isDragging ? 2 : void 0,
radius: 2,
onClick: e => handleSelect(item._id, index, e.nativeEvent),
children: /* @__PURE__ */jsxRuntime.jsx(Document, {
doc: item,
entities: orderedData,
increment: incrementIndex,
index,
isFirst: index === 0,
isLast: index === orderedData.length - 1,
dragBadge
})
})
})
});
}
}, "".concat(item._id, "-").concat(item[ORDER_FIELD_NAME]))), provided.placeholder]
})
})
});
}
const DEFAULT_PARAMS = {};
function DocumentListQuery(_ref6) {
let {
type,
filter,
params = DEFAULT_PARAMS
} = _ref6;
const [listIsUpdating, setListIsUpdating] = React.useState(false);
const [data, setData] = React.useState([]);
const query = "*[_type == $type ".concat(filter ? "&& ".concat(filter) : "", "]|order(@[$order] asc){\n _id, _type, ").concat(ORDER_FIELD_NAME, "\n }");
const queryParams = {
...params,
type,
order: ORDER_FIELD_NAME
};
const {
data: queryData,
loading,
error
} = sanityPluginUtils.useListeningQuery(query, {
params: queryParams,
initialValue: []
});
React.useEffect(() => {
if (queryData) {
const filteredDocuments = queryData.reduce((acc, cur) => {
if (!cur._id.startsWith("drafts.")) {
const alsoHasDraft = queryData.some(doc => doc._id === "drafts.".concat(cur._id));
return alsoHasDraft ? acc : [...acc, cur];
}
cur.hasPublished = queryData.some(doc => doc._id === cur._id.replace("drafts.", ""));
return [...acc, cur];
}, []);
setData(filteredDocuments);
} else {
setData([]);
}
}, [queryData]);
const unorderedDataCount = React.useMemo(() => (data == null ? void 0 : data.length) ? data.filter(doc => !doc[ORDER_FIELD_NAME]).length : 0, [data]);
if (loading) {
return /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
style: {
width: "100%",
height: "100%"
},
align: "center",
justify: "center",
children: /* @__PURE__ */jsxRuntime.jsx(ui.Spinner, {})
});
}
if (error) {
return /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
padding: 2,
children: /* @__PURE__ */jsxRuntime.jsx(sanityPluginUtils.Feedback, {
tone: "critical",
title: "There was an error",
description: "Please try again later"
})
});
}
if (!data || (data == null ? void 0 : data.length) == 0) return /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
align: "center",
direction: "column",
height: "fill",
justify: "center",
children: /* @__PURE__ */jsxRuntime.jsx(ui.Container, {
width: 1,
children: /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
paddingX: 4,
paddingY: 5,
children: /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
align: "center",
muted: true,
children: "No documents of this type"
})
})
})
});
return /* @__PURE__ */jsxRuntime.jsx(ui.Stack, {
space: 1,
style: {
overflow: "auto",
height: "100%"
},
children: /* @__PURE__ */jsxRuntime.jsxs(ui.Box, {
padding: 2,
children: [unorderedDataCount > 0 && /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
marginBottom: 2,
children: /* @__PURE__ */jsxRuntime.jsx(sanityPluginUtils.Feedback, {
tone: "caution",
description: /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, {
children: [unorderedDataCount, "/", data == null ? void 0 : data.length, " documents have no order. Select", " ", /* @__PURE__ */jsxRuntime.jsx("strong", {
children: "Reset Order"
}), " from the menu above to fix."]
})
})
}), /* @__PURE__ */jsxRuntime.jsx(DraggableList, {
data,
listIsUpdating,
setListIsUpdating
})]
})
});
}
function DocumentListWrapper(_ref7) {
let {
type,
showIncrements,
resetOrderTransaction,
filter,
params
} = _ref7;
const toast = ui.useToast();
const schema = sanity.useSchema();
React.useEffect(() => {
if ((resetOrderTransaction == null ? void 0 : resetOrderTransaction.title) && (resetOrderTransaction == null ? void 0 : resetOrderTransaction.status)) {
toast.push(resetOrderTransaction);
}
}, [resetOrderTransaction, toast]);
const schemaIsInvalid = React.useMemo(() => {
if (!type) {
return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, {
children: ["No ", /* @__PURE__ */jsxRuntime.jsx("code", {
children: "type"
}), " was configured"]
});
}
const typeSchema = schema.get(type);
if (!typeSchema) {
return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, {
children: ["Schema ", /* @__PURE__ */jsxRuntime.jsx("code", {
children: type
}), " not found"]
});
}
if (!("fields" in typeSchema) || !typeSchema.fields.some(field => (field == null ? void 0 : field.name) === ORDER_FIELD_NAME)) {
return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, {
children: ["Schema ", /* @__PURE__ */jsxRuntime.jsx("code", {
children: type
}), " must have an ", /* @__PURE__ */jsxRuntime.jsx("code", {
children: ORDER_FIELD_NAME
}), " field of type", " ", /* @__PURE__ */jsxRuntime.jsx("code", {
children: "string"
})]
});
}
if ("fields" in typeSchema && typeSchema.fields.some(field => {
var _a;
return (field == null ? void 0 : field.name) === ORDER_FIELD_NAME && ((_a = field == null ? void 0 : field.type) == null ? void 0 : _a.name) !== "string";
})) {
return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, {
children: [/* @__PURE__ */jsxRuntime.jsx("code", {
children: ORDER_FIELD_NAME
}), " field on Schema ", /* @__PURE__ */jsxRuntime.jsx("code", {
children: type
}), " must be", " ", /* @__PURE__ */jsxRuntime.jsx("code", {
children: "string"
}), " type"]
});
}
return "";
}, [type, schema]);
if (schemaIsInvalid) {
return /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
padding: 2,
children: /* @__PURE__ */jsxRuntime.jsx(sanityPluginUtils.Feedback, {
description: schemaIsInvalid,
tone: "caution"
})
});
}
return /* @__PURE__ */jsxRuntime.jsx(OrderableContext.Provider, {
value: {
showIncrements
},
children: /* @__PURE__ */jsxRuntime.jsx(DocumentListQuery, {
type,
filter,
params
})
});
}
async function resetOrder() {
let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
let client = arguments.length > 1 ? arguments[1] : undefined;
const query = "*[_type == $type]|order(@[$order] asc)._id";
const queryParams = {
type,
order: ORDER_FIELD_NAME
};
const documents = await client.fetch(query, queryParams);
if (!documents.length) {
return null;
}
const transaction = client.transaction();
let aLexoRank = lexorank.LexoRank.min();
for (let index = 0; index < documents.length; index += 1) {
aLexoRank = aLexoRank.genNext().genNext();
transaction.patch(documents[index], {
set: {
[ORDER_FIELD_NAME]: aLexoRank.toString()
}
});
}
return transaction.commit().then(update => update).catch(err => err);
}
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
enumerable: true,
configurable: true,
writable: true,
value
}) : obj[key] = value;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
class OrderableDocumentList extends React.Component {
constructor(props) {
super(props);
__publicField(this, "actionHandlers", {
showIncrements: () => {
this.setState(state => ({
showIncrements: !state.showIncrements
}));
},
resetOrder: async () => {
var _a;
this.setState(() => ({
resetOrderTransaction: {
status: "info",
title: "Reordering started...",
closable: true
}
}));
const update = await resetOrder(this.props.options.type, this.props.options.client);
const reorderWasSuccessful = (_a = update == null ? void 0 : update.results) == null ? void 0 : _a.length;
this.setState(() => ({
resetOrderTransaction: {
status: reorderWasSuccessful ? "success" : "info",
title: reorderWasSuccessful ? "Reordered ".concat(update.results.length === 1 ? "Document" : "Documents") : "Reordering failed",
closable: true
}
}));
}
});
this.state = {
showIncrements: false,
resetOrderTransaction: {}
};
}
render() {
var _a, _b, _c, _d, _e, _f;
const type = (_b = (_a = this == null ? void 0 : this.props) == null ? void 0 : _a.options) == null ? void 0 : _b.type;
if (!type) {
return null;
}
return /* @__PURE__ */jsxRuntime.jsx(DocumentListWrapper, {
filter: (_d = (_c = this == null ? void 0 : this.props) == null ? void 0 : _c.options) == null ? void 0 : _d.filter,
params: (_f = (_e = this == null ? void 0 : this.props) == null ? void 0 : _e.options) == null ? void 0 : _f.params,
type,
showIncrements: this.state.showIncrements,
resetOrderTransaction: this.state.resetOrderTransaction
});
}
}
function orderableDocumentListDeskItem(config) {
var _a, _b;
if (!(config == null ? void 0 : config.type) || !config.context || !config.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,
filter,
menuItems = [],
createIntent,
params,
title,
icon,
id,
context,
S
} = config;
const {
schema,
getClient
} = context;
const client = getClient({
apiVersion: API_VERSION
});
const listTitle = title != null ? title : "Orderable ".concat(type);
const listId = id != null ? id : "orderable-".concat(type);
const listIcon = icon != null ? icon : icons.SortIcon;
const typeTitle = (_b = (_a = schema.get(type)) == null ? void 0 : _a.title) != null ? _b : type;
if (createIntent !== false) {
menuItems.push(S.menuItem().title("Create new ".concat(typeTitle)).intent({
type: "create",
params: {
type
}
}).serialize());
}
return S.listItem().title(listTitle).id(listId).icon(listIcon).schemaType(type).child(Object.assign(S.documentTypeList(type).canHandleIntent(() => !!createIntent).serialize(), {
// Prevents the component from re-rendering when switching documents
__preserveInstance: true,
// Prevents the component from NOT re-rendering when switching listItems
key: listId,
type: "component",
component: OrderableDocumentList,
options: {
type,
filter,
params,
client
},
menuItems: [...menuItems, S.menuItem().title("Reset Order").icon(icons.GenerateIcon).action("resetOrder").serialize(), S.menuItem().title("Toggle Increments").icon(icons.SortIcon).action("showIncrements").serialize()]
})).serialize();
}
exports.orderRankField = orderRankField;
exports.orderRankOrdering = orderRankOrdering;
exports.orderableDocumentListDeskItem = orderableDocumentListDeskItem;
//# sourceMappingURL=index.js.map