Skip to content

Commit d4017fe

Browse files
authored
EPBDS-16211 A: the last seven class components as hooks (#132)
## What changes The last seven class components in `src` become function components: | component | where | was | |---|---|---| | `ToggleField` | `modules/form/inputs` | `PureComponent` | | `Upload` | `modules/upload/views` | `PureComponent`, `contextType`, state, a `Dropzone` ref | | `LocalDraftTableRow` | `engine/components` | `PureComponent` with state | | `Data` | `engine` | `Component`, render only | | `PopupContent` (template factory) | `engine/components/PopupContent.js` | a `PureComponent` class per call | | `PopupContent` (static popups) | `engine/mapper.js` | a `PureComponent` class per popup node | | `Examples` | `demo/pages` | `Component` with state | The one class component left in `src` is `Render.js`'s error boundary. React offers no hook for `componentDidCatch`, so it stays a class. Every `PureComponent` became `memo` (a shallow props compare, as before). Every `defaultProps` became a default parameter, which React 19 requires of a function component. Hooks only: TypeScript for the same seven is the next PR, as §9.2 asks (one moving part per PR). ## Four semantics the obvious conversion would have changed 1. **The default `translate` of `LocalDraftTableRow` and `Upload`.** Both defaulted it to `Active.translate` as read *when the module loaded*: `defaultProps` is evaluated once. The engine reassigns `Active.translate` in every document's constructor (`rules.js`), so a render-time read would take the translator of whichever document was built last. The default is a module constant. 2. **`Data`'s default `data` and `meta`.** They were two shared objects. The nested document compares `data` by reference, so the defaults are module constants, not a new `{}` per render. 3. **When `Upload` tells the host about a drag.** The class called `onFocus`/`onBlur` from `setState`'s callback, which runs: - after the commit; - with that commit's props; - even when the state was unchanged and `PureComponent` skipped the render. A hook skips the commit in that last case. So the callbacks queue, a layout effect flushes them after every commit (reading the committed props), and a counter forces the commit that runs them. The React 16 `persist()` handling is unchanged. 4. **What `ToggleField` hands Field.** The class gave Field `this.input`, one function per instance, so Field's component type never changed. That function read the *latest* `this.props`: all of them, including `onChange` and `instance`, which Field is deliberately not given, and `value`, which overrides the field's own. A module-level component keeps the type stable, and a context gives it the props without passing `instance` or `onChange` through Field. The existing leak test still holds. `PopupContent` keeps its fresh type per popup, which `rules.popup-content.test.js` pins, because the memoized function is still created per call. ## Measured Through the published entry, over the 38 examples, before → after: | | before | after | |---|---|---| | commits at mount | 107 | **107** | | `translate` calls at mount | 1013 | **1013** | | commits on an edit | 27 | **27** | | `translate` calls on an edit | 64 | **64** | | examples whose DOM differs, after mount / after an edit | — | **0 / 0** | `dist/index.js` is 328,053 → 327,402 bytes. ## Tests - **Two tests reached into the classes** and now go through the rendered component: - "updates the form input before invoking the external callback" called `new ToggleField(...).input(...)`. It now clicks the rendered toggle and records what the form holds when the callback runs. It was **mutation-checked**: with the two calls swapped, it fails. - "handleKeyPress opens dropzone on Enter" passed an unused `ref` to `Upload` through a wrapper class; on a function component that ref would warn. The wrapper and the ref are gone; the assertion is unchanged. - **Checked in the running demo:** - both toggles in `inputToggle` flip; - a draft row in `nestedDataKind` holds its input, "Add line" appends `DES-003 | Prototype | 2 | 300`, and the draft clears; - "Open Popup 1" opens with its content; - a drag toggles the upload's `active` class; - a title click expands its example and moves the hash; - no console error or React warning at any step. ## Gates All exited 0: - `lint:js`, `lint:css`, `typecheck`; - `docs:props:check`, `docs:views:check`, `css:fixture:check`; - `test:env-flags`, `test:coverage` (thresholds included), `build`; - `test:pack`, `test:pack:peers`, `test:types`; - `test:react17` and `test:react19`, 2907 tests each; - `test:e2e`, 41 tests; - the manifest contract. `test:react16` lost a worker to `SIGSEGV` on its first two runs: `StandaloneTabs.test.js`, then `fields.test.js`, 12 tests each, hence 2895. That is the Node 24 V8 crash ([nodejs/node#62393](nodejs/node#62393)). The third run passed 2907/2907. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent 5ede721 commit d4017fe

10 files changed

Lines changed: 472 additions & 459 deletions

File tree

‎docs/UPGRADE-PLAN.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,14 @@ Every workstream below is a series of small, independently shippable, reversible
431431

432432
**Acceptance per component:** tests green, demo example using the component pixel-equivalent, no new console warnings.
433433

434+
**DONE 2026-09-30, the last seven in one PR.** `ToggleField`, `Upload` and `LocalDraftTableRow` (items 3 and 4), `Data`, `PopupContent` in both its places (the template factory in `engine/components/PopupContent.js` and the static one `mapper.js` declares per popup node), and the demo's `Examples` page. Every `PureComponent` became `memo`, every `defaultProps` a default parameter, which React 19 requires of a function. Four of them had a semantic the obvious conversion would have changed, and each was kept:
435+
- `LocalDraftTableRow` and `Upload` defaulted `translate` to `Active.translate` as read when the module loaded. A render-time read would take the translator of whichever document the engine constructed last, so the default is a module constant.
436+
- `Data`'s default `data` and `meta` were shared objects, and the nested document compares `data` by reference, so the defaults are module constants and not a new `{}` per render.
437+
- `Upload` called the host's `onFocus`/`onBlur` from `setState`'s callback: after the commit, with that commit's props, and even when the state was unchanged and `PureComponent` skipped the render. A queue flushed by a layout effect, with a forced commit, keeps all three.
438+
- `ToggleField` handed Field one function per instance that read the LATEST props, `value` included, which overrides the field's own. A module-level component keeps the type stable, and a context gives it the props without passing `instance` or `onChange` through Field.
439+
440+
`PopupContent`'s fresh type per popup (`rules.popup-content.test.js`) is kept by creating the memoized function per call. **Measured on the corpus**, before → after, over the 38 examples through the published entry: commits at mount 107 → 107, `translate` calls 1013 → 1013, commits and `translate` calls on an edit 27 → 27 and 64 → 64. The DOM after mount and after an edit is identical in all 38. Two tests called the classes directly, `new ToggleField(...)` and a `ref` to `Upload`, and now go through the rendered component; the ordering one was mutation-checked. **The one class component left in `src` is `Render.js`'s error boundary, which React offers no hook for.**
441+
434442
### 9.3 Workstream B — Decompose the lifecycle engine (`rules.js` / `form/utils.js`)
435443

436444
**Motivation:** the prototype-patching of `UNSAFE_*` methods (`rules.js:593–595, 1182–1220`; `form/utils.js:397, 466, 598–615`) is the single biggest source of: StrictMode incompatibility, React 19 uncertainty, onboarding cost, and the high perceived risk of any change near the engine. 1868 lines across two files carry most of the library's behavior.
@@ -1773,7 +1781,7 @@ src/
17731781
| **1** | ✅ **DONE (2026-08-20).** ~~React 17: dev bump, peer widen (react + moment `^2.29.4`), QA; checkpoint release~~ — the bump and the widening landed (`peerDependencies`: react/react-dom `^16.14.0 || ^17.0.0 || ^18.0.0`, moment `^2.29.4`), and 17 has its own full-suite CI leg (`react-17` / `jest.react17.config.js`). The **checkpoint release** was cancelled by the §10 decision gate of 2026-08-18 — 17 folds into the React 18 release — so nothing publishes at the end of this phase. §5 records "Phase 1 is closed". | 1–2 days | QA checklist clean |
17741782
| **2** | ✅ **DONE except the release (re-checked 2026-09-17).** ~~React 18: `createRoot` (demo), RTL 12→16, `defaultProps` fixes, batching regression pass, peer widen, docs; checkpoint release~~ — `createRoot` at `src/demo/main.jsx:12`, `@testing-library/react` `^16.3.2` (+ `@testing-library/dom` `^10.4.1`), peers widened to include `^18.0.0`, no `flushSync` needed; §6 records "steps 1-8 done except the release". The manual publish + Pages deploy still ahead is the release itself, which stays deferred. | 1–2 weeks | CI green on 18, zero act-warnings |
17751783
| **3** | ✅ **DONE (re-verified 2026-09-17).** ~~Contract tests on all examples; JSON Schema + dev validation; error boundaries; React 16/17 CI smoke~~ — contract suites over all 38 examples (`examples.dom-contract.test.js`, `examples.behavior-contract.test.js`, `examples.meta-contract.test.js`), `meta.schema.json` at the repo root with dev validation at `src/core/ui-render/validateMeta.js`, the error boundary at `src/core/ui-render/Render.js:92` (`componentDidCatch`, with `Render.error-reporting.test.js` and `UIRender.error-hook.test.js`), and CI jobs `react-16-floor` / `react-17` running the whole suite. Appendix C's Phase 3 bullets are all ✅/☑. | 1–2 weeks | Contract suite in CI |
1776-
| **4** | Hooks migration of leaf components; ~~automatic JSX runtime~~ **shipped 2026-09-30 (§9.8)**; ~~SUIR passthrough-prop audit + lint guard (F1 step 0)~~ **shipped** (`docs/SUPPORTED-PROPS.md` + the `no-restricted-imports` guard); **housekeeping H1–H2 (dead code + docs truth)** | ongoing, per-component PRs | — |
1784+
| **4** | ~~Hooks migration of leaf components~~ **done 2026-09-30 (§9.2)**; ~~automatic JSX runtime~~ **shipped 2026-09-30 (§9.8)**; ~~SUIR passthrough-prop audit + lint guard (F1 step 0)~~ **shipped** (`docs/SUPPORTED-PROPS.md` + the `no-restricted-imports` guard); **housekeeping H1–H2 (dead code + docs truth)** | ongoing, per-component PRs | — |
17771785
| **4-S** | **Structure (§9.9): demo isolation (H3); engine re-home `pages/main`+`ui-render` → `core/engine` (H4, pure `git mv` commits); layer-direction lint (H5)** | ~2–4 days, in a quiet window | **H4 before Phase 6** |
17781786
| **TS** | **TypeScript migration track (§9.6): E0 infra after Phase 2 → utils+contract (E1) → components/modules (E2, rides 4/5a) → engine (E3, rides 6) → public-API switchover (E4) → `prop-types` dependency removed (E5); **go/no-go on the E2/E3 tail after E1** | continuous, per-PR | `tsc --noEmit` green throughout; E4 gated by the `dist/index.d.ts` golden diff |
17791787
| **5a** | ✅ **DONE (2026-09-08).** SUIR exit, JS side (F1 steps 1–3½): `Table`, `TooltipPop`, `Dropdown` all in-house, then `semantic-ui-react` removed from `dependencies` | ~3–5 weeks | behavioral + visual/a11y suites per step |

‎src/core/engine/Data.js‎

Lines changed: 75 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1-
import React, { Component } from 'react'
1+
import React from 'react'
22
import { type } from '../components'
33
import { Active } from '../utils'
44
import UIRenderWithUISetup from './rules'
55
import LocalDraftTableRow from './components/LocalDraftTableRow'
66

7+
// The class's `defaultProps` were two shared objects, and their identity is part of what they meant: `data`
8+
// reaches the nested document, which compares what it is given by reference. A default parameter would be a
9+
// new object on every render.
10+
const NO_DATA = {}
11+
const NO_META = {}
12+
713
/**
814
* Component to hold independent UI Render Instance Data
915
*
@@ -23,84 +29,44 @@ import LocalDraftTableRow from './components/LocalDraftTableRow'
2329
* }
2430
*
2531
*/
26-
export default class Data extends Component {
27-
static propTypes = {
28-
// Identifier for this type of data.
29-
// Data of the same `kind` are grouped into array as list, and used for complex validation (together as group).
30-
kind: type.Id.isRequired,
31-
// The UI Render Instance containing this Data component
32-
instance: type.Object.isRequired,
33-
// The Index of this Data component in the array of rendered data for removing itself
34-
index: type.NumberOrString,
35-
// Data.json to use
36-
data: type.Any,
37-
// Meta.json to use
38-
meta: type.Object,
39-
// Data.json to initialize with
40-
initialValues: type.Any,
41-
// Whether the `name` attribute should use data relative to root UI Render instance, defaults to this instance.
42-
rootData: type.Boolean,
43-
44-
relativePath: type.String,
45-
relativeIndex: type.Number,
46-
/** When true, TableCells draft row uses local state only until Add (no nested form / no parent values leakage). */
47-
localDraft: type.Boolean,
48-
}
32+
export default function Data ({
33+
kind, instance, index, relativeIndex, relativePath, data = NO_DATA, meta: metaIn = NO_META, initialValues = data,
34+
className, style, embedded, useForm, localDraft,
35+
}) {
36+
// Use Active.UIRender to avoid circular import
37+
const UIRender = Active.UIRender
4938

50-
static defaultProps = {
51-
data: {},
52-
meta: {},
53-
}
39+
// Never mutate shared meta from config: nested tables (e.g. one Data/TableCells per outer row) reuse the
40+
// same meta object reference — writing relativePath/relativeIndex on it would leave every row with the
41+
// last-rendered row's paths (mixed data, inputs not updating / wrong targets).
42+
const meta = (metaIn.view === 'TableCells' || metaIn.view === 'Data')
43+
? {...metaIn, relativePath, relativeIndex}
44+
: metaIn
5445

55-
render () {
56-
const {kind, instance, index, relativeIndex, data, meta: metaIn, initialValues = data, className, style, embedded, useForm, localDraft} = this.props
57-
// Use Active.UIRender to avoid circular import
58-
const UIRender = Active.UIRender
59-
60-
// Never mutate shared meta from config: nested tables (e.g. one Data/TableCells per outer row) reuse the
61-
// same meta object reference — writing relativePath/relativeIndex on it would leave every row with the
62-
// last-rendered row's paths (mixed data, inputs not updating / wrong targets).
63-
const meta = (metaIn.view === 'TableCells' || metaIn.view === 'Data')
64-
? {...metaIn, relativePath: this.props.relativePath, relativeIndex: this.props.relativeIndex}
65-
: metaIn
66-
67-
// TableCells only, or Data wrapping TableCells (e.g. renderExtraItem). Draft values stay in React state
68-
// until Add — no final-form fields at dataKind.*[nextIndex], so an empty `{}` is not materialized for the draft row.
69-
if (localDraft) {
70-
const rel = { relativePath: this.props.relativePath, relativeIndex: this.props.relativeIndex }
71-
const draftMeta = metaIn.view === 'TableCells'
72-
? meta
73-
: (metaIn.meta && metaIn.meta.view === 'TableCells' ? { ...metaIn.meta, ...rel } : null)
74-
if (draftMeta) {
75-
return (
76-
<LocalDraftTableRow
77-
meta={draftMeta}
78-
kind={kind}
79-
parentInstance={instance}
80-
/>
81-
)
82-
}
46+
// TableCells only, or Data wrapping TableCells (e.g. renderExtraItem). Draft values stay in React state
47+
// until Add — no final-form fields at dataKind.*[nextIndex], so an empty `{}` is not materialized for the draft row.
48+
if (localDraft) {
49+
const rel = { relativePath, relativeIndex }
50+
const draftMeta = metaIn.view === 'TableCells'
51+
? meta
52+
: (metaIn.meta && metaIn.meta.view === 'TableCells' ? { ...metaIn.meta, ...rel } : null)
53+
if (draftMeta) {
54+
return (
55+
<LocalDraftTableRow
56+
meta={draftMeta}
57+
kind={kind}
58+
parentInstance={instance}
59+
/>
60+
)
8361
}
62+
}
8463

85-
// Table row contexts set `relativeIndex` (field array index); `index` is often unset.
86-
// Prefer relativeIndex over index so row identity stays correct after FieldArray reindex (e.g. remove row).
87-
const rowIndex = relativeIndex != null ? relativeIndex : index
88-
89-
if (useForm) {
90-
return <UIRenderWithUISetup
91-
data={data}
92-
meta={meta}
93-
initialValues={initialValues}
94-
form={{kind}}
95-
parent={instance}
96-
index={rowIndex}
97-
relativeIndex={relativeIndex}
98-
embedded={embedded}
99-
{...{className, style}}
100-
/>
101-
}
64+
// Table row contexts set `relativeIndex` (field array index); `index` is often unset.
65+
// Prefer relativeIndex over index so row identity stays correct after FieldArray reindex (e.g. remove row).
66+
const rowIndex = relativeIndex != null ? relativeIndex : index
10267

103-
return <UIRender
68+
if (useForm) {
69+
return <UIRenderWithUISetup
10470
data={data}
10571
meta={meta}
10672
initialValues={initialValues}
@@ -112,6 +78,41 @@ export default class Data extends Component {
11278
{...{className, style}}
11379
/>
11480
}
81+
82+
return <UIRender
83+
data={data}
84+
meta={meta}
85+
initialValues={initialValues}
86+
form={{kind}}
87+
parent={instance}
88+
index={rowIndex}
89+
relativeIndex={relativeIndex}
90+
embedded={embedded}
91+
{...{className, style}}
92+
/>
93+
}
94+
95+
Data.propTypes = {
96+
// Identifier for this type of data.
97+
// Data of the same `kind` are grouped into array as list, and used for complex validation (together as group).
98+
kind: type.Id.isRequired,
99+
// The UI Render Instance containing this Data component
100+
instance: type.Object.isRequired,
101+
// The Index of this Data component in the array of rendered data for removing itself
102+
index: type.NumberOrString,
103+
// Data.json to use
104+
data: type.Any,
105+
// Meta.json to use
106+
meta: type.Object,
107+
// Data.json to initialize with
108+
initialValues: type.Any,
109+
// Whether the `name` attribute should use data relative to root UI Render instance, defaults to this instance.
110+
rootData: type.Boolean,
111+
112+
relativePath: type.String,
113+
relativeIndex: type.Number,
114+
/** When true, TableCells draft row uses local state only until Add (no nested form / no parent values leakage). */
115+
localDraft: type.Boolean,
115116
}
116117

117118
// =============================================================================

‎src/core/engine/components/LocalDraftTableRow.js‎

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { PureComponent } from 'react'
1+
import React, { memo, useState } from 'react'
22
import Button from '../../components/Button'
33
import Input from '../../components/Input'
44
import InputDate from '../../components/InputDate'
@@ -51,32 +51,33 @@ function parseRowValue (def, raw) {
5151
return raw
5252
}
5353

54+
// Read once, when this module loads, as the class's `defaultProps` were. `Active.translate` is reassigned by
55+
// every document the engine constructs (rules.js), so reading it at render would hand a draft row whichever
56+
// document was built last.
57+
const DEFAULT_TRANSLATE = Active.translate
58+
59+
const EMPTY_DRAFT = { draft: {}, fieldErrors: {} }
60+
5461
/**
5562
* Table "add row" draft: values live only in React state until the user commits (Add).
5663
* No react-final-form Field registration — avoids leaking draft into parent `values`.
5764
*/
58-
export default class LocalDraftTableRow extends PureComponent {
59-
static defaultProps = {
60-
translate: Active.translate
61-
}
62-
63-
state = {
64-
draft: {},
65-
fieldErrors: {}
66-
}
65+
function LocalDraftTableRow ({ meta, kind, parentInstance, translate = DEFAULT_TRANSLATE }) {
66+
const [state, setState] = useState(EMPTY_DRAFT)
67+
// `this.setState` merged into the state it was given; this keeps that shape, and the updater form.
68+
const update = (partial) => setState((s) => ({ ...s, ...(typeof partial === 'function' ? partial(s) : partial) }))
6769

68-
handleChange = (name, def) => (e) => {
70+
const handleChange = (name) => (e) => {
6971
const v = e && e.target ? e.target.value : e
70-
this.setState((s) => ({
72+
update((s) => ({
7173
draft: { ...s.draft, [name]: v },
7274
fieldErrors: { ...s.fieldErrors, [name]: undefined }
7375
}))
7476
}
7577

76-
handleAdd = () => {
77-
const { meta, kind, parentInstance } = this.props
78+
const handleAdd = () => {
7879
const inputs = collectInputs(meta.items)
79-
const { draft, fieldErrors: prevErr } = this.state
80+
const { draft, fieldErrors: prevErr } = state
8081
const fieldErrors = { ...prevErr }
8182
let hasErr = false
8283

@@ -111,7 +112,7 @@ export default class LocalDraftTableRow extends PureComponent {
111112
}
112113

113114
if (hasErr) {
114-
this.setState({ fieldErrors })
115+
update({ fieldErrors })
115116
return
116117
}
117118

@@ -122,7 +123,7 @@ export default class LocalDraftTableRow extends PureComponent {
122123
rowObject: row,
123124
fallbackDataKindPath: ''
124125
})
125-
if (appended !== false) this.setState({ draft: {}, fieldErrors: {} })
126+
if (appended !== false) update({ draft: {}, fieldErrors: {} })
126127
}
127128

128129
/**
@@ -134,18 +135,17 @@ export default class LocalDraftTableRow extends PureComponent {
134135
* `style={{verticalAlign: 'top'}}`, which is what the metas that actually align already do —
135136
* and expect a visual change, because that one works.
136137
*/
137-
renderInputCell = (def, i) => {
138-
const { translate } = this.props
138+
const renderInputCell = (def, i) => {
139139
const name = def.name
140-
const { draft, fieldErrors } = this.state
140+
const { draft, fieldErrors } = state
141141
const value = draft[name]
142142
const error = fieldErrors[name]
143143
const { className, type, format: _f, validate: _v, ...rest } = def
144144
const common = {
145145
...rest,
146146
name,
147147
value: value === undefined || value === null ? '' : value,
148-
onChange: this.handleChange(name, def),
148+
onChange: handleChange(name),
149149
error,
150150
translate,
151151
className
@@ -159,12 +159,12 @@ export default class LocalDraftTableRow extends PureComponent {
159159
)
160160
}
161161

162-
renderBranch = (item, i) => {
162+
const renderBranch = (item, i) => {
163163
if (item.view === 'Input' && item.name) {
164-
return this.renderInputCell(item, i)
164+
return renderInputCell(item, i)
165165
}
166166
if (item.view === 'VerticalLayout' || item.view === 'Col3') {
167-
return (item.items || []).flatMap((sub, j) => this.renderBranch(sub, `${i}-${j}`))
167+
return (item.items || []).flatMap((sub, j) => renderBranch(sub, `${i}-${j}`))
168168
}
169169
if (item.view === 'Button') {
170170
const oc = item.onClick
@@ -173,7 +173,7 @@ export default class LocalDraftTableRow extends PureComponent {
173173
const { onClick: _oc, children, ...btnRest } = item
174174
return (
175175
<Table.Cell key={`btn-${i}`}>
176-
<Button {...btnRest} type="button" onClick={this.handleAdd} translate={this.props.translate}>
176+
<Button {...btnRest} type="button" onClick={handleAdd} translate={translate}>
177177
{children}
178178
</Button>
179179
</Table.Cell>
@@ -182,14 +182,14 @@ export default class LocalDraftTableRow extends PureComponent {
182182
return null
183183
}
184184

185-
render () {
186-
const { meta } = this.props
187-
if (!meta || !meta.items) return null
188-
const cells = meta.items.flatMap((item, i) => {
189-
const node = this.renderBranch(item, i)
190-
if (node == null) return []
191-
return Array.isArray(node) ? node : [node]
192-
})
193-
return <>{cells}</>
194-
}
185+
if (!meta || !meta.items) return null
186+
const cells = meta.items.flatMap((item, i) => {
187+
const node = renderBranch(item, i)
188+
if (node == null) return []
189+
return Array.isArray(node) ? node : [node]
190+
})
191+
return <>{cells}</>
195192
}
193+
194+
// `memo` skips a render with shallow-equal props, as `PureComponent` did.
195+
export default memo(LocalDraftTableRow)

0 commit comments

Comments
 (0)