/
ArrayOfPrimitivesInput.tsx
199 lines (179 loc) · 6.68 KB
/
ArrayOfPrimitivesInput.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import React from 'react'
import {get} from 'lodash'
import {Card, Stack, Text} from '@sanity/ui'
import {ArrayOfPrimitivesInputProps} from '../../../types'
import {Item, List} from '../common/list'
import {PrimitiveItemProps} from '../../../types/itemProps'
import {ArrayOfPrimitivesItem} from '../../../members'
import {ErrorItem} from '../ArrayOfObjectsInput/List/ErrorItem'
import {UploadTargetCard} from '../common/UploadTargetCard'
import {getEmptyValue} from './getEmptyValue'
import {PrimitiveValue} from './types'
import {nearestIndexOf} from './utils/nearestIndex'
import {ItemRow} from './ItemRow'
import {ArrayOfPrimitivesFunctions} from './ArrayOfPrimitivesFunctions'
// Note: this should be a class component until React provides support for a hook version of getSnapshotBeforeUpdate
/** @beta */
export class ArrayOfPrimitivesInput extends React.PureComponent<ArrayOfPrimitivesInputProps> {
_element: HTMLElement | null = null
handleAppend = (itemValue: PrimitiveValue) => {
const {value = [], onIndexFocus, onItemAppend} = this.props
onItemAppend(itemValue)
onIndexFocus(value.length)
}
handlePrepend = (itemValue: PrimitiveValue) => {
const {onIndexFocus, value = [], onItemPrepend} = this.props
onItemPrepend(itemValue)
onIndexFocus(value.length)
}
handleSortEnd = (event: {fromIndex: number; toIndex: number}) => {
const {onIndexFocus, onMoveItem, value} = this.props
if (value) onMoveItem(event)
onIndexFocus(event.toIndex)
}
focus() {
if (this._element) {
this._element.focus()
}
}
getSnapshotBeforeUpdate(prevProps: ArrayOfPrimitivesInputProps) {
const {focusPath: prevFocusPath = [], value: prevValue = []} = prevProps
const {focusPath = [], value = []} = this.props
if (prevFocusPath[0] === focusPath[0] && prevValue.length !== value.length) {
// the length of the array has changed, but the focus path has not, which may happen if someone inserts or removes a new item above the one currently in focus
const focusIndex = focusPath[0]
const selection = window.getSelection()
if (!(selection?.focusNode instanceof HTMLElement)) {
return null
}
const input = selection.focusNode?.querySelector('input,textarea')
return input instanceof HTMLInputElement
? {
prevFocusedIndex: focusIndex,
restoreSelection: {
text: selection.toString(),
start: input.selectionStart,
end: input.selectionEnd,
value: input.value,
},
}
: {}
}
return null
}
componentDidUpdate(
prevProps: ArrayOfPrimitivesInputProps,
prevState: Record<string, unknown>,
snapshot?: {restoreSelection: {start: number; end: number}; prevFocusedIndex: number}
) {
const {onIndexFocus} = this.props
if (snapshot?.restoreSelection && prevProps.value) {
const prevFocusedValue = prevProps.value[snapshot.prevFocusedIndex]
const nearestIndex = nearestIndexOf(
this.props.value || [],
snapshot.prevFocusedIndex,
prevFocusedValue
)
if (nearestIndex === -1) {
return
}
const newInput = this._element?.querySelector(
`[data-item-index='${nearestIndex}'] input,textarea`
)
if (newInput instanceof HTMLInputElement) {
newInput.focus()
try {
newInput.setSelectionRange(snapshot.restoreSelection.start, snapshot.restoreSelection.end)
} catch {
// not all inputs supports selection (e.g. <input type="number" />)
}
}
onIndexFocus(nearestIndex)
}
}
renderArrayItem = (props: Omit<PrimitiveItemProps, 'renderDefault'>) => {
const {schemaType} = this.props
const sortable = schemaType.options?.sortable !== false
return <ItemRow {...props} sortable={sortable} insertableTypes={schemaType.of} />
}
render() {
const {
schemaType,
members,
readOnly,
renderInput,
onUpload,
onItemRemove,
resolveUploader,
elementProps,
arrayFunctions: ArrayFunctions = ArrayOfPrimitivesFunctions,
} = this.props
const isSortable = !readOnly && get(schemaType, 'options.sortable') !== false
// Note: we need this in order to generate new id's when items are moved around in the list
// without it, dndkit will restore focus on the original index of the dragged item
const membersWithSortIds = members.map((member) => ({
id: `${member.key}-${member.kind === 'item' ? member.item.value : 'error'}`,
member: member,
}))
return (
<Stack space={3} data-testid="array-primitives-input">
<UploadTargetCard
types={schemaType.of}
resolveUploader={resolveUploader}
onUpload={onUpload}
{...elementProps}
tabIndex={0}
>
<Stack space={1}>
{membersWithSortIds.length === 0 ? (
<Card padding={3} border style={{borderStyle: 'dashed'}} radius={2}>
<Text align="center" muted size={1}>
{schemaType.placeholder || <>No items</>}
</Text>
</Card>
) : (
<Card padding={1} border>
<List
onItemMove={this.handleSortEnd}
items={membersWithSortIds.map((m) => m.id)}
sortable={isSortable}
gap={1}
>
{membersWithSortIds.map(({member, id}, index) => {
return (
<Item key={member.key} id={id} sortable={isSortable} disableTransition>
{member.kind === 'item' && (
<ArrayOfPrimitivesItem
member={member}
renderItem={this.renderArrayItem}
renderInput={renderInput}
/>
)}
{member.kind === 'error' && (
<ErrorItem
sortable={isSortable}
member={member}
onRemove={() => onItemRemove(index)}
/>
)}
</Item>
)
})}
</List>
</Card>
)}
</Stack>
</UploadTargetCard>
<ArrayFunctions
onChange={this.props.onChange}
onItemAppend={this.handleAppend}
onItemPrepend={this.handlePrepend}
onValueCreate={getEmptyValue}
readOnly={this.props.readOnly}
schemaType={this.props.schemaType}
value={this.props.value}
/>
</Stack>
)
}
}