@xh/hoist 89.0.0 → 89.1.0

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 (68) hide show
  1. package/CHANGELOG.md +61 -5
  2. package/appcontainer/MessageModel.ts +11 -10
  3. package/appcontainer/README.md +6 -2
  4. package/build/types/appcontainer/MessageModel.d.ts +4 -1
  5. package/build/types/cmp/input/impl/LiveCommas.d.ts +21 -0
  6. package/build/types/core/XH.d.ts +7 -6
  7. package/build/types/core/model/HoistModel.d.ts +1 -0
  8. package/build/types/core/model/ManagedRefreshContextModel.d.ts +1 -0
  9. package/build/types/data/cube/View.d.ts +0 -2
  10. package/build/types/data/cube/impl/RowCache.d.ts +1 -1
  11. package/build/types/data/cube/row/BaseRow.d.ts +5 -0
  12. package/build/types/desktop/cmp/grid/editors/impl/InlineEditorModel.d.ts +6 -1
  13. package/build/types/desktop/cmp/input/NumberInput.d.ts +5 -2
  14. package/build/types/mobile/cmp/input/NumberInput.d.ts +5 -2
  15. package/build/types/test-support/agGrid.d.ts +2 -0
  16. package/build/types/test-support/hoistCore.d.ts +7 -1
  17. package/build/types/test-support/index.d.ts +1 -0
  18. package/build/types/test-support/jsonBlobs.d.ts +130 -0
  19. package/build/types/test-support/testApp.d.ts +5 -2
  20. package/cmp/grid/Grid.ts +1 -1
  21. package/cmp/grid/GridModel.ts +8 -3
  22. package/cmp/grid/columns/Column.ts +1 -1
  23. package/cmp/input/impl/LiveCommas.ts +59 -0
  24. package/core/XH.ts +7 -6
  25. package/core/model/HoistModel.ts +4 -2
  26. package/core/model/Hooks.ts +1 -0
  27. package/core/model/ManagedRefreshContextModel.ts +5 -1
  28. package/data/README.md +3 -2
  29. package/data/cube/View.ts +3 -9
  30. package/data/cube/impl/RowCache.ts +2 -2
  31. package/data/cube/row/BaseRow.ts +14 -1
  32. package/data/cube/row/ParentRow.ts +1 -1
  33. package/desktop/cmp/dash/canvas/impl/DashCanvasView.ts +49 -52
  34. package/desktop/cmp/grid/editors/BooleanEditor.ts +2 -1
  35. package/desktop/cmp/grid/editors/DateEditor.ts +4 -1
  36. package/desktop/cmp/grid/editors/SelectEditor.ts +4 -1
  37. package/desktop/cmp/grid/editors/impl/InlineEditorModel.ts +17 -5
  38. package/desktop/cmp/input/NumberInput.ts +51 -12
  39. package/desktop/cmp/input/Select.ts +25 -7
  40. package/docs/README.md +2 -0
  41. package/docs/companion-library-docs.md +205 -0
  42. package/docs/doc-registry.json +8 -0
  43. package/docs/lifecycle-app.md +17 -0
  44. package/docs/unit-testing.md +54 -3
  45. package/docs/upgrade-notes/v89-upgrade-notes.md +101 -2
  46. package/docs/version-compatibility.md +2 -1
  47. package/icon/README.md +4 -1
  48. package/mcp/README.md +79 -4
  49. package/mcp/cli/docs.ts +75 -30
  50. package/mcp/data/doc-id-resolver.ts +50 -9
  51. package/mcp/data/doc-registry.ts +462 -44
  52. package/mcp/data/doc-search.ts +25 -6
  53. package/mcp/formatters/docs.ts +136 -36
  54. package/mcp/instructions.ts +69 -0
  55. package/mcp/resources/docs.ts +10 -8
  56. package/mcp/server.ts +7 -13
  57. package/mcp/tools/docs.ts +64 -18
  58. package/mcp/util/paths.ts +85 -2
  59. package/mobile/cmp/input/NumberInput.ts +42 -4
  60. package/package.json +19 -19
  61. package/public/msal-redirect-bridge.min.js +1 -1
  62. package/svc/JsonBlobService.ts +7 -4
  63. package/test-support/agGrid.ts +12 -2
  64. package/test-support/hoistCore.ts +32 -5
  65. package/test-support/index.ts +1 -0
  66. package/test-support/jsonBlobs.ts +543 -0
  67. package/test-support/setup.ts +16 -6
  68. package/test-support/testApp.ts +36 -7
package/core/XH.ts CHANGED
@@ -671,10 +671,10 @@ export class XHApi {
671
671
  * this method will resolve immediately to their previously saved response, without showing
672
672
  * a dialog. This also applies to the `alert`, `confirm`, and `prompt` variants below.
673
673
  *
674
- * @returns true if user confirms, false if user cancels. If an input is provided, the
675
- * returned Promise will resolve to the input value if user confirms, false if user cancels.
676
- * Resolves to null if the message is closed without a choice - e.g. by a route change or
677
- * when replaced by a later message with the same `messageKey`.
674
+ * @returns true if the user confirms, or the input value if an input is provided. Resolves
675
+ * false for any other outcome - a cancel, a dismiss, or a close without a choice, e.g. by a
676
+ * route change or a later message with the same `messageKey`. With an input, test the result
677
+ * with `!== false`, as null and an empty string are valid confirmed values.
678
678
  */
679
679
  message<T = unknown>(config: MessageSpec): Promise<T | boolean> {
680
680
  return this.acm.messageSourceModel.message(config);
@@ -690,7 +690,7 @@ export class XHApi {
690
690
 
691
691
  /**
692
692
  * Show a modal 'confirm' dialog with message and default 'OK'/'Cancel' buttons.
693
- * @returns true if user confirms, false if user cancels.
693
+ * @returns true if user confirms, false otherwise. See {@link message} for details.
694
694
  */
695
695
  confirm(config: MessageSpec): Promise<boolean> {
696
696
  return this.acm.messageSourceModel.confirm(config);
@@ -705,7 +705,8 @@ export class XHApi {
705
705
  * 3. onKeyDown handler to confirm on <enter> (same as clicking 'OK') (desktop only)
706
706
  * Applications may also provide a custom HoistInput, in which all props must be set.
707
707
  *
708
- * @returns value of input if user confirms, false if user cancels.
708
+ * @returns value of input if user confirms, false otherwise. See {@link message} for details.
709
+ * Test the result with `!== false`, as null and an empty string are valid confirmed values.
709
710
  */
710
711
  prompt<T = unknown>(config: MessageSpec): Promise<T | false> {
711
712
  return this.acm.messageSourceModel.prompt(config);
@@ -136,9 +136,11 @@ export abstract class HoistModel extends HoistBase implements Loadable {
136
136
 
137
137
  // Internal State
138
138
  // - `_componentProps` is only set for linked models and mirrors the current React props.
139
- // - `_modelLookup` is injected by Hoist when this model is linked into a component hierarchy.
139
+ // - `_linked` is set by Hoist when this model is linked into a component hierarchy.
140
+ // - `_modelLookup` is injected on link, and is null for a model linked at the root.
140
141
  // - `_created` is basic lifecycle metadata (useful for diagnostics/ordering).
141
142
  @observableRef accessor _componentProps: DefaultHoistProps | null = null;
143
+ _linked: boolean = false;
142
144
  _modelLookup: any = null;
143
145
  _created: number = Date.now();
144
146
 
@@ -201,7 +203,7 @@ export abstract class HoistModel extends HoistBase implements Loadable {
201
203
  // Linked model support
202
204
  //---------------------------
203
205
  get isLinked(): boolean {
204
- return !!this._modelLookup;
206
+ return this._linked;
205
207
  }
206
208
 
207
209
  /**
@@ -67,6 +67,7 @@ export function useModelLinker(model: HoistModel, modelLookup: ModelLookup, prop
67
67
 
68
68
  // 1) Linking synchronous work: resolve lookups, initialize props, and call onLinked()
69
69
  if (isLinking) {
70
+ model._linked = true;
70
71
  model._modelLookup = modelLookup;
71
72
  each(model['_xhInjectedParentProperties'], (selector, name) => {
72
73
  const parentModel = modelLookup?.lookupModel(selector);
@@ -22,6 +22,7 @@ export class ManagedRefreshContextModel extends RefreshContextModel {
22
22
 
23
23
  model: ManagedRefreshTarget;
24
24
  refreshPending: boolean = false;
25
+ private pendingIsAutoRefresh: boolean = false;
25
26
 
26
27
  constructor(model: ManagedRefreshTarget) {
27
28
  super();
@@ -42,6 +43,9 @@ export class ManagedRefreshContextModel extends RefreshContextModel {
42
43
  }
43
44
 
44
45
  if (mode === 'onShowLazy') {
46
+ // Replay as an auto-refresh only if every missed refresh was one.
47
+ this.pendingIsAutoRefresh =
48
+ loadSpec.isAutoRefresh && (!this.refreshPending || this.pendingIsAutoRefresh);
45
49
  this.refreshPending = true;
46
50
  }
47
51
  }
@@ -53,7 +57,7 @@ export class ManagedRefreshContextModel extends RefreshContextModel {
53
57
  this.refreshAsync();
54
58
  } else if (mode === 'onShowLazy' && this.refreshPending) {
55
59
  this.refreshPending = false;
56
- this.refreshAsync();
60
+ this.pendingIsAutoRefresh ? this.autoRefreshAsync() : this.refreshAsync();
57
61
  }
58
62
  }
59
63
  }
package/data/README.md CHANGED
@@ -270,8 +270,9 @@ store.count; // Filtered record count
270
270
  store.allCount; // Total record count
271
271
  ```
272
272
 
273
- Store re-filters automatically whenever record data changes. Call `refreshFilter()` only when the
274
- state behind a `FunctionFilter` changes without any change to the records themselves.
273
+ Store re-filters automatically whenever record data changes, but a patched change (the default for
274
+ small changes) re-tests only the records it touches. Call `refreshFilter()` when the state behind a
275
+ `FunctionFilter` changes without any change to the records themselves.
275
276
 
276
277
  ### Observable Properties
277
278
 
package/data/cube/View.ts CHANGED
@@ -149,8 +149,6 @@ export class View
149
149
 
150
150
  private _fieldsByName: Map<string, CubeField> = null;
151
151
  private _rowDataGenerator: RowDataGenerator = null;
152
- // Monotonic source for cubeRowDigest stamps - safe-integer headroom spans centuries of use.
153
- _rowDigest = 0;
154
152
  // Fields eligible for aggregation at each level of the query - i.e. those with an aggregator
155
153
  // that are not themselves an applied dimension there - and useful subsets of same. Indexed by
156
154
  // row depth, with entry 0 (no dimensions applied) holding the superset for the whole query.
@@ -335,7 +333,7 @@ export class View
335
333
  */
336
334
  newParentRowData(id: string): ViewRowData {
337
335
  const ret = this._rowDataGenerator.newParentRowData(id);
338
- this.assignDigest(ret);
336
+ BaseRow.assignDigest(ret);
339
337
  return ret;
340
338
  }
341
339
 
@@ -345,14 +343,10 @@ export class View
345
343
  */
346
344
  newLeafRowData(id: string, src: PlainObject): ViewRowData {
347
345
  const ret = this._rowDataGenerator.newLeafRowData(id, src);
348
- this.assignDigest(ret);
346
+ BaseRow.assignDigest(ret);
349
347
  return ret;
350
348
  }
351
349
 
352
- assignDigest(data: ViewRowData) {
353
- data.cubeRowDigest = ++this._rowDigest;
354
- }
355
-
356
350
  private buildIndices() {
357
351
  this._fieldsByName = new Map(this.fields.map(it => [it.name, it]));
358
352
 
@@ -419,7 +413,7 @@ export class View
419
413
  _leafMap.get(rec.id)?.applyLeafDataUpdate(rec, checkFields, changed);
420
414
  });
421
415
 
422
- changed.rows.forEach(rowData => this.assignDigest(rowData));
416
+ changed.rows.forEach(rowData => BaseRow.assignDigest(rowData));
423
417
 
424
418
  this.createAggregationContext();
425
419
 
@@ -8,7 +8,7 @@
8
8
  import type {StoreRecord} from '@xh/hoist/data';
9
9
  import {isEqual, map} from 'lodash';
10
10
  import type {Query} from '../Query';
11
- import type {BaseRow} from '../row/BaseRow';
11
+ import {BaseRow} from '../row/BaseRow';
12
12
  import {ExposedLeafRow, type LeafRow} from '../row/LeafRow';
13
13
  import type {ParentRow} from '../row/ParentRow';
14
14
  import type {View} from '../View';
@@ -93,7 +93,7 @@ export class RowCache {
93
93
  beginGeneration() {
94
94
  const {view} = this;
95
95
  this.pruneForQueryChange(view.query);
96
- this.genStartDigest = view._rowDigest;
96
+ this.genStartDigest = BaseRow.currentDigest;
97
97
  this.exposedLeaves = view.exposesLeaves;
98
98
  this.reused = this.rebuilt = this.created = 0;
99
99
  }
@@ -19,6 +19,19 @@ import type {ParentRow} from './ParentRow';
19
19
  * @internal
20
20
  */
21
21
  export abstract class BaseRow implements ViewRow {
22
+ // Shared by all Views, so stamps never repeat across Views on the same Store.
23
+ private static lastDigest = 0;
24
+
25
+ /** The latest cubeRowDigest stamp given out by any View. */
26
+ static get currentDigest(): number {
27
+ return BaseRow.lastDigest;
28
+ }
29
+
30
+ /** Stamp row data with a new cubeRowDigest, marking it changed. */
31
+ static assignDigest(data: ViewRowData) {
32
+ data.cubeRowDigest = ++BaseRow.lastDigest;
33
+ }
34
+
22
35
  readonly view: View = null;
23
36
  readonly id: string = null;
24
37
 
@@ -53,7 +66,7 @@ export abstract class BaseRow implements ViewRow {
53
66
 
54
67
  if (!shallowEqualObjects(data.cubeBuckets, buckets)) {
55
68
  data.cubeBuckets = buckets;
56
- this.view.assignDigest(data as ViewRowData);
69
+ BaseRow.assignDigest(data as ViewRowData);
57
70
  }
58
71
 
59
72
  this.children?.forEach(it => it.syncBuckets(buckets));
@@ -136,7 +136,7 @@ export abstract class ParentRow extends BaseRow {
136
136
  changed = this.recomputeAggregatesForContextChange(this.recomputeCanAggregate());
137
137
  }
138
138
 
139
- if (changed) view.assignDigest(this.data);
139
+ if (changed) BaseRow.assignDigest(this.data);
140
140
  return this;
141
141
  }
142
142
 
@@ -5,11 +5,11 @@
5
5
  * Copyright © 2026 Extremely Heavy Industries Inc.
6
6
  */
7
7
  import {isEmpty} from 'lodash';
8
- import {ReactElement} from 'react';
9
8
  import {box} from '@xh/hoist/cmp/layout';
10
- import {hoistCmp, uses} from '@xh/hoist/core';
11
- import {ContextMenu} from '@xh/hoist/desktop/cmp/contextmenu';
9
+ import {hoistCmp, type MenuItemLike, uses} from '@xh/hoist/core';
10
+ import {contextMenu} from '@xh/hoist/desktop/cmp/contextmenu';
12
11
  import {createViewMenuItems} from '@xh/hoist/desktop/cmp/dash/canvas/impl/utils';
12
+ import {parseMenuItems} from '@xh/hoist/desktop/cmp/menu/impl/MenuItems';
13
13
  import {elementFromContent, useOnResize} from '@xh/hoist/utils/react';
14
14
  import {Icon} from '@xh/hoist/icon';
15
15
  import {popover, Position} from '@xh/hoist/kit/blueprint';
@@ -72,55 +72,52 @@ const headerMenu = hoistCmp.factory<DashCanvasViewModel>(({model}) => {
72
72
  viewId: id,
73
73
  replaceExisting: true
74
74
  }),
75
- content = ContextMenu({
76
- menuItems: [
77
- {
78
- text: 'Add',
79
- icon: Icon.add(),
80
- items: addMenuItems,
81
- hidden: contentLocked || isEmpty(addMenuItems)
82
- },
83
- {
84
- text: 'Remove',
85
- icon: Icon.cross(),
86
- hidden: !viewSpec.allowRemove || contentLocked,
87
- actionFn: () => containerModel.removeView(id)
88
- },
89
- {
90
- text: 'Rename',
91
- icon: Icon.edit(),
92
- hidden: !viewSpec.allowRename || renameLocked,
93
- actionFn: () => containerModel.renameView(id)
94
- },
95
- {
96
- text: 'Replace',
97
- icon: Icon.transaction(),
98
- items: replaceMenuItems,
99
- hidden: !viewSpec.allowRemove || contentLocked || isEmpty(replaceMenuItems)
100
- },
101
- {
102
- text: 'Duplicate',
103
- icon: Icon.copy(),
104
- hidden: !allowDuplicate || contentLocked || viewSpec.unique,
105
- actionFn: () =>
106
- containerModel
107
- .addViewInternal(viewSpec.id, {
108
- layout: getDuplicateLayout(positionParams, model),
109
- state: viewState,
110
- title
111
- })
112
- .ensureVisible()
113
- },
114
- '-',
115
- ...(model.extraMenuItems ?? []),
116
- '-',
117
- ...(containerModel.extraMenuItems ?? [])
118
- ]
119
- }) as ReactElement;
75
+ menuItems: MenuItemLike[] = [
76
+ {
77
+ text: 'Add',
78
+ icon: Icon.add(),
79
+ items: addMenuItems,
80
+ hidden: contentLocked || isEmpty(addMenuItems)
81
+ },
82
+ {
83
+ text: 'Remove',
84
+ icon: Icon.cross(),
85
+ hidden: !viewSpec.allowRemove || contentLocked,
86
+ actionFn: () => containerModel.removeView(id)
87
+ },
88
+ {
89
+ text: 'Rename',
90
+ icon: Icon.edit(),
91
+ hidden: !viewSpec.allowRename || renameLocked,
92
+ actionFn: () => containerModel.renameView(id)
93
+ },
94
+ {
95
+ text: 'Replace',
96
+ icon: Icon.transaction(),
97
+ items: replaceMenuItems,
98
+ hidden: !viewSpec.allowRemove || contentLocked || isEmpty(replaceMenuItems)
99
+ },
100
+ {
101
+ text: 'Duplicate',
102
+ icon: Icon.copy(),
103
+ hidden: !allowDuplicate || contentLocked || viewSpec.unique,
104
+ actionFn: () =>
105
+ containerModel
106
+ .addViewInternal(viewSpec.id, {
107
+ layout: getDuplicateLayout(positionParams, model),
108
+ state: viewState,
109
+ title
110
+ })
111
+ .ensureVisible()
112
+ },
113
+ '-',
114
+ ...(model.extraMenuItems ?? []),
115
+ '-',
116
+ ...(containerModel.extraMenuItems ?? [])
117
+ ];
120
118
 
121
- // Workaround using React functional component to check if ContextMenu renders null
122
- // TODO - build a popover wrapper that null-checks content instead of this workaround
123
- if (!content) return null;
119
+ // Skip the button if every item is hidden.
120
+ if (isEmpty(parseMenuItems(menuItems))) return null;
124
121
 
125
122
  return popover({
126
123
  position: Position.BOTTOM,
@@ -128,7 +125,7 @@ const headerMenu = hoistCmp.factory<DashCanvasViewModel>(({model}) => {
128
125
  item: button({
129
126
  icon: Icon.ellipsisVertical()
130
127
  }),
131
- content
128
+ content: contextMenu({menuItems})
132
129
  });
133
130
  });
134
131
 
@@ -46,7 +46,8 @@ export const [BooleanEditor, booleanEditor] = hoistCmp.withFactory<BooleanEditor
46
46
 
47
47
  return quickToggle
48
48
  ? useInstantEditor(props.agParams, ref)
49
- : useInlineEditorModel(checkbox, props, ref);
49
+ : // A checkbox's value is a boolean, so ignore the key that started the edit.
50
+ useInlineEditorModel(checkbox, props, ref, () => {});
50
51
  }
51
52
  });
52
53
 
@@ -46,6 +46,9 @@ export const [DateEditor, dateEditor] = hoistCmp.withFactory<DateEditorProps>({
46
46
  ...inputProps
47
47
  }
48
48
  };
49
- return useInlineEditorModel(dateInput, props, ref);
49
+ // A date input's value holds a date, so enter the key that started the edit as its text.
50
+ return useInlineEditorModel(dateInput, props, ref, (input, key) =>
51
+ (input as any).textInputRef.current?.noteValueChange(key)
52
+ );
50
53
  }
51
54
  });
@@ -49,6 +49,9 @@ export const [SelectEditor, selectEditor] = hoistCmp.withFactory<SelectEditorPro
49
49
  }
50
50
  };
51
51
 
52
- return useInlineEditorModel(select, props, ref);
52
+ // A select's value holds an option, so enter the key that started the edit as search text.
53
+ return useInlineEditorModel(select, props, ref, (input, key) =>
54
+ (input as any).enterSearchText(key)
55
+ );
53
56
  }
54
57
  });
@@ -25,14 +25,17 @@ import {ForwardedRef, ReactElement, useCallback} from 'react';
25
25
  * @param component - ElementFactory for HoistInput to render.
26
26
  * @param props - props passed to containing component
27
27
  * @param ref - forwardRef passed to containing component
28
+ * @param applyInitialKey - applies a printable key that started the edit to the focused input.
29
+ * Defaults to entering the key as the input's value.
28
30
  */
29
31
  export function useInlineEditorModel(
30
32
  component: ElementFactory,
31
33
  props: EditorProps<any>,
32
- ref: ForwardedRef<any>
34
+ ref: ForwardedRef<any>,
35
+ applyInitialKey: InitialKeyFn = (input, key) => input.noteValueChange(key)
33
36
  ): ReactElement {
34
37
  const {className, inputProps, agParams, gridModel} = props,
35
- impl = useLocalModel(() => new InlineEditorModel(agParams, gridModel));
38
+ impl = useLocalModel(() => new InlineEditorModel(agParams, gridModel, applyInitialKey));
36
39
 
37
40
  useGridCellEditor({
38
41
  // This is called in full-row editing when the user tabs into the cell
@@ -62,6 +65,9 @@ export function useInlineEditorModel(
62
65
  });
63
66
  }
64
67
 
68
+ /** Applies the printable key that started an edit to the editor's focused input. */
69
+ export type InitialKeyFn = (input: HoistInputModel, key: string) => void;
70
+
65
71
  /**
66
72
  * Local Model supporting inline cell editor components. Provides base functionality required by
67
73
  * ag-grid plus extension points for editors needing more complex behaviors.
@@ -76,15 +82,21 @@ class InlineEditorModel extends HoistModel {
76
82
  ref = createObservableRef<HoistInputModel>();
77
83
 
78
84
  agParams: CustomCellEditorProps;
85
+ applyInitialKey: InitialKeyFn;
79
86
 
80
87
  get inputEl() {
81
88
  return this.ref.current?.inputEl;
82
89
  }
83
90
 
84
- constructor(agParams: CustomCellEditorProps, gridModel: GridModel) {
91
+ constructor(
92
+ agParams: CustomCellEditorProps,
93
+ gridModel: GridModel,
94
+ applyInitialKey: InitialKeyFn
95
+ ) {
85
96
  super();
86
97
 
87
98
  this.agParams = agParams;
99
+ this.applyInitialKey = applyInitialKey;
88
100
  this.value = agParams.value;
89
101
 
90
102
  // Focus into the input once the component is rendered. With full row editing, multiple
@@ -104,9 +116,9 @@ class InlineEditorModel extends HoistModel {
104
116
  inputEl.focus();
105
117
 
106
118
  const {eventKey} = this.agParams;
107
- // Enter initial keystroke in value (if single char and not special key e.g (F2 or Enter).
119
+ // Apply initial keystroke (if single char and not special key e.g (F2 or Enter).
108
120
  if (eventKey?.length === 1) {
109
- ref.current.noteValueChange(eventKey);
121
+ this.applyInitialKey(ref.current, eventKey);
110
122
  } else {
111
123
  inputEl.select();
112
124
  }
@@ -11,15 +11,21 @@ import {
11
11
  PasswordManagerSupportProps,
12
12
  useHoistInputModel
13
13
  } from '@xh/hoist/cmp/input';
14
+ import {
15
+ addCommasWhileEditing,
16
+ getCaretSkippingCommas,
17
+ setCaretSkippingCommas,
18
+ skipCommaOnDelete
19
+ } from '@xh/hoist/cmp/input/impl/LiveCommas';
14
20
  import {hoistCmp, HoistProps, LayoutProps, StyleProps} from '@xh/hoist/core';
15
21
  import '@xh/hoist/desktop/register';
16
22
  import {fmtNumber, NumericPrecision, parseNumber, Precision, ZeroPad} from '@xh/hoist/format';
17
23
  import {numericInput} from '@xh/hoist/kit/blueprint';
18
24
  import {wait} from '@xh/hoist/promise';
19
25
  import {TEST_ID, throwIf, withDefault} from '@xh/hoist/utils/js';
20
- import {useComposedRefs, getLayoutProps} from '@xh/hoist/utils/react';
26
+ import {getLayoutProps, useComposedRefs, useOnMount} from '@xh/hoist/utils/react';
21
27
  import type {Property} from 'csstype';
22
- import {debounce, isNaN, isNil, isNumber, round} from 'lodash';
28
+ import {clamp, debounce, isNaN, isNil, isNumber, round} from 'lodash';
23
29
  import {KeyboardEventHandler, ReactElement, ReactNode, Ref, useLayoutEffect} from 'react';
24
30
 
25
31
  export interface NumberInputProps
@@ -32,8 +38,11 @@ export interface NumberInputProps
32
38
  /** True to commit on every change/keystroke, default false. */
33
39
  commitOnChange?: boolean;
34
40
 
35
- /** True to insert commas in displayed value. */
36
- displayWithCommas?: boolean;
41
+ /**
42
+ * Insert commas in displayed value - 'whenBlurred' (or true) to show them only when the input
43
+ * does not have focus, 'always' to also show them while the user types.
44
+ */
45
+ displayWithCommas?: boolean | 'always' | 'whenBlurred';
37
46
 
38
47
  /** True to convert entries suffixed with k/m/b to thousands/millions/billions. */
39
48
  enableShorthandUnits?: boolean;
@@ -147,7 +156,16 @@ class NumberInputModel extends HoistInputModel {
147
156
  return withDefault(this.componentProps.scaleFactor, 1);
148
157
  }
149
158
 
159
+ get commasWhileEditing(): boolean {
160
+ return this.componentProps.displayWithCommas === 'always';
161
+ }
162
+
163
+ // Caret position to restore after a reformat while editing, as a count of non-comma chars.
164
+ caretPos: number = null;
165
+
150
166
  onValueChange = (val, valAsString) => {
167
+ if (this.commasWhileEditing)
168
+ this.caretPos = getCaretSkippingCommas(this.inputEl as HTMLInputElement);
151
169
  this.noteValueChange(valAsString);
152
170
  };
153
171
 
@@ -187,7 +205,7 @@ class NumberInputModel extends HoistInputModel {
187
205
  if (isNaN(val)) return false;
188
206
  if (val === null) return true;
189
207
 
190
- // Enforce min/max here on commit. BP props only limit the incremental step change
208
+ // Hoist owns min/max, checking the parsed value - see clampSteppedValue().
191
209
  if (!isNil(min) && val < min) return false;
192
210
  if (!isNil(max) && val > max) return false;
193
211
 
@@ -196,9 +214,24 @@ class NumberInputModel extends HoistInputModel {
196
214
 
197
215
  onKeyDown: KeyboardEventHandler<HTMLInputElement> = ev => {
198
216
  if (ev.key === 'Enter') this.doCommit();
217
+ if (ev.key === 'ArrowUp' || ev.key === 'ArrowDown') this.clampSteppedValue();
199
218
  this.componentProps.onKeyDown?.(ev);
200
219
  };
201
220
 
221
+ onBeforeInput = (ev: InputEvent) => {
222
+ if (this.commasWhileEditing) skipCommaOnDelete(ev);
223
+ };
224
+
225
+ // BP steps the value on arrow keys without applying min/max - clamp the stepped value.
226
+ private clampSteppedValue() {
227
+ const {min, max} = this.componentProps,
228
+ val = this.toExternal(this.internalValue);
229
+ if (!isNumber(val) || isNaN(val)) return;
230
+
231
+ const clamped = clamp(val, min ?? -Infinity, max ?? Infinity);
232
+ if (clamped !== val) this.noteValueChange(this.toInternal(clamped));
233
+ }
234
+
202
235
  formatRenderValue(value: number) {
203
236
  const {componentProps, precision} = this;
204
237
 
@@ -206,7 +239,9 @@ class NumberInputModel extends HoistInputModel {
206
239
 
207
240
  if (this.hasFocus) {
208
241
  const ret = isNumber(value) && !isNil(precision) ? round(value, precision) : value;
209
- return ret?.toString();
242
+ return this.commasWhileEditing
243
+ ? addCommasWhileEditing(ret.toString())
244
+ : ret?.toString();
210
245
  }
211
246
 
212
247
  const {valueLabel, displayWithCommas} = componentProps,
@@ -240,13 +275,17 @@ const cmp = hoistCmp.factory<NumberInputModel>(({model, className, ...props}, re
240
275
  const {width, flex, ...layoutProps} = getLayoutProps(props),
241
276
  renderValue = model.formatRenderValue(model.renderValue);
242
277
 
243
- // BP workaround -- min, max, and stepsize can block Blueprint from rendering
244
- // intended value in underlying control -- ensure it is always shown.
278
+ // Restore the caret after a reformat while editing moved it.
245
279
  useLayoutEffect(() => {
246
- const input = model.inputEl;
247
- if (input) input.value = renderValue;
280
+ const input = model.inputEl as HTMLInputElement;
281
+ if (!input || model.caretPos == null) return;
282
+ setCaretSkippingCommas(input, model.caretPos);
283
+ model.caretPos = null;
248
284
  });
249
285
 
286
+ // Native listener, as React's onBeforeInput does not fire for deletes.
287
+ useOnMount(() => model.inputEl?.addEventListener('beforeinput', model.onBeforeInput));
288
+
250
289
  // BP bases expected precision off of dps in minorStepSize, if specified.
251
290
  // The default BP value of 0.1 for this prop emits a console warning any time the input
252
291
  // value extends beyond 1 dp. Re-default here to sync with our `precision` prop.
@@ -265,8 +304,8 @@ const cmp = hoistCmp.factory<NumberInputModel>(({model, className, ...props}, re
265
304
  disabled: props.disabled,
266
305
  inputRef: useComposedRefs(model.inputRef as Ref<HTMLInputElement>, props.inputRef),
267
306
  leftIcon: props.leftIcon,
268
- min: props.min,
269
- max: props.max,
307
+ // Lets BP parse a comma-formatted value when stepping with the arrow keys.
308
+ locale: model.commasWhileEditing ? 'en-US' : undefined,
270
309
  minorStepSize,
271
310
  majorStepSize,
272
311
  placeholder: props.placeholder,
@@ -414,18 +414,36 @@ class SelectInputModel extends HoistInputModel {
414
414
  super.noteFocused();
415
415
  }
416
416
 
417
- private selectText() {
418
- const {reactSelect} = this;
419
- if (!reactSelect) return;
417
+ /**
418
+ * Enter text into the search input and open the menu, as if typed by the user.
419
+ * Ignored if the select is not searchable.
420
+ */
421
+ enterSearchText(text: string) {
422
+ // Delay to run after the text selection scheduled by `noteFocused()`.
423
+ wait().then(() => {
424
+ const selectComp = this.innerSelect;
425
+ if (!this.hasFocus || !selectComp?.props.isSearchable) return;
426
+
427
+ selectComp.props.onInputChange(text, {
428
+ action: 'input-change',
429
+ prevInputValue: selectComp.props.inputValue ?? ''
430
+ });
431
+ selectComp.openMenu('first');
432
+ });
433
+ }
420
434
 
421
- // Unwrap the HOCs added by AsyncSelect / Creatable / WindowedSelect (each exposes the
422
- // inner Select via `.select`) to reach the underlying Select that owns the inputRef.
423
- let selectComp = reactSelect;
435
+ // Unwrap the HOCs added by AsyncSelect / Creatable / WindowedSelect (each exposes the inner
436
+ // Select via `.select`) to reach the underlying Select that owns the inputRef.
437
+ private get innerSelect() {
438
+ let selectComp = this.reactSelect;
424
439
  while (selectComp && !selectComp.inputRef) {
425
440
  selectComp = selectComp.select;
426
441
  }
427
- const inputElem = selectComp?.inputRef;
442
+ return selectComp;
443
+ }
428
444
 
445
+ private selectText() {
446
+ const inputElem = this.innerSelect?.inputRef;
429
447
  if (this.hasFocus && inputElem && document.activeElement === inputElem) {
430
448
  inputElem.select();
431
449
  }
package/docs/README.md CHANGED
@@ -64,6 +64,7 @@ See [`docs-roadmap.md`](./planning/docs-roadmap.md) for documentation coverage t
64
64
  | Configure local development environment | [Development Environment](./development-environment.md) |
65
65
  | Write or run unit tests, in an app or hoist-react | [Unit Testing](./unit-testing.md) |
66
66
  | Use MCP tools with AI assistants | [`/mcp/`](../mcp/README.md) |
67
+ | Serve a Hoist library's docs through the MCP tools | [Companion Library Docs](./companion-library-docs.md) |
67
68
  | Customize colors, fonts, spacing, or theme | [`/styles/`](../styles/README.md) |
68
69
  | Follow XH coding conventions | [Coding Conventions](./coding-conventions.md) |
69
70
  | Check hoist-react / hoist-core / hoist-dev-utils version compatibility | [Version Compatibility](./version-compatibility.md) |
@@ -158,6 +159,7 @@ for planned coverage:
158
159
  | Tool | Description |
159
160
  |------|-------------|
160
161
  | [MCP Server](../mcp/README.md) | Model Context Protocol server providing AI assistants with structured access to documentation, TypeScript types, and code generation prompts |
162
+ | [Companion Library Docs](./companion-library-docs.md) | How a library that builds on Hoist serves its docs through the MCP server and `hoist-docs` CLI, using a `hoist.docRegistry` field in its `package.json` |
161
163
 
162
164
  ## Upgrade Notes
163
165