pict-section-form 1.3.15 → 1.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/docs/Providers.md +12 -7
  2. package/docs/_sidebar.md +2 -0
  3. package/docs/input_providers/016-facet-filter.md +106 -0
  4. package/docs/input_providers/README.md +1 -0
  5. package/example_applications/README.md +6 -0
  6. package/example_applications/facet_filter/.quackage.json +9 -0
  7. package/example_applications/facet_filter/Facet-Filter-Application.js +210 -0
  8. package/example_applications/facet_filter/Facet-Filter-Server.js +233 -0
  9. package/example_applications/facet_filter/Facet-Filter-Smoke-Runner.js +101 -0
  10. package/example_applications/facet_filter/FacetFilterData.json +44 -0
  11. package/example_applications/facet_filter/README-FacetFilter.md +70 -0
  12. package/example_applications/facet_filter/html/Facet-Filter-Smoke.js +128 -0
  13. package/example_applications/facet_filter/html/index.html +74 -0
  14. package/example_applications/facet_filter/package.json +27 -0
  15. package/example_applications/nested_distill_sandbox/Sandbox-Driver-Headlight.js +17 -0
  16. package/example_applications/nested_distill_sandbox/Sandbox-Driver.js +369 -0
  17. package/example_applications/nested_distill_sandbox/Sandbox-Runner.js +372 -0
  18. package/example_applications/nested_distill_sandbox/approaches/A1-tabular-trigger-group.js +67 -0
  19. package/example_applications/nested_distill_sandbox/approaches/A3-crossmap-selectoptionsrefresh.js +61 -0
  20. package/example_applications/nested_distill_sandbox/approaches/A4-graph-solvers-flat-list.js +53 -0
  21. package/example_applications/nested_distill_sandbox/approaches/A5-facet-filter.js +75 -0
  22. package/example_applications/nested_distill_sandbox/approaches/A5b-facet-filter-symmetric.js +15 -0
  23. package/example_applications/nested_distill_sandbox/approaches/A5h-facet-filter-headlight-picker.js +15 -0
  24. package/example_applications/nested_distill_sandbox/approaches/R0-original-jmf-manifest-headlight.js +27 -0
  25. package/example_applications/nested_distill_sandbox/approaches/R1-real-jmf-manifest-headlight.js +136 -0
  26. package/example_applications/nested_distill_sandbox/approaches/_Common.js +344 -0
  27. package/example_applications/nested_distill_sandbox/approaches/_Scenarios.js +262 -0
  28. package/package.json +1 -1
  29. package/source/providers/Pict-Provider-DynamicSolver.js +2 -0
  30. package/source/providers/Pict-Provider-ListDistilling.js +266 -1
  31. package/source/providers/Pict-Provider-MetaLists.js +16 -2
  32. package/source/providers/inputs/Pict-Provider-Input-FacetFilter.js +232 -0
  33. package/source/providers/inputs/Pict-Provider-Input-Select.js +41 -1
  34. package/source/views/Pict-View-Form-Metacontroller.js +5 -3
  35. package/test/Pict-Provider-ListDistilling-Facet_tests.js +375 -0
  36. package/test/PictSectionForm-Injection-Conformance_tests.js +11 -0
  37. package/test/fixtures/injection/Injection-Fixture-Cases.js +1 -0
  38. package/test/fixtures/injection/Injection-Fixture-Manifest.json +15 -0
  39. package/types/source/providers/Pict-Provider-DynamicSolver.d.ts.map +1 -1
  40. package/types/source/providers/Pict-Provider-ListDistilling.d.ts +90 -1
  41. package/types/source/providers/Pict-Provider-ListDistilling.d.ts.map +1 -1
  42. package/types/source/providers/Pict-Provider-MetaLists.d.ts.map +1 -1
  43. package/types/source/providers/inputs/Pict-Provider-Input-FacetFilter.d.ts +103 -0
  44. package/types/source/providers/inputs/Pict-Provider-Input-FacetFilter.d.ts.map +1 -0
  45. package/types/source/providers/inputs/Pict-Provider-Input-Select.d.ts +12 -0
  46. package/types/source/providers/inputs/Pict-Provider-Input-Select.d.ts.map +1 -1
  47. package/types/source/views/Pict-View-Form-Metacontroller.d.ts.map +1 -1
package/docs/Providers.md CHANGED
@@ -207,6 +207,10 @@ Manages dynamic list definitions for select inputs.
207
207
  - Provides dynamic list generation
208
208
  - Manages list refresh
209
209
 
210
+ **PickList keys:** `Hash`, `ListAddress`, `ListSourceAddress` (read from the form data, or from application
211
+ state with `ListSourceAddressGlobal: true`), `IDTemplate`, `TextTemplate`, `Unique`, `Sorted`, and
212
+ `SkipEmpty` (skip records whose id or text renders empty without logging them).
213
+
210
214
  **Key Methods:**
211
215
 
212
216
  ```javascript
@@ -222,20 +226,20 @@ pict.providers.MetaLists.setList('StatusCodes', [
222
226
 
223
227
  ### ListDistilling
224
228
 
225
- Filters lists based on rules and conditions.
229
+ Filters a select input's options by the `ListFilterRules` on its descriptor.
226
230
 
227
231
  **Hash:** `ListDistilling`
228
232
 
229
- **Responsibilities:**
230
- - Applies filter rules to lists
231
- - Manages dependent list relationships
232
- - Handles cascading list updates
233
+ **Rule types:** `Explicit` (compare each option to one value), `CrossMap` (keep options a join list maps to
234
+ another value), `Facet` (options drawn from a shared record list, narrowed by the other inputs of the same
235
+ row -- see [FacetFilter](input_providers/016-facet-filter.md)), or the hash of a provider with its own
236
+ `filterList`.
233
237
 
234
238
  **Key Methods:**
235
239
 
236
240
  ```javascript
237
- // Distill a list based on rules
238
- const filtered = pict.providers.ListDistilling.distillList(sourceList, rules, context);
241
+ // Filter a list of { id, text } options for an input; pass the row index for a tabular input.
242
+ const filtered = pict.providers.ListDistilling.filterList(view, input, options, rowIndex);
239
243
  ```
240
244
 
241
245
  ### DataBroker
@@ -293,6 +297,7 @@ Input extension providers handle specific input types. They all extend
293
297
  | `Pict-Input-EntityBundleRequest` | EntityBundleRequest | Entity loading |
294
298
  | `Pict-Input-AutofillTriggerGroup` | AutofillTriggerGroup | Auto-fill |
295
299
  | `Pict-Input-TemplatedEntityLookup` | TemplatedEntityLookup | Entity lookup |
300
+ | `Pict-Input-FacetFilter` | (any select) | Keeps facet dropdowns consistent on change |
296
301
 
297
302
  ## Creating Custom Providers
298
303
 
package/docs/_sidebar.md CHANGED
@@ -42,6 +42,8 @@
42
42
  - [RichText](input_providers/014-rich-text.md)
43
43
  - [Diagram](input_providers/015-diagram.md)
44
44
 
45
+ - [FacetFilter](input_providers/016-facet-filter.md)
46
+
45
47
  - Examples
46
48
 
47
49
  - [Simple Table](#/page/examples/simple_table/README)
@@ -0,0 +1,106 @@
1
+ # FacetFilter Input Provider
2
+
3
+ Dropdowns that choose from one shared list of records, each narrowed by what the others hold. Pick a genre
4
+ and the author list shows only authors with books in it; pick a book and its genre and author fill in. In a
5
+ tabular group every row is independent: a row's lists narrow by that row's choices only.
6
+
7
+ Two pieces work together:
8
+
9
+ - a `Facet` rule in the input's `ListFilterRules` narrows what the dropdown offers
10
+ (`ListDistilling.filterList`, applied whenever the list is built for a row), and
11
+ - the `Pict-Input-FacetFilter` provider keeps the row consistent when one of them changes.
12
+
13
+ ## Provider Information
14
+
15
+ | Property | Value |
16
+ |----------|-------|
17
+ | Provider Hash | `Pict-Input-FacetFilter` |
18
+ | Input Type | Any select-style input (`Option`), alongside its own provider |
19
+ | Supports Tabular | Yes (row-scoped) |
20
+
21
+ ## Basic Usage
22
+
23
+ The shared list is any array of records in application state -- typically loaded once by the form's
24
+ `InitialBundle` and flattened with a `ProjectDataset` step. Each dropdown names the record field it holds:
25
+
26
+ ```json
27
+ {
28
+ "PickLists":
29
+ [
30
+ { "Hash": "Genres", "ListAddress": "Genres", "ListSourceAddress": "AppData.Catalog", "ListSourceAddressGlobal": true, "IDTemplate": "{~D:Record.Genre~}", "TextTemplate": "{~D:Record.Genre~}", "Unique": true, "Sorted": true, "SkipEmpty": true },
31
+ { "Hash": "Authors", "ListAddress": "Authors", "ListSourceAddress": "AppData.Catalog", "ListSourceAddressGlobal": true, "IDTemplate": "{~D:Record.Author~}", "TextTemplate": "{~D:Record.Author~}", "Unique": true, "Sorted": true, "SkipEmpty": true },
32
+ { "Hash": "Books", "ListAddress": "Books", "ListSourceAddress": "AppData.Catalog", "ListSourceAddressGlobal": true, "IDTemplate": "{~D:Record.IDBook~}", "TextTemplate": "{~D:Record.Title~}" }
33
+ ]
34
+ }
35
+ ```
36
+
37
+ ```json
38
+ "Genre":
39
+ {
40
+ "Name": "Genre", "Hash": "ShelfGenre", "DataAddress": "Genre", "DataType": "String",
41
+ "PictForm":
42
+ {
43
+ "InputType": "Option",
44
+ "SelectOptionsPickList": "Genres",
45
+ "ListFilterRules": [ { "FilterType": "Facet", "JoinListAddress": "AppData.Catalog", "JoinListAddressGlobal": true, "JoinListValueAddress": "Genre" } ],
46
+ "Providers": [ "Pict-Input-FacetFilter" ]
47
+ }
48
+ }
49
+ ```
50
+
51
+ Give `Author` and `Book` the same rule with `JoinListValueAddress` `Author` and `IDBook`. Inputs that share a
52
+ `JoinListAddress` find each other -- there is no per-pair wiring.
53
+
54
+ ## The Facet rule
55
+
56
+ | Key | Default | Meaning |
57
+ |-----|---------|---------|
58
+ | `JoinListAddress` | -- | Where the shared records are. |
59
+ | `JoinListAddressGlobal` | `false` | Resolve `JoinListAddress` against application state (`AppData.`, `Pict.`, `Bundle.`) rather than the form data. |
60
+ | `JoinListValueAddress` | -- | The record field this input holds; an option is offered when a record agreeing with the other choices has it. |
61
+ | `NarrowBy` | `All` | `All`: narrowed by every other choice. `Preceding`: narrowed only by the inputs before it (column order in a table), so any upstream value can always be picked and the downstream ones adjust. |
62
+ | `Facets` | `[]` | Extra constraints that are not dropdowns in the set: `{ JoinListValueAddress, Value \| ValueAddress, Operator }`. `ValueAddress` reads the form data. `Operator` is `EQ` (default), `NE`, `LT`, `LE`, `GT` or `GE`; numbers compare as numbers, and a bare `YYYY-MM-DD` compares against the date part of an ISO timestamp. An empty value does not constrain. |
63
+ | `KeepCurrentValue` | `true` | Always offer the value the input already holds, so a filter never hides a stored choice (for example one that has since fallen out of a date range). |
64
+ | `ClearInvalid` | `true` | FacetFilter: clear this input when a sibling's change contradicts it. |
65
+ | `AutoFillSingle` | `true` | FacetFilter: fill this input when exactly one value is left for it. |
66
+ | `CarryFields` | -- | FacetFilter: `{ "<row address>": "<record address>" }`. When this input holds a value and the choices identify exactly one record, copy those fields into the row (or the form, outside a table); clear them otherwise. |
67
+
68
+ Narrowing is joint: one record has to agree with every constraint at once, not a different record per
69
+ constraint.
70
+
71
+ ## What FacetFilter does on a change
72
+
73
+ When the user changes a facet input, before the form solves:
74
+
75
+ 1. Walking the other inputs in column order, each one no longer consistent with the change (and the ones
76
+ already kept) is cleared, unless its rule says `ClearInvalid: false`.
77
+ 2. Each empty input left with exactly one possible value takes it, repeated until nothing changes. The input
78
+ the user changed is never filled, so clearing it sticks.
79
+ 3. `CarryFields` are copied from the record the row now identifies, or cleared.
80
+
81
+ Because this runs before the solve, section and record set solvers see the finished row in the same pass.
82
+
83
+ It never runs on load or on marshal, so opening a saved document rewrites nothing -- including carried
84
+ fields, which keep the values they had when the choice was made even if the shared records change later.
85
+
86
+ ## PickList keys used here
87
+
88
+ | Key | Meaning |
89
+ |-----|---------|
90
+ | `ListSourceAddressGlobal` | Read `ListSourceAddress` from application state rather than the form data, so a list can be built from data the form does not save. |
91
+ | `SkipEmpty` | Skip records whose `IDTemplate` / `TextTemplate` render empty without logging each one -- for distinct-value lists over a field some records lack. |
92
+
93
+ ## Injection
94
+
95
+ Injected (salted) copies of a manifest keep a Facet rule as written: the join list is shared application
96
+ state and `JoinListValueAddress` names a field of its records, so neither is translated, and sibling inputs
97
+ are found by position (same row, same view) so copies never mix. A `Facets[].ValueAddress` that points at
98
+ form data is not translated either; use a literal `Value` or an application-state address in a manifest
99
+ that will be injected.
100
+
101
+ ## Related
102
+
103
+ - [Select](001-select.md) -- the dropdown the rule narrows; tabular lists with a Facet rule are refreshed on
104
+ every marshal and only rebuilt when their options change.
105
+ - [AutofillTriggerGroup](011-autofill-trigger-group.md) -- trigger-driven autofill for values outside a
106
+ facet set.
@@ -22,6 +22,7 @@ behavior for different data types and interaction patterns.
22
22
  | 013 | [TabSectionSelector](013-tab-section-selector.md) | TabSectionSelector | Tab navigation for sections |
23
23
  | 014 | [RichText](014-rich-text.md) | RichText | Markdown editor (edit) + rendered markdown (view); pluggable image uploader |
24
24
  | 015 | [Diagram](015-diagram.md) | Diagram | Excalidraw (edit) + inline themed SVG (view); themeify on save |
25
+ | 016 | [FacetFilter](016-facet-filter.md) | (any select) | Dropdowns over one shared record list, each narrowed by the others (row-scoped in tables) |
25
26
 
26
27
  ## Provider Categories
27
28
 
@@ -51,6 +51,12 @@ a product re-renders every table whose columns are generated from it; the hide
51
51
  class lives on an element that render regenerates, so it used to be dropped.
52
52
  Single file, all configuration.
53
53
 
54
+ ### Facet Filter
55
+
56
+ Order lines picking Genre -> Author -> Book from one shared catalog, each dropdown narrowed by the others in
57
+ its row and kept consistent on change (Facet list-filter rules + the FacetFilter provider). Ships a small REST
58
+ server so the catalog loads over HTTP: `npm run build && npm start`. See README-FacetFilter.md.
59
+
54
60
  ## Advanced
55
61
 
56
62
  ### Postcard
@@ -0,0 +1,9 @@
1
+ {
2
+ "GulpExecutions": [
3
+ {
4
+ "Hash": "default",
5
+ "Name": "Default standard build.",
6
+ "BuildFileLabel": "",
7
+ "BrowsersListRC": "since 2022"
8
+ }]
9
+ }
@@ -0,0 +1,210 @@
1
+ const libPictSectionForm = require('../../source/Pict-Section-Form.js');
2
+
3
+ /*
4
+ Facet Filter example: order lines that pick Genre -> Author -> Book from one shared catalog, each dropdown
5
+ narrowed by the others in the same row (a `Facet` ListFilterRule), kept consistent on change and carrying
6
+ the chosen book's price and format into the row (the `Pict-Input-FacetFilter` provider).
7
+
8
+ The catalog is loaded once by the form-level InitialBundle from the example's REST server
9
+ (Facet-Filter-Server.js): active publishers, then their books, then a ProjectDataset step that flattens
10
+ each book's nested Details into one graph row per book. Nothing is fetched when a dropdown changes.
11
+ */
12
+
13
+ const GRAPH_ADDRESS = 'AppData.Catalog.Graph';
14
+
15
+ /**
16
+ * The Facet rule every dropdown in a table shares; only JoinListValueAddress differs per column.
17
+ *
18
+ * @param {string} pJoinListValueAddress - the graph field this column holds
19
+ * @param {string} pNarrowBy - 'Preceding' or 'All'
20
+ * @param {Record<string, string>} [pCarryFields]
21
+ * @return {Record<string, any>}
22
+ */
23
+ function facetColumn(pJoinListValueAddress, pNarrowBy, pCarryFields)
24
+ {
25
+ const tmpRule =
26
+ {
27
+ Filter: 'Catalog graph',
28
+ FilterType: 'Facet',
29
+ JoinListAddress: GRAPH_ADDRESS,
30
+ JoinListAddressGlobal: true,
31
+ JoinListValueAddress: pJoinListValueAddress,
32
+ NarrowBy: pNarrowBy,
33
+ Facets:
34
+ [
35
+ { JoinListValueAddress: 'Language', ValueAddress: 'OrderLanguage' },
36
+ { JoinListValueAddress: 'InPrintFrom', Operator: 'LE', ValueAddress: 'OrderInPrintOn' },
37
+ { JoinListValueAddress: 'InPrintUntil', Operator: 'GE', ValueAddress: 'OrderInPrintOn' }
38
+ ]
39
+ };
40
+ if (pCarryFields)
41
+ {
42
+ tmpRule.CarryFields = pCarryFields;
43
+ }
44
+ return { ListFilterRules: [ tmpRule ], Providers: [ 'Pict-Input-FacetFilter' ] };
45
+ }
46
+
47
+ /**
48
+ * One order-line row manifest; the two tables differ only in how their lists narrow.
49
+ *
50
+ * @param {string} pScope
51
+ * @param {string} pGroup
52
+ * @param {string} pNarrowBy
53
+ * @return {Record<string, any>}
54
+ */
55
+ function orderLineManifest(pScope, pGroup, pNarrowBy)
56
+ {
57
+ const fColumn = (pKey, pName, pDataType, pPictForm) => (
58
+ {
59
+ Name: pName, Hash: `${pScope}${pKey}`, DataAddress: pKey, DataType: pDataType,
60
+ PictForm: Object.assign({ Section: 'Order', Group: pGroup }, pPictForm)
61
+ });
62
+ return (
63
+ {
64
+ Scope: pScope,
65
+ Descriptors:
66
+ {
67
+ Genre: fColumn('Genre', 'Genre', 'String', Object.assign({ InputType: 'Option', SelectOptionsPickList: 'Genres' }, facetColumn('Genre', pNarrowBy))),
68
+ Author: fColumn('Author', 'Author', 'String', Object.assign({ InputType: 'Option', SelectOptionsPickList: 'Authors' }, facetColumn('Author', pNarrowBy))),
69
+ Book: fColumn('Book', 'Book', 'String', Object.assign({ InputType: 'Option', SelectOptionsPickList: 'Books' }, facetColumn('IDBook', pNarrowBy, { Price: 'Price', Format: 'Format' }))),
70
+ Quantity: Object.assign(fColumn('Quantity', 'Qty', 'Number', {}), { Default: 1 }),
71
+ Price: fColumn('Price', 'Price', 'PreciseNumber', { InputType: 'ReadOnly' }),
72
+ Format: fColumn('Format', 'Format', 'String', { InputType: 'ReadOnly' }),
73
+ LineTotal: fColumn('LineTotal', 'Line Total', 'PreciseNumber', { InputType: 'ReadOnly' })
74
+ }
75
+ });
76
+ }
77
+
78
+ const _LineSolvers =
79
+ [
80
+ 'LineTotal = IF(Book, "==", "", 0, Price * Quantity)'
81
+ ];
82
+
83
+ module.exports = libPictSectionForm.PictFormApplication;
84
+
85
+ module.exports.default_configuration.pict_configuration = (
86
+ {
87
+ Product: 'FacetFilterExample',
88
+ DefaultAppData:
89
+ {
90
+ Order:
91
+ {
92
+ Language: '',
93
+ InPrintOn: '',
94
+ // A line saved earlier: its book has since gone out of print, and its price was carried when it
95
+ // was picked (the catalog lists it higher now). Opening the form rewrites neither.
96
+ Lines: [ { Genre: 'Science', Author: 'L. Brandt', Book: '109', Quantity: 2, Price: 18, Format: 'Hardcover' }, { Quantity: 1 }, { Quantity: 1 } ],
97
+ CompareLines: [ { Quantity: 1 }, { Quantity: 1 }, { Quantity: 1 } ]
98
+ }
99
+ },
100
+ DefaultFormManifest:
101
+ {
102
+ Scope: 'FacetFilterExample',
103
+
104
+ InitialBundle:
105
+ [
106
+ { Entity: 'Publisher', Filter: 'FBV~Active~EQ~1', Destination: 'AppData.Catalog.Publishers' },
107
+ // The leading 0 keeps the IN list valid when no publisher is active.
108
+ { Entity: 'Book', Filter: 'FBL~IDPublisher~INN~0,{~PJU:,^IDPublisher^AppData.Catalog.Publishers~}', Destination: 'AppData.Catalog.Books' },
109
+ {
110
+ Type: 'ProjectDataset',
111
+ InputRecordsetAddress: 'AppData.Catalog.Books',
112
+ OutputRecordsetAddress: GRAPH_ADDRESS,
113
+ RecordPrototypeAddress: 'OutputRecordset[]<<~?IDBook,==,{~D:InputRecord.IDBook~}?~>>',
114
+ RecordFieldMapping:
115
+ {
116
+ Default:
117
+ {
118
+ 'InputRecord.IDBook': 'OutputRecord.IDBook',
119
+ 'InputRecord.Title': 'OutputRecord.Title',
120
+ 'InputRecord.IDPublisher': 'OutputRecord.IDPublisher',
121
+ 'InputRecord.InPrintFrom': 'OutputRecord.InPrintFrom',
122
+ 'InputRecord.InPrintUntil': 'OutputRecord.InPrintUntil',
123
+ 'InputRecord.Details.Genre': 'OutputRecord.Genre',
124
+ 'InputRecord.Details.Author': 'OutputRecord.Author',
125
+ 'InputRecord.Details.Language': 'OutputRecord.Language',
126
+ 'InputRecord.Details.Current.Price': 'OutputRecord.Price',
127
+ 'InputRecord.Details.Current.Format': 'OutputRecord.Format'
128
+ }
129
+ }
130
+ }
131
+ ],
132
+
133
+ PickLists:
134
+ [
135
+ { Hash: 'Genres', ListAddress: 'Genres', ListSourceAddress: GRAPH_ADDRESS, ListSourceAddressGlobal: true, IDTemplate: '{~D:Record.Genre~}', TextTemplate: '{~D:Record.Genre~}', Unique: true, Sorted: true, SkipEmpty: true },
136
+ { Hash: 'Authors', ListAddress: 'Authors', ListSourceAddress: GRAPH_ADDRESS, ListSourceAddressGlobal: true, IDTemplate: '{~D:Record.Author~}', TextTemplate: '{~D:Record.Author~}', Unique: true, Sorted: true, SkipEmpty: true },
137
+ { Hash: 'Books', ListAddress: 'Books', ListSourceAddress: GRAPH_ADDRESS, ListSourceAddressGlobal: true, IDTemplate: '{~D:Record.IDBook~}', TextTemplate: '{~D:Record.Title~} ({~D:Record.Language~})', Sorted: true }
138
+ ],
139
+
140
+ Descriptors:
141
+ {
142
+ 'Order.Language':
143
+ {
144
+ Name: 'Language', Hash: 'OrderLanguage', DataType: 'String',
145
+ PictForm:
146
+ {
147
+ Section: 'Order', Group: 'Header', Row: 1, Width: 3, InputType: 'Option',
148
+ SelectOptions: [ { id: '', text: 'Any language' }, { id: 'EN', text: 'English' }, { id: 'FR', text: 'French' }, { id: 'DE', text: 'German' } ]
149
+ }
150
+ },
151
+ 'Order.InPrintOn':
152
+ {
153
+ Name: 'In print on (YYYY-MM-DD)', Hash: 'OrderInPrintOn', DataType: 'String',
154
+ PictForm: { Section: 'Order', Group: 'Header', Row: 1, Width: 3 }
155
+ },
156
+ 'Order.Total':
157
+ {
158
+ Name: 'Order total (left-narrowing table)', Hash: 'OrderTotal', DataType: 'PreciseNumber',
159
+ PictForm: { Section: 'Order', Group: 'Header', Row: 1, Width: 3, InputType: 'ReadOnly' }
160
+ },
161
+ 'Order.CompareTotal':
162
+ {
163
+ Name: 'Order total (symmetric table)', Hash: 'OrderCompareTotal', DataType: 'PreciseNumber',
164
+ PictForm: { Section: 'Order', Group: 'Header', Row: 1, Width: 3, InputType: 'ReadOnly' }
165
+ }
166
+ },
167
+
168
+ Sections:
169
+ [
170
+ {
171
+ Name: 'Book Club Order',
172
+ Hash: 'Order',
173
+ Solvers:
174
+ [
175
+ 'OrderInPrintOn = WHEN(OrderInPrintOn, OrderInPrintOn, DATEFORMAT(NULL, "YYYY-MM-DD"))',
176
+ 'OrderTotal = SUM(Order.Lines[].LineTotal)',
177
+ 'OrderCompareTotal = SUM(Order.CompareLines[].LineTotal)'
178
+ ],
179
+ Groups:
180
+ [
181
+ { Name: 'Order', Hash: 'Header', Rows: [] },
182
+ {
183
+ Name: 'Order lines -- each list narrowed by the columns to its left (NarrowBy: Preceding)',
184
+ Hash: 'Lines',
185
+ Layout: 'Tabular',
186
+ RecordSetAddress: 'Order.Lines',
187
+ RecordManifest: 'OrderLine',
188
+ MinimumRowCount: 3,
189
+ RecordSetSolvers: _LineSolvers
190
+ },
191
+ {
192
+ Name: 'The same, narrowed symmetrically -- each list by every other choice (NarrowBy: All)',
193
+ Hash: 'CompareLines',
194
+ Layout: 'Tabular',
195
+ RecordSetAddress: 'Order.CompareLines',
196
+ RecordManifest: 'CompareLine',
197
+ MinimumRowCount: 3,
198
+ RecordSetSolvers: _LineSolvers
199
+ }
200
+ ]
201
+ }
202
+ ],
203
+
204
+ ReferenceManifests:
205
+ {
206
+ OrderLine: orderLineManifest('OrderLine', 'Lines', 'Preceding'),
207
+ CompareLine: orderLineManifest('CompareLine', 'CompareLines', 'All')
208
+ }
209
+ }
210
+ });
@@ -0,0 +1,233 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ A small meadow-endpoints stand-in for the Facet Filter example: serves the built app from ./dist and the
4
+ catalog in FacetFilterData.json over the read routes the pict EntityProvider uses, logging every request.
5
+
6
+ node Facet-Filter-Server.js [--port 8086] [--latency 0]
7
+
8
+ Routes (all GET, under /1.0/):
9
+ <Entity>/Schema capability probe; answers with no Query support
10
+ <Entity>/<ID> one record
11
+ <Entity>s[/FilteredTo/<filter>][/<begin>/<cap>] a page of records
12
+ <Entity>s/Count[/FilteredTo/<filter>] { Count }
13
+
14
+ Filters are meadow FilteredTo stanzas joined by "~": FBV~Field~Operator~Value (EQ, NE, LT, LE, GT, GE, LK)
15
+ and FBL~Field~INN~a,b,c. Anything else answers 400, so a malformed filter is visible rather than ignored.
16
+ Deleted records are left out the way meadow-endpoints leaves them out.
17
+ */
18
+
19
+ const libHTTP = require('http');
20
+ const libFS = require('fs');
21
+ const libPath = require('path');
22
+
23
+ const DIST_DIRECTORY = libPath.join(__dirname, 'dist');
24
+ const DATA = JSON.parse(libFS.readFileSync(libPath.join(__dirname, 'FacetFilterData.json'), 'utf8'));
25
+ const CONTENT_TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.map': 'application/json', '.css': 'text/css', '.json': 'application/json' };
26
+
27
+ /**
28
+ * @param {Array<string>} pArguments
29
+ * @return {{ Port: number, Latency: number }}
30
+ */
31
+ function parseArguments(pArguments)
32
+ {
33
+ const tmpOptions = { Port: 8086, Latency: 0 };
34
+ for (let i = 0; i < pArguments.length; i++)
35
+ {
36
+ if (pArguments[i] === '--port')
37
+ {
38
+ tmpOptions.Port = parseInt(pArguments[++i], 10);
39
+ }
40
+ else if (pArguments[i] === '--latency')
41
+ {
42
+ tmpOptions.Latency = parseInt(pArguments[++i], 10);
43
+ }
44
+ }
45
+ return tmpOptions;
46
+ }
47
+
48
+ /**
49
+ * @param {any} pLeft - the record's value
50
+ * @param {string} pOperator
51
+ * @param {string} pRight - the filter's value
52
+ * @return {boolean}
53
+ */
54
+ function compare(pLeft, pOperator, pRight)
55
+ {
56
+ if ((pLeft === undefined) || (pLeft === null))
57
+ {
58
+ return pOperator === 'NE';
59
+ }
60
+ const tmpNumeric = (pRight !== '') && !isNaN(Number(pRight)) && !isNaN(Number(pLeft));
61
+ let tmpLeft = tmpNumeric ? Number(pLeft) : String(pLeft);
62
+ const tmpRight = tmpNumeric ? Number(pRight) : pRight;
63
+ // A bare date compares against the date part of a timestamp, as the database does.
64
+ if (!tmpNumeric && /^\d{4}-\d{2}-\d{2}$/.test(pRight) && /^\d{4}-\d{2}-\d{2}T/.test(tmpLeft))
65
+ {
66
+ tmpLeft = tmpLeft.substring(0, 10);
67
+ }
68
+ switch (pOperator)
69
+ {
70
+ case 'EQ':
71
+ return tmpLeft === tmpRight;
72
+ case 'NE':
73
+ return tmpLeft !== tmpRight;
74
+ case 'LT':
75
+ return tmpLeft < tmpRight;
76
+ case 'LE':
77
+ return tmpLeft <= tmpRight;
78
+ case 'GT':
79
+ return tmpLeft > tmpRight;
80
+ case 'GE':
81
+ return tmpLeft >= tmpRight;
82
+ case 'LK':
83
+ return new RegExp(`^${String(tmpRight).split('%').map((pPart) => pPart.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`, 'i').test(String(tmpLeft));
84
+ default:
85
+ throw new Error(`Unsupported operator [${pOperator}]`);
86
+ }
87
+ }
88
+
89
+ /**
90
+ * @param {string} pFilter - decoded FilteredTo expression
91
+ * @return {(pRecord: Record<string, any>) => boolean}
92
+ */
93
+ function buildPredicate(pFilter)
94
+ {
95
+ const tmpParts = pFilter.split('~');
96
+ if ((tmpParts.length % 4) !== 0)
97
+ {
98
+ throw new Error(`Filter [${pFilter}] is not a list of Type~Field~Operator~Value stanzas`);
99
+ }
100
+ const tmpClauses = [];
101
+ for (let i = 0; i < tmpParts.length; i += 4)
102
+ {
103
+ const [ tmpType, tmpField, tmpOperator, tmpValue ] = tmpParts.slice(i, i + 4);
104
+ if (tmpType === 'FSF')
105
+ {
106
+ continue;
107
+ }
108
+ if ((tmpType === 'FBL') && (tmpOperator === 'INN'))
109
+ {
110
+ const tmpSet = new Set(tmpValue.split(',').filter((pEntry) => pEntry !== ''));
111
+ tmpClauses.push((pRecord) => tmpSet.has(String(pRecord[tmpField])));
112
+ continue;
113
+ }
114
+ if ((tmpType === 'FBV') && [ 'EQ', 'NE', 'LT', 'LE', 'GT', 'GE', 'LK' ].includes(tmpOperator))
115
+ {
116
+ tmpClauses.push((pRecord) => compare(pRecord[tmpField], tmpOperator, tmpValue));
117
+ continue;
118
+ }
119
+ throw new Error(`Unsupported filter stanza [${tmpType}~${tmpField}~${tmpOperator}]`);
120
+ }
121
+ return (pRecord) => tmpClauses.every((fClause) => fClause(pRecord));
122
+ }
123
+
124
+ /**
125
+ * @param {string} pPath - the path after /1.0/
126
+ * @return {{ Status: number, Body: any }}
127
+ */
128
+ function answerAPI(pPath)
129
+ {
130
+ const tmpSegments = pPath.split('/').filter((pSegment) => pSegment !== '').map((pSegment) => decodeURIComponent(pSegment));
131
+ const tmpHead = tmpSegments[0] || '';
132
+ if (DATA[tmpHead] && (tmpSegments[1] === 'Schema'))
133
+ {
134
+ return { Status: 200, Body: { Entity: tmpHead } };
135
+ }
136
+ if (DATA[tmpHead] && /^\d+$/.test(tmpSegments[1] || ''))
137
+ {
138
+ const tmpRecord = DATA[tmpHead].find((pRecord) => String(pRecord[`ID${tmpHead}`]) === tmpSegments[1] && !pRecord.Deleted);
139
+ return tmpRecord ? { Status: 200, Body: tmpRecord } : { Status: 404, Body: { Error: 'Record not found' } };
140
+ }
141
+ const tmpEntity = tmpHead.endsWith('s') ? tmpHead.slice(0, -1) : '';
142
+ if (!DATA[tmpEntity])
143
+ {
144
+ return { Status: 404, Body: { Error: `No route for [${pPath}]` } };
145
+ }
146
+ let tmpRest = tmpSegments.slice(1);
147
+ const tmpCount = (tmpRest[0] === 'Count');
148
+ if (tmpCount)
149
+ {
150
+ tmpRest = tmpRest.slice(1);
151
+ }
152
+ let tmpPredicate = () => true;
153
+ if (tmpRest[0] === 'FilteredTo')
154
+ {
155
+ tmpPredicate = buildPredicate(tmpRest[1] || '');
156
+ tmpRest = tmpRest.slice(2);
157
+ }
158
+ const tmpRecords = DATA[tmpEntity].filter((pRecord) => !pRecord.Deleted && tmpPredicate(pRecord));
159
+ if (tmpCount)
160
+ {
161
+ return { Status: 200, Body: { Count: tmpRecords.length } };
162
+ }
163
+ const tmpBegin = (tmpRest.length >= 2) ? parseInt(tmpRest[0], 10) : 0;
164
+ const tmpCap = (tmpRest.length >= 2) ? parseInt(tmpRest[1], 10) : tmpRecords.length;
165
+ return { Status: 200, Body: tmpRecords.slice(tmpBegin, tmpBegin + tmpCap) };
166
+ }
167
+
168
+ /**
169
+ * @param {import('http').ServerResponse} pResponse
170
+ * @param {string} pURLPath
171
+ */
172
+ function serveStatic(pResponse, pURLPath)
173
+ {
174
+ const tmpRelative = (pURLPath === '/') ? 'index.html' : decodeURIComponent(pURLPath).replace(/^\/+/, '');
175
+ const tmpPath = libPath.join(DIST_DIRECTORY, tmpRelative);
176
+ if (!tmpPath.startsWith(DIST_DIRECTORY) || !libFS.existsSync(tmpPath) || !libFS.statSync(tmpPath).isFile())
177
+ {
178
+ pResponse.writeHead(404, { 'Content-Type': 'text/plain' });
179
+ pResponse.end(libFS.existsSync(DIST_DIRECTORY) ? 'Not found' : 'No dist/ yet -- run `npm run build` first.');
180
+ return;
181
+ }
182
+ pResponse.writeHead(200, { 'Content-Type': CONTENT_TYPES[libPath.extname(tmpPath)] || 'application/octet-stream', 'Cache-Control': 'no-store' });
183
+ libFS.createReadStream(tmpPath).pipe(pResponse);
184
+ }
185
+
186
+ function main()
187
+ {
188
+ const tmpOptions = parseArguments(process.argv.slice(2));
189
+ const tmpServer = libHTTP.createServer((pRequest, pResponse) =>
190
+ {
191
+ const tmpURL = new URL(pRequest.url, 'http://localhost');
192
+ if (!tmpURL.pathname.startsWith('/1.0/'))
193
+ {
194
+ return serveStatic(pResponse, tmpURL.pathname);
195
+ }
196
+ const tmpStart = Date.now();
197
+ let tmpAnswer;
198
+ if (pRequest.method !== 'GET')
199
+ {
200
+ tmpAnswer = { Status: 405, Body: { Error: `${pRequest.method} is not served by this example` } };
201
+ }
202
+ else
203
+ {
204
+ try
205
+ {
206
+ tmpAnswer = answerAPI(tmpURL.pathname.substring('/1.0/'.length));
207
+ }
208
+ catch (pError)
209
+ {
210
+ tmpAnswer = { Status: 400, Body: { Error: pError.message } };
211
+ }
212
+ }
213
+ setTimeout(() =>
214
+ {
215
+ const tmpBody = JSON.stringify(tmpAnswer.Body);
216
+ pResponse.writeHead(tmpAnswer.Status, { 'Content-Type': 'application/json' });
217
+ pResponse.end(tmpBody);
218
+ const tmpSummary = Array.isArray(tmpAnswer.Body) ? `${tmpAnswer.Body.length} record(s)` : (tmpAnswer.Body.Error || JSON.stringify(tmpAnswer.Body));
219
+ console.log(`${new Date().toISOString()} ${pRequest.method} ${decodeURIComponent(tmpURL.pathname)} -> ${tmpAnswer.Status} ${tmpSummary} (${Date.now() - tmpStart} ms)`);
220
+ }, tmpOptions.Latency);
221
+ });
222
+ tmpServer.listen(tmpOptions.Port, () =>
223
+ {
224
+ console.log(`Facet Filter example: http://localhost:${tmpOptions.Port}/ (API latency ${tmpOptions.Latency} ms)`);
225
+ });
226
+ }
227
+
228
+ if (require.main === module)
229
+ {
230
+ main();
231
+ }
232
+
233
+ module.exports = { answerAPI, buildPredicate };