session-provider.tsx 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. /** Internal React bindings for the renderer host and active session provide bundle. */
  2. import { createContext, useContext, type ReactNode } from 'react'
  3. import type {
  4. HostObservable, MaybeSnapshotSelectorHook, SessionMaybeProvideInfo, SessionProvideInfo,
  5. SlotRendererHost, SnapshotSelectorHook,
  6. } from '@deepseek-ai/dsh-client-ui-slots'
  7. import { bindSnapshotSelector } from './bind.ts'
  8. /**
  9. * A missing-provider assembly error: the shell wired the tree wrong. The slot
  10. * error boundary rethrows this class so misassembly stays fail-loud while
  11. * registrant errors (inject factories, entry components) are contained
  12. * per entry.
  13. */
  14. export class SlotAssemblyError extends Error {}
  15. /** In-package renderer host context. */
  16. export const HostContext = createContext<SlotRendererHost | null>(null)
  17. /**
  18. * Read the installed renderer host; throws outside the rendered root tree
  19. * (framework components must not render detached from the renderer).
  20. * @returns the host surface.
  21. */
  22. export function useHost(): SlotRendererHost {
  23. const host = useContext(HostContext)
  24. if (!host) throw new SlotAssemblyError('slot machinery rendered outside the installed renderer tree')
  25. return host
  26. }
  27. const BindingContext = createContext<SessionMaybeProvideInfo | null>(null)
  28. /** Read the current-session-optional bundle supplied at the root. */
  29. export function useSessionMaybeProvideInfo(): SessionMaybeProvideInfo {
  30. const info = useContext(BindingContext)
  31. if (!info) throw new SlotAssemblyError('session-aware slot rendered outside the root binding provider')
  32. return info
  33. }
  34. /**
  35. * Read the enclosing session provide bundle; throws outside a SessionProvider
  36. * subtree (session slots must not render without a session).
  37. * @returns the enclosing bundle.
  38. */
  39. export function useSessionProvideInfo(): SessionProvideInfo {
  40. const info = useSessionMaybeProvideInfo()
  41. if (info.sessionId === undefined) throw new SlotAssemblyError('strict session slot rendered without a session')
  42. return info as SessionProvideInfo
  43. }
  44. /**
  45. * Identity-stable selector hook per host observable. uSES resubscribes when
  46. * the subscribe reference changes, so the bound hook must be created once per
  47. * source — cached here by source identity (sources are host-owned singletons).
  48. * @param source - host-provided observable.
  49. * @returns the cached selector hook.
  50. */
  51. export function observableHook<T>(source: HostObservable<T>): SnapshotSelectorHook<T> {
  52. let hook = hookCache.get(source)
  53. if (hook === undefined) {
  54. hook = bindSnapshotSelector(source)
  55. hookCache.set(source, hook)
  56. }
  57. return hook as SnapshotSelectorHook<T>
  58. }
  59. const hookCache = new WeakMap<object, unknown>()
  60. const absentSource: HostObservable<undefined> = {
  61. getSnapshot: () => undefined,
  62. subscribe: () => () => {},
  63. }
  64. /** Bind a source that disappears with the current session to an optional selector hook. */
  65. export function maybeObservableHook<T>(source: HostObservable<T> | undefined): MaybeSnapshotSelectorHook<T> {
  66. if (source !== undefined) return observableHook(source)
  67. return useAbsentSnapshot as MaybeSnapshotSelectorHook<T>
  68. }
  69. function useAbsentSnapshot<S>(_selector: (snapshot: never) => S, _equal?: (a: S, b: S) => boolean): S | undefined {
  70. return observableHook(absentSource)(() => undefined)
  71. }
  72. /**
  73. * Root-level binding provider. It follows current selection without a key, so
  74. * session-maybe entries retain their React identity while the context value
  75. * moves between absent and definite session bundles.
  76. */
  77. export function SessionMaybeProvider({ children }: { children: ReactNode }) {
  78. const host = useHost()
  79. const id = observableHook(host.sessions.current)((s) => s)
  80. return (
  81. <BindingContext.Provider value={host.sessions.maybeProvideInfo(id)}>
  82. {children}
  83. </BindingContext.Provider>
  84. )
  85. }
  86. /** SessionProvider surface: render-prop body plus the no-session branch. */
  87. export interface SessionProviderProps {
  88. /** No-session body (also covers a current id whose session cannot be resolved). */
  89. empty?: (() => ReactNode) | undefined
  90. /** Session body; remounted per session via key={sessionId}. */
  91. children: (sessionId: string) => ReactNode
  92. }
  93. /**
  94. * Framework-wired session area: subscribes to the host's current-session
  95. * source, resolves the session cell, and remounts the body under
  96. * `key={sessionId}` so a session switch rebuilds the session subtree. This
  97. * dependency-inverted layer uses plain string ids; `PropsRuntime` applies the
  98. * branded type at the component boundary.
  99. */
  100. export function SessionProvider({ empty, children }: SessionProviderProps) {
  101. const host = useHost()
  102. const id = observableHook(host.sessions.current)((s) => s)
  103. const info = id === undefined ? undefined : host.sessions.provideInfo(id)
  104. if (id === undefined || info === undefined) return <>{empty?.() ?? null}</>
  105. return (
  106. <BindingContext.Provider value={info} key={id}>
  107. {children(id)}
  108. </BindingContext.Provider>
  109. )
  110. }