Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ export class Field<T> {
this._onUpdateRequested = onUpdateRequested;
}

/**
* Framework adapters use this hook to mirror field updates back into UI
* state. Adapters assume ownership of this callback while they are mounted,
* so application code should not overwrite it directly.
*/
public updateUI: ((newValue: ReadonlyValue<T>) => void) | null = null;

/**
Expand Down
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 components/state-management/state-management-react/README.md
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.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./src/use-field";
39 changes: 39 additions & 0 deletions components/state-management/state-management-react/package.json
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"
}
}
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";
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();
});
});
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>);
}
};
}

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 components/state-management/state-management-react/tsconfig.json
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"
}
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"
]
}
Loading
Loading