Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(soup): use urql solid library for graphql path (#5349)

dev-rb1d3c88349ae2
diff --git a/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts b/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts
new file mode 100644
index 0000000000..765e52892f
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/create-graphql-grouped-soup-queries.ts
@@ -0,0 +1,304 @@
+import { createUrqlInfiniteQuery } from '@app/lib/urql-solid';
+import type { EntityData } from '@entity';
+import {
+ makeGraphqlGroupedSoupContinuationInput,
+ makeGraphqlGroupedSoupInput,
+} from '@queries/soup/graphql-ast';
+import { registerGroupedSoupContinuation } from '@queries/soup/grouped/graphql-operation-registry';
+import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';
+import type {
+ SoupApiItemFilter,
+ SoupAstBody,
+ SoupAstItemsGroupedPage,
+ SoupParams,
+} from '@queries/soup/items';
+import {
+ isDisplayableSoupItem,
+ isInstructionsMdDoc,
+ mapApiSoupItemToEntity,
+} from '@queries/soup/transform-utils';
+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
+import {
+ type GroupedSoupInput,
+ GroupSoupDocument,
+ type GroupSoupQuery,
+ type GroupSoupQueryVariables,
+} from '@service-storage/graphql/generated/graphql';
+import {
+ getGraphqlSoupClient,
+ mapGraphqlGroupedSoupPage,
+} from '@service-storage/graphql-soup';
+import {
+ type Accessor,
+ createComputed,
+ createMemo,
+ createRoot,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
+
+export type GroupQueryData = {
+ entities: EntityData[];
+};
+
+type GraphqlGroupConfig = {
+ key: string;
+ group: GroupMeta;
+ field: GroupByField;
+ initialInput: GroupedSoupInput;
+ enabled: boolean;
+ itemFilter: SoupApiItemFilter | undefined;
+};
+
+type GraphqlGroupQuery = {
+ key: string;
+ data: Accessor<GroupQueryData | undefined>;
+ hasNextPage: Accessor<boolean>;
+ isFetchingNextPage: Accessor<boolean>;
+ fetchNextPage: () => Promise<void>;
+ resetToInitialPage: () => void;
+ dispose: () => void;
+};
+
+type GraphqlGroupedInitialPage = {
+ items: SoupAstItemsGroupedPage['items'];
+ groups: GroupMeta[];
+};
+
+type CreateGraphqlGroupedSoupQueriesArgs = {
+ initialPage: Accessor<GraphqlGroupedInitialPage | undefined>;
+ groupByField: Accessor<GroupByField | undefined>;
+ soupParams: Accessor<
+ Omit<SoupParams, 'sort_method'> & {
+ sort_method: Exclude<SoupParams['sort_method'], 'frecency'>;
+ }
+ >;
+ soupBody: Accessor<SoupAstBody>;
+ enabled: Accessor<boolean>;
+ itemFilter: Accessor<SoupApiItemFilter | undefined>;
+};
+
+function groupPage(
+ data: GroupSoupQuery,
+ group: GroupMeta
+):
+ | {
+ items: ReturnType<typeof mapGraphqlGroupedSoupPage>['items'];
+ group: GroupMeta;
+ }
+ | undefined {
+ const page = mapGraphqlGroupedSoupPage(data);
+ const bin = page.groups.find((candidate) => candidate.key === group.key);
+ if (!bin) return;
+ return {
+ items: page.items,
+ group: {
+ ...group,
+ totalCount: bin.totalCount,
+ itemIds: bin.itemIds,
+ nextCursor: bin.nextCursor,
+ },
+ };
+}
+
+/** Creates live initial and continuation GroupSoup observers for visible bins. */
+export function createGraphqlGroupedSoupQueries(
+ args: CreateGraphqlGroupedSoupQueriesArgs
+): {
+ list: Accessor<GraphqlGroupQuery[]>;
+ map: Accessor<Map<string, GraphqlGroupQuery>>;
+ resetToInitialPage: () => void;
+} {
+ const instructionsIdQuery = useInstructionsMdIdQuery();
+
+ const mapItems = (
+ items: SoupAstItemsGroupedPage['items'],
+ itemIds: readonly string[],
+ itemFilter: SoupApiItemFilter | undefined
+ ): EntityData[] =>
+ itemIds.flatMap((id) => {
+ const item = items[id];
+ if (!item || !isDisplayableSoupItem(item)) return [];
+ if (itemFilter && !itemFilter(item)) return [];
+ if (isInstructionsMdDoc(item, instructionsIdQuery)) return [];
+ return [mapApiSoupItemToEntity(item)];
+ });
+
+ const configs = createMemo<GraphqlGroupConfig[]>(() => {
+ const field = args.groupByField();
+ const initialPage = args.initialPage();
+ if (!field || !initialPage) return [];
+
+ let initialInput: GroupedSoupInput;
+ try {
+ initialInput = makeGraphqlGroupedSoupInput({
+ params: args.soupParams(),
+ body: args.soupBody(),
+ groupBy: field,
+ });
+ } catch {
+ return [];
+ }
+
+ const enabled = args.enabled();
+ const itemFilter = args.itemFilter();
+ return initialPage.groups.map((group) => ({
+ key: group.key,
+ group,
+ field,
+ initialInput,
+ enabled,
+ itemFilter,
+ }));
+ });
+
+ const queryByKey = new Map<string, GraphqlGroupQuery>();
+ const [revision, setRevision] = createSignal(0);
+
+ const createGroupQuery = (
+ key: string,
+ initialConfig: GraphqlGroupConfig
+ ): GraphqlGroupQuery => {
+ let dispose: (() => void) | undefined;
+
+ const queryResult = createRoot((rootDispose) => {
+ dispose = rootDispose;
+ const getConfig = createMemo(
+ () => configs().find((config) => config.key === key) ?? initialConfig
+ );
+
+ const query = createUrqlInfiniteQuery<
+ GroupSoupQuery,
+ GroupSoupQueryVariables,
+ string | null,
+ GroupQueryData
+ >(() => {
+ const config = getConfig();
+ return {
+ query: GroupSoupDocument,
+ client: getGraphqlSoupClient(),
+ initialPageParam: null,
+ variables: (cursor) => {
+ if (cursor === null) return { input: config.initialInput };
+ const input = makeGraphqlGroupedSoupContinuationInput({
+ groupBy: config.field,
+ groupKey: config.key,
+ cursor,
+ });
+ registerGroupedSoupContinuation(config.initialInput, input);
+ return { input };
+ },
+ getNextPageParam: (lastPage) =>
+ groupPage(lastPage, config.group)?.group.nextCursor,
+ select: ({ pages }) => ({
+ entities: pages.flatMap((page) => {
+ const selected = groupPage(page, config.group);
+ return selected
+ ? mapItems(
+ selected.items,
+ selected.group.itemIds,
+ config.itemFilter
+ )
+ : [];
+ }),
+ }),
+ enabled: config.enabled,
+ requestPolicy: 'cache-first',
+ keepPreviousData: false,
+ };
+ });
+
+ const initialData = (): GroupQueryData | undefined => {
+ const config = getConfig();
+ const initialPage = args.initialPage();
+ if (!initialPage) return;
+ const group = initialPage.groups.find(
+ (candidate) => candidate.key === config.key
+ );
+ if (!group) return;
+ return {
+ entities: mapItems(
+ initialPage.items,
+ group.itemIds,
+ config.itemFilter
+ ),
+ };
+ };
+
+ return {
+ key,
+ data: () => query.data ?? initialData(),
+ hasNextPage: () =>
+ query.data === undefined
+ ? (getConfig().group.nextCursor ?? null) !== null
+ : query.hasNextPage,
+ isFetchingNextPage: () => query.isFetchingNextPage,
+ fetchNextPage: async () => {
+ if (query.data === undefined) await query.refetch();
+ await query.fetchNextPage();
+ },
+ resetToInitialPage: query.resetToInitialPage,
+ };
+ });
+
+ return {
+ ...queryResult,
+ dispose: () => dispose?.(),
+ };
+ };
+
+ createComputed(
+ on(
+ () => configs().map((config) => config.key),
+ (keys) => {
+ const activeKeys = new Set(keys);
+ let changed = false;
+
+ for (const [key, query] of queryByKey) {
+ if (activeKeys.has(key)) continue;
+ query.dispose();
+ queryByKey.delete(key);
+ changed = true;
+ }
+
+ for (const key of keys) {
+ if (queryByKey.has(key)) continue;
+ const config = configs().find((candidate) => candidate.key === key);
+ if (!config) continue;
+ queryByKey.set(key, createGroupQuery(key, config));
+ changed = true;
+ }
+
+ if (changed) setRevision((value) => value + 1);
+ }
+ )
+ );
+
+ onCleanup(() => {
+ for (const query of queryByKey.values()) query.dispose();
+ queryByKey.clear();
+ });
+
+ const list = createMemo(() => {
+ revision();
+ return configs().flatMap((config) => {
+ const query = queryByKey.get(config.key);
+ return query ? [query] : [];
+ });
+ });
+ const map = createMemo(() =>
+ list().reduce((queries, query) => {
+ queries.set(query.key, query);
+ return queries;
+ }, new Map<string, GraphqlGroupQuery>())
+ );
+
+ return {
+ list,
+ map,
+ resetToInitialPage: () => {
+ for (const query of list()) query.resetToInitialPage();
+ },
+ };
+}
diff --git a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts b/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
index f14bdb4bad..3ee9d37f1e 100644
--- a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
+++ b/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
@@ -1,17 +1,13 @@
+import { createGraphqlGroupedSoupQueries } from '@app/features/next-soup/soup-view/create-graphql-grouped-soup-queries';
import { createInfiniteQueries } from '@app/features/next-soup/soup-view/create-infinite-queries';
import { throwOnErr } from '@core/util/result';
import type { EntityData } from '@entity';
import { useQueryClient } from '@queries/client';
import { groupedCacheVersion } from '@queries/soup/cache';
-import {
- makeGraphqlGroupedSoupContinuationInput,
- makeGraphqlGroupedSoupInput,
-} from '@queries/soup/graphql-ast';
import {
parseGroupMeta,
serializeGroupByField,
} from '@queries/soup/grouped/api';
-import { registerGroupedSoupContinuation } from '@queries/soup/grouped/graphql-operation-registry';
import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';
import type {
SoupApiItemFilter,
@@ -28,7 +24,6 @@ import {
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import { storageServiceClient } from '@service-storage/client';
import type { SoupApiItem } from '@service-storage/generated/schemas';
-import { fetchGraphqlGroupedSoup } from '@service-storage/graphql-soup';
import type { InfiniteData } from '@tanstack/solid-query';
import {
type Accessor,
@@ -63,7 +58,8 @@ type CreateGroupedSoupQueriesArgs = {
}
>;
soupBody: Accessor<SoupAstBody>;
- transport: Accessor<'rest' | 'graphql' | undefined>;
+ /** True only when the live GraphQL grouped parent query owns the view. */
+ graphqlReactive: Accessor<boolean>;
queryOptions: Accessor<{
enabled?: boolean;
meta?: {
@@ -130,7 +126,7 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
const field = args.groupByField();
const initialGroupedPage = args.initialPage();
- if (!field || !initialGroupedPage) {
+ if (args.graphqlReactive() || !field || !initialGroupedPage) {
return [];
}
@@ -152,53 +148,6 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
return initialPage;
}
- if (args.transport() === 'graphql') {
- const continuationInput = makeGraphqlGroupedSoupContinuationInput({
- groupBy: field,
- groupKey: group.key,
- cursor: ctx.pageParam,
- });
- registerGroupedSoupContinuation(
- makeGraphqlGroupedSoupInput({
- params: args.soupParams(),
- body: args.soupBody(),
- groupBy: field,
- }),
- continuationInput
- );
- const response = await fetchGraphqlGroupedSoup(continuationInput);
- const nextGroup = response.groups.find(
- (candidate) => candidate.key === group.key
- );
- if (!nextGroup) {
- if (response.groups.length > 0) {
- throw new Error(
- `GraphQL grouped Soup continuation omitted bin ${group.key}`
- );
- }
-
- // The group may have been exhausted by concurrent deletes
- // between pages. Treat an empty response as a terminal page.
- return {
- items: {},
- group: {
- ...group,
- itemIds: [],
- nextCursor: null,
- },
- };
- }
-
- return {
- items: response.items,
- group: {
- ...group,
- itemIds: nextGroup.itemIds,
- nextCursor: nextGroup.nextCursor,
- },
- };
- }
-
const response = await throwOnErr(async () =>
storageServiceClient.getGroupedSoupAstGroupPage({
params: {
@@ -242,11 +191,22 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
GroupQueryPage,
GroupQueryData | undefined
>(configs);
+ const graphqlQueries = createGraphqlGroupedSoupQueries({
+ initialPage: args.initialPage,
+ groupByField: args.groupByField,
+ soupParams: args.soupParams,
+ soupBody: args.soupBody,
+ enabled: () =>
+ args.graphqlReactive() && args.queryOptions().enabled === true,
+ itemFilter: () => args.queryOptions().meta?.itemFilter,
+ });
const [groupDataVersion, setGroupDataVersion] = createSignal(0);
- const list = createMemo(() =>
- queries.list().map((query) => ({
+ const list = createMemo(() => {
+ if (args.graphqlReactive()) return graphqlQueries.list();
+
+ return queries.list().map((query) => ({
...query,
data: () => {
groupDataVersion();
@@ -260,8 +220,8 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
setGroupDataVersion((version) => version + 1);
return result;
},
- }))
- );
+ }));
+ });
const map = createMemo(() => {
const next = new Map<string, ReturnType<typeof list>[number]>();
@@ -276,7 +236,7 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
() => args.initialPage(),
(initialGroupedPage) => {
const field = args.groupByField();
- if (!field || !initialGroupedPage) return;
+ if (args.graphqlReactive() || !field || !initialGroupedPage) return;
batch(() => {
for (const group of initialGroupedPage.groups) {
@@ -307,5 +267,8 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
...queries,
list,
map,
+ resetToInitialPage: () => {
+ if (args.graphqlReactive()) graphqlQueries.resetToInitialPage();
+ },
};
}
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
index d5063844f5..10fe23dd54 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx
@@ -77,6 +77,7 @@ import type {
import type { SoupParams } from '@queries/soup/items';
import { useSoupAstItemsQuery } from '@queries/soup/items';
import { soupKeys } from '@queries/soup/keys';
+import { useReactiveGroupedSoupAstItemsQuery } from '@queries/soup/reactive-grouped-items';
import { useReactiveSoupAstItemsQuery } from '@queries/soup/reactive-items';
import { mapApiSoupItemToEntity } from '@queries/soup/transform-utils';
import type { SoupApiItem, SoupPage } from '@service-storage/generated/schemas';
@@ -297,9 +298,6 @@ export const SoupViewContextProvider: FlowComponent<
const useGraphqlSoupFF = useFeatureFlag(ENABLE_GRAPHQL_SOUP_FLAG, {
enabledOverride: ENABLE_GRAPHQL_SOUP_OVERRIDE,
});
- const resolveTransport = () =>
- useGraphqlSoupFF().enabled ? 'graphql' : undefined;
-
const panel = useSplitPanelOrThrow();
const activeListView = createMemo<ListView | undefined>(() => {
@@ -380,19 +378,19 @@ export const SoupViewContextProvider: FlowComponent<
);
onCleanup(predicatesCaptorTeardown);
- const trimToFirstPage = () => {
+ const resetToInitialPage = () => {
const groupBy = serverGroupByField();
- // Reactive urql path keeps its own page list (no-op when inactive or
- // already on one page). Defined below; only invoked at runtime.
- reactiveItemsQuery.trimToFirstPage();
+ reactiveItemsQuery.resetToInitialPage();
+ reactiveGroupedItemsQuery.resetToInitialPage();
+ groupQueries.resetToInitialPage();
queryClient.setQueryData(
soupKeys.astItems({
params: soupParams(),
body: soupBody(),
groupBy,
- transport: resolveTransport(),
+ transport: reactiveActive() ? 'graphql' : undefined,
}).queryKey,
(prev: InfiniteData<SoupPage> | SoupPage | undefined) => {
if (!prev) return;
@@ -440,22 +438,22 @@ export const SoupViewContextProvider: FlowComponent<
const queryFilters: QueryStore = {
...store,
set: (query) => {
- trimToFirstPage();
+ resetToInitialPage();
store.set(query);
persistQueryFilters();
},
replace: (query) => {
- trimToFirstPage();
+ resetToInitialPage();
store.replace(query);
persistQueryFilters();
},
add: (query) => {
- trimToFirstPage();
+ resetToInitialPage();
store.add(query);
persistQueryFilters();
},
remove: (query) => {
- trimToFirstPage();
+ resetToInitialPage();
store.remove(query);
persistQueryFilters();
},
@@ -942,23 +940,49 @@ export const SoupViewContextProvider: FlowComponent<
};
// Reactive urql path (same `enable-graphql-soup` flag as the transport):
- // the flat soup list subscribes to the GraphQL query directly, so
- // normalized-cache pushes (optimistic property writes, sibling writes,
- // other tabs) re-render without a TanStack invalidation round-trip.
- // Grouped views and ASTs without a GraphQL translation stay on TanStack.
- const reactiveEligible = () =>
- useGraphqlSoupFF().enabled && !serverGroupByField();
+ // flat and server-grouped GraphQL views retain live operation sources, so
+ // normalized-cache pushes update every loaded page directly. Unsupported
+ // ASTs and REST transport continue through the TanStack fallback.
+ const reactiveEligible = () => useGraphqlSoupFF().enabled;
const reactiveItemsQuery = useReactiveSoupAstItemsQuery(
() => ({ params: soupParams(), body: soupBody() }),
() => ({
- enabled: enabled() && !search.isSearching() && reactiveEligible(),
+ enabled:
+ enabled() &&
+ !search.isSearching() &&
+ reactiveEligible() &&
+ !serverGroupByField(),
+ showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,
+ })
+ );
+ const reactiveGroupedItemsQuery = useReactiveGroupedSoupAstItemsQuery(
+ () => ({
+ params: soupParams(),
+ body: soupBody(),
+ groupBy: serverGroupByField(),
+ }),
+ () => ({
+ enabled:
+ enabled() &&
+ !search.isSearching() &&
+ reactiveEligible() &&
+ serverGroupByField() !== undefined,
showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,
})
);
- const reactiveActive = () =>
- reactiveEligible() && reactiveItemsQuery.isSupported();
+ const reactiveFlatActive = () =>
+ reactiveEligible() &&
+ !serverGroupByField() &&
+ reactiveItemsQuery.isSupported();
+ const reactiveGroupedActive = () =>
+ reactiveEligible() &&
+ serverGroupByField() !== undefined &&
+ reactiveGroupedItemsQuery.isSupported();
+ const reactiveActive = () => reactiveFlatActive() || reactiveGroupedActive();
+ const activeReactiveItemsQuery = () =>
+ reactiveGroupedActive() ? reactiveGroupedItemsQuery : reactiveItemsQuery;
const itemsQuery = useSoupAstItemsQuery(
() => {
@@ -967,7 +991,7 @@ export const SoupViewContextProvider: FlowComponent<
params: soupParams(),
body: soupBody(),
groupBy,
- transport: resolveTransport(),
+ transport: reactiveActive() ? 'graphql' : undefined,
};
},
() => {
@@ -989,25 +1013,23 @@ export const SoupViewContextProvider: FlowComponent<
const itemsQueryData = () =>
itemsQuery.isLoading ? undefined : itemsQuery.data;
- /**
- * Unified soup items surface: the reactive urql query when active, the
- * TanStack infinite query otherwise. Grouped data (`groups`/`itemsById`)
- * only ever comes from the TanStack side — grouping is never reactive.
- */
+ /** Unified reactive-GraphQL or TanStack fallback Soup surface. */
const itemsSource = {
data: () =>
- reactiveActive() ? reactiveItemsQuery.data() : itemsQueryData(),
+ reactiveActive() ? activeReactiveItemsQuery().data() : itemsQueryData(),
isLoading: () =>
- reactiveActive() ? reactiveItemsQuery.isLoading() : itemsQuery.isLoading,
+ reactiveActive()
+ ? activeReactiveItemsQuery().isLoading()
+ : itemsQuery.isLoading,
isFetching: () =>
reactiveActive()
- ? reactiveItemsQuery.isFetching()
+ ? activeReactiveItemsQuery().isFetching()
: itemsQuery.isFetching,
isPlaceholderData: () =>
reactiveActive() ? false : itemsQuery.isPlaceholderData,
isFetchingNextPage: () =>
reactiveActive()
- ? reactiveItemsQuery.isFetchingNextPage()
+ ? activeReactiveItemsQuery().isFetchingNextPage()
: itemsQuery.isFetchingNextPage,
isEnabled: () =>
reactiveActive()
@@ -1015,11 +1037,11 @@ export const SoupViewContextProvider: FlowComponent<
: itemsQuery.isEnabled,
hasNextPage: () =>
reactiveActive()
- ? reactiveItemsQuery.hasNextPage()
+ ? activeReactiveItemsQuery().hasNextPage()
: itemsQuery.hasNextPage,
fetchNextPage: () => {
if (reactiveActive()) {
- reactiveItemsQuery.fetchNextPage();
+ activeReactiveItemsQuery().fetchNextPage();
} else {
itemsQuery.fetchNextPage();
}
@@ -1133,17 +1155,17 @@ export const SoupViewContextProvider: FlowComponent<
const groupQueries = createGroupedSoupQueries({
initialPage: createMemo(() => {
- if (itemsQuery.isPlaceholderData) return;
+ if (itemsSource.isPlaceholderData()) return;
- const groups = itemsQueryData()?.groups;
- const items = itemsQueryData()?.itemsById;
+ const groups = itemsSource.data()?.groups;
+ const items = itemsSource.data()?.itemsById;
if (!groups || !items) return;
return { groups, items };
}),
groupByField: serverGroupByField,
soupParams,
soupBody,
- transport: resolveTransport,
+ graphqlReactive: reactiveGroupedActive,
queryOptions: () => {
const view = activeListView();
return {
@@ -1471,7 +1493,7 @@ export const SoupViewContextProvider: FlowComponent<
refresh: async () => {
if (!enabled()) return;
- trimToFirstPage();
+ resetToInitialPage();
await Promise.all([
queryClient.invalidateQueries(
@@ -1482,7 +1504,9 @@ export const SoupViewContextProvider: FlowComponent<
),
// The reactive urql page refetches from the network directly;
// it is outside the TanStack cache the invalidation reaches.
- reactiveActive() ? reactiveItemsQuery.refresh() : Promise.resolve(),
+ reactiveActive()
+ ? activeReactiveItemsQuery().refresh()
+ : Promise.resolve(),
invalidateUserNotifications(),
]);
},
diff --git a/apps/web/src/lib/queries/soup/grouped/api.ts b/apps/web/src/lib/queries/soup/grouped/api.ts
index 9a4ceec3bd..282d96f954 100644
--- a/apps/web/src/lib/queries/soup/grouped/api.ts
+++ b/apps/web/src/lib/queries/soup/grouped/api.ts
@@ -1,3 +1,4 @@
+import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import type { SoupProperty } from '@service-storage/generated/schemas';
import type { ApiGroupByField as ApiGroupedSoupField } from '@service-storage/generated/schemas/apiGroupByField';
import type { ApiGroupMeta } from '@service-storage/generated/schemas/apiGroupMeta';
@@ -157,6 +158,72 @@ function getGroupedPropertyValueType(
return value?.type;
}
+// Stable UUIDs from migrations/20251128000001_seed_system_properties.sql.
+// Custom (user-created) options fall through to displayOrder.
+const STATUS_OPTION_ORDER: readonly string[] = [
+ '00000001-0000-0000-0002-000000000001', // Not Started
+ '00000001-0000-0000-0002-000000000002', // In Progress
+ '00000001-0000-0000-0002-000000000003', // In Review
+ NOT_SET_GROUP_KEY,
+ '00000001-0000-0000-0002-000000000004', // Completed
+ '00000001-0000-0000-0002-000000000005', // Canceled
+];
+
+const PRIORITY_OPTION_ORDER: readonly string[] = [
+ '00000001-0000-0000-0003-000000000004', // Urgent
+ '00000001-0000-0000-0003-000000000003', // High
+ '00000001-0000-0000-0003-000000000002', // Medium
+ '00000001-0000-0000-0003-000000000001', // Low
+ NOT_SET_GROUP_KEY,
+];
+
+function keyRank(order: readonly string[], key: string): number {
+ const i = order.indexOf(key);
+ return i === -1 ? order.length : i;
+}
+
+function defaultOrder(a: GroupMeta, b: GroupMeta): number {
+ if (a.displayOrder === null && b.displayOrder === null) return 0;
+ if (a.displayOrder === null) return 1;
+ if (b.displayOrder === null) return -1;
+ return a.displayOrder - b.displayOrder;
+}
+
+/** Returns the stable display ordering used by grouped Soup parent results. */
+export function makeGroupComparator(
+ groupBy: GroupByField | undefined
+): (a: GroupMeta, b: GroupMeta) => number {
+ if (groupBy?.type === 'property') {
+ if (groupBy.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STATUS) {
+ return (a, b) => {
+ const diff =
+ keyRank(STATUS_OPTION_ORDER, a.key) -
+ keyRank(STATUS_OPTION_ORDER, b.key);
+ return diff !== 0 ? diff : defaultOrder(a, b);
+ };
+ }
+ if (groupBy.propertyDefinitionId === SYSTEM_PROPERTY_IDS.PRIORITY) {
+ return (a, b) => {
+ const diff =
+ keyRank(PRIORITY_OPTION_ORDER, a.key) -
+ keyRank(PRIORITY_OPTION_ORDER, b.key);
+ return diff !== 0 ? diff : defaultOrder(a, b);
+ };
+ }
+ if (groupBy.propertyDefinitionId === SYSTEM_PROPERTY_IDS.ASSIGNEES) {
+ return (a, b) => {
+ const aNotSet = a.key === NOT_SET_GROUP_KEY;
+ const bNotSet = b.key === NOT_SET_GROUP_KEY;
+ if (aNotSet && bNotSet) return 0;
+ if (aNotSet) return 1;
+ if (bNotSet) return -1;
+ return a.label.localeCompare(b.label);
+ };
+ }
+ }
+ return defaultOrder;
+}
+
/**
* Compute the group keys an item belongs to under the given grouping.
* Returns `undefined` when bucketing can't be reproduced client-side
diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.ts
index ccb6f952c9..45fe3e7e15 100644
--- a/apps/web/src/lib/queries/soup/items.ts
+++ b/apps/web/src/lib/queries/soup/items.ts
@@ -1,17 +1,13 @@
import { filterSoupItemByRequestBody } from '@app/features/next-soup/filters/query-filters';
import { throwOnErr } from '@core/util/result';
import type { EntityData } from '@entity';
-import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import {
+ makeGroupComparator,
parseGroupMeta,
resolveGroupMetaForKey,
serializeGroupByField,
} from '@queries/soup/grouped/api';
-import {
- type GroupByField,
- type GroupMeta,
- NOT_SET_GROUP_KEY,
-} from '@queries/soup/grouped/types';
+import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';
import { soupKeys } from '@queries/soup/keys';
import {
isDisplayableSoupItem,
@@ -364,68 +360,3 @@ export const useSoupAstItemsQuery = (
};
});
};
-
-// Stable UUIDs from migrations/20251128000001_seed_system_properties.sql.
-// Custom (user-created) options fall through to displayOrder.
-const STATUS_OPTION_ORDER: readonly string[] = [
- '00000001-0000-0000-0002-000000000001', // Not Started
- '00000001-0000-0000-0002-000000000002', // In Progress
- '00000001-0000-0000-0002-000000000003', // In Review
- NOT_SET_GROUP_KEY,
- '00000001-0000-0000-0002-000000000004', // Completed
- '00000001-0000-0000-0002-000000000005', // Canceled
-];
-
-const PRIORITY_OPTION_ORDER: readonly string[] = [
- '00000001-0000-0000-0003-000000000004', // Urgent
- '00000001-0000-0000-0003-000000000003', // High
- '00000001-0000-0000-0003-000000000002', // Medium
- '00000001-0000-0000-0003-000000000001', // Low
- NOT_SET_GROUP_KEY,
-];
-
-function keyRank(order: readonly string[], key: string): number {
- const i = order.indexOf(key);
- return i === -1 ? order.length : i;
-}
-
-function defaultOrder(a: GroupMeta, b: GroupMeta): number {
- if (a.displayOrder === null && b.displayOrder === null) return 0;
- if (a.displayOrder === null) return 1;
- if (b.displayOrder === null) return -1;
- return a.displayOrder - b.displayOrder;
-}
-
-function makeGroupComparator(
- groupBy: GroupByField | undefined
-): (a: GroupMeta, b: GroupMeta) => number {
- if (groupBy?.type === 'property') {
- if (groupBy.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STATUS) {
- return (a, b) => {
- const diff =
- keyRank(STATUS_OPTION_ORDER, a.key) -
- keyRank(STATUS_OPTION_ORDER, b.key);
- return diff !== 0 ? diff : defaultOrder(a, b);
- };
- }
- if (groupBy.propertyDefinitionId === SYSTEM_PROPERTY_IDS.PRIORITY) {
- return (a, b) => {
- const diff =
- keyRank(PRIORITY_OPTION_ORDER, a.key) -
- keyRank(PRIORITY_OPTION_ORDER, b.key);
- return diff !== 0 ? diff : defaultOrder(a, b);
- };
- }
- if (groupBy.propertyDefinitionId === SYSTEM_PROPERTY_IDS.ASSIGNEES) {
- return (a, b) => {
- const aNotSet = a.key === NOT_SET_GROUP_KEY;
- const bNotSet = b.key === NOT_SET_GROUP_KEY;
- if (aNotSet && bNotSet) return 0;
- if (aNotSet) return 1;
- if (bNotSet) return -1;
- return a.label.localeCompare(b.label);
- };
- }
- }
- return defaultOrder;
-}
diff --git a/apps/web/src/lib/queries/soup/reactive-grouped-items.ts b/apps/web/src/lib/queries/soup/reactive-grouped-items.ts
new file mode 100644
index 0000000000..43eb35a366
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/reactive-grouped-items.ts
@@ -0,0 +1,158 @@
+/*
+ * Reactive urql-backed grouped Soup parent query. The initial GroupSoup
+ * operation remains subscribed so normalized property writes update grouped
+ * rows and group membership without a TanStack invalidation round-trip.
+ */
+
+import { Telemetry } from '@macro-inc/observability';
+import {
+ makeGroupComparator,
+ resolveGroupMetaForKey,
+} from '@queries/soup/grouped/api';
+import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';
+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
+import {
+ GroupSoupDocument,
+ type GroupSoupQuery,
+ type GroupSoupQueryVariables,
+} from '@service-storage/graphql/generated/graphql';
+import {
+ getGraphqlSoupClient,
+ mapGraphqlGroupedSoupPage,
+} from '@service-storage/graphql-soup';
+import type { CombinedError } from '@urql/core';
+import { type Accessor, createComputed, createMemo, on } from 'solid-js';
+import { createUrqlQuery } from '../../urql-solid';
+import { makeGraphqlGroupedSoupInput } from './graphql-ast';
+import type { SoupAstBody, SoupAstItemsData, SoupAstParams } from './items';
+import type { ReactiveSoupAstItemsQuery } from './reactive-items';
+import { mapSoupPageToEntityList } from './transform-utils';
+
+export type ReactiveGroupedSoupAstItemsQueryArgs = {
+ params: SoupAstParams;
+ body: SoupAstBody;
+ groupBy: GroupByField | undefined;
+};
+
+export type ReactiveGroupedSoupAstItemsQueryOptions = {
+ enabled: boolean;
+ showSupportedForeignEntities?: boolean;
+};
+
+function mapReactiveGroupedSoupData(
+ data: GroupSoupQuery,
+ groupBy: GroupByField,
+ options: Parameters<typeof mapSoupPageToEntityList>[1]
+): SoupAstItemsData {
+ const page = mapGraphqlGroupedSoupPage(data);
+ const groups = page.groups
+ .map((group): GroupMeta => {
+ const firstItem = page.items[group.itemIds[0] ?? ''];
+ const resolved = resolveGroupMetaForKey(groupBy, group.key, firstItem);
+ return {
+ key: group.key,
+ label: resolved?.label ?? group.key,
+ displayOrder: resolved?.displayOrder ?? null,
+ totalCount: group.totalCount,
+ itemIds: group.itemIds,
+ nextCursor: group.nextCursor,
+ };
+ })
+ .sort(makeGroupComparator(groupBy));
+
+ const items = groups.flatMap((group) =>
+ group.itemIds.flatMap((id) => {
+ const item = page.items[id];
+ return item ? [item] : [];
+ })
+ );
+
+ return {
+ entities: mapSoupPageToEntityList(
+ { items, next_cursor: undefined },
+ options
+ ),
+ groups,
+ itemsById: page.items,
+ };
+}
+
+/** Creates the live parent operation that discovers grouped Soup bins. */
+export function useReactiveGroupedSoupAstItemsQuery(
+ args: Accessor<ReactiveGroupedSoupAstItemsQueryArgs>,
+ options: Accessor<ReactiveGroupedSoupAstItemsQueryOptions>
+): ReactiveSoupAstItemsQuery {
+ const instructionsIdQuery = useInstructionsMdIdQuery();
+ const input = createMemo(() => {
+ const { params, body, groupBy } = args();
+ if (!groupBy) return;
+ try {
+ return makeGraphqlGroupedSoupInput({ params, body, groupBy });
+ } catch {
+ // Unsupported GraphQL Soup AST — consumers fall back to TanStack/REST.
+ return undefined;
+ }
+ });
+ const isSupported = () => input() !== undefined;
+
+ const query = createUrqlQuery<
+ GroupSoupQuery,
+ GroupSoupQueryVariables,
+ SoupAstItemsData
+ >(() => {
+ const queryOptions = options();
+ const groupBy = args().groupBy;
+ const queryInput = input();
+
+ const common = {
+ query: GroupSoupDocument,
+ client: getGraphqlSoupClient(),
+ requestPolicy: 'cache-and-network' as const,
+ keepPreviousData: false,
+ select: (data: GroupSoupQuery) =>
+ mapReactiveGroupedSoupData(data, groupBy!, {
+ instructionsIdQuery,
+ showSupportedForeignEntities:
+ queryOptions.showSupportedForeignEntities,
+ }),
+ };
+
+ if (!queryOptions.enabled || !groupBy || queryInput === undefined) {
+ return { ...common, enabled: false as const };
+ }
+
+ return {
+ ...common,
+ variables: { input: queryInput },
+ enabled: true,
+ };
+ });
+
+ const error = (): CombinedError | undefined => query.error ?? undefined;
+ createComputed(
+ on(error, (queryError) => {
+ if (queryError) {
+ Telemetry.error(queryError, { graphqlOperation: 'GroupSoup' });
+ }
+ })
+ );
+
+ return {
+ data: () => query.data,
+ error,
+ isSupported,
+ isLoading: () => query.isLoading,
+ isFetching: () => query.isFetching,
+ isFetchingNextPage: () => false,
+ hasNextPage: () => false,
+ fetchNextPage: () => undefined,
+ resetToInitialPage: () => undefined,
+ refresh: async () => {
+ if (input() === undefined) return;
+ await query.refetch({
+ requestPolicy: 'network-only',
+ throwOnError: true,
+ });
+ },
+ };
+}
diff --git a/apps/web/src/lib/queries/soup/reactive-items.test.ts b/apps/web/src/lib/queries/soup/reactive-items.test.ts
index 3ef847993f..5cfb8de5a8 100644
--- a/apps/web/src/lib/queries/soup/reactive-items.test.ts
+++ b/apps/web/src/lib/queries/soup/reactive-items.test.ts
@@ -1,16 +1,20 @@
-import { createRoot, createSignal } from 'solid-js';
+import type {
+ Client,
+ GraphQLRequest,
+ Operation,
+ OperationContext,
+ OperationResult,
+} from '@urql/core';
+import { createRoot } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { makeSubject } from 'wonka';
-const createQuerySignalMock = vi.hoisted(() => vi.fn());
+const getGraphqlSoupClientMock = vi.hoisted(() => vi.fn());
const mapGraphqlSoupPageMock = vi.hoisted(() => vi.fn((data) => data));
const mapSoupPageToEntityListMock = vi.hoisted(() =>
vi.fn((page) => page.items)
);
-vi.mock('@graphql-cache/solid/create-query-signal', () => ({
- createQuerySignal: createQuerySignalMock,
-}));
-
vi.mock('@macro-inc/observability', () => ({
Telemetry: { error: vi.fn() },
}));
@@ -19,12 +23,8 @@ vi.mock('@queries/storage/instructions-md', () => ({
useInstructionsMdIdQuery: vi.fn(() => ({})),
}));
-vi.mock('@service-storage/graphql/generated/graphql', () => ({
- SoupDocument: {},
-}));
-
vi.mock('@service-storage/graphql-soup', () => ({
- getGraphqlSoupClient: vi.fn(() => ({})),
+ getGraphqlSoupClient: getGraphqlSoupClientMock,
mapGraphqlSoupPage: mapGraphqlSoupPageMock,
}));
@@ -38,6 +38,43 @@ vi.mock('./transform-utils', () => ({
import { useReactiveSoupAstItemsQuery } from './reactive-items';
+type FakeExecution = {
+ next(data: unknown): void;
+};
+
+function makeFakeClient(): {
+ client: Client;
+ executions: FakeExecution[];
+} {
+ const executions: FakeExecution[] = [];
+ const execute = (
+ _request: GraphQLRequest<unknown, Record<string, unknown>>,
+ context: Partial<OperationContext>
+ ) => {
+ const subject =
+ makeSubject<OperationResult<unknown, Record<string, unknown>>>();
+ const operation = {
+ kind: 'query',
+ context,
+ } as Operation<unknown, Record<string, unknown>>;
+ executions.push({
+ next: (data) =>
+ subject.next({ operation, data } as OperationResult<
+ unknown,
+ Record<string, unknown>
+ >),
+ });
+ return subject.source;
+ };
+
+ return {
+ executions,
+ client: {
+ executeQuery: execute,
+ } as unknown as Client,
+ };
+}
+
describe('useReactiveSoupAstItemsQuery', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -48,13 +85,8 @@ describe('useReactiveSoupAstItemsQuery', () => {
items: [{ id: 'task-1', type: 'document', name: 'Task' }],
next_cursor: null,
};
- const [queryData, setQueryData] = createSignal<unknown>(firstPage);
- createQuerySignalMock.mockReturnValue({
- data: queryData,
- error: () => undefined,
- fetching: () => false,
- stale: () => false,
- });
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
createRoot((dispose) => {
const query = useReactiveSoupAstItemsQuery(
@@ -62,17 +94,22 @@ describe('useReactiveSoupAstItemsQuery', () => {
() => ({ enabled: true })
);
+ expect(fake.executions).toHaveLength(1);
+ fake.executions[0]?.next(firstPage);
+
const initial = query.data();
- expect(initial?.entities[0]).toEqual(firstPage.items[0]);
+ const initialEntity = initial?.entities[0];
+ expect(initialEntity).toEqual(firstPage.items[0]);
- setQueryData(structuredClone(firstPage));
+ fake.executions[0]?.next(structuredClone(firstPage));
expect(query.data()).toBe(initial);
+ expect(query.data()?.entities[0]).toBe(initialEntity);
- setQueryData({
+ fake.executions[0]?.next({
...firstPage,
items: [{ ...firstPage.items[0], name: 'Updated task' }],
});
- expect(query.data()).not.toBe(initial);
+ expect(query.data()?.entities[0]).toBe(initialEntity);
expect(query.data()?.entities[0]?.name).toBe('Updated task');
dispose();
diff --git a/apps/web/src/lib/queries/soup/reactive-items.ts b/apps/web/src/lib/queries/soup/reactive-items.ts
index 4caeb63ce4..3db26266b8 100644
--- a/apps/web/src/lib/queries/soup/reactive-items.ts
+++ b/apps/web/src/lib/queries/soup/reactive-items.ts
@@ -1,20 +1,15 @@
-/**
- * Reactive urql-backed soup items: the flagged alternative to the TanStack
- * `useSoupAstItemsQuery` path. Each page holds a live subscription to the
- * GraphQL Soup query, so results pushed by the normalized cache exchange
- * (optimistic property mutations, sibling writes, other tabs) re-render
- * the soup list directly — no TanStack invalidation round-trip.
+/*
+ * Reactive urql-backed Soup items: the flagged alternative to the TanStack
+ * `useSoupAstItemsQuery` path. Every loaded page remains subscribed to its
+ * normalized GraphQL cache operation so cache writes update the list directly.
*
- * Scope matches the GraphQL transport: flat (non-grouped) views whose
- * filter AST has a GraphQL translation. Consumers check `isSupported`
- * and fall back to the TanStack path otherwise.
+ * Scope matches the GraphQL transport: flat views whose filter AST has a
+ * GraphQL translation. Consumers check `isSupported` and fall back to the
+ * TanStack path otherwise.
*/
-import { deepEqual } from '@core/util/compareUtils';
-import { createQuerySignal } from '@graphql-cache/solid/create-query-signal';
import { Telemetry } from '@macro-inc/observability';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
-import type { SoupPage } from '@service-storage/generated/schemas/soupPage';
import {
SoupDocument,
type SoupQuery,
@@ -26,14 +21,8 @@ import {
mapGraphqlSoupPage,
} from '@service-storage/graphql-soup';
import type { CombinedError } from '@urql/core';
-import {
- type Accessor,
- createComputed,
- createMemo,
- createSignal,
- mapArray,
- on,
-} from 'solid-js';
+import { type Accessor, createComputed, createMemo, on } from 'solid-js';
+import { createUrqlInfiniteQuery } from '../../urql-solid';
import { makeGraphqlSoupInput } from './graphql-ast';
import type { SoupAstBody, SoupAstItemsData, SoupAstParams } from './items';
import { mapSoupPageToEntityList } from './transform-utils';
@@ -59,9 +48,9 @@ export type ReactiveSoupAstItemsQuery = {
isFetchingNextPage: Accessor<boolean>;
hasNextPage: Accessor<boolean>;
fetchNextPage: () => void;
- /** Drops all but the first page (filter changes, pull-to-refresh). */
- trimToFirstPage: () => void;
- /** Trims to the first page and refetches it from the network. */
+ /** Discards loaded continuation pages while retaining the initial page. */
+ resetToInitialPage: () => void;
+ /** Refetches the currently loaded page chain from the network. */
refresh: () => Promise<void>;
};
@@ -86,52 +75,45 @@ export function useReactiveSoupAstItemsQuery(
const firstPageInput = createMemo(() => inputForCursor(null));
const isSupported = () => firstPageInput() !== undefined;
- // Cursors of the pages currently shown. Structural key: the input memo
- // yields a fresh object per read, so compare serialized form to avoid
- // resetting pagination on every unrelated reactive tick.
- const inputKey = createMemo(() => {
- const input = firstPageInput();
- return input === undefined ? undefined : JSON.stringify(input);
- });
- const [cursors, setCursors] = createSignal<(string | null)[]>([null]);
- createComputed(on(inputKey, () => setCursors([null]), { defer: true }));
+ const query = createUrqlInfiniteQuery<
+ SoupQuery,
+ SoupQueryVariables,
+ string | null,
+ SoupAstItemsData
+ >(() => {
+ const firstInput = firstPageInput();
+ const queryOptions = options();
+ const showSupportedForeignEntities =
+ queryOptions.showSupportedForeignEntities;
- const pages = mapArray(cursors, (cursor) => {
- const query = createQuerySignal<SoupQuery, SoupQueryVariables>({
- client: getGraphqlSoupClient,
- document: SoupDocument,
- // Serve the cached page instantly, revalidate over the network, and
- // keep receiving cache-pushed re-executions for the page's lifetime.
- requestPolicy: 'cache-and-network',
- variables: () => {
- if (!options().enabled) return undefined;
+ return {
+ query: SoupDocument,
+ client: getGraphqlSoupClient(),
+ initialPageParam: null,
+ variables: (cursor) => {
const input = inputForCursor(cursor);
- return input === undefined ? undefined : { input };
- },
- });
- const page = createMemo<SoupPage | undefined>(
- () => {
- const data = query.data();
- return data == null ? undefined : mapGraphqlSoupPage(data);
+ if (!input) {
+ throw new Error('GraphQL Soup input became unsupported');
+ }
+ return { input };
},
- undefined,
- {
- // Cache writes for unrelated backfill arguments can re-execute this
- // operation with identical data. Retain the prior page so Solid's
- // keyed list does not remount every row and dismiss open editors.
- equals: deepEqual,
- }
- );
- return { query, page };
+ getNextPageParam: (lastPage) => mapGraphqlSoupPage(lastPage).next_cursor,
+ enabled: queryOptions.enabled && firstInput !== undefined,
+ requestPolicy: 'cache-and-network',
+ keepPreviousData: false,
+ select: ({ pages }) => ({
+ entities: pages.flatMap((page) =>
+ mapSoupPageToEntityList(mapGraphqlSoupPage(page), {
+ instructionsIdQuery,
+ showSupportedForeignEntities,
+ })
+ ),
+ groups: undefined,
+ }),
+ };
});
- const error = (): CombinedError | undefined => {
- for (const entry of pages()) {
- const queryError = entry.query.error();
- if (queryError) return queryError;
- }
- return undefined;
- };
+ const error = (): CombinedError | undefined => query.error ?? undefined;
createComputed(
on(error, (queryError) => {
if (queryError) {
@@ -140,59 +122,24 @@ export function useReactiveSoupAstItemsQuery(
})
);
- const lastPage = () => pages().at(-1);
-
- const data = createMemo<SoupAstItemsData | undefined>(() => {
- const list = pages();
- if (list[0]?.page() === undefined) return undefined;
- const entities = list.flatMap((entry) => {
- const page = entry.page();
- if (!page) return [];
- return mapSoupPageToEntityList(page, {
- instructionsIdQuery,
- showSupportedForeignEntities: options().showSupportedForeignEntities,
- });
- });
- return { entities, groups: undefined };
- });
-
- const isFetching = () =>
- pages().some((entry) => entry.query.fetching() || entry.query.stale());
-
return {
- data,
+ data: () => query.data,
error,
isSupported,
- isLoading: () => data() === undefined && isFetching(),
- isFetching,
- isFetchingNextPage: () => {
- const last = lastPage();
- return (
- cursors().length > 1 &&
- last !== undefined &&
- last.page() === undefined &&
- last.query.fetching()
- );
- },
- hasNextPage: () => lastPage()?.page()?.next_cursor != null,
+ isLoading: () => query.isLoading,
+ isFetching: () => query.isFetching,
+ isFetchingNextPage: () => query.isFetchingNextPage,
+ hasNextPage: () => query.hasNextPage,
fetchNextPage: () => {
- const next = lastPage()?.page()?.next_cursor;
- if (next == null || cursors().includes(next)) return;
- setCursors((prev) => [...prev, next]);
- },
- trimToFirstPage: () => {
- setCursors((prev) => (prev.length > 1 ? [prev[0] ?? null] : prev));
+ void query.fetchNextPage();
},
+ resetToInitialPage: query.resetToInitialPage,
refresh: async () => {
- setCursors((prev) => (prev.length > 1 ? [prev[0] ?? null] : prev));
- const input = firstPageInput();
- if (input === undefined) return;
- // Shares the operation key with the page subscription: the fresh
- // network result is broadcast to it, updating the UI.
- const result = await getGraphqlSoupClient()
- .query(SoupDocument, { input }, { requestPolicy: 'network-only' })
- .toPromise();
- if (result.error) throw result.error;
+ if (firstPageInput() === undefined) return;
+ await query.refetch({
+ requestPolicy: 'network-only',
+ throwOnError: true,
+ });
},
};
}
diff --git a/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsx b/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsx
index 3ebb5ba706..59d606a921 100644
--- a/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsx
+++ b/apps/web/src/lib/urql-solid/create-urql-infinite-query.test.tsx
@@ -149,6 +149,51 @@ describe('createUrqlInfiniteQuery', () => {
expect(fake.executions[0]?.unsubscribed).toBe(false);
});
+ it('resets to the live initial page before refetching', async () => {
+ const fake = makeFakeClient();
+ let query!: ReturnType<
+ typeof createUrqlInfiniteQuery<Page, Variables, string | null, string[]>
+ >;
+ const dispose = createRoot((rootDispose) => {
+ query = createUrqlInfiniteQuery<Page, Variables, string | null, string[]>(
+ () => ({
+ query: DOCUMENT,
+ client: fake.client,
+ initialPageParam: null,
+ variables: (cursor) => ({ cursor }),
+ getNextPageParam: (lastPage) => lastPage.nextCursor,
+ select: ({ pages }) => pages.flatMap((page) => page.values),
+ })
+ );
+ return rootDispose;
+ });
+ disposals.push(dispose);
+
+ fake.executions[0]?.next({ values: ['first'], nextCursor: 'cursor-1' });
+ const nextPage = query.fetchNextPage();
+ fake.executions[1]?.next({ values: ['second'], nextCursor: null });
+ await nextPage;
+
+ query.resetToInitialPage();
+
+ expect(query.data).toEqual(['first']);
+ expect(query.hasNextPage).toBe(true);
+ expect(fake.executions[0]?.unsubscribed).toBe(false);
+ expect(fake.executions[1]?.unsubscribed).toBe(true);
+
+ const refetch = query.refetch();
+ expect(fake.executions).toHaveLength(3);
+ expect(fake.executions[2]?.variables).toEqual({ cursor: null });
+ fake.executions[2]?.next({
+ values: ['first-refreshed'],
+ nextCursor: null,
+ });
+ await refetch;
+
+ expect(query.data).toEqual(['first-refreshed']);
+ expect(fake.executions).toHaveLength(3);
+ });
+
it('disables page subscriptions and re-enables them', () => {
const fake = makeFakeClient();
const [enabled, setEnabled] = createSignal(true);
diff --git a/apps/web/src/lib/urql-solid/infinite-query-observer.ts b/apps/web/src/lib/urql-solid/infinite-query-observer.ts
index b65934f7b0..42fe901761 100644
--- a/apps/web/src/lib/urql-solid/infinite-query-observer.ts
+++ b/apps/web/src/lib/urql-solid/infinite-query-observer.ts
@@ -219,6 +219,7 @@ export class InfiniteQueryObserver<
isFetchNextPageError:
this.state.paginationError !== undefined ||
this.failedNextPage !== undefined,
+ resetToInitialPage: this.resetToInitialPage,
fetchNextPage: this.fetchNextPage,
refetch: this.refetch,
};
@@ -254,6 +255,15 @@ export class InfiniteQueryObserver<
this.result.clear();
}
+ readonly resetToInitialPage = (): void => {
+ if (this.destroyed) return;
+
+ this.cancelActions();
+ this.destroyPages(1);
+ this.setState({ paginationError: undefined });
+ this.emit();
+ };
+
readonly fetchNextPage = (
refetchOptions: UrqlQueryRefetchOptions = {}
): Promise<InfiniteResult<PageData, Variables, PageParam, SelectedData>> => {
diff --git a/apps/web/src/lib/urql-solid/types.ts b/apps/web/src/lib/urql-solid/types.ts
index a1a16a58fe..605ded166f 100644
--- a/apps/web/src/lib/urql-solid/types.ts
+++ b/apps/web/src/lib/urql-solid/types.ts
@@ -184,6 +184,8 @@ export type UrqlInfiniteQueryResult<
readonly hasNextPage: boolean;
readonly isFetchingNextPage: boolean;
readonly isFetchNextPageError: boolean;
+ /** Discards every continuation page while retaining the live initial page. */
+ resetToInitialPage(): void;
fetchNextPage(
options?: UrqlQueryRefetchOptions
): Promise<