@sanity/hierarchical-document-list 0.1.0 → 1.1.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 (85) hide show
  1. package/.husky/commit-msg +4 -0
  2. package/.husky/pre-commit +4 -0
  3. package/.idea/hierarchical-document-list.iml +11 -0
  4. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  5. package/.idea/misc.xml +6 -0
  6. package/.idea/modules.xml +8 -0
  7. package/.idea/prettier.xml +7 -0
  8. package/.idea/vcs.xml +6 -0
  9. package/CHANGELOG.md +15 -0
  10. package/README.md +329 -224
  11. package/commitlint.config.js +3 -0
  12. package/lib/TreeDeskStructure.d.ts +8 -7
  13. package/lib/TreeDeskStructure.js +96 -71
  14. package/lib/TreeInputComponent.d.ts +19 -19
  15. package/lib/TreeInputComponent.js +50 -21
  16. package/lib/components/DeskWarning.d.ts +6 -6
  17. package/lib/components/DeskWarning.js +46 -25
  18. package/lib/components/DocumentInNode.d.ts +11 -11
  19. package/lib/components/DocumentInNode.js +81 -58
  20. package/lib/components/DocumentPreviewStatus.d.ts +7 -7
  21. package/lib/components/DocumentPreviewStatus.js +39 -35
  22. package/lib/components/NodeActions.d.ts +10 -10
  23. package/lib/components/NodeActions.js +61 -37
  24. package/lib/components/NodeContentRenderer.d.ts +8 -8
  25. package/lib/components/NodeContentRenderer.js +105 -81
  26. package/lib/components/PlaceholderDropzone.d.ts +9 -9
  27. package/lib/components/PlaceholderDropzone.js +30 -28
  28. package/lib/components/SuppressedDnDManager.d.ts +2 -0
  29. package/lib/components/SuppressedDnDManager.js +59 -0
  30. package/lib/components/TreeEditor.d.ts +12 -12
  31. package/lib/components/TreeEditor.js +74 -54
  32. package/lib/components/TreeEditorErrorBoundary.d.ts +16 -17
  33. package/lib/components/TreeEditorErrorBoundary.js +74 -69
  34. package/lib/components/TreeNodeRenderer.d.ts +3 -3
  35. package/lib/components/TreeNodeRenderer.js +59 -35
  36. package/lib/components/TreeNodeRendererScaffold.d.ts +4 -4
  37. package/lib/components/TreeNodeRendererScaffold.js +44 -42
  38. package/lib/createDeskHierarchy.d.ts +14 -14
  39. package/lib/createDeskHierarchy.js +84 -67
  40. package/lib/createHierarchicalSchemas.d.ts +98 -0
  41. package/lib/createHierarchicalSchemas.js +138 -0
  42. package/lib/{utils → hooks}/useAllItems.d.ts +7 -7
  43. package/lib/{utils → hooks}/useAllItems.js +119 -94
  44. package/lib/{utils → hooks}/useLocalTree.d.ts +17 -17
  45. package/lib/{utils → hooks}/useLocalTree.js +59 -37
  46. package/lib/{utils → hooks}/useTreeOperations.d.ts +9 -9
  47. package/lib/hooks/useTreeOperations.js +39 -0
  48. package/lib/{utils → hooks}/useTreeOperationsProvider.d.ts +14 -14
  49. package/lib/hooks/useTreeOperationsProvider.js +85 -0
  50. package/lib/index.d.ts +3 -3
  51. package/lib/index.js +12 -3
  52. package/lib/schemas/hierarchy.tree.d.ts +13 -23
  53. package/lib/schemas/hierarchy.tree.js +19 -31
  54. package/lib/types.d.ts +128 -0
  55. package/lib/types.js +2 -0
  56. package/lib/utils/flatDataToTree.d.ts +6 -6
  57. package/lib/utils/flatDataToTree.js +26 -23
  58. package/lib/utils/getAdjescentNodes.d.ts +12 -12
  59. package/lib/utils/getAdjescentNodes.js +19 -16
  60. package/lib/utils/getCommonTreeProps.d.ts +7 -7
  61. package/lib/utils/getCommonTreeProps.js +33 -27
  62. package/lib/utils/getTreeHeight.d.ts +3 -3
  63. package/lib/utils/getTreeHeight.js +11 -7
  64. package/lib/utils/gradientPatchAdapter.d.ts +4 -4
  65. package/lib/utils/gradientPatchAdapter.js +40 -35
  66. package/lib/utils/idUtils.d.ts +2 -2
  67. package/lib/utils/idUtils.js +13 -8
  68. package/lib/utils/injectNodeTypeInPatches.d.ts +12 -0
  69. package/lib/utils/injectNodeTypeInPatches.js +59 -0
  70. package/lib/utils/moveItemInArray.d.ts +5 -5
  71. package/lib/utils/moveItemInArray.js +26 -23
  72. package/lib/utils/throwError.d.ts +7 -0
  73. package/lib/utils/throwError.js +12 -0
  74. package/lib/utils/treeData.d.ts +18 -18
  75. package/lib/utils/treeData.js +118 -106
  76. package/lib/utils/treePatches.d.ts +15 -15
  77. package/lib/utils/treePatches.js +171 -141
  78. package/lint-staged.config.js +4 -0
  79. package/package.json +65 -56
  80. package/sanity.json +12 -12
  81. package/tsconfig.json +20 -20
  82. package/lib/createHierarchicalField.d.ts +0 -8
  83. package/lib/createHierarchicalField.js +0 -51
  84. package/lib/utils/useTreeOperations.js +0 -16
  85. package/lib/utils/useTreeOperationsProvider.js +0 -60
@@ -1,67 +1,84 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
- import { jsx as _jsx } from "react/jsx-runtime";
13
- import S from '@sanity/desk-tool/structure-builder';
14
- import { AddIcon } from '@sanity/icons';
15
- import TreeDeskStructure from './TreeDeskStructure';
16
- var deskTreeValidator = function (props) {
17
- var documentId = props.documentId, referenceTo = props.referenceTo;
18
- if (typeof documentId !== 'string' && !documentId) {
19
- throw new Error('[hierarchical input] Please add a documentId to your tree');
20
- }
21
- if (!Array.isArray(referenceTo)) {
22
- throw new Error("[hierarchical input] Missing valid 'referenceTo' in createDeskHierarchy (documentId \"".concat(documentId, "\")"));
23
- }
24
- return function (deskProps) { return _jsx(TreeDeskStructure, __assign({}, deskProps, { options: props }), void 0); };
25
- };
26
- export default function createDeskHierarchy(props) {
27
- var documentId = props.documentId, referenceTo = props.referenceTo, referenceOptions = props.referenceOptions;
28
- var mainList = ((referenceTo === null || referenceTo === void 0 ? void 0 : referenceTo.length) === 1
29
- ? S.documentTypeList(referenceTo[0]).schemaType(referenceTo[0])
30
- : S.documentList().filter('_type in $types').params({ types: referenceTo }))
31
- .id(documentId)
32
- .menuItems((referenceTo || []).map(function (schemaType) {
33
- return S.menuItem()
34
- .intent({
35
- type: 'create',
36
- params: { type: schemaType, template: schemaType }
37
- })
38
- // @TODO: get the title for each schema type
39
- .title(schemaType)
40
- .icon(AddIcon);
41
- }))
42
- .canHandleIntent(function (intent, context) {
43
- if (intent === 'edit' && context.id === props.documentId) {
44
- return true;
45
- }
46
- if (intent === 'create' && referenceTo.includes(context.type)) {
47
- return true;
48
- }
49
- return false;
50
- });
51
- if (referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filter) {
52
- mainList = mainList.filter(referenceOptions.filter);
53
- }
54
- if (referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filterParams) {
55
- mainList = mainList.params(referenceOptions.filterParams);
56
- }
57
- return S.listItem()
58
- .id(documentId)
59
- .title(props.title || documentId)
60
- .icon(props.icon)
61
- .child(Object.assign(mainList.serialize(), {
62
- type: 'component',
63
- component: deskTreeValidator(props),
64
- options: props,
65
- __preserveInstance: true
66
- }, props.title ? { title: props.title } : {}));
67
- }
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 __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ var jsx_runtime_1 = require("react/jsx-runtime");
18
+ var structure_builder_1 = __importDefault(require("@sanity/desk-tool/structure-builder"));
19
+ var icons_1 = require("@sanity/icons");
20
+ var schema_1 = __importDefault(require("part:@sanity/base/schema"));
21
+ var TreeDeskStructure_1 = __importDefault(require("./TreeDeskStructure"));
22
+ var throwError_1 = __importDefault(require("./utils/throwError"));
23
+ var deskTreeValidator = function (props) {
24
+ var documentId = props.documentId, referenceTo = props.referenceTo;
25
+ if (typeof documentId !== 'string' && !documentId) {
26
+ (0, throwError_1.default)('invalidDocumentId');
27
+ }
28
+ if (!Array.isArray(referenceTo)) {
29
+ (0, throwError_1.default)('invalidReferenceTo', "(documentId \"".concat(documentId, "\")"));
30
+ }
31
+ return function (deskProps) { return (0, jsx_runtime_1.jsx)(TreeDeskStructure_1.default, __assign({}, deskProps, { options: props }), void 0); };
32
+ };
33
+ function createDeskHierarchy(props) {
34
+ var documentId = props.documentId, referenceTo = props.referenceTo, referenceOptions = props.referenceOptions;
35
+ /**
36
+ * Context: With multiple referenced document types we can’t set S.documentList().schemaType(),
37
+ * which only accepts one type. So the desk doesn’t have an expanded schemaType to access and
38
+ * try creating a new document without that, which breaks resolveEnabledActions (and probably more)
39
+ * in packages\@sanity\base\src\actions\utils\legacy_documentActionUtils.js
40
+ */
41
+ var safelyCreatableTypes = referenceTo.slice(0, 1);
42
+ var mainList = ((safelyCreatableTypes === null || safelyCreatableTypes === void 0 ? void 0 : safelyCreatableTypes.length) === 1
43
+ ? structure_builder_1.default.documentTypeList(safelyCreatableTypes[0]).schemaType(safelyCreatableTypes[0])
44
+ : structure_builder_1.default.documentList().filter('_type in $types').params({ types: safelyCreatableTypes }))
45
+ .id(documentId)
46
+ .menuItems((safelyCreatableTypes || []).map(function (schemaType) {
47
+ var _a, _b;
48
+ return structure_builder_1.default.menuItem()
49
+ .intent({
50
+ type: 'create',
51
+ params: { type: schemaType }
52
+ })
53
+ .title("Create ".concat((_a = schema_1.default.get(schemaType)) === null || _a === void 0 ? void 0 : _a.title))
54
+ .icon(((_b = schema_1.default.get(schemaType)) === null || _b === void 0 ? void 0 : _b.icon) || icons_1.AddIcon);
55
+ }))
56
+ .canHandleIntent(function (intent, context) {
57
+ // Can edit itself
58
+ if (intent === 'edit' && context.id === props.documentId) {
59
+ return true;
60
+ }
61
+ // Can create & edit referenced document types
62
+ if (safelyCreatableTypes.includes(context.type)) {
63
+ return true;
64
+ }
65
+ return false;
66
+ });
67
+ if (referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filter) {
68
+ mainList = mainList.filter(referenceOptions.filter);
69
+ }
70
+ if (referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filterParams) {
71
+ mainList = mainList.params(referenceOptions.filterParams);
72
+ }
73
+ return structure_builder_1.default.listItem()
74
+ .id(documentId)
75
+ .title(props.title || documentId)
76
+ .icon(props.icon)
77
+ .child(Object.assign(mainList.serialize(), {
78
+ type: 'component',
79
+ component: deskTreeValidator(props),
80
+ options: props,
81
+ __preserveInstance: true
82
+ }, props.title ? { title: props.title } : {}));
83
+ }
84
+ exports.default = createDeskHierarchy;
@@ -0,0 +1,98 @@
1
+ import { ArraySchemaType } from '@sanity/types';
2
+ import * as React from 'react';
3
+ import { TreeDeskStructureProps, TreeFieldSchema } from './types';
4
+ declare type SchemaOptions = Omit<TreeDeskStructureProps, 'documentId' | 'maxDepth'>;
5
+ export declare function createHierarchicalField({ name, title, options, ...rest }: TreeFieldSchema): Omit<ArraySchemaType, 'type' | 'jsonType' | 'of'> & {
6
+ type: string;
7
+ inputComponent: React.FC<any>;
8
+ of?: any[];
9
+ };
10
+ export default function createHierarchicalSchemas(options: SchemaOptions): ({
11
+ name: string;
12
+ title: string;
13
+ type: string;
14
+ fields: ({
15
+ name: string;
16
+ type: string;
17
+ } | {
18
+ name: string;
19
+ type: string;
20
+ title: string;
21
+ fields: ({
22
+ name: string;
23
+ type: string;
24
+ weak?: undefined;
25
+ to?: undefined;
26
+ options?: undefined;
27
+ } | {
28
+ name: string;
29
+ type: string;
30
+ weak: boolean;
31
+ to: {
32
+ type: string;
33
+ }[];
34
+ options: {
35
+ filter?: string | undefined;
36
+ filterParams?: Record<string, unknown> | undefined;
37
+ } | undefined;
38
+ })[];
39
+ })[];
40
+ } | {
41
+ name: string;
42
+ title: string;
43
+ type: string;
44
+ of: ({
45
+ name: string;
46
+ title: string;
47
+ type: string;
48
+ fields: ({
49
+ name: string;
50
+ type: string;
51
+ } | {
52
+ name: string;
53
+ type: string;
54
+ title: string;
55
+ fields: ({
56
+ name: string;
57
+ type: string;
58
+ weak?: undefined;
59
+ to?: undefined;
60
+ options?: undefined;
61
+ } | {
62
+ name: string;
63
+ type: string;
64
+ weak: boolean;
65
+ to: {
66
+ type: string;
67
+ }[];
68
+ options: {
69
+ filter?: string | undefined;
70
+ filterParams?: Record<string, unknown> | undefined;
71
+ } | undefined;
72
+ })[];
73
+ })[];
74
+ } | {
75
+ type: string;
76
+ })[];
77
+ } | {
78
+ name: string | undefined;
79
+ title: string;
80
+ type: string;
81
+ liveEdit: boolean;
82
+ fields: (Omit<ArraySchemaType<unknown>, "type" | "of" | "jsonType"> & {
83
+ type: string;
84
+ inputComponent: React.FC<any>;
85
+ of?: any[] | undefined;
86
+ })[];
87
+ preview: {
88
+ select: {
89
+ id: string;
90
+ tree: string;
91
+ };
92
+ prepare({ id, tree }: {
93
+ id: string;
94
+ tree: unknown[];
95
+ }): Record<string, string>;
96
+ };
97
+ })[];
98
+ export {};
@@ -0,0 +1,138 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
25
+ return (mod && mod.__esModule) ? mod : { "default": mod };
26
+ };
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.createHierarchicalField = void 0;
29
+ var TreeDeskStructure_1 = require("./TreeDeskStructure");
30
+ var TreeInputComponent_1 = __importDefault(require("./TreeInputComponent"));
31
+ var injectNodeTypeInPatches_1 = require("./utils/injectNodeTypeInPatches");
32
+ var throwError_1 = __importDefault(require("./utils/throwError"));
33
+ function createHierarchicalNodeValueType(_a) {
34
+ var referenceTo = _a.referenceTo, referenceOptions = _a.referenceOptions, documentType = _a.documentType;
35
+ return {
36
+ // when used inside the field, name & type are overwritten by createHierarchicalNodeType
37
+ name: documentType ? (0, injectNodeTypeInPatches_1.getSchemaTypeName)(documentType, 'nodeValue') : injectNodeTypeInPatches_1.INTERNAL_NODE_VALUE_TYPE,
38
+ type: 'object',
39
+ title: "Hierarchical node value (".concat(documentType, ")"),
40
+ fields: [
41
+ { name: 'docType', type: 'string' },
42
+ {
43
+ name: 'reference',
44
+ type: 'reference',
45
+ weak: true,
46
+ to: referenceTo.map(function (type) { return ({ type: type }); }),
47
+ options: referenceOptions
48
+ }
49
+ ]
50
+ };
51
+ }
52
+ function createHierarchicalNodeType(options) {
53
+ return {
54
+ // name & type are overwritten by createHierarchicalField
55
+ name: options.documentType
56
+ ? (0, injectNodeTypeInPatches_1.getSchemaTypeName)(options.documentType, 'node')
57
+ : injectNodeTypeInPatches_1.INTERNAL_NODE_TYPE,
58
+ title: "Hierarchical node (".concat(options.documentType, ")"),
59
+ type: 'object',
60
+ fields: [
61
+ { name: 'parent', type: 'string' },
62
+ options.documentType
63
+ ? { name: 'value', type: (0, injectNodeTypeInPatches_1.getSchemaTypeName)(options.documentType, 'nodeValue') }
64
+ : // If no documentType is defined, use an anonymized inline object to avoid
65
+ __assign(__assign({}, createHierarchicalNodeValueType(options)), { name: 'value', type: 'object' })
66
+ ]
67
+ };
68
+ }
69
+ function createHierarchicalArrayType(options) {
70
+ return {
71
+ // name & type are overwritten by createHierarchicalField
72
+ name: options.documentType
73
+ ? (0, injectNodeTypeInPatches_1.getSchemaTypeName)(options.documentType, 'array')
74
+ : injectNodeTypeInPatches_1.INTERNAL_NODE_ARRAY_TYPE,
75
+ title: "Hierarchical array of nodes (".concat(options.documentType, ")"),
76
+ type: 'array',
77
+ of: [
78
+ options.documentType
79
+ ? { type: (0, injectNodeTypeInPatches_1.getSchemaTypeName)(options.documentType, 'node') }
80
+ : createHierarchicalNodeType(options)
81
+ ]
82
+ };
83
+ }
84
+ function createHierarchicalField(_a) {
85
+ var name = _a.name, title = _a.title, options = _a.options, rest = __rest(_a, ["name", "title", "options"]);
86
+ if (!Array.isArray(options === null || options === void 0 ? void 0 : options.referenceTo)) {
87
+ (0, throwError_1.default)('invalidReferenceTo', "(field of name \"".concat(name, "\")"));
88
+ }
89
+ return __assign(__assign(__assign({}, rest), { name: name, title: title, inputComponent: TreeInputComponent_1.default, options: options }), (options.documentType
90
+ ? { type: (0, injectNodeTypeInPatches_1.getSchemaTypeName)(options.documentType, 'array') }
91
+ : __assign(__assign({}, createHierarchicalArrayType(options)), { name: name })));
92
+ }
93
+ exports.createHierarchicalField = createHierarchicalField;
94
+ function createHierarchicalDocType(options) {
95
+ return {
96
+ name: options.documentType,
97
+ title: 'Hierarchical tree',
98
+ type: 'document',
99
+ // The plugin needs to define a `schemaType` with liveEdit enabled so that
100
+ // `useDocumentOperation` in TreeDeskStructure.tsx doesn't create drafts at every patch.
101
+ liveEdit: true,
102
+ fields: [
103
+ createHierarchicalField({
104
+ name: options.fieldKeyInDocument || TreeDeskStructure_1.DEFAULT_FIELD_KEY,
105
+ title: 'Hierarchical Tree',
106
+ options: options
107
+ })
108
+ ],
109
+ preview: {
110
+ select: {
111
+ id: '_id',
112
+ tree: 'tree'
113
+ },
114
+ prepare: function (_a) {
115
+ var id = _a.id, tree = _a.tree;
116
+ return {
117
+ title: "Hierarchical documents (ID: ".concat(id, ")"),
118
+ subtitle: "".concat((tree === null || tree === void 0 ? void 0 : tree.length) || 0, " document(s) in its list.")
119
+ };
120
+ }
121
+ }
122
+ };
123
+ }
124
+ function createHierarchicalSchemas(options) {
125
+ if (!Array.isArray(options.referenceTo) || options.referenceTo.length <= 0) {
126
+ (0, throwError_1.default)('invalidReferenceTo');
127
+ }
128
+ if (!options.documentType) {
129
+ (0, throwError_1.default)('invalidDocumentType');
130
+ }
131
+ return [
132
+ createHierarchicalDocType(options),
133
+ createHierarchicalArrayType(options),
134
+ createHierarchicalNodeType(options),
135
+ createHierarchicalNodeValueType(options)
136
+ ];
137
+ }
138
+ exports.default = createHierarchicalSchemas;
@@ -1,7 +1,7 @@
1
- import { AllItems, TreeInputOptions } from '../types';
2
- declare type Status = 'loading' | 'success' | 'error';
3
- export default function useAllItems(options: TreeInputOptions): {
4
- status: Status;
5
- allItems: AllItems;
6
- };
7
- export {};
1
+ import { AllItems, TreeInputOptions } from '../types';
2
+ declare type Status = 'loading' | 'success' | 'error';
3
+ export default function useAllItems(options: TreeInputOptions): {
4
+ status: Status;
5
+ allItems: AllItems;
6
+ };
7
+ export {};
@@ -1,94 +1,119 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
- import sanityClient from 'part:@sanity/base/client';
13
- import React from 'react';
14
- import { isDraft, unprefixId } from './idUtils';
15
- var client = sanityClient.withConfig({
16
- apiVersion: '2021-09-01'
17
- });
18
- function getDeskFilter(_a) {
19
- var referenceTo = _a.referenceTo, referenceOptions = _a.referenceOptions;
20
- var filterParts = ['_type in $docTypes'];
21
- if (referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filter) {
22
- filterParts.push(referenceOptions.filter);
23
- }
24
- return {
25
- filter: filterParts.join(' && '),
26
- params: __assign(__assign({}, ((referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filterParams) || {})), { docTypes: referenceTo.map(function (schemaType) { return schemaType; }) })
27
- };
28
- }
29
- function updateItemInState(state, item) {
30
- var _a;
31
- var newState = __assign({}, state);
32
- var publishedId = unprefixId(item._id);
33
- newState[publishedId] = __assign(__assign({}, (newState[publishedId] || {})), (_a = {}, _a[isDraft(item._id) ? 'draft' : 'published'] = item, _a));
34
- return newState;
35
- }
36
- function allItemsReducer(state, action) {
37
- var _a;
38
- var _b, _c, _d;
39
- if (action.type === 'addOrEditItem' && ((_b = action.item) === null || _b === void 0 ? void 0 : _b._id)) {
40
- return updateItemInState(state, action.item);
41
- }
42
- if (action.type === 'removeItem') {
43
- var publishedId = unprefixId(action.itemId);
44
- return __assign(__assign({}, state), (_a = {}, _a[publishedId] = isDraft(action.itemId)
45
- ? // If a draft, keep only published
46
- {
47
- published: (_c = state[publishedId]) === null || _c === void 0 ? void 0 : _c.published
48
- }
49
- : {
50
- draft: (_d = state[publishedId]) === null || _d === void 0 ? void 0 : _d.draft
51
- }, _a));
52
- }
53
- if (action.type === 'setInitialData') {
54
- return action.items.reduce(updateItemInState, {});
55
- }
56
- return state;
57
- }
58
- export default function useAllItems(options) {
59
- var _a = React.useState('loading'), status = _a[0], setStatus = _a[1];
60
- var _b = React.useReducer(allItemsReducer, {}), allItems = _b[0], dispatch = _b[1];
61
- function handleListener(event) {
62
- if (event.type !== 'mutation') {
63
- return;
64
- }
65
- if (event.result) {
66
- dispatch({ type: 'addOrEditItem', item: event.result });
67
- }
68
- else {
69
- dispatch({ type: 'removeItem', itemId: event.documentId });
70
- }
71
- }
72
- function handleFirstLoad(items) {
73
- dispatch({ type: 'setInitialData', items: items });
74
- setStatus('success');
75
- }
76
- React.useEffect(function () {
77
- var _a = getDeskFilter(options), filter = _a.filter, params = _a.params;
78
- var query = "*[".concat(filter, "] {\n _id,\n _type,\n _updatedAt,\n }");
79
- client
80
- .fetch(query, params)
81
- .then(handleFirstLoad)
82
- .catch(function () {
83
- setStatus('error');
84
- });
85
- var listener = client.listen(query, params).subscribe(handleListener);
86
- return function () {
87
- listener.unsubscribe();
88
- };
89
- }, []);
90
- return {
91
- status: status,
92
- allItems: allItems
93
- };
94
- }
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 __importDefault = (this && this.__importDefault) || function (mod) {
33
+ return (mod && mod.__esModule) ? mod : { "default": mod };
34
+ };
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ var client_1 = __importDefault(require("part:@sanity/base/client"));
37
+ var React = __importStar(require("react"));
38
+ var idUtils_1 = require("../utils/idUtils");
39
+ var client = client_1.default.withConfig({
40
+ apiVersion: '2021-09-01'
41
+ });
42
+ function getDeskFilter(_a) {
43
+ var referenceTo = _a.referenceTo, referenceOptions = _a.referenceOptions;
44
+ var filterParts = ['_type in $docTypes'];
45
+ if (referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filter) {
46
+ filterParts.push(referenceOptions.filter);
47
+ }
48
+ return {
49
+ filter: filterParts.join(' && '),
50
+ params: __assign(__assign({}, ((referenceOptions === null || referenceOptions === void 0 ? void 0 : referenceOptions.filterParams) || {})), { docTypes: referenceTo.map(function (schemaType) { return schemaType; }) })
51
+ };
52
+ }
53
+ function updateItemInState(state, item) {
54
+ var _a;
55
+ var newState = __assign({}, state);
56
+ var publishedId = (0, idUtils_1.unprefixId)(item._id);
57
+ newState[publishedId] = __assign(__assign({}, (newState[publishedId] || {})), (_a = {}, _a[(0, idUtils_1.isDraft)(item._id) ? 'draft' : 'published'] = item, _a));
58
+ return newState;
59
+ }
60
+ function allItemsReducer(state, action) {
61
+ var _a;
62
+ var _b, _c, _d;
63
+ if (action.type === 'addOrEditItem' && ((_b = action.item) === null || _b === void 0 ? void 0 : _b._id)) {
64
+ return updateItemInState(state, action.item);
65
+ }
66
+ if (action.type === 'removeItem') {
67
+ var publishedId = (0, idUtils_1.unprefixId)(action.itemId);
68
+ return __assign(__assign({}, state), (_a = {}, _a[publishedId] = (0, idUtils_1.isDraft)(action.itemId)
69
+ ? // If a draft, keep only published
70
+ {
71
+ published: (_c = state[publishedId]) === null || _c === void 0 ? void 0 : _c.published
72
+ }
73
+ : {
74
+ draft: (_d = state[publishedId]) === null || _d === void 0 ? void 0 : _d.draft
75
+ }, _a));
76
+ }
77
+ if (action.type === 'setInitialData') {
78
+ return action.items.reduce(updateItemInState, {});
79
+ }
80
+ return state;
81
+ }
82
+ function useAllItems(options) {
83
+ var _a = React.useState('loading'), status = _a[0], setStatus = _a[1];
84
+ var _b = React.useReducer(allItemsReducer, {}), allItems = _b[0], dispatch = _b[1];
85
+ function handleListener(event) {
86
+ if (event.type !== 'mutation') {
87
+ return;
88
+ }
89
+ if (event.result) {
90
+ dispatch({ type: 'addOrEditItem', item: event.result });
91
+ }
92
+ else {
93
+ dispatch({ type: 'removeItem', itemId: event.documentId });
94
+ }
95
+ }
96
+ function handleFirstLoad(items) {
97
+ dispatch({ type: 'setInitialData', items: items });
98
+ setStatus('success');
99
+ }
100
+ React.useEffect(function () {
101
+ var _a = getDeskFilter(options), filter = _a.filter, params = _a.params;
102
+ var query = "*[".concat(filter, "] {\n _id,\n _type,\n _updatedAt,\n }");
103
+ client
104
+ .fetch(query, params)
105
+ .then(handleFirstLoad)
106
+ .catch(function () {
107
+ setStatus('error');
108
+ });
109
+ var listener = client.listen(query, params).subscribe(handleListener);
110
+ return function () {
111
+ listener.unsubscribe();
112
+ };
113
+ }, []);
114
+ return {
115
+ status: status,
116
+ allItems: allItems
117
+ };
118
+ }
119
+ exports.default = useAllItems;