-
-
Notifications
You must be signed in to change notification settings - Fork 7
feat: Add state-management-react #141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletions
3
components/state-management/state-management-react/CHANGELOG.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| # Changelog | ||
|
|
||
| This file will be updated automatically during release. |
58 changes: 58 additions & 0 deletions
58
components/state-management/state-management-react/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| # State Management Adapter for React | ||
|
|
||
| If you're writing view models with `@ethnolib/state-management-core`, this package | ||
| lets React components bind directly to `Field` instances. | ||
|
|
||
| Use `useField()` anywhere you would normally wire React state to a form control, | ||
| display value, or other reactive UI element. | ||
|
|
||
| ```tsx | ||
| import { Field } from "@ethnolib/state-management-core"; | ||
| import { useField } from "@ethnolib/state-management-react"; | ||
|
|
||
| function usePersonViewModel() { | ||
| const name = new Field("John"); | ||
| const age = new Field(5, (newAge) => { | ||
| console.log(`I am now ${newAge}`); | ||
| }); | ||
|
|
||
| function haveBirthday() { | ||
| age.requestUpdate(age.value + 1); | ||
| } | ||
|
|
||
| return { name, age, haveBirthday }; | ||
| } | ||
|
|
||
| export function PersonCard() { | ||
| const person = usePersonViewModel(); | ||
| const [name, setName] = useField(person.name); | ||
| const [age] = useField(person.age); | ||
|
|
||
| return ( | ||
| <div> | ||
| <input value={name} onChange={(event) => setName(event.target.value)} /> | ||
| <p> | ||
| Hello, {name}. You are {age}. | ||
| </p> | ||
| <button onClick={person.haveBirthday}>Have a birthday!</button> | ||
| </div> | ||
| ); | ||
| } | ||
| ``` | ||
|
|
||
| ## Notes | ||
|
|
||
| - `useField()` returns the current field value and a setter that calls `requestUpdate()`. | ||
| - Multiple React components can subscribe to the same `Field` instance. | ||
| - When React swaps one `Field` instance for another, the hook cleans up the old subscription automatically. | ||
|
|
||
| ## Maintenance Note | ||
|
|
||
| This package still supports React 17, so `useField()` uses a small manual | ||
| subscription layer instead of `useSyncExternalStore()`. | ||
|
|
||
| If React 17 support is dropped in the future, the hook can be simplified | ||
| substantially by rewriting it around `useSyncExternalStore()`, which would let | ||
| React own the subscription lifecycle and snapshot synchronization. | ||
|
|
||
| See the main [README](../../../README.md) for workspace-level development details. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from "./src/use-field"; |
39 changes: 39 additions & 0 deletions
39
components/state-management/state-management-react/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| { | ||
| "name": "@ethnolib/state-management-react", | ||
| "description": "An adapter to use @ethnolib/state-management-core with React", | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/sillsdev/EthnoLib.git", | ||
| "directory": "components/state-management/state-management-react" | ||
| }, | ||
| "author": "SIL Global", | ||
| "license": "MIT", | ||
| "version": "0.1.0", | ||
| "main": "./index.js", | ||
| "types": "./index.d.ts", | ||
| "scripts": { | ||
| "build": "nx vite:build", | ||
| "typecheck": "tsc", | ||
| "test": "nx vite:test --config vitest.config.ts", | ||
| "testonce": "nx vite:test --config vitest.config.ts --run", | ||
| "lint": "eslint ." | ||
| }, | ||
| "dependencies": { | ||
| "@ethnolib/state-management-core": "0.1.1" | ||
| }, | ||
| "peerDependencies": { | ||
| "react": "^17.0.2", | ||
| "react-dom": "^17.0.2" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/react": "^17", | ||
| "@types/react-dom": "^17", | ||
| "@types/node": "^20.16.11", | ||
| "jsdom": "^26.0.0", | ||
| "tsx": "^4.19.2", | ||
| "typescript": "^5.2.2" | ||
| }, | ||
| "volta": { | ||
| "extends": "../../../package.json" | ||
| } | ||
| } | ||
139 changes: 139 additions & 0 deletions
139
components/state-management/state-management-react/src/use-field.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| import React from "react"; | ||
| import ReactDOM from "react-dom"; | ||
| import { act } from "react-dom/test-utils"; | ||
andrew-polk marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| import { afterEach, describe, expect, it, vi } from "vitest"; | ||
| import { Field } from "@ethnolib/state-management-core"; | ||
| import { useField } from "./use-field"; | ||
|
|
||
| // This test harness intentionally uses React 17-compatible APIs because the | ||
| // package still supports React 17 in peerDependencies. | ||
|
|
||
| function renderUseField<T>(field: Field<T>) { | ||
| const container = document.createElement("div"); | ||
| document.body.appendChild(container); | ||
|
|
||
| const result: { | ||
| current: [T, (value: T) => void] | null; | ||
| } = { | ||
| current: null, | ||
| }; | ||
|
|
||
| function HookHost(props: { boundField: Field<T> }) { | ||
| result.current = useField(props.boundField); | ||
| return null; | ||
| } | ||
|
|
||
| function render(boundField: Field<T>) { | ||
| act(() => { | ||
| ReactDOM.render(React.createElement(HookHost, { boundField }), container); | ||
| }); | ||
| } | ||
|
|
||
| render(field); | ||
|
|
||
| return { | ||
| result, | ||
| rerender(nextField: Field<T>) { | ||
| render(nextField); | ||
| }, | ||
| unmount() { | ||
| act(() => { | ||
| ReactDOM.unmountComponentAtNode(container); | ||
| }); | ||
| container.remove(); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| describe("useField", () => { | ||
| afterEach(() => { | ||
| document.body.innerHTML = ""; | ||
| }); | ||
|
|
||
| it("returns the current field value and reacts to field updates", () => { | ||
| const field = new Field("initial"); | ||
| const rendered = renderUseField(field); | ||
|
|
||
| expect(rendered.result.current?.[0]).toBe("initial"); | ||
|
|
||
| act(() => { | ||
| field.value = "from-ui"; | ||
| }); | ||
|
|
||
| expect(rendered.result.current?.[0]).toBe("from-ui"); | ||
| rendered.unmount(); | ||
| }); | ||
|
|
||
| it("setter requests a field update and the rendered value stays in sync", () => { | ||
| const onUpdateRequested = vi.fn(); | ||
| const field = new Field("old", onUpdateRequested); | ||
| const rendered = renderUseField(field); | ||
|
|
||
| act(() => { | ||
| rendered.result.current?.[1]("new"); | ||
| }); | ||
|
|
||
| expect(field.value).toBe("new"); | ||
| expect(onUpdateRequested).toHaveBeenCalledWith("new", "old"); | ||
| expect(rendered.result.current?.[0]).toBe("new"); | ||
| rendered.unmount(); | ||
| }); | ||
|
|
||
| it("supports multiple hook instances for the same field", () => { | ||
| const field = new Field("initial"); | ||
| const first = renderUseField(field); | ||
| const second = renderUseField(field); | ||
|
|
||
| act(() => { | ||
| field.requestUpdate("updated"); | ||
| }); | ||
|
|
||
| expect(first.result.current?.[0]).toBe("updated"); | ||
| expect(second.result.current?.[0]).toBe("updated"); | ||
|
|
||
| first.unmount(); | ||
|
|
||
| act(() => { | ||
| field.requestUpdate("after-first-unmount"); | ||
| }); | ||
|
|
||
| expect(second.result.current?.[0]).toBe("after-first-unmount"); | ||
| expect(field.updateUI).not.toBeNull(); | ||
| second.unmount(); | ||
| expect(field.updateUI).toBeNull(); | ||
| }); | ||
|
|
||
| it("moves the subscription when the field reference changes", () => { | ||
| const firstField = new Field("first"); | ||
| const secondField = new Field("second"); | ||
| const rendered = renderUseField(firstField); | ||
|
|
||
| rendered.rerender(secondField); | ||
|
|
||
| expect(firstField.updateUI).toBeNull(); | ||
| expect(secondField.updateUI).not.toBeNull(); | ||
|
|
||
| act(() => { | ||
| secondField.requestUpdate("updated"); | ||
| }); | ||
|
|
||
| expect(rendered.result.current?.[0]).toBe("updated"); | ||
| rendered.unmount(); | ||
| }); | ||
|
|
||
| it("keeps the setter stable until the field instance changes", () => { | ||
| const firstField = new Field("first"); | ||
| const secondField = new Field("second"); | ||
| const rendered = renderUseField(firstField); | ||
|
|
||
| const initialSetter = rendered.result.current?.[1]; | ||
| rendered.rerender(firstField); | ||
|
|
||
| expect(rendered.result.current?.[1]).toBe(initialSetter); | ||
|
|
||
| rendered.rerender(secondField); | ||
|
|
||
| expect(rendered.result.current?.[1]).not.toBe(initialSetter); | ||
| rendered.unmount(); | ||
| }); | ||
| }); | ||
71 changes: 71 additions & 0 deletions
71
components/state-management/state-management-react/src/use-field.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import { useCallback, useEffect, useState } from "react"; | ||
| import { Field } from "@ethnolib/state-management-core"; | ||
|
|
||
| type FieldSubscriber<T> = (value: T) => void; | ||
|
|
||
| type FieldSubscriptionState = { | ||
| previousUpdateUI: ((value: unknown) => void) | null; | ||
| subscribers: Set<(value: unknown) => void>; | ||
| }; | ||
|
|
||
| const fieldSubscriptionStates = new WeakMap<Field<unknown>, FieldSubscriptionState>(); | ||
|
|
||
| // If React 17 support is dropped, this adapter can be simplified substantially | ||
| // by rewriting useField() around useSyncExternalStore instead of maintaining a | ||
| // manual subscriber registry. | ||
|
|
||
| function subscribeToField<T>(field: Field<T>, subscriber: FieldSubscriber<T>) { | ||
| let subscriptionState = fieldSubscriptionStates.get(field as Field<unknown>); | ||
| if (!subscriptionState) { | ||
| const subscribers = new Set<(value: unknown) => void>(); | ||
| const previousUpdateUI = | ||
| (field.updateUI as ((value: unknown) => void) | null) ?? null; | ||
| const dispatchToSubscribers = (value: unknown) => { | ||
| previousUpdateUI?.(value); | ||
| subscribers.forEach((currentSubscriber) => currentSubscriber(value)); | ||
| }; | ||
|
|
||
| subscriptionState = { | ||
| previousUpdateUI, | ||
| subscribers, | ||
| }; | ||
| fieldSubscriptionStates.set(field as Field<unknown>, subscriptionState); | ||
| field.updateUI = dispatchToSubscribers as Field<T>["updateUI"]; | ||
| } | ||
|
|
||
| subscriptionState.subscribers.add(subscriber as (value: unknown) => void); | ||
|
|
||
| return () => { | ||
| const currentState = fieldSubscriptionStates.get(field as Field<unknown>); | ||
| if (!currentState) { | ||
| return; | ||
| } | ||
|
|
||
| currentState.subscribers.delete(subscriber as (value: unknown) => void); | ||
| if (currentState.subscribers.size === 0) { | ||
| field.updateUI = currentState.previousUpdateUI as Field<T>["updateUI"]; | ||
| fieldSubscriptionStates.delete(field as Field<unknown>); | ||
| } | ||
| }; | ||
andrew-polk marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| export function useField<T>(field: Field<T>): [T, (value: T) => void] { | ||
| const [fieldValue, setFieldValueState] = useState<T>(field.value as T); | ||
|
|
||
| const setFieldValue = useCallback((value: T) => { | ||
| field.requestUpdate(value); | ||
| }, [field]); | ||
|
|
||
| useEffect(() => { | ||
| const unsubscribe = subscribeToField(field, (value) => { | ||
| setFieldValueState(value); | ||
| }); | ||
|
|
||
| // Catch updates that may have happened between render and effect setup. | ||
| setFieldValueState(field.value as T); | ||
|
|
||
| return unsubscribe; | ||
| }, [field]); | ||
|
|
||
| return [fieldValue, setFieldValue]; | ||
| } | ||
22 changes: 22 additions & 0 deletions
22
components/state-management/state-management-react/tsconfig.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| { | ||
| "compilerOptions": { | ||
| "jsx": "react-jsx", | ||
| "allowJs": false, | ||
| "esModuleInterop": false, | ||
| "allowSyntheticDefaultImports": true, | ||
| "strict": true | ||
| }, | ||
| "ts-node": { | ||
| "moduleTypes": { | ||
| "*": "esm" | ||
| } | ||
| }, | ||
| "files": [], | ||
| "include": [], | ||
| "references": [ | ||
| { | ||
| "path": "./tsconfig.lib.json" | ||
| } | ||
| ], | ||
| "extends": "../../../tsconfig.base.json" | ||
| } |
27 changes: 27 additions & 0 deletions
27
components/state-management/state-management-react/tsconfig.lib.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| { | ||
| "extends": "./tsconfig.json", | ||
| "compilerOptions": { | ||
| "outDir": "../../../dist/out-tsc", | ||
| "types": ["node", "vite/client"], | ||
| "composite": true, | ||
| "declaration": true, | ||
| "declarationMap": true | ||
| }, | ||
| "exclude": [ | ||
| "**/*.spec.ts", | ||
| "**/*.test.ts", | ||
| "**/*.spec.tsx", | ||
| "**/*.test.tsx", | ||
| "**/*.spec.js", | ||
| "**/*.test.js", | ||
| "**/*.spec.jsx", | ||
| "**/*.test.jsx" | ||
| ], | ||
| "include": [ | ||
| "./**/*.js", | ||
| "./**/*.jsx", | ||
| "./**/*.ts", | ||
| "./**/*.tsx", | ||
| "../index.ts" | ||
| ] | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.