@sanity/hierarchical-document-list 0.1.0-next.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +99 -26
  2. package/lib/TreeDeskStructure.d.ts +2 -1
  3. package/lib/TreeDeskStructure.js +82 -33
  4. package/lib/TreeInputComponent.d.ts +1 -1
  5. package/lib/TreeInputComponent.js +50 -8
  6. package/lib/components/DeskWarning.d.ts +1 -1
  7. package/lib/components/DeskWarning.js +43 -9
  8. package/lib/components/DocumentInNode.d.ts +1 -1
  9. package/lib/components/DocumentInNode.js +64 -28
  10. package/lib/components/DocumentPreviewStatus.d.ts +1 -1
  11. package/lib/components/DocumentPreviewStatus.js +36 -13
  12. package/lib/components/NodeActions.d.ts +1 -1
  13. package/lib/components/NodeActions.js +55 -18
  14. package/lib/components/NodeContentRenderer.js +75 -49
  15. package/lib/components/PlaceholderDropzone.d.ts +1 -1
  16. package/lib/components/PlaceholderDropzone.js +22 -9
  17. package/lib/components/TreeEditor.d.ts +1 -1
  18. package/lib/components/TreeEditor.js +48 -30
  19. package/lib/components/TreeEditorErrorBoundary.d.ts +2 -16
  20. package/lib/components/TreeEditorErrorBoundary.js +50 -31
  21. package/lib/components/TreeNodeRenderer.js +53 -16
  22. package/lib/components/TreeNodeRendererScaffold.d.ts +1 -1
  23. package/lib/components/TreeNodeRendererScaffold.js +19 -139
  24. package/lib/createDeskHierarchy.js +58 -27
  25. package/lib/createHierarchicalSchemas.d.ts +78 -0
  26. package/lib/createHierarchicalSchemas.js +138 -0
  27. package/lib/{utils → hooks}/useAllItems.d.ts +0 -0
  28. package/lib/hooks/useAllItems.js +119 -0
  29. package/lib/{utils → hooks}/useLocalTree.d.ts +0 -0
  30. package/lib/hooks/useLocalTree.js +59 -0
  31. package/lib/{utils → hooks}/useTreeOperations.d.ts +1 -1
  32. package/lib/hooks/useTreeOperations.js +39 -0
  33. package/lib/{utils → hooks}/useTreeOperationsProvider.d.ts +1 -1
  34. package/lib/hooks/useTreeOperationsProvider.js +85 -0
  35. package/lib/index.d.ts +1 -1
  36. package/lib/index.js +12 -3
  37. package/lib/schemas/hierarchy.tree.d.ts +5 -15
  38. package/lib/schemas/hierarchy.tree.js +10 -21
  39. package/lib/utils/flatDataToTree.js +21 -9
  40. package/lib/utils/getAdjescentNodes.js +10 -6
  41. package/lib/utils/getCommonTreeProps.js +28 -10
  42. package/lib/utils/getTreeHeight.js +9 -5
  43. package/lib/utils/gradientPatchAdapter.js +26 -18
  44. package/lib/utils/idUtils.js +9 -2
  45. package/lib/utils/injectNodeTypeInPatches.d.ts +12 -0
  46. package/lib/utils/injectNodeTypeInPatches.js +58 -0
  47. package/lib/utils/moveItemInArray.js +18 -5
  48. package/lib/utils/throwError.d.ts +7 -0
  49. package/lib/utils/throwError.js +12 -0
  50. package/lib/utils/treeData.js +87 -46
  51. package/lib/utils/treePatches.js +96 -47
  52. package/package.json +1 -2
  53. package/tsconfig.json +4 -4
  54. package/lib/createHierarchicalField.d.ts +0 -8
  55. package/lib/createHierarchicalField.js +0 -36
  56. package/lib/utils/useAllItems.js +0 -92
  57. package/lib/utils/useLocalTree.js +0 -27
  58. package/lib/utils/useTreeOperations.js +0 -16
  59. package/lib/utils/useTreeOperationsProvider.js +0 -52
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.INTERNAL_NODE_ARRAY_TYPE = exports.INTERNAL_NODE_VALUE_TYPE = exports.INTERNAL_NODE_TYPE = exports.DEFAULT_DOC_TYPE = exports.getSchemaTypeName = void 0;
15
+ function getSchemaTypeName(documentType, type) {
16
+ switch (type) {
17
+ case 'document':
18
+ return documentType;
19
+ case 'array':
20
+ return "".concat(documentType, ".array");
21
+ case 'node':
22
+ return "".concat(documentType, ".node");
23
+ case 'nodeValue':
24
+ return "".concat(documentType, ".nodeValue");
25
+ default:
26
+ return documentType;
27
+ }
28
+ }
29
+ exports.getSchemaTypeName = getSchemaTypeName;
30
+ /**
31
+ * Temporary value of nodes' `_type` before they are normalized and persisted as the user-defined choice.
32
+ */
33
+ exports.DEFAULT_DOC_TYPE = 'hierarchy.tree';
34
+ exports.INTERNAL_NODE_TYPE = getSchemaTypeName(exports.DEFAULT_DOC_TYPE, 'node');
35
+ exports.INTERNAL_NODE_VALUE_TYPE = getSchemaTypeName(exports.DEFAULT_DOC_TYPE, 'nodeValue');
36
+ exports.INTERNAL_NODE_ARRAY_TYPE = getSchemaTypeName(exports.DEFAULT_DOC_TYPE, 'array');
37
+ /**
38
+ * Barebones recursive utility to inject the desired nodeObjectType in patches generated in deeply nested components and utilities.
39
+ */
40
+ function injectNodeTypeInPatches(patchData, documentType) {
41
+ if (Array.isArray(patchData)) {
42
+ return patchData.map(function (child) { return injectNodeTypeInPatches(child, documentType); });
43
+ }
44
+ if (typeof patchData === 'object' && patchData !== null) {
45
+ return Object.keys(patchData).reduce(function (newObject, key) {
46
+ var _a, _b;
47
+ var value = patchData[key];
48
+ if (key === '_type' &&
49
+ typeof value === 'string' &&
50
+ [exports.INTERNAL_NODE_TYPE, exports.INTERNAL_NODE_VALUE_TYPE].includes(value)) {
51
+ return __assign(__assign({}, newObject), (_a = {}, _a[key] = getSchemaTypeName(documentType, value === exports.INTERNAL_NODE_TYPE ? 'node' : 'nodeValue'), _a));
52
+ }
53
+ return __assign(__assign({}, newObject), (_b = {}, _b[key] = injectNodeTypeInPatches(value, documentType), _b));
54
+ }, {});
55
+ }
56
+ return patchData;
57
+ }
58
+ exports.default = injectNodeTypeInPatches;
@@ -1,13 +1,26 @@
1
- export default function moveItemInArray({ array, fromIndex, toIndex }) {
1
+ "use strict";
2
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
3
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
4
+ if (ar || !(i in from)) {
5
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
6
+ ar[i] = from[i];
7
+ }
8
+ }
9
+ return to.concat(ar || Array.prototype.slice.call(from));
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ function moveItemInArray(_a) {
13
+ var array = _a.array, fromIndex = _a.fromIndex, toIndex = _a.toIndex;
2
14
  if (fromIndex === toIndex) {
3
15
  return array;
4
16
  }
5
- const newArray = [...array];
6
- const target = newArray[fromIndex];
7
- const inc = toIndex < fromIndex ? -1 : 1;
8
- for (let i = fromIndex; i !== toIndex; i += inc) {
17
+ var newArray = __spreadArray([], array, true);
18
+ var target = newArray[fromIndex];
19
+ var inc = toIndex < fromIndex ? -1 : 1;
20
+ for (var i = fromIndex; i !== toIndex; i += inc) {
9
21
  newArray[i] = newArray[i + inc];
10
22
  }
11
23
  newArray[toIndex] = target;
12
24
  return newArray;
13
25
  }
26
+ exports.default = moveItemInArray;
@@ -0,0 +1,7 @@
1
+ declare const ERROR_MESSAGES: {
2
+ invalidDocumentId: string;
3
+ invalidDocumentType: string;
4
+ invalidReferenceTo: string;
5
+ };
6
+ export default function throwError(message: keyof typeof ERROR_MESSAGES, extraContext?: string): void;
7
+ export {};
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var ERROR_MESSAGES = {
4
+ invalidDocumentId: 'Please add a documentId to your tree',
5
+ invalidDocumentType: 'Please add a valid documentType to createHierarchicalSchemas',
6
+ invalidReferenceTo: "Missing valid 'referenceTo' value"
7
+ };
8
+ function throwError(message, extraContext) {
9
+ if (extraContext === void 0) { extraContext = ''; }
10
+ throw new Error("[hierarchical input] ".concat(ERROR_MESSAGES[message], " ").concat(extraContext));
11
+ }
12
+ exports.default = throwError;
@@ -1,44 +1,76 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { randomKey } from '@sanity/util/content';
3
- import DocumentInNode from '../components/DocumentInNode';
4
- import NodeActions from '../components/NodeActions';
5
- import flatDataToTree from './flatDataToTree';
6
- export const dataToEditorTree = ({ tree, allItems, visibilityMap }) => {
7
- const itemsWithTitle = tree
8
- .filter((item) => item?.value?.reference?._ref)
9
- .map((item) => {
10
- const refId = item.value?.reference?._ref;
11
- const docPair = refId ? allItems[refId] : undefined;
12
- const draftDoc = docPair?.draft;
13
- const publishedDoc = docPair?.published;
14
- const enhancedItem = {
15
- ...item,
16
- expanded: visibilityMap[item._key] !== false,
17
- draftId: draftDoc?._id,
18
- publishedId: publishedDoc?._id,
19
- draftUpdatedAt: draftDoc?._updatedAt,
20
- publishedUpdatedAt: publishedDoc?._updatedAt
21
- };
22
- return {
23
- ...enhancedItem,
24
- title: (nodeProps) => (_jsx(DocumentInNode, { item: enhancedItem, action: _jsx(NodeActions, { nodeProps: nodeProps }, void 0) }, void 0)),
25
- children: []
26
- };
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __rest = (this && this.__rest) || function (s, e) {
14
+ var t = {};
15
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
+ t[p] = s[p];
17
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
+ t[p[i]] = s[p[i]];
21
+ }
22
+ return t;
23
+ };
24
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
25
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
26
+ if (ar || !(i in from)) {
27
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
28
+ ar[i] = from[i];
29
+ }
30
+ }
31
+ return to.concat(ar || Array.prototype.slice.call(from));
32
+ };
33
+ var __importDefault = (this && this.__importDefault) || function (mod) {
34
+ return (mod && mod.__esModule) ? mod : { "default": mod };
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.normalizeNodeForStorage = exports.getUnaddedItems = exports.flatTree = exports.dataToEditorTree = void 0;
38
+ var jsx_runtime_1 = require("react/jsx-runtime");
39
+ var content_1 = require("@sanity/util/content");
40
+ var DocumentInNode_1 = __importDefault(require("../components/DocumentInNode"));
41
+ var NodeActions_1 = __importDefault(require("../components/NodeActions"));
42
+ var flatDataToTree_1 = __importDefault(require("./flatDataToTree"));
43
+ var injectNodeTypeInPatches_1 = require("./injectNodeTypeInPatches");
44
+ var dataToEditorTree = function (_a) {
45
+ var tree = _a.tree, allItems = _a.allItems, visibilityMap = _a.visibilityMap;
46
+ var itemsWithTitle = tree
47
+ .filter(function (item) { var _a, _b; return (_b = (_a = item === null || item === void 0 ? void 0 : item.value) === null || _a === void 0 ? void 0 : _a.reference) === null || _b === void 0 ? void 0 : _b._ref; })
48
+ .map(function (item) {
49
+ var _a, _b;
50
+ var refId = (_b = (_a = item.value) === null || _a === void 0 ? void 0 : _a.reference) === null || _b === void 0 ? void 0 : _b._ref;
51
+ var docPair = refId ? allItems[refId] : undefined;
52
+ var draftDoc = docPair === null || docPair === void 0 ? void 0 : docPair.draft;
53
+ var publishedDoc = docPair === null || docPair === void 0 ? void 0 : docPair.published;
54
+ var enhancedItem = __assign(__assign({}, item), { expanded: visibilityMap[item._key] !== false, draftId: draftDoc === null || draftDoc === void 0 ? void 0 : draftDoc._id, publishedId: publishedDoc === null || publishedDoc === void 0 ? void 0 : publishedDoc._id, draftUpdatedAt: draftDoc === null || draftDoc === void 0 ? void 0 : draftDoc._updatedAt, publishedUpdatedAt: publishedDoc === null || publishedDoc === void 0 ? void 0 : publishedDoc._updatedAt });
55
+ return __assign(__assign({}, enhancedItem), { title: function (nodeProps) { return ((0, jsx_runtime_1.jsx)(DocumentInNode_1.default, { item: enhancedItem, action: (0, jsx_runtime_1.jsx)(NodeActions_1.default, { nodeProps: nodeProps }, void 0) }, void 0)); }, children: [] });
27
56
  });
28
- return flatDataToTree(itemsWithTitle);
57
+ return (0, flatDataToTree_1.default)(itemsWithTitle);
29
58
  };
30
- const documentPairToNode = (doc) => {
31
- if (!doc?.published?._id) {
59
+ exports.dataToEditorTree = dataToEditorTree;
60
+ var documentPairToNode = function (doc) {
61
+ var _a, _b, _c, _d;
62
+ if (!((_a = doc === null || doc === void 0 ? void 0 : doc.published) === null || _a === void 0 ? void 0 : _a._id)) {
32
63
  return undefined;
33
64
  }
34
65
  return {
35
- _key: randomKey(12),
36
- _type: 'hierarchy.node',
37
- draftId: doc.draft?._id,
38
- draftUpdatedAt: doc.draft?._updatedAt,
66
+ _key: (0, content_1.randomKey)(12),
67
+ _type: injectNodeTypeInPatches_1.INTERNAL_NODE_TYPE,
68
+ draftId: (_b = doc.draft) === null || _b === void 0 ? void 0 : _b._id,
69
+ draftUpdatedAt: (_c = doc.draft) === null || _c === void 0 ? void 0 : _c._updatedAt,
39
70
  publishedId: doc.published._id,
40
- publishedUpdatedAt: doc.published?._updatedAt,
71
+ publishedUpdatedAt: (_d = doc.published) === null || _d === void 0 ? void 0 : _d._updatedAt,
41
72
  value: {
73
+ _type: injectNodeTypeInPatches_1.INTERNAL_NODE_VALUE_TYPE,
42
74
  reference: {
43
75
  _ref: doc.published._id,
44
76
  _type: 'reference',
@@ -48,30 +80,39 @@ const documentPairToNode = (doc) => {
48
80
  }
49
81
  };
50
82
  };
51
- export const flatTree = (tree) => {
52
- return tree.reduce((flattened, item) => {
53
- const { children, ...node } = item;
54
- return [...flattened, node, ...(Array.isArray(children) ? flatTree(children) : [])];
83
+ var flatTree = function (tree) {
84
+ return tree.reduce(function (flattened, item) {
85
+ var children = item.children, node = __rest(item, ["children"]);
86
+ return __spreadArray(__spreadArray(__spreadArray([], flattened, true), [node], false), (Array.isArray(children) ? (0, exports.flatTree)(children) : []), true);
55
87
  }, []);
56
88
  };
57
- export const getUnaddedItems = (data) => {
89
+ exports.flatTree = flatTree;
90
+ var getUnaddedItems = function (data) {
58
91
  if (!data.tree) {
59
92
  return Object.entries(data.allItems)
60
- .map((value) => documentPairToNode(value[1]))
93
+ .map(function (value) { return documentPairToNode(value[1]); })
61
94
  .filter(Boolean);
62
95
  }
63
96
  return Object.entries(data.allItems)
64
- .filter(([publishedId]) => publishedId &&
65
- // unadded items shouldn't be in the tree
66
- !data.tree.some((treeItem) => treeItem?.value?.reference?._ref === publishedId))
67
- .map(([_publishedId, documentPair]) => documentPairToNode(documentPair))
97
+ .filter(function (_a) {
98
+ var publishedId = _a[0];
99
+ return publishedId &&
100
+ // unadded items shouldn't be in the tree
101
+ !data.tree.some(function (treeItem) { var _a, _b; return ((_b = (_a = treeItem === null || treeItem === void 0 ? void 0 : treeItem.value) === null || _a === void 0 ? void 0 : _a.reference) === null || _b === void 0 ? void 0 : _b._ref) === publishedId; });
102
+ })
103
+ .map(function (_a) {
104
+ var _publishedId = _a[0], documentPair = _a[1];
105
+ return documentPairToNode(documentPair);
106
+ })
68
107
  .filter(Boolean);
69
108
  };
70
- export function normalizeNodeForStorage(item) {
109
+ exports.getUnaddedItems = getUnaddedItems;
110
+ function normalizeNodeForStorage(item) {
71
111
  return {
72
112
  _key: item._key,
73
- _type: item._type || 'hierarchy.node',
113
+ _type: item._type || injectNodeTypeInPatches_1.INTERNAL_NODE_TYPE,
74
114
  value: item.value,
75
115
  parent: item.parent
76
116
  };
77
117
  }
118
+ exports.normalizeNodeForStorage = normalizeNodeForStorage;
@@ -1,55 +1,100 @@
1
- import * as Patch from '@sanity/form-builder/lib/patch/patches';
2
- import { randomKey } from '@sanity/util/content';
3
- import { getFlatDataFromTree } from 'react-sortable-tree';
4
- import getAdjescentNodes from './getAdjescentNodes';
5
- import moveItemInArray from './moveItemInArray';
6
- import { normalizeNodeForStorage } from './treeData';
7
- export function getAddItemPatch(item) {
8
- const normalizedNode = normalizeNodeForStorage(item);
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || function (mod) {
26
+ if (mod && mod.__esModule) return mod;
27
+ var result = {};
28
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
29
+ __setModuleDefault(result, mod);
30
+ return result;
31
+ };
32
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
33
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
34
+ if (ar || !(i in from)) {
35
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
36
+ ar[i] = from[i];
37
+ }
38
+ }
39
+ return to.concat(ar || Array.prototype.slice.call(from));
40
+ };
41
+ var __importDefault = (this && this.__importDefault) || function (mod) {
42
+ return (mod && mod.__esModule) ? mod : { "default": mod };
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.getMoveItemPatch = exports.getMovedNodePatch = exports.getRemoveItemPatch = exports.getDuplicateItemPatch = exports.getAddItemPatch = void 0;
46
+ var Patch = __importStar(require("@sanity/form-builder/lib/patch/patches"));
47
+ var content_1 = require("@sanity/util/content");
48
+ var react_sortable_tree_1 = require("react-sortable-tree");
49
+ var getAdjescentNodes_1 = __importDefault(require("./getAdjescentNodes"));
50
+ var moveItemInArray_1 = __importDefault(require("./moveItemInArray"));
51
+ var treeData_1 = require("./treeData");
52
+ function getAddItemPatch(item) {
53
+ var normalizedNode = (0, treeData_1.normalizeNodeForStorage)(item);
9
54
  return [
10
55
  // Add the node to the end of the tree
11
56
  Patch.insert([normalizedNode], 'after', [-1])
12
57
  ];
13
58
  }
14
- export function getDuplicateItemPatch(nodeProps) {
15
- const newItem = {
16
- ...nodeProps.node,
17
- _key: randomKey(12)
18
- };
19
- const normalizedNode = normalizeNodeForStorage(newItem);
59
+ exports.getAddItemPatch = getAddItemPatch;
60
+ function getDuplicateItemPatch(nodeProps) {
61
+ var newItem = __assign(__assign({}, nodeProps.node), { _key: (0, content_1.randomKey)(12) });
62
+ var normalizedNode = (0, treeData_1.normalizeNodeForStorage)(newItem);
20
63
  return [
21
64
  // Add duplicated node before the existing one
22
65
  Patch.insert([normalizedNode], 'before', [{ _key: nodeProps.node._key }])
23
66
  ];
24
67
  }
25
- export function getRemoveItemPatch({ node }) {
26
- const keyPath = { _key: node._key };
27
- const children = getChildrenPaths(node);
28
- return [
68
+ exports.getDuplicateItemPatch = getDuplicateItemPatch;
69
+ function getRemoveItemPatch(_a) {
70
+ var node = _a.node;
71
+ var keyPath = { _key: node._key };
72
+ var children = getChildrenPaths(node);
73
+ return __spreadArray([
29
74
  // 1. Unset the removed node
30
- Patch.unset([keyPath]),
31
- // 2. Unset its children
32
- ...children.map((path) => Patch.unset([{ _key: path }]))
33
- ];
75
+ Patch.unset([keyPath])
76
+ ], children.map(function (path) { return Patch.unset([{ _key: path }]); }), true);
34
77
  }
35
- export function getMovedNodePatch(data) {
36
- const { nextParentNode } = data;
37
- const keyPath = { _key: data.node._key };
78
+ exports.getRemoveItemPatch = getRemoveItemPatch;
79
+ function getMovedNodePatch(data) {
80
+ var _a, _b;
81
+ var nextParentNode = data.nextParentNode;
82
+ var keyPath = { _key: data.node._key };
38
83
  // === REMOVING NODE FROM TREE ===
39
84
  // `nextPath` will be null if the item is removed from tree
40
85
  if (!Array.isArray(data.nextPath)) {
41
86
  return getRemoveItemPatch({ node: data.node });
42
87
  }
43
- const nextFlatTree = getFlatDataFromTree({
88
+ var nextFlatTree = (0, react_sortable_tree_1.getFlatDataFromTree)({
44
89
  treeData: data.treeData,
45
- getNodeKey: (t) => t.node._key
90
+ getNodeKey: function (t) { return t.node._key; }
46
91
  });
47
- const normalizedNode = normalizeNodeForStorage(data.node);
48
- const { leadingNode, followingNode } = getAdjescentNodes({
92
+ var normalizedNode = (0, treeData_1.normalizeNodeForStorage)(data.node);
93
+ var _c = (0, getAdjescentNodes_1.default)({
49
94
  flatTree: nextFlatTree,
50
95
  node: data.node,
51
96
  treeIndex: data.nextTreeIndex
52
- });
97
+ }), leadingNode = _c.leadingNode, followingNode = _c.followingNode;
53
98
  return [
54
99
  // 1. Unset the moved node
55
100
  // (will be ignored by Content Lake on new nodes with _key not yet in tree)
@@ -57,12 +102,12 @@ export function getMovedNodePatch(data) {
57
102
  // 2. SIBLING-BASED PLACEMENT
58
103
  // If we were to place solely based on nextTreeIndex, concurrent changes from other editors could put the new node in an unexpected position.
59
104
  // Let's instead anchor it to the _key of the sibling coming before or after it.
60
- leadingNode?.node?._key
105
+ ((_a = leadingNode === null || leadingNode === void 0 ? void 0 : leadingNode.node) === null || _a === void 0 ? void 0 : _a._key)
61
106
  ? // After the sibling before it
62
107
  Patch.insert([normalizedNode], 'after', [{ _key: leadingNode.node._key }])
63
108
  : // Or before the sibling right after it, in case there's no leading sibling node
64
109
  // prettier-ignore
65
- Patch.insert([normalizedNode], 'before', [followingNode?.node?._key ? { _key: followingNode.node._key } : data.nextTreeIndex]),
110
+ Patch.insert([normalizedNode], 'before', [((_b = followingNode === null || followingNode === void 0 ? void 0 : followingNode.node) === null || _b === void 0 ? void 0 : _b._key) ? { _key: followingNode.node._key } : data.nextTreeIndex]),
66
111
  // 3. Patch the new node with its new `parent`
67
112
  nextParentNode
68
113
  ? // If it has a parent node, set that parent's _key
@@ -71,46 +116,49 @@ export function getMovedNodePatch(data) {
71
116
  Patch.unset([keyPath, 'parent'])
72
117
  ];
73
118
  }
119
+ exports.getMovedNodePatch = getMovedNodePatch;
74
120
  function getChildrenPaths(node) {
75
121
  if (!Array.isArray(node.children)) {
76
122
  return [];
77
123
  }
78
124
  return node.children
79
- .reduce((keyPaths, child) => [...keyPaths, child._key, ...getChildrenPaths(child)], [])
125
+ .reduce(function (keyPaths, child) { return __spreadArray(__spreadArray(__spreadArray([], keyPaths, true), [child._key], false), getChildrenPaths(child), true); }, [])
80
126
  .filter(Boolean);
81
127
  }
82
- export function getMoveItemPatch({ nodeProps: { node, treeIndex }, localTree, direction = 'up' }) {
83
- const keyPath = { _key: node._key };
84
- const nextTreeIndex = treeIndex + (direction === 'up' ? -1 : 1);
85
- const flatTree = getFlatDataFromTree({
128
+ function getMoveItemPatch(_a) {
129
+ var _b, _c;
130
+ var _d = _a.nodeProps, node = _d.node, treeIndex = _d.treeIndex, localTree = _a.localTree, _e = _a.direction, direction = _e === void 0 ? 'up' : _e;
131
+ var keyPath = { _key: node._key };
132
+ var nextTreeIndex = treeIndex + (direction === 'up' ? -1 : 1);
133
+ var flatTree = (0, react_sortable_tree_1.getFlatDataFromTree)({
86
134
  treeData: localTree,
87
- getNodeKey: (t) => t.node._key
135
+ getNodeKey: function (t) { return t.node._key; }
88
136
  });
89
- const nextFlatTree = moveItemInArray({
137
+ var nextFlatTree = (0, moveItemInArray_1.default)({
90
138
  array: flatTree,
91
139
  fromIndex: treeIndex,
92
140
  toIndex: nextTreeIndex
93
141
  });
94
- const { leadingNode, followingNode } = getAdjescentNodes({
142
+ var _f = (0, getAdjescentNodes_1.default)({
95
143
  flatTree: nextFlatTree,
96
- node,
144
+ node: node,
97
145
  treeIndex: nextTreeIndex
98
- });
99
- const normalizedNode = normalizeNodeForStorage(node);
146
+ }), leadingNode = _f.leadingNode, followingNode = _f.followingNode;
147
+ var normalizedNode = (0, treeData_1.normalizeNodeForStorage)(node);
100
148
  // When moving up, look at following node to figure out what is the next parent.
101
- const nodeToInheritParent = direction === 'up' ? followingNode : leadingNode;
102
- const nextParentNode = nodeToInheritParent?.parentNode;
149
+ var nodeToInheritParent = direction === 'up' ? followingNode : leadingNode;
150
+ var nextParentNode = nodeToInheritParent === null || nodeToInheritParent === void 0 ? void 0 : nodeToInheritParent.parentNode;
103
151
  return [
104
152
  // 1. Unset the moved node
105
153
  // (will be ignored by Content Lake on new nodes with _key not yet in tree)
106
154
  Patch.unset([keyPath]),
107
155
  // 2. SIBLING-BASED PLACEMENT
108
- leadingNode?.node?._key
156
+ ((_b = leadingNode === null || leadingNode === void 0 ? void 0 : leadingNode.node) === null || _b === void 0 ? void 0 : _b._key)
109
157
  ? // After the sibling before it
110
158
  Patch.insert([normalizedNode], 'after', [{ _key: leadingNode.node._key }])
111
159
  : // Or before the sibling right after it, in case there's no leading sibling node
112
160
  Patch.insert([normalizedNode], 'before', [
113
- followingNode?.node?._key ? { _key: followingNode.node._key } : nextTreeIndex
161
+ ((_c = followingNode === null || followingNode === void 0 ? void 0 : followingNode.node) === null || _c === void 0 ? void 0 : _c._key) ? { _key: followingNode.node._key } : nextTreeIndex
114
162
  ]),
115
163
  // 3. Patch the new node with its new `parent`
116
164
  nextParentNode
@@ -120,3 +168,4 @@ export function getMoveItemPatch({ nodeProps: { node, treeIndex }, localTree, di
120
168
  Patch.unset([keyPath, 'parent'])
121
169
  ];
122
170
  }
171
+ exports.getMoveItemPatch = getMoveItemPatch;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/hierarchical-document-list",
3
- "version": "0.1.0-next.3",
3
+ "version": "1.0.0",
4
4
  "author": "Sanity <hello@sanity.io>",
5
5
  "license": "MIT",
6
6
  "main": "lib/index.js",
@@ -41,7 +41,6 @@
41
41
  "styled-components": "^5.3.3",
42
42
  "typescript": "^4.5.5"
43
43
  },
44
- "type": "module",
45
44
  "dependencies": {
46
45
  "assert": "^2.0.0",
47
46
  "react-sortable-tree": "^2.8.0"
package/tsconfig.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "ESNext",
3
+ "target": "es5",
4
4
  "useDefineForClassFields": true,
5
5
  "lib": ["DOM", "DOM.Iterable", "ESNext"],
6
6
  "allowJs": false,
7
7
  "skipLibCheck": true,
8
- "esModuleInterop": false,
9
- "allowSyntheticDefaultImports": true,
8
+ "esModuleInterop": true,
9
+ "allowSyntheticDefaultImports": false,
10
10
  "strict": true,
11
11
  "forceConsistentCasingInFileNames": true,
12
- "module": "ESNext",
12
+ "module": "CommonJS",
13
13
  "moduleResolution": "Node",
14
14
  "resolveJsonModule": true,
15
15
  "isolatedModules": true,
@@ -1,8 +0,0 @@
1
- import { ArraySchemaType } from '@sanity/types';
2
- import React from 'react';
3
- import { TreeFieldSchema } from './types';
4
- export default function createHierarchicalField({ name, title, options, ...rest }: TreeFieldSchema): Omit<ArraySchemaType, 'type' | 'jsonType' | 'of'> & {
5
- type: string;
6
- inputComponent: React.FC<any>;
7
- of: any[];
8
- };
@@ -1,36 +0,0 @@
1
- import TreeInputComponent from './TreeInputComponent';
2
- export default function createHierarchicalField({ name, title, options, ...rest }) {
3
- if (!Array.isArray(options?.referenceTo)) {
4
- throw new Error(`[hierarchical input] Missing valid options.referenceTo in createHierarchicalField (field of name "${name}")`);
5
- }
6
- return {
7
- ...rest,
8
- options,
9
- name,
10
- title,
11
- type: 'array',
12
- of: [
13
- {
14
- type: 'object',
15
- fields: [
16
- { name: 'parent', type: 'string' },
17
- {
18
- name: 'value',
19
- type: 'object',
20
- fields: [
21
- { name: 'docType', type: 'string' },
22
- {
23
- name: 'reference',
24
- type: 'reference',
25
- weak: true,
26
- to: options.referenceTo.map((type) => ({ type })),
27
- options: options.referenceOptions
28
- }
29
- ]
30
- }
31
- ]
32
- }
33
- ],
34
- inputComponent: TreeInputComponent
35
- };
36
- }