From 77c9143471742f7a455e4aec749ad5aeee8d3c67 Mon Sep 17 00:00:00 2001 From: Roman Vyakhirev Date: Fri, 30 Oct 2026 09:57:11 +0100 Subject: [PATCH 01/37] docs: add headless widgets design docs Design docs for the headless widget concept (generic) and the combobox contract with its safety-net rules and the 8-step migration plan. --- docs/design/headless-combobox.md | 452 +++++++++++++++++++++++++++++++ docs/design/headless-widgets.md | 360 ++++++++++++++++++++++++ 2 files changed, 812 insertions(+) create mode 100644 docs/design/headless-combobox.md create mode 100644 docs/design/headless-widgets.md diff --git a/docs/design/headless-combobox.md b/docs/design/headless-combobox.md new file mode 100644 index 0000000000..a3e8dd92d4 --- /dev/null +++ b/docs/design/headless-combobox.md @@ -0,0 +1,452 @@ +# Headless combobox + +Status: exploration, first target of [headless-widgets.md](./headless-widgets.md). Read that document first; this one only holds what is specific to `combobox-web`. + +## 1. Where the seam is today + +The combobox is closer to the concept than it looks. The `Selector` interface in `src/helpers/types.ts` is already a headless model: options, captions, selection, search term, lazy loading, validation, read-only state, Mendix binding. It knows nothing about HTML. + +The other half is tangled into the UI. `SingleSelection.tsx` and `MultiSelection.tsx` each do three jobs at once: wire downshift (keyboard, ARIA, open state), wire floating-ui (positioning), and render Atlas markup with `form-control` classes. So the split is three-way: + +| Today | Becomes | +| --------------------------------------------------------------- | -------------------------- | +| `helpers/` providers and selectors, `useGetSelector` | Core store and ViewModel | +| `useDownshiftSingleSelectProps`, `useDownshiftMultiSelectProps` | `useComboboxBehavior` | +| `useFloatingMenu` | `useComboboxPopover` | +| `components/`, `ui/Combobox.scss` | Atlas View, parts, classes | +| `Combobox.tsx` | Thin wrapper | + +`useGetSelector` already hand-rolls a store and forces re-renders with `setInput({})`. Replacing it with a MobX store and the snapshot hook is a small move. + +Two side channels in the current code disappear once the Core owns UI state, and are worth knowing about before touching the hooks: + +- `useDownshiftSingleSelectProps` and its multi counterpart assign `selector.onLeaveEvent = closeMenu`, so the model holds a callback into downshift. With `isOpen` in the Core, `leave()` closes the menu directly. +- `useGetSelector` registers `onAfterSearchTermChange` on the options provider purely to trigger a React re-render. With MobX, the search term is observable and no callback is needed. + +The selector families (association, database, static, enum/boolean) each have a `Preview/` variant used only by `Combobox.editorPreview.tsx`. Since the editor preview keeps its own rendering, the preview providers can stay in the widget package, or ship in the core package as a `preview` entry. Decide in migration step 1. + +The dropdown-filter plugin (`shared/widget-plugin-dropdown-filter`) is the in-repo precedent: controllers, stores, a `classes()` map in `picker-primitives.tsx`, and a `Combobox` control driven by a `useComboboxProps` factory. It was never designed as a public surface, but its shape is the right one. + +## 2. State ownership decisions + +All of `isOpen`, `inputValue`, and `highlightedIndex` live in the Core: + +- `inputValue` drives the datasource filter (`setSearchTerm`) and the `onChangeFilterInputEvent` with its debounce. +- `onLeaveEvent` closes the menu, so the Core must own `isOpen`. +- `highlightedIndex` is needed for the ARIA status message, and a library View simply ignores it. + +Downshift stays for keyboard and ARIA, but fully controlled: `isOpen`, `inputValue`, `selectedItem`, and `highlightedIndex` are all passed in from the Core and every `onXChange` forwards to a Core command. The key handling and accumulated bug fixes in the two downshift hooks survive the move unchanged. + +Chip order for multi-select (`selectedItemsSorting`) is a model concern, exposed as the order of `chips`, because it is a Studio Pro property with data meaning. It is not a hint. + +## 3. ViewModel + +```ts +interface ComboboxOptionVM { + id: string; + caption: string; // always present: the caption attribute or expression + content?: ReactNode; // present whenever a custom-content widget is configured, regardless of placement + selected: boolean; + highlighted: boolean; +} + +interface ComboboxHints { + readOnlyStyle: "control" | "text"; + selectedItemsStyle: "boxes" | "text"; + loadingType: "skeleton" | "spinner"; + customContent: "none" | "everywhere" | "menuOnly"; // Studio Pro "no" | "yes" | "listItem" +} + +interface ComboboxViewModel extends WidgetViewModel { + mode: "single" | "multi"; + + // state + options: ReadonlyArray; + value: string | ReadonlyArray | null; + selected: ComboboxOptionVM | null; // single mode, the selected option with its caption and content + chips: ReadonlyArray; // multi mode, selected items in configured order + inputValue: string; + isOpen: boolean; + highlightedIndex: number; + clearable: boolean; + filterable: boolean; + allSelected: "all" | "some" | "none"; // multi mode, select-all checkbox state + loading: { isLoading: boolean; hasMore: boolean }; + slots: { menuFooter?: ReactNode }; + + // commands, referentially stable + open(): void; + close(): void; + toggle(): void; + highlight(index: number): void; + select(id: string): void; + deselect(id: string): void; + toggleItem(id: string): void; + clear(): void; + selectAll(): void; + setInputValue(text: string): void; + loadMore(): void; + enter(): void; // widget received focus from outside, fires onEnterEvent + leave(): void; // focus left the widget, fires onLeaveEvent and closes +} +``` + +Notes: + +- `caption` is always a string. The Core needs it anyway for filtering, downshift's `itemToString`, and the ARIA status message. +- `content` is the widget tree the app developer configured under "Custom content" (`optionsSourceAssociationCustomContent` and its database and static siblings). It is the one place React leaks into the contract. The Core builds it whenever the widget is configured and never decides where it is shown. Placement is the View's decision, guided by `hints.customContent`: the Atlas View renders `content` in the menu for `everywhere` and `menuOnly`, and in the input and chips for `everywhere` only. A custom View renders `content ?? caption` wherever it likes. This is safe because every use of the placement today is presentational: `CaptionsProvider.render`, the class and placeholder toggles in `SingleSelection`, and `getSelectedCaptionsPlaceholder`. +- `enter` and `leave` exist so a View that does not use our Behavior can still fire the Mendix enter and leave events. +- All texts come through `vm.t`, see the generic document, section 7.1. The combobox text map: + +```ts +interface ComboboxTexts { + noOptions: []; + emptyOption: []; + clearSelection: []; + removeSelection: []; + selectAll: []; + a11ySelectedValue: [caption: string]; + a11yOptionsAvailable: [count: number]; + a11yInstructions: []; + a11yNoOption: []; +} +``` + +The status message that downshift builds today by concatenating `a11ySelectedValue`, the count, `a11yOptionsAvailable`, and `a11yInstructions` becomes `a11y.statusMessage`, composed by the Core through `t`. A View using our Behavior gets it in the live region; a View without Behavior reads it directly. Parametrised keys replace today's string concatenation, so word order is no longer fixed to English. + +### Structural sharing slices + +`inputSlice` (inputValue, isOpen, highlightedIndex), `selectionSlice` (value, selected, chips, allSelected), `optionsSlice` (array of per-id `optionSlice` entries), `loadingSlice`, `staticSlice` (hints, t, clearable, filterable, a11y). Typing a character rebuilds `inputSlice` only. Moving the highlight creates exactly two new option objects. + +## 4. Behavior + +```ts +interface ComboboxBehavior { + getRootProps(): { onFocus; onBlur }; // enter and leave detection via relatedTarget + getInputProps(): { + id; + role: "combobox"; + value; + onChange; + onKeyDown; + onFocus; + onBlur; + ref; + "aria-expanded"; + "aria-controls"; + "aria-activedescendant"; + "aria-autocomplete"; + "aria-invalid"; + "aria-describedby"; + "aria-required"; + "aria-label"; + "aria-labelledby"; + "data-open"; + "data-disabled"; + }; + getToggleProps(): { tabIndex: -1; onClick; onMouseDown; "aria-label"; "data-open" }; + getMenuProps(): { id; role: "listbox"; "aria-labelledby"; "aria-multiselectable"; onMouseDown; onScroll; ref }; + getOptionProps(index: number): { + id; + role: "option"; + "aria-selected"; + onClick; + onMouseMove; + "data-highlighted"; + "data-selected"; + }; + getChipProps(index: number): { tabIndex; onKeyDown; ref; "data-active" }; + getChipRemoveProps(index: number): { onClick; "aria-label"; tabIndex: -1 }; + getClearProps(): { onClick; "aria-label"; tabIndex }; + getSelectAllProps(): { onClick; "aria-label"; checked: "all" | "some" | "none" }; +} + +function useComboboxBehavior(vm: ComboboxViewModel): ComboboxBehavior; +``` + +Behaviour that must survive, with its current home: + +- Backspace on an empty single-select input clears when clearable (`SingleSelection.onInputKeyDown`). +- Backspace and ArrowLeft redirect to chips only when the caret rule in `isChipNavigationPermitted` allows it (`MultiSelection`). +- Focus restoration after chip removal (`MultiSelection`, chipRefs effect). +- Space toggles the highlighted item in multi mode without closing. +- Menu `onMouseDown` prevents blur; header and footer stop propagation so clicks inside do not close. +- Lazy loading triggers from menu scroll (`useLazyLoading`). + +## 5. Popover + +```ts +function useComboboxPopover(vm: ComboboxViewModel, options?: { alwaysOpen?: boolean }): ComboboxPopover; +``` + +Wraps today's `useFloatingMenu`: fixed strategy, bottom-start, flip, size capped at 320px, width matched to the reference. `alwaysOpen` is the editor preview's `keepMenuOpen` and disables floating entirely. + +## 6. Classes + +```ts +type ComboboxClassKey = + | "root" + | "inputContainer" + | "input" + | "placeholder" + | "toggle" + | "clear" + | "chip" + | "chipRemove" + | "selectAll" + | "menu" + | "menuList" + | "menuItem" + | "menuHeader" + | "menuFooter" + | "noOptions" + | "loader" + | "validation"; + +function classes(prefix = "widget-combobox"): Record; +``` + +Today's modifier classes and their replacements: + +| Today | Becomes | +| ------------------------------------------ | ---------------------------------- | +| `widget-combobox-input-container-active` | `inputContainer` + `data-open` | +| `widget-combobox-input-container-disabled` | `inputContainer` + `data-disabled` | +| `widget-combobox-menu-hidden` | `menu` without `data-open` | +| `widget-combobox-item-highlighted` | `menuItem` + `data-highlighted` | +| `widget-combobox-item-selected` | `menuItem` + `data-selected` | +| `widget-combobox-input-nofilter` | `input` + `data-readonly` | +| `widget-combobox-menu-lazy-scroll` | `menuList` + `data-lazy` | + +`form-control` and `form-control-static` are applied by the Atlas View only, from `hints.readOnlyStyle`. + +## 7. Parts + +```ts +interface ComboboxParts { + Root; + InputContainer; + Input; + Placeholder; + Toggle; + Clear; + Chip; + ChipRemove; + SelectAll; + Menu; + MenuList; + Option; + MenuHeader; + MenuFooter; + NoOptions; + Loader; + Validation; +} +``` + +Each part receives `{ vm, className }` plus its Behavior props (for example `Option` receives `option`, `index`, `optionProps`). The Atlas View is the composition of these parts and nothing else. + +## 8. View contract + +```ts +interface ComboboxViewProps { + core: ComboboxCore; + classes?: Partial; + parts?: Partial; +} +type ComboboxViewComponent = ComponentType; +``` + +## 9. Examples per customisation level + +All of these are files in the app project, see the delivery section of the generic document. Each exports a `ComboboxViewComponent` and nothing else. + +### Level 0: CSS only, no JavaScript + +```css +.widget-combobox-menu-item[data-highlighted] { + background: var(--brand-50); +} +.widget-combobox-menu-item[data-selected] { + font-weight: 600; +} +``` + +### Level 1: a few class touches + +```tsx +import { ComboboxView, type ComboboxViewComponent } from "@mendix/combobox-core"; + +export const MyCombobox: ComboboxViewComponent = props => ( + +); +``` + +Tailwind, same file shape: + +```tsx +export const MyCombobox: ComboboxViewComponent = props => ( + +); +``` + +### Level 2: replace one part + +```tsx +import { ComboboxView, type ComboboxParts, type ComboboxViewComponent } from "@mendix/combobox-core"; + +const MyOption: ComboboxParts["Option"] = ({ option, optionProps, className }) => ( +
  • + + {option.content ?? option.caption} +
  • +); + +export const MyCombobox: ComboboxViewComponent = props => ; +``` + +Keyboard and ARIA keep working because `optionProps` still comes from our Behavior. + +### Level 3a: full View with our Behavior (Tailwind, raw markup) + +```tsx +import { + useComboboxViewModel, + useComboboxBehavior, + useComboboxPopover, + type ComboboxViewComponent +} from "@mendix/combobox-core"; + +export const MyCombobox: ComboboxViewComponent = ({ core }) => { + const vm = useComboboxViewModel(core); + const b = useComboboxBehavior(vm); + const pop = useComboboxPopover(vm); + return ( +
    + + + {vm.isOpen && ( +
      + {vm.options.map((o, i) => ( +
    • + {o.content ?? o.caption} +
    • + ))} +
    + )} + {vm.validation &&

    {vm.validation}

    } +
    + ); +}; +``` + +### Level 3b: full View with a component library (Material UI, no Behavior) + +```tsx +import Autocomplete from "@mui/material/Autocomplete"; +import TextField from "@mui/material/TextField"; +import { useComboboxViewModel, type ComboboxViewComponent } from "@mendix/combobox-core"; + +export const MyCombobox: ComboboxViewComponent = ({ core }) => { + const vm = useComboboxViewModel(core); + const byId = (id: string | null) => vm.options.find(o => o.id === id) ?? null; + return ( + o.caption} + renderOption={(props, o) =>
  • {o.content ?? o.caption}
  • } + value={vm.mode === "single" ? vm.selected : vm.chips} + onChange={(_, next) => (next ? vm.select(next.id) : vm.clear())} + inputValue={vm.inputValue} + onInputChange={(_, text) => vm.setInputValue(text)} + disabled={vm.readOnly} + loading={vm.loading.isLoading} + renderInput={params => ( + + )} + onFocus={vm.enter} + onBlur={vm.leave} + /> + ); +}; +``` + +Material UI owns keyboard and ARIA here. The Core still owns data, Mendix binding, lazy loading, and events. `highlightedIndex` is ignored, which is harmless. `getOptionLabel` uses the plain `caption`; `renderOption` shows custom `content` when the app developer configured it, ignoring the `menuOnly` versus `everywhere` hint, which is the View's prerogative. + +## 10. Thin wrapper and package layout + +```tsx +// packages/pluggableWidgets/combobox-web/src/Combobox.tsx +export default function Combobox(props: ComboboxContainerProps) { + const core = useComboboxCore(props); + const View = useWidgetView("Combobox", props.uiVariant); + return ; +} +``` + +``` +packages/ + headless/combobox/ @mendix/combobox-core + src/core/ ComboboxCore, store, providers (from helpers/), ViewModel builder + src/hooks/ useComboboxViewModel, useComboboxState, useComboboxBehavior, useComboboxPopover + src/atlas/ ComboboxView, parts/, classes.ts, Combobox.scss + src/conformance/ shared test suite + examples/ the five Views above + AGENTS.md + pluggableWidgets/combobox-web/ Combobox.tsx wrapper, XML, editorConfig, editorPreview, icons +``` + +`Combobox.xml` gains one property: `uiVariant`, string, default `atlas`, in the Advanced group. `Combobox.editorPreview.tsx` stays as it is. + +## 11. Safety net + +The existing net is thinner than the migration needs. Status at 2026-10-28: + +| Layer | Coverage | +| -------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| Component unit tests | 29 cases across `SingleSelection`, `MultiSelection`, `StaticSelection`, with 3 DOM snapshots | +| Helper unit tests | 20 cases, all on the database selector and its utils | +| E2E | 28 Playwright cases with 17 visual snapshots: every data source family, keyboard chip handling, onChange, menu positioning | + +Not covered directly at that date: association, static, enum, and boolean selectors; lazy loading; the filter-event debounce; enter and leave events; custom content; validation display. These are exactly what step 1 touches. + +Update, same day: the OpenSpec change `combobox-selector-safety-net` in the package added characterisation tests for rule 1 below. The unit suite went from 6 suites and 61 tests to 16 suites and 194 tests with the 5 snapshots untouched. Every selector family, `getSelector`, `BaseOptionsProvider` filtering, `LazyLoadProvider`, `datasourceFilter` and the `useGetSelector` seam are covered, and each pinned quirk is marked `// Quirk:` in the test and listed in that change's `design.md`. Enter and leave events, custom content rendering beyond `caption.render`, and validation display remain covered only through the component tests. + +Rules, in order of application: + +1. **Characterisation tests first, at the seam that does not move.** The `Selector` interface stays the Core's internal API in step 1. Before any change, write tests against it for every family using the builders in `widget-plugin-test-utils`: `currentId`, `setValue` writing to the attribute or association, `options.getAll` under a search term, `caption.get`, `readOnly`, `validation`, `clearable`, `loadMore`, and `updateProps` transitions from unavailable to available. They pass on the old code and must pass unchanged on the new code. This is what the package's tdd-refactor OpenSpec schema calls "existing behaviour preservation tests". +2. **Strangler, not rewrite.** Step 1 changes the inside of `useGetSelector` and the providers only. `components/` and its tests are untouched. A snapshot diff in steps 1 to 3 is a regression; `pnpm run test -u` is not allowed in those steps. +3. **Split the store change from the re-render change.** Convert the store to MobX while keeping the `setInput({})` trigger, verify, then replace the trigger with a reaction in a separate commit. Two small diffs bisect; one large one does not. +4. **MobX strict mode in tests.** `configure({ enforceActions: "always" })` in the Jest setup, so any mutation outside an action throws in CI instead of showing up as stale UI in Studio Pro. +5. **Never make Mendix values observable.** `ListValue`, `EditableValue`, `ListWidgetValue` go in as `observable.ref` through a props gate, the pattern `widget-plugin-mobx-kit` and the dropdown-filter stores already use. Wrapping one in `makeAutoObservable` breaks silently. +6. **E2E is the gate per step.** Visual snapshots stay identical through step 3. Step 4 (classes and data attributes) is the only step that changes the DOM on purpose and the only step where snapshots are updated, with the diff reviewed in the PR. +7. **Run the component suite against both paths in step 2.** Keep the Selector path alive behind a test-only switch while the ViewModel path is introduced, parametrise the component tests to run twice, delete the old path once both are green. +8. **Manual checklist in Studio Pro** on the `combobox-web-atlas4` test project: one page per data source family, plus read-only, validation, custom content, lazy loading, and the onChange flows. Automated tests do not exercise the editor preview, and the preview providers share code with the runtime ones. + +## 12. Migration plan + +Each step keeps the MPK, the XML, and the existing unit and E2E tests green. + +1. **Extract the store.** Precondition: section 11, rules 1 to 5 in place. Move `getSelector`, the providers, and the selectors into a MobX store under a Core. Replace the forced re-render in `useGetSelector` with the snapshot hook. No change to `components/`. +2. **Build the ViewModel.** Add the computed slices from section 3. Rewrite `SingleSelection` and `MultiSelection` to read from the ViewModel instead of the Selector. Whatever they cannot get from the ViewModel is a gap in the contract; fix the contract, not the View. +3. **Extract Behavior and Popover.** Make downshift controlled by the Core. Move `useDownshift*` and `useFloatingMenu` into the two hooks with the getter shapes from sections 4 and 5. Verify every item in the "behaviour that must survive" list. +4. **Introduce classes and data attributes.** Replace literal class names with the map and modifier classes with data attributes per the table in section 6. Update `Combobox.scss` and the E2E selectors. +5. **Split into parts.** Break the Atlas View into one component per class key. Add the `classes` and `parts` props. +6. **Move to a package.** Create `packages/headless/combobox`, point the widget at it, reduce `Combobox.tsx` to the wrapper in section 10. +7. **Write the second View.** A throwaway Material UI View in a sandbox, run against the conformance suite. This is the real test of the ViewModel shape. +8. **Prove the in-project route.** Add `uiVariant` and the hardcoded first-iteration registry. Put a View file into a Mendix test project with the package in `node_modules`, let the project bundler compile it, hardcode its registration, and confirm the widget renders it with `uiVariant` set. + +Publishing to npm comes after step 8. + +## 13. Open questions (combobox) + +- Which Mendix test project proves step 8, and where exactly does the hardcoded registration call live? +- Does the existing combobox OpenSpec folder get one change per migration step, or one change for the whole split? diff --git a/docs/design/headless-widgets.md b/docs/design/headless-widgets.md new file mode 100644 index 0000000000..5f9774b17d --- /dev/null +++ b/docs/design/headless-widgets.md @@ -0,0 +1,360 @@ +# Headless widgets: replaceable UI for pluggable widgets + +Status: exploration, not yet scheduled. First target: combobox, see [headless-combobox.md](./headless-combobox.md). + +This document is the widget-agnostic concept. Per-widget documents hold the concrete contract, examples, migration plan, and questions for one widget. + +## 1. Problem + +Every widget in this repository is a monolith. One component owns the Mendix binding (EditableValue, ListValue, ActionValue), the lifecycle, the keyboard and ARIA behaviour, the popover positioning, and the HTML structure styled with Atlas UI classes. Atlas is coupled to an outdated Bootstrap, so the markup and class structure of every widget is dictated by it. + +App developers increasingly want widgets to render in their own design system: Material UI, Ant Design, Tailwind, or a corporate component library. Today the only option is to override Atlas CSS against undocumented class names. Changing the HTML structure is impossible. + +## 2. Goal + +Split each widget into a part we own, which keeps the lifecycle, the Mendix API binding, and the hard behaviour, and a part the app developer may replace, which renders the HTML. Ship our own Atlas rendering as the default so existing apps see no change. + +App developers never rebuild widgets. They write or adjust a View as a file in their own project, with our package in `node_modules`, and the widget picks it up. We stay in control of the Core and the Marketplace widget. + +Non-goals for the first iteration: + +- Data grid. Its surface is too large to prove the concept on. +- Studio Pro design-mode preview of custom UIs. The editor preview keeps its own simplified rendering. +- A visual theming tool. This is a code-level contract. + +## 3. Vocabulary + +| Term | Meaning | +| ------------- | ----------------------------------------------------------------------------------------------------------------- | +| **Core** | Headless object per widget. Owns all state, the Mendix binding, and the lifecycle. Implemented with MobX. | +| **ViewModel** | Plain, immutable object the Core exposes. State plus stable commands. The only required public contract. | +| **View** | React component that renders a ViewModel. We ship the Atlas View. App developers may ship their own. | +| **Behavior** | Optional hook that turns a ViewModel into DOM prop getters: keyboard handling and ARIA attributes. | +| **Popover** | Optional hook that positions a floating element. Wraps floating-ui. | +| **Classes** | Typed map of CSS hook names, one per rendered part. Overridable. | +| **Parts** | Small components used by the Atlas View, one per element. Individually replaceable. | +| **Host** | Whatever creates a Core and mounts a View. The pluggable widget is the host in apps; our test harness is another. | +| **Variant** | Free-string name of a View, set per widget instance in Studio Pro through the `uiVariant` property. | + +"Headless" follows the industry use of the word (Headless UI, Radix Primitives, React Aria, Downshift). + +## 4. Layering + +``` +Mendix props ──▶ Core (MobX store, Mendix binding, all state) + │ + ├── ViewModel plain data + stable commands REQUIRED + ├── useXBehavior(vm) keyboard + ARIA prop getters optional + ├── useXPopover(vm) floating refs + styles optional + ├── classes() CSS hook names optional + └── parts one small component per element optional + │ + ▼ + View (Atlas default, or app developer's) +``` + +Rules that keep the layering honest: + +1. The Core knows nothing about HTML. No class names, no refs, no DOM events. +2. The ViewModel contains plain data and functions. No MobX observables, no React nodes except where a slot explicitly carries one. +3. The Atlas View is built only from the ViewModel and the optional helpers. If the Atlas View needs something the ViewModel does not expose, the ViewModel is incomplete. +4. Behavior, Popover, Classes, and Parts are each a function of the ViewModel. None of them hold model state. +5. Studio Pro properties that only describe Atlas presentation are exposed as advisory `hints`. A custom View may ignore them. + +## 5. State ownership + +All state lives in the Core, including UI-looking state such as open flags, input text, and highlighted index. Reasons: + +- Mendix often cares about it. Input text may drive a datasource filter and an event; a leave event may close a menu. +- A View built on a component library (Material UI, Ant) runs that library in controlled mode against the ViewModel. Such libraries accept open, input value, and value as controlled props. +- One source of truth makes conformance tests (section 11) meaningful regardless of the View. + +Third-party behaviour libraries such as downshift may stay, but in fully controlled mode: the Core is the source of truth and the library reduces DOM events into Core commands. + +## 6. Reactivity: MobX inside, plain objects outside + +The Core is a MobX store. MobX is never exposed. The Mendix client bundles its own MobX version and widgets bundle another. `observer` from one copy cannot see observables from another, so exposing a MobX object would force every app developer onto our exact MobX instance. + +### 6.1 Snapshot hook + +The Core exposes `viewModel` as a MobX `computed`. A computed caches, so two reads with no state change in between return the same reference. That is exactly the contract `useSyncExternalStore` needs. + +```ts +function useWidgetViewModel(core: { viewModel: VM }): VM { + const subscribe = useCallback((onChange: () => void) => reaction(() => core.viewModel, onChange), [core]); + const getSnapshot = useCallback(() => core.viewModel, [core]); + return useSyncExternalStore(subscribe, getSnapshot); +} +``` + +A selector variant is offered next to it, built on `useSyncExternalStoreWithSelector`, so sub-components subscribe to a slice only: + +```ts +const isOpen = useWidgetState(core, vm => vm.isOpen); +``` + +### 6.2 Structural sharing + +The ViewModel is a tree of computeds, not one big computed. Each slice is its own cached getter. Per-item slices are cached by id with `computedFn`. + +```ts +class SomeCore { + get headerSlice() { + return { value: this.store.inputValue, isOpen: this.store.isOpen }; + } + get itemsSlice() { + return this.store.visibleIds.map(id => this.itemSlice(id)); + } + itemSlice = computedFn((id: string) => ({ + id, + caption: this.store.caption(id), + selected: this.store.isSelected(id) + })); + get viewModel() { + return { ...this.headerSlice, items: this.itemsSlice, ...this.commands }; + } +} +``` + +A change in one slice rebuilds that slice and the top-level object. Every other slice and every unchanged item keep their reference, so `React.memo` in a View skips them. This is what keeps plain-object snapshots cheap enough for lists. + +### 6.3 Commands are stable + +Commands are bound once in the Core constructor. Their identity never changes, so `onClick={vm.open}` does not defeat memoisation. + +### 6.4 Our own Views + +Views inside this repository may use `observer` from our MobX copy and read the store directly for fine-grained updates. The Atlas View deliberately does not, for the first iteration. It consumes the ViewModel through the public snapshot hook, so it doubles as the proof that the contract is complete. + +### 6.5 Rejected alternative: live ViewModel + +A ViewModel whose properties are getters reading observables, with the Core supplying an `observer` wrapper (`core.observe(MyView)`), gives fine-grained tracking without exposing MobX. It is rejected as the default because of the classic footgun: passing the live object to a memoised child that reads a property the parent did not read means the child never updates. Plain snapshots cannot surprise anyone that way. It may return later as an opt-in for power users. + +## 7. The ViewModel envelope + +Every widget's ViewModel starts with the same envelope. This is what keeps the concept uniform across simple and complex widgets. + +```ts +interface WidgetViewModel { + id: string; + status: "loading" | "ready" | "unavailable"; + readOnly: boolean; + validation?: string; + a11y: { label?: string; required: boolean; describedBy?: string; statusMessage?: string }; + hints: Hints; // advisory, Atlas-presentation properties from Studio Pro + t: Translate; // all user-facing and ARIA texts, see 7.1 + className?: string; // Studio Pro "Class" system property + style?: CSSProperties; // Studio Pro "Style" system property +} +``` + +Widget-specific state and commands extend it. Commands are referentially stable. Nothing in a ViewModel type may mention a behaviour library, a positioning library, Atlas, or class names. + +### 7.1 Texts + +Every text a View may need, including ARIA labels and live-region fragments, comes through one function on the envelope: + +```ts +type TextMap = Record; // key -> parameter tuple + +type Translate = (key: K, ...params: Texts[K]) => string; + +// usage +vm.t("noOptions"); // "No options found" +vm.t("optionsAvailable", 12); // "Number of options available: 12" +``` + +Rules: + +- **Keys and parameter arity are typed per widget.** Each widget declares its `TextMap`. A View author or an agent sees every available text in autocompletion, and a wrong parameter count fails to compile. +- **ARIA texts are ordinary texts.** Labels for clear, remove, select-all, and the live-region fragments are all keys. Nothing is hidden inside Behavior. +- **A composed live-region message is a convenience, not a replacement.** Where the Core composes a status message from several fragments and runtime state, it exposes the result as `a11y.statusMessage`, built through `t`. Behavior feeds it to the live region; a View without Behavior reads it directly. The atomic keys stay available. +- **Views bring their own strings for anything we do not define.** `t` only knows our keys. A custom View that wants an extra tooltip uses the app's own mechanism. +- **Parameter substitution is not our concern.** Placeholders, formatting, and language selection are done by the platform. We pass a key and parameters and get a string. + +Where the strings come from is a platform matter. Mendix is introducing system text translations with an API of roughly this shape. We consume that API and wrap it, so the ViewModel shape stays ours and never exposes the platform type directly. Implementation details, including how the current per-instance text template properties map onto it, are deliberately left for later. + +A range slider shows how small the widget-specific part can be, and that the envelope scales down: + +```ts +interface RangeSliderViewModel extends WidgetViewModel<{ tooltipMode: "always" | "hover" | "never" }> { + value: readonly [number, number]; + min: number; + max: number; + step: number; + marks: ReadonlyArray<{ value: number; label?: string }>; + orientation: "horizontal" | "vertical"; + setValue(next: readonly [number, number]): void; // live, while dragging + commit(): void; // write to attributes and fire onChange +} +``` + +Complex widgets compose: a data grid ViewModel would hold column, row, pagination, and filter ViewModels, each with its own snapshot hook, so the structural sharing of section 6.2 applies one level deeper. + +## 8. Optional helpers + +All four helpers are functions of the ViewModel. A View picks the subset it needs. The Atlas View uses all of them. + +### 8.1 Behavior + +Behavior reads ViewModel state, calls ViewModel commands, and returns DOM attributes and handlers for the View to spread onto whichever elements it chooses. The shape is prop getters, the pattern downshift and React Aria use: one `getXProps()` per interactive element, returning `role`, `aria-*`, `id`, event handlers, a `ref` where focus management needs one, and the state data attributes from section 8.3. + +It is a hook, not a field on the ViewModel, for three reasons. It needs DOM refs and effects such as restoring focus. It is optional, so a View built on a component library never calls it. Keeping it out of the ViewModel keeps the ViewModel pure data, which is what makes it serializable, loggable, and testable without a DOM. + +### 8.2 Popover + +Positioning is a separate hook from Behavior on purpose. Ant and Material UI bring their own popper but may still want our keyboard handling, or the reverse. The hook returns `setReference`, `setFloating`, `styles`, and `isPositioned`. + +### 8.3 Classes and state attributes + +The Classes map has one key per rendered part. Nothing for colours or sizes. Atlas framework classes such as `form-control` are not in the map; they belong to the Atlas View alone. Published names are API: renaming one is a breaking change of the npm package. + +Structural identity goes in classes. State goes in boolean data attributes: `data-open`, `data-highlighted`, `data-selected`, `data-disabled`, `data-loading`, `data-empty`, `data-active`, `data-invalid`. Modifier classes such as `widget-x-item-highlighted` are retired. This is what makes every styling approach work without translation: + +```scss +// Atlas SCSS +.widget-x-menu-item[data-highlighted] { + background: $brand-primary-light; +} +``` + +```html + +
  • +``` + +Overrides replace the default class for that key, they do not append. A Tailwind user does not want the Atlas class left behind dragging Atlas rules with it. Appending is explicit: `menuItem: cx(defaultClasses.menuItem, "extra")`. + +### 8.4 Parts + +Parts are the small components the Atlas View is assembled from, one per Classes key. Each receives its slice of the ViewModel plus the matching Behavior props, and spreads them. Replacing one part keeps keyboard and ARIA working because the props still come from our Behavior. + +## 9. The View contract and the customisation levels + +```ts +interface WidgetViewProps { + core: Core; + classes?: Partial; + parts?: Partial; +} +``` + +Every View, ours or theirs, has this signature. That continuity is the point: a View that starts as a two-line class override never has to be thrown away to become a full rewrite. + +| Level | What the app developer writes | What they keep from us | +| ----- | ----------------------------------------------------------------------- | --------------------------------------- | +| 0 | CSS against published class names and data attributes. No View file. | Everything | +| 1 | A View that renders our Atlas View with a `classes` override | Markup, behaviour, positioning | +| 2 | Same, plus one or more `parts` replaced | Behaviour, positioning, remaining parts | +| 3a | Their own markup using our Behavior and Popover hooks | Keyboard, ARIA, positioning | +| 3b | A component-library widget in controlled mode, using the ViewModel only | Data, Mendix binding, events | + +Concrete examples for each level live in the per-widget documents. + +## 10. Hosting and delivery + +### 10.1 The widget as a thin wrapper + +The npm package is the product. The pluggable widget is the host for it inside apps. The wrapper keeps three responsibilities and sheds everything else: + +1. Declare the Studio Pro surface: XML, editor config, editor preview, icons, package metadata. +2. Kickstart the Core: create on mount, feed container props on every render, dispose on unmount. +3. Resolve the View: read the `uiVariant` property, ask the registry, fall back to the Atlas View. + +```tsx +export default function SomeWidget(props: SomeWidgetContainerProps) { + const core = useSomeWidgetCore(props); + const View = useWidgetView("SomeWidget", props.uiVariant); + return ; +} +``` + +Our own test harness and Storybook host the Core with the same lines. If the wrapper needs a private API the harness cannot reach, the design has a hole. + +### 10.2 Package layout + +A new package type beside `pluggableWidgets` and `shared`: + +``` +packages/ + headless// @mendix/-core public npm package + src/core/ store, providers, ViewModel builder + src/hooks/ useXViewModel, useXState, useXBehavior, useXPopover + src/atlas/ XView, parts, classes, X.scss + src/conformance/ shared test suite (section 11) + examples/ one View per customisation level + AGENTS.md agent-facing guide to the contract + pluggableWidgets/-web/ thin wrapper, depends on the core as workspace:* +``` + +In the first iteration a Core accepts the generated `XContainerProps` directly. That couples the npm package to the XML, so they move together. A narrower config type is a later refinement. + +### 10.3 Delivery: Views live in the app project + +This is the primary and, for now, the only supported route. + +- The app developer's View is a source file inside their Mendix project. It is theirs to edit, by hand or by an AI agent. It exports a component and nothing else. +- Our Core, hooks, Atlas View, parts, and types sit in `node_modules` next to that file. The thin widget sits in the project as the Marketplace MPK. Neither is edited by the app developer. +- **Compilation is the project bundler's job.** The View file is compiled by the Mendix project bundler at project run or build time, together with everything else, never earlier and never by us. We ship source-compatible packages and types, not a build step. +- **Duplication is the project bundler's job.** The MPK, the package in `node_modules`, and the View file are bundled in the same pass. We do not design around two copies. +- **The registry belongs to the client.** It is a client-owned lookup from widget id plus variant name to a View component. The widget only reads from it. +- **Registration belongs to Studio Pro.** How a View file becomes known to the registry is out of scope for this design. We assume the View is already in the registry when the widget mounts. +- **For the first iteration both are hardcoded.** Until the client and Studio Pro provide them, the registry is a small window-scoped object we own, following the pattern of `widget-plugin-external-events`, and registration is a hardcoded call in a known place. This is scaffolding to prove the contract, not the design. +- **`uiVariant` is a free string**, defaulting to `atlas`. A picker or enumeration may come later. + +React is enforced by the Mendix client, so a registered View runs on the same React as the widget. + +**Rejected for now: the rebuild route.** App developers could scaffold a widget around the Core and ship it with the same widget id. Rejected because we want to stay in control of the widget, and because it puts the app developer in charge of a build pipeline when they should only be in charge of UI. + +### 10.4 Least friction: built for agents as much as for people + +The app developer, and increasingly their AI agent, should concentrate on the UI and nothing else. The package therefore carries everything an agent needs to produce a correct View without reading our source: + +- **Types are the documentation.** Every public type has a JSDoc line per member stating what it is and when it changes. +- **Examples ship in the package.** One View per customisation level. An agent copies the closest one. +- **An agent-facing guide ships in the package.** Describes the contract, the levels, the rule that `hints` are advisory, and the data-attribute convention. +- **Conformance tests run inside the project.** The suite from section 11 is importable, so a View can be tested locally and by the agent before the app runs. +- **Optional scaffold command.** Writes the level-1 example and a conformance test file into the project. An agent can do the same from the examples folder. + +Success test: an agent with only the package in `node_modules` and a one-line request ("make the combobox look like our Tailwind design system") produces a working, accessible View on the first attempt. + +### 10.5 Versioning + +Two versions after the split. The npm package follows semver on the ViewModel, the Behavior getters, the Parts props, and the Classes map. The MPK remains a Marketplace artifact that pins a core version. Changelog discipline covers both. + +## 11. Conformance tests + +We cannot guarantee accessibility of a custom View. We can hand the author the test suite we use ourselves. Each package ships a Jest + RTL suite and a Playwright suite that take any View component for that widget and assert the behaviour the widget promises: opening, keyboard navigation, selection, dismissal, ARIA state tracking, lazy loading where applicable. The Atlas View runs the same suite in CI. + +## 12. Rollout order + +1. Combobox, internally, with no publishing. Proves Core, ViewModel, Behavior, Popover, Classes, Parts, and the Atlas View split. See [headless-combobox.md](./headless-combobox.md). +2. A throwaway second View on a component library, run against the conformance suite. The real test of the contract. +3. The in-project delivery route, with the hardcoded registry and registration, in a Mendix test project. +4. Range slider, to confirm the envelope generalises down. +5. Publishing to npm. +6. Remaining widgets one at a time. Data grid last. + +## 13. Open questions (generic) + +- Does the registry key on widget id, or on a stable headless package name, so that a renamed widget keeps its Views? +- Should the envelope carry the Studio Pro label (`labelId`, label caption) for widgets with the Label system property, or is that the host's concern? +- Where does `useWidgetView` and the temporary registry live: a new shared plugin package, or inside `widget-plugin-platform`? +- Which widgets after the range slider? Candidates with small surfaces and clear value: switch, rating, badge button, progress bar. +- `widget-plugin-dropdown-filter` carries a second, private combobox implementation for the data grid filters. Once the headless combobox exists, should the filter controls become Views over the same Core, or stay separate because their model (filter store, not attribute binding) differs? +- How do we test a View in isolation inside this repo before the registry exists: Storybook, a Jest harness hosting the Core with mocked Mendix values from `widget-plugin-test-utils`, or both? + +## 14. Decisions log + +| Date | Decision | +| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 2026-10-28 | Views live in the app project; the rebuild route is rejected. We stay in control of the Core and the MPK. | +| 2026-10-28 | The project bundler compiles the View file and deduplicates the package. We ship no build step. | +| 2026-10-28 | Registry is the client's; registration is Studio Pro's. Both hardcoded in the first iteration. | +| 2026-10-28 | `uiVariant` is a free string. | +| 2026-10-28 | Editor preview keeps its own simplified rendering. | +| 2026-10-28 | MobX inside the Core, never exposed. Plain snapshot ViewModel with structural sharing is the public contract. | +| 2026-10-28 | Atlas View consumes the ViewModel through the public hook, as proof the contract is complete. | +| 2026-10-28 | Combobox first, range slider second, data grid deferred. | +| 2026-10-28 | Options carry `caption: string` always and `content?: ReactNode` when configured. Placement is a hint; the Core never decides where content is shown. | +| 2026-10-28 | All texts, ARIA included, come through a typed `t(key, ...params)` on the envelope, wrapping the upcoming platform system-text API. Mechanics out of scope. | From f7ca4925d0ecacd604320a4aeda222a117539e07 Mon Sep 17 00:00:00 2001 From: Roman Vyakhirev Date: Thu, 29 Oct 2026 14:49:24 +0100 Subject: [PATCH 02/37] build(combobox-web): add mobx, mobx-kit and brandi, run jest in strict action mode Adds mobx 6.12.3, @mendix/widget-plugin-mobx-kit and brandi for the headless combobox plan: the selector store becomes observable (step 1) and the core is assembled from a brandi container like the data grid and gallery widgets (step 2). The package now runs Jest through its own jest.config.js so a setup file can enable enforceActions: always and turn the MobX strict-mode warning into a test failure. --- .../pluggableWidgets/combobox-web/jest.setup.ts | 14 ++++++++++++++ .../pluggableWidgets/combobox-web/package.json | 5 ++++- pnpm-lock.yaml | 11 ++++++++++- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/pluggableWidgets/combobox-web/jest.setup.ts b/packages/pluggableWidgets/combobox-web/jest.setup.ts index cae07e08e6..452b790324 100644 --- a/packages/pluggableWidgets/combobox-web/jest.setup.ts +++ b/packages/pluggableWidgets/combobox-web/jest.setup.ts @@ -1,3 +1,17 @@ +import { configure } from "mobx"; + +// Every observable mutation must go through an action. MobX only warns about violations, so the +// warning is turned into a failure here; in Studio Pro the same mistake shows up as stale UI. +configure({ enforceActions: "always" }); + +const warn = console.warn; +console.warn = (...args: unknown[]): void => { + if (typeof args[0] === "string" && args[0].startsWith("[MobX]")) { + throw new Error(args[0]); + } + warn(...args); +}; + // downshift checks in development that every getter of a hook in use is called and its ref applied, // and only logs when it is not. The log is turned into a failure here; in the browser it floods the // console on every render of the widget. diff --git a/packages/pluggableWidgets/combobox-web/package.json b/packages/pluggableWidgets/combobox-web/package.json index 1dff199d52..d4cd86e9fc 100644 --- a/packages/pluggableWidgets/combobox-web/package.json +++ b/packages/pluggableWidgets/combobox-web/package.json @@ -50,9 +50,12 @@ }, "dependencies": { "@floating-ui/react": "^0.26.27", + "@mendix/widget-plugin-mobx-kit": "workspace:*", + "brandi": "^5.0.0", "classnames": "^2.5.1", "downshift": "^7.6.2", - "match-sorter": "^8.1.0" + "match-sorter": "^8.1.0", + "mobx": "6.12.3" }, "devDependencies": { "@mendix/automation-utils": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 348100127e..4004a64bbc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -965,6 +965,12 @@ importers: '@floating-ui/react': specifier: ^0.26.27 version: 0.26.28(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@mendix/widget-plugin-mobx-kit': + specifier: workspace:* + version: link:../../shared/widget-plugin-mobx-kit + brandi: + specifier: ^5.0.0 + version: 5.1.0 classnames: specifier: ^2.5.1 version: 2.5.1 @@ -974,6 +980,9 @@ importers: match-sorter: specifier: ^8.1.0 version: 8.3.0 + mobx: + specifier: 6.12.3 + version: 6.12.3(patch_hash=39c55279e8f75c9a322eba64dd22e1a398f621c64bbfc3632e55a97f46edfeb9) devDependencies: '@mendix/automation-utils': specifier: workspace:* @@ -11084,7 +11093,7 @@ packages: optional: true xlsx@https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz: - resolution: {tarball: https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz} + resolution: {integrity: sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==, tarball: https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz} version: 0.20.3 engines: {node: '>=0.8'} hasBin: true From a06d55f30733c196b18b657755db2f9ee82effa6 Mon Sep 17 00:00:00 2001 From: Roman Vyakhirev Date: Thu, 29 Oct 2026 14:52:07 +0100 Subject: [PATCH 03/37] refactor(combobox-web): make the selector store observable with mobx Every selector, options provider, captions provider and the lazy-load provider now declares its state with makeObservable. Mendix values enter as observable.ref only, props updates and setters are actions, derived getters are computed. The Selector interface and the re-render trigger in useGetSelector are unchanged so the characterisation tests pass as they are. StaticOptionsProvider loses three field redeclarations that would have shadowed the base class observables. --- .../Association/AssociationMultiSelector.ts | 13 +++++++++++++ .../Association/AssociationOptionsProvider.ts | 6 ++++++ .../AssociationSimpleCaptionsProvider.tsx | 11 ++++++++++- .../Association/AssociationSingleSelector.ts | 7 +++++++ .../Association/BaseAssociationSelector.ts | 13 +++++++++++++ .../helpers/BaseDatasourceOptionsProvider.ts | 14 ++++++++++++++ .../src/helpers/BaseOptionsProvider.ts | 14 ++++++++++++++ .../Database/DatabaseCaptionsProvider.tsx | 13 ++++++++++++- .../Database/DatabaseMultiSelectionSelector.ts | 17 +++++++++++++++++ .../Database/DatabaseSingleSelectionSelector.ts | 16 ++++++++++++++++ .../helpers/Database/DatabaseValuesProvider.ts | 9 ++++++++- .../EnumAndBooleanSimpleCaptionsProvider.tsx | 10 ++++++++++ .../helpers/EnumBool/EnumBoolOptionsProvider.ts | 6 ++++++ .../helpers/EnumBool/EnumBoolSingleSelector.tsx | 13 +++++++++++++ .../src/helpers/LazyLoadProvider.ts | 10 ++++++++++ .../helpers/Static/StaticCaptionsProvider.tsx | 12 +++++++++++- .../src/helpers/Static/StaticOptionsProvider.ts | 6 +++--- .../src/helpers/Static/StaticSingleSelector.ts | 13 +++++++++++++ .../__tests__/BaseOptionsProvider.spec.ts | 8 ++++++-- 19 files changed, 202 insertions(+), 9 deletions(-) diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationMultiSelector.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationMultiSelector.ts index 44729b3756..13b9aae0d2 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationMultiSelector.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationMultiSelector.ts @@ -1,4 +1,5 @@ import { ReferenceSetValue } from "mendix"; +import { action, makeObservable, observable, override } from "mobx"; import { ThreeStateCheckBoxEnum } from "@mendix/widget-plugin-component-kit/ThreeStateCheckBox"; import { ComboboxContainerProps, @@ -20,6 +21,18 @@ export class AssociationMultiSelector selectAllButton = false; selectedItemsSorting: SelectedItemsSortingEnum = "none"; + constructor(props: { filterInputDebounceInterval: number }) { + super(props); + makeObservable(this, { + selectedItemsStyle: observable, + selectionMethod: observable, + selectAllButton: observable, + selectedItemsSorting: observable, + updateProps: override, + setValue: action + }); + } + updateProps(props: ComboboxContainerProps): void { super.updateProps(props); this.selectedItemsStyle = props.selectedItemsStyle; diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationOptionsProvider.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationOptionsProvider.ts index e7ba43f417..99fb438b5d 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationOptionsProvider.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationOptionsProvider.ts @@ -1,4 +1,5 @@ import { ReferenceSetValue, ReferenceValue } from "mendix"; +import { makeObservable, override } from "mobx"; import { BaseDatasourceOptionsProvider, BaseProps } from "../BaseDatasourceOptionsProvider"; type Props = BaseProps & { @@ -6,6 +7,11 @@ type Props = BaseProps & { }; export class AssociationOptionsProvider extends BaseDatasourceOptionsProvider { + constructor(...args: ConstructorParameters) { + super(...args); + makeObservable(this, { _updateProps: override }); + } + _updateProps(props: Props): void { super._updateProps(props); diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSimpleCaptionsProvider.tsx b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSimpleCaptionsProvider.tsx index b756e76145..11821df1d1 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSimpleCaptionsProvider.tsx +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSimpleCaptionsProvider.tsx @@ -1,4 +1,5 @@ import { DynamicValue, ListAttributeValue, ListExpressionValue, ListWidgetValue, ObjectItem } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ReactNode } from "react"; import { OptionsSourceAssociationCustomContentTypeEnum } from "../../../typings/ComboboxProps"; import { CaptionPlacement, CaptionsProvider } from "../types"; @@ -18,7 +19,15 @@ export class AssociationSimpleCaptionsProvider implements CaptionsProvider { protected customContentType: OptionsSourceAssociationCustomContentTypeEnum = "no"; emptyCaption = ""; - constructor(private optionsMap: Map) {} + constructor(private optionsMap: Map) { + makeObservable(this, { + formatter: observable.ref, + customContent: observable.ref, + customContentType: observable, + emptyCaption: observable, + updateProps: action + }); + } updateProps(props: Props): void { if (!props.emptyOptionText || props.emptyOptionText.status === "unavailable") { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSingleSelector.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSingleSelector.ts index 8f0455dbcd..54f2362129 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSingleSelector.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Association/AssociationSingleSelector.ts @@ -1,4 +1,5 @@ import { ReferenceValue } from "mendix"; +import { action, makeObservable, override } from "mobx"; import { ComboboxContainerProps } from "../../../typings/ComboboxProps"; import { SingleSelector } from "../types"; import { BaseAssociationSelector } from "./BaseAssociationSelector"; @@ -8,6 +9,12 @@ export class AssociationSingleSelector implements SingleSelector { type = "single" as const; + + constructor(props: { filterInputDebounceInterval: number }) { + super(props); + makeObservable(this, { updateProps: override, setValue: action }); + } + updateProps(props: ComboboxContainerProps): void { super.updateProps(props); this.currentId = this._attr?.value?.id ?? null; diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Association/BaseAssociationSelector.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Association/BaseAssociationSelector.ts index 30b4bad3ea..ec429485a4 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Association/BaseAssociationSelector.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Association/BaseAssociationSelector.ts @@ -1,4 +1,5 @@ import { ListAttributeValue, ObjectItem, ReferenceSetValue, ReferenceValue } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ComboboxContainerProps, LoadingTypeEnum, @@ -28,6 +29,18 @@ export class BaseAssociationSelector(this, { + status: observable, + clearable: observable, + currentId: observable.ref, + readOnly: observable, + lazyLoading: observable, + loadingType: observable, + customContentType: observable, + validation: observable, + _attr: observable.ref, + updateProps: action + }); } updateProps(props: ComboboxContainerProps): void { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/BaseDatasourceOptionsProvider.ts b/packages/pluggableWidgets/combobox-web/src/helpers/BaseDatasourceOptionsProvider.ts index ca719d9bbe..14ea81d486 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/BaseDatasourceOptionsProvider.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/BaseDatasourceOptionsProvider.ts @@ -1,5 +1,6 @@ import { ListAttributeValue, ListValue, ObjectItem } from "mendix"; import { FilterCondition } from "mendix/filters"; +import { action, computed, makeObservable, observable, override } from "mobx"; import { debounce } from "@mendix/widget-plugin-platform/utils/debounce"; import { BaseOptionsProvider } from "./BaseOptionsProvider"; import { datasourceFilter } from "./datasourceFilter"; @@ -33,6 +34,19 @@ export class BaseDatasourceOptionsProvider extends BaseOptionsProvider(this, { + ds: observable.ref, + attributeId: observable.ref, + loading: observable, + sortOrder: computed, + status: override, + hasMore: override, + isLoading: override, + datasourceFilter: computed, + loadMore: override, + loadSelectedValue: action, + _updateProps: override + }); } get sortOrder(): SortOrder { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/BaseOptionsProvider.ts b/packages/pluggableWidgets/combobox-web/src/helpers/BaseOptionsProvider.ts index dccef45840..e92d0d9195 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/BaseOptionsProvider.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/BaseOptionsProvider.ts @@ -1,4 +1,5 @@ import { matchSorter, MatchSorterOptions } from "match-sorter"; +import { action, computed, makeObservable, observable } from "mobx"; import { FilterTypeEnum } from "typings/ComboboxProps"; import { CaptionsProvider, OptionsProvider, Status } from "./types"; import { getFilterTypeOptions } from "./utils"; @@ -14,6 +15,18 @@ export class BaseOptionsProvider implements OptionsProv constructor(caption: CaptionsProvider) { this.caption = caption; + makeObservable(this, { + options: observable.ref, + filterType: observable, + searchTerm: observable, + lazyLoading: observable, + hasMore: computed, + isLoading: computed, + status: computed, + setSearchTerm: action, + loadMore: action, + _updateProps: action + }); } get hasMore(): boolean { @@ -50,6 +63,7 @@ export class BaseOptionsProvider implements OptionsProv this.trigger?.(); } + /** @deprecated The search term is observable; subscribe to it instead. Kept until step 2 drops it from the interface. */ onAfterSearchTermChange(callback: () => void): void { this.trigger = callback; } diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseCaptionsProvider.tsx b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseCaptionsProvider.tsx index dccc7d5c8f..fbd331de72 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseCaptionsProvider.tsx +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseCaptionsProvider.tsx @@ -1,4 +1,5 @@ import { DynamicValue, ListAttributeValue, ListExpressionValue, ListWidgetValue, ObjectItem } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ReactNode } from "react"; import { OptionsSourceAssociationCustomContentTypeEnum } from "../../../typings/ComboboxProps"; import { CaptionPlacement, CaptionsProvider } from "../types"; @@ -22,7 +23,17 @@ export class DatabaseCaptionsProvider implements CaptionsProvider { emptyCaption = ""; overrideCaption: string | null | undefined = undefined; - constructor(private optionsMap: Map) {} + constructor(private optionsMap: Map) { + makeObservable(this, { + formatter: observable.ref, + customContent: observable.ref, + customContentType: observable, + attribute: observable.ref, + emptyCaption: observable, + overrideCaption: observable, + updateProps: action + }); + } updateProps(props: Props): void { if (!props.emptyOptionText || props.emptyOptionText.status === "unavailable") { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseMultiSelectionSelector.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseMultiSelectionSelector.ts index 6574d7bdf2..78393ca8e1 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseMultiSelectionSelector.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseMultiSelectionSelector.ts @@ -1,4 +1,5 @@ import { ListAttributeValue, ObjectItem, SelectionMultiValue } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ThreeStateCheckBoxEnum } from "@mendix/widget-plugin-component-kit/ThreeStateCheckBox"; import { ComboboxContainerProps, @@ -37,6 +38,22 @@ export class DatabaseMultiSelectionSelector implements MultiSelector { constructor(props: { filterInputDebounceInterval: number }) { this.caption = new DatabaseCaptionsProvider(this._objectsMap); this.options = new DatabaseOptionsProvider(this.caption, this._objectsMap, props.filterInputDebounceInterval); + makeObservable(this, { + clearable: observable, + currentId: observable.ref, + customContentType: observable, + lazyLoading: observable, + loadingType: observable, + readOnly: observable, + selectAllButton: observable, + selectedItemsStyle: observable, + selection: observable.ref, + selectionMethod: observable, + status: observable, + selectedItemsSorting: observable, + updateProps: action, + setValue: action + }); } getOptions(): string[] { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseSingleSelectionSelector.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseSingleSelectionSelector.ts index 6510505fa6..484dce7bf2 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseSingleSelectionSelector.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseSingleSelectionSelector.ts @@ -1,4 +1,5 @@ import { EditableValue, ListAttributeValue, ObjectItem, SelectionSingleValue } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ComboboxContainerProps, LoadingTypeEnum, @@ -38,6 +39,21 @@ export class DatabaseSingleSelectionSelector< this.caption = new DatabaseCaptionsProvider(this._objectsMap); this.options = new DatabaseOptionsProvider(this.caption, this._objectsMap, props.filterInputDebounceInterval); this.values = new DatabaseValuesProvider(this._objectsMap); + makeObservable(this, { + clearable: observable, + currentId: observable, + customContentType: observable, + lazyLoading: observable, + loadingType: observable, + readOnly: observable, + status: observable, + validation: observable, + _attr: observable.ref, + selection: observable.ref, + updateProps: action, + setAttributeValue: action, + setValue: action + }); } updateProps(props: ComboboxContainerProps): void { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseValuesProvider.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseValuesProvider.ts index 2b5a957219..5f7d2b0ebe 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseValuesProvider.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Database/DatabaseValuesProvider.ts @@ -1,4 +1,5 @@ import { DynamicValue, ListAttributeValue, ObjectItem } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ValuesProvider } from "../types"; interface Props { @@ -10,7 +11,13 @@ export class DatabaseValuesProvider implements ValuesProvider { private attribute?: ListAttributeValue; private emptyValue?: DynamicValue | undefined; - constructor(private optionsMap: Map) {} + constructor(private optionsMap: Map) { + makeObservable(this, { + attribute: observable.ref, + emptyValue: observable.ref, + updateProps: action + }); + } updateProps(props: Props): void { this.attribute = props.valueAttribute; diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumAndBooleanSimpleCaptionsProvider.tsx b/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumAndBooleanSimpleCaptionsProvider.tsx index a614b39623..9f0cfbb59c 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumAndBooleanSimpleCaptionsProvider.tsx +++ b/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumAndBooleanSimpleCaptionsProvider.tsx @@ -1,4 +1,5 @@ import { DynamicValue, EditableValue } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ReactNode } from "react"; import { CaptionsProvider } from "../types"; @@ -10,6 +11,15 @@ interface EnumAndBooleanSimpleCaptionsProviderProps { export class EnumAndBooleanSimpleCaptionsProvider implements CaptionsProvider { private attr?: EditableValue; emptyCaption = ""; + + constructor() { + makeObservable(this, { + attr: observable.ref, + emptyCaption: observable, + updateProps: action + }); + } + updateProps(props: EnumAndBooleanSimpleCaptionsProviderProps): void { this.attr = props.attribute; if (!props.emptyOptionText || props.emptyOptionText.status === "unavailable") { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolOptionsProvider.ts b/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolOptionsProvider.ts index 77b22868c4..9fa48e867c 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolOptionsProvider.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolOptionsProvider.ts @@ -1,4 +1,5 @@ import { EditableValue } from "mendix"; +import { makeObservable, observable, override } from "mobx"; import { FilterTypeEnum } from "../../../typings/ComboboxProps"; import { BaseOptionsProvider } from "../BaseOptionsProvider"; @@ -8,6 +9,11 @@ export class EnumBoolOptionsProvider extends BaseOpt > { private isBoolean = false; + constructor(...args: ConstructorParameters) { + super(...args); + makeObservable(this, { isBoolean: observable, _updateProps: override }); + } + _updateProps(props: { attribute: EditableValue; filterType: FilterTypeEnum }): void { if (props.attribute.status === "unavailable") { this.options = []; diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolSingleSelector.tsx b/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolSingleSelector.tsx index d0db872e39..37ec8bfb1b 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolSingleSelector.tsx +++ b/packages/pluggableWidgets/combobox-web/src/helpers/EnumBool/EnumBoolSingleSelector.tsx @@ -1,4 +1,5 @@ import { EditableValue } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ComboboxContainerProps, OptionsSourceAssociationCustomContentTypeEnum } from "../../../typings/ComboboxProps"; import { SingleSelector, Status } from "../types"; import { EnumAndBooleanSimpleCaptionsProvider } from "./EnumAndBooleanSimpleCaptionsProvider"; @@ -22,6 +23,18 @@ export class EnumBooleanSingleSelector implements SingleSelector { constructor() { this.caption = new EnumAndBooleanSimpleCaptionsProvider(); this.options = new EnumBoolOptionsProvider(this.caption); + makeObservable(this, { + status: observable, + validation: observable, + isBoolean: observable, + _attr: observable.ref, + currentId: observable, + customContentType: observable, + clearable: observable, + readOnly: observable, + updateProps: action, + setValue: action + }); } updateProps(props: ComboboxContainerProps): void { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/LazyLoadProvider.ts b/packages/pluggableWidgets/combobox-web/src/helpers/LazyLoadProvider.ts index 9b8c18d359..b9b25d9ad7 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/LazyLoadProvider.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/LazyLoadProvider.ts @@ -1,9 +1,19 @@ import { ListValue, ValueStatus } from "mendix"; +import { action, makeObservable, observable } from "mobx"; export class LazyLoadProvider { private ds?: ListValue; private limit: number = 0; + constructor() { + makeObservable(this, { + ds: observable.ref, + limit: observable, + updateProps: action, + getLimit: action + }); + } + updateProps(ds: ListValue): void { this.limit = ds.limit; this.ds = ds; diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticCaptionsProvider.tsx b/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticCaptionsProvider.tsx index 396f216a94..feff5a5e6a 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticCaptionsProvider.tsx +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticCaptionsProvider.tsx @@ -1,4 +1,5 @@ import { DynamicValue, ListAttributeValue } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ReactNode } from "react"; import { OptionsSourceAssociationCustomContentTypeEnum, @@ -24,7 +25,16 @@ export class StaticCaptionsProvider implements CaptionsProvider { emptyCaption = ""; overrideCaption: string | null | undefined = undefined; - constructor(private optionsMap: Map) {} + constructor(private optionsMap: Map) { + makeObservable(this, { + customContent: observable.ref, + customContentType: observable, + attribute: observable.ref, + emptyCaption: observable, + overrideCaption: observable, + updateProps: action + }); + } updateProps(props: Props): void { if (!props.emptyOptionText || props.emptyOptionText.status === "unavailable") { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticOptionsProvider.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticOptionsProvider.ts index 022f625dde..3c8c2f566c 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticOptionsProvider.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticOptionsProvider.ts @@ -1,4 +1,5 @@ import { matchSorter } from "match-sorter"; +import { makeObservable, observable, override } from "mobx"; import { StaticCaptionsProvider } from "./StaticCaptionsProvider"; import { FilterTypeEnum, OptionsSourceStaticDataSourceType } from "../../../typings/ComboboxProps"; import { BaseOptionsProvider } from "../BaseOptionsProvider"; @@ -10,15 +11,14 @@ interface Props { } export class StaticOptionsProvider extends BaseOptionsProvider { - options: string[] = []; ds: OptionsSourceStaticDataSourceType[] | undefined; - searchTerm = ""; - filterType: FilterTypeEnum = "contains"; + constructor( caption: StaticCaptionsProvider, private valuesMap: Map ) { super(caption); + makeObservable(this, { ds: observable.ref, status: override, _updateProps: override }); } get status(): Status { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticSingleSelector.ts b/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticSingleSelector.ts index c6d0b5265e..f4752ea50d 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticSingleSelector.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/Static/StaticSingleSelector.ts @@ -1,4 +1,5 @@ import { EditableValue } from "mendix"; +import { action, makeObservable, observable } from "mobx"; import { ComboboxContainerProps, OptionsSourceStaticDataSourceType, @@ -28,6 +29,18 @@ export class StaticSingleSelector implements SingleSelector { constructor() { this.caption = new StaticCaptionsProvider(this._objectsMap); this.options = new StaticOptionsProvider(this.caption, this._objectsMap); + makeObservable(this, { + attributeType: observable, + status: observable, + clearable: observable, + currentId: observable, + readOnly: observable, + customContentType: observable, + validation: observable, + _attr: observable.ref, + updateProps: action, + setValue: action + }); } updateProps(props: ComboboxContainerProps): void { diff --git a/packages/pluggableWidgets/combobox-web/src/helpers/__tests__/BaseOptionsProvider.spec.ts b/packages/pluggableWidgets/combobox-web/src/helpers/__tests__/BaseOptionsProvider.spec.ts index 14242e6165..554ae78210 100644 --- a/packages/pluggableWidgets/combobox-web/src/helpers/__tests__/BaseOptionsProvider.spec.ts +++ b/packages/pluggableWidgets/combobox-web/src/helpers/__tests__/BaseOptionsProvider.spec.ts @@ -1,3 +1,4 @@ +import { runInAction } from "mobx"; import { FilterTypeEnum } from "../../../typings/ComboboxProps"; import { BaseOptionsProvider } from "../BaseOptionsProvider"; import { CaptionsProvider } from "../types"; @@ -18,8 +19,11 @@ const captionsProvider: CaptionsProvider = { class TestOptionsProvider extends BaseOptionsProvider { constructor(filterType: FilterTypeEnum) { super(captionsProvider); - this.filterType = filterType; - this.options = ["a", "b", "c", "d"]; + // The provider state is observable; the test subclass seeds it the way an action would. + runInAction(() => { + this.filterType = filterType; + this.options = ["a", "b", "c", "d"]; + }); } } From 9522aee57892f765ed54e6e9f220f3c23bd807a5 Mon Sep 17 00:00:00 2001 From: Roman Vyakhirev Date: Thu, 29 Oct 2026 14:53:42 +0100 Subject: [PATCH 04/37] refactor(combobox-web): replace the forced re-render with a snapshot hook useGetSelector no longer registers onAfterSearchTermChange to call setState. It subscribes to the observable search term through useObservableSnapshot, a useSyncExternalStore wrapper around a MobX reaction. The hook is the snapshot hook from the headless design docs and will read the ViewModel in step 2. --- .../__tests__/useObservableSnapshot.spec.tsx | 62 +++++++++++++++++++ .../combobox-web/src/hooks/useGetSelector.ts | 12 ++-- .../src/hooks/useObservableSnapshot.ts | 14 +++++ 3 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 packages/pluggableWidgets/combobox-web/src/hooks/__tests__/useObservableSnapshot.spec.tsx create mode 100644 packages/pluggableWidgets/combobox-web/src/hooks/useObservableSnapshot.ts diff --git a/packages/pluggableWidgets/combobox-web/src/hooks/__tests__/useObservableSnapshot.spec.tsx b/packages/pluggableWidgets/combobox-web/src/hooks/__tests__/useObservableSnapshot.spec.tsx new file mode 100644 index 0000000000..04a0e21a93 --- /dev/null +++ b/packages/pluggableWidgets/combobox-web/src/hooks/__tests__/useObservableSnapshot.spec.tsx @@ -0,0 +1,62 @@ +import { renderHook, act } from "@testing-library/react"; +import { makeObservable, observable, runInAction } from "mobx"; +import { useObservableSnapshot } from "../useObservableSnapshot"; + +class Store { + term = ""; + other = 0; + + constructor() { + makeObservable(this, { term: observable, other: observable }); + } +} + +describe("useObservableSnapshot", () => { + it("returns the current value and re-renders once per change", () => { + const store = new Store(); + let renders = 0; + const read = (): string => store.term; + const { result } = renderHook(() => { + renders++; + return useObservableSnapshot(read); + }); + expect(result.current).toBe(""); + const before = renders; + + act(() => runInAction(() => (store.term = "a"))); + + expect(result.current).toBe("a"); + expect(renders).toBe(before + 1); + }); + + it("ignores observables the read function does not touch", () => { + const store = new Store(); + let renders = 0; + const read = (): string => store.term; + renderHook(() => { + renders++; + return useObservableSnapshot(read); + }); + const before = renders; + + act(() => runInAction(() => (store.other = 1))); + + expect(renders).toBe(before); + }); + + it("stops listening after unmount", () => { + const store = new Store(); + let renders = 0; + const read = (): string => store.term; + const { unmount } = renderHook(() => { + renders++; + return useObservableSnapshot(read); + }); + unmount(); + const before = renders; + + act(() => runInAction(() => (store.term = "a"))); + + expect(renders).toBe(before); + }); +}); diff --git a/packages/pluggableWidgets/combobox-web/src/hooks/useGetSelector.ts b/packages/pluggableWidgets/combobox-web/src/hooks/useGetSelector.ts index 1ebb816045..3d16eca000 100644 --- a/packages/pluggableWidgets/combobox-web/src/hooks/useGetSelector.ts +++ b/packages/pluggableWidgets/combobox-web/src/hooks/useGetSelector.ts @@ -1,5 +1,6 @@ -import { useMemo, useRef, useState } from "react"; +import { useCallback, useMemo, useRef } from "react"; import { debounce } from "@mendix/widget-plugin-platform/utils/debounce"; +import { useObservableSnapshot } from "./useObservableSnapshot"; import { ComboboxContainerProps } from "../../typings/ComboboxProps"; import { getSelector } from "../helpers/getSelector"; import { Selector } from "../helpers/types"; @@ -20,7 +21,6 @@ function onInputValueChange( export function useGetSelector(props: ComboboxContainerProps): Selector { const selectorRef = useRef(undefined); - const [, setInput] = useState({}); const [onFilterChangeDebounce] = useMemo( () => debounce((filterValue?: string) => { @@ -31,7 +31,6 @@ export function useGetSelector(props: ComboboxContainerProps): Selector { if (!selectorRef.current) { selectorRef.current = getSelector(props); - selectorRef.current.options.onAfterSearchTermChange(() => setInput({})); } else { if (!selectorRef.current.onFilterInputChange) { selectorRef.current.onFilterInputChange = onFilterChangeDebounce; @@ -39,5 +38,10 @@ export function useGetSelector(props: ComboboxContainerProps): Selector { } selectorRef.current.updateProps(props); - return selectorRef.current; + // The search term is the only store state that changes outside a props update or a Mendix + // value write, so it is the only observable the host subscribes to in migration step 1. + const selector = selectorRef.current; + useObservableSnapshot(useCallback(() => selector.options.searchTerm, [selector])); + + return selector; } diff --git a/packages/pluggableWidgets/combobox-web/src/hooks/useObservableSnapshot.ts b/packages/pluggableWidgets/combobox-web/src/hooks/useObservableSnapshot.ts new file mode 100644 index 0000000000..69a4a5efa6 --- /dev/null +++ b/packages/pluggableWidgets/combobox-web/src/hooks/useObservableSnapshot.ts @@ -0,0 +1,14 @@ +import { reaction } from "mobx"; +import { useCallback, useSyncExternalStore } from "react"; + +/** + * Subscribes a component to a MobX derivation without exposing MobX to it. + * + * `read` must return a stable value while nothing changed: a primitive, or a `computed` that + * caches its result. That is the contract `useSyncExternalStore` needs to skip re-renders. + * The design docs call this the snapshot hook; in step 2 it reads the ViewModel. + */ +export function useObservableSnapshot(read: () => T): T { + const subscribe = useCallback((onChange: () => void) => reaction(read, onChange), [read]); + return useSyncExternalStore(subscribe, read, read); +} From 7b8b35f8fe3c080a445da381345564214089a99d Mon Sep 17 00:00:00 2001 From: Roman Vyakhirev Date: Thu, 29 Oct 2026 14:55:00 +0100 Subject: [PATCH 05/37] docs(combobox-web): record migration step 1 as an openspec change Adds the combobox-mobx-store change (proposal, design, tasks) and a status line under step 1 of the headless combobox migration plan. --- docs/design/headless-combobox.md | 1 + .../changes/combobox-mobx-store/design.md | 55 +++++++++++++++++++ .../changes/combobox-mobx-store/proposal.md | 25 +++++++++ .../changes/combobox-mobx-store/tasks.md | 31 +++++++++++ 4 files changed, 112 insertions(+) create mode 100644 packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/design.md create mode 100644 packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/proposal.md create mode 100644 packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/tasks.md diff --git a/docs/design/headless-combobox.md b/docs/design/headless-combobox.md index a3e8dd92d4..c6771072d0 100644 --- a/docs/design/headless-combobox.md +++ b/docs/design/headless-combobox.md @@ -436,6 +436,7 @@ Rules, in order of application: Each step keeps the MPK, the XML, and the existing unit and E2E tests green. 1. **Extract the store.** Precondition: section 11, rules 1 to 5 in place. Move `getSelector`, the providers, and the selectors into a MobX store under a Core. Replace the forced re-render in `useGetSelector` with the snapshot hook. No change to `components/`. + Status 2026-10-29: done in the package change `combobox-mobx-store` (stacked on the safety-net branch). The selectors and providers are observable, `useObservableSnapshot` replaces the `setState({})` trigger and subscribes to the search term only. The props gate was deferred to step 2 because the `Selector` seam still takes props by method call. 2. **Build the ViewModel.** Add the computed slices from section 3. Rewrite `SingleSelection` and `MultiSelection` to read from the ViewModel instead of the Selector. Whatever they cannot get from the ViewModel is a gap in the contract; fix the contract, not the View. 3. **Extract Behavior and Popover.** Make downshift controlled by the Core. Move `useDownshift*` and `useFloatingMenu` into the two hooks with the getter shapes from sections 4 and 5. Verify every item in the "behaviour that must survive" list. 4. **Introduce classes and data attributes.** Replace literal class names with the map and modifier classes with data attributes per the table in section 6. Update `Combobox.scss` and the E2E selectors. diff --git a/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/design.md b/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/design.md new file mode 100644 index 0000000000..a96f8c0f6d --- /dev/null +++ b/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/design.md @@ -0,0 +1,55 @@ +## Test Cases + +This is a refactor. The existing characterisation tests from `combobox-selector-safety-net` are the net; they pass unchanged. The strict-mode Jest setup is the new guard, and the snapshot hook gets its own spec. + +### Regression Tests + +- Selector seam unchanged (unit) - every spec under `src/helpers/**/__tests__/` and `src/hooks/__tests__/useGetSelector.spec.tsx` + - **Given**: the converted store + - **When**: the suite runs with `enforceActions: "always"` + - **Then**: 194 tests pass, no `[MobX]` warning is raised, the 5 snapshots are unchanged +- Search-term re-render (unit) - `useGetSelector.spec.tsx` "re-renders the host when the search term changes" + - **Given**: a rendered `useGetSelector` + - **When**: `options.setSearchTerm("gree")` + - **Then**: exactly one extra render, `options.getAll()` returns `["green"]` +- Mutation outside an action fails (unit) - `BaseOptionsProvider.spec.ts` before the test subclass was fixed + - **Given**: `TestOptionsProvider` assigning `filterType` and `options` directly in its constructor + - **When**: the suite runs + - **Then**: 12 failures with "changing (observed) observable values without using an action is not allowed", which proves the guard works + +### Snapshot hook (`useObservableSnapshot.spec.tsx`) + +- Returns the current value and re-renders once per change + - **Given**: a store with an observable `term`, a hook reading it + - **When**: `term` changes inside an action + - **Then**: the hook returns the new value and the host rendered exactly once more +- Ignores observables the read function does not touch + - **Given**: the same store + - **When**: another observable changes + - **Then**: no re-render +- Stops listening after unmount + - **Given**: the hook unmounted + - **When**: `term` changes + - **Then**: no re-render + +### E2E + +- `pnpm run e2e` on the PR (CI runs it for changed packages). Visual snapshots must be identical; step 1 changes no DOM. + +## Annotation rules applied + +- `observable` for primitives and enums the UI reads (`status`, `currentId` of single selectors, `readOnly`, `clearable`, `validation`, style and method flags, `searchTerm`, `filterType`, `emptyCaption`). +- `observable.ref` for arrays (`options`, multi `currentId`) and for every Mendix value: `_attr`, `ds`, `selection`, `formatter`, `customContent`, `attribute`, `emptyValue`, `attributeId`. A Mendix value is never made deep observable. +- `computed` for getters without side effects: `status`, `hasMore`, `isLoading`, `sortOrder`, `datasourceFilter`. `getAll()` stays a method because the lazy-loading branch schedules a datasource filter. +- `action` for every mutating method, including `LazyLoadProvider.getLimit`, which updates its remembered limit. +- `override` on every subclass method or getter that replaces an annotated base member. +- Plain fields, on purpose: the `Map`s shared between a selector and its providers (replaced wholesale in `_updateProps`), `caption`, `options`, `values` (child stores), and `onEnterEvent`, `onLeaveEvent`, `onFilterInputChange`, which the downshift hooks and `useGetSelector` assign during render. + +## Notes + +- `enforceActions: "always"` only warns in MobX 6. `jest.setup.ts` throws on any `console.warn` that starts with `[MobX]`; that is what makes the guard effective. +- `pnpm run test ` does not filter in this package; use `pnpm run test --testPathPatterns `. +- The step subscribes to the search term only. Every other store change is either a props update, which already re-renders the widget, or a Mendix value write, which re-renders through the client. Subscribing to more would be step 2's ViewModel in disguise. +- `updateProps` still runs during render, as before. The reaction in the snapshot hook only observes the search term, which `updateProps` never writes, so no store update is reported to React while it renders. +- The pinned quirks from `combobox-selector-safety-net` are preserved; none was fixed here. +- Found on the way: two safety-net specs did not pass `tsc --noEmit` (string literals where `ValueStatus` is expected, an `ActionValue` cast). Jest runs through swc without type checking, so CI did not catch it. Fixed on the safety-net branch on 2026-10-30; `pnpm exec tsc --noEmit -p tsconfig.json` is clean on this branch. diff --git a/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/proposal.md b/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/proposal.md new file mode 100644 index 0000000000..f1c12b919a --- /dev/null +++ b/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/proposal.md @@ -0,0 +1,25 @@ +## Why + +Migration step 1 of `docs/design/headless-combobox.md`: the selector store becomes a MobX store so that step 2 can derive a ViewModel from it. Today the selectors are plain classes mutated in `updateProps`, and the only state change that is not a props update, the search term, reaches React through a callback that calls `setState({})` in `useGetSelector`. Nothing can observe the store, so nothing can be derived from it. + +## Root Cause + +`useGetSelector` hand-rolls a store: one instance per widget, `updateProps` on every render, and a forced re-render on search-term change through `options.onAfterSearchTermChange`. The selectors, options providers and captions providers keep their state in plain fields. That works for the current components, which read the selector directly during render, but it offers no subscription point for a snapshot hook or a computed ViewModel. + +## What Changes + +- `package.json`: adds `mobx` 6.12.3 and `@mendix/widget-plugin-mobx-kit` (both already used by other widgets in the repo). The `test` script runs `jest --projects jest.config.js`. +- `jest.config.js` and `jest.setup.ts`: extend the shared Jest config with `configure({ enforceActions: "always" })` and turn the MobX strict-mode warning into a thrown error, so a mutation outside an action fails the suite. +- `src/helpers/**`: every selector, options provider, captions provider, the values provider and `LazyLoadProvider` declare their state with `makeObservable`. Plain fields become `observable`; arrays and Mendix values (`ListValue`, `EditableValue`, `ReferenceValue`, `ReferenceSetValue`, `SelectionValue`, `ListWidgetValue`, formatters) become `observable.ref`; `updateProps`, `_updateProps`, `setValue`, `setSearchTerm`, `loadMore`, `loadSelectedValue` and `getLimit` become actions; the status, loading and sort getters become `computed`. Overrides are annotated with `override`. `StaticOptionsProvider` drops three field redeclarations that shadowed the base class observables. +- `src/hooks/useObservableSnapshot.ts` (new): `useSyncExternalStore` over a MobX `reaction`. This is the snapshot hook from the design docs. +- `src/hooks/useGetSelector.ts`: subscribes to `selector.options.searchTerm` through the snapshot hook instead of registering a `setState` callback. +- `src/helpers/__tests__/BaseOptionsProvider.spec.ts`: the test subclass seeds its state inside `runInAction`. No expectation changed. + +Not in this change: `src/components/`, the downshift hooks, `useActionEvents`, the preview selectors, the `Selector` interface. `onAfterSearchTermChange` stays on the interface, marked deprecated, until step 2 removes it with its test. The props gate from `widget-plugin-mobx-kit` is not introduced yet: the `Selector` seam takes props by method call and the characterisation tests depend on that; the gate arrives in step 2 together with the first computed that derives from props. + +## Impact + +- **Behaviour**: none intended. The 194 characterisation and component tests pass unchanged, the 5 DOM snapshots are untouched. The `useGetSelector` seam tests pin the same render count on search-term change as before. +- **Runtime**: MobX is bundled into the widget as it is for the data grid, gallery and image cropper. Outside tests MobX runs with its default `enforceActions: "observed"`; the only observed value is the search term and its setter is an action, so no console warnings are expected. +- **Release**: no CHANGELOG entry. Nothing user-facing changes. +- **Dependencies**: `mobx`, `@mendix/widget-plugin-mobx-kit`. diff --git a/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/tasks.md b/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/tasks.md new file mode 100644 index 0000000000..dd3bb9f0ac --- /dev/null +++ b/packages/pluggableWidgets/combobox-web/openspec/changes/combobox-mobx-store/tasks.md @@ -0,0 +1,31 @@ +## 1. Test Setup + +- [x] 1.1 Add `mobx` and `@mendix/widget-plugin-mobx-kit` to `package.json` (approved by Roman on 2026-10-29), `pnpm i`. +- [x] 1.2 Add `jest.config.js` and `jest.setup.ts` with `enforceActions: "always"` and the `[MobX]` warning turned into an error; switch the `test` script to `jest --projects jest.config.js`. +- [x] 1.3 Baseline under the new config: 16 suites, 194 tests, 5 snapshots, green. + +## 2. Implementation + +- [x] 2.1 Convert the base providers: `BaseOptionsProvider`, `BaseDatasourceOptionsProvider`, `LazyLoadProvider`. +- [x] 2.2 Convert the captions and values providers of every family. +- [x] 2.3 Convert the selectors: association single and multi, enumeration and boolean, static, database single and multi, plus `AssociationOptionsProvider`, `EnumBoolOptionsProvider`, `StaticOptionsProvider`. +- [x] 2.4 Fix the one test fixture that mutated observables outside an action (`BaseOptionsProvider.spec.ts`); no expectation changed. +- [x] 2.5 Commit the store conversion with the `setState({})` trigger still in place; suite green. +- [x] 2.6 Add `useObservableSnapshot` with its spec; replace the trigger in `useGetSelector`; commit separately. + +## 3. Refactoring + +- [x] 3.1 Remove the shadowing field redeclarations in `StaticOptionsProvider`. +- [ ] 3.2 Step 2: remove `onAfterSearchTermChange` from the `OptionsProvider` interface, its base implementation and its two tests, and introduce the props gate. + +## 4. Verification + +- [x] 4.1 `pnpm run test`: 17 suites, 197 tests, 5 snapshots unchanged, no `-u`. +- [x] 4.2 `pnpm run lint`: 0 errors; the remaining warnings are pre-existing and in untouched files. +- [x] 4.3 `pnpm run build`: MPK builds. +- [ ] 4.4 E2E on the PR through CI with zero visual snapshot changes; local run against Studio Pro after a rebuild of the widget. + +## Notes + +- Three commits as rule 3 of the design doc asks: dependencies and strict mode, store conversion, snapshot hook. +- Lint warning count moved from 11 to 12 in untouched files between the two branches; none is in a converted file. From b2b03abeb8f8370d44f6bfccc8e2a1a3edc3ab8d Mon Sep 17 00:00:00 2001 From: Roman Vyakhirev Date: Fri, 30 Oct 2026 17:07:38 +0100 Subject: [PATCH 06/37] feat(combobox-web): add the combobox core, its container and view model Migration step 2 of docs/design/headless-combobox.md. The core derives a plain ViewModel from the selector store as cached slices, so a View can memoise on them, and the two selection views render from that snapshot only. The core is assembled by a brandi container like the data grid and gallery widgets: a frozen config for the static Studio Pro properties, a props gate for the Mendix values, the selector family bound per instance, and a setup host for the debounced filter-input action. getSelector and useGetSelector are replaced by the container and useComboboxCore; the editor preview uses the same container over the preview selectors. --- .../src/Combobox.editorPreview.tsx | 60 +--- .../combobox-web/src/Combobox.tsx | 45 +-- .../MultiSelection/MultiSelection.tsx | 150 ++++----- .../MultiSelection/MultiSelectionMenu.tsx | 63 ++-- .../src/components/SelectionProps.ts | 15 + .../SingleSelection/SingleSelection.tsx | 109 ++---- .../SingleSelection/SingleSelectionMenu.tsx | 49 ++- .../combobox-web/src/core/Combobox.config.ts | 108 ++++++ .../src/core/Combobox.container.ts | 86 +++++ .../combobox-web/src/core/ComboboxCore.ts | 314 ++++++++++++++++++ .../combobox-web/src/core/ComboboxGate.ts | 22 ++ .../src/core/ComboboxSetup.service.ts | 4 + .../src/core/ComboboxViewModel.ts | 90 +++++ .../src/core/FilterInputEvent.service.ts | 37 +++ .../combobox-web/src/core/WidgetViewModel.ts | 42 +++ .../src/core/__tests__/ComboboxCore.spec.tsx | 300 +++++++++++++++++ .../FilterInputEvent.service.spec.ts | 99 ++++++ .../__tests__/createComboboxContainer.spec.ts | 99 ++++++ .../src/core/createComboboxContainer.ts | 7 + .../src/core/createPreviewContainer.tsx | 84 +++++ .../combobox-web/src/core/tokens.ts | 21 ++ .../src/helpers/__tests__/getSelector.spec.ts | 73 ---- .../combobox-web/src/helpers/getSelector.ts | 36 -- .../combobox-web/src/helpers/types.ts | 32 +- .../combobox-web/src/helpers/utils.ts | 20 +- .../hooks/__tests__/useGetSelector.spec.tsx | 133 -------- .../combobox-web/src/hooks/useComboboxCore.ts | 52 +++ .../src/hooks/useDownshiftMultiSelectProps.ts | 53 +-- .../hooks/useDownshiftSingleSelectProps.ts | 32 +- .../combobox-web/src/hooks/useGetSelector.ts | 47 --- 30 files changed, 1572 insertions(+), 710 deletions(-) create mode 100644 packages/pluggableWidgets/combobox-web/src/components/SelectionProps.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/Combobox.config.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/Combobox.container.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/ComboboxCore.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/ComboboxGate.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/ComboboxSetup.service.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/ComboboxViewModel.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/FilterInputEvent.service.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/WidgetViewModel.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/__tests__/ComboboxCore.spec.tsx create mode 100644 packages/pluggableWidgets/combobox-web/src/core/__tests__/FilterInputEvent.service.spec.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/__tests__/createComboboxContainer.spec.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/createComboboxContainer.ts create mode 100644 packages/pluggableWidgets/combobox-web/src/core/createPreviewContainer.tsx create mode 100644 packages/pluggableWidgets/combobox-web/src/core/tokens.ts delete mode 100644 packages/pluggableWidgets/combobox-web/src/helpers/__tests__/getSelector.spec.ts delete mode 100644 packages/pluggableWidgets/combobox-web/src/helpers/getSelector.ts delete mode 100644 packages/pluggableWidgets/combobox-web/src/hooks/__tests__/useGetSelector.spec.tsx create mode 100644 packages/pluggableWidgets/combobox-web/src/hooks/useComboboxCore.ts delete mode 100644 packages/pluggableWidgets/combobox-web/src/hooks/useGetSelector.ts diff --git a/packages/pluggableWidgets/combobox-web/src/Combobox.editorPreview.tsx b/packages/pluggableWidgets/combobox-web/src/Combobox.editorPreview.tsx index 31f2a0d54c..7af74b9b9e 100644 --- a/packages/pluggableWidgets/combobox-web/src/Combobox.editorPreview.tsx +++ b/packages/pluggableWidgets/combobox-web/src/Combobox.editorPreview.tsx @@ -1,64 +1,22 @@ -import type { DynamicValue } from "mendix"; import { ReactElement, useMemo } from "react"; -import { generateUUID } from "@mendix/widget-plugin-platform/framework/generate-uuid"; import { ComboboxPreviewProps } from "../typings/ComboboxProps"; import { SingleSelection } from "./components/SingleSelection/SingleSelection"; +import { ComboboxCore } from "./core/ComboboxCore"; +import { createPreviewContainer } from "./core/createPreviewContainer"; +import { CB_TOKENS as CB } from "./core/tokens"; +import { SingleSelector } from "./helpers/types"; import "./ui/Combobox.scss"; -import { AssociationPreviewSelector } from "./helpers/Association/Preview/AssociationPreviewSelector"; -import { DatabasePreviewSelector } from "./helpers/Database/Preview/DatabasePreviewSelector"; -import { StaticPreviewSelector } from "./helpers/Static/Preview/StaticPreviewSelector"; -import { SelectionBaseProps, SingleSelector } from "./helpers/types"; - -const available = (value: T): DynamicValue => - ({ - status: "available", - value - }) as DynamicValue; export const preview = (props: ComboboxPreviewProps): ReactElement => { - const id = generateUUID().toString(); - const commonProps: Omit, "selector"> = { - tabIndex: 1, - inputId: id, - labelId: `${id}-label`, - readOnlyStyle: props.readOnlyStyle, - ariaRequired: available(false), - a11yConfig: { - ariaLabels: { - clearSelection: props.clearButtonAriaLabel, - removeSelection: props.removeValueAriaLabel, - selectAll: props.selectAllButtonCaption - }, - a11yStatusMessage: { - a11ySelectedValue: props.a11ySelectedValue, - a11yOptionsAvailable: props.a11yOptionsAvailable, - a11yInstructions: props.a11yInstructions, - a11yNoOption: props.noOptionsText || props.a11yNoOptions - } - }, - menuFooterContent: props.showFooter ? ( - -
    - - ) : null, - keepMenuOpen: - props.showFooter || - (props.optionsSourceStaticDataSource.length > 0 && props.staticDataSourceCustomContentType !== "no") - }; + const keepMenuOpen = + props.showFooter || + (props.optionsSourceStaticDataSource.length > 0 && props.staticDataSourceCustomContentType !== "no"); // eslint-disable-next-line react-hooks/rules-of-hooks - const selector: SingleSelector = useMemo(() => { - if (props.source === "static") { - return new StaticPreviewSelector(props); - } - if (props.source === "database") { - return new DatabasePreviewSelector(props); - } - return new AssociationPreviewSelector(props); - }, [props]); + const core = useMemo(() => createPreviewContainer(props).get(CB.core) as ComboboxCore, [props]); return (
    - +
    ); }; diff --git a/packages/pluggableWidgets/combobox-web/src/Combobox.tsx b/packages/pluggableWidgets/combobox-web/src/Combobox.tsx index bafce1d9bd..e0c25fdf79 100644 --- a/packages/pluggableWidgets/combobox-web/src/Combobox.tsx +++ b/packages/pluggableWidgets/combobox-web/src/Combobox.tsx @@ -5,55 +5,30 @@ import { ComboboxContainerProps } from "../typings/ComboboxProps"; import { MultiSelection } from "./components/MultiSelection/MultiSelection"; import { Placeholder } from "./components/Placeholder"; import { SingleSelection } from "./components/SingleSelection/SingleSelection"; -import { SelectionBaseProps } from "./helpers/types"; -import { textOrFallback } from "./helpers/utils"; +import { ComboboxCore } from "./core/ComboboxCore"; +import { MultiSelector, SingleSelector } from "./helpers/types"; import { useActionEvents } from "./hooks/useActionEvents"; -import { useGetSelector } from "./hooks/useGetSelector"; +import { useComboboxCore } from "./hooks/useComboboxCore"; import "./ui/Combobox.scss"; -const DEFAULT_CLEAR_SELECTION_LABEL = "Clear selection"; -const DEFAULT_REMOVE_VALUE_LABEL = "Remove value"; - export default function Combobox(props: ComboboxContainerProps): ReactElement { - const selector = useGetSelector(props); + const { core, vm } = useComboboxCore(props); const actionEvents = useActionEvents({ onEnterEvent: props.onEnterEvent, onLeaveEvent: props.onLeaveEvent, - selector + selector: core.selector }); - const commonProps: Omit, "selector"> = { - tabIndex: props.tabIndex!, - inputId: props.id, - labelId: `${props.id}-label`, - noOptionsText: props.noOptionsText?.value, - readOnlyStyle: props.readOnlyStyle, - ariaRequired: props.ariaRequired, - ariaLabel: props.ariaLabel?.value, - a11yConfig: { - ariaLabels: { - clearSelection: textOrFallback(props.clearButtonAriaLabel?.value, DEFAULT_CLEAR_SELECTION_LABEL), - removeSelection: textOrFallback(props.removeValueAriaLabel?.value, DEFAULT_REMOVE_VALUE_LABEL), - selectAll: props.selectAllButtonCaption?.value ?? "" - }, - a11yStatusMessage: { - a11ySelectedValue: props.a11ySelectedValue?.value ?? "", - a11yOptionsAvailable: props.a11yOptionsAvailable?.value ?? "", - a11yInstructions: props.a11yInstructions?.value ?? "", - a11yNoOption: textOrFallback(props.noOptionsText?.value, props.a11yNoOptions?.value ?? "") - } - }, - menuFooterContent: props.showFooter ? props.menuFooterContent : undefined - }; return (
    - {selector.status === "unavailable" ? ( + {vm.status === "unavailable" ? ( - ) : selector.type === "single" ? ( - + ) : vm.mode === "single" ? ( + // The casts go once the views stop taking the selector (migration step 3). + } vm={vm} /> ) : ( - + } vm={vm} /> )}
    ); diff --git a/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelection.tsx b/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelection.tsx index 86907e007b..93fa70480b 100644 --- a/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelection.tsx +++ b/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelection.tsx @@ -1,13 +1,14 @@ import classNames from "classnames"; import { Fragment, KeyboardEvent, ReactElement, useEffect, useMemo, useRef } from "react"; import { ClearButton } from "../../assets/icons"; -import { MultiSelector, SelectionBaseProps } from "../../helpers/types"; -import { getInputLabel, getSelectedCaptionsPlaceholder, getValidationErrorId } from "../../helpers/utils"; +import { MultiSelector } from "../../helpers/types"; +import { getInputLabel, getValidationErrorId } from "../../helpers/utils"; import { useDownshiftMultiSelectProps } from "../../hooks/useDownshiftMultiSelectProps"; import { useFloatingMenu } from "../../hooks/useFloatingMenu"; import { useLazyLoading } from "../../hooks/useLazyLoading"; import { ComboboxWrapper } from "../ComboboxWrapper"; import { InputPlaceholder } from "../Placeholder"; +import { SelectionProps } from "../SelectionProps"; import { MultiSelectionMenu } from "./MultiSelectionMenu"; import { SelectAllButton } from "./SelectAllButton"; @@ -38,14 +39,9 @@ function isChipNavigationPermitted(event: KeyboardEvent): boolean { ); } -export function MultiSelection({ - selector, - tabIndex, - a11yConfig, - menuFooterContent, - ariaRequired, - ...options -}: SelectionBaseProps): ReactElement { +export function MultiSelection({ core, vm, keepMenuOpen }: SelectionProps): ReactElement { + // The downshift hook still reads the selector through the core; the markup reads the ViewModel only. + const inputId = vm.id; const inputRef = useRef(null); /** Chip DOM nodes by index, so focus can be restored after a chip is removed. */ const chipRefs = useRef>([]); @@ -63,21 +59,17 @@ export function MultiSelection({ removeSelectedItem, setActiveIndex, selectedItems, - items, - setSelectedItems, toggleSelectedItem - } = useDownshiftMultiSelectProps(selector, options, inputRef, a11yConfig.a11yStatusMessage); + } = useDownshiftMultiSelectProps(core, { inputId, labelId: `${inputId}-label` }, inputRef); // Guard keepMenuOpen so floating-ui (and its autoUpdate scroll/resize listeners) stay disabled // in always-open mode, matching SingleSelection. keepMenuOpen is only set by the editor preview, // which renders SingleSelection exclusively, so MultiSelection never receives it at runtime or in // preview; this is a defensive guard. The inline always-open branch (alwaysOpen on the menu wrapper) // is intentionally not threaded through MultiSelectionMenu because it is unreachable for multi-select. - const keepMenuOpen = options.keepMenuOpen; const { refs, floatingStyles } = useFloatingMenu(keepMenuOpen === true ? false : isOpen); - const isSelectedItemsBoxStyle = selector.selectedItemsStyle === "boxes"; - const isOptionsSelected = selector.isOptionsSelected(); - const inputLabel = getInputLabel(options.inputId); - const errorId = getValidationErrorId(options.inputId); + const isSelectedItemsBoxStyle = vm.hints.selectedItemsStyle === "boxes"; + const inputLabel = getInputLabel(inputId); + const errorId = getValidationErrorId(inputId); const hasLabel = useMemo(() => Boolean(inputLabel), [inputLabel]); const inputProps = getInputProps({ ...getDropdownProps( @@ -102,10 +94,10 @@ export function MultiSelection({ } } }, - disabled: selector.readOnly, - readOnly: selector.options.filterType === "none", - "aria-required": ariaRequired.value, - "aria-label": !hasLabel && options.ariaLabel ? options.ariaLabel : undefined + disabled: vm.readOnly, + readOnly: !vm.filterable, + "aria-required": vm.a11y.required, + "aria-label": !hasLabel && vm.a11y.label ? vm.a11y.label : undefined }); /** @@ -141,22 +133,12 @@ export function MultiSelection({ // focus the node that is about to unmount. }, [selectedItems.length]); - const memoizedselectedCaptions = useMemo( - () => getSelectedCaptionsPlaceholder(selector, selectedItems), - [selector, selectedItems] - ); - - const lazyLoading = selector.lazyLoading ?? false; const { onScroll } = useLazyLoading({ - hasMoreItems: selector.options.hasMore ?? false, - isInfinite: lazyLoading, + hasMoreItems: vm.loading.hasMore, + isInfinite: vm.loading.lazy, isOpen, - loadMore: () => { - if (selector.options.loadMore) { - selector.options.loadMore(); - } - }, - readOnly: selector.readOnly + loadMore: vm.loadMore, + readOnly: vm.readOnly }); return ( @@ -164,28 +146,28 @@ export function MultiSelection({ 0} + validation={vm.validation} + isLoading={vm.loading.lazy && vm.loading.isLoading} + isMultiselectActive={vm.chips.length > 0} errorId={errorId} >
    {isSelectedItemsBoxStyle && - selectedItems.map((selectedItemForRender, index) => { + vm.chips.map((chip, index) => { return (
    { chipRefs.current[index] = node; @@ -199,15 +181,15 @@ export function MultiSelection({ } })} > - {selector.caption.render(selectedItemForRender, "label")} - {!selector.readOnly && ( + {chip.content} + {!vm.readOnly && ( { e.stopPropagation(); - removeSelectedItem(selectedItemForRender); + removeSelectedItem(chip.id); }} > @@ -218,71 +200,61 @@ export function MultiSelection({ })} - {memoizedselectedCaptions} + {vm.selectedContent}
    - {!selector.readOnly && - selector.clearable && - selector.currentId !== null && - selector.currentId.length > 0 && ( - - )} + {!vm.readOnly && vm.clearable && vm.value !== null && vm.value.length > 0 && ( + + )} { - if (isOptionsSelected === "all") { - setSelectedItems([]); + if (vm.allSelected === "all") { + vm.clear(); } else { - setSelectedItems(selector.options.getAll()); + vm.selectAll(); } }} /> ) : undefined } - menuFooterContent={menuFooterContent} - inputId={options.inputId} - selector={selector} + vm={vm} isOpen={isOpen} highlightedIndex={highlightedIndex} - selectableItems={items} getItemProps={getItemProps} getMenuProps={getMenuProps} - selectedItems={selectedItems} - noOptionsText={options.noOptionsText} onOptionClick={() => { inputRef.current?.focus(); }} - isLoading={selector.options.isLoading} - lazyLoading={lazyLoading} onScroll={onScroll} floatingRef={refs.setFloating} floatingStyles={floatingStyles} diff --git a/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelectionMenu.tsx b/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelectionMenu.tsx index 62864eb768..52d589d263 100644 --- a/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelectionMenu.tsx +++ b/packages/pluggableWidgets/combobox-web/src/components/MultiSelection/MultiSelectionMenu.tsx @@ -1,91 +1,80 @@ import { UseComboboxPropGetters } from "downshift/typings"; import { CSSProperties, MouseEvent, ReactElement, ReactNode, Ref } from "react"; import { Checkbox } from "../../assets/icons"; -import { MultiSelector } from "../../helpers/types"; +import { ComboboxViewModel } from "../../core/ComboboxViewModel"; import { ComboboxMenuWrapper } from "../ComboboxMenuWrapper"; import { ComboboxOptionWrapper } from "../ComboboxOptionWrapper"; import { Loader } from "../Loader"; interface MultiSelectionMenuProps extends Partial> { + vm: ComboboxViewModel; isOpen: boolean; - selectableItems: string[]; - selectedItems: string[]; highlightedIndex: number | null; - selector: MultiSelector; - noOptionsText?: string; - inputId?: string; menuHeaderContent?: ReactNode; - menuFooterContent?: ReactNode; onOptionClick?: (e: MouseEvent) => void; - isLoading: boolean; - lazyLoading: boolean; onScroll: (e: any) => void; floatingRef?: Ref; floatingStyles?: CSSProperties; } export function MultiSelectionMenu({ + vm, isOpen, getMenuProps, getItemProps, highlightedIndex, - selector, - selectableItems, - noOptionsText, - inputId, menuHeaderContent, - menuFooterContent, onOptionClick, - isLoading, - lazyLoading, onScroll, floatingRef, floatingStyles }: MultiSelectionMenuProps): ReactElement { + const { options, loading } = vm; + const withCheckbox = vm.hints.selectionMethod === "checkbox"; + return ( } - menuFooterContent={menuFooterContent} + menuFooterContent={vm.slots.menuFooter} menuHeaderContent={menuHeaderContent} - noOptionsText={noOptionsText} + noOptionsText={vm.t("noOptions")} onOptionClick={onOptionClick} - onScroll={lazyLoading ? onScroll : undefined} + onScroll={loading.lazy ? onScroll : undefined} > {isOpen && - selectableItems.map((item, index) => { - const isActive = highlightedIndex === index; - const isSelected = selector.currentId?.includes(item); + options.map((option, index) => { + // Quirk: while the selector has no value at all (not even an empty list), options + // used to get no aria-selected attribute instead of "false". Kept until step 4. + const isSelected = vm.value === null ? undefined : option.selected; return ( - {selector.selectionMethod === "checkbox" && ( - - )} - {selector.caption.render(item, "options", `${inputId}_${item}`)} + {withCheckbox && } + {option.content} ); })} diff --git a/packages/pluggableWidgets/combobox-web/src/components/SelectionProps.ts b/packages/pluggableWidgets/combobox-web/src/components/SelectionProps.ts new file mode 100644 index 0000000000..180058bc6c --- /dev/null +++ b/packages/pluggableWidgets/combobox-web/src/components/SelectionProps.ts @@ -0,0 +1,15 @@ +import { ComboboxCore } from "../core/ComboboxCore"; +import { ComboboxViewModel } from "../core/ComboboxViewModel"; +import { Selector } from "../helpers/types"; + +/** + * What a selection View receives in migration step 2: the ViewModel snapshot it renders from, and + * the Core for the behaviour hooks that still read the selector directly (downshift and lazy + * loading). Step 3 replaces those hooks and drops `core`. + */ +export interface SelectionProps { + core: ComboboxCore; + vm: ComboboxViewModel; + /** Editor preview only: render the menu inline and always open. */ + keepMenuOpen?: boolean; +} diff --git a/packages/pluggableWidgets/combobox-web/src/components/SingleSelection/SingleSelection.tsx b/packages/pluggableWidgets/combobox-web/src/components/SingleSelection/SingleSelection.tsx index 0abc622316..12b5b42603 100644 --- a/packages/pluggableWidgets/combobox-web/src/components/SingleSelection/SingleSelection.tsx +++ b/packages/pluggableWidgets/combobox-web/src/components/SingleSelection/SingleSelection.tsx @@ -1,69 +1,47 @@ import classNames from "classnames"; import { Fragment, KeyboardEventHandler, ReactElement, useMemo, useRef } from "react"; import { ClearButton } from "../../assets/icons"; -import { SelectionBaseProps, SingleSelector } from "../../helpers/types"; +import { SingleSelector } from "../../helpers/types"; import { getInputLabel, getValidationErrorId } from "../../helpers/utils"; import { useDownshiftSingleSelectProps } from "../../hooks/useDownshiftSingleSelectProps"; import { useFloatingMenu } from "../../hooks/useFloatingMenu"; import { useLazyLoading } from "../../hooks/useLazyLoading"; import { ComboboxWrapper } from "../ComboboxWrapper"; import { InputPlaceholder } from "../Placeholder"; +import { SelectionProps } from "../SelectionProps"; import { SingleSelectionMenu } from "./SingleSelectionMenu"; -export function SingleSelection({ - selector, - tabIndex = 0, - a11yConfig, - keepMenuOpen, - menuFooterContent, - ariaRequired, - ...options -}: SelectionBaseProps): ReactElement { +export function SingleSelection({ core, vm, keepMenuOpen }: SelectionProps): ReactElement { + // Behaviour hooks still read the selector through the core; the markup reads the ViewModel only. + const { selector } = core; + const inputId = vm.id; + const tabIndex = vm.tabIndex ?? 0; const { getInputProps, getToggleButtonProps, getItemProps, - selectedItem, getMenuProps, reset, isOpen, highlightedIndex, selectItem - } = useDownshiftSingleSelectProps(selector, options, a11yConfig.a11yStatusMessage); + } = useDownshiftSingleSelectProps(core, { inputId, labelId: `${inputId}-label` }); const inputRef = useRef(null); const { refs, floatingStyles } = useFloatingMenu(keepMenuOpen === true ? false : isOpen); - const lazyLoading = selector.lazyLoading ?? false; const { onScroll } = useLazyLoading({ - hasMoreItems: selector.options.hasMore ?? false, - isInfinite: lazyLoading, + hasMoreItems: vm.loading.hasMore, + isInfinite: vm.loading.lazy, isOpen, - loadMore: () => { - if (selector.options.loadMore) { - selector.options.loadMore(); - } - }, + loadMore: vm.loadMore, datasourceFilter: selector.options.datasourceFilter, - readOnly: selector.readOnly + readOnly: vm.readOnly }); - const selectedItemCaption = useMemo( - () => selector.caption.render(selectedItem, "label"), - // eslint-disable-next-line react-hooks/exhaustive-deps - [ - selectedItem, - selector.status, - selector.caption, - selector.caption.emptyCaption, - selector.currentId, - selector.caption.formatter - ] - ); - - const inputLabel = getInputLabel(options.inputId); - const errorId = getValidationErrorId(options.inputId); + const inputLabel = getInputLabel(inputId); + const errorId = getValidationErrorId(inputId); const hasLabel = useMemo(() => Boolean(inputLabel), [inputLabel]); const onInputKeyDown = useMemo | undefined>(() => { - if (!selector.clearable) { + if (!vm.clearable) { return undefined; } @@ -72,72 +50,62 @@ export function SingleSelection({ selectItem(null); } }; - }, [selector.clearable, selectItem]); + }, [vm.clearable, selectItem]); const inputProps = getInputProps( { - disabled: selector.readOnly, - readOnly: selector.options.filterType === "none", + disabled: vm.readOnly, + readOnly: !vm.filterable, ref: inputRef, - "aria-required": ariaRequired.value, - "aria-label": !hasLabel && options.ariaLabel ? options.ariaLabel : undefined, + "aria-required": vm.a11y.required, + "aria-label": !hasLabel && vm.a11y.label ? vm.a11y.label : undefined, onKeyDown: onInputKeyDown }, { suppressRefError: true } ); + const customContentEverywhere = vm.hints.customContent === "everywhere"; return (
    - - {selectedItemCaption} + + {vm.selectedContent}
    - {((!selector.readOnly && selector.clearable && selector.currentId !== null) || - (selector.selectorType === "static" && - selector.currentId !== null && - !selector.readOnly && - selector.clearable && - selector.attributeType !== "boolean")) && ( + {!vm.readOnly && vm.clearable && vm.value !== null && (