From b17ca6a1dc36d4a813ae35be9b4143e59cdf4954 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:18:28 +0000 Subject: [PATCH 1/4] wip(react): metadata selector store, per-type revisions (#37903 PR 1) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyRPrFte1TGnaiugba --- .../src/providers/MetadataProvider.tsx | 187 +++++++++++++++--- .../app-shell/src/providers/bundledReads.ts | 56 +++++- .../react/src/context/AppShellContext.tsx | 151 +++++++++++++- 3 files changed, 365 insertions(+), 29 deletions(-) diff --git a/ui/packages/app-shell/src/providers/MetadataProvider.tsx b/ui/packages/app-shell/src/providers/MetadataProvider.tsx index 138ab38a521..d26a30c6ce1 100644 --- a/ui/packages/app-shell/src/providers/MetadataProvider.tsx +++ b/ui/packages/app-shell/src/providers/MetadataProvider.tsx @@ -4,6 +4,7 @@ import { useCallback, useRef, useMemo, + useLayoutEffect, type ReactNode, } from 'react'; import { expandViewContainer } from '@objectstack/spec/ui'; @@ -22,6 +23,7 @@ import { resolveInlineMode } from '@object-ui/plugin-form/core'; import { fieldGroupsPlaceRelationship, isGroupPlaceableRelationship } from '@objectstack/spec/data'; import { MetadataCtx, + MetadataStoreCtx, answeredLoadFailure, classifyLoadError, useMetadata, @@ -29,7 +31,10 @@ import { type MetadataContextValue, type MetadataItemReadOptions, type MetadataCacheState, + type MetadataStore, type MetadataTypeStatus, + useMetadataSelector, + useMetadataTypeItems, } from '@object-ui/react'; import { usePreviewDrafts } from '../preview/PreviewModeContext.js'; import { createConsoleMetadataClient } from '../views/metadata-admin/metadataClientFactory.js'; @@ -37,7 +42,9 @@ import { subscribeCanvasInvalidate, subscribeMetadataRefresh } from '../assistan import { BUNDLE_MISS, BUNDLE_PENDING, + BUNDLE_STORE_KEY, BundledReadsCtx, + BundledReadsStoreCtx, type BundledRead, type BundledReads, } from './bundledReads.js'; @@ -1007,6 +1014,88 @@ function removeNoOrgSeedEntry(type: string): void { // Provider // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// The selector store (objectstack#37903) +// --------------------------------------------------------------------------- + +/** + * The key a change to the object scopes (`readObjectScope`) is recorded + * under. No metadata type is named this, so a per-type reader of `object` is + * not woken by a scope landing it does not read. + */ +const SCOPE_STORE_KEY = '#scope'; +const SCOPE_KEYS: readonly string[] = [SCOPE_STORE_KEY]; +const BUNDLE_KEYS: readonly string[] = [BUNDLE_STORE_KEY]; +/** The key the aggregate load flags (`loading`, `error`) are recorded under. */ +const STATUS_STORE_KEY = '#status'; + +/** The provider's {@link MetadataStore}, plus the two calls only the provider makes. */ +interface ProviderStore extends MetadataStore { + /** Record that `types` changed, or the whole store with none; woken at the next {@link flush}. */ + mark(types?: readonly string[]): void; + /** Hand the store the value of this render, read by {@link MetadataStore.getValue}. */ + setValue(value: MetadataContextValue): void; + /** After a commit: count what changed and wake the readers it concerns. */ + flush(): void; +} + +interface StoreListener { + listener: () => void; + types: readonly string[] | undefined; +} + +/** + * One store per provider instance. Its state lives here, outside React's + * memo caches (ui/AGENTS.md #10): the revisions, the pending changes and the + * listeners. A change is only recorded by {@link ProviderStore.mark}; readers + * are woken by {@link ProviderStore.flush}, after the provider's commit, so a + * reader always selects from the value that commit rendered. + */ +function createProviderStore(): ProviderStore { + let value: MetadataContextValue | null = null; + let wholeStoreRevision = 0; + const revisions = new Map(); + let pendingWhole = false; + const pending = new Set(); + const listeners = new Set(); + return { + getValue() { + if (value === null) throw new Error('MetadataProvider: the store is read before the provider rendered'); + return value; + }, + subscribe(listener, types) { + const entry: StoreListener = { listener, types: types ? [...types] : undefined }; + listeners.add(entry); + return () => { + listeners.delete(entry); + }; + }, + getRevision(type) { + return wholeStoreRevision + (revisions.get(type) ?? 0); + }, + mark(types) { + if (!types) pendingWhole = true; + else for (const type of types) pending.add(type); + }, + setValue(next) { + value = next; + }, + flush() { + if (!pendingWhole && pending.size === 0) return; + const whole = pendingWhole; + const changed = new Set(pending); + pendingWhole = false; + pending.clear(); + if (whole) wholeStoreRevision += 1; + else for (const type of changed) revisions.set(type, (revisions.get(type) ?? 0) + 1); + for (const entry of Array.from(listeners)) { + if (!listeners.has(entry)) continue; + if (whole || !entry.types || entry.types.some((type) => changed.has(type))) entry.listener(); + } + }, + }; +} + export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: MetadataProviderProps) { const cacheRef = useRef>(new Map()); const itemPromisesRef = useRef>(new Map()); @@ -1104,18 +1193,27 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: const answeredBundleRef = useRef(null); const [version, setVersion] = useState(0); + // objectstack#37903 — the store selector readers subscribe to. It records + // which types each bump changed and wakes their readers after the commit. + const storeRef = useRef(null); + if (storeRef.current === null) storeRef.current = createProviderStore(); + const store = storeRef.current; // Defer state bumps so they never occur synchronously during a consumer's // render phase. `ensureType` may be invoked from inside `useMemo` getters // (e.g. when a list-page renders and triggers a lazy fetch), and React // forbids cross-component setState during render. queueMicrotask schedules // the update after the current render has committed. - const bump = useCallback(() => { + // + // `types` names what changed, for the store's per-type readers; a bump that + // names nothing (or is handed a promise's value) changed the whole store. + const bump = useCallback((types?: readonly string[]) => { + store.mark(Array.isArray(types) ? types : undefined); if (typeof queueMicrotask === 'function') { queueMicrotask(() => setVersion(v => v + 1)); } else { Promise.resolve().then(() => setVersion(v => v + 1)); } - }, []); + }, [store]); // ── objectstack#28645 — the app bundle, read in render ─────────────────── // @@ -1147,7 +1245,8 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: // A load on the wire re-renders the readers when it lands, once per load. if (peek.settled && !watchedBundleLoadsRef.current.has(peek.settled)) { watchedBundleLoadsRef.current.add(peek.settled); - void peek.settled.then(bump, bump); + const landed = () => bump(BUNDLE_KEYS); + void peek.settled.then(landed, landed); } if (peek.status === 'ready') answeredBundleRef.current = peek.items; return peek; @@ -1160,7 +1259,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: // `peekBundle` re-marked the ask; none is now the answer. bundleNoneAskedRef.current = false; bundleNoneFinalRef.current = true; - bump(); + bump(BUNDLE_KEYS); }); const readBundledItem = useCallback( (type: string, name: string, ownerPackageId?: unknown): BundledRead => { @@ -1199,14 +1298,14 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: const peek = peekBundle(); // No bundle at all: the readers' next read misses on its own. if (!peek) { - bump(); + bump(BUNDLE_KEYS); return; } // Not entered yet (the effect above settles that), or a load on the wire, // which re-renders the readers when it lands. if (peek.status !== 'ready' || peek.settled) return; if (!peek.items.get('app')?.has(asked)) bundleAppMissRef.current.add(asked); - bump(); + bump(BUNDLE_KEYS); }); const readBundledReferencing = useCallback( (appName: string, objectName: string): BundledRead => { @@ -1337,7 +1436,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: } } debug(`fetched type=${type} items=${items.length} in ${Date.now() - started}ms`); - bump(); + bump([type]); return items; }) .catch((err: unknown) => { @@ -1351,7 +1450,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: // explicit retry immediate. entry.fetchedAt = Date.now(); debug(`fetch failed type=${type}`, error); - bump(); + bump([type]); return [] as any[]; }); @@ -1504,14 +1603,14 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: entry.status = 'ready'; entry.answered = true; debug(`fetched object scope package=${packageId} items=${items.length}`); - bump(); + bump(SCOPE_KEYS); }) .catch((err: unknown) => { if (scopesRef.current.get(packageId) !== entry) return; entry.status = 'error'; entry.answered = true; debug(`fetch failed object scope package=${packageId}`, err); - bump(); + bump(SCOPE_KEYS); }); }, [bump], @@ -1536,7 +1635,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: // objectstack#29728 — and what the server said, when one answered. if (answer) entry.answers = { ...entry.answers, [name]: answer }; else if (name in entry.answers) entry.answers = withoutName(entry.answers, name); - bump(); + bump(SCOPE_KEYS); return; } entry.names.set(name, 'answered'); @@ -1552,7 +1651,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: if (refusal ? entry.refused[name] !== refusal : name in entry.refused) { entry.refused = refusal ? { ...entry.refused, [name]: refusal } : withoutName(entry.refused, name); } - bump(); + bump(SCOPE_KEYS); }); }, [bump, readItem], @@ -1598,7 +1697,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: for (const name of names) delete answers[name]; entry.answers = answers; debug(`fetched object names scope names=${names.length} items=${items.length}`); - bump(); + bump(SCOPE_KEYS); }, (err: unknown) => { if (scopesRef.current.get(NAMES_BATCH_SCOPE) !== entry) return; @@ -1611,7 +1710,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: else delete answers[name]; } entry.answers = answers; - bump(); + bump(SCOPE_KEYS); }, ); }, @@ -1700,7 +1799,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: entry.fetchedAt = 0; debug(`invalidated type=${type}`); } - bump(); + bump(type === 'object' ? [type, SCOPE_STORE_KEY] : [type]); }, [bump, dropAdapterObjectReads, getEntry], ); @@ -1872,7 +1971,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: entry.byName.set(it.name, it); } } - bump(); + bump(['app']); setInitialLoading(false); } @@ -2097,7 +2196,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: } } if (toBatch.length > 0) void fetchScopeNames(entry, toBatch); - if (answeredFromPresence) bump(); + if (answeredFromPresence) bump(SCOPE_KEYS); // objectui#13052 — `settled` stays false while a name's read has // failed (a failure is not an answer, objectui#13009); `failed` names // those reads once nothing else is still in flight, so a reader can stop @@ -2190,22 +2289,64 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: return base; }, [version, initialLoading, initialError, ensureType, getItem, getEntry, refresh, invalidate, readType, readObjectScope]); + // The store answers what this render answers (objectstack#37903). + store.setValue(value); + + // The aggregate load flags are React state, not a bump: record their change + // too, so a selector of `loading` or `error` is woken by it. A new adapter + // is a new world for every read (the bundle included): the whole store. + const committedRef = useRef({ initialLoading, initialError, adapter }); + useLayoutEffect(() => { + const previous = committedRef.current; + committedRef.current = { initialLoading, initialError, adapter }; + if (previous.adapter !== adapter) store.mark(); + if (previous.initialLoading !== initialLoading || previous.initialError !== initialError) { + store.mark([STATUS_STORE_KEY]); + } + // Keyed on the state that changes, never on the memoised value's + // identity (ui/AGENTS.md #10): a flush with nothing recorded does nothing. + store.flush(); + }, [store, version, initialLoading, initialError, adapter]); // A new identity per version, so a reader re-renders when the bundle lands. const bundledReads = useMemo(() => { void version; return { item: readBundledItem, viewsFor: readBundledViews, objectsReferencing: readBundledReferencing }; }, [version, readBundledItem, readBundledViews, readBundledReferencing]); + // objectstack#37903 — the same reads behind ONE object for the provider's + // lifetime, for `useBundledItem`, which is woken by the store instead. + const bundledReadsRef = useRef(bundledReads); + bundledReadsRef.current = bundledReads; + const stableBundledReadsRef = useRef(null); + if (stableBundledReadsRef.current === null) { + stableBundledReadsRef.current = { + item: (type, name, ownerPackageId) => bundledReadsRef.current.item(type, name, ownerPackageId), + viewsFor: (objectNames) => bundledReadsRef.current.viewsFor(objectNames), + objectsReferencing: (appName, objectName) => bundledReadsRef.current.objectsReferencing(appName, objectName), + }; + } return ( - - {children} - + + + + {children} + + + ); } +/** + * One type's items with the aggregate load flags. Reads through the store + * (objectstack#37903): it re-renders when `type`'s list or a flag it returns + * changes, not on every metadata change. + */ export function useMetadataType(type: string): { items: any[]; loading: boolean; error: Error | null } { - const ctx = useMetadata(); - const items = ctx.getItemsByType(type); - return { items, loading: ctx.loading && type === 'app', error: ctx.error }; + const items = useMetadataTypeItems(type); + const loading = useMetadataSelector((metadata) => metadata.loading && type === 'app'); + const error = useMetadataSelector(selectError); + return { items, loading, error }; } + +const selectError = (metadata: MetadataContextValue): Error | null => metadata.error; diff --git a/ui/packages/app-shell/src/providers/bundledReads.ts b/ui/packages/app-shell/src/providers/bundledReads.ts index 2b3e09355d4..e4ba53bd1d9 100644 --- a/ui/packages/app-shell/src/providers/bundledReads.ts +++ b/ui/packages/app-shell/src/providers/bundledReads.ts @@ -13,7 +13,8 @@ * no-provider answer (a miss: every read reads its list). */ -import { createContext, useContext } from 'react'; +import { createContext, use, useCallback, useContext, useRef, useSyncExternalStore } from 'react'; +import { MetadataStoreCtx } from '@object-ui/react'; /** * One bundle-first read: `pending` while the app bundle that may hold it has @@ -62,15 +63,62 @@ export interface BundledReads { export const BundledReadsCtx = createContext(null); +/** + * objectstack#37903 — the same reads as {@link BundledReadsCtx}, behind ONE + * object for the provider's lifetime. `useBundledItem` reads it and is woken + * by the metadata store when the bundle changes, instead of re-rendering with + * every new {@link BundledReadsCtx} value (one per metadata change). + */ +export const BundledReadsStoreCtx = createContext(null); + +/** + * The store key a change to what the bundle answers is recorded under: a + * bundle landing, an app it does not hold, no bundle at all. No metadata type + * is named this. + */ +export const BUNDLE_STORE_KEY = '#bundle'; +const BUNDLE_STORE_KEYS: readonly string[] = [BUNDLE_STORE_KEY]; +const NO_SUBSCRIBE = (): (() => void) => () => {}; + +/** The same answer: the same state, and for a hit, the same item. */ +function sameBundledRead(a: BundledRead, b: BundledRead): boolean { + if (a.state !== b.state) return false; + return a.state !== 'hit' || (b.state === 'hit' && Object.is(a.value, b.value)); +} + /** The provider's {@link BundledReads}, or `null` outside a `MetadataProvider` (every read then reads its list). */ export function useBundledReads(): BundledReads | null { return useContext(BundledReadsCtx); } -/** {@link BundledReads.item} as a hook; a miss outside a `MetadataProvider` or with no name. */ +/** + * {@link BundledReads.item} as a hook; a miss outside a `MetadataProvider` or + * with no name. Under a provider it re-renders when its read's answer changes + * (objectstack#37903): a bundle landing, an app it does not hold, a world + * switch, never another metadata type landing. + */ export function useBundledItem(type: string, name: string | undefined | null, ownerPackageId?: unknown): BundledRead { - const reads = useBundledReads(); - return reads && name ? reads.item(type, name, ownerPackageId) : BUNDLE_MISS; + const stable = useContext(BundledReadsStoreCtx); + const store = useContext(MetadataStoreCtx); + const subscribed = stable !== null && store !== null; + // Without the provider's stable reads (a test that stands in for the + // provider), read the context as before. `use` reads it conditionally, so a + // reader under the provider never subscribes to its per-change value. + const legacy = subscribed ? null : use(BundledReadsCtx); + const subscribe = useCallback( + (listener: () => void) => (subscribed ? store.subscribe(listener, BUNDLE_STORE_KEYS) : NO_SUBSCRIBE()), + [subscribed, store], + ); + const lastRef = useRef | null>(null); + const getSnapshot = (): BundledRead => { + const reads = subscribed ? stable : legacy; + const next = reads && name ? reads.item(type, name, ownerPackageId) : BUNDLE_MISS; + const last = lastRef.current; + if (last && sameBundledRead(last, next)) return last; + lastRef.current = next; + return next; + }; + return useSyncExternalStore(subscribe, getSnapshot, getSnapshot); } /** diff --git a/ui/packages/react/src/context/AppShellContext.tsx b/ui/packages/react/src/context/AppShellContext.tsx index 0161fbad1b9..98a795dc364 100644 --- a/ui/packages/react/src/context/AppShellContext.tsx +++ b/ui/packages/react/src/context/AppShellContext.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, useEffect, useState } from 'react'; +import { createContext, use, useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react'; import type { DataSource } from '@object-ui/types'; // --------------------------------------------------------------------------- @@ -184,11 +184,158 @@ export function useMetadata(): MetadataContextValue { return ctx ?? NO_METADATA_PROVIDER; } +// --------------------------------------------------------------------------- +// MetadataStore — selector subscriptions (objectstack#37903) +// --------------------------------------------------------------------------- + +/** + * What a metadata provider publishes for readers that subscribe by selector + * instead of re-rendering with every change of {@link MetadataCtx}. + * + * `MetadataCtx`'s value is a new object each time the provider's cache + * changes, whatever changed, so every `useMetadata()` reader re-renders on + * every change: a reader of `dashboards` when the object list lands, a reader + * that only holds `getItem` when the app bundle lands. A store is ONE object + * for the provider's lifetime, published on {@link MetadataStoreCtx}; a reader + * of {@link useMetadataSelector} re-renders when its own selection changes. + * + * `useMetadata()` itself is unchanged: it still reads `MetadataCtx` and still + * re-renders on every change. Readers move to selectors family by family. + */ +export interface MetadataStore { + /** + * The value `useMetadata()` reads under the same provider, as of the + * provider's latest commit: the collections, the load flags and the same + * functions. + */ + getValue(): MetadataContextValue; + /** + * Calls `listener` after each provider commit that changed what the store + * answers. With `types`, only when one of those metadata types changed, or + * the whole store did (a preview or organization switch). Returns the + * unsubscribe. + */ + subscribe(listener: () => void, types?: readonly string[]): () => void; + /** + * How many times `type`'s answer has changed: its list landing, failing or + * being invalidated, and every change of the whole store. Diagnostic and + * test reading; a reader selects the answer itself. + */ + getRevision(type: string): number; +} + +/** + * The provider's {@link MetadataStore}, or `null` outside one. A host or test + * that puts a value into {@link MetadataCtx} by hand publishes no store, and + * the selector hooks then read that value, re-rendering with it as + * `useMetadata()` does. + */ +export const MetadataStoreCtx = createContext(null); + +const NO_STORE_SUBSCRIBE = (): (() => void) => () => {}; + +/** + * The last selection a reader made: the value it was read from, the selector + * it was read with, and what that selector answered. A cache only: a miss + * reads the value again, so nothing depends on these identities but speed. + */ +interface Selection { + source: MetadataContextValue; + select: unknown; + value: T; +} + +/** + * The subscription under {@link useMetadataSelector} and + * {@link useMetadataTypeSelection}. `types` narrows which store commits wake + * the reader; only a selection that reads exactly those types may narrow it. + */ +function useStoreSelection( + select: (metadata: MetadataContextValue) => T, + isEqual: ((a: T, b: T) => boolean) | undefined, + types: readonly string[] | undefined, +): T { + const store = useContext(MetadataStoreCtx); + // No store: read `MetadataCtx` as `useMetadata()` does. `use` reads a + // context conditionally, so a reader under a store never subscribes to + // `MetadataCtx`, whose value is new on every provider change. + const legacy = store ? null : (use(MetadataCtx) ?? NO_METADATA_PROVIDER); + // `types` is read through its joined key: a caller may pass a new array each render. + const typesKey = types ? types.join('\u0000') : null; + const typesRef = useRef(types); + typesRef.current = types; + const subscribe = useCallback( + (listener: () => void) => (store ? store.subscribe(listener, typesKey === null ? undefined : typesRef.current) : NO_STORE_SUBSCRIBE()), + [store, typesKey], + ); + const lastRef = useRef | null>(null); + const getSnapshot = (): T => { + const source = legacy ?? store!.getValue(); + const last = lastRef.current; + if (last && last.source === source && last.select === select) return last.value; + const next = select(source); + const value = last && (isEqual ? isEqual(last.value, next) : Object.is(last.value, next)) ? last.value : next; + lastRef.current = { source, select, value }; + return value; + }; + return useSyncExternalStore(subscribe, getSnapshot, getSnapshot); +} + +/** + * Read one answer out of the metadata store, re-rendering only when that + * answer changes (objectstack#37903). + * + * `select` is called with the value `useMetadata()` returns and may be a new + * function each render. Its result is compared with the previous one by + * `isEqual`, `Object.is` by default: a selector that builds a new array or + * object each call passes an `isEqual` that compares what it reads, or the + * reader re-renders on every store commit as a `useMetadata()` reader does. + * The functions on the value (`getItem`, `ensureType`, `refresh`, …) keep + * their identity across commits, so selecting one re-renders nothing. + * + * Outside a {@link MetadataStore} (no provider, or a hand-rolled + * `MetadataCtx` value), it reads that value and re-renders with it. + */ +export function useMetadataSelector( + select: (metadata: MetadataContextValue) => T, + isEqual?: (a: T, b: T) => boolean, +): T { + return useStoreSelection(select, isEqual, undefined); +} + +/** + * The items of one metadata type, re-rendering only when that type's list + * changes (objectstack#37903). The same list `getItemsByType(type)` returns, + * and like it, a first read of a type not yet asked starts its fetch. + */ +export function useMetadataTypeItems(type: string): any[] { + const select = useCallback((metadata: MetadataContextValue) => metadata.getItemsByType(type), [type]); + return useStoreSelection(select, undefined, [type]); +} + +/** + * The load status of one metadata type, re-rendering only when it changes + * (objectstack#37903). `'ready'` outside a provider that reports statuses, as + * `getTypeStatus` documents. The object registry answers once its views have + * too, so `'object'` also listens to `'view'`. + */ +export function useMetadataTypeStatus(type: string): MetadataTypeStatus { + const select = useCallback( + (metadata: MetadataContextValue): MetadataTypeStatus => metadata.getTypeStatus?.(type) ?? 'ready', + [type], + ); + return useStoreSelection(select, undefined, type === 'object' ? ['object', 'view'] : [type]); +} + +const selectGetItem = (metadata: MetadataContextValue) => metadata.getItem; + export function useMetadataItem( type: string, name: string | undefined | null, ): { item: any | null; loading: boolean; error: Error | null } { - const { getItem } = useMetadata(); + // The function alone: it keeps its identity across store commits, so this + // reader re-renders for its own state, not for every metadata change. + const getItem = useMetadataSelector(selectGetItem); const [state, setState] = useState<{ item: any | null; loading: boolean; error: Error | null }>({ item: null, loading: !!name, From 773edf9341f63db716e0fa1a4df9a5b905f6b92a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:22:38 +0000 Subject: [PATCH 2/4] test(app-shell): render-count harness and selector store pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyRPrFte1TGnaiugba --- ...adataProvider.selectorStore-37903.test.tsx | 219 ++++++++++++++++++ .../__tests__/metadataRenderCount.harness.tsx | 179 ++++++++++++++ .../useMetadataSelector-37903.test.tsx | 170 ++++++++++++++ 3 files changed, 568 insertions(+) create mode 100644 ui/packages/app-shell/src/providers/__tests__/MetadataProvider.selectorStore-37903.test.tsx create mode 100644 ui/packages/app-shell/src/providers/__tests__/metadataRenderCount.harness.tsx create mode 100644 ui/packages/react/src/context/__tests__/useMetadataSelector-37903.test.tsx diff --git a/ui/packages/app-shell/src/providers/__tests__/MetadataProvider.selectorStore-37903.test.tsx b/ui/packages/app-shell/src/providers/__tests__/MetadataProvider.selectorStore-37903.test.tsx new file mode 100644 index 00000000000..733e601cb41 --- /dev/null +++ b/ui/packages/app-shell/src/providers/__tests__/MetadataProvider.selectorStore-37903.test.tsx @@ -0,0 +1,219 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37903 — metadata readers subscribe by selector. + * + * ## What was measured + * + * `MetadataProvider` held one store-wide `version` counter and rebuilt its + * context value on every bump, so every `useMetadata()` reader re-rendered on + * every store change, whatever it read. Measured on main 7605e0c9: loading the + * `object` list re-rendered four memoised readers once each, though one read + * `apps`, one `dashboards`, one `pages` and one only held `getItem`. On a + * console list page the store bumps six times before the first paint + * (PR #37883's profile). + * + * ## What these pins hold, in both directions + * + * The provider publishes a store (`MetadataStoreCtx`) that records which + * types each bump changed and wakes selector readers after the commit: + * + * - A per-type reader (`useMetadataTypeItems`, `useMetadataTypeStatus`) does + * not re-render when another type lands, and does when its own type's list + * changes. + * - A `useMetadataSelector` reader re-renders when its selection changes and + * not when the store changes around it; a reader of a function re-renders + * on nothing. + * - `useMetadataType`, `useMetadataItem` and `useBundledItem` read through + * the store: an unrelated type landing does not re-render them; their own + * answer landing does. + * - LIVE CONTROL: a `useMetadata()` reader still re-renders on every store + * change. `useMetadata()` is unchanged by this card's first PR; a reader + * leaves that behaviour by moving to a selector. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { cleanup } from '@testing-library/react'; +import { useContext } from 'react'; +import { + MetadataStoreCtx, + useMetadata, + useMetadataItem, + useMetadataSelector, + useMetadataTypeItems, + useMetadataTypeStatus, + type MetadataStore, +} from '@object-ui/react'; +import { useMetadataType } from '../MetadataProvider'; +import { useBundledItem } from '../bundledReads'; +import { counted, drain, fakeBundle, mountReaders, renderCounts, servedLists } from './metadataRenderCount.harness'; + +const LISTS = { + app: [{ name: 's37903_app', label: 'App' }], + object: [{ name: 's37903_task', label: 'Task', fields: { title: { type: 'text' } } }], + view: [], + dashboard: [{ name: 's37903_home', label: 'Home' }], + page: [{ name: 's37903_page', type: 'record', object: 's37903_task' }], +}; + +afterEach(cleanup); + +describe('MetadataProvider store: per-type readers (objectstack#37903)', () => { + it('a reader of one type does not re-render when another type lands, and does when its own list changes', async () => { + const served = servedLists(LISTS); + const counts = renderCounts(); + const Dashboards = counted(counts, 'dashboards', () => useMetadataTypeItems('dashboard').length); + const m = mountReaders(served, ); + await m.settled(); + const settled = counts.of('dashboards'); + + await m.land('object'); + await m.land('page'); + expect(counts.of('dashboards')).toBe(settled); + + served.dashboard = [...served.dashboard, { name: 's37903_second', label: 'Second' }]; + await m.refetch('dashboard'); + expect(counts.of('dashboards')).toBe(settled + 1); + expect(m.ctx().dashboards).toHaveLength(2); + }); + + it('a status reader re-renders when its type settles, not when another type does', async () => { + const counts = renderCounts(); + const PageStatus = counted(counts, 'pageStatus', () => useMetadataTypeStatus('page')); + const m = mountReaders(servedLists(LISTS), ); + await m.settled(); + const settled = counts.of('pageStatus'); + expect(m.ctx().getTypeStatus!('page')).toBe('idle'); + + await m.land('dashboard'); + expect(counts.of('pageStatus')).toBe(settled); + + await m.land('page'); + expect(m.ctx().getTypeStatus!('page')).toBe('ready'); + expect(counts.of('pageStatus')).toBe(settled + 1); + }); +}); + +describe('MetadataProvider store: useMetadataSelector (objectstack#37903)', () => { + it('re-renders when its selection changes, not when the store changes around it', async () => { + const served = servedLists(LISTS); + const counts = renderCounts(); + const DashboardCount = counted(counts, 'dashboardCount', () => useMetadataSelector((metadata) => metadata.dashboards.length)); + const m = mountReaders(served, ); + await m.settled(); + const settled = counts.of('dashboardCount'); + + await m.land('object'); + await m.land('page'); + expect(counts.of('dashboardCount')).toBe(settled); + + served.dashboard = []; + await m.refetch('dashboard'); + expect(counts.of('dashboardCount')).toBe(settled + 1); + }); + + it('a reader of a function renders once and is woken by no store change', async () => { + const counts = renderCounts(); + const GetItem = counted(counts, 'getItem', () => { + void useMetadataSelector((metadata) => metadata.getItem); + return 'getItem'; + }); + const m = mountReaders(servedLists(LISTS), ); + await m.settled(); + await m.land('object'); + await m.land('dashboard'); + await m.land('page'); + expect(counts.of('getItem')).toBe(1); + }); + + it('an isEqual keeps a selection that builds a new array each read from re-rendering', async () => { + const counts = renderCounts(); + const sameNames = (a: string[], b: string[]) => a.length === b.length && a.every((n, i) => n === b[i]); + const Names = counted(counts, 'names', () => + useMetadataSelector((metadata) => metadata.apps.map((app: { name: string }) => app.name), sameNames).join(','), + ); + const m = mountReaders(servedLists(LISTS), ); + await m.settled(); + const settled = counts.of('names'); + await m.land('object'); + await m.land('dashboard'); + expect(counts.of('names')).toBe(settled); + }); +}); + +describe('MetadataProvider store: the hooks that read through it (objectstack#37903)', () => { + it('useMetadataType re-renders with its own type, not with another', async () => { + const served = servedLists(LISTS); + const counts = renderCounts(); + const Dashboards = counted(counts, 'type', () => useMetadataType('dashboard').items.length); + const m = mountReaders(served, ); + await m.settled(); + const settled = counts.of('type'); + await m.land('object'); + expect(counts.of('type')).toBe(settled); + served.dashboard = []; + await m.refetch('dashboard'); + expect(counts.of('type')).toBe(settled + 1); + }); + + it('useMetadataItem renders for its own read, not for the store changing around it', async () => { + const counts = renderCounts(); + const Item = counted(counts, 'item', () => useMetadataItem('object', 's37903_task').item?.name ?? 'none'); + const m = mountReaders(servedLists(LISTS), ); + await m.settled(); + const settled = counts.of('item'); + await m.land('dashboard'); + await m.land('page'); + expect(counts.of('item')).toBe(settled); + }); + + it('useBundledItem re-renders when the bundle lands, not when a type does', async () => { + const bundle = fakeBundle(); + const counts = renderCounts(); + const Bundled = counted(counts, 'bundled', () => useBundledItem('page', 's37903_page').state); + bundle.enter(); + const m = mountReaders(servedLists(LISTS), , bundle); + await m.settled(); + const pending = counts.of('bundled'); + expect(m.ctx()).toBeTruthy(); + + await m.land('dashboard'); + await m.land('object'); + expect(counts.of('bundled')).toBe(pending); + + await bundle.land({ page: LISTS.page }); + await drain(); + expect(counts.of('bundled')).toBe(pending + 1); + }); +}); + +describe('MetadataProvider store: revisions and the unchanged useMetadata() (objectstack#37903)', () => { + it('counts a revision per change of a type, and none for another type', async () => { + let store: MetadataStore | null = null; + function StoreProbe() { + store = useContext(MetadataStoreCtx); + return null; + } + const served = servedLists(LISTS); + const m = mountReaders(served, ); + await m.settled(); + expect(store).not.toBeNull(); + const objects = store!.getRevision('object'); + const dashboards = store!.getRevision('dashboard'); + + await m.land('dashboard'); + expect(store!.getRevision('dashboard')).toBe(dashboards + 1); + expect(store!.getRevision('object')).toBe(objects); + }); + + it('LIVE CONTROL: a useMetadata() reader still re-renders on every store change', async () => { + const counts = renderCounts(); + const Legacy = counted(counts, 'legacy', () => useMetadata().dashboards.length); + const m = mountReaders(servedLists(LISTS), ); + await m.settled(); + const settled = counts.of('legacy'); + await m.land('object'); + await m.land('page'); + expect(counts.of('legacy')).toBeGreaterThanOrEqual(settled + 2); + }); +}); diff --git a/ui/packages/app-shell/src/providers/__tests__/metadataRenderCount.harness.tsx b/ui/packages/app-shell/src/providers/__tests__/metadataRenderCount.harness.tsx new file mode 100644 index 00000000000..de8c236de5c --- /dev/null +++ b/ui/packages/app-shell/src/providers/__tests__/metadataRenderCount.harness.tsx @@ -0,0 +1,179 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37903 — the render-count harness for metadata readers. + * + * A reader family's pin mounts its readers under a real `MetadataProvider` + * whose adapter serves a fixed set of lists, then counts how many times each + * reader rendered across a store change: a type landing, a type refetched with + * a changed list, the app bundle landing. A reader that subscribes by + * selector renders once per change of what it reads; a `useMetadata()` reader + * renders once per store change, whatever it reads. Each counted reader is + * wrapped in `memo`, so a count measures the store's wake-ups and not its + * parent's renders. + * + * Usage: + * + * ```tsx + * const served = servedLists({ object: [...], dashboard: [...] }); + * const counts = renderCounts(); + * const Dashboards = counted(counts, 'dashboards', () => useMetadataTypeItems('dashboard').length); + * const m = mountReaders(served, ); + * await m.settled(); + * const before = counts.of('dashboards'); + * await m.land('object'); + * expect(counts.of('dashboards')).toBe(before); + * ``` + */ + +import { act, render } from '@testing-library/react'; +import { memo, type ReactNode } from 'react'; +import { useMetadata, type MetadataContextValue } from '@object-ui/react'; +import { MetadataProvider } from '../MetadataProvider'; + +type Doc = Record & { name: string }; + +/** The lists the adapter serves, by type; mutable, so a refetch can change one. */ +export type ServedLists = Record; + +/** A copy of `lists` the test may mutate between reads. */ +export function servedLists(lists: ServedLists): ServedLists { + return structuredClone(lists); +} + +/** The app bundle the adapter answers `peekAppBundle` with, as the real adapter does. */ +export interface FakeBundle { + state: + | { status: 'none' } + | { status: 'pending'; settled: Promise } + | { status: 'ready'; items: Map }>> }; + /** The app is entered: its bundle is on the wire. */ + enter(): void; + /** The bundle lands holding `docs`, by type. */ + land(docs: ServedLists): Promise; +} + +export function fakeBundle(): FakeBundle { + let resolve: () => void = () => {}; + const bundle: FakeBundle = { + state: { status: 'none' }, + enter() { + if (bundle.state.status !== 'none') return; + bundle.state = { status: 'pending', settled: new Promise((r) => { resolve = r; }) }; + }, + async land(docs) { + const items = new Map }>>(); + for (const [type, list] of Object.entries(docs)) { + const byName = new Map }>(); + for (const doc of list) byName.set(doc.name, { item: structuredClone(doc), envelope: { type, name: doc.name, item: doc } }); + items.set(type, byName); + } + bundle.state = { status: 'ready', items }; + resolve(); + await Promise.resolve(); + }, + }; + return bundle; +} + +/** An adapter that serves `served` as the network does: a new array per fetch. */ +export function servedAdapter(served: ServedLists, bundle?: FakeBundle) { + return { + clearCache: () => {}, + invalidateCache: () => {}, + ...(bundle ? { peekAppBundle: () => bundle.state } : {}), + getObjectSchema(name: string) { + const item = (served.object ?? []).find((o) => o.name === name); + return item ? Promise.resolve(structuredClone(item)) : Promise.reject(Object.assign(new Error('not found'), { httpStatus: 404 })); + }, + getClient: () => ({ + meta: { + getItems: (type: string) => Promise.resolve({ type, items: structuredClone(served[type] ?? []) }), + getItem: () => Promise.resolve({ item: null }), + }, + }), + } as unknown as Parameters[0]['adapter']; +} + +/** Render counts by reader name. */ +export interface RenderCounts { + of(name: string): number; + bump(name: string): void; +} + +export function renderCounts(): RenderCounts { + const counts = new Map(); + return { + of: (name) => counts.get(name) ?? 0, + bump: (name) => counts.set(name, (counts.get(name) ?? 0) + 1), + }; +} + +/** + * A memoised reader named `name` that renders `read()`'s answer and counts + * its renders. `read` is called as a hook, so it may call the metadata hooks. + */ +export function counted(counts: RenderCounts, name: string, read: () => unknown) { + const Reader = memo(function CountedReader() { + counts.bump(name); + const answer = read(); + return {typeof answer === 'string' || typeof answer === 'number' ? answer : JSON.stringify(answer ?? null)}; + }); + Reader.displayName = `Counted(${name})`; + return Reader; +} + +/** Let every queued fetch, microtask bump and commit run. */ +export async function drain(): Promise { + for (let i = 0; i < 5; i += 1) { + await act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + } +} + +export interface MountedReaders { + /** The provider's value, as a `useMetadata()` reader last read it. */ + ctx(): MetadataContextValue; + /** Load `type`'s list (a lazy type's first read) and let the commit run. */ + land(type: string): Promise; + /** Refetch `type`'s list from `served` (change it first) and let the commit run. */ + refetch(type: string): Promise; + /** Let boot settle: the eager types and every fetch their readers kicked. */ + settled(): Promise; +} + +/** Mount `readers` under a real provider over `served`, with a context probe beside them. */ +export function mountReaders(served: ServedLists, readers: ReactNode, bundle?: FakeBundle): MountedReaders { + let latest: MetadataContextValue | null = null; + function Probe() { + latest = useMetadata(); + return null; + } + render( + + + {readers} + , + ); + const ctx = () => { + if (!latest) throw new Error('the provider has not rendered'); + return latest; + }; + return { + ctx, + async land(type) { + await act(async () => { + await ctx().ensureType(type); + }); + await drain(); + }, + async refetch(type) { + await act(async () => { + await ctx().refresh(type); + }); + await drain(); + }, + settled: drain, + }; +} diff --git a/ui/packages/react/src/context/__tests__/useMetadataSelector-37903.test.tsx b/ui/packages/react/src/context/__tests__/useMetadataSelector-37903.test.tsx new file mode 100644 index 00000000000..619fe97da9d --- /dev/null +++ b/ui/packages/react/src/context/__tests__/useMetadataSelector-37903.test.tsx @@ -0,0 +1,170 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37903 — the selector hooks over a `MetadataStore`, without the + * app-shell provider: a hand-written store, a hand-rolled `MetadataCtx` value, + * and no provider at all. The provider's own store is pinned in app-shell + * (`MetadataProvider.selectorStore-37903.test.tsx`). + * + * - Under a store, a reader subscribes with the types its hook reads (none + * for `useMetadataSelector`, which compares its selection on every commit) + * and re-renders only when its selection changes. + * - Under a hand-rolled `MetadataCtx` value (no store), it reads that value + * and re-renders with it, as a `useMetadata()` reader does. + * - With no provider, it reads the no-provider fallback. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { act, cleanup, render } from '@testing-library/react'; +import { memo, useState, type ReactNode } from 'react'; +import { + MetadataCtx, + MetadataStoreCtx, + useMetadataSelector, + useMetadataTypeItems, + useMetadataTypeStatus, + type MetadataContextValue, + type MetadataStore, +} from '../AppShellContext'; + +afterEach(cleanup); + +function valueWith(lists: Record): MetadataContextValue { + return { + apps: lists.app ?? [], + objects: lists.object ?? [], + dashboards: lists.dashboard ?? [], + reports: [], + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: (type: string) => lists[type] ?? [], + getTypeStatus: (type: string) => (lists[type] ? 'ready' : 'idle'), + }; +} + +/** A store a test drives by hand: `commit(next, types)` is one provider commit. */ +function handStore(initial: MetadataContextValue) { + let value = initial; + const subscriptions: Array<{ listener: () => void; types: readonly string[] | undefined }> = []; + const store: MetadataStore = { + getValue: () => value, + subscribe(listener, types) { + const entry = { listener, types }; + subscriptions.push(entry); + return () => { + subscriptions.splice(subscriptions.indexOf(entry), 1); + }; + }, + getRevision: () => 0, + }; + return { + store, + subscriptions, + commit(next: MetadataContextValue, types?: readonly string[]) { + value = next; + act(() => { + for (const s of [...subscriptions]) { + if (!types || !s.types || s.types.some((t) => types.includes(t))) s.listener(); + } + }); + }, + }; +} + +describe('selector hooks under a MetadataStore (objectstack#37903)', () => { + it('each hook subscribes with the types it reads', () => { + const hand = handStore(valueWith({ dashboard: [] })); + function Readers() { + useMetadataSelector((m) => m.apps.length); + useMetadataTypeItems('dashboard'); + useMetadataTypeStatus('object'); + useMetadataTypeStatus('page'); + return null; + } + render( + + + , + ); + expect(hand.subscriptions.map((s) => s.types?.join('+') ?? 'every commit').sort()).toEqual( + ['dashboard', 'every commit', 'object+view', 'page'].sort(), + ); + }); + + it('re-renders when its selection changes and keeps its render when it does not', () => { + const hand = handStore(valueWith({ dashboard: [{ name: 'a' }] })); + let renders = 0; + const Reader = memo(function Reader() { + renders += 1; + return {useMetadataSelector((m) => m.dashboards.length)}; + }); + render( + + + , + ); + expect(renders).toBe(1); + // Another type changed: same selection. + hand.commit(valueWith({ dashboard: [{ name: 'a' }], object: [{ name: 'o' }] })); + expect(renders).toBe(1); + hand.commit(valueWith({ dashboard: [{ name: 'a' }, { name: 'b' }] })); + expect(renders).toBe(2); + }); + + it('a per-type reader is not woken by a commit of another type, and is by its own', () => { + const dashboards = [{ name: 'a' }]; + const hand = handStore(valueWith({ dashboard: dashboards })); + let renders = 0; + const Reader = memo(function Reader() { + renders += 1; + return {useMetadataTypeItems('dashboard').length}; + }); + render( + + + , + ); + hand.commit(valueWith({ dashboard: dashboards, object: [{ name: 'o' }] }), ['object']); + expect(renders).toBe(1); + hand.commit(valueWith({ dashboard: [...dashboards, { name: 'b' }] }), ['dashboard']); + expect(renders).toBe(2); + }); +}); + +describe('selector hooks without a store (objectstack#37903)', () => { + it('read a hand-rolled MetadataCtx value and re-render with it', () => { + let setValue: (v: MetadataContextValue) => void = () => {}; + function Host({ children }: { children: ReactNode }) { + const [value, set] = useState(() => valueWith({ dashboard: [{ name: 'a' }] })); + setValue = set; + return {children}; + } + function Reader() { + return {useMetadataTypeItems('dashboard').length}; + } + const { getByTestId } = render( + + + , + ); + expect(getByTestId('n').textContent).toBe('1'); + act(() => setValue(valueWith({ dashboard: [{ name: 'a' }, { name: 'b' }] }))); + expect(getByTestId('n').textContent).toBe('2'); + }); + + it('read the no-provider fallback outside any provider', () => { + function Reader() { + const items = useMetadataTypeItems('dashboard'); + const status = useMetadataTypeStatus('dashboard'); + const loading = useMetadataSelector((m) => m.loading); + return {`${items.length}/${status}/${String(loading)}`}; + } + const { getByTestId } = render(); + expect(getByTestId('r').textContent).toBe('0/ready/false'); + }); +}); From b9202f7f1c594e797020f334da1bdfd505d58447 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:26:40 +0000 Subject: [PATCH 3/4] refactor(react): subscribe by joined type key, no ref written in render Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyRPrFte1TGnaiugba --- ui/packages/app-shell/src/providers/bundledReads.ts | 2 +- ui/packages/react/src/context/AppShellContext.tsx | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/ui/packages/app-shell/src/providers/bundledReads.ts b/ui/packages/app-shell/src/providers/bundledReads.ts index e4ba53bd1d9..422cad7dfed 100644 --- a/ui/packages/app-shell/src/providers/bundledReads.ts +++ b/ui/packages/app-shell/src/providers/bundledReads.ts @@ -81,7 +81,7 @@ const BUNDLE_STORE_KEYS: readonly string[] = [BUNDLE_STORE_KEY]; const NO_SUBSCRIBE = (): (() => void) => () => {}; /** The same answer: the same state, and for a hit, the same item. */ -function sameBundledRead(a: BundledRead, b: BundledRead): boolean { +function sameBundledRead(a: BundledRead, b: BundledRead): boolean { if (a.state !== b.state) return false; return a.state !== 'hit' || (b.state === 'hit' && Object.is(a.value, b.value)); } diff --git a/ui/packages/react/src/context/AppShellContext.tsx b/ui/packages/react/src/context/AppShellContext.tsx index 98a795dc364..0e5819ec2f4 100644 --- a/ui/packages/react/src/context/AppShellContext.tsx +++ b/ui/packages/react/src/context/AppShellContext.tsx @@ -233,6 +233,8 @@ export interface MetadataStore { export const MetadataStoreCtx = createContext(null); const NO_STORE_SUBSCRIBE = (): (() => void) => () => {}; +/** Joins a reader's types into one dependency; no metadata type name holds it. */ +const TYPES_SEPARATOR = '\u0000'; /** * The last selection a reader made: the value it was read from, the selector @@ -261,11 +263,10 @@ function useStoreSelection( // `MetadataCtx`, whose value is new on every provider change. const legacy = store ? null : (use(MetadataCtx) ?? NO_METADATA_PROVIDER); // `types` is read through its joined key: a caller may pass a new array each render. - const typesKey = types ? types.join('\u0000') : null; - const typesRef = useRef(types); - typesRef.current = types; + const typesKey = types ? types.join(TYPES_SEPARATOR) : null; const subscribe = useCallback( - (listener: () => void) => (store ? store.subscribe(listener, typesKey === null ? undefined : typesRef.current) : NO_STORE_SUBSCRIBE()), + (listener: () => void) => + store ? store.subscribe(listener, typesKey === null ? undefined : typesKey.split(TYPES_SEPARATOR)) : NO_STORE_SUBSCRIBE(), [store, typesKey], ); const lastRef = useRef | null>(null); From e6c912cca40c2cc2fa2d666b7416d26b76469499 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:28:15 +0000 Subject: [PATCH 4/4] chore(changeset): metadata selector store Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibyRPrFte1TGnaiugba --- .changeset/37903-metadata-selector-store.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .changeset/37903-metadata-selector-store.md diff --git a/.changeset/37903-metadata-selector-store.md b/.changeset/37903-metadata-selector-store.md new file mode 100644 index 00000000000..60c079d5fb1 --- /dev/null +++ b/.changeset/37903-metadata-selector-store.md @@ -0,0 +1,19 @@ +--- +'@object-ui/react': patch +'@object-ui/app-shell': patch +--- + +feat(react): metadata readers can subscribe by selector — `useMetadataSelector`, `useMetadataTypeItems`, `useMetadataTypeStatus` and the `MetadataStoreCtx` store + +Clause-②: yes (widening) +Metadata-protocol: none + +`MetadataProvider` rebuilt its context value on every change of its cache, so every `useMetadata()` reader re-rendered on every change, whatever it read: a reader of `dashboards` when the object list landed, a reader that only holds `getItem` when the app bundle landed. The provider now also publishes a store on the new `MetadataStoreCtx` (one object for the provider's lifetime, typed `MetadataStore`) that records which metadata types each change touched and wakes its readers after the provider's commit. Three new hooks in `@object-ui/react` read it: + +- `useMetadataSelector(select, isEqual?)` returns `select(metadata)` and re-renders only when that answer changes (`Object.is` by default; pass `isEqual` for a selector that builds a new array or object each read). +- `useMetadataTypeItems(type)` returns `getItemsByType(type)` and re-renders only when that type's list changes. +- `useMetadataTypeStatus(type)` returns `getTypeStatus(type)` and re-renders only when it changes. + +`useMetadataItem` (`@object-ui/react`), and `useMetadataType` and `useBundledItem` (`@object-ui/app-shell`), now read through the store: an unrelated type landing no longer re-renders their readers. Outside a provider, or under a hand-written `MetadataCtx` value with no store, the hooks read that value and re-render with it, as `useMetadata()` does. + +Nothing else changes: `useMetadata()` still re-renders on every store change, and what any hook returns is unchanged.