Skip to content

Commit 4613190

Browse files
committed
working
1 parent ba6d873 commit 4613190

File tree

10 files changed

+245
-120
lines changed

10 files changed

+245
-120
lines changed

examples/react/todo/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
"private": true,
44
"version": "0.0.25",
55
"dependencies": {
6-
"@tanstack/db-collections": "^0.0.23",
6+
"@tanstack/db-collections": "workspace:*",
77
"@tanstack/db-devtools": "workspace:*",
88
"@tanstack/query-core": "^5.81.5",
9-
"@tanstack/react-db": "^0.0.20",
9+
"@tanstack/react-db": "workspace:*",
1010
"@tanstack/react-db-devtools": "workspace:*",
1111
"@tanstack/react-router": "^1.125.6",
1212
"@tanstack/react-router-devtools": "^1.127.3",

examples/react/todo/src/lib/collections.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createCollection } from "@tanstack/react-db"
2+
import { initializeDbDevtools } from "@tanstack/react-db-devtools"
23
import {
34
electricCollectionOptions,
45
queryCollectionOptions,
@@ -10,6 +11,10 @@ import { api } from "./api"
1011
// Create a query client for query collections
1112
const queryClient = new QueryClient()
1213

14+
// Initialize DB devtools early (idempotent - safe to call multiple times)
15+
console.log('🏗️ Collections.ts: Initializing devtools before creating collections...')
16+
initializeDbDevtools()
17+
1318
// Electric Todo Collection
1419
export const electricTodoCollection = createCollection(
1520
electricCollectionOptions({
@@ -170,3 +175,5 @@ export const queryConfigCollection = createCollection(
170175
},
171176
})
172177
)
178+
179+

examples/react/todo/src/main.tsx

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,8 @@ import React from "react"
22
import { createRoot } from "react-dom/client"
33
import { RouterProvider } from "@tanstack/react-router"
44
import { createRouter } from "./router"
5-
import { initializeDbDevtools } from "@tanstack/react-db-devtools"
65
import "./index.css"
76

8-
// Initialize DB devtools BEFORE any collections are created
9-
if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {
10-
console.log('Main: Initializing devtools early...')
11-
initializeDbDevtools()
12-
}
13-
147
const router = createRouter()
158

169
createRoot(document.getElementById(`root`)!).render(

packages/db-devtools/src/devtools.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,23 @@ import type { DbDevtoolsRegistry } from "./types"
88
* Collections will automatically register themselves if this registry is present.
99
*/
1010
export function initializeDbDevtools(): void {
11-
initializeDevtoolsRegistry()
11+
// SSR safety check
12+
if (typeof window === 'undefined') {
13+
return
14+
}
15+
16+
// Initialize the registry
17+
const registry = initializeDevtoolsRegistry()
18+
19+
// Set up global registration function that collections can call
20+
;(window as any).__TANSTACK_DB_DEVTOOLS_REGISTER__ = (collection: any) => {
21+
registry.registerCollection(collection)
22+
}
23+
24+
// Set up global unregistration function
25+
;(window as any).__TANSTACK_DB_DEVTOOLS_UNREGISTER__ = (id: string) => {
26+
registry.unregisterCollection(id)
27+
}
1228
}
1329

1430
/**

packages/db-devtools/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,4 @@ export type { TanstackDbDevtoolsConfig } from "./TanstackDbDevtools"
2020
// export { DbDevtoolsPanel } from "./DbDevtoolsPanel"
2121

2222
// Export the initialization function
23-
export { initializeDbDevtools } from "./registry"
23+
export { initializeDbDevtools } from "./devtools"

packages/db-devtools/src/registry.ts

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,15 @@ class DbDevtoolsRegistryImpl implements DbDevtoolsRegistry {
1616
}
1717

1818
registerCollection = (collection: any): void => {
19+
console.log('Registry: Registering collection', {
20+
id: collection.id,
21+
type: this.detectCollectionType(collection),
22+
status: collection.status,
23+
size: collection.size,
24+
hasTransactions: collection.transactions.size > 0,
25+
registrySize: this.collections.size
26+
})
27+
1928
const metadata: CollectionMetadata = {
2029
id: collection.id,
2130
type: this.detectCollectionType(collection),
@@ -40,6 +49,12 @@ class DbDevtoolsRegistryImpl implements DbDevtoolsRegistry {
4049
}
4150

4251
this.collections.set(collection.id, entry)
52+
53+
console.log('Registry: Collection registered successfully', {
54+
id: collection.id,
55+
totalCollections: this.collections.size,
56+
allCollectionIds: Array.from(this.collections.keys())
57+
})
4358

4459
// Track performance for live queries
4560
if (this.isLiveQuery(collection)) {
@@ -76,9 +91,11 @@ class DbDevtoolsRegistryImpl implements DbDevtoolsRegistry {
7691
}
7792

7893
getAllCollectionMetadata = (): Array<CollectionMetadata> => {
94+
console.log('Registry: getAllCollectionMetadata called, total collections:', this.collections.size)
95+
7996
const results: Array<CollectionMetadata> = []
8097

81-
for (const [_id, entry] of this.collections) {
98+
for (const [id, entry] of this.collections) {
8299
const collection = entry.weakRef.deref()
83100
if (collection) {
84101
// Collection is still alive, update metadata
@@ -88,14 +105,22 @@ class DbDevtoolsRegistryImpl implements DbDevtoolsRegistry {
88105
entry.metadata.transactionCount = collection.transactions.size
89106
entry.metadata.lastUpdated = new Date()
90107
results.push({ ...entry.metadata })
108+
console.log('Registry: Found live collection:', {
109+
id,
110+
status: collection.status,
111+
size: collection.size,
112+
type: entry.metadata.type
113+
})
91114
} else {
92115
// Collection was garbage collected, mark it
93116
entry.metadata.status = `cleaned-up`
94117
entry.metadata.lastUpdated = new Date()
95118
results.push({ ...entry.metadata })
119+
console.log('Registry: Found GC\'d collection:', id)
96120
}
97121
}
98122

123+
console.log('Registry: Returning metadata for', results.length, 'collections')
99124
return results
100125
}
101126

@@ -310,23 +335,4 @@ export function initializeDevtoolsRegistry(): DbDevtoolsRegistry {
310335
return (window as any).__TANSTACK_DB_DEVTOOLS__ as DbDevtoolsRegistry
311336
}
312337

313-
// Initialize devtools and set up automatic collection registration
314-
export function initializeDbDevtools(): void {
315-
// SSR safety check
316-
if (typeof window === 'undefined') {
317-
return
318-
}
319-
320-
// Initialize the registry
321-
const registry = initializeDevtoolsRegistry()
322338

323-
// Set up global registration function that collections can call
324-
;(window as any).__TANSTACK_DB_DEVTOOLS_REGISTER__ = (collection: any) => {
325-
registry.registerCollection(collection)
326-
}
327-
328-
// Set up global unregistration function
329-
;(window as any).__TANSTACK_DB_DEVTOOLS_UNREGISTER__ = (id: string) => {
330-
registry.unregisterCollection(id)
331-
}
332-
}

packages/db/src/collection.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,21 @@ export const collectionsStore = new Map<string, CollectionImpl<any, any>>()
2424

2525
// Check for devtools registry and register collection if available
2626
function registerWithDevtools(collection: CollectionImpl<any, any, any>): void {
27-
if (typeof window !== `undefined` && (window as any).__TANSTACK_DB_DEVTOOLS_REGISTER__) {
28-
(window as any).__TANSTACK_DB_DEVTOOLS_REGISTER__(collection)
27+
if (typeof window !== `undefined`) {
28+
console.log('Collection created, checking for devtools registration:', {
29+
collectionId: collection.id,
30+
registryAvailable: !!(window as any).__TANSTACK_DB_DEVTOOLS_REGISTER__,
31+
registryExists: !!(window as any).__TANSTACK_DB_DEVTOOLS__
32+
})
33+
34+
if ((window as any).__TANSTACK_DB_DEVTOOLS_REGISTER__) {
35+
(window as any).__TANSTACK_DB_DEVTOOLS_REGISTER__(collection)
36+
;(collection as any).isRegisteredWithDevtools = true
37+
console.log('Collection registered with devtools:', collection.id)
38+
} else {
39+
;(collection as any).isRegisteredWithDevtools = false
40+
console.warn('Devtools registry not available for collection:', collection.id)
41+
}
2942
}
3043
}
3144

@@ -238,6 +251,7 @@ export class CollectionImpl<
238251
private gcTimeoutId: ReturnType<typeof setTimeout> | null = null
239252
private preloadPromise: Promise<void> | null = null
240253
private syncCleanupFn: (() => void) | null = null
254+
private isRegisteredWithDevtools = false
241255

242256
/**
243257
* Register a callback to be executed on the next commit
@@ -548,6 +562,7 @@ export class CollectionImpl<
548562
// Unregister from devtools if available
549563
if (typeof window !== `undefined` && (window as any).__TANSTACK_DB_DEVTOOLS_UNREGISTER__) {
550564
(window as any).__TANSTACK_DB_DEVTOOLS_UNREGISTER__(this.id)
565+
this.isRegisteredWithDevtools = false
551566
}
552567

553568
// Clear data
@@ -605,6 +620,11 @@ export class CollectionImpl<
605620
this.activeSubscribersCount++
606621
this.cancelGCTimer()
607622

623+
// Re-register with devtools if not already registered (handles timing issues)
624+
if (!this.isRegisteredWithDevtools) {
625+
registerWithDevtools(this)
626+
}
627+
608628
// Start sync if collection was cleaned up
609629
if (this._status === `cleaned-up` || this._status === `idle`) {
610630
this.startSync()

packages/react-db-devtools/src/ReactDbDevtools.tsx

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { useEffect, useRef, useState } from "react"
33
import { TanstackDbDevtools } from "@tanstack/db-devtools"
44
import type { TanstackDbDevtoolsConfig } from "@tanstack/db-devtools"
5+
import { initializeDbDevtools } from "./index"
56

67
export interface TanStackReactDbDevtoolsProps extends TanstackDbDevtoolsConfig {
78
// Additional React-specific props if needed
@@ -29,10 +30,11 @@ export function TanStackReactDbDevtools(props: TanStackReactDbDevtoolsProps = {}
2930
// Set flag to prevent multiple initializations
3031
initializingRef.current = true
3132

32-
// Note: Devtools registry is now initialized in main.tsx before collections are created
33-
console.log('ReactDbDevtools: Skipping devtools initialization (done in main.tsx)')
34-
35-
console.log('ReactDbDevtools: Creating TanstackDbDevtools instance')
33+
// Note: Devtools registry is now initialized in collections.ts before collections are created
34+
console.log('ReactDbDevtools: Calling initializeDbDevtools as backup (also called in collections.ts)')
35+
initializeDbDevtools()
36+
37+
console.log('ReactDbDevtools: Creating TanstackDbDevtools instance')
3638
const devtoolsInstance = new TanstackDbDevtools(props)
3739

3840
try {

0 commit comments

Comments
 (0)