-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathGroupingChooser.ts
More file actions
443 lines (412 loc) · 15.8 KB
/
Copy pathGroupingChooser.ts
File metadata and controls
443 lines (412 loc) · 15.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
* This file belongs to Hoist, an application development toolkit
* developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
*
* Copyright © 2026 Extremely Heavy Industries Inc.
*/
import {GroupingChooserModel} from '@xh/hoist/cmp/grouping';
import {GroupingChooserLocalModel} from '@xh/hoist/cmp/grouping/impl/GroupingChooserLocalModel';
import {
box,
div,
filler,
fragment,
frame,
hbox,
hframe,
placeholder,
vbox,
vframe
} from '@xh/hoist/cmp/layout';
import {hoistCmp, Side, useLocalModel, uses} from '@xh/hoist/core';
import {button, ButtonProps} from '@xh/hoist/desktop/cmp/button';
import {select} from '@xh/hoist/desktop/cmp/input';
import {panel} from '@xh/hoist/desktop/cmp/panel';
import '@xh/hoist/desktop/register';
import {toolbar} from '@xh/hoist/desktop/cmp/toolbar';
import {Icon} from '@xh/hoist/icon';
import {menu, menuItem, popover} from '@xh/hoist/kit/blueprint';
import {dragDropContext, draggable, droppable} from '@xh/hoist/kit/react-beautiful-dnd';
import {elemWithin, getTestId} from '@xh/hoist/utils/js';
import {splitLayoutProps} from '@xh/hoist/utils/react';
import classNames from 'classnames';
import {isEmpty, isNil} from 'lodash';
import './GroupingChooser.scss';
import {ReactNode} from 'react';
export interface GroupingChooserProps extends ButtonProps<GroupingChooserModel> {
/** Title for value-editing portion of popover, or null to suppress. */
editorTitle?: ReactNode;
/** Text to represent empty state (i.e. value = null or []) */
emptyText?: string;
/**
* Side of the popover, relative to the value-editing controls, on which the Favorites list
* should be rendered, if enabled.
*/
favoritesSide?: Side;
/** Title for favorites-list portion of popover, or null to suppress. */
favoritesTitle?: ReactNode;
/** Min height in pixels of the popover menu itself. */
popoverMinHeight?: number;
/** Position of popover relative to target button. */
popoverPosition?: 'bottom' | 'top';
/**
* Width in pixels of the popover menu itself.
* If unspecified, will default based on favorites enabled status + side.
*/
popoverWidth?: number;
/** True (default) to style trigger button background and borders to match inputs. */
styleButtonAsInput?: boolean;
}
/**
* Control for selecting a list of dimensions for grouping APIs, with built-in support for
* drag-and-drop reordering and user-managed favorites.
*
* @see GroupingChooserModel
*/
export const [GroupingChooser, groupingChooser] = hoistCmp.withFactory<GroupingChooserProps>({
displayName: 'GroupingChooser',
model: uses(GroupingChooserModel),
className: 'xh-grouping-chooser',
render(
{
model,
className,
editorTitle = 'Group By',
emptyText = 'Ungrouped',
favoritesSide = 'right',
favoritesTitle = 'Favorites',
popoverWidth,
popoverMinHeight,
popoverPosition = 'bottom',
styleButtonAsInput = true,
testId,
...rest
},
ref
) {
const impl = useLocalModel(GroupingChooserLocalModel),
{value, allowEmpty, persistFavorites} = model,
{editorIsOpen} = impl,
isOpen = editorIsOpen,
label = isEmpty(value) && allowEmpty ? emptyText : model.getValueLabel(value),
[layoutProps, buttonProps] = splitLayoutProps(rest),
favesClassNameMod = `faves-${persistFavorites ? favoritesSide : 'disabled'}`,
favesTB = isTB(favoritesSide);
popoverWidth = popoverWidth || (persistFavorites && !favesTB ? 500 : 250);
return box({
ref,
className,
...layoutProps,
item: popover({
isOpen,
popoverRef: impl.popoverRef,
popoverClassName: `xh-grouping-chooser-popover xh-grouping-chooser-popover--${favesClassNameMod}`,
// Left align editor to keep in place when button changing size when commitOnChange: true
position: `${popoverPosition}-left`,
minimal: false,
item: fragment(
button({
text: label,
title: label,
tabIndex: -1,
className: classNames(
'xh-grouping-chooser-button',
styleButtonAsInput ? 'xh-grouping-chooser-button--as-input' : null
),
minimal: styleButtonAsInput,
...buttonProps,
onClick: () => impl.toggleEditor(),
testId
})
),
content: popoverCmp({
model: impl,
editorTitle,
emptyText,
favoritesSide,
favoritesTitle,
popoverWidth,
popoverMinHeight,
testId
}),
onInteraction: (nextOpenState, e) => {
if (
isOpen &&
nextOpenState === false &&
e?.target &&
!elemWithin(e.target as HTMLElement, 'xh-grouping-chooser-button')
) {
impl.commitPendingValueAndClose();
}
}
})
});
}
});
//------------------
// Editor
//------------------
const popoverCmp = hoistCmp.factory<GroupingChooserLocalModel>({
render({
model,
editorTitle,
emptyText,
favoritesSide,
favoritesTitle,
popoverWidth,
popoverMinHeight,
testId
}) {
const {parentModel} = model,
{persistFavorites} = parentModel,
favesTB = isTB(favoritesSide),
isFavesFirst = favoritesSide === 'left' || favoritesSide === 'top',
items = [
editor({
editorTitle,
emptyText,
testId: getTestId(testId, 'editor')
}),
favoritesChooser({
// Omit if favorites generally disabled, or if none saved yet AND in top/bottom
// orientation - the empty state looks clumsy in that case. Show when empty in
// left/right orientation to avoid large jump in popover width.
omit: !parentModel.persistFavorites || (!parentModel.hasFavorites && favesTB),
favoritesSide,
favoritesTitle,
testId: getTestId(testId, 'favorites')
})
],
itemsContainer = !persistFavorites ? frame : favesTB ? vframe : hframe;
if (isFavesFirst) {
items.reverse();
}
return panel({
className: 'xh-grouping-chooser-popover__inner',
width: popoverWidth,
minHeight: popoverMinHeight,
items: itemsContainer({items}),
bbar: toolbar({
compact: true,
omit: !parentModel.persistFavorites,
items: [filler(), favoritesAddBtn({testId})]
})
});
}
});
const editor = hoistCmp.factory<GroupingChooserLocalModel>({
render({editorTitle, emptyText, testId}) {
return vbox({
className: 'xh-grouping-chooser__editor',
testId,
items: [
div({className: 'xh-popup__title', item: editorTitle, omit: isNil(editorTitle)}),
dimensionList({emptyText}),
addDimensionControl()
]
});
}
});
const dimensionList = hoistCmp.factory<GroupingChooserLocalModel>({
render({model, emptyText}) {
if (isEmpty(model.pendingValue)) {
return model.parentModel.allowEmpty
? hbox({
className: 'xh-grouping-chooser__row',
items: [filler(), emptyText, filler()]
})
: null;
}
return dragDropContext({
onDragEnd: result => model.onDragEnd(result),
item: droppable({
droppableId: 'dimension-list',
children: dndProps =>
div({
ref: dndProps.innerRef,
className: 'xh-grouping-chooser__list',
items: [
...model.pendingValue.map((dimension, idx) =>
dimensionRow({dimension, idx})
),
dndProps.placeholder
]
})
})
});
}
});
const dimensionRow = hoistCmp.factory<GroupingChooserLocalModel>({
render({model, dimension, idx}) {
// The options for this select include its current value
const options = model.getDimSelectOpts([...model.availableDims, dimension]);
return draggable({
key: dimension,
draggableId: dimension,
index: idx,
children: (dndProps, dndState) => {
// Because the popover uses css transforms to position itself,
// we need to adjust the draggable's transform to account for this.
//
// The below workaround is based on approaches discussed on this thread:
// https://github.com/atlassian/react-beautiful-dnd/issues/128
let transform = dndProps.draggableProps.style.transform;
if (dndState.isDragging || dndState.isDropAnimating) {
let rowValues = parseTransform(transform),
pPos = model.popoverRef.current.getBoundingClientRect(),
popoverValues = {
x: pPos.left,
y: pPos.top
};
// Account for drop animation
if (dndState.isDropAnimating) {
const {x, y} = dndState.dropAnimation.moveTo;
rowValues = [x, y];
}
// Subtract the popover's X / Y translation from the row's
if (!isEmpty(rowValues)) {
const x = rowValues[0] - popoverValues.x,
y = rowValues[1] - popoverValues.y;
transform = `translate(${x}px, ${y}px)`;
}
}
return div({
key: dimension,
className: classNames(
'xh-grouping-chooser__row',
dndState.isDragging ? 'xh-grouping-chooser__row--dragging' : null
),
items: [
div({
className: 'xh-grouping-chooser__row__grabber',
item: Icon.grip({prefix: 'fal'}),
...dndProps.dragHandleProps,
tabIndex: -1
}),
div({
className: 'xh-grouping-chooser__row__select',
item: select({
options,
value: dimension,
flex: 1,
width: null,
hideDropdownIndicator: true,
onChange: newDim => model.replacePendingDimAtIdx(newDim, idx)
})
}),
button({
icon: Icon.delete(),
intent: 'danger',
tabIndex: -1,
className: 'xh-grouping-chooser__row__remove-btn',
onClick: () => model.removePendingDimAtIdx(idx)
})
],
ref: dndProps.innerRef,
...dndProps.draggableProps,
style: {
...dndProps.draggableProps.style,
transform
}
});
}
});
}
});
const addDimensionControl = hoistCmp.factory<GroupingChooserLocalModel>({
render({model}) {
if (!model.isAddEnabled) return null;
const options = model.getDimSelectOpts();
return div({
className: 'xh-grouping-chooser__add-control',
items: [
div({
className: 'xh-grouping-chooser__add-control__icon',
item: Icon.grip({prefix: 'fal'})
}),
select({
// By changing the key each time the options change, we can
// ensure the Select loses its internal input state.
key: JSON.stringify(options),
options,
placeholder: 'Add level...',
flex: 1,
width: null,
hideDropdownIndicator: true,
hideSelectedOptionCheck: true,
onChange: newDim => model.addPendingDim(newDim)
})
]
});
}
});
/**
* Extract integer values from CSS transform string. Works for both `translate` and `translate3d`.
* e.g. `translate3d(250px, 150px, 0px) -> [250, 150, 0]`
*/
function parseTransform(transformStr: string): number[] {
return transformStr
?.replace('3d', '')
.match(/[-]{0,1}[\d]*[.]{0,1}[\d]+/g)
?.map(it => parseInt(it));
}
//------------------
// Favorites
//------------------
const favoritesChooser = hoistCmp.factory<GroupingChooserLocalModel>({
render({model, favoritesSide, favoritesTitle, testId}) {
const {parentModel} = model,
{favoritesOptions: options, hasFavorites} = parentModel;
return vbox({
className: `xh-grouping-chooser__favorites xh-grouping-chooser__favorites--${favoritesSide}`,
testId,
items: [
div({
className: 'xh-popup__title',
item: favoritesTitle,
omit: isNil(favoritesTitle)
}),
hasFavorites
? menu({
items: options.map(it => favoriteMenuItem(it))
})
: placeholder('No favorites saved.')
]
});
}
});
const favoriteMenuItem = hoistCmp.factory<GroupingChooserLocalModel>({
render({model, value, label}) {
const {parentModel} = model;
return menuItem({
text: label,
className: 'xh-grouping-chooser__favorites__favorite',
onClick: () => {
model.setPendingValue(value);
model.commitPendingValueAndClose();
},
labelElement: button({
icon: Icon.delete(),
intent: 'danger',
onClick: e => {
parentModel.removeFavorite(value);
e.stopPropagation();
}
})
});
}
});
const favoritesAddBtn = hoistCmp.factory<GroupingChooserLocalModel>({
render({model, testId}) {
return button({
text: 'Save as Favorite',
icon: Icon.favorite(),
className: 'xh-grouping-chooser__favorites__add-btn',
testId: getTestId(testId, 'favorites-add-btn'),
omit: !model.parentModel.persistFavorites,
disabled: !model.isAddFavoriteEnabled,
onClick: () => model.addPendingAsFavorite()
});
}
});
const isTB = (favoritesSide: Side) => favoritesSide === 'top' || favoritesSide === 'bottom';