jsl-ui 10.1.1 → 10.2.1

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 (41) hide show
  1. package/docs/DataBinding.md +19 -0
  2. package/docs/DateTimeComponent.md +1 -0
  3. package/docs/GridComponent.md +8 -5
  4. package/docs/InputComponent.md +1 -1
  5. package/docs/README.md +1 -0
  6. package/examples/showcase/checks-and-expanders.ts +2 -17
  7. package/examples/showcase/data-binding.ts +138 -0
  8. package/examples/showcase/dates.ts +6 -16
  9. package/examples/showcase/fields.ts +14 -26
  10. package/examples/showcase/generate-sources.cjs +104 -0
  11. package/examples/showcase/grids.ts +240 -13
  12. package/examples/showcase/index.html +12 -2
  13. package/examples/showcase/selects.ts +6 -8
  14. package/examples/showcase/showcase-sources.ts +95 -0
  15. package/examples/showcase/showcase.css +23 -2
  16. package/examples/showcase/showcase.ts +28 -5
  17. package/lib/components/auto-suggest/AutoSuggestComponent.d.ts +4 -4
  18. package/lib/components/auto-suggest/AutoSuggestComponent.js +1 -1
  19. package/lib/components/checkbox/CheckBoxComponent.d.ts +2 -3
  20. package/lib/components/checkbox/CheckBoxComponent.js +7 -20
  21. package/lib/components/date/DateComponent.d.ts +4 -4
  22. package/lib/components/date/DateComponent.js +11 -27
  23. package/lib/components/date-time/DateTimeComponent.d.ts +4 -4
  24. package/lib/components/date-time/DateTimeComponent.js +21 -32
  25. package/lib/components/input/InputComponent.d.ts +1 -4
  26. package/lib/components/input/InputComponent.js +14 -32
  27. package/lib/components/number/NumberComponent.d.ts +1 -4
  28. package/lib/components/number/NumberComponent.js +11 -29
  29. package/lib/components/select/SelectComponent.d.ts +1 -3
  30. package/lib/components/select/SelectComponent.js +8 -22
  31. package/lib/components/time/TimeComponent.d.ts +4 -3
  32. package/lib/components/time/TimeComponent.js +11 -24
  33. package/lib/grid/slick-default-theme.css +10 -2
  34. package/lib/grid/slick.grid.css +3 -1
  35. package/lib/grid.css +32 -3
  36. package/lib/index.css +151 -122
  37. package/lib/index.css.map +1 -1
  38. package/lib/index.js.map +1 -1
  39. package/lib/interaction/data-binding.d.ts +27 -0
  40. package/lib/interaction/data-binding.js +72 -0
  41. package/package.json +3 -1
@@ -0,0 +1,19 @@
1
+ # Data binding
2
+
3
+ Input, AutoSuggest, Number, CheckBox, Select, Date, Time and DateTime support `bindTo`, `property`, `bindMode` and an optional `converter`. Binding defaults to `"toModel"`.
4
+
5
+ | Mode | Initial value | User changes and `setValue()` | External model changes |
6
+ | --- | --- | --- | --- |
7
+ | `toModel` | Control `value` or its default | Write to the model | Never read |
8
+ | `fromModel` | Model | Change the control, but do not write to the model | Apply on render when the model value changes |
9
+ | `both` | Model | Write to the model | Apply on render when the model value changes |
10
+
11
+ When a `toModel` control is mounted, an explicitly supplied initial `value` is written to the model without raising a change event. If the value was omitted, mounting does not write. Calling `setValue()` before mounting writes immediately in a writable mode and takes precedence over the initial option. `setValue()` does not raise change events.
12
+
13
+ In `fromModel` and `both` modes, a render preserves a local value or draft while the model value remains unchanged. A changed model value is applied on the next render; changing a plain object does not itself schedule a render. Dates and arrays are compared by value, including in-place changes.
14
+
15
+ `converter.toUI` converts model values for the control; `converter.toData` converts control values before writing. Valid user changes write before the change callback is raised. Invalid drafts are not published.
16
+
17
+ For Input and AutoSuggest, `bindOnInput: true` writes on input in writable modes, and `false` waits for change. When omitted, input events write if an `onInput` handler is registered; otherwise they wait for change. The model is updated before `onInput` handlers run.
18
+
19
+ DateTime does not publish a partially filled date and time. Clearing both fields publishes `null` in a writable mode.
@@ -11,3 +11,4 @@ const appointment = new DateTimeComponent({
11
11
 
12
12
  - Bind the composite control to one `Date`; it combines the date and time inputs. `getValueAsDate()` returns `null` for invalid input; `getValue()` returns text.
13
13
  - `setValue()` updates both inputs without raising change callbacks. The control edits local date/time, without timezone conversion.
14
+ - A partially filled date and time remains a draft. Clearing both fields publishes `null` to writable bindings. See [Data binding](DataBinding.md).
@@ -22,15 +22,18 @@ const grid = new GridComponent<Request>(
22
22
  ## Patterns and features
23
23
 
24
24
  - **Identity and lifecycle:** Use a unique, stable `primaryKey` and keep the component instance stable across parent renders. Register setup and event handlers with `initEvents()`; `getRef()` resolves after the grid mounts. A stable `saveColumnsKey` preserves column settings.
25
- - **Columns and editing:** Set formatters, editors, widths, `sortable`, and `filterable` per column. Enable `editable` in grid options to edit cells; the demos show text, number, date, time, boolean, lookup, and custom editors. Use grid events such as `onBeforeEditCell` and `onAfterEdit` for application rules.
26
- - **Derived and grouped data:** Use `addFormula(field, calculate, dependencies)` for calculated values, then `triggerAllFormulas()` for initial values. The grid's DataView supports filters, grouping, expand/collapse, and aggregators for group summaries.
27
- - **Sorting and layout:** `multiColumnSort` and `numberedMultiColumnSort` support prioritized sorts. `frozenColumn`, `rowHeight`/`autoHeight`, `showColumnGroups` with each column's `columnGroup`, and footer rows cover wide or structured grids.
28
- - **Interaction and rendering:** Examples include row and cell selection, manual row reordering (`allowRowMove`), custom cell formatters, rendered JSL components, asynchronous cell rendering, variable row heights, column spans, and undo/redo. Disable sorting when manual row order should remain authoritative.
25
+ - **Columns and editing:** Columns default their `field` to their `id`. Set `sortable` and `filterable` on columns and `showHeaderMenu: true` to expose sorting and filtering in the header menu. Enable `editable` and provide column editors to edit cells; use `onAfterEdit` for application updates. Custom header icons can be supplied through `column.header.buttons`.
26
+ - **Formulas and totals:** Use `addFormula(field, calculate, dependencies)` and `triggerAllFormulas()` for calculated values. For grouped totals, configure DataView grouping with an aggregator such as `SumAggregator`, enable `displayTotalsRow`, and use a column's `groupTotalsFormatter` to format the result. Set `aggregateCollapsed: true` to keep totals visible when groups are collapsed.
27
+ - **Variable row heights:** Set `variableRowHeight: true` and give individual data items a `__height` in pixels. Rows without a height, including group headers, use `rowHeight` (40 px by default). Heights are explicit, not measured from wrapped content; call `grid.refresh()` after changing them.
28
+ - **Hierarchical rows:** Use `IndentFormatter` for the tree column and initialize `GridTree` in `initEvents()` with the parent ID field. Keep parents before their descendants in the data, with each subtree contiguous; ordinary sorting can break that order.
29
+ - **Selection:** The grid starts with a row selection model. Use `setSelectionModel(new CellSelectionModel())` for cell ranges and subscribe to the model's `onSelectedRangesChanged` event for range coordinates. Clear the old model's ranges before switching modes. The showcase demonstrates counting selected cells and calculating a sum and average from numeric values.
30
+ - **Components in cells:** Use `ComponentFormatter` and render the component into `args.dom` from `onAppendCell`. Cells can be recreated during scrolling or refresh, so keep state in the row data rather than only in the cell DOM; call `refreshDataItem(item)` when it changes.
31
+ - **Sorting and layout:** `multiColumnSort` and `numberedMultiColumnSort` support prioritized sorts. `frozenColumn`, `rowHeight`/`autoHeight`, `showColumnGroups` with each column's `columnGroup`, and footer rows cover wide or structured grids. Disable sorting when manual row order (`allowRowMove`) should remain authoritative.
29
32
  - **Styling:** `NumericFormatter` aligns cell values; set `headerCssClass: "right"` or `"center"` explicitly to align headers. Keep `content-box` sizing on cells and headers so padding and borders do not disrupt grid measurements.
30
33
 
31
34
  ## Examples
32
35
 
33
- - [GridComponent showcase](../examples/showcase/grids.ts): sorting, editing, formatters, grouping, frozen columns, formulas, totals, and row reordering.
36
+ - [GridComponent showcase](../examples/showcase/grids.ts): interactive examples for sorting, editing, grouping and totals, hierarchy, cell components, selection, variable heights, and more. Each example has a **Show code** option.
34
37
  - [Focused grid demos](../examples/grid/g-01-basic.html): [large-data grouping and filters](../examples/grid/g-02-grouping.html), [custom formatters and editors](../examples/grid/g-03-customformatter-forcefit.html), [JSL cell components](../examples/grid/g-06-cellcomponents.html), [async rendering](../examples/grid/g-07-asyncrender.html), [selection](../examples/grid/g-10-selection.html), [column spans](../examples/grid/g-11-colspan.html), [undo/redo](../examples/grid/g-12-undo-redo.html), [filter row](../examples/grid/g-13-filterrow.html), and [row reordering](../examples/grid/g-14-reorder.html).
35
38
 
36
39
  The focused demos mostly use `createJSLGrid` directly and show the underlying grid APIs; use the showcase for `GridComponent` patterns.
@@ -10,6 +10,6 @@ const input = new InputComponent({
10
10
  });
11
11
  ```
12
12
 
13
- - Binding defaults to `"toModel"`. Use `"both"` to also read external model changes on render; `bindOnInput` writes while typing rather than waiting for change.
13
+ - Binding defaults to `"toModel"`. Use `"both"` to also read external model changes on render. See [Data binding](DataBinding.md) for `bindOnInput` and draft behavior.
14
14
  - `setValue()` updates the binding without raising change callbacks.
15
15
  - Use [FormFieldComponent](FormFieldComponent.md) for a visible label. Keep the default control styling unless the host deliberately supplies its own via `unstyled`.
package/docs/README.md CHANGED
@@ -5,6 +5,7 @@
5
5
  - Theme through `--jsl-color-*` variables on the application or a container; avoid overriding internal markup.
6
6
  - [Showcase sources](../examples/showcase/) are included as usage references.
7
7
  - Consult the shipped `lib/**/*.d.ts` files for options; these guides cover usage decisions rather than duplicate interfaces.
8
+ - See [Data binding](DataBinding.md) for binding modes, initialization, converters and draft behavior.
8
9
 
9
10
  Guides for the public components exported by `jsl-ui`:
10
11
 
@@ -44,14 +44,6 @@ function syncChannels() {
44
44
  allChannels.indeterminate = count > 0 && count < channels.length;
45
45
  partialStatus.content = count + " of " + channels.length + " channels selected.";
46
46
  }
47
- const model = { digest: 1 };
48
- const bindingStatus = status("Model value: 1");
49
- const boundCheck = new CheckBoxComponent({
50
- id: "checkbox-bound", label: "Send a weekly digest", bindTo: model, property: "digest", bindMode: "both",
51
- converter: { toUI: value => value === 1, toData: checked => checked ? 1 : 0 },
52
- onChange: () => { bindingStatus.content = "Model value: " + model.digest; }
53
- });
54
-
55
47
  export const checkboxShowcase = section("checkboxes", "09", "Checkboxes",
56
48
  "Small choices, clearly marked. Comfortable labels and a visible place for focus.",
57
49
  group([
@@ -74,17 +66,10 @@ export const checkboxShowcase = section("checkboxes", "09", "Checkboxes",
74
66
  card("checkbox-partial", "03", "Some, all, or none", "A mixed parent summarizes its children. Activating it selects or clears the whole group.", [
75
67
  group([allChannels, group(channels, "checkbox-child-list")], "checkbox-stack"), partialStatus,
76
68
  text("pre", "checkbox.indeterminate = true;\ncheckbox.setValue(true); // Silent checked update", "sample-code")
77
- ]),
78
- card("checkbox-binding", "04", "Connected to your model", "A converter maps checked state to a numeric value. Two-way binding keeps the display in sync.", [
79
- boundCheck, bindingStatus,
80
- group([action("Toggle from the model", () => {
81
- model.digest = model.digest === 1 ? 0 : 1;
82
- bindingStatus.content = "Model value: " + model.digest;
83
- })], "sample-row")
84
69
  ])
85
70
  ], [
86
- text("pre", 'new CheckBoxComponent({\n label: "Send a weekly digest",\n value: true,\n bindTo: model, property: "digest", bindMode: "both",\n onChange: checked => console.log(checked)\n});', "sample-code"),
87
- text("p", "Existing value, label, enabled, class, style, id, binding, converter, onChange, getValue(), and setValue() APIs are preserved. class still applies to the input and style to its wrapper. setValue() works before mounting, updates writable bindings, and does not raise onChange."),
71
+ text("pre", 'new CheckBoxComponent({\n label: "Send a weekly digest",\n value: true,\n onChange: checked => console.log(checked)\n});', "sample-code"),
72
+ text("p", "Existing value, label, enabled, class, style, id, onChange, getValue(), and setValue() APIs are preserved. class still applies to the input and style to its wrapper. setValue() updates the control without raising onChange."),
88
73
  text("p", "The optional description is associated with the input as supporting text. Use ariaLabel when the visible label is empty. indeterminate sets an initial mixed state; the indeterminate property can update it later. The next user activation clears mixed state and raises the usual boolean change event.")
89
74
  ]);
90
75
 
@@ -0,0 +1,138 @@
1
+ import { IJSLComponent, IJSLVNode } from "jsl-render";
2
+ import { ButtonComponent } from "../../components/button/ButtonComponent";
3
+ import { CheckBoxComponent } from "../../components/checkbox/CheckBoxComponent";
4
+ import { DateTimeComponent } from "../../components/date-time/DateTimeComponent";
5
+ import { InputComponent } from "../../components/input/InputComponent";
6
+ import { NumberComponent } from "../../components/number/NumberComponent";
7
+ import { SelectComponent } from "../../components/select/SelectComponent";
8
+ import { date } from "../../core/date";
9
+
10
+ type Content = IJSLVNode | IJSLComponent;
11
+ const text = (tag: string, content: string, className?: string): IJSLVNode => ({ tag, content, attr: { class: className } });
12
+ const group = (children: Content[], className?: string): IJSLVNode => ({ tag: "div", attr: { class: className }, children });
13
+ const status = (content: string): IJSLVNode => ({ tag: "p", content, attr: { class: "sample-status", role: "status" } });
14
+ const action = (content: string, click: () => void) => new ButtonComponent({ content, click, type: "button", outlined: true, size: "small" });
15
+ const field = (id: string, label: string, control: Content) => group([
16
+ { tag: "label", content: label, attr: { for: id } }, control
17
+ ], "binding-field");
18
+ function card(id: string, number: string, title: string, description: string, children: Content[]): IJSLVNode {
19
+ return { tag: "article", attr: { class: "sample-card", id }, children: [
20
+ group([text("span", number, "sample-number"), text("h2", title)], "card-heading"),
21
+ text("p", description, "card-description"), ...children
22
+ ] };
23
+ }
24
+
25
+ const createModel = { title: "Waiting for the first commit" };
26
+ const createStatus = status("Model value: Ready for review");
27
+ const createInput = new InputComponent({
28
+ id: "binding-to-model", value: "Ready for review", bindTo: createModel, property: "title", bindMode: "toModel",
29
+ onChange: () => { createStatus.content = "Model value: " + createModel.title; }
30
+ });
31
+
32
+ const readModel = { subscribed: false };
33
+ const readStatus = status("Model value: off. Toggle the control to see that edits stay local.");
34
+ const readCheck = new CheckBoxComponent({
35
+ id: "binding-from-model", label: "Send weekly updates", bindTo: readModel, property: "subscribed", bindMode: "fromModel",
36
+ onChange: value => { readStatus.content = "Change event: " + (value ? "on" : "off") + "; model is still " + (readModel.subscribed ? "on" : "off") + "."; }
37
+ });
38
+
39
+ const budgetModel = { cents: 12500 };
40
+ const budgetStatus = status("Model value: 12500 cents");
41
+ const budgetInput = new NumberComponent({
42
+ id: "binding-both", bindTo: budgetModel, property: "cents", bindMode: "both", format: "0.00",
43
+ converter: { toUI: cents => cents / 100, toData: amount => amount == null ? null : Math.round(amount * 100) },
44
+ onChange: () => { budgetStatus.content = "Model value: " + budgetModel.cents + " cents"; }
45
+ });
46
+
47
+ const projectOptions = [
48
+ { value: "website", text: "Website refresh" },
49
+ { value: "library", text: "Component library" },
50
+ { value: "research", text: "Customer research" }
51
+ ];
52
+ const projectModel = { current: "library" };
53
+ const projectStatus = status("Model value: library");
54
+ const projectSelect = new SelectComponent({
55
+ id: "binding-select", data: projectOptions, bindTo: projectModel, property: "current", bindMode: "both",
56
+ ariaLabel: "Bound project", placeholder: "Choose a project",
57
+ onChange: value => { projectStatus.content = "Model value: " + (value ?? "empty"); }
58
+ });
59
+
60
+ const appointmentModel = { appointment: new Date(2026, 9, 21, 14, 45) };
61
+ const appointmentText = () => {
62
+ const value = appointmentModel.appointment;
63
+ return value ? "Model value: " + date.format(value) + " at " + date.formatTime(value, "HourMinute") : "Model value: cleared";
64
+ };
65
+ const appointmentStatus = status(appointmentText());
66
+ const appointment = new DateTimeComponent({
67
+ id: "binding-datetime", bindTo: appointmentModel, property: "appointment", bindMode: "both",
68
+ onChange: () => { appointmentStatus.content = appointmentText(); }
69
+ });
70
+
71
+ export const dataBindingShowcase: IJSLVNode = {
72
+ tag: "section", attr: { id: "data-binding", class: "component-section", "aria-labelledby": "data-binding-title" }, children: [
73
+ group([
74
+ group([
75
+ text("p", "THE ESSENTIALS / 24", "eyebrow"),
76
+ { tag: "h2", content: "Data binding", attr: { id: "data-binding-title", class: "section-title" } },
77
+ text("p", "Choose which side owns the value. See model updates, local edits, events, and conversion across controls.", "hero-description")
78
+ ], "hero-copy"),
79
+ group([
80
+ text("span", "INTERACTIVE PREVIEW", "preview-caption"),
81
+ field("binding-preview", "Project title", new InputComponent({
82
+ id: "binding-preview", value: "Planning that stays in sync", ariaLabel: "Binding preview"
83
+ })),
84
+ text("span", "Edit any example, then use its action to change the model.", "preview-note")
85
+ ], "hero-preview binding-preview")
86
+ ], "hero"),
87
+ group([
88
+ text("span", "Overview", "overview-label"), text("span", "3 binding modes", "overview-stat"),
89
+ text("span", "Events and converters", "overview-stat"), text("span", "External model updates", "overview-stat")
90
+ ], "overview-bar"),
91
+ group([
92
+ card("binding-both-card", "01", "Two way with a converter", "The control shows dollars while the model stores cents. Commits and setValue() write; changed model data refreshes the control.", [
93
+ field("binding-both", "Budget (dollars)", budgetInput), budgetStatus,
94
+ action("Set model to $250.00", () => {
95
+ budgetModel.cents = 25000;
96
+ budgetStatus.content = "Model value: 25000 cents";
97
+ }),
98
+ text("pre", 'new NumberComponent({\n bindTo: model, property: "cents", bindMode: "both",\n converter: {\n toUI: cents => cents / 100,\n toData: dollars => Math.round(dollars * 100)\n }\n});', "sample-code")
99
+ ]),
100
+ card("binding-to-model-card", "02", "Control to model", "The control starts from its explicit value. On mount, that value initializes the model; later commits write back.", [
101
+ field("binding-to-model", "Project title", createInput), createStatus,
102
+ text("pre", 'new InputComponent({\n value: "Ready for review",\n bindTo: model, property: "title",\n bindMode: "toModel"\n});', "sample-code")
103
+ ]),
104
+ card("binding-from-model-card", "03", "Model to control", "The model supplies the initial value and wins when it changes. A user change still raises onChange but does not write back.", [
105
+ readCheck, readStatus,
106
+ group([action("Set model to on", () => {
107
+ readModel.subscribed = true;
108
+ readStatus.content = "Model value: on. The checkbox updates on render.";
109
+ }), action("Set model to off", () => {
110
+ readModel.subscribed = false;
111
+ readStatus.content = "Model value: off. The checkbox updates on render.";
112
+ })], "sample-row"),
113
+ text("pre", 'new CheckBoxComponent({\n bindTo: model, property: "subscribed",\n bindMode: "fromModel",\n onChange: value => console.log(value)\n});', "sample-code")
114
+ ]),
115
+ card("binding-select-card", "04", "The same contract on Select", "Select stores option keys. A control change writes the key; changing the model updates the selected option on render.", [
116
+ field("binding-select", "Project", projectSelect), projectStatus,
117
+ action("Choose Website refresh in the model", () => {
118
+ projectModel.current = "website";
119
+ projectStatus.content = "Model value: website";
120
+ }),
121
+ text("p", "Single selection uses a scalar key; multiple selection uses an array of keys.", "inline-note")
122
+ ]),
123
+ card("binding-datetime-card", "05", "Date and time share one value", "DateTime binds one Date across both fields. A partial entry stays local; clearing both fields writes null.", [
124
+ field("binding-datetime", "Appointment", appointment), appointmentStatus,
125
+ action("Move appointment to October 26", () => {
126
+ appointmentModel.appointment = new Date(2026, 9, 26, 11, 15);
127
+ appointmentStatus.content = appointmentText();
128
+ })
129
+ ])
130
+ ], "sample-grid binding-sample-grid"),
131
+ { tag: "details", attr: { class: "usage" }, children: [
132
+ text("summary", "Binding modes & compatibility"),
133
+ text("p", "toModel uses the control's value or default and never reads the model. An explicit initial value is written once when the control mounts. fromModel reads the model and never writes to it. both reads the model and writes user changes and setValue() back."),
134
+ text("p", "In fromModel and both, a local edit remains visible while the model value stays the same. A changed model value is applied on the next render. Updating a plain object does not request a render by itself."),
135
+ text("p", "Converters use toUI for model-to-control values and toData for control-to-model values. Input writes on every input event when bindOnInput is true; when omitted, it does so if an onInput handler is registered. See the component guides for control-specific events and validation.")
136
+ ] }
137
+ ]
138
+ };
@@ -114,7 +114,7 @@ export const dateShowcase = section("dates", "05", "Dates",
114
114
  ])
115
115
  ], [
116
116
  code('new DateComponent({\n value: new Date(2026, 9, 15),\n min: new Date(2026, 9, 1), max: new Date(2026, 9, 31),\n onChange: value => console.log(value)\n});'),
117
- text("p", "Existing formatting, parsing, localization, dateClass, inRange, binding, and getRef options remain available. Empty fields return null. setValue(date) updates the field and calendar silently. getRef().setState(state) retains its selection events; pass true as a second argument for a silent update."),
117
+ text("p", "Formatting, parsing, localization, dateClass, inRange, and getRef options remain available. Empty fields return null. setValue(date) updates the field and calendar silently. getRef().setState(state) retains its selection events; pass true as a second argument for a silent update."),
118
118
  text("p", "Calendar controls support Tab, Enter, Space, arrow keys, and Escape. Use ariaLabel or an associated label for the field. Popups within dialogs stay inside the dialog; appendTo allows an explicit popup container.")
119
119
  ]);
120
120
 
@@ -139,12 +139,6 @@ export const dateRangeShowcase = section("date-ranges", "06", "Date ranges",
139
139
  ]);
140
140
 
141
141
  const timeStatus = status("Pick a date and enter a time.");
142
- const dateTimeModel = { appointment: day(21, 14, 45) };
143
- const boundStatus = status("October 21 at 14:45");
144
- const boundDateTime = new DateTimeComponent({
145
- id: "showcase-datetime-bound", bindTo: dateTimeModel, property: "appointment", bindMode: "both",
146
- onChange: value => { boundStatus.content = value ? format(value) + " at " + date.formatTime(value, "HourMinute") : "Appointment cleared"; }
147
- });
148
142
  export const dateTimeShowcase = section("date-times", "07", "Date & time",
149
143
  "A day and a moment, together. Familiar fields with room for precision.", new DateTimeComponent({
150
144
  id: "showcase-datetime-preview", value: day(15, 10, 30), ariaLabel: "Preview appointment"
@@ -156,12 +150,8 @@ export const dateTimeShowcase = section("date-times", "07", "Date & time",
156
150
  })), timeStatus,
157
151
  field("showcase-datetime-disabled", "Unavailable schedule", new DateTimeComponent({ id: "showcase-datetime-disabled", value: day(15), enabled: false }))
158
152
  ]),
159
- card("datetime-model", "02", "Connected to your application", "Changes update the model. A model change refreshes both fields.", [
160
- field("showcase-datetime-bound", "Appointment", boundDateTime),
161
- group([action("Move to October 26", () => {
162
- dateTimeModel.appointment = day(26, 11, 15);
163
- boundStatus.content = "Model updated to October 26 at 11:15.";
164
- }), action("Open in a dialog", () => {
153
+ card("datetime-dialog", "02", "Schedule in context", "The date picker stays within its dialog while you choose a time.", [
154
+ action("Open scheduler", () => {
165
155
  DialogComponent.show({
166
156
  header: "Schedule an appointment", width: "28rem",
167
157
  content: group([
@@ -169,10 +159,10 @@ export const dateTimeShowcase = section("date-times", "07", "Date & time",
169
159
  field("showcase-dialog-date", "Appointment", new DateTimeComponent({ id: "showcase-dialog-date", value: day(21, 14, 45) }))
170
160
  ]), footer: group([DialogComponent.Cancel(), DialogComponent.Ok()], "sample-row")
171
161
  });
172
- })], "sample-row"), boundStatus
162
+ }), text("p", "Date and time binding modes are shown together in the Data binding section.", "inline-note")
173
163
  ])
174
164
  ], [
175
- code('new DateTimeComponent({\n value: new Date(2026, 9, 15, 9, 30),\n inputMode: "HourMinute", // Or "HourMinuteSecond"\n bindTo: model, property: "appointment", bindMode: "both",\n onChange: value => console.log(value)\n});'),
176
- text("p", "The existing Date-valued callbacks, converters, getValue(), and getValueAsDate() remain available. toModel, fromModel, and both binding modes are supported. An incomplete value returns null; malformed dates and times do not update the model. setValue(date) silently updates both fields."),
165
+ code('new DateTimeComponent({\n value: new Date(2026, 9, 15, 9, 30),\n inputMode: "HourMinute", // Or "HourMinuteSecond"\n onChange: value => console.log(value)\n});'),
166
+ text("p", "The existing Date-valued callbacks, converters, getValue(), and getValueAsDate() remain available. An incomplete value returns null; malformed dates and times do not update the model. setValue(date) silently updates both fields. Binding modes are demonstrated in the Data binding section."),
177
167
  text("p", "The supplied id belongs to the date field; the time field gets an id with '-time' appended. ariaLabel names the group, and dateAriaLabel and timeAriaLabel can name its fields. Date-only formatting and parsing options apply to the date field.")
178
168
  ]);
@@ -36,8 +36,7 @@ function section(id: string, number: string, title: string, description: string,
36
36
  ] };
37
37
  }
38
38
  const inputStatus = status("Start typing to see the input event.");
39
- const textModel = { notes: "A few notes for the team." };
40
- const textStatus = status("26 characters in the model.");
39
+ const notesStatus = status("A few notes for the team.");
41
40
  export const inputShowcase = section("inputs", "11", "Inputs",
42
41
  "A consistent place to type. Simple defaults for text, passwords, and longer notes.",
43
42
  new InputComponent({ id: "input-preview", placeholder: "What are you working on?", ariaLabel: "Preview input" }), [
@@ -48,19 +47,18 @@ export const inputShowcase = section("inputs", "11", "Inputs",
48
47
  onChange: value => { inputStatus.content = "Committed: " + (value || "empty"); }
49
48
  })), inputStatus
50
49
  ]),
51
- card("input-textarea", "02", "Room for a longer thought", "The same component supports a textarea, including binding on every input event.", [
50
+ card("input-textarea", "02", "Room for a longer thought", "Use the same familiar events with a multiline field.", [
52
51
  sampleField("input-notes", "Notes", new InputComponent({
53
- id: "input-notes", type: "textarea", rows: 4,
54
- bindTo: textModel, property: "notes", bindMode: "both", bindOnInput: true,
55
- onInput: () => { textStatus.content = textModel.notes.length + " characters in the model."; }
56
- })), textStatus
52
+ id: "input-notes", type: "textarea", rows: 4, value: "A few notes for the team.",
53
+ onInput: value => { notesStatus.content = value.length + " characters in the notes."; }
54
+ })), notesStatus
57
55
  ]),
58
56
  card("input-states", "03", "Useful native input types", "Passwords, email, read-only values, and disabled fields share the same base appearance.", [
59
57
  sampleField("input-password", "Password", new InputComponent({ id: "input-password", type: "password", value: "A little privacy" })),
60
58
  sampleField("input-readonly", "Read-only identifier", new InputComponent({ id: "input-readonly", value: "PROJ-2026-010", readOnly: true })),
61
59
  sampleField("input-disabled", "Unavailable value", new InputComponent({ id: "input-disabled", value: "Managed by your team", enabled: false }))
62
60
  ]),
63
- card("input-unstyled", "04", "A building block when needed", "Opt out of the library surface for a grid cell or a custom editor. Behavior and binding remain available.", [
61
+ card("input-unstyled", "04", "A building block when needed", "Opt out of the library surface for a grid cell or a custom editor while keeping normal input behavior.", [
64
62
  group([
65
63
  text("span", "PROJECT /", "inline-note"),
66
64
  new InputComponent({ id: "input-plain", value: "An inline title", ariaLabel: "Inline title", unstyled: true, class: "showcase-inline-input" })
@@ -68,14 +66,12 @@ export const inputShowcase = section("inputs", "11", "Inputs",
68
66
  text("pre", '{ unstyled: true, class: "my-editor" }', "sample-code")
69
67
  ])
70
68
  ], [
71
- text("pre", 'new InputComponent({\n value: "A project", placeholder: "Project name",\n bindTo: model, property: "name", bindMode: "both",\n onChange: value => console.log(value)\n});', "sample-code"),
72
- text("p", "Existing options, events, binding, converters, getValue(), and setValue() remain supported. The input alias for type is retained. setValue() stays silent. unstyled skips the base CSS class; ariaLabel, readOnly, rows, autocomplete, and focus() are optional additions."),
73
- text("p", "bindOnInput now works even without an onInput subscriber. Two-way bindings preserve a draft until the model actually changes, including the caret in a textarea.")
69
+ text("pre", 'new InputComponent({\n value: "A project", placeholder: "Project name",\n onChange: value => console.log(value)\n});', "sample-code"),
70
+ text("p", "Existing options, events, getValue(), and setValue() remain supported. The input alias for type is retained. setValue() stays silent. unstyled skips the base CSS class; ariaLabel, readOnly, rows, autocomplete, and focus() are optional additions."),
71
+ text("p", "Use bindOnInput to choose when a bound model updates. Binding modes and model synchronization are demonstrated in the Data binding section.")
74
72
  ]);
75
73
 
76
74
  const numberStatus = status("Commit a value with Enter or by leaving the field.");
77
- const moneyModel = { cents: 12500 };
78
- const moneyStatus = status("Model value: 12500 cents");
79
75
  export const numberShowcase = section("numbers", "12", "Numbers",
80
76
  "The same surface, with numeric behavior. Formats and converters stay close to the value.",
81
77
  new NumberComponent({ id: "number-preview", value: 1250.5, format: "#,0.00", ariaLabel: "Preview amount" }), [
@@ -86,28 +82,20 @@ export const numberShowcase = section("numbers", "12", "Numbers",
86
82
  })), numberStatus,
87
83
  sampleField("number-zero", "Whole number", new NumberComponent({ id: "number-zero", value: 0, format: "0" }))
88
84
  ]),
89
- card("number-binding", "02", "One value, two representations", "A converter presents cents as a decimal amount and converts committed edits back to cents.", [
90
- sampleField("number-cents", "Budget", new NumberComponent({
91
- id: "number-cents", bindTo: moneyModel, property: "cents", bindMode: "both", format: "0.00",
92
- converter: { toUI: value => value / 100, toData: value => value == null ? null : Math.round(value * 100) },
93
- onChange: () => { moneyStatus.content = "Model value: " + moneyModel.cents + " cents"; }
94
- })), moneyStatus,
95
- action("Set budget to 250.00", () => { moneyModel.cents = 25000; moneyStatus.content = "Model value: 25000 cents"; })
96
- ]),
97
- card("number-options", "03", "Choose when to format", "Formatting and Enter commits can be disabled independently.", [
85
+ card("number-options", "02", "Choose when to format", "Formatting and Enter commits can be disabled independently.", [
98
86
  sampleField("number-live", "Format preserved while editing", new NumberComponent({
99
87
  id: "number-live", value: 12.5, format: "0.00", formatOnBlur: false, commitOnEnter: false
100
88
  })),
101
89
  text("pre", "{ formatOnBlur: false, commitOnEnter: false }", "sample-code")
102
90
  ]),
103
- card("number-states", "04", "Consistent states", "Disabled and read-only values match the other controls. Unstyled mode remains available for embedded editors.", [
91
+ card("number-states", "03", "Consistent states", "Disabled and read-only values match the other controls. Unstyled mode remains available for embedded editors.", [
104
92
  sampleField("number-disabled", "Unavailable amount", new NumberComponent({ id: "number-disabled", value: 99, format: "0.00", enabled: false })),
105
93
  sampleField("number-readonly", "Calculated total", new NumberComponent({ id: "number-readonly", value: 149.95, format: "0.00", readOnly: true })),
106
94
  text("pre", '{ unstyled: true }', "sample-code")
107
95
  ])
108
96
  ], [
109
97
  text("pre", 'new NumberComponent({\n value: 1250.5, format: "#,0.00",\n onChange: value => console.log(value)\n});', "sample-code"),
110
- text("p", "getValue() returns the displayed string; getValueAsNumber() returns its parsed number. Formatting follows the existing culture settings and numeric helpers. Empty values remain undefined. setValue() updates writable bindings silently."),
98
+ text("p", "getValue() returns the displayed string; getValueAsNumber() returns its parsed number. Formatting follows the existing culture settings and numeric helpers. Empty values remain undefined. setValue() updates the control silently."),
111
99
  text("p", "commitOnEnter is now honored. Enter followed by blur does not publish the same commit twice. Malformed numeric drafts remain visible for correction and do not write NaN to the model.")
112
100
  ]);
113
101
 
@@ -170,8 +158,8 @@ export const formFieldShowcase = section("form-fields", "13", "Form fields",
170
158
  new FormFieldComponent({ id: "field-disabled-input", label: "Managed identifier", disabled: true, value: "PROJ-2026-010" })
171
159
  ])
172
160
  ], [
173
- text("pre", 'const input = new InputComponent({ bindTo: model, property: "name", bindMode: "both" });\nconst field = new FormFieldComponent({\n label: "Project name", control: input,\n description: "Choose a name your team will recognize.",\n required: true\n});', "sample-code"),
174
- text("p", "FormField owns labels, layout, descriptions, required indicators, and validation feedback. The child owns editing, formatting, binding, and popup cleanup. Supply control to compose an existing component; legacy type, value, dateOptions, numberOptions, and autoSuggestOptions use a compatibility factory."),
161
+ text("pre", 'const input = new InputComponent({ value: "Project name" });\nconst field = new FormFieldComponent({\n label: "Project name", control: input,\n description: "Choose a name your team will recognize.",\n required: true\n});', "sample-code"),
162
+ text("p", "FormField owns labels, layout, descriptions, required indicators, and validation feedback. The child owns editing, formatting, and popup cleanup. Supply control to compose an existing component; legacy type, value, dateOptions, numberOptions, and autoSuggestOptions use a compatibility factory."),
175
163
  text("p", "getValue() and setValue() delegate to the wrapped control, so supplied controls use their own setter types (for example, a number or Date). Legacy number and date fields continue to accept string values. getControl() returns the child component. A generic return type can describe custom controls, for example FormFieldComponent<string[]> for a multi-select."),
176
164
  text("p", "A native label targets the wrapped control's existing ID. id or controlId can specify the target. Helper and validation messages extend existing aria-describedby associations. disabled uses a native fieldset so controls such as SelectComponent are disabled together."),
177
165
  text("p", "The default labelPosition is above. The optional floating presentation places an always-visible label on the outline, preserving space for a placeholder. Custom controls keep their own surfaces.")
@@ -0,0 +1,104 @@
1
+ // Generate self-contained examples from the showcase's own TypeScript source.
2
+ // Run before serving or building the showcase so the code views stay in sync.
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const ts = require("typescript");
6
+
7
+ const directory = __dirname;
8
+ const files = ["showcase.ts", "dialogs.ts", "tabs.ts", "dates.ts", "selects.ts",
9
+ "checks-and-expanders.ts", "fields.ts", "feedback-and-navigation.ts",
10
+ "layout-and-navigation.ts", "grids.ts", "dropdown-menus.ts", "data-binding.ts"];
11
+ const examples = {};
12
+
13
+ for (const file of files) {
14
+ const contents = fs.readFileSync(path.join(directory, file), "utf8");
15
+ const source = ts.createSourceFile(file, contents, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
16
+ const declarations = new Map();
17
+ const effects = [];
18
+ const imports = [];
19
+
20
+ for (const statement of source.statements) {
21
+ if (ts.isImportDeclaration(statement)) {
22
+ imports.push(statement);
23
+ } else if (ts.isVariableStatement(statement)) {
24
+ for (const declaration of statement.declarationList.declarations) {
25
+ if (ts.isIdentifier(declaration.name)) declarations.set(declaration.name.text, statement);
26
+ }
27
+ } else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) ||
28
+ ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name) {
29
+ declarations.set(statement.name.text, statement);
30
+ } else if (ts.isExpressionStatement(statement)) {
31
+ effects.push(statement);
32
+ }
33
+ }
34
+
35
+ function identifiers(node) {
36
+ const result = new Set();
37
+ function visit(child) {
38
+ if (ts.isIdentifier(child)) result.add(child.text);
39
+ ts.forEachChild(child, visit);
40
+ }
41
+ visit(node);
42
+ return result;
43
+ }
44
+
45
+ function effectTarget(statement) {
46
+ let expression = statement.expression;
47
+ if (ts.isBinaryExpression(expression)) expression = expression.left;
48
+ if (ts.isCallExpression(expression)) expression = expression.expression;
49
+ while (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) expression = expression.expression;
50
+ return ts.isIdentifier(expression) ? expression.text : null;
51
+ }
52
+
53
+ function makeSource(expression) {
54
+ const included = new Set();
55
+ const pending = [...identifiers(expression)];
56
+ const names = new Set();
57
+ while (pending.length) {
58
+ const name = pending.pop();
59
+ if (names.has(name)) continue;
60
+ names.add(name);
61
+ const declaration = declarations.get(name);
62
+ if (declaration && !included.has(declaration)) {
63
+ included.add(declaration);
64
+ pending.push(...identifiers(declaration));
65
+ }
66
+ for (const effect of effects) {
67
+ if (effectTarget(effect) === name && !included.has(effect)) {
68
+ included.add(effect);
69
+ pending.push(...identifiers(effect));
70
+ }
71
+ }
72
+ }
73
+ const body = source.statements.filter(statement => included.has(statement)).map(statement => statement.getText(source)).join("\n\n");
74
+ const usedImports = imports.flatMap(statement => {
75
+ const clause = statement.importClause;
76
+ if (!clause) return [];
77
+ const bindings = clause.namedBindings;
78
+ const named = bindings && ts.isNamedImports(bindings)
79
+ ? bindings.elements.filter(element => names.has(element.name.text)).map(element => element.getText(source)) : [];
80
+ const defaultName = clause.name && names.has(clause.name.text) ? clause.name.text : "";
81
+ const namespace = bindings && ts.isNamespaceImport(bindings) && names.has(bindings.name.text) ? bindings.getText(source) : "";
82
+ const parts = [defaultName, namespace || (named.length ? "{ " + named.join(", ") + " }" : "")].filter(Boolean);
83
+ return parts.length ? ["import " + (clause.isTypeOnly ? "type " : "") + parts.join(", ") + " from " + statement.moduleSpecifier.getText(source) + ";"] : [];
84
+ });
85
+ const stylesheet = 'import "../../ui/base.css";\nimport "./showcase.css";';
86
+ return stylesheet + "\n" + usedImports.join("\n") + '\nimport { JSLRender as ExampleRenderer } from "jsl-render";\n\n' + body +
87
+ '\n\n// Add <div id="example"></div> to the page.\nnew ExampleRenderer(document.getElementById("example"), true).render(\n ' + expression.getText(source) + "\n);";
88
+ }
89
+
90
+ function visit(node) {
91
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.arguments.length && ts.isStringLiteral(node.arguments[0])) {
92
+ const id = node.arguments[0].text;
93
+ if (node.expression.text === "card" || (file === "layout-and-navigation.ts" && node.expression.text === "section")) {
94
+ if (examples[id]) throw new Error("Duplicate showcase example: " + id);
95
+ examples[id] = makeSource(node);
96
+ }
97
+ }
98
+ ts.forEachChild(node, visit);
99
+ }
100
+ visit(source);
101
+ }
102
+
103
+ fs.writeFileSync(path.join(directory, "showcase-sources.ts"),
104
+ "// Generated by generate-sources.cjs. Do not edit by hand.\nexport const showcaseSources: Record<string, string> = " + JSON.stringify(examples, null, 2) + ";\n");