SPB Git

Repository Public

react.ts 7.5 KB 200 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Identity8 * File             : sdk/typescript/src/react.ts9 * Module           : sdk10 * Repository       : https://git.spboucher.ai/maclustr-identity11 * Project Website  : https://identity.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * @maclustr/identity/react — React bindings over the browser entry. React is an optional peer dependency.44 * Like the browser entry, this never takes a secret key: `createSession` must call YOUR server.45 */46import { createElement, useCallback, useEffect, useRef, useState } from "react";47import type { ButtonHTMLAttributes, ReactElement, ReactNode } from "react";48import { openVerification } from "./browser";49import type { VerificationCancel, VerificationFlowError, VerificationHandle, VerificationMode, VerificationResult } from "./browser";5051export type VerificationState = "idle" | "creating" | "open" | "completed" | "cancelled" | "error";5253export interface UseVerificationOptions {54  /**55   * Asks your own backend to create a session and resolves with its hosted `url`56   * (for example `fetch("/api/identity/session", {method: "POST"}).then(r => r.json())`).57   */58  createSession: () => Promise<string | { url: string }>;59  mode?: VerificationMode;60  container?: HTMLElement;61  title?: string;62  closeLabel?: string;63  autoClose?: boolean;64  onReady?: (info: { sessionId: string | null }) => void;65  onComplete?: (result: VerificationResult) => void;66  onCancel?: (info: VerificationCancel) => void;67  onError?: (error: VerificationFlowError) => void;68}6970export interface UseVerification {71  state: VerificationState;72  /** Result reported by the hosted page. A hint for the interface only: confirm on your server. */73  result: VerificationResult | null;74  error: VerificationFlowError | null;75  open: () => Promise<void>;76  close: () => void;77}7879export function useVerification(options: UseVerificationOptions): UseVerification {80  const [state, setState] = useState<VerificationState>("idle");81  const [result, setResult] = useState<VerificationResult | null>(null);82  const [error, setError] = useState<VerificationFlowError | null>(null);83  const handle = useRef<VerificationHandle | null>(null);84  const latest = useRef(options);85  latest.current = options;86  const mounted = useRef(true);87  const busy = useRef(false);8889  useEffect(() => {90    mounted.current = true;91    return () => {92      mounted.current = false;93      handle.current?.close();94      handle.current = null;95    };96  }, []);9798  const close = useCallback(() => {99    handle.current?.close();100    handle.current = null;101    busy.current = false;102    setState((s) => (s === "open" || s === "creating" ? "idle" : s));103  }, []);104105  const open = useCallback(async () => {106    if (busy.current) return;107    busy.current = true;108    setState("creating");109    setResult(null);110    setError(null);111    const fail = (e: VerificationFlowError) => {112      busy.current = false;113      if (!mounted.current) return;114      setError(e);115      setState("error");116      latest.current.onError?.(e);117    };118    let url: string;119    try {120      const created = await latest.current.createSession();121      url = typeof created === "string" ? created : created.url;122    } catch (e) {123      fail({ sessionId: null, code: "session_creation_failed", message: e instanceof Error ? e.message : "Could not create the verification session." });124      return;125    }126    if (!mounted.current) return;127    try {128      const o = latest.current;129      handle.current = openVerification({130        url,131        mode: o.mode,132        container: o.container,133        title: o.title,134        closeLabel: o.closeLabel,135        autoClose: o.autoClose,136        onReady: (info) => latest.current.onReady?.(info),137        onComplete: (r) => {138          busy.current = false;139          if (mounted.current) {140            setResult(r);141            setState("completed");142          }143          latest.current.onComplete?.(r);144        },145        onCancel: (info) => {146          busy.current = false;147          if (mounted.current) setState("cancelled");148          latest.current.onCancel?.(info);149        },150        onError: (e) => {151          // Page-level errors leave the flow open; a lost popup channel ends it.152          if (e.code === "popup_channel_lost") busy.current = false;153          if (mounted.current) {154            setError(e);155            if (e.code === "popup_channel_lost") setState("error");156          }157          latest.current.onError?.(e);158        },159      });160      if (mounted.current) setState("open");161    } catch (e) {162      fail({ sessionId: null, code: "open_failed", message: e instanceof Error ? e.message : "Could not open the verification page." });163    }164  }, []);165166  return { state, result, error, open, close };167}168169export interface VerifyButtonProps extends UseVerificationOptions, Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onClick" | "onError" | "title"> {170  children?: ReactNode;171  /** Label while the session is being created. */172  busyLabel?: ReactNode;173}174175/** A plain `<button>` that creates a session through your backend and opens the hosted verification page. */176export function VerifyButton(props: VerifyButtonProps): ReactElement {177  const { createSession, mode, container, title, closeLabel, autoClose, onReady, onComplete, onCancel, onError, children, busyLabel, disabled, ...rest } = props;178  const v = useVerification({ createSession, mode, container, title, closeLabel, autoClose, onReady, onComplete, onCancel, onError });179  const busy = v.state === "creating" || v.state === "open";180  return createElement(181    "button",182    {183      type: "button",184      ...rest,185      disabled,186      // While the flow is open the button is not `disabled`: a disabled element cannot receive focus, and focus187      // must return to it when the dialog closes. Extra clicks are ignored by the hook.188      "aria-disabled": busy ? true : undefined,189      "aria-busy": v.state === "creating" ? true : undefined,190      "data-state": v.state,191      onClick: () => {192        if (!busy) void v.open();193      },194    },195    v.state === "creating" && busyLabel !== undefined ? busyLabel : (children ?? "Verify my identity"),196  );197}198199export type { VerificationCancel, VerificationFlowError, VerificationHandle, VerificationMode, VerificationResult } from "./browser";200
Files main
Menu

Theme