ActionProvider.svelte 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <script module lang="ts">
  2. import { getContext } from "svelte";
  3. import type {
  4. ActionBinding,
  5. ActionConfirm,
  6. ActionHandler,
  7. ResolvedAction,
  8. } from "@json-render/core";
  9. const ACTION_KEY = Symbol.for("json-render-actions");
  10. /**
  11. * Pending confirmation state
  12. */
  13. export interface PendingConfirmation {
  14. action: ResolvedAction;
  15. handler: ActionHandler;
  16. resolve: () => void;
  17. reject: () => void;
  18. }
  19. export interface CurrentValue<T> {
  20. readonly current: T;
  21. }
  22. /**
  23. * Action context value
  24. */
  25. export interface ActionContext {
  26. /** Registered action handlers */
  27. handlers: Record<string, ActionHandler>;
  28. /** Currently loading action names */
  29. loadingActions: Set<string>;
  30. /** Pending confirmation dialog */
  31. pendingConfirmation: PendingConfirmation | null;
  32. /** Execute an action binding */
  33. execute: (binding: ActionBinding) => Promise<void>;
  34. /** Confirm the pending action */
  35. confirm: () => void;
  36. /** Cancel the pending action */
  37. cancel: () => void;
  38. /** Register an action handler */
  39. registerHandler: (name: string, handler: ActionHandler) => void;
  40. }
  41. /**
  42. * Get the action context from component tree
  43. */
  44. export function getActionContext(): ActionContext {
  45. const ctx = getContext<ActionContext>(ACTION_KEY);
  46. if (!ctx) {
  47. throw new Error(
  48. "getActionContext must be called within an ActionProvider",
  49. );
  50. }
  51. return ctx;
  52. }
  53. /**
  54. * Convenience helper to get a registered action handler by name
  55. */
  56. export function getAction(
  57. name: string,
  58. ): CurrentValue<ActionHandler | undefined> {
  59. const context = getActionContext();
  60. return {
  61. get current() {
  62. return context.handlers[name];
  63. },
  64. };
  65. }
  66. /**
  67. * Props for ConfirmDialog component
  68. */
  69. export interface ConfirmDialogProps {
  70. /** The confirmation config */
  71. confirm: ActionConfirm;
  72. /** Called when confirmed */
  73. onConfirm: () => void;
  74. /** Called when cancelled */
  75. onCancel: () => void;
  76. }
  77. /**
  78. * Generate a unique ID for use with the "$id" token.
  79. */
  80. let idCounter = 0;
  81. function generateUniqueId(): string {
  82. idCounter += 1;
  83. return `${Date.now()}-${idCounter}`;
  84. }
  85. /**
  86. * Deep-resolve dynamic value references within an object.
  87. */
  88. function deepResolveValue(
  89. value: unknown,
  90. get: (path: string) => unknown,
  91. ): unknown {
  92. if (value === null || value === undefined) return value;
  93. if (value === "$id") {
  94. return generateUniqueId();
  95. }
  96. if (typeof value === "object" && !Array.isArray(value)) {
  97. const obj = value as Record<string, unknown>;
  98. const keys = Object.keys(obj);
  99. if (keys.length === 1 && typeof obj.$state === "string") {
  100. return get(obj.$state as string);
  101. }
  102. if (keys.length === 1 && "$id" in obj) {
  103. return generateUniqueId();
  104. }
  105. }
  106. if (Array.isArray(value)) {
  107. return value.map((item) => deepResolveValue(item, get));
  108. }
  109. if (typeof value === "object") {
  110. const resolved: Record<string, unknown> = {};
  111. for (const [key, val] of Object.entries(
  112. value as Record<string, unknown>,
  113. )) {
  114. resolved[key] = deepResolveValue(val, get);
  115. }
  116. return resolved;
  117. }
  118. return value;
  119. }
  120. </script>
  121. <script lang="ts">
  122. import { setContext, type Snippet } from "svelte";
  123. import {
  124. resolveAction,
  125. executeAction,
  126. nextActionDispatchId,
  127. notifyActionDispatch,
  128. notifyActionSettle,
  129. type ActionBinding as CoreActionBinding,
  130. type ActionHandler as CoreActionHandler,
  131. } from "@json-render/core";
  132. import { getStateContext } from "./StateProvider.svelte";
  133. import { getOptionalValidationContext } from "./ValidationProvider.svelte";
  134. import { SvelteSet } from "svelte/reactivity";
  135. interface Props {
  136. handlers?: Record<string, CoreActionHandler>;
  137. navigate?: (path: string) => void;
  138. children?: Snippet;
  139. }
  140. let { handlers = {}, navigate, children }: Props = $props();
  141. const stateCtx = getStateContext();
  142. const validation = getOptionalValidationContext();
  143. let registeredHandlers = $state.raw<Record<string, CoreActionHandler>>({});
  144. let loadingActions = new SvelteSet<string>();
  145. let pendingConfirmation = $state.raw<PendingConfirmation | null>(null);
  146. const execute = async (binding: CoreActionBinding): Promise<void> => {
  147. const resolved = resolveAction(binding, stateCtx.getSnapshot());
  148. // --- devtools / observer hooks ---
  149. const dispatchId = nextActionDispatchId();
  150. const dispatchedAt = Date.now();
  151. notifyActionDispatch({
  152. id: dispatchId,
  153. name: resolved.action,
  154. params: resolved.params,
  155. at: dispatchedAt,
  156. });
  157. let __ok = true;
  158. let __error: unknown = undefined;
  159. try {
  160. if (resolved.action === "setState" && resolved.params) {
  161. const statePath = resolved.params.statePath as string;
  162. const value = resolved.params.value;
  163. if (statePath) {
  164. stateCtx.set(statePath, value);
  165. }
  166. return;
  167. }
  168. if (resolved.action === "pushState" && resolved.params) {
  169. const statePath = resolved.params.statePath as string;
  170. const rawValue = resolved.params.value;
  171. if (statePath) {
  172. const resolvedValue = deepResolveValue(rawValue, stateCtx.get);
  173. const arr = (stateCtx.get(statePath) as unknown[] | undefined) ?? [];
  174. stateCtx.set(statePath, [...arr, resolvedValue]);
  175. const clearStatePath = resolved.params.clearStatePath as
  176. | string
  177. | undefined;
  178. if (clearStatePath) {
  179. stateCtx.set(clearStatePath, "");
  180. }
  181. }
  182. return;
  183. }
  184. if (resolved.action === "removeState" && resolved.params) {
  185. const statePath = resolved.params.statePath as string;
  186. const index = resolved.params.index as number;
  187. if (statePath !== undefined && index !== undefined) {
  188. const arr = (stateCtx.get(statePath) as unknown[] | undefined) ?? [];
  189. stateCtx.set(
  190. statePath,
  191. arr.filter((_, i) => i !== index),
  192. );
  193. }
  194. return;
  195. }
  196. if (resolved.action === "validateForm") {
  197. if (!validation?.validateAll) {
  198. console.warn(
  199. "validateForm action was dispatched but no ValidationProvider is connected. " +
  200. "Ensure ValidationProvider is rendered inside the provider tree.",
  201. );
  202. return;
  203. }
  204. const valid = validation.validateAll();
  205. const errors: Record<string, string[]> = {};
  206. for (const [path, fieldState] of Object.entries(validation.fieldStates)) {
  207. if (fieldState.result && !fieldState.result.valid) {
  208. errors[path] = fieldState.result.errors;
  209. }
  210. }
  211. const statePath =
  212. (resolved.params?.statePath as string) || "/formValidation";
  213. stateCtx.set(statePath, { valid, errors });
  214. return;
  215. }
  216. if (resolved.action === "push" && resolved.params) {
  217. const screen = resolved.params.screen as string;
  218. if (screen) {
  219. const currentScreen = stateCtx.get("/currentScreen") as
  220. | string
  221. | undefined;
  222. const navStack =
  223. (stateCtx.get("/navStack") as string[] | undefined) ?? [];
  224. if (currentScreen) {
  225. stateCtx.set("/navStack", [...navStack, currentScreen]);
  226. } else {
  227. stateCtx.set("/navStack", [...navStack, ""]);
  228. }
  229. stateCtx.set("/currentScreen", screen);
  230. }
  231. return;
  232. }
  233. if (resolved.action === "pop") {
  234. const navStack =
  235. (stateCtx.get("/navStack") as string[] | undefined) ?? [];
  236. if (navStack.length > 0) {
  237. const previousScreen = navStack[navStack.length - 1];
  238. stateCtx.set("/navStack", navStack.slice(0, -1));
  239. if (previousScreen) {
  240. stateCtx.set("/currentScreen", previousScreen);
  241. } else {
  242. stateCtx.set("/currentScreen", undefined);
  243. }
  244. }
  245. return;
  246. }
  247. const handler =
  248. registeredHandlers[resolved.action] ?? handlers[resolved.action];
  249. if (!handler) {
  250. console.warn(`No handler registered for action: ${resolved.action}`);
  251. return;
  252. }
  253. if (resolved.confirm) {
  254. return new Promise<void>((resolve, reject) => {
  255. pendingConfirmation = {
  256. action: resolved,
  257. handler,
  258. resolve: () => {
  259. pendingConfirmation = null;
  260. resolve();
  261. },
  262. reject: () => {
  263. pendingConfirmation = null;
  264. reject(new Error("Action cancelled"));
  265. },
  266. };
  267. }).then(async () => {
  268. loadingActions.add(resolved.action);
  269. try {
  270. await executeAction({
  271. action: resolved,
  272. handler,
  273. setState: stateCtx.set,
  274. navigate,
  275. executeAction: async (name) => {
  276. const subBinding: CoreActionBinding = { action: name };
  277. await execute(subBinding);
  278. },
  279. });
  280. } finally {
  281. loadingActions.delete(resolved.action);
  282. }
  283. });
  284. }
  285. loadingActions.add(resolved.action);
  286. try {
  287. await executeAction({
  288. action: resolved,
  289. handler,
  290. setState: stateCtx.set,
  291. navigate,
  292. executeAction: async (name) => {
  293. const subBinding: CoreActionBinding = { action: name };
  294. await execute(subBinding);
  295. },
  296. });
  297. } finally {
  298. loadingActions.delete(resolved.action);
  299. }
  300. } catch (err) {
  301. __ok = false;
  302. __error = err;
  303. throw err;
  304. } finally {
  305. const now = Date.now();
  306. notifyActionSettle({
  307. id: dispatchId,
  308. name: resolved.action,
  309. ok: __ok,
  310. at: now,
  311. durationMs: now - dispatchedAt,
  312. error: __error,
  313. });
  314. }
  315. };
  316. const ctx: ActionContext = {
  317. get handlers() {
  318. return { ...handlers, ...registeredHandlers };
  319. },
  320. get loadingActions() {
  321. return loadingActions;
  322. },
  323. get pendingConfirmation() {
  324. return pendingConfirmation;
  325. },
  326. execute,
  327. confirm: () => {
  328. pendingConfirmation?.resolve();
  329. },
  330. cancel: () => {
  331. pendingConfirmation?.reject();
  332. },
  333. registerHandler: (name: string, handler: CoreActionHandler) => {
  334. registeredHandlers = { ...registeredHandlers, [name]: handler };
  335. },
  336. };
  337. setContext(ACTION_KEY, ctx);
  338. </script>
  339. {@render children?.()}