-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathResourcesPicker.tsx
More file actions
357 lines (341 loc) · 10.8 KB
/
ResourcesPicker.tsx
File metadata and controls
357 lines (341 loc) · 10.8 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/** @jsx jsx */
import { jsx } from '@emotion/core';
import {
Avatar,
Button,
CircularProgress,
IconButton,
InputAdornment,
ListItem,
ListItemAvatar,
ListItemText,
Paper,
TextField,
Typography,
} from '@material-ui/core';
import { Close, Create, Search } from '@material-ui/icons';
import { runInAction, action } from 'mobx';
import { useObserver, useLocalStore } from 'mobx-react';
import React, { useEffect } from 'react';
import { CustomReactEditorProps } from '../interfaces/custom-react-editor-props';
import { Resource } from '../interfaces/resource';
import { BuilderRequest } from '../interfaces/builder-request';
import { SetEcomKeysMessage } from '../components/set-keys-message';
import pluralize from 'pluralize';
import throttle from 'lodash/throttle';
export interface CommerceAPIOperations {
[resourceName: string]: {
resourcePicker?: React.FC<ResourcePickerProps>;
findById(id: string): Promise<Resource>;
findByHandle?(handle: string): Promise<Resource>;
search(search: string, offset?: number, limit?: number): Promise<Resource[]>;
getRequestObject(id: string, resource?: Resource): BuilderRequest;
};
}
export interface ResourcesPickerButtonProps
extends CustomReactEditorProps<BuilderRequest | string> {
isPreview?: boolean;
handleOnly?: boolean;
api: CommerceAPIOperations;
resourcePicker?: React.FC<ResourcePickerProps>;
pluginId: string;
pluginName: string;
resourceName: string;
previewType?: string;
}
export interface ResourcePreviewCellProps {
resource: Resource;
button?: boolean;
selected?: boolean;
className?: string;
}
export const ResourcePreviewCell: React.FC<ResourcePreviewCellProps> = props =>
useObserver(() => (
<ListItem className={props.className} button={props.button} selected={props.selected}>
{props.resource.image && (
<ListItemAvatar>
<Avatar css={{ borderRadius: 4 }} src={props.resource.image.src} />
</ListItemAvatar>
)}
<ListItemText
primary={
<div
css={{
maxWidth: 400,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{props.resource.title !== 'untitled' ? (
<div>
{props.resource.title} - {props.resource.id}
</div>
) : (
props.resource.title
)}
</div>
}
/>
</ListItem>
));
export type ResourcePickerProps = CustomReactEditorProps<Resource> & {
api: CommerceAPIOperations;
omitIds?: string[];
resourceName: string;
title?: string;
};
export const ResourcePicker: React.FC<ResourcePickerProps> = props => {
const store = useLocalStore(() => ({
searchInputText: '',
loading: false,
resources: [] as Resource[],
search: throttle(async () => {
store.loading = true;
const catchError = (err: any) => {
console.error('search error:', err);
props.context.snackBar.show('Oh no! There was an error searching for resources');
};
const resourcesResponse = await props.api[props.resourceName]
.search(store.searchInputText)
.catch(catchError);
runInAction(() => {
if (Array.isArray(resourcesResponse)) {
store.resources = resourcesResponse.filter(
resource => !(props.omitIds || []).includes(String(resource.id))
);
}
store.loading = false;
});
}, 400),
}));
useEffect(() => {
store.search();
}, [store.searchInputText]);
return useObserver(() => (
<div css={{ display: 'flex', flexDirection: 'column', minWidth: 500, padding: 30 }}>
<TextField
css={{ marginBottom: 10 }}
value={store.searchInputText}
placeholder={props.title || `Search ${pluralize.plural(props.resourceName)}...`}
InputProps={{
style: {
padding: '8px 0px',
},
startAdornment: (
<InputAdornment css={{ margin: '8px -2px 8px 8px' }} position="start">
<Search css={{ color: 'var(--off-background-7)', fontSize: 20 }} />
</InputAdornment>
),
}}
onChange={action(e => (store.searchInputText = e.target.value))}
/>
{store.loading && <CircularProgress disableShrink css={{ margin: '50px auto' }} />}
<div>
{!store.loading &&
(store.resources.length ? (
store.resources.map(item => (
<div
key={item.id}
onClick={e => {
props.onChange(item);
}}
>
<ResourcePreviewCell
selected={String(item.id) === String(props.value?.id)}
button
resource={item}
key={item.id}
/>
</div>
))
) : (
<div>
<Typography
css={{
margin: '40px 20px',
textAlign: 'center',
fontSize: 17,
}}
variant="caption"
>
No {pluralize.plural(props.resourceName)} found
</Typography>
</div>
))}
</div>
</div>
));
};
export const ResourcesPickerButton: React.FC<ResourcesPickerButtonProps> = props => {
const store = useLocalStore(() => ({
loading: false,
error: null,
resourceInfo: null as Resource | null,
resourceHandle: props.handleOnly && typeof props.value === 'string' ? props.value : undefined,
resourceId: props.handleOnly
? undefined
: typeof props.value === 'string'
? props.value
: props.value?.options?.get(props.resourceName),
updateResourceId(newProps: ResourcesPickerButtonProps) {
this.resourceId = newProps.handleOnly
? undefined
: typeof newProps.value === 'string'
? newProps.value
: newProps.value?.options?.get(newProps.resourceName);
},
async getResource() {
this.error = null;
this.loading = true;
try {
const resourceService = props.api[props.resourceName];
const value =
(this.resourceId && (await resourceService.findById(this.resourceId))) ||
(this.resourceHandle &&
resourceService.findByHandle &&
(await resourceService.findByHandle(this.resourceHandle)));
this.resourceInfo = value || null;
} catch (e) {
console.error(e);
this.error = e as any;
props.context.snackBar.show(
`Oh no! There was an error fetching ${pluralize.plural(props.resourceName)}`
);
}
this.loading = false;
},
async showPickResouceModal(title?: string) {
const { value, resourcePicker, ...rest } = props;
const PickerCompnent = resourcePicker || ResourcePicker;
const close = await props.context.globalState.openDialog(
<PickerCompnent
{...rest}
resourceName={props.resourceName}
{...(this.resourceInfo && { value: this.resourceInfo })}
title={title}
onChange={action(value => {
if (value) {
this.resourceHandle = value.handle;
this.resourceId = String(value.id);
this.getResource();
if (props.handleOnly) {
props.onChange(this.resourceHandle);
} else {
if (props.field?.isTargeting) {
props.onChange(this.resourceId);
} else {
props.onChange(
props.api[props.resourceName].getRequestObject(this.resourceId, value)
);
}
}
}
close();
})}
/>,
false,
{
PaperProps: {
// Align modal to top so doesn't jump around centering itself when
// grows and shrinks to show more/less resources or loading
style: {
alignSelf: 'flex-start',
},
},
}
);
},
}));
useEffect(() => {
store.updateResourceId(props);
store.getResource();
}, [props.value]);
useEffect(() => {
const hasPreviewFields = Boolean(
props.context.designerState.editingModel?.fields.find(
(field: { type: string }) => field.type === props.previewType
)
);
if (
hasPreviewFields &&
props.context.globalState.globalDialogs.length === 0 &&
props.context.designerState?.editingContentModel &&
props.isPreview &&
(!props.value || store.error)
) {
setTimeout(() => store.showPickResouceModal(`Pick a ${props.resourceName} to preview`));
}
}, [store.error]);
return useObserver(() => {
const pluginSettings = props.context.user.organization.value.settings.plugins.get(
props.pluginId
);
if (!pluginSettings.get('hasConnected')) {
return <SetEcomKeysMessage pluginId={props.pluginId} pluginName={props.pluginName} />;
}
return (
<div css={{ display: 'flex', flexDirection: 'column', padding: '10px 0' }}>
{store.loading && (
<CircularProgress size={20} disableShrink css={{ margin: '30px auto' }} />
)}
{store.resourceInfo && (
<Paper
css={{
position: 'relative',
}}
>
<ResourcePreviewCell button css={{ paddingRight: 70 }} resource={store.resourceInfo} />
<IconButton
css={{
position: 'absolute',
right: 42,
top: 0,
bottom: 0,
height: 50,
marginTop: 'auto',
marginBottom: 'auto',
}}
onClick={() => {
store.showPickResouceModal();
}}
>
<Create css={{ color: '#888' }} />
</IconButton>
<IconButton
css={{
position: 'absolute',
right: 2,
top: 0,
bottom: 0,
height: 50,
marginTop: 'auto',
marginBottom: 'auto',
opacity: 0.7,
}}
onClick={action(() => {
store.resourceHandle = undefined;
store.resourceId = undefined;
store.resourceInfo = null;
props.onChange(null as any);
})}
>
<Close css={{ color: '#888' }} />
</IconButton>
</Paper>
)}
{!store.resourceInfo && !store.loading && (
<Button
color="primary"
variant="contained"
onClick={() => {
store.showPickResouceModal();
}}
>
Choose {props.resourceName}
</Button>
)}
</div>
);
});
};