Files
SnowLuma/.pnpm-store/v11/files/10/9d8ba7dac0bfd83c31464d52d762f92c348560de4286b5a887fe983fb232763e6de1777f2797e9af8fb499384898c5a513c6135ce26ee4df39dea8679e1b8e
TanTan 2a69b23b47
Dev Build / cleanup (push) Canceled after 0s
Dev Build / typecheck (push) Canceled after 0s
Dev Build / build (linux-arm64, ubuntu-24.04-arm, linux-arm64) (push) Canceled after 0s
Dev Build / build (linux-x64, ubuntu-latest, linux-x64) (push) Canceled after 0s
Dev Build / build (win-x64, windows-latest, win32-x64) (push) Canceled after 0s
Dev Build / dispatch-dev-docker (push) Canceled after 0s
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

61 lines
1.8 KiB
Plaintext

import { PERMALINK } from "../../constants.js";
import { createContext } from "../context.js";
import { useContext } from "../../context.js";
import { useCallback, useState } from "../../hooks/index.js";
//#region src/jsx/dom/hooks/index.ts
/**
* Provide hooks used only in jsx/dom
*/
const FormContext = createContext({
pending: false,
data: null,
method: null,
action: null
});
const actions = /* @__PURE__ */ new Set();
const registerAction = (action) => {
actions.add(action);
action.finally(() => actions.delete(action));
};
/**
* This hook returns the current form status
* @returns FormStatus
*/
const useFormStatus = () => {
return useContext(FormContext);
};
/**
* This hook returns the current state and a function to update the state optimistically
* The current state is updated optimistically and then reverted to the original state when all actions are resolved
* @param state
* @param updateState
* @returns [T, (action: N) => void]
*/
const useOptimistic = (state, updateState) => {
const [optimisticState, setOptimisticState] = useState(state);
if (actions.size > 0) Promise.all(actions).finally(() => {
setOptimisticState(state);
});
else setOptimisticState(state);
return [optimisticState, useCallback((newData) => {
setOptimisticState((currentState) => updateState(currentState, newData));
}, [])];
};
/**
* This hook returns the current state and a function to update the state by form action
* @param fn
* @param initialState
* @param permalink
* @returns [T, (data: FormData) => void]
*/
const useActionState = (fn, initialState, permalink) => {
const [state, setState] = useState(initialState);
const actionState = async (data) => {
setState(await fn(state, data));
};
actionState[PERMALINK] = permalink;
return [state, actionState];
};
//#endregion
export { FormContext, registerAction, useActionState, useFormStatus, useOptimistic };