@sanity/hierarchical-document-list 2.1.3 → 3.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 (44) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +30 -28
  3. package/dist/index.d.ts +170 -195
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +835 -6031
  6. package/dist/index.js.map +1 -1
  7. package/package.json +38 -77
  8. package/dist/index.d.mts +0 -240
  9. package/dist/index.mjs +0 -6433
  10. package/dist/index.mjs.map +0 -1
  11. package/sanity.json +0 -8
  12. package/src/TreeDeskStructure.tsx +0 -80
  13. package/src/TreeInputComponent.tsx +0 -41
  14. package/src/components/DeskWarning.tsx +0 -40
  15. package/src/components/DocumentInNode.tsx +0 -133
  16. package/src/components/DocumentPreviewStatus.tsx +0 -70
  17. package/src/components/NodeActions.tsx +0 -85
  18. package/src/components/NodeContentRenderer.tsx +0 -141
  19. package/src/components/PlaceholderDropzone.tsx +0 -45
  20. package/src/components/TreeEditor.tsx +0 -184
  21. package/src/components/TreeEditorErrorBoundary.tsx +0 -14
  22. package/src/components/TreeNodeRenderer.tsx +0 -37
  23. package/src/components/TreeNodeRendererScaffold.tsx +0 -193
  24. package/src/createDeskHierarchy.tsx +0 -110
  25. package/src/createHierarchicalSchemas.tsx +0 -151
  26. package/src/hooks/useAllItems.ts +0 -119
  27. package/src/hooks/useLocalTree.ts +0 -40
  28. package/src/hooks/useTreeOperations.ts +0 -25
  29. package/src/hooks/useTreeOperationsProvider.ts +0 -86
  30. package/src/index.ts +0 -25
  31. package/src/schemas/hierarchy.tree.ts +0 -19
  32. package/src/types.ts +0 -148
  33. package/src/utils/flatDataToTree.ts +0 -20
  34. package/src/utils/getAdjescentNodes.ts +0 -30
  35. package/src/utils/getCommonTreeProps.tsx +0 -28
  36. package/src/utils/getTreeHeight.ts +0 -8
  37. package/src/utils/gradientPatchAdapter.ts +0 -43
  38. package/src/utils/idUtils.ts +0 -7
  39. package/src/utils/injectNodeTypeInPatches.ts +0 -60
  40. package/src/utils/moveItemInArray.ts +0 -26
  41. package/src/utils/throwError.ts +0 -9
  42. package/src/utils/treeData.tsx +0 -119
  43. package/src/utils/treePatches.ts +0 -171
  44. package/v2-incompatible.js +0 -11
@@ -1,119 +0,0 @@
1
- import * as React from 'react'
2
- import {SanityDocument, useClient} from 'sanity'
3
- import {AllItems, TreeInputOptions} from '../types'
4
- import {isDraft, unprefixId} from '../utils/idUtils'
5
-
6
- function getDeskFilter({referenceTo, referenceOptions}: TreeInputOptions): {
7
- filter: string
8
- params: Record<string, unknown>
9
- } {
10
- const filterParts: string[] = ['_type in $docTypes']
11
-
12
- if (referenceOptions?.filter) {
13
- filterParts.push(referenceOptions.filter)
14
- }
15
-
16
- return {
17
- filter: filterParts.join(' && '),
18
- params: {
19
- ...(referenceOptions?.filterParams || {}),
20
- docTypes: referenceTo.map((schemaType) => schemaType)
21
- }
22
- }
23
- }
24
-
25
- type Status = 'loading' | 'success' | 'error'
26
-
27
- type ACTIONTYPE =
28
- | {type: 'addOrEditItem'; item: SanityDocument}
29
- | {type: 'removeItem'; itemId: string}
30
- | {type: 'setInitialData'; items: SanityDocument[]}
31
-
32
- function updateItemInState(state: AllItems, item: SanityDocument): AllItems {
33
- const newState = {...state}
34
- const publishedId = unprefixId(item._id)
35
- newState[publishedId] = {
36
- ...(newState[publishedId] || {}),
37
- [isDraft(item._id) ? 'draft' : 'published']: item
38
- }
39
- return newState
40
- }
41
-
42
- function allItemsReducer(state: AllItems, action: ACTIONTYPE): AllItems {
43
- if (action.type === 'addOrEditItem' && action.item?._id) {
44
- return updateItemInState(state, action.item)
45
- }
46
-
47
- if (action.type === 'removeItem') {
48
- const publishedId = unprefixId(action.itemId)
49
- return {
50
- ...state,
51
- [publishedId]: isDraft(action.itemId)
52
- ? // If a draft, keep only published
53
- {
54
- published: state[publishedId]?.published
55
- }
56
- : {
57
- draft: state[publishedId]?.draft
58
- }
59
- }
60
- }
61
-
62
- if (action.type === 'setInitialData') {
63
- return action.items.reduce(updateItemInState, {} as AllItems)
64
- }
65
- return state
66
- }
67
-
68
- export default function useAllItems(options: TreeInputOptions): {
69
- status: Status
70
- allItems: AllItems
71
- } {
72
- const client = useClient({
73
- apiVersion: '2021-09-01'
74
- })
75
- const [status, setStatus] = React.useState<Status>('loading')
76
- const [allItems, dispatch] = React.useReducer(allItemsReducer, {})
77
-
78
- function handleListener(event: any) {
79
- if (event.type !== 'mutation') {
80
- return
81
- }
82
-
83
- if (event.result) {
84
- dispatch({type: 'addOrEditItem', item: event.result})
85
- } else {
86
- dispatch({type: 'removeItem', itemId: event.documentId})
87
- }
88
- }
89
-
90
- function handleFirstLoad(items: SanityDocument[]) {
91
- dispatch({type: 'setInitialData', items})
92
- setStatus('success')
93
- }
94
-
95
- React.useEffect(() => {
96
- const {filter, params} = getDeskFilter(options)
97
- const query = `*[${filter}] {
98
- _id,
99
- _type,
100
- _updatedAt,
101
- }`
102
- client
103
- .fetch<SanityDocument[]>(query, params)
104
- .then(handleFirstLoad)
105
- .catch(() => {
106
- setStatus('error')
107
- })
108
-
109
- const listener = client.listen(query, params).subscribe(handleListener)
110
- return () => {
111
- listener.unsubscribe()
112
- }
113
- }, [])
114
-
115
- return {
116
- status,
117
- allItems
118
- }
119
- }
@@ -1,40 +0,0 @@
1
- import * as React from 'react'
2
- import {AllItems, LocalTreeItem, StoredTreeItem, VisibilityMap} from '../types'
3
- import {dataToEditorTree} from '../utils/treeData'
4
-
5
- /**
6
- * Enhances tree data with information on:
7
- * - `expanded` - native property of react-sortable-tree to determine collapsing & expanding of a node's children
8
- * - `draftId` & `publishedId` - refer to LocalTreeItem's type annotations
9
- *
10
- * Doesn't modify the main tree or has side-effects on data.
11
- * Has the added benefit of being local to the user, so external changes won't affect local visibility.
12
- */
13
- export default function useLocalTree({
14
- tree,
15
- allItems,
16
- }: {
17
- tree: StoredTreeItem[]
18
- allItems: AllItems
19
- }): {
20
- handleVisibilityToggle: (data: any) => void
21
- localTree: LocalTreeItem[]
22
- } {
23
- const [visibilityMap, setVisibilityMap] = React.useState<VisibilityMap>({})
24
-
25
- function handleVisibilityToggle(data: any) {
26
- setVisibilityMap({
27
- ...visibilityMap,
28
- [data.node._key]: data.expanded,
29
- })
30
- }
31
-
32
- return {
33
- localTree: dataToEditorTree({
34
- tree,
35
- allItems,
36
- visibilityMap,
37
- }),
38
- handleVisibilityToggle,
39
- }
40
- }
@@ -1,25 +0,0 @@
1
- import * as React from 'react'
2
- import useAllItems from './useAllItems'
3
- import useTreeOperationsProvider from './useTreeOperationsProvider'
4
-
5
- type ContextValue = ReturnType<typeof useTreeOperationsProvider> & {
6
- allItemsStatus: ReturnType<typeof useAllItems>['status']
7
- }
8
-
9
- function placeholder() {
10
- // no-op
11
- }
12
-
13
- export const TreeOperationsContext = React.createContext<ContextValue>({
14
- addItem: placeholder,
15
- duplicateItem: placeholder,
16
- removeItem: placeholder,
17
- handleMovedNode: placeholder,
18
- moveItemDown: placeholder,
19
- moveItemUp: placeholder,
20
- allItemsStatus: 'loading',
21
- })
22
-
23
- export default function useTreeOperations(): ContextValue {
24
- return React.useContext(TreeOperationsContext)
25
- }
@@ -1,86 +0,0 @@
1
- import {PatchEvent, PathSegment, prefixPath, setIfMissing} from 'sanity'
2
- import {LocalTreeItem, NodeProps} from '../types'
3
- import {
4
- HandleMovedNode,
5
- HandleMovedNodeData,
6
- getAddItemPatch,
7
- getDuplicateItemPatch,
8
- getMoveItemPatch,
9
- getMovedNodePatch,
10
- getRemoveItemPatch
11
- } from '../utils/treePatches'
12
-
13
- export default function useTreeOperationsProvider(props: {
14
- patchPrefix?: PathSegment
15
- onChange: (patch: PatchEvent) => void
16
- localTree: LocalTreeItem[]
17
- }): {
18
- handleMovedNode: HandleMovedNode
19
- addItem: (item: LocalTreeItem) => void
20
- duplicateItem: (nodeProps: NodeProps) => void
21
- removeItem: (nodeProps: NodeProps) => void
22
- moveItemUp: (nodeProps: NodeProps) => void
23
- moveItemDown: (nodeProps: NodeProps) => void
24
- } {
25
- const {localTree} = props
26
-
27
- function runPatches(patches: any) {
28
- const finalPatches = [
29
- // Ensure tree array exists before any operation
30
- setIfMissing([]),
31
- ...(patches || [])
32
- ]
33
- let patchEvent = PatchEvent.from(finalPatches)
34
- if (props.patchPrefix) {
35
- patchEvent = PatchEvent.from(
36
- finalPatches.map((patch) => prefixPath(patch, props.patchPrefix as PathSegment))
37
- )
38
- }
39
- props.onChange(patchEvent)
40
- }
41
-
42
- function handleMovedNode(data: HandleMovedNodeData & {node: LocalTreeItem}) {
43
- runPatches(getMovedNodePatch(data))
44
- }
45
-
46
- function addItem(item: LocalTreeItem) {
47
- runPatches(getAddItemPatch(item))
48
- }
49
-
50
- function duplicateItem(nodeProps: NodeProps & {node: LocalTreeItem}) {
51
- runPatches(getDuplicateItemPatch(nodeProps))
52
- }
53
-
54
- function removeItem(nodeProps: NodeProps) {
55
- runPatches(getRemoveItemPatch(nodeProps))
56
- }
57
-
58
- function moveItemUp(nodeProps: NodeProps) {
59
- runPatches(
60
- getMoveItemPatch({
61
- nodeProps,
62
- localTree,
63
- direction: 'up'
64
- })
65
- )
66
- }
67
-
68
- function moveItemDown(nodeProps: NodeProps) {
69
- runPatches(
70
- getMoveItemPatch({
71
- nodeProps,
72
- localTree,
73
- direction: 'down'
74
- })
75
- )
76
- }
77
-
78
- return {
79
- handleMovedNode,
80
- addItem,
81
- removeItem,
82
- moveItemUp,
83
- moveItemDown,
84
- duplicateItem
85
- }
86
- }
package/src/index.ts DELETED
@@ -1,25 +0,0 @@
1
- import {definePlugin} from 'sanity'
2
- import {default as createDeskHierarchy, type TreeProps} from './createDeskHierarchy'
3
- import {default as createHierarchicalSchemas} from './createHierarchicalSchemas'
4
- import {default as hierarchyTree} from './schemas/hierarchy.tree'
5
- import {default as flatDataToTree} from './utils/flatDataToTree'
6
-
7
- export {createDeskHierarchy, createHierarchicalSchemas, flatDataToTree, hierarchyTree, TreeProps}
8
-
9
- /**
10
- * Usage in `sanity.config.ts` (or .js)
11
- *
12
- * ```ts
13
- * import {defineConfig} from 'sanity'
14
- * import {hierarchicalDocumentList} from '@sanity/hierarchical-document-list'
15
- *
16
- * export default defineConfig({
17
- * // ...
18
- * plugins: [hierarchicalDocumentList()],
19
- * })
20
- * ```
21
- */
22
-
23
- export const hierarchicalDocumentList = definePlugin({
24
- name: 'sanity-plugin-hierarchical-document-list'
25
- })
@@ -1,19 +0,0 @@
1
- import {defineType} from 'sanity'
2
-
3
- export default defineType({
4
- name: 'hierarchy.tree',
5
- title: 'Hierarchical tree',
6
- type: 'document',
7
- // The plugin needs to define a `schemaType` with liveEdit enabled so that
8
- // `useDocumentOperation` in TreeDeskStructure.tsx doesn't create drafts at every patch.
9
- liveEdit: true,
10
- // Let's avoid defining the actual hierarchical field, else GraphQL users won't be able to deploy schemas
11
- fields: [
12
- {
13
- name: 'unusedField',
14
- title: 'Unused field',
15
- type: 'string',
16
- hidden: true,
17
- },
18
- ],
19
- })
package/src/types.ts DELETED
@@ -1,148 +0,0 @@
1
- import {TreeItem} from '@nosferatu500/react-sortable-tree'
2
- import {ArraySchemaType, ObjectSchemaType, SanityDocument} from 'sanity'
3
- import {INTERNAL_NODE_TYPE, INTERNAL_NODE_VALUE_TYPE} from './utils/injectNodeTypeInPatches'
4
-
5
- interface SanityReference {
6
- _type: 'reference'
7
- _ref: string
8
- _weak?: boolean
9
- }
10
-
11
- /**
12
- * Objects saved to tree documents in Sanity's Content Lake
13
- */
14
- export interface StoredTreeItem {
15
- _key: string
16
- _type: typeof INTERNAL_NODE_TYPE | string
17
- value?: {
18
- _type: typeof INTERNAL_NODE_VALUE_TYPE | string
19
- reference?: SanityReference
20
- docType?: string
21
- }
22
- /**
23
- * _key of parent node
24
- */
25
- parent?: string | null
26
- }
27
-
28
- /**
29
- * Tree items enhanced locally in the client with info from `allItems` and `visibilityMap`.
30
- * `allItems` stop here and never become LocalTreeItems as they aren't added to react-sortable-tree.
31
- *
32
- * See `useLocalTree.ts` and `dataToEditorTree()`.
33
- */
34
- export interface EnhancedTreeItem extends StoredTreeItem {
35
- expanded?: boolean | undefined
36
- /**
37
- * Used by DocumentInNode to render the preview for drafts if they exist.
38
- * Also informs document status icons.
39
- */
40
- draftId?: string
41
- draftUpdatedAt?: string
42
- /**
43
- * If not present, DocumentInNode will show up an error for invalid document.
44
- * - undefined `publishedId` could mean the document is either deleted, or it doesn't match GROQ filters anymore
45
- */
46
- publishedId?: string
47
- publishedUpdatedAt?: string
48
- }
49
-
50
- /**
51
- * Tree items as found in the sortable tree itself.
52
- */
53
- export type LocalTreeItem = EnhancedTreeItem & Pick<TreeItem, 'title' | 'children'>
54
-
55
- export interface TreeInputOptions {
56
- /**
57
- * What document types this hierarchy can refer to.
58
- * Similar to the `to` property of the [reference field](https://www.sanity.io/docs/reference-type).
59
- */
60
- referenceTo: string[]
61
-
62
- /**
63
- * Used to provide fine-grained filtering for documents.
64
- */
65
- referenceOptions?: {
66
- /**
67
- * Static filter to apply to tree document queries.
68
- */
69
- filter?: string
70
- /**
71
- * Parameters / variables to pass to the GROQ query ran to fetch documents.
72
- */
73
- filterParams?: Record<string, unknown>
74
- }
75
-
76
- /**
77
- * How deep should editors be allowed to nest items.
78
- */
79
- maxDepth?: number
80
-
81
- /**
82
- * Schema type for your hierarchical documents.
83
- * Refer to documentation on how to provide these schemas in your studio.
84
- *
85
- * Defautlt: 'hierarchy.tree' - this schema is bundled with the plugin
86
- */
87
- documentType?: string
88
- }
89
-
90
- export interface TreeFieldSchema
91
- extends Omit<ArraySchemaType, 'of' | 'type' | 'inputComponent' | 'jsonType'> {
92
- options: ArraySchemaType['options'] & TreeInputOptions
93
- }
94
-
95
- export interface TreeNodeObjectSchema
96
- extends Omit<ObjectSchemaType, 'name' | 'fields' | 'type' | 'inputComponent' | 'jsonType'> {
97
- options: ObjectSchemaType['options'] & TreeInputOptions
98
- }
99
-
100
- export interface TreeDeskStructureProps extends TreeInputOptions {
101
- /**
102
- * _id of the document that will hold the tree data.
103
- */
104
- documentId: string
105
-
106
- /**
107
- * (Optional)
108
- * Key for the field representing the hierarchical tree inside the document.
109
- * `tree` by default.
110
- */
111
- fieldKeyInDocument?: string
112
- }
113
-
114
- export interface DocumentPair {
115
- draft?: SanityDocument
116
- published?: SanityDocument
117
- }
118
-
119
- export interface AllItems {
120
- [publishedId: string]: DocumentPair | undefined
121
- }
122
-
123
- type DocumentOperation<Payload = unknown> = {
124
- execute?: (payload?: Payload) => void
125
- disabled?: boolean | string
126
- }
127
-
128
- export interface DocumentOperations {
129
- patch?: DocumentOperation<unknown[]>
130
- commit?: DocumentOperation
131
- del?: DocumentOperation
132
- delete?: DocumentOperation
133
- discardChanges?: DocumentOperation
134
- duplicate?: DocumentOperation
135
- restore?: DocumentOperation
136
- unpublish?: DocumentOperation
137
- publish?: DocumentOperation
138
- }
139
-
140
- export interface VisibilityMap {
141
- [_key: string]: boolean
142
- }
143
-
144
- export interface NodeProps {
145
- node: LocalTreeItem
146
- }
147
-
148
- export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>
@@ -1,20 +0,0 @@
1
- import {getTreeFromFlatData} from '@nosferatu500/react-sortable-tree'
2
- import {StoredTreeItem} from '../types'
3
-
4
- interface TreeItemWithChildren extends StoredTreeItem {
5
- children?: TreeItemWithChildren[]
6
- }
7
-
8
- export default function flatDataToTree(data: StoredTreeItem[]): TreeItemWithChildren[] {
9
- return getTreeFromFlatData({
10
- flatData: data.map((item) => ({
11
- ...item,
12
- // if parent: undefined, the tree won't be constructed
13
- parent: item.parent || null,
14
- })),
15
- getKey: (item) => item._key,
16
- getParentKey: (item) => item.parent,
17
- // without rootKey, the tree won't be constructed
18
- rootKey: null as any,
19
- }) as TreeItemWithChildren[]
20
- }
@@ -1,30 +0,0 @@
1
- import {FlatDataItem, TreeItem} from '@nosferatu500/react-sortable-tree'
2
-
3
- /**
4
- * Gets adjescent non-children nodes of a given treeIndex.
5
- */
6
- export default function getAdjescentNodes({
7
- flatTree,
8
- node,
9
- treeIndex,
10
- }: {
11
- flatTree: FlatDataItem[]
12
- node: TreeItem
13
- treeIndex: number
14
- }): {
15
- leadingNode?: FlatDataItem
16
- followingNode?: FlatDataItem
17
- } {
18
- const leadingNode = flatTree
19
- .slice(0, treeIndex)
20
- .reverse()
21
- // Disregard children nodes - these include the current node's key in their `path` array
22
- .find((item) => !item.path.includes(node._key))
23
-
24
- const followingNode = flatTree.slice(treeIndex + 1).find((item) => !item.path.includes(node._key))
25
-
26
- return {
27
- leadingNode,
28
- followingNode,
29
- }
30
- }
@@ -1,28 +0,0 @@
1
- import {ReactSortableTreeProps} from '@nosferatu500/react-sortable-tree/react-sortable-tree'
2
- import React from 'react'
3
- import NodeContentRenderer from '../components/NodeContentRenderer'
4
- import PlaceholderDropzone from '../components/PlaceholderDropzone'
5
- import TreeNodeRenderer from '../components/TreeNodeRenderer'
6
- // import {ROW_HEIGHT} from './getTreeHeight'
7
-
8
- export default function getCommonTreeProps({
9
- placeholder
10
- }: {
11
- placeholder: {
12
- title: string
13
- subtitle?: string
14
- }
15
- }): Partial<ReactSortableTreeProps> {
16
- return {
17
- theme: {
18
- nodeContentRenderer: NodeContentRenderer,
19
- placeholderRenderer: (props: any) => <PlaceholderDropzone {...placeholder} {...props} />,
20
- treeNodeRenderer: TreeNodeRenderer,
21
- style: {height: '100%'},
22
- innerStyle: undefined,
23
- scaffoldBlockPxWidth: 44,
24
- slideRegionSize: 100
25
- // rowHeight: ROW_HEIGHT,
26
- }
27
- }
28
- }
@@ -1,8 +0,0 @@
1
- import {getVisibleNodeCount, TreeItem} from '@nosferatu500/react-sortable-tree'
2
-
3
- export default function getTreeHeight(treeData: TreeItem[], rowHeight: number): string {
4
- const visibleNodeCount = getVisibleNodeCount({treeData})
5
-
6
- // prettier-ignore
7
- return `${50 + (rowHeight * visibleNodeCount)}px`
8
- }
@@ -1,43 +0,0 @@
1
- // Adapted from @sanity/form-builder/src/sanity/utils/gradientPatchAdapter.ts
2
- import {arrayToJSONMatchPath} from '@sanity/mutator'
3
-
4
- type Patch = Record<string, any>
5
-
6
- type GradientPatch = Record<string, any>
7
-
8
- export function toGradient(patches: Patch[]): GradientPatch[] {
9
- return patches.map(toGradientPatch)
10
- }
11
-
12
- function toGradientPatch(patch: Patch): GradientPatch {
13
- const matchPath = arrayToJSONMatchPath(patch.path || [])
14
- if (patch.type === 'insert') {
15
- const {position, items} = patch
16
- return {
17
- insert: {
18
- [position]: matchPath,
19
- items: items,
20
- },
21
- }
22
- }
23
-
24
- if (patch.type === 'unset') {
25
- return {
26
- unset: [matchPath],
27
- }
28
- }
29
-
30
- if (!patch.type) {
31
- throw new Error(`Missing patch type in patch ${JSON.stringify(patch)}`)
32
- }
33
- if (matchPath) {
34
- return {
35
- [patch.type]: {
36
- [matchPath]: patch.value,
37
- },
38
- }
39
- }
40
- return {
41
- [patch.type]: patch.value,
42
- }
43
- }
@@ -1,7 +0,0 @@
1
- export function unprefixId(_id = ''): string {
2
- return _id.replace('drafts.', '')
3
- }
4
-
5
- export function isDraft(_id = ''): boolean {
6
- return _id.startsWith('drafts.')
7
- }
@@ -1,60 +0,0 @@
1
- export function getSchemaTypeName(
2
- documentType: string,
3
- type: 'document' | 'node' | 'nodeValue' | 'array'
4
- ): string {
5
- switch (type) {
6
- case 'document':
7
- return documentType
8
- case 'array':
9
- return `${documentType}.array`
10
- case 'node':
11
- return `${documentType}.node`
12
- case 'nodeValue':
13
- return `${documentType}.nodeValue`
14
- default:
15
- return documentType
16
- }
17
- }
18
-
19
- /**
20
- * Temporary value of nodes' `_type` before they are normalized and persisted as the user-defined choice.
21
- */
22
- export const DEFAULT_DOC_TYPE = 'hierarchy.tree'
23
- export const INTERNAL_NODE_TYPE = getSchemaTypeName(DEFAULT_DOC_TYPE, 'node')
24
- export const INTERNAL_NODE_VALUE_TYPE = getSchemaTypeName(DEFAULT_DOC_TYPE, 'nodeValue')
25
- export const INTERNAL_NODE_ARRAY_TYPE = getSchemaTypeName(DEFAULT_DOC_TYPE, 'array')
26
-
27
- /**
28
- * Barebones recursive utility to inject the desired nodeObjectType in patches generated in deeply nested components and utilities.
29
- */
30
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
31
- export default function injectNodeTypeInPatches(patchData: any, documentType: string): any {
32
- if (Array.isArray(patchData)) {
33
- return patchData.map((child) => injectNodeTypeInPatches(child, documentType))
34
- }
35
- if (typeof patchData === 'object' && patchData !== null) {
36
- return Object.keys(patchData).reduce((newObject, key) => {
37
- const value = patchData[key as keyof typeof patchData]
38
-
39
- if (
40
- key === '_type' &&
41
- typeof value === 'string' &&
42
- [INTERNAL_NODE_TYPE, INTERNAL_NODE_VALUE_TYPE].includes(value)
43
- ) {
44
- return {
45
- ...newObject,
46
- [key]: getSchemaTypeName(
47
- documentType,
48
- value === INTERNAL_NODE_TYPE ? 'node' : 'nodeValue'
49
- ),
50
- }
51
- }
52
-
53
- return {
54
- ...newObject,
55
- [key]: injectNodeTypeInPatches(value, documentType),
56
- }
57
- }, {})
58
- }
59
- return patchData
60
- }
@@ -1,26 +0,0 @@
1
- export default function moveItemInArray<ItemType = unknown>({
2
- array,
3
- fromIndex,
4
- toIndex,
5
- }: {
6
- array: ItemType[]
7
- fromIndex: number
8
- toIndex: number
9
- }): ItemType[] {
10
- if (fromIndex === toIndex) {
11
- return array
12
- }
13
-
14
- const newArray = [...array]
15
-
16
- const target = newArray[fromIndex]
17
- const inc = toIndex < fromIndex ? -1 : 1
18
-
19
- for (let i = fromIndex; i !== toIndex; i += inc) {
20
- newArray[i] = newArray[i + inc]
21
- }
22
-
23
- newArray[toIndex] = target
24
-
25
- return newArray
26
- }