Download web/src/connectors/ConnectTutorial.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/connectors/ConnectTutorial.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/connectors/ConnectTutorial.tsx
-
curl -L -o ConnectTutorial.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/connectors/ConnectTutorial.tsx
18.7 kB
| // Secrets stay in this mounted draft until a successful test or dismissal. | |
| import { useEffect, useRef, useState } from "react"; | |
| import { Copy } from "@phosphor-icons/react/dist/csr/Copy"; | |
| import { Check } from "@phosphor-icons/react/dist/csr/Check"; | |
| import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, WORKSPACE_STALE_EVENT, checkTenant } from "../apiContract"; | |
| import { ConnectionWizard, GuideSteps } from "../settings/ExternalAccessPane"; | |
| import { listAutomations } from "../automation/automationApi"; | |
| import { clearConnectorDetailCache, parseConnectSpec } from "./ConnectorModal"; | |
| import type { ConnectorConnectSpec } from "./ConnectorModal"; | |
| import type { ConnectorRow } from "./ConnectorsPage"; | |
| export interface TutorialGuide { | |
| need: string; | |
| steps: string[]; | |
| failureAction: string; | |
| testNote: string; | |
| } | |
| const screenText = (value: unknown) => typeof value === "string" | |
| ? value.trim().replace(/[\u2013\u2014]/g, ", ") : ""; | |
| const object = (value: unknown): Record<string, unknown> => value !== null | |
| && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}; | |
| export function parseTutorialGuide(value: unknown, mode: "database" | "ai" = "database"): TutorialGuide | null { | |
| const row = object(value); | |
| const need = screenText(row.need); | |
| const steps = Array.isArray(row.steps) ? row.steps.map(screenText).filter(Boolean) : []; | |
| const failureAction = screenText(row.failureAction); | |
| const testNote = screenText(row.testNote); | |
| const validTestNote = typeof row.testNote === "string" && (mode === "ai" || testNote !== ""); | |
| return need && steps.length && failureAction && validTestNote ? { need, steps, failureAction, testNote } : null; | |
| } | |
| type SetupSpec = ConnectorConnectSpec & { | |
| hint: string; | |
| fieldHints: Record<string, string>; | |
| tutorial: TutorialGuide; | |
| initialDatabases: { key: string; label: string; selected: boolean }[]; | |
| }; | |
| type SetupRead = { phase: "loading" } | { phase: "error"; message: string } | |
| | { phase: "held" } | { phase: "ready"; spec: SetupSpec }; | |
| // Never display raw provider/exception text: a failed probe can echo a submitted secret. | |
| async function call(path: string, init?: RequestInit): Promise<{ | |
| ok: boolean; status: number; body: Record<string, unknown>; stopped?: boolean; | |
| }> { | |
| const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init }); | |
| if (checkTenant(response)) return { ok: false, status: 409, body: {}, stopped: true }; | |
| if (response.status === 401) { | |
| window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); | |
| return { ok: false, status: 401, body: {}, stopped: true }; | |
| } | |
| return { ok: response.ok, status: response.status, body: object(await response.json().catch(() => null)) }; | |
| } | |
| export default function ConnectTutorial(props: { | |
| row: ConnectorRow; | |
| onDone: () => void; | |
| onOpenSettings: () => void; | |
| intent?: "connect" | "add"; | |
| }) { | |
| return props.row.key === "webhooks" ? <WebhookTutorial {...props} /> : <CredentialTutorial {...props} />; | |
| } | |
| function CredentialTutorial({ row, onDone, onOpenSettings, intent = "connect" }: { | |
| row: ConnectorRow; | |
| onDone: () => void; | |
| onOpenSettings: () => void; | |
| intent?: "connect" | "add"; | |
| }) { | |
| const [read, setRead] = useState<SetupRead>({ phase: "loading" }); | |
| const [readVersion, setReadVersion] = useState(0); | |
| const [connected, setConnected] = useState(false); | |
| const [label, setLabel] = useState(row.label); | |
| const [scope, setScope] = useState(""); | |
| const [values, setValues] = useState<Record<string, string>>({}); | |
| const [selectedDatabases, setSelectedDatabases] = useState<string[]>([]); | |
| const [storedId, setStoredId] = useState<string | null>(null); | |
| const [busy, setBusy] = useState(false); | |
| const [error, setError] = useState(""); | |
| const [uncertainSave, setUncertainSave] = useState(false); | |
| const inFlight = useRef(false); | |
| const mounted = useRef(false); | |
| useEffect(() => { | |
| mounted.current = true; | |
| return () => { mounted.current = false; }; | |
| }, []); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setRead({ phase: "loading" }); | |
| void (async () => { | |
| try { | |
| const response = await call(`/connectors/${encodeURIComponent(row.key)}/detail` | |
| + "?databases_offset=0&databases_limit=1&fields=summary", { signal: controller.signal }); | |
| if (controller.signal.aborted || response.stopped) return; | |
| const keychain = object(response.body.keychain); | |
| if (!response.ok || keychain.canConnect !== true) { | |
| setRead({ phase: "error", message: response.status === 403 || keychain.canConnect === false | |
| ? "Ask your workspace administrator for permission to connect this source." | |
| : "Setup could not be loaded. Try again." }); | |
| return; | |
| } | |
| // Only Setup's explicit Add another action can add beside an existing connection. | |
| if (intent !== "add" && Array.isArray(keychain.entries) && keychain.entries.length > 0) { | |
| setRead({ phase: "held" }); | |
| return; | |
| } | |
| const rawSpec = object(keychain.connect); | |
| const spec = parseConnectSpec(rawSpec); | |
| const tutorial = parseTutorialGuide(rawSpec.tutorial); | |
| if (!spec || !tutorial) { | |
| setRead({ phase: "error", message: "Setup instructions are unavailable. Open connection settings." }); | |
| return; | |
| } | |
| const fieldHints: Record<string, string> = {}; | |
| for (const value of Array.isArray(rawSpec.fields) ? rawSpec.fields : []) { | |
| const field = object(value); | |
| if (typeof field.key === "string") fieldHints[field.key] = screenText(field.hint); | |
| } | |
| setValues(Object.fromEntries(spec.fields.map((field) => [field.key, field.default ?? ""]))); | |
| setLabel(spec.defaultLabel ?? ""); | |
| setScope(spec.scopes[0]); | |
| const initialDatabases = (intent !== "add" && Array.isArray(rawSpec.initialDatabases) ? rawSpec.initialDatabases : []) | |
| .map(object).filter((item) => typeof item.key === "string" && typeof item.label === "string") | |
| .map((item) => ({ key: String(item.key), label: screenText(item.label), selected: item.selected === true })); | |
| setSelectedDatabases(initialDatabases.filter((item) => item.selected).map((item) => item.key)); | |
| setRead({ phase: "ready", spec: { ...spec, hint: screenText(rawSpec.hint), fieldHints, tutorial, initialDatabases } }); | |
| } catch { | |
| if (!controller.signal.aborted) setRead({ phase: "error", message: "Cannot reach the server. Try again." }); | |
| } | |
| })(); | |
| return () => controller.abort(); | |
| }, [row.key, readVersion, intent]); | |
| if (read.phase === "loading") return <div className="shell-loading"> | |
| <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading setup" /> | |
| </div>; | |
| if (read.phase === "error") return <div> | |
| <p className="conn-tutorial-error" role="alert">{read.message}</p> | |
| <button type="button" className="conn-tutorial-button" onClick={() => setReadVersion((v) => v + 1)}>Try again</button> | |
| <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Connection settings</button> | |
| </div>; | |
| if (read.phase === "held") return <div> | |
| <p className="external-sub">A key is already stored.</p> | |
| <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Settings</button> | |
| </div>; | |
| const { spec } = read; | |
| const complete = Boolean(label.trim()) && spec.scopes.includes(scope) | |
| && spec.fields.every((field) => Boolean(values[field.key]?.trim())); | |
| const hasSelection = spec.initialDatabases.length > 0; | |
| const test = async () => { | |
| if (inFlight.current || !complete || uncertainSave || connected) return; | |
| inFlight.current = true; | |
| setBusy(true); | |
| setError(""); | |
| let entryId = storedId; | |
| let saving = entryId === null; | |
| try { | |
| if (saving) { | |
| const result = await call("/admin/keychain", { | |
| method: "POST", headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ label: label.trim() === spec.defaultLabel ? "" : label.trim(), type: spec.type, scope, | |
| ...(hasSelection ? { initialDatabases: selectedDatabases } : {}), | |
| fields: Object.fromEntries(spec.fields.map((field) => [field.key, values[field.key].trim()])) }), | |
| }); | |
| if (!mounted.current || result.stopped) return; | |
| if (!result.ok) { | |
| const code = object(result.body.error).code; | |
| setError(result.status === 403 | |
| ? "Ask your workspace administrator for permission to add this connection." | |
| : code === "keychain_locked" | |
| ? "Ask your workspace administrator to unlock the keychain, then try again." | |
| : result.status >= 500 | |
| ? "Open connection settings to check whether the key was saved before trying again." | |
| : `The key was not saved. ${spec.tutorial.failureAction}`); | |
| if (result.status >= 500) setUncertainSave(true); | |
| return; | |
| } | |
| const id = object(result.body.entry).id; | |
| if (typeof id !== "string" || !id) { | |
| setUncertainSave(true); | |
| setError("Open connection settings to find the saved key. Do not store it again."); | |
| return; | |
| } | |
| entryId = id; | |
| setStoredId(id); | |
| clearConnectorDetailCache(); | |
| window.dispatchEvent(new CustomEvent(WORKSPACE_STALE_EVENT)); | |
| saving = false; | |
| } | |
| // Only this explicit button reaches the existing canonical test door. A retry uses the | |
| // returned ID, never another create. Draft fields remain available after a failed Test. | |
| const result = await call(`/admin/keychain/${encodeURIComponent(entryId!)}/test`, { method: "POST" }); | |
| if (!mounted.current || result.stopped) return; | |
| if (!result.ok || result.body.ok !== true) { | |
| setError(result.status === 403 | |
| ? "Ask your workspace administrator for permission to test this connection." | |
| : result.status === 404 | |
| ? "The saved key is unavailable. Open connection settings and select the current key." | |
| : `Test failed. ${spec.tutorial.failureAction}`); | |
| return; | |
| } | |
| clearConnectorDetailCache(); | |
| setValues({}); | |
| setConnected(true); | |
| } catch { | |
| if (!mounted.current) return; | |
| if (saving) { | |
| setUncertainSave(true); | |
| setError("Cannot reach the server. Open connection settings to check whether the key was saved before trying again."); | |
| } else { | |
| setError("Cannot reach the server. Check your connection, then test the saved key again."); | |
| } | |
| } finally { | |
| inFlight.current = false; | |
| if (mounted.current) setBusy(false); | |
| } | |
| }; | |
| return <div className="conn-tutorial" data-connect-tutorial={row.key}> | |
| <ConnectionWizard title="Connection setup" titleId="conn-tutorial-title" | |
| footer={<> | |
| <button type="button" className="conn-tutorial-button is-primary" | |
| disabled={!connected && (busy || !complete || uncertainSave)} | |
| onClick={connected ? onDone : () => void test()}> | |
| {connected ? "Done" : busy ? "Testing…" : storedId ? "Test again" : "Test"} | |
| </button> | |
| </>}> | |
| <GuideSteps mode="short" tutorial={spec.tutorial} steps={[ | |
| ...spec.tutorial.steps.map((text) => ({ text })), | |
| { text: <div className="conn-tutorial-fields" title={spec.hint || undefined}> | |
| <span className="external-step-instruction">Connect account</span> | |
| <div className="conn-tutorial-field"> | |
| <label htmlFor="conn-tutorial-label">Connection name</label> | |
| <input id="conn-tutorial-label" maxLength={80} value={label} disabled={busy || storedId !== null || uncertainSave} | |
| onChange={(event) => setLabel(event.target.value)} /> | |
| </div> | |
| {spec.scopes.length > 1 ? <div className="conn-tutorial-field"> | |
| <label htmlFor="conn-tutorial-scope">Scope</label> | |
| <select id="conn-tutorial-scope" value={scope} disabled={busy || storedId !== null || uncertainSave} | |
| onChange={(event) => setScope(event.target.value)}> | |
| {spec.scopes.map((option) => <option key={option} value={option}>{option === "business" ? "Business" : option === "personal" ? "Personal" : screenText(option)}</option>)} | |
| </select> | |
| </div> : null} | |
| {spec.fields.map((field) => <div className="conn-tutorial-field" key={field.key}> | |
| <label htmlFor={`conn-tutorial-${field.key}`}>{screenText(field.label)}</label> | |
| <input id={`conn-tutorial-${field.key}`} name={field.key} type={field.secret ? "password" : "text"} | |
| autoComplete="off" spellCheck={false} value={values[field.key] ?? ""} | |
| disabled={busy || storedId !== null || uncertainSave} | |
| aria-describedby={spec.fieldHints[field.key] ? `conn-tutorial-${field.key}-hint` : undefined} | |
| onChange={(event) => setValues((current) => ({ ...current, [field.key]: event.target.value }))} /> | |
| {spec.fieldHints[field.key] ? <p className="external-sub" id={`conn-tutorial-${field.key}-hint`}>{spec.fieldHints[field.key]}</p> : null} | |
| </div>)} | |
| {hasSelection ? <div className="conn-tutorial-fields"> | |
| <span className="external-step-instruction">Choose databases</span> | |
| {spec.initialDatabases.map((database) => <label key={database.key} className="conn-tutorial-choice"> | |
| <input type="checkbox" checked={selectedDatabases.includes(database.key)} | |
| disabled={busy || storedId !== null || uncertainSave} | |
| onChange={(event) => setSelectedDatabases((current) => event.target.checked | |
| ? [...current, database.key] : current.filter((key) => key !== database.key))} /> | |
| {database.label} | |
| </label>)} | |
| </div> : null} | |
| {storedId || uncertainSave ? <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Connection settings</button> : null} | |
| </div> }, | |
| ]} /> | |
| {error || connected ? <> | |
| {error ? <div className="conn-tutorial-error" role="alert"> | |
| <p>{error}</p> | |
| {storedId || uncertainSave ? <button type="button" className="conn-tutorial-button" onClick={onOpenSettings}>Connection settings</button> : null} | |
| </div> : null} | |
| {connected ? <p className="external-sub" role="status">{spec.type === "stripe" || spec.type === "shopify" | |
| ? "Key stored" : spec.type === "odoo" ? "Server reachable" : "Connected"}</p> : null} | |
| </> : null} | |
| </ConnectionWizard> | |
| </div>; | |
| } | |
| type HookRead = { phase: "loading" } | { phase: "error" } | { phase: "ready"; hooks: { id: string; name: string; url: string }[] }; | |
| function WebhookTutorial({ row, onDone }: { row: ConnectorRow; onDone: () => void }) { | |
| const [hookRead, setHookRead] = useState<HookRead>({ phase: "loading" }); | |
| const [copiedId, setCopiedId] = useState(""); | |
| const [copying, setCopying] = useState(false); | |
| const [copyError, setCopyError] = useState(""); | |
| const guide = row.tutorial; | |
| const hasGuide = Boolean(guide); | |
| useEffect(() => { | |
| if (!hasGuide) return; | |
| const controller = new AbortController(); | |
| setHookRead({ phase: "loading" }); | |
| listAutomations(controller.signal).then((data) => { | |
| if (controller.signal.aborted || !data) return; | |
| // The URL shape matches AutomationBuilder's Hook URL field: real id, minted trigger token. | |
| const hooks = (Array.isArray(data.automations) ? data.automations : []) | |
| .filter((automation) => !automation.retired && automation.trigger?.key === "webhook" | |
| && typeof automation.trigger.token === "string" && automation.trigger.token) | |
| .map((automation) => ({ | |
| id: automation.id, | |
| name: screenText(automation.name) || "Untitled automation", | |
| url: `${window.location.origin}${API_V1}/automations/${encodeURIComponent(automation.id)}` | |
| + `/hook/${automation.trigger?.token ?? ""}`, | |
| })); | |
| setHookRead({ phase: "ready", hooks }); | |
| }).catch(() => { | |
| if (!controller.signal.aborted) setHookRead({ phase: "error" }); | |
| }); | |
| return () => controller.abort(); | |
| }, [hasGuide]); | |
| if (!guide) return <div> | |
| <p className="conn-tutorial-error" role="alert">Webhook instructions are unavailable.</p> | |
| <a className="conn-tutorial-button is-primary" href="#/automation" onClick={onDone}>Automations</a> | |
| </div>; | |
| const hooks = hookRead.phase === "ready" ? hookRead.hooks : []; | |
| const copyAddress = async (id: string, value: string) => { | |
| if (copying) return; | |
| setCopying(true); | |
| setCopyError(""); | |
| try { | |
| await navigator.clipboard.writeText(value); | |
| setCopiedId(id); | |
| } catch { | |
| setCopiedId(""); | |
| setCopyError("Select the URL and copy it manually."); | |
| } finally { | |
| setCopying(false); | |
| } | |
| }; | |
| const hookSteps = hookRead.phase === "loading" | |
| ? [{ id: "hook-loading", text: <p className="external-step-instruction" role="status">Loading webhook URLs</p> }] | |
| : hookRead.phase === "error" | |
| ? [{ id: "hook-error", text: <p className="conn-tutorial-error" role="alert">Webhook URLs could not be loaded.</p> }] | |
| : hooks.length === 0 | |
| ? [{ id: "hook-empty", text: "No automation uses the Webhooks trigger yet." }] | |
| : hooks.map((hook) => ({ id: `hook-${hook.id}`, text: hook.name, block: hook.url })); | |
| return <div className="conn-tutorial" data-connect-tutorial="webhooks"> | |
| <ConnectionWizard title="Webhook setup" titleId="conn-tutorial-title" footer={<> | |
| <button type="button" className="conn-tutorial-button" onClick={onDone}>Close</button> | |
| <a className="conn-tutorial-button is-primary" href="#/automation" onClick={onDone}>Automations</a> | |
| </>}> | |
| <GuideSteps tutorial={guide} renderCopy={(value, _index, step) => { | |
| const hook = hooks.find((item) => `hook-${item.id}` === step.id); | |
| if (!hook) return null; | |
| const copied = copiedId === hook.id; | |
| return <button type="button" className="external-step-copy" data-hook-copy={hook.id} | |
| disabled={copying} aria-label={`${copied ? "Copied" : "Copy"} webhook URL for ${hook.name}`} | |
| onClick={() => void copyAddress(hook.id, value)} aria-live="polite"> | |
| {copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />} | |
| <span>{copied ? "Copied" : "Copy"}</span> | |
| </button>; | |
| }} | |
| steps={[ | |
| ...guide.steps.map((text) => ({ text })), | |
| ...hookSteps, | |
| ]} /> | |
| {copyError ? <p className="conn-tutorial-error" role="alert">{copyError}</p> : null} | |
| </ConnectionWizard> | |
| </div>; | |
| } | |