hooks.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. 'use client'
  2. import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react'
  3. import { useRouter } from 'next/navigation'
  4. import {
  5. recordRoom,
  6. type PresenceUser,
  7. type RecordChange,
  8. type RecordKind,
  9. } from '@/lib/realtime/events'
  10. import type { Me } from './manager'
  11. import { useRealtime, useRealtimeState } from './RealtimeProvider'
  12. import { createRefreshGovernor } from './refresh-governor'
  13. /**
  14. * What a page uses. Everything here is a thin layer over the collaboration
  15. * manager, and every one of them is safe to call when there is no provider:
  16. * the page renders, and does not update by itself.
  17. *
  18. * Making a new kind of page collaborative is two lines: `useLiveRecord` to
  19. * stay current, and `<PresenceChips>` to show who else is there.
  20. */
  21. /**
  22. * Tells you when this record changed somewhere else, and after a
  23. * reconnection, when something may have changed while the socket was down.
  24. *
  25. * The handler is called with the change for the first case and with `null`
  26. * for the second, because a resync has no single change to describe.
  27. */
  28. export function useRecordChanges(
  29. kind: RecordKind,
  30. id: string | null | undefined,
  31. handler: (change: RecordChange | null) => void
  32. ): void {
  33. const realtime = useRealtime()
  34. const ref = useRef(handler)
  35. useEffect(() => {
  36. ref.current = handler
  37. }, [handler])
  38. useEffect(() => {
  39. if (!realtime || !id) return
  40. const stopWatching = realtime.watch(recordRoom(kind, id), (change) => ref.current(change))
  41. const stopResync = realtime.onResync(() => ref.current(null))
  42. return () => {
  43. stopWatching()
  44. stopResync()
  45. }
  46. }, [realtime, kind, id])
  47. }
  48. /**
  49. * Whether a change is this page's own save coming back, which it must not
  50. * answer: the page has already shown the result, and re-reading would fight
  51. * the form somebody is typing in.
  52. *
  53. * Only a change from another web page of the same person can be that. One
  54. * from the technician app is never an echo of a browser, whoever is signed
  55. * in on the phone, and a one-person shop is signed in on both: for a while
  56. * the desk ignored its own phone finishing a job, because the check read the
  57. * user and not the source, and the phone holds no presence to say it is a
  58. * second device.
  59. *
  60. * Between two of the person's own web pages, presence decides: a save on the
  61. * laptop has to reach their own tablet in the bay, and the room's `devices`
  62. * count says whether there is one.
  63. */
  64. export function isOwnEcho(
  65. change: RecordChange,
  66. me: Me | null | undefined,
  67. presence: PresenceUser[] | undefined
  68. ): boolean {
  69. if (change.by.source !== 'web') return false
  70. if (!change.by.userId || !me || change.by.userId !== me.userId) return false
  71. const mine = presence?.find((user) => user.userId === me.userId)
  72. return !mine || mine.devices < 2
  73. }
  74. /**
  75. * The record kept current on screen: re-read the page's own server data when
  76. * it changes somewhere else.
  77. *
  78. * Your own changes are skipped, because the page that made them has already
  79. * shown the result and re-reading would fight the form somebody is typing in.
  80. * When and how often the re-read happens is the governor's decision
  81. * (refresh-governor.ts), which is what makes it impossible for this hook to
  82. * turn into a page that polls.
  83. */
  84. export function useLiveRecord(
  85. kind: RecordKind,
  86. id: string | null | undefined,
  87. options: { onChange?: (change: RecordChange | null) => void } = {}
  88. ): void {
  89. const router = useRouter()
  90. const realtime = useRealtime()
  91. const onChange = useRef(options.onChange)
  92. useEffect(() => {
  93. onChange.current = options.onChange
  94. }, [options.onChange])
  95. const governor = useRef<ReturnType<typeof createRefreshGovernor> | null>(null)
  96. useEffect(() => {
  97. const created = createRefreshGovernor({
  98. refresh: () => router.refresh(),
  99. onPressure: (gapMs) => {
  100. if (process.env.NODE_ENV !== 'production') {
  101. console.warn(
  102. `[realtime] ${kind}:${id} is changing unusually often; re-reading every ${gapMs} ms`
  103. )
  104. }
  105. },
  106. })
  107. governor.current = created
  108. const onVisible = () => {
  109. if (document.visibilityState === 'visible') created.visible()
  110. }
  111. document.addEventListener('visibilitychange', onVisible)
  112. return () => {
  113. document.removeEventListener('visibilitychange', onVisible)
  114. created.dispose()
  115. governor.current = null
  116. }
  117. }, [router, kind, id])
  118. useRecordChanges(
  119. kind,
  120. id,
  121. useCallback(
  122. (change) => {
  123. if (
  124. change &&
  125. id &&
  126. isOwnEcho(change, realtime?.getState().me, realtime?.presenceOf(recordRoom(kind, id)))
  127. ) {
  128. return
  129. }
  130. onChange.current?.(change)
  131. governor.current?.request()
  132. },
  133. [realtime, kind, id]
  134. )
  135. )
  136. }
  137. const NOBODY: PresenceUser[] = []
  138. const nothingToWatch = () => () => undefined
  139. /**
  140. * Who else has this record open.
  141. *
  142. * Standing in the room is what makes this browser appear in everyone else's
  143. * chips, so a page that only wants to watch changes should use
  144. * `useRecordChanges` and not this. Leaving happens on unmount, and on the
  145. * socket closing. Any number of components may call this for one record:
  146. * the manager counts them, and the server sees one person.
  147. */
  148. export function useRecordPresence(
  149. kind: RecordKind,
  150. id: string | null | undefined
  151. ): { others: PresenceUser[]; me: Me | null } {
  152. const realtime = useRealtime()
  153. const { me } = useRealtimeState()
  154. const room = id ? recordRoom(kind, id) : null
  155. useEffect(() => {
  156. if (!realtime || !room) return
  157. return realtime.join(room)
  158. }, [realtime, room])
  159. const subscribe = useMemo(
  160. () =>
  161. realtime && room
  162. ? (onChange: () => void) => realtime.watchPresence(room, onChange)
  163. : nothingToWatch,
  164. [realtime, room]
  165. )
  166. const everyone = useSyncExternalStore(
  167. subscribe,
  168. () => (realtime && room ? realtime.presenceOf(room) : NOBODY),
  169. () => NOBODY
  170. )
  171. const others = useMemo(
  172. () => everyone.filter((user) => user.userId !== me?.userId),
  173. [everyone, me?.userId]
  174. )
  175. return { others, me }
  176. }