@djangocfg/layouts 2.1.663 → 2.1.664

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/layouts",
3
- "version": "2.1.663",
3
+ "version": "2.1.664",
4
4
  "description": "Simple, straightforward layout components for Next.js - import and use with props",
5
5
  "keywords": [
6
6
  "layouts",
@@ -91,24 +91,23 @@
91
91
  "test": "vitest run"
92
92
  },
93
93
  "peerDependencies": {
94
- "@djangocfg/analytics": "^2.1.663",
95
- "@djangocfg/api": "^2.1.663",
96
- "@djangocfg/devtools": "^2.1.663",
97
- "@djangocfg/i18n": "^2.1.663",
98
- "@djangocfg/realtime": "^2.1.663",
99
- "@djangocfg/ui-core": "^2.1.663",
94
+ "@djangocfg/analytics": "^2.1.664",
95
+ "@djangocfg/api": "^2.1.664",
96
+ "@djangocfg/devtools": "^2.1.664",
97
+ "@djangocfg/i18n": "^2.1.664",
98
+ "@djangocfg/realtime": "^2.1.664",
99
+ "@djangocfg/ui-core": "^2.1.664",
100
100
  "@hookform/resolvers": "^5.2.2 || ^7.0.2",
101
+ "@tanstack/react-query": "^5.108.2",
101
102
  "consola": "^3.4.2",
102
103
  "lucide-react": "^1.68.0",
103
104
  "moment": "^2.30.1",
104
105
  "next": "^16.4.5",
105
106
  "next-intl": "^4.9.1",
106
- "p-retry": "^7.0.0",
107
107
  "react": "^19.0.0",
108
108
  "react-dom": "^19.0.0",
109
109
  "react-hook-form": "^7.69.0",
110
110
  "sonner": "^2.0.7",
111
- "swr": "^2.3.7",
112
111
  "tailwindcss": "^4.1.18",
113
112
  "tailwindcss-animate": "^1.0.7",
114
113
  "zod": "^4.3.6",
@@ -124,14 +123,15 @@
124
123
  "qrcode.react": "^4.2.0"
125
124
  },
126
125
  "devDependencies": {
127
- "@djangocfg/analytics": "^2.1.663",
128
- "@djangocfg/api": "^2.1.663",
129
- "@djangocfg/devtools": "^2.1.663",
130
- "@djangocfg/i18n": "^2.1.663",
131
- "@djangocfg/realtime": "^2.1.663",
132
- "@djangocfg/typescript-config": "^2.1.663",
133
- "@djangocfg/ui-core": "^2.1.663",
126
+ "@djangocfg/analytics": "^2.1.664",
127
+ "@djangocfg/api": "^2.1.664",
128
+ "@djangocfg/devtools": "^2.1.664",
129
+ "@djangocfg/i18n": "^2.1.664",
130
+ "@djangocfg/realtime": "^2.1.664",
131
+ "@djangocfg/typescript-config": "^2.1.664",
132
+ "@djangocfg/ui-core": "^2.1.664",
134
133
  "@storybook/react-vite": "^10.6.5",
134
+ "@tanstack/react-query": "5.108.2",
135
135
  "@types/node": "^25.9.5",
136
136
  "@types/react": "19.3.0",
137
137
  "@types/react-dom": "19.3.0",
@@ -139,7 +139,6 @@
139
139
  "next-intl": "^4.14.9",
140
140
  "sonner": "2.0.8",
141
141
  "storybook": "^10.6.5",
142
- "swr": "^2.5.1",
143
142
  "typescript": "^5.9.3",
144
143
  "vitest": "^5.1.0",
145
144
  "zustand": "^5.0.16"
@@ -11,7 +11,7 @@
11
11
  * Provides essential app-wide providers:
12
12
  * - ThemeProvider (light/dark/system theme)
13
13
  * - TooltipProvider (tooltip positioning)
14
- * - SWRConfig (data fetching)
14
+ * - QueryClientProvider (React Query: the app's own client, one above, or one with django-cfg's defaults)
15
15
  * - AuthProvider (authentication context)
16
16
  * - RealtimeProvider (`@djangocfg/realtime`, lazy: no socket until a `useTopic` mounts)
17
17
  * - AuthDialog (global auth prompt dialog)
@@ -45,7 +45,6 @@
45
45
  'use client';
46
46
 
47
47
  import { nodeEnv } from "@djangocfg/ui-core/lib";
48
- import { SWRConfig } from 'swr';
49
48
 
50
49
  import { Devtools, devtools } from '@djangocfg/devtools';
51
50
  import { errorDetailToDevtoolsEvent } from '../../components/errors/ErrorsTracker';
@@ -69,7 +68,7 @@ import { ProjectNameProvider } from '../../shared/ProjectContext';
69
68
  import { PwaManifestCheck, PwaMetaGuard } from './pwaMeta';
70
69
  import { resolveDevtoolsBaseUrl } from './devtoolsBaseUrl';
71
70
  import { RealtimeMount } from './realtime/RealtimeMount';
72
- import { realtimeRefresh } from './realtime/realtimeRefresh';
71
+ import { AppQueryProvider } from './query/AppQueryProvider';
73
72
  import { resolveRealtimeApiUrl } from './realtime/realtimeApiUrl';
74
73
 
75
74
  import React from 'react';
@@ -96,8 +95,6 @@ function ScrollToTop() {
96
95
  return null;
97
96
  }
98
97
 
99
- const REALTIME_SWR_MIDDLEWARE = [realtimeRefresh];
100
-
101
98
  /** Inside `AuthProvider` so a login or logout reconnects the socket with the new identity. */
102
99
  function OptionalRealtime({
103
100
  config,
@@ -119,7 +116,7 @@ function OptionalRealtime({
119
116
  /**
120
117
  * BaseApp - Core providers wrapper for any React/Next.js app
121
118
  *
122
- * Includes: ThemeProvider, TooltipProvider, SWRConfig, AuthProvider, AnalyticsProvider,
119
+ * Includes: ThemeProvider, TooltipProvider, QueryClientProvider, AuthProvider, AnalyticsProvider,
123
120
  * ErrorTrackingProvider, ErrorBoundary (optional)
124
121
  * Also renders global Toaster and PageProgress components
125
122
  */
@@ -132,7 +129,8 @@ export function BaseApp({
132
129
  analytics,
133
130
  errorTracking,
134
131
  errorBoundary,
135
- swr,
132
+ queryClient,
133
+ queryDevtools,
136
134
  devtools: devtoolsConfig,
137
135
  i18n,
138
136
  pwaMeta = true,
@@ -198,14 +196,7 @@ export function BaseApp({
198
196
  : undefined
199
197
  }
200
198
  >
201
- <SWRConfig
202
- value={{
203
- revalidateOnFocus: swr?.revalidateOnFocus ?? true,
204
- revalidateOnReconnect: swr?.revalidateOnReconnect ?? true,
205
- dedupingInterval: swr?.dedupingInterval ?? 2000,
206
- use: realtime === false ? undefined : REALTIME_SWR_MIDDLEWARE,
207
- }}
208
- >
199
+ <AppQueryProvider queryClient={queryClient} queryDevtools={queryDevtools}>
209
200
  <AuthProvider config={authEnabled ? authConfig : undefined} enabled={authEnabled}>
210
201
  <OptionalRealtime config={realtime} apiUrl={realtimeApiUrl}>
211
202
  <AnalyticsProvider trackingId={analytics?.googleTrackingId}>
@@ -234,7 +225,7 @@ export function BaseApp({
234
225
  </AnalyticsProvider>
235
226
  </OptionalRealtime>
236
227
  </AuthProvider>
237
- </SWRConfig>
228
+ </AppQueryProvider>
238
229
  </UiProviders>
239
230
  </NextLinkProvider>
240
231
  </NextRouterAdapter>
@@ -1,7 +1,7 @@
1
1
  # BaseApp — provider stack
2
2
 
3
3
  `BaseApp` is the **single, framework-agnostic provider wrapper** for any React
4
- host. It mounts theme, auth, i18n, SWR, error tracking, monitor, the debug
4
+ host. It mounts theme, auth, i18n, the React Query client, realtime, error tracking, monitor, the debug
5
5
  panel, and the router adapter — everything an app needs *above* the page tree.
6
6
 
7
7
  There is **no `AppLayout` layout-router** anymore. Picking which shell
@@ -82,7 +82,8 @@ interface BaseAppProps {
82
82
  analytics?: AnalyticsConfig; // Google Analytics
83
83
  errorTracking?: ErrorTrackingConfig;
84
84
  errorBoundary?: ErrorBoundaryConfig; // enabled by default
85
- swr?: SWRConfigOptions;
85
+ queryClient?: QueryClient; // the app's own; else one above BaseApp is reused, else one with our defaults
86
+ queryDevtools?: QueryDevtoolsLoader; // () => import('@tanstack/react-query-devtools'), dev builds only
86
87
  monitor?: MonitorConfig;
87
88
  debug?: DebugConfig; // debug panel (auto in dev / ?debug=1 in prod)
88
89
  i18n?: I18nLayoutConfig; // locale + routing for the link bridge
@@ -90,6 +91,22 @@ interface BaseAppProps {
90
91
  }
91
92
  ```
92
93
 
94
+ ## React Query and realtime refresh
95
+
96
+ `BaseApp` owns the page's one QueryClient. A `queryClient` prop wins and is used
97
+ as it is. Without it, a QueryClient already provided above `BaseApp` is reused,
98
+ so a page never holds two caches. Otherwise `createAppQueryClient()` makes one
99
+ per mount, never at module scope. Its defaults: no retry on a 4xx, up to 2 on a
100
+ network error or a 5xx, `throwOnError: false`, `staleTime` 30 s, refetch on
101
+ focus, and mutations are not retried.
102
+
103
+ A generated query whose view is marked `@invalidated_by("topic")` carries the
104
+ concrete topic names in `meta.realtimeTopics` (the generated
105
+ `runtime/realtime-query.ts`). `RealtimeMount` watches the QueryCache. While such
106
+ a query has an observer, its topics stay subscribed (released lazily, 1.5 s
107
+ after the last one goes). A message, a gap or a fresh subscription going live
108
+ invalidates the queries tagged with that topic. The page needs no code.
109
+
93
110
  ## Per-route forced theme (optional)
94
111
 
95
112
  To force a theme on a subtree (e.g. an always-dark marketing landing) without
@@ -12,6 +12,9 @@ export { BaseApp } from './BaseApp';
12
12
  export { resolveDevtoolsBaseUrl } from './devtoolsBaseUrl';
13
13
  export { resolveRealtimeApiUrl } from './realtime/realtimeApiUrl';
14
14
  export type { BaseAppProps } from './BaseApp';
15
+ export { createAppQueryClient, shouldRetryQuery } from './query';
16
+ export type { QueryDevtoolsLoader } from './query';
17
+ export { REALTIME_META_KEY, topicsOfQuery } from './realtime/queryRealtime';
15
18
 
16
19
  export type { I18nLayoutConfig } from '../types';
17
20
 
@@ -0,0 +1,65 @@
1
+ // @vitest-environment jsdom
2
+ import { QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';
3
+ import React, { act } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { AppQueryProvider, QUERY_MAX_RETRIES, createAppQueryClient, shouldRetryQuery } from './AppQueryProvider';
8
+
9
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
10
+
11
+ function clientUnder(tree: (probe: React.ReactNode) => React.ReactNode): QueryClient {
12
+ let seen: QueryClient | null = null;
13
+ function Probe() {
14
+ seen = useQueryClient();
15
+ return null;
16
+ }
17
+ const root = createRoot(document.createElement('div'));
18
+ act(() => root.render(<>{tree(<Probe />)}</>));
19
+ act(() => root.unmount());
20
+ if (seen === null) throw new Error('no QueryClient reached the probe');
21
+ return seen;
22
+ }
23
+
24
+ describe('shouldRetryQuery', () => {
25
+ it('never retries a 4xx, retries a 5xx and a network failure up to the limit', () => {
26
+ expect(shouldRetryQuery(0, { statusCode: 404 })).toBe(false);
27
+ expect(shouldRetryQuery(0, { status: 401 })).toBe(false);
28
+ expect(shouldRetryQuery(0, { statusCode: 502 })).toBe(true);
29
+ expect(shouldRetryQuery(0, Object.assign(new Error('offline'), { name: 'NetworkError' }))).toBe(true);
30
+ expect(shouldRetryQuery(0, new TypeError('Failed to fetch'))).toBe(true);
31
+ expect(shouldRetryQuery(QUERY_MAX_RETRIES, { statusCode: 503 })).toBe(false);
32
+ expect(shouldRetryQuery(0, new Error('response failed validation'))).toBe(false);
33
+ });
34
+
35
+ it('is the default of the client BaseApp creates, with mutations not retried', () => {
36
+ const defaults = createAppQueryClient().getDefaultOptions();
37
+ expect(defaults.queries?.retry).toBe(shouldRetryQuery);
38
+ expect(defaults.queries?.throwOnError).toBe(false);
39
+ expect(defaults.mutations?.retry).toBe(false);
40
+ });
41
+ });
42
+
43
+ describe('AppQueryProvider', () => {
44
+ it('reuses a QueryClient provided above it instead of nesting a second cache', () => {
45
+ const outer = new QueryClient();
46
+ const seen = clientUnder((probe) => (
47
+ <QueryClientProvider client={outer}>
48
+ <AppQueryProvider>{probe}</AppQueryProvider>
49
+ </QueryClientProvider>
50
+ ));
51
+ expect(seen).toBe(outer);
52
+ });
53
+
54
+ it("uses the app's own client as it is", () => {
55
+ const own = new QueryClient();
56
+ const seen = clientUnder((probe) => <AppQueryProvider queryClient={own}>{probe}</AppQueryProvider>);
57
+ expect(seen).toBe(own);
58
+ expect(seen.getDefaultOptions().queries?.retry).toBeUndefined();
59
+ });
60
+
61
+ it("creates one with django-cfg's defaults when there is none", () => {
62
+ const seen = clientUnder((probe) => <AppQueryProvider>{probe}</AppQueryProvider>);
63
+ expect(seen.getDefaultOptions().queries?.retry).toBe(shouldRetryQuery);
64
+ });
65
+ });
@@ -0,0 +1,94 @@
1
+ 'use client';
2
+
3
+ import { QueryClient, QueryClientContext, QueryClientProvider } from '@tanstack/react-query';
4
+ import { Suspense, lazy, useContext, useMemo, useState } from 'react';
5
+
6
+ import type { ComponentType, ReactNode } from 'react';
7
+
8
+ /** Retries after a failure: none on a 4xx or a non-network error, up to this many on a network error or a 5xx. */
9
+ export const QUERY_MAX_RETRIES = 2;
10
+ /** How long a fetched query counts as fresh before a mount or a focus refetches it. */
11
+ export const QUERY_STALE_TIME_MS = 30_000;
12
+
13
+ function statusOf(error: unknown): number | null {
14
+ if (typeof error !== 'object' || error === null) return null;
15
+ const { statusCode, status } = error as { statusCode?: unknown; status?: unknown };
16
+ if (typeof statusCode === 'number' && statusCode > 0) return statusCode;
17
+ if (typeof status === 'number' && status > 0) return status;
18
+ return null;
19
+ }
20
+
21
+ /**
22
+ * Structural, not `instanceof`: a 5xx or a failed connection is worth another try; a 4xx, a response that failed
23
+ * validation or a configuration error will fail the same way again.
24
+ */
25
+ export function shouldRetryQuery(failureCount: number, error: unknown): boolean {
26
+ if (failureCount >= QUERY_MAX_RETRIES) return false;
27
+ const status = statusOf(error);
28
+ if (status !== null) return status >= 500;
29
+ const name = error instanceof Error ? error.name : '';
30
+ return name === 'NetworkError' || name === 'TypeError';
31
+ }
32
+
33
+ /** A new QueryClient with django-cfg's defaults. One per mounted app: never at module scope (SSR). */
34
+ export function createAppQueryClient(): QueryClient {
35
+ return new QueryClient({
36
+ defaultOptions: {
37
+ queries: {
38
+ retry: shouldRetryQuery,
39
+ throwOnError: false,
40
+ staleTime: QUERY_STALE_TIME_MS,
41
+ refetchOnWindowFocus: true,
42
+ },
43
+ mutations: { retry: false },
44
+ },
45
+ });
46
+ }
47
+
48
+ /** `() => import('@tanstack/react-query-devtools')`: the app's own import, so the package is the app's choice. */
49
+ export type QueryDevtoolsLoader = () => Promise<{ ReactQueryDevtools: ComponentType<{ initialIsOpen?: boolean }> }>;
50
+
51
+ export interface AppQueryProviderProps {
52
+ /** The app's own client. It wins and its defaults are used as they are. */
53
+ queryClient?: QueryClient;
54
+ /** React Query Devtools, rendered in development only and loaded lazily. */
55
+ queryDevtools?: QueryDevtoolsLoader;
56
+ children: ReactNode;
57
+ }
58
+
59
+ function QueryDevtools({ load }: { load: QueryDevtoolsLoader }) {
60
+ const Devtools = useMemo(() => lazy(() => load().then((m) => ({ default: m.ReactQueryDevtools }))), [load]);
61
+ return (
62
+ <Suspense fallback={null}>
63
+ <Devtools initialIsOpen={false} />
64
+ </Suspense>
65
+ );
66
+ }
67
+
68
+ /**
69
+ * The app's QueryClient. `queryClient` wins; else a QueryClient already provided above is reused, so a page never
70
+ * holds two caches; else one is created with `createAppQueryClient` for the life of this mount.
71
+ */
72
+ export function AppQueryProvider({ queryClient, queryDevtools, children }: AppQueryProviderProps) {
73
+ const outer = useContext(QueryClientContext);
74
+ // Created once per mount even when unused: a QueryClient that is never provided holds nothing and starts nothing.
75
+ const [own] = useState(createAppQueryClient);
76
+ const devtools =
77
+ queryDevtools && process.env.NODE_ENV !== 'production' ? <QueryDevtools load={queryDevtools} /> : null;
78
+
79
+ const client = queryClient ?? (outer ? null : own);
80
+ if (client === null) {
81
+ return (
82
+ <>
83
+ {children}
84
+ {devtools}
85
+ </>
86
+ );
87
+ }
88
+ return (
89
+ <QueryClientProvider client={client}>
90
+ {children}
91
+ {devtools}
92
+ </QueryClientProvider>
93
+ );
94
+ }
@@ -0,0 +1,8 @@
1
+ export {
2
+ AppQueryProvider,
3
+ QUERY_MAX_RETRIES,
4
+ QUERY_STALE_TIME_MS,
5
+ createAppQueryClient,
6
+ shouldRetryQuery,
7
+ } from './AppQueryProvider';
8
+ export type { AppQueryProviderProps, QueryDevtoolsLoader } from './AppQueryProvider';
@@ -1,16 +1,17 @@
1
1
  'use client';
2
2
 
3
+ import { useQueryClient } from '@tanstack/react-query';
3
4
  import { useCallback, useEffect } from 'react';
4
- import { useSWRConfig } from 'swr';
5
5
 
6
6
  import { setRealtimeCidProvider } from '@djangocfg/api';
7
7
  import { devtools } from '@djangocfg/devtools';
8
- import { RealtimeProvider, isKeyForTopic, useRealtimeClient } from '@djangocfg/realtime/react';
8
+ import { RealtimeProvider, useRealtimeClient } from '@djangocfg/realtime/react';
9
9
 
10
10
  import type { ReactNode } from 'react';
11
11
  import type { ReportedIssue } from '@djangocfg/realtime';
12
12
  import type { RealtimeConfig } from '@djangocfg/realtime/react';
13
13
 
14
+ import { bridgeQueryCache, topicsOfQuery } from './queryRealtime';
14
15
  import { realtimeIssueEvent } from './realtimeIssueEvent';
15
16
 
16
17
  interface RealtimeMountProps {
@@ -33,6 +34,14 @@ function RealtimeCidBridge() {
33
34
  return null;
34
35
  }
35
36
 
37
+ /** Keeps the topics of the mounted, tagged queries subscribed; see `bridgeQueryCache`. */
38
+ function RealtimeQueryBridge() {
39
+ const client = useRealtimeClient();
40
+ const queryClient = useQueryClient();
41
+ useEffect(() => (client === null ? undefined : bridgeQueryCache(queryClient, client)), [client, queryClient]);
42
+ return null;
43
+ }
44
+
36
45
  /** Realtime problems go to the same monitor as every other frontend error. Never throws. */
37
46
  function captureIssue(issue: ReportedIssue): void {
38
47
  try {
@@ -43,20 +52,20 @@ function captureIssue(issue: ReportedIssue): void {
43
52
  }
44
53
 
45
54
  /**
46
- * `RealtimeProvider` with the app's defaults: unless the app passes `onGap`, a
47
- * gap refreshes legacy SWR cache entries tagged with the topic, so the REST API
48
- * stays the source of truth; new Orval/React Query consumers use
49
- * `useTopicRefresh` with their generated query key. Issues are captured by
50
- * `@djangocfg/devtools` (an app's
51
- * own `onIssue` runs as well). Sits inside `SWRConfig` and `AuthProvider`.
55
+ * `RealtimeProvider` with the app's defaults. A generated query whose operation is `invalidated_by` a topic carries
56
+ * it in `meta.realtimeTopics`; while such a query is mounted its topics stay subscribed, and a message or a gap
57
+ * invalidates it, so the REST API stays the source of truth and a page needs no code (`RealtimeQueryBridge`). Unless
58
+ * the app passes `onGap`, a gap on a `useTopic` subscription invalidates the queries tagged with that topic too.
59
+ * Issues are captured by `@djangocfg/devtools` (an app's own `onIssue` runs as well). Sits inside the app's
60
+ * QueryClient and `AuthProvider`.
52
61
  */
53
62
  export function RealtimeMount({ config, apiUrl, children }: RealtimeMountProps) {
54
- const { mutate } = useSWRConfig();
55
- const revalidateTopic = useCallback(
63
+ const queryClient = useQueryClient();
64
+ const invalidateTopic = useCallback(
56
65
  (topic: string) => {
57
- void mutate((key) => isKeyForTopic(key, topic));
66
+ void queryClient.invalidateQueries({ predicate: (query) => topicsOfQuery(query).includes(topic) });
58
67
  },
59
- [mutate],
68
+ [queryClient],
60
69
  );
61
70
  const appOnIssue = config.onIssue;
62
71
  const onIssue = useCallback(
@@ -67,8 +76,9 @@ export function RealtimeMount({ config, apiUrl, children }: RealtimeMountProps)
67
76
  [appOnIssue],
68
77
  );
69
78
  return (
70
- <RealtimeProvider {...config} apiUrl={apiUrl} onGap={config.onGap ?? revalidateTopic} onIssue={onIssue}>
79
+ <RealtimeProvider {...config} apiUrl={apiUrl} onGap={config.onGap ?? invalidateTopic} onIssue={onIssue}>
71
80
  <RealtimeCidBridge />
81
+ <RealtimeQueryBridge />
72
82
  {children}
73
83
  </RealtimeProvider>
74
84
  );
@@ -0,0 +1,108 @@
1
+ import { QueryClient, QueryObserver } from '@tanstack/react-query';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import { createRealtimeClient } from '@djangocfg/realtime';
5
+ import { createMockServer } from '@djangocfg/realtime/testing';
6
+
7
+ import { REALTIME_META_KEY, bridgeQueryCache } from './queryRealtime';
8
+
9
+ beforeEach(() => {
10
+ vi.useFakeTimers();
11
+ });
12
+
13
+ afterEach(() => {
14
+ vi.useRealTimers();
15
+ });
16
+
17
+ function setup() {
18
+ const server = createMockServer({ ping: 0 });
19
+ const client = createRealtimeClient({ url: server.url, WebSocket: server.WebSocket, random: () => 0, wake: () => () => {} });
20
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
21
+ return { server, client, queryClient };
22
+ }
23
+
24
+ /** What a generated hook does: the query's options, with `meta.realtimeTopics` from `runtime/realtime-query.ts`. */
25
+ function observe(queryClient: QueryClient, key: unknown[], topics: string[] | null) {
26
+ const queryFn = vi.fn(async () => ({ n: queryFn.mock.calls.length }));
27
+ const observer = new QueryObserver(queryClient, {
28
+ queryKey: key,
29
+ queryFn,
30
+ ...(topics ? { meta: { [REALTIME_META_KEY]: topics } } : {}),
31
+ });
32
+ const unsubscribe = observer.subscribe(() => {});
33
+ return { queryFn, unsubscribe };
34
+ }
35
+
36
+ const settle = () => vi.advanceTimersByTimeAsync(300);
37
+
38
+ describe('bridgeQueryCache', () => {
39
+ it('refetches a tagged query on a message and on a gap, and leaves an untagged one alone', async () => {
40
+ const { server, client, queryClient } = setup();
41
+ const tagged = observe(queryClient, ['/apix/realtime_demo/pings/'], ['demo.pings']);
42
+ const untagged = observe(queryClient, ['/cfg/accounts/profile/'], null);
43
+ const stop = bridgeQueryCache(queryClient, client);
44
+ await settle();
45
+ expect(server.subscribers('demo.pings')).toBe(1);
46
+
47
+ // The first fetch, plus one when the subscription went live (a publication between them would be lost).
48
+ const afterLive = tagged.queryFn.mock.calls.length;
49
+ expect(afterLive).toBeGreaterThanOrEqual(1);
50
+ expect(untagged.queryFn).toHaveBeenCalledTimes(1);
51
+
52
+ server.publish('demo.pings', { id: 1 });
53
+ server.publish('demo.pings', { id: 2 });
54
+ await settle();
55
+ expect(tagged.queryFn).toHaveBeenCalledTimes(afterLive + 1); // one refetch per burst
56
+
57
+ server.bumpEpoch('demo.pings');
58
+ await settle();
59
+ expect(tagged.queryFn).toHaveBeenCalledTimes(afterLive + 2);
60
+ expect(untagged.queryFn).toHaveBeenCalledTimes(1);
61
+
62
+ stop();
63
+ tagged.unsubscribe();
64
+ untagged.unsubscribe();
65
+ });
66
+
67
+ it('subscribes a topic only while a tagged query has an observer, and releases it after the last one goes', async () => {
68
+ const { server, client, queryClient } = setup();
69
+ const stop = bridgeQueryCache(queryClient, client);
70
+ await settle();
71
+ expect(server.connections).toBe(0);
72
+
73
+ const first = observe(queryClient, ['/apix/realtime_demo/pings/', { page: 1 }], ['demo.pings']);
74
+ const second = observe(queryClient, ['/apix/realtime_demo/pings/', { page: 2 }], ['demo.pings']);
75
+ await settle();
76
+ expect(server.subscribers('demo.pings')).toBe(1);
77
+
78
+ first.unsubscribe();
79
+ await vi.advanceTimersByTimeAsync(2_000);
80
+ expect(server.subscribers('demo.pings')).toBe(1); // the second still watches it
81
+
82
+ second.unsubscribe();
83
+ await vi.advanceTimersByTimeAsync(1_000);
84
+ expect(server.subscribers('demo.pings')).toBe(1); // the client's delayed release (1.5 s) has not run yet
85
+ await vi.advanceTimersByTimeAsync(1_000);
86
+ expect(server.subscribers('demo.pings')).toBe(0);
87
+
88
+ // The queries are still cached (gcTime), with no observer: a message refetches nothing.
89
+ const calls = second.queryFn.mock.calls.length;
90
+ server.publish('demo.pings', { id: 3 });
91
+ await settle();
92
+ expect(second.queryFn).toHaveBeenCalledTimes(calls);
93
+
94
+ await vi.advanceTimersByTimeAsync(31_500);
95
+ expect(server.connections).toBe(0);
96
+ stop();
97
+ });
98
+
99
+ it('opens no socket when no query is tagged', async () => {
100
+ const { server, client, queryClient } = setup();
101
+ const untagged = observe(queryClient, ['/cfg/accounts/profile/'], null);
102
+ const stop = bridgeQueryCache(queryClient, client);
103
+ await vi.advanceTimersByTimeAsync(60_000);
104
+ expect(server.connections).toBe(0);
105
+ stop();
106
+ untagged.unsubscribe();
107
+ });
108
+ });
@@ -0,0 +1,64 @@
1
+ import { watchTopics } from '@djangocfg/realtime';
2
+
3
+ import type { Query, QueryClient } from '@tanstack/react-query';
4
+ import type { RealtimeClient, WatchTopicsOptions } from '@djangocfg/realtime';
5
+
6
+ /**
7
+ * The `meta` key a generated query carries its topics under: the concrete topic names of the operation's
8
+ * `invalidated_by` (`x-realtime-invalidates`), written by the generated `runtime/realtime-query.ts`.
9
+ */
10
+ export const REALTIME_META_KEY = 'realtimeTopics';
11
+
12
+ /** The topics a query is tagged with; `[]` for an untagged query. */
13
+ export function topicsOfQuery(query: Pick<Query, 'meta'>): string[] {
14
+ const topics = query.meta?.[REALTIME_META_KEY];
15
+ return Array.isArray(topics) ? topics.filter((topic): topic is string => typeof topic === 'string') : [];
16
+ }
17
+
18
+ const SYNC_EVENTS = new Set(['added', 'removed', 'observerAdded', 'observerRemoved', 'observerOptionsUpdated']);
19
+
20
+ /**
21
+ * Keeps the realtime subscriptions in step with the QueryCache: a topic is subscribed while at least one query
22
+ * tagged with it has an observer (a mounted hook), and released when the last one goes. The client's own delayed
23
+ * unsubscribe (1.5 s) absorbs a remount. A message, a gap or a fresh subscription going live invalidates the
24
+ * queries tagged with that topic, once per burst (`watchTopics`). Returns the function that stops it all.
25
+ */
26
+ export function bridgeQueryCache(
27
+ queryClient: QueryClient,
28
+ client: RealtimeClient,
29
+ options: WatchTopicsOptions = {},
30
+ ): () => void {
31
+ const cache = queryClient.getQueryCache();
32
+ const watched = new Map<string, () => void>();
33
+
34
+ const invalidate = (topic: string) => {
35
+ void queryClient.invalidateQueries({ predicate: (query) => topicsOfQuery(query).includes(topic) });
36
+ };
37
+
38
+ const sync = () => {
39
+ const wanted = new Set<string>();
40
+ for (const query of cache.getAll()) {
41
+ if (query.getObserversCount() === 0) continue;
42
+ for (const topic of topicsOfQuery(query)) wanted.add(topic);
43
+ }
44
+ for (const [topic, release] of watched) {
45
+ if (wanted.has(topic)) continue;
46
+ watched.delete(topic);
47
+ release();
48
+ }
49
+ for (const topic of wanted) {
50
+ if (!watched.has(topic)) watched.set(topic, watchTopics(client, [topic], () => invalidate(topic), options));
51
+ }
52
+ };
53
+
54
+ // Hooks below mount before this effect runs: their queries are already in the cache.
55
+ sync();
56
+ const unsubscribe = cache.subscribe((event) => {
57
+ if (SYNC_EVENTS.has(event.type)) sync();
58
+ });
59
+ return () => {
60
+ unsubscribe();
61
+ for (const release of watched.values()) release();
62
+ watched.clear();
63
+ };
64
+ }
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * The one sidebar button: same box, icon and position rules on mobile and desktop.
3
3
  * In the top bar it opens the sidebar; inside the sidebar header it closes or collapses it. Both are
4
- * `toggleSidebar`. `Button`'s `tooltip` names the action and shows the Cmd/Ctrl+B binding (it lives in ui-core's sidebar provider) for the viewer's system; none where the device cannot hover. The labels are plain
5
- * English: the layouts have no message catalogue (only a locale hook).
4
+ * `toggleSidebar`. No tooltip and no native title (decided 2026-11-04, `87a7b8019`): the icon is familiar and a hover
5
+ * card over it got in the way. `aria-label` names the action; Cmd/Ctrl+B still works through ui-core's sidebar
6
+ * provider. The labels are plain English: the layouts have no message catalogue (only a locale hook).
6
7
  */
7
8
 
8
9
  'use client';
@@ -31,7 +32,6 @@ export const PrivateSidebarTrigger = React.forwardRef<
31
32
  variant="ghost"
32
33
  size="icon"
33
34
  aria-label={label}
34
- tooltip={{ content: label, hotkey: 'mod+b', side: 'bottom', sideOffset: 8 }}
35
35
  className={cn(TRIGGER_CLASS, className)}
36
36
  onClick={(event) => {
37
37
  onClick?.(event);
@@ -14,7 +14,6 @@ This module provides shared TypeScript types used across all layout components i
14
14
  - **`AuthConfig`** - Authentication configuration
15
15
  - **`ErrorTrackingConfig`** - Error tracking settings
16
16
  - **`ErrorBoundaryConfig`** - Error boundary options
17
- - **`SWRConfigOptions`** - SWR data fetching configuration
18
17
 
19
18
  ### Layout Component Types
20
19
 
@@ -13,7 +13,6 @@
13
13
  export type {
14
14
  ThemeConfig,
15
15
  ThemeStylePresetId,
16
- SWRConfigOptions,
17
16
  } from './providers.types';
18
17
 
19
18
  // External provider configs (re-export for convenience)
@@ -21,7 +21,9 @@ import type { ErrorBoundaryConfig, ErrorTrackingConfig } from '../../components/
21
21
  export type NextIntlRouting = object & { __nextIntlRouting?: never };
22
22
 
23
23
  // Import local provider configs
24
- import type { ThemeConfig, SWRConfigOptions } from './providers.types';
24
+ import type { ThemeConfig } from './providers.types';
25
+ import type { QueryClient } from '@tanstack/react-query';
26
+ import type { QueryDevtoolsLoader } from '../AppLayout/query/AppQueryProvider';
25
27
  import type { DevtoolsProps } from '@djangocfg/devtools';
26
28
  import type { RealtimeConfig } from '@djangocfg/realtime/react';
27
29
 
@@ -67,8 +69,19 @@ export interface BaseLayoutProps {
67
69
  /** Error tracking configuration (from components/errors) */
68
70
  errorTracking?: ErrorTrackingConfig;
69
71
 
70
- /** SWR configuration */
71
- swr?: SWRConfigOptions;
72
+ /**
73
+ * The app's own React Query client. Without it `BaseApp` reuses a QueryClient provided above it, else creates one
74
+ * per mount with django-cfg's defaults (`createAppQueryClient`: no retry on 4xx, up to 2 on a network error or a
75
+ * 5xx, `throwOnError: false`, `staleTime` 30 s, refetch on focus, mutations not retried). A client passed here
76
+ * is used as it is: its defaults are not merged.
77
+ */
78
+ queryClient?: QueryClient;
79
+
80
+ /**
81
+ * React Query Devtools, development builds only, loaded on demand:
82
+ * `queryDevtools={() => import('@tanstack/react-query-devtools')}` (the app installs the package).
83
+ */
84
+ queryDevtools?: QueryDevtoolsLoader;
72
85
 
73
86
  /** Error boundary configuration (from components/errors, enabled by default) */
74
87
  errorBoundary?: ErrorBoundaryConfig;
@@ -84,8 +97,9 @@ export interface BaseLayoutProps {
84
97
  /**
85
98
  * Realtime (`@djangocfg/realtime`): one lazy WebSocket per tab for `useTopic`. On by default and free until a
86
99
  * component subscribes. The URL defaults to the API origin (`realtime.apiUrl`, `apiUrl`, `auth.apiUrl`, then
87
- * `NEXT_PUBLIC_API_URL`) plus `/ws`, `wss:` for `https:`. A gap refetches the SWR keys tagged with the topic unless
88
- * `onGap` is given. `false` turns it off.
100
+ * `NEXT_PUBLIC_API_URL`) plus `/ws`, `wss:` for `https:`. A mounted query tagged with a topic
101
+ * (`invalidated_by` on its view) is invalidated on each message and gap of that topic; `onGap` replaces the
102
+ * default for `useTopic` subscriptions. `false` turns it off.
89
103
  */
90
104
  realtime?: RealtimeConfig | false;
91
105
 
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Provider Configuration Types
3
3
  *
4
- * Configuration types for layout providers (theme, SWR, MCP chat)
4
+ * Configuration types for layout providers (theme, MCP chat)
5
5
  * Note: Analytics, PWA, Push, and Error types are defined in their respective modules
6
6
  */
7
7
 
@@ -16,12 +16,3 @@ export interface ThemeConfig {
16
16
  storageKey?: string;
17
17
  }
18
18
 
19
- // ============================================================================
20
- // SWR Configuration
21
- // ============================================================================
22
-
23
- export interface SWRConfigOptions {
24
- revalidateOnFocus?: boolean;
25
- revalidateOnReconnect?: boolean;
26
- dedupingInterval?: number;
27
- }
@@ -1,7 +1,6 @@
1
1
  'use client';
2
2
 
3
3
  import React, { useMemo, useRef, useState } from 'react';
4
- import { SWRConfig } from 'swr';
5
4
 
6
5
  import {
7
6
  type AuthStep,
@@ -55,9 +54,6 @@ function formatRateLimit(seconds: number): string {
55
54
  return `${seconds}s`;
56
55
  }
57
56
 
58
- /** Fresh SWR cache per story: the list is cached for an hour, which would leak one story's providers into the next. */
59
- const freshSwrCache = () => new Map();
60
-
61
57
  function WithServerOAuth({ oauthProviders, oauthFromServer: _, ...rest }: MockAuthFormProviderProps) {
62
58
  const { providers, isReady } = useOAuthProviders();
63
59
  const ids = useMemo(() => providers.map((p) => p.id), [providers]);
@@ -67,9 +63,7 @@ function WithServerOAuth({ oauthProviders, oauthFromServer: _, ...rest }: MockAu
67
63
 
68
64
  export const MockAuthFormProvider: React.FC<MockAuthFormProviderProps> = (props) =>
69
65
  props.oauthFromServer ? (
70
- <SWRConfig value={{ provider: freshSwrCache }}>
71
- <WithServerOAuth {...props} />
72
- </SWRConfig>
66
+ <WithServerOAuth {...props} />
73
67
  ) : (
74
68
  <MockAuthFormProviderBase {...props} />
75
69
  );
@@ -1,20 +0,0 @@
1
- 'use client';
2
-
3
- import { useTopicRefresh } from '@djangocfg/realtime/react';
4
-
5
- import type { Middleware, SWRHook } from 'swr';
6
-
7
- /**
8
- * Zero-code refresh: every `useSWR` whose key is tagged with a topic
9
- * (`['orders:42', …]`, see `isKeyForTopic`) watches that topic while mounted
10
- * and revalidates on each publication and on a gap, coalesced to one
11
- * revalidation per ~250 ms. Untagged keys cost nothing.
12
- */
13
- export const realtimeRefresh: Middleware = (useSWRNext: SWRHook) =>
14
- function useRealtimeRefresh(key, fetcher, config) {
15
- const swr = useSWRNext(key, fetcher, config);
16
- useTopicRefresh(key, () => {
17
- void swr.mutate();
18
- });
19
- return swr;
20
- };