index.ts
This file
Path
src/jsx/hooks/index.ts
437 lines · 12.7 KiB · TypeScript
Last changed by
Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–317why, one step back1import type { JSX } from '../base'2import { DOM_STASH } from '../constants'3import { buildDataStack, update } from '../dom/render'4import type { Context, Node, NodeObject, PendingType, UpdateHook } from '../dom/render'56type UpdateStateFunction<T> = (newState: T | ((currentState: T) => T)) => void78const STASH_SATE = 09export const STASH_EFFECT = 110const STASH_CALLBACK = 211const STASH_MEMO = 312const STASH_REF = 41314export type EffectData = [15 readonly unknown[] | undefined, // deps16 (() => void | (() => void)) | undefined, // layout effect17 (() => void) | undefined, // cleanup18 (() => void) | undefined, // effect19 (() => void) | undefined, // insertion effect20]2122const resolvedPromiseValueMap: WeakMap<Promise<unknown>, unknown> = new WeakMap<23 Promise<unknown>,24 unknown25>()2627const isDepsChanged = (28 prevDeps: readonly unknown[] | undefined,29 deps: readonly unknown[] | undefined30): boolean =>31 !prevDeps ||32 !deps ||33 prevDeps.length !== deps.length ||34 deps.some((dep, i) => dep !== prevDeps[i])3536let viewTransitionState:37 | [38 boolean, // isUpdating39 boolean, // useViewTransition() is called40 ]41 | undefined = undefined4243const documentStartViewTransition: (cb: () => void) => { finished: Promise<void> } = (cb) => {44 // eslint-disable-next-line @typescript-eslint/no-explicit-any45 if ((document as any)?.startViewTransition) {46 // eslint-disable-next-line @typescript-eslint/no-explicit-any47 return (document as any).startViewTransition(cb)48 } else {49 cb()50 return { finished: Promise.resolve() }51 }52}5354let updateHook: UpdateHook | undefined = undefined55const viewTransitionHook = (56 context: Context,57 node: Node,58 cb: (context: Context) => void59): Promise<void> => {60 const state: [boolean, boolean] = [true, false]61 let lastVC = node.vC62 return documentStartViewTransition(() => {63 if (lastVC === node.vC) {64 viewTransitionState = state65 cb(context)66 viewTransitionState = undefined67 lastVC = node.vC68 }69 }).finished.then(() => {70 if (state[1] && lastVC === node.vC) {71 state[0] = false72 viewTransitionState = state73 cb(context)74 viewTransitionState = undefined75 }76 })77}7879export const startViewTransition = (callback: () => void): void => {80 updateHook = viewTransitionHook8182 try {83 callback()84 } finally {85 updateHook = undefined86 }87}8889export const useViewTransition = (): [boolean, (callback: () => void) => void] => {90 const buildData = buildDataStack.at(-1) as [Context, NodeObject]91 if (!buildData) {92 return [false, () => {}]93 }9495 if (viewTransitionState) {96 viewTransitionState[1] = true97 }98 return [!!viewTransitionState?.[0], startViewTransition]99}100101// PendingType is defined in "../dom/render", 3 is used for useDeferredValue102const pendingStack: [PendingType | 3, Promise<void>][] = []103const runCallback = (type: PendingType, callback: Function): void => {104 let resolve: (() => void) | undefined105 const promise = new Promise<void>((r) => (resolve = r))106 pendingStack.push([type, promise])107 try {108 const res = callback()109 if (res instanceof Promise) {110 res.then(resolve, resolve)111 } else {112 resolve!()113 }114 } finally {115 pendingStack.pop()116 }117}118119export const startTransition = (callback: () => void): void => {120 runCallback(1, callback)121}122const startTransitionHook = (callback: () => void | Promise<void>): void => {123 runCallback(2, callback)124}125126export const useTransition = (): [boolean, (callback: () => void | Promise<void>) => void] => {127 const buildData = buildDataStack.at(-1) as [Context, NodeObject]128 if (!buildData) {129 return [false, () => {}]130 }131132 const [error, setError] = useState<[Error]>()133 const [state, updateState] = useState<boolean>()134 if (error) {135 throw error[0]136 }137 const startTransitionLocalHook = useCallback<typeof startTransitionHook>(138 (callback) => {139 startTransitionHook(() => {140 updateState((state) => !state)141 let res = callback()142 if (res instanceof Promise) {143 res = res.catch((e) => {144 setError([e])145 })146 }147 return res148 })149 },150 [state]151 )152153 const [context] = buildData154 return [context[0] === 2, startTransitionLocalHook]155}156157type UseDeferredValue = <T>(value: T, initialValue?: T) => T158export const useDeferredValue: UseDeferredValue = <T>(value: T, ...rest: [T | undefined]): T => {159 const [values, setValues] = useState<[T, T]>(160 (rest.length ? [rest[0], rest[0]] : [value, value]) as [T, T]161 )162 if (Object.is(values[1], value)) {163 return values[1]164 }165166 pendingStack.push([3, Promise.resolve()])167 updateHook = async (context: Context, _, cb: (context: Context) => void) => {168 cb(context)169 values[0] = value170 }171 setValues([values[0], value])172 updateHook = undefined173 pendingStack.pop()174175 return values[0]176}177178type UseStateType = {179 <T>(initialState: T | (() => T)): [T, UpdateStateFunction<T>]180 <T = undefined>(): [T | undefined, UpdateStateFunction<T | undefined>]181}182export const useState: UseStateType = <T>(183 initialState?: T | (() => T)184): [T, UpdateStateFunction<T>] => {185 const resolveInitialState = () =>186 typeof initialState === 'function' ? (initialState as () => T)() : (initialState as T)187188 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]189 if (!buildData) {190 return [resolveInitialState(), () => {}]191 }192 const [, node] = buildData193194 const stateArray = (node[DOM_STASH][1][STASH_SATE] ||= [])195 const hookIndex = node[DOM_STASH][0]++196197 return (stateArray[hookIndex] ||= [198 resolveInitialState(),199 (newState: T | ((currentState: T) => T)) => {200 const localUpdateHook = updateHook201 const stateData = stateArray[hookIndex]202 if (typeof newState === 'function') {203 newState = (newState as (currentState: T) => T)(stateData[0])204 }205206 if (!Object.is(newState, stateData[0])) {207 stateData[0] = newState208 if (pendingStack.length) {209 const [pendingType, pendingPromise] = pendingStack.at(-1) as [210 PendingType | 3,211 Promise<void>,212 ]213 Promise.all([214 pendingType === 3215 ? node216 : update([pendingType, false, localUpdateHook as UpdateHook], node),217 pendingPromise,218 ]).then(([node]) => {219 if (!node || !(pendingType === 2 || pendingType === 3)) {220 return221 }222223 const lastVC = node.vC224225 const addUpdateTask = () => {226 setTimeout(() => {227 // return if `node` is rerendered after current transition228 if (lastVC !== node.vC) {229 return230 }231 update([pendingType === 3 ? 1 : 0, false, localUpdateHook as UpdateHook], node)232 })233 }234235 requestAnimationFrame(addUpdateTask)236 })237 } else {238 update([0, false, localUpdateHook as UpdateHook], node)239 }240 }241 },242 ])243}244245export const useReducer = <T, A>(246 reducer: (state: T, action: A) => T,247 initialArg: T,248 init?: (initialState: T) => T249): [T, (action: A) => void] => {250 const handler = useCallback(251 (action: A) => {252 setState((state) => reducer(state, action))253 },254 [reducer]255 )256 const [state, setState] = useState(() => (init ? init(initialArg) : initialArg))257 return [state, handler]258}259260const useEffectCommon = (261 index: number,262 effect: () => void | (() => void),263 deps?: readonly unknown[]264): void => {265 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]266 if (!buildData) {267 return268 }269 const [, node] = buildData270271 const effectDepsArray = (node[DOM_STASH][1][STASH_EFFECT] ||= [])272 const hookIndex = node[DOM_STASH][0]++273274 const [prevDeps, , prevCleanup] = (effectDepsArray[hookIndex] ||= [])275 if (isDepsChanged(prevDeps, deps)) {276 if (prevCleanup) {277 prevCleanup()278 }279 const runner = () => {280 data[index] = undefined // clear this effect in order to avoid calling effect twice281 data[2] = effect() as (() => void) | undefined282 }283 const data: EffectData = [deps, undefined, undefined, undefined, undefined]284 data[index] = runner285 effectDepsArray[hookIndex] = data286 }287}288export const useEffect = (effect: () => void | (() => void), deps?: readonly unknown[]): void =>289 useEffectCommon(3, effect, deps)290export const useLayoutEffect = (291 effect: () => void | (() => void),292 deps?: readonly unknown[]293): void => useEffectCommon(1, effect, deps)294export const useInsertionEffect = (295 effect: () => void | (() => void),296 deps?: readonly unknown[]297): void => useEffectCommon(4, effect, deps)298299export const useCallback = <T extends Function>(callback: T, deps: readonly unknown[]): T => {300 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]301 if (!buildData) {302 return callback303 }304 const [, node] = buildData305306 const callbackArray = (node[DOM_STASH][1][STASH_CALLBACK] ||= [])307 const hookIndex = node[DOM_STASH][0]++308309 const prevDeps = callbackArray[hookIndex]310 if (isDepsChanged(prevDeps?.[1], deps)) {311 callbackArray[hookIndex] = [callback, deps]312 } else {313 callback = callbackArray[hookIndex][0] as T314 }315 return callback316}317Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 318–323why, one step back318export type RefObject<T> = { current: T }319320export function useRef<T>(initialValue: T): RefObject<T>321export function useRef<T>(initialValue: T | null): RefObject<T | null>322export function useRef<T>(initialValue: T | undefined): RefObject<T | undefined>323export function useRef<T>(initialValue?: T | null): RefObject<T | null | undefined> {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 324–325why, one step back324 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]325 if (!buildData) {Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 326why, one step back326 return { current: initialValue } as RefObject<T | null | undefined>Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 327–374why, one step back327 }328 const [, node] = buildData329330 const refArray = (node[DOM_STASH][1][STASH_REF] ||= [])331 const hookIndex = node[DOM_STASH][0]++332333 return (refArray[hookIndex] ||= { current: initialValue })334}335336export const use = <T>(promise: Promise<T>): T => {337 const cachedRes = resolvedPromiseValueMap.get(promise) as [T] | [undefined, unknown] | undefined338 if (cachedRes) {339 if (cachedRes.length === 2) {340 throw cachedRes[1]341 }342 return cachedRes[0] as T343 }344 promise.then(345 (res) => resolvedPromiseValueMap.set(promise, [res]),346 (e) => resolvedPromiseValueMap.set(promise, [undefined, e])347 )348349 throw promise350}351352export const useMemo = <T>(factory: () => T, deps: readonly unknown[]): T => {353 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]354 if (!buildData) {355 return factory()356 }357 const [, node] = buildData358359 const memoArray = (node[DOM_STASH][1][STASH_MEMO] ||= [])360 const hookIndex = node[DOM_STASH][0]++361362 const prevDeps = memoArray[hookIndex]363 if (isDepsChanged(prevDeps?.[1], deps)) {364 memoArray[hookIndex] = [factory(), deps]365 }366 return memoArray[hookIndex][0] as T367}368369let idCounter = 0370export const useId = (): string => useMemo(() => `:r${(idCounter++).toString(32)}:`, [])371372// Define to avoid errors. This hook currently does nothing.373export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}374Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 375why, one step back375export const createRef = <T>(): RefObject<T | null> => {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 376–379why, one step back376 return { current: null }377}378379export const forwardRef = <T, P = {}>(Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 380–381why, one step back380 Component: (props: P, ref?: RefObject<T | null>) => JSX.Element381): ((props: P & { ref?: RefObject<T | null> }) => JSX.Element) => {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 382–388why, one step back382 return (props) => {383 const { ref, ...rest } = props384 return Component(rest as P, ref)385 }386}387388export const useImperativeHandle = <T>(Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 389why, one step back389 ref: RefObject<T | null>,Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 390–414why, one step back390 createHandle: () => T,391 deps: readonly unknown[]392): void => {393 useEffect(() => {394 ref.current = createHandle()395 return () => {396 ref.current = null397 }398 }, deps)399}400401export const useSyncExternalStore = <T>(402 subscribe: (callback: () => void) => () => void,403 getSnapshot: () => T,404 getServerSnapshot?: () => T405): T => {406 const buildData = buildDataStack.at(-1) as [Context, unknown]407 if (!buildData) {408 // now a stringify process, maybe in server side409 if (!getServerSnapshot) {410 throw new Error('getServerSnapshot is required for server side rendering')411 }412 return getServerSnapshot()413 }414fix(jsx): handle useSyncExternalStore subscription and snapshot changes (#5166)Taku Amanobefore adoption224d2f5
lines 415–423why, one step back415 const snapshot =416 buildData[0][4] && getServerSnapshot ? (getServerSnapshot as () => T)() : getSnapshot()417 const [, setVersion] = useState(0)418 const latestSnapshot = useRef<[T, () => T]>([snapshot, getSnapshot])419 latestSnapshot.current = [snapshot, getSnapshot]420 const unsubscribeRef = useRef<() => void>(null)421422 // Swap subscriptions at effect flush: a returned cleanup would run synchronously423 // during render when `subscribe` changes, leaving a window with no subscription.Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 424why, one step back424 useEffect(() => {fix(jsx): handle useSyncExternalStore subscription and snapshot changes (#5166)Taku Amanobefore adoption224d2f5
lines 425–430why, one step back425 const update = () => setVersion((version) => version + 1)426 unsubscribeRef.current?.()427 unsubscribeRef.current = subscribe(update)428 const [snapshot, getSnapshot] = latestSnapshot.current!429 if (!Object.is(snapshot, getSnapshot())) {430 update()Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 431why, one step back431 }fix(jsx): handle useSyncExternalStore subscription and snapshot changes (#5166)Taku Amanobefore adoption224d2f5
line 432why, one step back432 }, [subscribe])Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 433why, one step back433fix(jsx): handle useSyncExternalStore subscription and snapshot changes (#5166)Taku Amanobefore adoption224d2f5
lines 434–436why, one step back434 useEffect(() => () => unsubscribeRef.current?.(), [])435436 return snapshotMerge commit from forkYusuke Wadabefore adoptionf0b094d
line 437why, one step back437}