Repository navigation
Expand file tree
/
Copy pathListView.tsx
More file actions
8726 lines (8426 loc) · 465 KB
/
Copy pathListView.tsx
File metadata and controls
8726 lines (8426 loc) · 465 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
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as React from 'react';
import { cn, Button, Input, Popover, PopoverContent, PopoverTrigger, FilterBuilder, SortBuilder, NavigationOverlay, GroupingEditor, RefreshIndicator, DataErrorState, resolveIcon, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@object-ui/components';
import type { SortItem } from '@object-ui/components';
import { Search, X, EyeOff, Group, Paintbrush, Download, Rows4, Rows3, Rows2, Lock, Printer, Plus, Trash2, CheckSquare, AlertTriangle, ShieldAlert, RotateCw, Loader2, Info, Inbox } from 'lucide-react';
import type { FilterBuilderRowGroup } from '@object-ui/components';
import { VALUELESS_FILTER_BUILDER_OPERATORS, isFilterValueComplete, isCurrencyCompanion } from '@object-ui/components';
import { ViewSwitcherDropdown } from './ViewSwitcher';
import { ListEmptyState, hasDeclaredFilter, filterNamesCurrentUser } from './ListEmptyState';
import { ListViewCompactHeader, ListViewCompactRows, ListViewCappedRows, CAPPED_LIST_DEFAULT_LIMIT } from './ListViewCompact';
import {
ViewSettingsPopover,
ViewSettingsContent,
groupFieldOptions,
type ViewSettingsField,
PHONE_TOUCH_TARGET,
useBelowSm,
} from './components/ViewSettingsPopover';
import {
ListPhonePanelsContext,
PhoneFilterSheet,
PhoneListToolbar,
PhonePanelSheet,
PhoneSortSheet,
PHONE_CHIP,
PHONE_CHIP_ACTIVE,
type ListPhonePanels,
} from './phone/PhoneListPanels';
import { UserFilters, type UserFiltersHandle } from './UserFilters';
import { ConditionChipRow, SortPanel } from './conditions/ListConditionControls';
import {
TOOLBAR_ROW,
TOOLBAR_ROW_LEADING_PHONE,
TOOLBAR_LEFT_GROUP,
TOOLBAR_LEFT_GROUP_LEADING,
TOOLBAR_LEADING,
TOOLBAR_USER_FILTERS,
TOOLBAR_USER_FILTERS_LEADING_PHONE,
TOOLBAR_CLUSTER,
TOOLBAR_CLUSTER_LEADING_PHONE,
} from './listToolbarRow';
import {
calendarWindowCovers,
calendarWindowFilter,
calendarWindowFor,
fetchCalendarWindow,
initialCalendarWindow,
type CalendarVisibleRange,
type CalendarWindow,
} from './calendarWindow';
import { SchemaRenderer, useNavigationOverlay, classifyLoadError, answeredLoadFailure, isPermissionError, usePredicateScope, useDataInvalidation, useFilterScope, useResolvedFilter, NonGridRowCeilingNote, OwnWritesContext, createOwnWrites } from '@object-ui/react';
import type { LoadErrorKind, AnsweredLoadFailure } from '@object-ui/react';
import { useDensityMode, resolveInlineAriaProps } from '@object-ui/react';
import type { DataTableSchema, DependsOnInput, ListViewSchema, ObjectMapConfig } from '@object-ui/types';
import { detectStatusField, isSystemManagedField } from '@object-ui/types';
import { usePullToRefresh } from '@object-ui/mobile';
import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, isObjectExportOffered, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField, withHeaderSortPick } from '@object-ui/core';
import { useObjectLabel, useSafeFieldLabel, createSafeTranslation, useDisplayLocale, pickLocalized, recordCurrencyField, recordCurrencyReadField } from '@object-ui/i18n';
// Two resolvers, two vocabularies — the repo spells the distinction into the
// NAMES (objectui#4167). `resolveInlineI18nLabel` is the spec's own
// `resolveI18nLabel`: it resolves the INLINE per-locale map
// (`{ en: …, 'zh-CN': … }`) that `@objectstack/spec` 17.0.0-rc.6 folded into
// `I18nLabel`, which is what the nested `aria` bag carries. It does NOT accept
// objectui's keyed `{ key, defaultValue, params }` ref — that vocabulary lives
// on the FLAT `schema.ariaLabel` and is resolved by `SchemaRenderer` instead
// (objectui#5134).
import { resolveI18nLabel as resolveInlineI18nLabel, normalizeFilterOperator, PaginationConfigSchema } from '@objectstack/spec/ui';
import type { ColumnSummary, GroupingConfig } from '@objectstack/spec/ui';
import { canonicalAstOperator, isVirtualSearchField, platformProvisionsStorage, resolveInjectedSystemColumns, resolveSearchFieldResolution, type SearchFieldMeta } from '@objectstack/spec/data';
import { SystemFieldName } from '@objectstack/spec/system';
import { usePermissions } from '@object-ui/permissions';
import { RecordDetailPanel } from '@object-ui/plugin-detail';
import { resolveBulkActions, useBulkActionItems, useUndeclaredActionNamesWarning, readListScrollState } from '@object-ui/plugin-grid';
/**
* The `case 'map'` branch below builds an `object-map` schema by flattening
* the view's `map` block's CONTENTS to the top level — one entry per key
* `ObjectMapConfigSchema` declares, written under the name the FLAT form uses
* for that key. Whitelisted rather than a whole-bag spread: `style` is ALSO
* `BaseSchema.style` (inline CSS, legal on every node), and spreading the raw
* `map` block collapsed the two namespaces onto one key (objectui#5177). That
* reason is unchanged, and so is its consequence: a key the declaration does
* NOT carry never reaches the product.
*
* `style` IS delivered (objectui#9950) — under its flat spelling `mapStyle`,
* NOT by widening the whitelist to let `style` through unrenamed.
* `getMapConfig` in `ObjectMap.tsx` reads `schema.mapStyle || schema.map?.style`
* and deliberately does NOT read a top-level `style`, because that key is the
* base face's inline CSS (objectui#5017). `mapStyle` is itself a declared
* member of `ObjectMapSchema`, so the flat product stays inside the declaration
* at both ends. Before this, a view authoring `map: { style: '<url>' }` parsed
* green, was dropped here, and the map painted the PUBLIC DEMO TILES.
*
* HAND-LISTED, not derived at runtime — deliberately, and only here (`plugin-
* map`'s own `FLAT_MAP_CONFIG_KEYS` in `ObjectMap.tsx` DOES derive from
* `ObjectMapConfigSchema.shape`, and should stay that way): this file is
* reachable from `examples/console-starter`'s own `src/`, so it is part of the
* import graph `vite-alias-closure.test.ts` walks. That walker resolves a bare
* `@object-ui/*` specifier with plain `index.<ext>` conventions and cannot find
* `@object-ui/types/zod`'s actual barrel file (`zod/index.zod.ts` — a
* non-standard name) — a REAL runtime import of it here reproducibly fails
* that gate (measured on objectui#5177's first PR, PR #5231, CI run
* 32160288416), even though Vite's own alias table already resolves the
* specifier correctly (`examples/console-starter/vite.config.ts` has carried
* an explicit `@object-ui/types/zod` entry since PR #5156). `ObjectMap.tsx`
* gets away with the runtime import only because nothing in
* console-starter's graph reaches `@object-ui/plugin-map` today.
*
* Anti-drift is TWO mechanisms, neither of them this comment:
* - the type below is TOTAL — a `Record` over EVERY `keyof ObjectMapConfig`,
* not a list of some of them — so a key added to the declaration fails
* `tsc` here until it is given a flat spelling. A key can no longer be
* left out by simply not being written down, which is how `style` was.
* - `ListView.mapFlatten.test.tsx` pins this object's key set against
* `ObjectMapConfigSchema.shape` — imported only from that TEST file, which
* the alias-closure walker explicitly excludes from traversal — and asserts
* the RELATION (every declared key is delivered under its flat spelling).
* The pre-#9950 pin could not see the omission because it compared the hand
* list against `shape` MINUS `style`: the set it measured against was
* narrowed by the same subtraction the defect was made of, so it stayed
* green while an authored style was being discarded.
*/
export const FLAT_MAP_CONFIG_SPELLING = {
latitudeField: 'latitudeField',
longitudeField: 'longitudeField',
locationField: 'locationField',
titleField: 'titleField',
descriptionField: 'descriptionField',
zoom: 'zoom',
center: 'center',
// The one key whose flat spelling differs from its declared name — see the
// objectui#9950 paragraph above for why it is `mapStyle` and not `style`.
style: 'mapStyle',
} as const satisfies Record<keyof ObjectMapConfig, string>;
/**
* Copy the declared keys an author actually wrote onto the flat product,
* each under its flat spelling — the map's keys by default, the gantt's when
* that branch passes `GANTT_CONFIG_SPELLING` (`@object-ui/core`, one copy
* shared with `plugin-view`'s `ObjectView`, objectui#13458).
*
* Values travel AS WRITTEN: this is transport, not a second validation of the
* declared block — that reading belongs to `getMapConfig` in `ObjectMap.tsx`
* and stays there (objectui#5018). Discarding an ill-typed value here would
* reintroduce exactly the silent drop objectui#9950 closed.
*/
function pickFlatMapConfig(
mapConfig: unknown,
spelling: Readonly<Record<string, string>> = FLAT_MAP_CONFIG_SPELLING,
): Record<string, unknown> {
if (!mapConfig || typeof mapConfig !== 'object') return {};
const source = mapConfig as Record<string, unknown>;
return Object.fromEntries(
Object.entries(spelling)
.filter(([declared]) => declared in source)
.map(([declared, flat]) => [flat, source[declared]]),
);
}
/**
* The effective map configuration for a list view: the spec's VIEW-LEVEL `map`
* block, through the flat whitelist.
*
* `map` is `ListMapConfigSchema` (objectstack#9340, consumable here since the
* `@objectstack/spec` 17.1.0 pin) — a strict, seven-key block that flows into
* this package's own `ListViewSchema` by reference (it is not in
* `LIST_VIEW_LOCAL_OVERRIDES`, so `specFieldsExcept` imports it). It was
* authorable and validated but never read: `case 'map'` forwarded only the
* legacy `options.map` bag, so declaring it changed nothing at runtime
* (objectui#5042).
*
* ONE SOURCE (#25923). This merged the block OVER the legacy `options.map` bag,
* per key, until the spec retired the bag: the list overlay refuses `options`,
* and a stored bag is folded onto the top-level block (per key, the block
* winning — this function's old precedence) by the spec's ADR-0087 D2
* conversion `list-view-options-bag-folded` before a row is served. So the
* block is all there is to read, here and in every sibling visualization.
*
* The block goes through the whitelist, so it cannot reintroduce the `style`
* namespace collision that objectui#5177 closed.
*
* NOT a second validation of the seven keys — that reading belongs to
* `getMapConfig` in `ObjectMap.tsx` and stays there (objectui#5018). This is
* the whitelist-flatten that already existed, applied to one more source.
*/
function resolveListMapConfig(schema: { map?: unknown }): Record<string, unknown> {
return pickFlatMapConfig(schema.map);
}
/**
* What a list view's `chart` block binds to — resolved ONCE, for both readers.
*
* `case 'chart'` below routes on `shape` and reads the fields; the capability
* gate in `availableViews` reads `resolves`. One function, because the gate's
* question ("is this chart offerable?") is the render branch's own question
* ("can I bind this block?") and a second copy of it drifts (objectui#7544;
* the same class of drift objectui#7495 tracks elsewhere).
*
* The gate had NO chart check at all before #7544: `chart` entered `resolvable`
* only via the "always allow switching back to the schema viewType" leg, so a
* `grid` view declaring a complete block and whitelisting `['grid', 'chart']`
* had its own `appearance.allowedVisualizations` filtered to nothing and fell
* back to `['grid']` (ADR-0047, whitelist ∩ resolvable). Same shape and same
* fix as `map`'s (objectui#5042, `resolveListMapConfig` above).
*
* ONE SOURCE (#25923): the view-level `chart` block. It used to replace the
* legacy `options.chart` bag WHOLESALE (`||`); the spec retired the bag, and its
* D2 fold keeps that precedence for a stored row (a bag beside a block is
* dropped, a bag alone becomes the block). The gate and the render branch read
* the same block, so the two can never judge different configs.
*
* `resolves` is the "renders from names the AUTHOR wrote" question: an ADR-0021
* (objectstack-ai/objectstack#1890) `dataset` with at least one measure in
* `values`. The dimensions are what it plots BY, and a block may legitimately
* declare none (a single aggregate), so they are not required here.
*
* ⛔ THERE IS NO SECOND SHAPE (objectui#6152 round 15). The pre-ADR-0021 inline
* axes (`xAxisField` / `categoryField`, `yAxisFields` / `valueField`,
* `aggregation`) were the legacy leg of this resolver, read in both nestings;
* every door refuses them by name (the spec's `ListChartConfigSchema` is a
* strict object of `chartType` / `dataset` / `dimensions` / `values`), so the leg and its `'name'` / `'value'`
* floors retired with the render path they fed. A block that names no
* `dataset` is `'unbound'`: the gate never offers a switch into it, and a view
* whose `viewType` forces it reaches `case 'chart'`'s unbound node, which
* `ObjectChart` refuses on screen (objectui#8168) instead of plotting a binding
* nobody wrote.
*/
interface ListChartBinding {
/** The view-level `chart` block. */
config: Record<string, any>;
/** `'dataset'` when the block names an ADR-0021 `dataset`, else `'unbound'`. */
shape: 'dataset' | 'unbound';
/** Whether the block declares everything its shape needs to plot authored names. */
resolves: boolean;
/** ADR-0021 semantic dataset, as authored. */
dataset?: any;
dimensions: string[];
values: string[];
}
function resolveListChartBinding(schema: { chart?: unknown }): ListChartBinding {
const config: Record<string, any> = (schema.chart || {}) as Record<string, any>;
if (config.dataset) {
const dimensions: string[] = Array.isArray(config.dimensions) ? config.dimensions : [];
const values: string[] = Array.isArray(config.values) ? config.values : [];
return { config, shape: 'dataset', resolves: values.length > 0, dataset: config.dataset, dimensions, values };
}
return { config, shape: 'unbound', resolves: false, dimensions: [], values: [] };
}
/**
* The list view's props.
*
* ## Why there is no `[key: string]: any` here (objectui#4528)
*
* There used to be one, and it erased this entire interface. A string index
* signature puts `string` into `keyof Props`, so `'ref' extends keyof Props` is
* always true and React's `PropsWithoutRef` takes its `Omit` branch — and
* `Omit` over a type carrying a string index signature keeps ONLY the index
* signature. Every declared property below was dropped from the resolved type.
* Measured on the pre-fix source:
* `keyof React.ComponentProps< typeof ListView >` was `string | number`, and
* `React.ComponentProps< typeof ListView >['onRowClick']` was `any`, while this
* interface went on declaring `(record: Record< string, unknown >) => void`.
*
* The same trap, in `packages/components`, is objectui#4422 / PR #4438; this is
* the sweep of the two packages that issue left unswept.
*
* ## The props that were only ever reachable through it
*
* `ListView` reads several props it never declared, because the index signature
* was answering for them — `dataSource`, `onAddRecord`, `onBulkAction`,
* `onPageSizeChange` are read directly, and `onEdit` / `onDelete` /
* `onBulkDelete` ride the `{...props}` forward into the active view component
* (`ObjectGrid` declares all three). They are declared by name below, at the
* type each one actually lands on, rather than left to an index signature that
* types them `any` and erases everything around them.
*/
/**
* One group of the rows a grouped grid or a board shows, as `onRowsChange`
* reports it (objectstack#28461): the group's key (a board's lane id), its
* heading as the list reads it, and its rows in display order.
*/
export interface ListViewRowGroup {
key: string;
label: string;
rows: ReadonlyArray<Record<string, unknown>>;
}
/**
* A part of a list that can differ from its view (objectstack#28950): what a
* host's 「personalized」 marker names. See `onPersonalizationChange`.
*/
export type ListPersonalizationPart =
| 'sort'
| 'filters'
| 'search'
| 'grouping'
| 'columns'
| 'hiddenFields'
| 'density'
| 'layout'
| 'rowColor'
| 'inlineEdit';
export interface ListViewProps {
schema: ListViewSchema;
className?: string;
/**
* Data-source adapter. Read directly (`dataSource.find`,
* `dataSource.getObjectSchema`, `dataSource.onMutation`) and forwarded to the
* active view component. Typed `any` deliberately: that is what it resolved
* to before objectui#4528, so declaring it changes what is DECLARED without
* changing what any call site is held to. Narrowing it to a real adapter type
* is a separate change with its own consumer sweep.
*/
dataSource?: any;
onViewChange?: (view: ListViewVisualization) => void;
/**
* Fires with the advanced-filter group the toolbar's `FilterBuilder` emitted.
*
* `FilterBuilderRowGroup` because that is what the one call site actually passes: the
* builder's own `onChange` value, handed straight through beside
* `setCurrentFilters` — itself `React.useState<FilterBuilderRowGroup>`. Deliberately NOT
* the filter AST `normalizeFilters` / `buildEffectiveFilter` speak: those run
* later, on the query-building path, and nothing they produce reaches this
* callback. A host receives the BUILDER's group verbatim, which is what lets
* it round-trip back in through `initialFilters`.
*/
onFilterChange?: (filters: FilterBuilderRowGroup) => void;
/**
* Fires with the view's sort after a builder edit, a header click or a
* "reset to the view's default".
*
* `SortItem[]` because every emit crosses exactly one boundary —
* `emitSortChange` — and both of its legs carry that element type: the array
* passed in, and `filterPlatformSortableSort`'s return, which is generic in
* the element (readonly T[] in, T[] out) and so preserves whatever it is
* given. Normalized-vs-raw therefore does not move the TYPE here; it only
* decides whether platform-unsortable entries are still present (#6455).
* Under a served projection they never are: the emit drops them, as every
* request this list sends already does (objectstack#30024).
*/
onSortChange?: (sort: SortItem[]) => void;
/**
* Fires with the grouping after a user edit in either grouping editor: the
* toolbar's Group panel (a level added, changed or removed, or Clear) and the
* compact toolbar's settings popover. `undefined` when the grouping is
* cleared.
*
* The value is the spec's `GroupingConfig`, the shape `schema.grouping`
* takes, so a host hands it back through `schema.grouping` unchanged
* (objectui#11860). Not fired when the list re-reads a changed
* `schema.grouping` or `groupBy`: that value came from the host.
*/
onGroupingChange?: (grouping: GroupingConfig | undefined) => void;
onSearchChange?: (search: string) => void;
/** Called when the user toggles fields via the Hide Fields popover. */
onHiddenFieldsChange?: (hidden: string[]) => void;
/**
* objectstack#30077 — the names among `schema.columns` that the READER added
* to their own list (`onAddedFieldsChange`), not the view. The host appends
* them to the columns it hands in `schema`; this prop is its split of that
* one value into its two sources, so unticking an added column takes it off
* the list again instead of hiding it. A HOST prop, never a schema key.
* Read by content, never by identity.
*/
addedFields?: ReadonlyArray<string>;
/**
* objectstack#30077 — the door that lets a reader add a field to their list.
* When it is wired, the Hide Fields popover (the toolbar's and the Display
* panel's) lists, after the view's columns, every other field of the object
* the caller may read (`canReadField`) and the definition does not mark
* `hidden`, unticked; ticking one calls this with the whole new list of
* added names, and unticking an added column calls it without that name.
* The host stores the list as the reader's own and appends it to
* `schema.columns`. A HOST prop, never a schema key. Absent ⇒ the popover
* lists the view's columns alone, exactly as before.
*/
onAddedFieldsChange?: (added: string[]) => void;
/**
* @deprecated Never called since objectstack#35684: a list has no inline-edit
* mode and no toggle. Its grid is editable wherever the reader may edit and
* the view does not declare `userActions.editInline: false`.
*/
onInlineEditChange?: (next: boolean) => void;
/** Called when the user resizes/reorders columns in the underlying grid. */
onColumnStateChange?: (state: { order?: string[]; widths?: Record<string, number> }) => void;
/**
* objectstack#35702 — the grid's footer calculation picked by the reader
* (`null` = None). Absent ⇒ the footer draws its figures and offers no
* menu. The host keeps the pick as the column's `summary` (on the view, or
* in an unsaved draft it hands back in `columns`, objectstack#36194) and
* resolves whether it did; on `false` the grid takes the pick back. A HOST
* prop, never a schema key.
*/
onColumnSummaryPick?: (field: string, summary: ColumnSummary | null) => void | boolean | Promise<void | boolean>;
/**
* objectstack#35702 — the fields whose calculation the host can keep (the
* columns a saved view would carry); the menu is offered on those only.
* Absent ⇒ every field column. A HOST prop, never a schema key.
*/
columnSummaryPickFields?: readonly string[];
/**
* Callback when a row/item is clicked (overrides NavigationConfig).
*
* TWO parameters since objectui#9357, and the second is not decoration: this
* prop reaches `useNavigationOverlay` as its `onRowClick`, and `handleClick`
* invokes it as `onRowClick(record, event)` — the modifier payload a host
* needs to implement Cmd/Ctrl/middle-click for itself. Declaring one
* parameter hid the second on the ONE line a host reads. Spelled `any` and
* not `HandleClickModifiers` for the reason objectui#9341 measured on
* `ObjectKanbanSchema.onCardClick`: that interface lives in
* `@object-ui/react`, the published twins in `@object-ui/types` may not name
* it, and a host that discovered the payload from the implementation
* annotated it `React.MouseEvent` — which a narrower declaration refuses
* contravariantly. `BaseSchema`'s own `onClick` / `onChange` / `onSubmit`
* already use this spelling for exactly this situation.
*/
onRowClick?: (record: Record<string, unknown>, event?: any) => void;
/** Show view type switcher (Grid/Kanban/etc). Default: false (view type is fixed) */
showViewSwitcher?: boolean;
/** Initial user-filter selections to restore (field → values; `_tab` for the active preset). */
userFilterSelections?: Record<string, Array<string | number | boolean>>;
/** Fires with the raw user-filter selections whenever the user changes them. */
onUserFilterSelectionsChange?: (selections: Record<string, Array<string | number | boolean>>) => void;
/**
* Initial advanced-filter (FilterBuilder) group to restore at mount, e.g.
* from a per-user localStorage cache. Read once by the lazy initializer —
* later prop changes don't override in-flight user edits, so hosts remount
* (via `key`) when they need to swap the restored value (view switch).
*/
initialFilters?: FilterBuilderRowGroup;
/** Initial search term to restore at mount (same one-shot semantics as `initialFilters`). */
initialSearchTerm?: string;
/** Called when the user asks for a new record (toolbar "+ New" and the empty-state CTA). */
onAddRecord?: () => void;
/** Called with a non-delete bulk action key and the currently selected rows. */
onBulkAction?: (action: string, records: any[]) => void;
/** Called when the user picks a different page size in the pager. */
onPageSizeChange?: (pageSize: number) => void;
/**
* Row-level affordances forwarded to the active view component. `ObjectGrid`
* declares all three with exactly these signatures; they are named here so the
* hosts that pass them (`ObjectView`, `StudioDesignSurface`) are held to a
* contract instead of to an index signature.
*/
onEdit?: (record: any) => void;
onDelete?: (record: any) => void;
onBulkDelete?: (records: any[]) => void;
/**
* A host-drawn node rendered FIRST in the toolbar row's left group, before
* the user filters, in a `min-w-0 flex-1` wrapper: it takes the width the
* right-hand tool cluster leaves (objectui#12440). The console passes its
* saved-view `ViewTabBar` here, so the view tabs and Filter · Sort ·
* Display · Search share one row.
*
* A HOST prop on the React component, never a schema key: it is a React
* node a host composes, nothing an author writes, and the list view's own
* `tabs` key is retired from the protocol (objectui#11073). It is
* destructured by name so it never rides the `{...props}` forward into the
* active view component. Absent ⇒ the toolbar row is exactly what it was.
*
* A host that passes it carries the view's DESCRIPTION too (objectui#12528):
* the console's `ViewTabBar` draws it as the active tab's tooltip and ▾ menu
* header, so the list draws none. Without it the list draws the description
* itself, as an info control at the start of the toolbar row — never as a
* row of its own, so the toolbar sits at one height with or without one.
*
* It may be a function of the list's state (objectstack#35548): the
* console's view switcher reads, inside its one trigger, how many records
* the list holds and which layout it draws.
*/
toolbarLeading?: React.ReactNode | ((state: ListToolbarLeadingState) => React.ReactNode);
/**
* objectstack#35878 — the right end of the view bar, drawn by the host. It
* is called with the list's own tools for that end (its search) and returns
* what the end shows: the console puts the page's create button and ⋮ More
* after the search. Absent ⇒ the search alone, as before.
*
* objectstack#36113 — the second argument carries the list's export door
* (`ListToolbarTrailingState`), for a host that draws it at the bar's end
* too; the 视图设置 footer keeps its own export entries. The phone's row
* passes no export door.
*
* A HOST prop, never a schema key.
*/
toolbarTrailing?: (tools: React.ReactNode, state: ListToolbarTrailingState) => React.ReactNode;
/**
* objectstack#35878 — the right end of the condition row under the view
* bar, drawn by the host: the console's 「Personalized · Reset」. Given, it
* takes the place of the row's own 「Reset」 (which puts back the filter and
* sort only). A HOST prop, never a schema key.
*/
conditionRowEnd?: React.ReactNode;
/**
* A host-drawn node beside each row's title in the grid (objectui#13330),
* handed to `ObjectGrid`'s `rowAdornment`: the cell of the object's declared
* name field when a column shows it, else the first shown column, and the
* card's title in the card view. Called with the row record; `null` draws
* nothing. The console's Users list on a managed environment marks a user
* who holds nothing beyond the baseline with it.
*
* A HOST prop, never a schema key: a React node a host composes, nothing an
* author writes. Only the grid is handed it; the other visualizations and
* the compact posture draw no title cell to put it beside, and draw none.
* Absent ⇒ every row is exactly what it was.
*/
rowAdornment?: (record: Record<string, unknown>) => React.ReactNode;
/**
* A host-drawn node beside each row's record LINK in the grid
* (objectstack#26681), handed to `ObjectGrid`'s `recordLinkAdornment`: after
* the link cell the row's record opens from, never inside it. Called with
* the row record; `null` draws nothing. The console's object list passes an
* "open as full page" arrow for a row that opens the drawer.
*
* A HOST prop, never a schema key, for the reason `rowAdornment` is one.
* Only the grid is handed it. Absent ⇒ every row is exactly what it was.
*/
recordLinkAdornment?: (record: Record<string, unknown>) => React.ReactNode;
/**
* Opens a record a lookup cell's chip names, in place (objectstack#36015),
* handed to `ObjectGrid`'s `openReferencedRecord`: in the grid a single
* click on such a chip opens its record here, and lookup cells draw an edit
* button. The console's object list opens it in its side drawer.
*
* A HOST prop, never a schema key, for the reason `rowAdornment` is one.
* Only the grid is handed it. Absent ⇒ a chip only selects its cell.
*/
openReferencedRecord?: (objectName: string, recordId: string) => void;
/**
* Whether a click on a row opens anything, as the host that owns the row
* click (`onRowClick`) knows it (objectstack#33317), handed to the view's own
* `rowOpensRecord`: the grid (its table and its phone cards), the gallery and
* the board (objectstack#33548). `false` ⇒ the grid draws its record-link
* cells as plain text and its row context menu offers no Open, and no card
* face draws a pointer or a hover lift; the row or card click still reaches
* `onRowClick`, and card actions stay. The console's object list passes
* `false` for a view authored `navigation.mode: 'none'` and for a list-only
* object.
*
* A HOST prop, never a schema key, for the reason `rowAdornment` is one.
* Absent ⇒ every row and card is exactly what it was.
*/
rowOpensRecord?: boolean;
/**
* The VIEW'S OWN hidden fields, row height and sort, for a host that lays
* the user's own preference over them in `schema` (objectui#12949). The
* Display control's trigger count and its "Reset to view default" compare
* hidden fields and density against this value rather than against
* `schema`, and the sort popover's "Reset to view default" compares and
* restores the sort against it. Without `onRestoreViewDefaults` a reset
* hands the value back through the same doors the controls write through
* (`onHiddenFieldsChange`, `schema.onDensityChange`, `onSortChange`).
*
* When it is passed, its members are the whole baseline: an absent
* `hiddenFields` means the view hides nothing, an absent `rowHeight` means
* the view's default density, an absent `sort` means the view declares no
* sort. Absent ⇒ `schema` is the view's own, exactly as before. A HOST prop,
* never a schema key: it is the host's split of one composed value into its
* two sources, nothing an author writes.
*
* `grouping` (objectstack#28950) is read only to tell a personalized list
* (`onPersonalizationChange`), for a host that lays a grouping the URL
* carries over the view's in `schema`. Unlike the three above, a
* `viewDefaults` without the `grouping` key leaves the grouping `schema`
* opened with as the view's own.
*
* `filters` (objectstack#30073) are the view's own conditions, for a host
* that shows them as Filter panel rows (and passes them as
* `initialFilters`) instead of applying them under the list: the panel's
* finished conditions are then judged against these, so the view's own
* rows are not a personalization and an edit, a removal or a "Clear all"
* is. Absent ⇒ any finished panel condition is the reader's own, as before.
*
* `viewType` and `rowColor` (objectstack#35955) are the view's own layout
* and row colour, for a host that lays the reader's unsaved choice of
* either into `schema` (`onViewChange`, `onRowColorChange`): the Display
* control's count and the `layout` / `rowColor` parts are judged against
* these. Like `grouping`, each is read only when its key is present;
* without it `schema` holds the view's own.
*/
viewDefaults?: Pick<ListViewSchema, 'hiddenFields' | 'rowHeight' | 'sort' | 'grouping'> & {
filters?: FilterBuilderRowGroup;
viewType?: ListViewSchema['viewType'];
rowColor?: ListViewSchema['rowColor'];
};
/**
* A reset to the view's own, told apart from a choice (objectstack#28948).
* For a host that stores the user's preference and passes `viewDefaults`:
* when it is wired, the Display control's "Reset to view default" and the
* sort popover's "Reset to view default" do NOT write the view's values
* through the controls' doors, which a host would store as the user's own
* choice. They call this instead, naming the parts the reset returned to the
* view's own, and the host CLEARS those parts of the stored preference, so
* the user follows later changes to the view.
*
* `sort` and `hiddenFields` are put back in the list at once; the density
* follows `schema.rowHeight` once the host's clear lays the view's own back
* there. A deliberate choice is unchanged: removing every sort level or
* showing every column still goes through `onSortChange` /
* `onHiddenFieldsChange` as an empty list. Settings outside the three parts
* (layout, grouping, row color, row numbers, inline edit, gallery card size)
* reset exactly as without it. A HOST prop, never a schema key.
*/
onRestoreViewDefaults?: (parts: ReadonlyArray<'sort' | 'hiddenFields' | 'rowHeight'>) => void;
/**
* What of the list on screen differs from the view (objectstack#28950), for
* a host that marks a personalized list and owns the one way back to the
* view. Called with the parts each time that set changes, and once at
* mount; an empty list means the list on screen is the view's own.
*
* Every part is judged against the VIEW: `sort`, `hiddenFields`, the table
* density and the grouping against `viewDefaults` when the host passes it
* (else against `schema`); `filters` is the reader's query apart from the
* search (the Filter panel's finished conditions, the user-filter chips, the
* "In a queue" toggle; the view's declared `filter` is never one); `search`
* is a term the list applies. The Display-only settings (`layout`,
* `rowColor`) are those the Display control counts. The gallery card size
* is not a part: it is kept per object, not per view. `columns` is never
* reported here, since the column layout is the host's own stored state; it
* is in the type so a host can add it. Nor is `inlineEdit` since
* objectstack#35684, which retired the mode it named.
*
* When it is passed the host owns the reset, so the Display control draws
* no "Reset to view default" of its own. The sort popover's reset and the
* Filter panel's "Clear all" stay: each puts back one control. A HOST prop,
* never a schema key. Absent ⇒ nothing is reported and the Display control
* keeps its reset, exactly as before.
*/
onPersonalizationChange?: (parts: ReadonlyArray<ListPersonalizationPart>) => void;
/**
* The reader's pick in the toolbar's row colour panel (objectstack#35955):
* the colour rule now in force, or `null` for "none" (Clear, or the None
* entry). Told for a pick only, never for a reset or a prop change, so a
* host can keep the reader's choice as an unsaved change and lay it back
* into `schema.rowColor` when the list mounts again. A HOST prop, never a
* schema key. Absent ⇒ the pick stays the list's own, as before.
*/
onRowColorChange?: (rowColor: NonNullable<ListViewSchema['rowColor']> | null) => void;
/**
* Rename the open view from the options menu's first row, its name
* (`schema.label`, objectstack#35551). Wired only for a reader who may
* rename the view: the owner of one of their own views, or someone who may
* edit a shared one; without it the name row is read-only. Resolve `false`
* on a refused rename and the field reverts. A HOST prop, never a schema
* key. The name row is drawn for a host that wires this or
* `onPersonalizationChange` (a host that shows views), and a label.
*/
onRenameView?: (label: string) => boolean | Promise<boolean>;
/**
* 保存 in the options menu (objectstack#35551, the 「已个性化」 marker's
* save, objectstack#30073): the list on screen becomes the open view's
* stored body. A host wires it only for a view the reader owns and may
* update, and only while the list differs from the view. Absent ⇒ none.
*/
onSaveView?: () => void;
/**
* The host's full reset (the 「已个性化」 marker's), drawn as the options
* menu's 恢复默认 in place of the list's own reset. A host that reports
* `onPersonalizationChange` and wires this only while the list differs
* from the view gives the reset its home in the menu. Absent ⇒ the list's
* own reset, or, under `onPersonalizationChange`, 恢复默认 dimmed.
*/
onResetView?: () => void;
/**
* Draw the COMPACT posture (objectui#12703): a header with the list's title
* and record count over two-line rows (the view's first visible column, its
* second muted below), and none of the toolbar, view tabs, row-number column,
* pager or record-count bar. The `list-view` page block passes it when the
* page region it sits in is narrower than half the page
* (`usePageRegionPosture` from `@object-ui/components`).
*
* A HOST prop, never a schema key: the posture is measured by the page
* renderer, never authored, and `@objectstack/spec` declares no key for it.
* It applies to a paged grid, the view that draws the rows this component
* fetches a page of; any other kind (a board, a calendar, a grouped grid)
* keeps its full rendering. Absent ⇒ the full list, exactly as before.
*/
compact?: boolean;
/**
* Draw the CAPPED posture (objectstack#26613): the first rows of the list, at
* most `pagination.pageSize` of them (the page block's `dataSource.limit`
* lands there) and `CAPPED_LIST_DEFAULT_LIMIT` when none is stated, in a
* short table of the view's first four columns, ending with a 「View all N →」
* link to the rest. None of the toolbar, view tabs, row-number column, pager
* or record-count bar. The `list-view` page block passes it when the page
* region it sits in is half the page or wider.
*
* A HOST prop, never a schema key, for the reason `compact` is one. It
* applies where `compact` applies, to a paged grid; `compact` wins when both
* are passed. Absent ⇒ the full list, exactly as before.
*/
capped?: boolean;
/**
* Called with the number of records the list's query matched, each time a
* load settles with a different answer (objectstack#26613). The `list-view`
* page block hands it the count channel of the `page:tabs` panel it sits in,
* so the tab's badge says how many records its list holds. Only a paged grid
* that draws the rows it fetched answers; other kinds never call it.
*/
onTotalChange?: (total: number) => void;
/**
* Called with the rows the list shows, in the order it shows them, each
* time that set changes once a load settles — another page, sort, filter or
* search (objectstack#26679). The console's object page hands it to its
* record drawer, whose `↑` `↓` at the root step through these rows. Answered
* where `onTotalChange` is: a paged grid that draws the rows it fetched.
*
* A grouped grid and a board answer too (objectstack#28461), with `groups`:
* every open group — a board's every open lane — in display order, its
* heading and the rows drawn under it; `rows` is those rows end to end. A
* collapsed group draws no rows and is not among them. Any other kind (a
* calendar, a gantt) has no single row order and answers with no rows and
* no groups, so a host never steps through a stale set.
*
* A HOST prop, never a schema key: the rows are the list's runtime state.
*/
onRowsChange?: (
rows: ReadonlyArray<Record<string, unknown>>,
groups?: ReadonlyArray<ListViewRowGroup>,
) => void;
/**
* The page a paged grid shows, 1-based, for a host that keeps it
* (objectstack#30850): the console keeps it in the address, so Back from a
* record opened as a full page, a reload and a copied link land on it.
* Passing it makes the page CONTROLLED: the list reads this value every
* render and keeps no page of its own, so the host answers every
* `onPageChange` by passing the new value back. A whole number from 1 up.
*
* The list still decides when the page moves: the pager; back to 1 when the
* object, filters, sort, search, grouping, page size or view change; to the
* last reachable page when a load comes back empty past the end. Each move
* is an `onPageChange`. Only a paged grid reads it; other kinds fetch one
* window and draw no pager.
*
* A HOST prop, never a schema key: the page is the reader's place in the
* list, not anything an author writes. Absent ⇒ the list keeps the page
* itself and starts at 1, exactly as before.
*/
page?: number;
/**
* Called with the page the list moves to (objectstack#30850). Under a
* controlled `page` the host passes the value back; without one it is a
* notification. A HOST prop, never a schema key.
*/
onPageChange?: (page: number) => void;
/**
* Fields whose conditions in `schema.filter` the HOST draws itself as its
* own tags (objectstack#35727) — the data page's 「Filtered by」 row for the
* conditions its address carries. The list still filters on them; its
* condition row draws no locked chip for them, so each condition shows
* once, and 「Reset」 (which never clears the view's filter) is not offered
* for them.
*
* A HOST prop, never a schema key: which surface draws a condition is the
* page's layout, not anything an author writes. Absent ⇒ every condition of
* the view's filter is a locked chip, exactly as before.
*/
hostDrawnConditionFields?: ReadonlyArray<string>;
}
// Helper to convert FilterBuilder group to ObjectStack AST.
// Accepts both the FilterBuilder vocabulary (camelCase) and the
// @objectstack/spec ViewFilterRule vocabulary (snake_case).
/**
* The shared value-less set, re-keyed by the spelling
* `normalizeFilterOperator` folds each member to — the lookup table
* `convertFilterGroupToAST` reads (objectui#9359).
*
* DERIVED, never a second literal: a hand-kept canonical copy beside the
* exported set is exactly how the two would come to disagree, and the
* disagreement is invisible — a filter the panel shows and the query does not
* carry.
*
* Why it exists here instead of the export being widened: the exported set
* states a fact about what the BUILDER'S DROPDOWN draws, and its members are
* that dropdown's own camelCase ids. Two other layers read it — this function
* (what the live grid QUERIES) and `app-shell`'s `foldFilterGroupToSpecRules`
* (what a saved view PERSISTS, already documented as this set PLUS the
* canonical spellings only that layer sees). Folding the canonical spellings
* INTO the export would make that layer's deliberate compensation redundant by
* side effect, in a file nobody is editing. The defect was never a set missing
* members; it was a reader that forgot to normalize its input, so the reader is
* what is repaired. Same shape the sibling repair used at the builder's own
* value-input gate (objectui#9302).
*
* `exists` / `notExists` fold to themselves — the spec's vocabulary has no
* existence operator and `VIEW_FILTER_OPERATOR_ALIASES` deliberately has no row
* for either — so this set is the same SIZE as the one it derives from.
*/
const VALUELESS_FILTER_BUILDER_OPERATORS_CANONICAL: ReadonlySet<string> = new Set(
[...VALUELESS_FILTER_BUILDER_OPERATORS].map(op => String(normalizeFilterOperator(op))),
);
/**
* Is this row COMPLETE without a value — asked of whichever spelling the row
* actually carries (objectui#9359).
*
* The two halves of one predicate used to speak different vocabularies. The
* value-less short-circuit did a raw `has()` on the exported set's camelCase
* ids, while the completeness test it falls through to
* (`isFilterValueComplete`) DOES fold, through this same
* `normalizeFilterOperator`, to decide arity. So a row spelled `is_null` — the
* spec's canonical form, which is what `foldFilterGroupToSpecRules` persists
* and what any spec-side producer emits — missed the short-circuit, landed on
* `scalar`, had its `value: ''` read as an unfinished row and was DROPPED. The
* function returned `[]`, the grid queried with no filter at all, and every
* record came back while the panel showed a filter applied. Silent.
*
* That is the same failure objectui#4744 repaired for the dropdown's own
* spellings — recorded in the exported set's docblock — reached by the other
* vocabulary. Folding here is one more site joining a fold this file already
* performs (`mapOperator` already matches case- and underscore-insensitively,
* and `isFilterValueComplete` folds through the spec's map) rather than a new
* dialect.
*/
function isValuelessFilterOperator(operator: string): boolean {
return VALUELESS_FILTER_BUILDER_OPERATORS_CANONICAL.has(String(normalizeFilterOperator(operator)));
}
/**
* Filter-builder / view operator → filter-AST operator.
*
* Every value returned must be a member of the spec's `VALID_AST_OPERATORS`
* (`@objectstack/spec/data`). That set gates `isFilterAST()`, and a filter it
* rejects is passed through unconverted and then silently DROPPED by driver-sql
* — an unfiltered result set with no error (objectstack#3948). Pinned by
* `filter-operator-ast-parity.test.ts`.
*
* Exported for that test. @internal
*/
export function mapOperator(op: string) {
// The spec's alias table carries the same operator in up to four spellings
// (`not_equals`, `notEquals`, `notequals`, `ne`), and stored view metadata
// holds all of them — `saveMeta` persists the authored body verbatim, so the
// spec's own normalization never reaches the row. Matching them case- and
// underscore-insensitively collapses that whole class instead of enumerating
// it: a switch listing spellings by hand had already missed eight.
switch (op.toLowerCase().replace(/[_\s]/g, '')) {
case 'equals': case 'eq': return '=';
case 'notequals': case 'ne': case 'neq': return '!=';
case 'contains': return 'contains';
// Canonical in `VIEW_FILTER_OPERATORS` as of @objectstack/spec 17.1.0
// (objectui#5328), and an explicit arm rather than a `default` fall-through
// even though the emitted spelling is identical: `icontains` is its own
// member of `VALID_AST_OPERATORS`, so the raw passthrough happens to be
// accepted today, and relying on that is the exact slack this file's own
// header records as how it stopped discriminating in #3641.
case 'icontains': return 'icontains';
case 'notcontains': return 'notcontains';
case 'startswith': return 'startswith';
case 'endswith': return 'endswith';
case 'greaterthan': case 'gt': return '>';
case 'greaterorequal': case 'greaterthanorequal': case 'gte': return '>=';
case 'lessthan': case 'lt': return '<';
case 'lessorequal': case 'lessthanorequal': case 'lte': return '<=';
case 'in': return 'in';
// `nin`, not `'not in'`: the spaced spelling is in no spec vocabulary, so
// `isFilterAST()` rejected it and driver-sql skipped the filter entirely.
// The array case never reached the wire (normalizeFilterCondition expands
// it below), but a non-array value escaped as an unfiltered query.
case 'notin': case 'nin': return 'nin';
// Canonical `VIEW_FILTER_OPERATORS` members with no AST counterpart; the
// gap here is what returned unfiltered rows for a stored date filter.
case 'before': return '<';
case 'after': return '>';
case 'between': return 'between';
case 'isnull': return 'isnull';
case 'isnotnull': return 'isnotnull';
// objectui#10813 — the empty pair, which the spec lowers to its ONE
// 「is empty」 operator, `$empty` (objectstack#20446), expanded by the
// column's declared type on the server. It used to be answered by two arms
// in `convertFilterGroupToAST` as an equality to `null` — a null-only test
// that never counted `''` or `[]`, while the SAME rule saved into the view
// (`foldFilterGroupToSpecRules` persists `is_empty`) ran as `$empty`: one
// panel, two record sets, depending on whether the view had been saved.
case 'isempty': return 'isempty';
case 'isnotempty': return 'isnotempty';
default: return op;
}
}
/**
* Opt-in `FilterBuilder` operators the list toolbar offers — deliberately NONE
* (objectui#4736).
*
* `OPT_IN_OPERATORS` in `@object-ui/components` withholds the operator ids that
* only the MongoDB-style criteria dialect can carry. This toolbar persists into
* the other two, and into BOTH of them at once:
*
* - the array/triplet filter AST, via `mapOperator` above, for the live grid;
* - `ViewFilterRule[]`, via app-shell's `foldFilterGroupToSpecRules`, when the
* user saves the panel's group as a view.
*
* Neither vocabulary has a case-insensitive contains or an existence operator,
* so this surface opts into nothing. Named and passed explicitly rather than
* omitted at the call site: this constant is the handle
* `list-offered-operator-expressible-parity.test.ts` reads to compute what the
* toolbar actually offers, and an inline `extraOperators` added later would
* otherwise widen the dropdown without the parity test noticing.
*
* @internal exported for that test
*/
export const LIST_VIEW_EXTRA_OPERATORS: readonly string[] = [];
/** Every not-in spelling this normalizer expands. See the note at the call site. */
const NOT_IN_SPELLINGS = new Set(['nin', 'not_in', 'notIn', 'notin', 'not in']);
/**
* Normalize a single filter condition: convert `in`/not-in operators
* into backend-compatible `or`/`and` of equality conditions.
* E.g., ['status', 'in', ['a','b']] → ['or', ['status','=','a'], ['status','=','b']]
*/
export function normalizeFilterCondition(condition: any[]): any[] {
if (!Array.isArray(condition) || condition.length < 3) return condition;
const [field, op, value] = condition;
// Recurse into logical groups
if (typeof field === 'string' && (field === 'and' || field === 'or')) {
return [field, ...condition.slice(1).map((c: any) =>
Array.isArray(c) ? normalizeFilterCondition(c) : c
)];
}
if (op === 'in' && Array.isArray(value)) {
if (value.length === 0) return [];
if (value.length === 1) return [field, '=', value[0]];
return ['or', ...value.map((v: any) => [field, '=', v])];
}
// `nin` is what mapOperator now emits; the rest are spellings an external
// caller may still pass, since this function is part of plugin-list's public
// surface. Accepting all of them keeps the expansion working either way.
if (NOT_IN_SPELLINGS.has(op) && Array.isArray(value)) {
if (value.length === 0) return [];
if (value.length === 1) return [field, '!=', value[0]];
return ['and', ...value.map((v: any) => [field, '!=', v])];
}
return condition;
}
/**
* Normalize a view's `sort` declaration to SortItem[]. @objectstack/spec
* ListViewSchema.sort is `string | Array<{ field, order }>` — the TOP-LEVEL
* value may be a bare string ("name desc"); array entries may be strings
* (legacy "field desc") or `{ field, order }` objects. Calling `.map` on the
* bare-string form threw "schema.sort.map is not a function" and crashed the
* list (spec/renderer shape-mismatch audit, objectui#2578 follow-up).
*/
export function parseSortConfig(sort: unknown): SortItem[] {
const entries = typeof sort === 'string' ? [sort] : Array.isArray(sort) ? sort : [];
const items: SortItem[] = [];
for (const s of entries) {
if (typeof s === 'string') {
const parts = s.trim().split(/\s+/);
if (!parts[0]) continue;
items.push({
id: crypto.randomUUID(),
field: parts[0],
order: (parts[1]?.toLowerCase() === 'desc' ? 'desc' : 'asc') as 'asc' | 'desc',
});
} else if (s && typeof s === 'object' && typeof (s as any).field === 'string') {
items.push({
id: crypto.randomUUID(),
field: (s as any).field,
order: ((s as any).order as 'asc' | 'desc') || 'asc',
});
}
}
return items;
}
/**
* Format an action identifier string into a human-readable label.
* e.g., 'send_email' → 'Send Email'
*/
function formatActionLabel(action: string): string {
return action.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}
/**
* Resolve the spec `AddRecordConfigSchema.position` (`ui/view.zod.ts`:
* `top | bottom | both`) to the two render slots. A binary ternary used to
* collapse `both` to `top`, so the bottom button never rendered (#2941).
*
* An absent or unrecognized value keeps this renderer's historical `top`
* placement. (The spec's own default is `bottom`; spec-parsed metadata