-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAssociationSelector.js
721 lines (602 loc) · 21.1 KB
/
AssociationSelector.js
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
import React, { useMemo, useState } from "react"
import PropTypes from "prop-types"
import cx from "classnames"
import { ButtonToolbar, ListGroup, ListGroupItem } from "reactstrap"
import { FieldMode, FormGroup, useFormConfig, Icon } from "domainql-form"
import { action } from "mobx";
import { observer as fnObserver, useLocalObservable } from "mobx-react-lite";
import toPath from "lodash.topath"
import get from "lodash.get"
import set from "lodash.set"
import { v4 } from "uuid"
import config from "../config";
import i18n from "../i18n";
import GraphQLQuery from "../GraphQLQuery";
import { getFirstValue } from "../model/InteractiveQuery";
import { getGenericType, INTERACTIVE_QUERY } from "../domain";
import AssociationSelectorModal from "./AssociationSelectorModal";
import autoSubmitHack from "../util/autoSubmitHack";
import { and, Condition, field, value, values } from "../FilterDSL";
import { getGraphQLMethodType, lookupType, unwrapAll, unwrapNonNull } from "../util/type-utils";
function getQueryCondition(defaultQueryCondition, queryCondition) {
if (defaultQueryCondition && queryCondition) {
return and(defaultQueryCondition, queryCondition);
}
if (defaultQueryCondition) {
return defaultQueryCondition;
}
if (queryCondition) {
return queryCondition;
}
return null;
}
export const NO_SEARCH_FILTER = "NO_SEARCH_FILTER";
/**
* Filter Mode: Do not offer a column filter by default.
*/
export const NO_FILTER = "NO_FILTER";
/**
* Filter Mode: Offer a column filter even if a search filter is defined (with the searchFilter prop).
*/
export const COLUMN_FILTER = "COLUMN_FILTER";
/**
* Creates a filter condition for the given type, searchFilter prop and search term
*
* @param {String} type GraphQL base type
* @param {function|String}searchFilter searchFilter prop
* @param {String} searchTerm current search value
* @return {object} condition graph or null
*/
export function createSearchFilter(type, searchFilter, searchTerm)
{
if (!searchFilter)
{
return null;
}
let condition;
if (typeof searchFilter === "function")
{
condition = searchFilter(searchTerm)
}
else
{
const scalarType = unwrapNonNull(lookupType(type, "rows." + searchFilter)).name;
if (scalarType === "String")
{
condition = field(searchFilter)
.containsIgnoreCase(
value(
searchTerm,
scalarType
)
);
}
else
{
condition = field(searchFilter)
.toString()
.containsIgnoreCase(
value(
searchTerm,
scalarType
)
);
}
}
return condition;
}
function toggleOpen(modalState)
{
return {
... modalState,
isOpen: !modalState.isOpen
};
}
const removeLink = action(
"Remove Link",
(root, selected, link, name, value) => {
const id = get(link,value);
selected.delete(id);
const links = get(root, name);
const newLinks = links.filter(l => l !== link);
set(root, name, newLinks);
//console.log("AFTER: {}", toJS(root))
}
);
const MODAL_STATE_CLOSED = {
iQuery: null,
columns: null,
selectedBefore: null,
valuePath: null,
idPath: null,
isOpen: false
};
let associationSelectorCount = 0;
const updateLinksAction = action("AssociationSelector.updateLinks", (root, name, newLinks) =>
{
set(root, name, newLinks);
});
function createNewLink(generateId, valuePath, linkedObj, root, linkObjectsField, onNew)
{
const type = root._type;
const targetField = valuePath[0];
const leftSideRelation = config.inputSchema.getRelations().find(r => r.rightSideObjectName === linkObjectsField && r.targetType === type);
if (!leftSideRelation)
{
throw new Error("Could not find left side relation for type '" + type + "' and linked objects field '" + linkObjectsField + "'");
}
const linkType = leftSideRelation.sourceType;
const rightSideRelation = config.inputSchema.getRelations().find(r => r.sourceType === linkType && r.leftSideObjectName === targetField);
if (!rightSideRelation)
{
throw new Error("Could not find right side relation with source type '" + linkType + "' and left side object field '" + targetField + "'");
}
const newLink = {
_type: linkType,
id: generateId(),
[targetField]: linkedObj
};
if (leftSideRelation.sourceField === "OBJECT_AND_SCALAR" || leftSideRelation.sourceField === "SCALAR")
{
newLink[leftSideRelation.sourceFields[0]] = root.id;
}
if (rightSideRelation.sourceField === "OBJECT_AND_SCALAR")
{
newLink[rightSideRelation.sourceFields[0]] = linkedObj.id;
}
if (typeof onNew === "function")
{
onNew(newLink);
}
return newLink;
}
function updateLinks(root, name, modalState, selected, generateId, onNew)
{
const { iQuery, valuePath } = modalState;
const idPath = valuePath.slice(1);
const newLinkIds = new Set(selected);
const objectLookup = new Map();
// remove all existing linked ids
const links = get(root, name);
for (let i = 0; i < links.length; i++)
{
const link = links[i];
const obj = get(link, valuePath[0]);
newLinkIds.delete(obj.id);
objectLookup.set(obj.id, obj)
}
const linkIdsToFetch = new Set(newLinkIds);
// remove all selected ids from the current page and add them to our object lookup
for (let i = 0; i < iQuery.rows.length; i++)
{
const row = iQuery.rows[i];
const id = get(row, idPath);
if (selected.has(id))
{
linkIdsToFetch.delete(id);
objectLookup.set(id, row)
}
}
let promise;
const idField = idPath.join(".");
const type = lookupType(iQuery.type, idField);
if (type.kind !== "SCALAR")
{
throw new Error("Id field is not a scalar: " + iQuery.type + "." + idField)
}
// if there's still ids to fetch
if (linkIdsToFetch.size > 0)
{
// we query the rest
promise = iQuery._query.execute({
config: {
condition: field(idField)
.in(
values(type.name, ... linkIdsToFetch)
),
pageSize: 0
}
})
}
else
{
promise = Promise.resolve(false);
}
return promise.then(
result => {
if (result !== false)
{
const {rows} = getFirstValue(result);
for (let i = 0; i < rows.length; i++)
{
const row = rows[i];
const id = get(row, idPath);
objectLookup.set(id, row);
}
}
const newLinks = [];
// insert all existing links that are still selected
for (let i = 0; i < links.length; i++)
{
const link = links[i];
if (selected.has(get(link, valuePath)))
{
newLinks.push(link)
}
}
// create new links for new links ids
for (let id of newLinkIds)
{
const linkedObj = objectLookup.get(id);
if (!linkedObj)
{
throw new Error("No linked object for id " + id);
}
const newObj = createNewLink(generateId, valuePath, linkedObj, root, name, onNew);
newLinks.push(newObj)
}
updateLinksAction(root, name, newLinks);
}
)
}
function setsEqual(setA, setB)
{
if (setA.size !== setB.size)
{
return false;
}
for (let value of setA)
{
if (!setB.has(value))
{
return false;
}
}
return true;
}
const updateSelected = action("AssociationSelector.updateSelected", (selected, links, valuePath) => {
const newSelected = new Set();
links.forEach(
link => newSelected.add(
get(link, valuePath)
)
);
selected.replace(newSelected);
})
let associationSelectorCounter = 0
/**
* Displays the currently associated entities of a many-to-many relationship as seen from one of the associated sides.
*/
const AssociationSelector = fnObserver(props => {
const [associationSelectorId] = useState("associationSelector-"+ associationSelectorCounter++)
const {
name,
value,
display,
mode: modeFromProps,
label,
query,
queryCondition: queryConditionFromProps,
modalTitle,
fade,
helpText,
labelClass,
formGroupClass,
generateId,
onNew,
visibleColumns,
alignPagination,
paginationPageSizes,
searchFilter,
modalFilter,
onFieldConfigClick,
disabled
} = props;
const queryDef = query.getQueryDefinition();
const iQueryType = useMemo(
() => {
if (queryDef != null) {
const aliases = queryDef.aliases;
const queryName = queryDef.methodCalls[0];
const gqlMethodName = aliases ? aliases[queryName] || queryName : queryName;
return getGraphQLMethodType(gqlMethodName).name
}
return null;
},
[ queryDef ]
);
const [elementId] = useState("assoc-selector-" + (++associationSelectorCount));
const formConfig = useFormConfig();
const [modalState, setModalState] = useState(MODAL_STATE_CLOSED);
const links = get(formConfig.root, name);
const selected = useLocalObservable(() => new Set());
const queryCondition = typeof queryConditionFromProps === "function" ?
queryConditionFromProps() :
queryConditionFromProps;
const defaultQueryCondition = query.defaultVars.config?.condition;
const executeQueryCondition = getQueryCondition(defaultQueryCondition, queryCondition);
const openModal = () => {
query.execute(
{
...query.defaultVars,
config: {
...query.defaultVars.config,
condition : executeQueryCondition
}
}
).then(
result => {
try
{
const iQuery = getFirstValue(result);
if (getGenericType(iQuery._type) !== INTERACTIVE_QUERY)
{
throw new Error("Result is no interactive query object");
}
const { inputSchema } = config;
const rawVisibleColumns = visibleColumns ?? inputSchema.getTypeMeta(iQuery.type, "associationSelectorVisibleColumns");
const convertedVisibleColumns = typeof rawVisibleColumns === "string" ?
rawVisibleColumns.split(",") :
rawVisibleColumns;
const columns = iQuery.columnStates
.filter(
cs => cs.enabled && cs.name !== "id" && cs.name !== config.mergeOptions.versionField
&& (convertedVisibleColumns?.includes(cs.name) ?? true)
)
.map(
cs => {
const heading = inputSchema.getFieldMeta(iQuery.type, cs.name, "heading");
return { name: cs.name, heading }
}
);
const valuePath = toPath(value);
updateSelected(selected, links, valuePath);
const selectedBefore = new Set(selected);
const columnTypes = columns.map(({name}) => unwrapAll(lookupType(iQuery.type, name)).name)
setModalState({
iQuery,
columns,
columnTypes,
isOpen: true,
valuePath,
selectedBefore,
idPath: valuePath.slice(1)
});
}
catch (e)
{
console.error("ERROR", e);
}
}
);
};
const toggle = () => {
setModalState(toggleOpen);
const { selectedBefore } = modalState;
if (!setsEqual(selected, selectedBefore))
{
autoSubmitHack(formConfig);
updateLinks(formConfig.root, name, modalState, selected, generateId, onNew)
}
};
if (!Array.isArray(links))
{
throw new Error("AssociationSelector name prop must point to list of link values: " + JSON.stringify(links, null, 4));
}
const effectiveMode = modeFromProps || formConfig.options.mode;
const isDisabled = effectiveMode === FieldMode.DISABLED || effectiveMode === FieldMode.READ_ONLY || (typeof disabled === "function" ? disabled() : disabled);
const fieldConfigButton = useMemo(() => {
if (typeof onFieldConfigClick === "function") {
return (
<button
type="button"
className="btn btn-light btn-field-config" // very small; absolute; top right
onClick={() => {
onFieldConfigClick({
isFieldContext: false,
name,
formId: formConfig.ctx.formId,
fieldId: elementId,
path: toPath(value),
rootType: formConfig.type,
root: formConfig.root,
});
}}
>
{
<Icon className="fa-cog" />
}
</button>
);
}
}, [onFieldConfigClick]);
return (
<React.Fragment>
<FormGroup
formConfig={ formConfig }
fieldId={ elementId}
label={ label }
helpText={ helpText }
labelClass={ labelClass }
formGroupClass={formGroupClass}
errorMessages={null}
mode={ effectiveMode }
>
<ListGroup
id={ elementId }
className="assoc-selector"
>
{
links.map((link,idx) => {
return (
<ListGroupItem
key={idx}
className="d-flex justify-content-between align-items-center"
>
{
typeof display === "function" ? display(link) : get(link, display)
}
<button
type="Button"
className="btn btn-link m-0 p-0"
title={
i18n("Remove Association")
}
onClick={
() => removeLink(formConfig.root, selected, link, name, value)
}
disabled={isDisabled}
>
<Icon className="fa-times"/>
</button>
</ListGroupItem>
);
})
}
</ListGroup>
<ButtonToolbar>
<button
type="Button"
className={cx("btn btn-light", effectiveMode === FieldMode.DISABLED && "disabled")}
onClick={ openModal }
disabled={isDisabled}
name={ name }
>
<Icon className="fa-clipboard-check mr-1"/>
{
i18n("Select")
}
</button>
</ButtonToolbar>
</FormGroup>
{fieldConfigButton}
<AssociationSelectorModal
{ ... modalState }
iQueryType={ iQueryType }
selected={ selected }
title={modalTitle}
toggle={toggle}
fade={fade}
modalFilter={ modalFilter }
searchFilter={ searchFilter }
alignPagination={ alignPagination }
paginationPageSizes={ paginationPageSizes }
associationSelectorId={ associationSelectorId }
/>
</React.Fragment>
)
});
AssociationSelector.propTypes = {
/**
* Path to use as display value for associations or render function for associations ( linkObj => ReactElement ).
*/
display: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]).isRequired,
/**
* Path to use as the representative value / id of the link
*/
value: PropTypes.string,
/**
* iQuery GraphQL query to fetch the current list of target objects
*/
query: PropTypes.instanceOf(GraphQLQuery).isRequired,
/**
* Optional FilterDSL condition to be applied to the execution of the AssociationSelector's query
*/
queryCondition: PropTypes.oneOfType([
PropTypes.instanceOf(Condition),
PropTypes.func
]),
/**
* Title for the modal dialog selecting the target object
*/
modalTitle: PropTypes.string,
// FIELD PROP TYPES
/**
* Name / path for the association selector field. In contrast to most normal fields this does not point
* to a scalar value but to list of associative entity / link table fields with embedded target objects
*/
name: PropTypes.string,
/**
* Mode for this calendar field. If not set or set to null, the mode will be inherited from the <Form/> or <FormBlock>.
*/
mode: PropTypes.oneOf(FieldMode.values()),
/**
* Additional help text for this field. Is rendered for non-erroneous fields in place of the error.
*/
helpText: PropTypes.string,
/**
* Label for the field. Must be defined if name is missing.
*/
label: PropTypes.string,
/**
* Additional HTML classes for the label element.
*/
labelClass: PropTypes.string,
/**
* Additional HTML classes for the form group element.
*/
formGroupClass: PropTypes.string,
/**
* Whether to do the modal fade animation on selection (default is true)
*/
fade: PropTypes.bool,
/**
* Function to return a new id value for newly created associations. Note that you can use placeholder id values.
*
* Default is to create a new UUID (NPM "uuid" v4).
*/
generateId: PropTypes.func,
/**
* Optional callback function that is called for every newly created association link and allows to modify
* properties on that new link. ( link => ... )
*
*/
onNew: PropTypes.func,
/**
* Disables the AssociationSelector.
* Can be defined as callback function.
*/
disabled: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.func
]),
/**
* Field name or function returning a filter expression used to allow and
* validate text-input changes of the selected value.
*
* The field or filter must match exactly one element from the current `query`.
*
* (Function must be of the form `value => ...` and must return a Filter DSL condition.)
*
*/
searchFilter: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]),
/**
* set the pagination alignment of the datagrid in the modal ("left" [default], "center", "right")
*/
alignPagination: PropTypes.string,
/**
* set the available page sizes for the datagrid pagination
*/
paginationPageSizes: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
/**
* Filter mode for the selector modal. Controls display of column and repeated search filter in interaction with the searchFilter prop,
*/
modalFilter: PropTypes.oneOf([
NO_SEARCH_FILTER,
NO_FILTER,
COLUMN_FILTER
]),
};
AssociationSelector.defaultProps = {
modalTitle: i18n("Select Associated Objects"),
fade: false,
generateId: v4
};
AssociationSelector.displayName = "AssociationSelector";
export default AssociationSelector;