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
19 changes: 19 additions & 0 deletions .changeset/37903-metadata-selector-store.md
Original file line number Diff line number Diff line change
@@ -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.
187 changes: 164 additions & 23 deletions ui/packages/app-shell/src/providers/MetadataProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
useCallback,
useRef,
useMemo,
useLayoutEffect,
type ReactNode,
} from 'react';
import { expandViewContainer } from '@objectstack/spec/ui';
Expand All @@ -22,22 +23,28 @@ import { resolveInlineMode } from '@object-ui/plugin-form/core';
import { fieldGroupsPlaceRelationship, isGroupPlaceableRelationship } from '@objectstack/spec/data';
import {
MetadataCtx,
MetadataStoreCtx,
answeredLoadFailure,
classifyLoadError,
useMetadata,
type AnsweredLoadFailure,
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';
import { subscribeCanvasInvalidate, subscribeMetadataRefresh } from '../assistant/assistantBus.js';
import {
BUNDLE_MISS,
BUNDLE_PENDING,
BUNDLE_STORE_KEY,
BundledReadsCtx,
BundledReadsStoreCtx,
type BundledRead,
type BundledReads,
} from './bundledReads.js';
Expand Down Expand Up @@ -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<string, number>();
let pendingWhole = false;
const pending = new Set<string>();
const listeners = new Set<StoreListener>();
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<Map<string, TypeCacheEntry>>(new Map());
const itemPromisesRef = useRef<Map<string, ItemPromiseMap>>(new Map());
Expand Down Expand Up @@ -1104,18 +1193,27 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }:
const answeredBundleRef = useRef<AppBundleItems | null>(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<ProviderStore | null>(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 ───────────────────
//
Expand Down Expand Up @@ -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;
Expand All @@ -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<any> => {
Expand Down Expand Up @@ -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<readonly string[]> => {
Expand Down Expand Up @@ -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) => {
Expand All @@ -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[];
});

Expand Down Expand Up @@ -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],
Expand All @@ -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');
Expand All @@ -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],
Expand Down Expand Up @@ -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;
Expand All @@ -1611,7 +1710,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }:
else delete answers[name];
}
entry.answers = answers;
bump();
bump(SCOPE_KEYS);
},
);
},
Expand Down Expand Up @@ -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],
);
Expand Down Expand Up @@ -1872,7 +1971,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }:
entry.byName.set(it.name, it);
}
}
bump();
bump(['app']);
setInitialLoading(false);
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<BundledReads>(() => {
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<BundledReads | null>(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 (
<MetadataCtx.Provider value={value}>
<BundledReadsCtx.Provider value={bundledReads}>{children}</BundledReadsCtx.Provider>
</MetadataCtx.Provider>
<MetadataStoreCtx.Provider value={store}>
<MetadataCtx.Provider value={value}>
<BundledReadsStoreCtx.Provider value={stableBundledReadsRef.current}>
<BundledReadsCtx.Provider value={bundledReads}>{children}</BundledReadsCtx.Provider>
</BundledReadsStoreCtx.Provider>
</MetadataCtx.Provider>
</MetadataStoreCtx.Provider>
);
}

/**
* 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;
Loading
Loading