Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions packages/kit/src/client/rpc-shared-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,26 @@ import { createSharedState } from '../utils/shared-state'

export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcSharedStateHost {
const sharedState = new Map<string, SharedState<any>>()
const initialValues = new Map<string, any>()
const isStaticBackend = rpc.connectionMeta.backend === 'static'

function mergeWithInitialValue(key: string, serverState: any): any {
const initial = initialValues.get(key)
if (initial && typeof initial === 'object' && !Array.isArray(initial)
&& typeof serverState === 'object' && !Array.isArray(serverState)) {
return { ...initial, ...serverState }
}
return serverState
}

rpc.client.register({
name: 'devtoolskit:internal:rpc:client-state:updated',
type: 'event',
handler: (key: string, fullState: any, syncId: string) => {
const state = sharedState.get(key)
if (!state || state.syncIds.has(syncId))
return
state.mutate(() => fullState, syncId)
state.mutate(() => mergeWithInitialValue(key, fullState), syncId)
},
})

Expand Down Expand Up @@ -52,6 +62,9 @@ export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcShare
return {
keys: () => Array.from(sharedState.keys()),
get: async <T extends object>(key: string, options?: RpcSharedStateGetOptions<T>) => {
if (options?.initialValue !== undefined) {
initialValues.set(key, options.initialValue)
}
if (sharedState.has(key)) {
return sharedState.get(key)!
}
Expand All @@ -70,7 +83,7 @@ export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcShare
rpc.call('devtoolskit:internal:rpc:server-state:get', key)
.then((serverState) => {
if (serverState !== undefined)
state.mutate(() => serverState)
state.mutate(() => mergeWithInitialValue(key, serverState))
})
.catch((error) => {
console.error('Error getting server state', error)
Expand All @@ -79,8 +92,8 @@ export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcShare
return state
}
else {
const initialValue = await rpc.call('devtoolskit:internal:rpc:server-state:get', key) as T
state.mutate(() => initialValue)
const serverValue = await rpc.call('devtoolskit:internal:rpc:server-state:get', key) as T
state.mutate(() => mergeWithInitialValue(key, serverValue))
sharedState.set(key, state)
registerSharedState(key, state)
return state
Expand Down
Loading