From 96966c3b72cf82c9391f3b182e1dd0641ffec522 Mon Sep 17 00:00:00 2001 From: chihlasm Date: Sat, 7 Mar 2026 18:44:14 -0500 Subject: [PATCH] feat: Flow Transfer, Procedural Assist & UI Design System (#97) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add flow export/import backend (migration, endpoints, schemas) Add .rfflow file export/import support: - Migration 050: import_metadata JSONB column on trees - GET /trees/{id}/export?format=json|xml endpoint - POST /trees/import endpoint (creates draft, resolves categories/tags) - FlowExportEnvelope, FlowImportRequest/Response schemas - import_metadata field on TreeResponse Co-Authored-By: Claude Opus 4.6 * feat: add flow export/import frontend + backend tests Frontend: - ExportFlowModal with JSON/XML format selection + download - ImportFlowModal with drag-drop file picker + preview step - rfflowParser for client-side JSON/XML .rfflow parsing - Export buttons on editor toolbar and library action menus - Import button on library page next to Create New - Provenance display for imported flows in editor - flowTransfer API client + types Backend: - Fix regex->pattern deprecation in export endpoint - 12 integration tests covering export, import, round-trip, access control, tag/category creation, version validation Co-Authored-By: Claude Opus 4.6 * refactor: remove XML export, JSON-only for .rfflow files - Remove XML builder, format query param, and XML tests - Simplify ExportFlowModal (no format picker) - Simplify rfflowParser (JSON-only) - Remove format field from schemas and types Co-Authored-By: Claude Opus 4.6 * fix: match Flow Assist chat input to AI Assistant styling + strengthen one-question prompt Co-Authored-By: Claude Opus 4.6 * feat: add procedural flow support to AI chat builder (Flow Assist) - Add procedural-specific system prompts (schema, interview protocol, response format) - Dispatch prompts by flow_type: procedural/maintenance use flat steps schema, troubleshooting uses decision tree schema - Parse [STEPS_UPDATE] and [INTAKE_FORM] markers in AI responses - Add validate_generated_procedural_steps() validator - Handle intake form extraction in AI chat import endpoint - Add StaticStepsPreview component for procedural flow preview - Update store and page to render correct preview by flow type Co-Authored-By: Claude Opus 4.6 * feat: add flow type selection to Flow Assist entry points - CreateFlowDropdown now shows "Build with Flow Assist" under each flow type - Library page "Flow Assist" button respects current type filter - Clean up unused AIFlowBuilderModal references Co-Authored-By: Claude Opus 4.6 * docs: update CLAUDE.md with AI chat builder and intake form learnings Co-Authored-By: Claude Opus 4.6 * fix: refine assistant chat prompt for concise answers and focused questions Co-Authored-By: Claude Opus 4.6 * feat: switch AI provider to Claude Sonnet 4.6 + add shift+enter hint to chat inputs - Default AI_PROVIDER changed from gemini to anthropic - AI_MODEL and AI_MODEL_ANTHROPIC updated to claude-sonnet-4-6 - Added "Shift + Enter for a new line" hint below all chat textareas Co-Authored-By: Claude Opus 4.6 * docs: update CLAUDE.md with AI provider and chat input learnings Co-Authored-By: Claude Opus 4.6 * docs: add editor-embedded Flow Assist design document Design for replacing the standalone /ai/chat page with context-aware AI side panels embedded in each editor (Troubleshooting + Procedural). Covers ghost node suggestion system, output-based thresholds, config-driven model routing, knowledge integration, and per-flow chat persistence. Co-Authored-By: Claude Opus 4.6 * docs: add editor-embedded Flow Assist implementation plan 25-task plan across 9 phases covering backend foundation, frontend infrastructure, tree/procedural editor integration, AI-assisted create, old code removal, action-type dispatch, suggestion audit trail, and build verification. Co-Authored-By: Claude Opus 4.6 * fix: use actual root node ID in orphan validation check AI-generated trees use descriptive IDs (e.g., "verify-account-exists") instead of "root", causing the root node to be falsely flagged as orphaned. Co-Authored-By: Claude Opus 4.6 * feat: add config-driven AI model tier routing Co-Authored-By: Claude Opus 4.6 * feat: extend AI chat session with tree_id and archived_at Add tree_id FK (CASCADE) for editor-embedded sessions and archived_at timestamp column to ai_chat_sessions table. Co-Authored-By: Claude Opus 4.6 * feat: add AI suggestion audit trail table Co-Authored-By: Claude Opus 4.6 * feat: add action_type and focal_node_id to AI chat message API - Add VALID_ACTION_TYPES literal and action_type/focal_node_id fields to AIChatMessageRequest schema - Add tree_id field to AIChatStartRequest schema for editor-embedded sessions - Update send_message() signature with action_type and focal_node_id params - Update start_chat_session() signature with tree_id param - Pass new params through endpoints to service functions - All new params have defaults so existing behavior is unchanged Co-Authored-By: Claude Opus 4.6 * feat: route AI model selection through action-type config Update get_ai_provider() to accept an optional model override parameter (applied only to AnthropicProvider; Gemini always uses its own model). Thread action_type-based model resolution through send_message() and generate_final_tree() in the AI chat service. Co-Authored-By: Claude Opus 4.6 * feat: add TypeScript types for editor-embedded AI Co-Authored-By: Claude Opus 4.6 * feat: add shared ContextMenu component Co-Authored-By: Claude Opus 4.6 * feat: add useEditorAI hook and editorAI API client Co-Authored-By: Claude Opus 4.6 * feat: add EditorAIPanel component with Chat and Suggestions tabs Co-Authored-By: Claude Opus 4.6 * feat: integrate AI panel, context menu, and ghost nodes in tree editor - Add AI Assist panel toggle button to tree editor toolbar - Wire EditorAIPanel alongside TreeEditorLayout with single-panel rule - Thread onNodeContextMenu through TreeEditorLayout → FlowCanvas → FlowCanvasNode - Add right-click context menu with Generate Branch, Explain Node, Delete actions - Add ghost node detection (_suggestion flag) with dashed border + opacity styling - Add Accept/Dismiss overlay buttons on ghost nodes for future suggestion handling Co-Authored-By: Claude Opus 4.6 * feat: integrate AI panel, context menu, and ghost steps in procedural editor Co-Authored-By: Claude Opus 4.6 * feat: add AI prompt dialog and wire into CreateFlowDropdown Replace navigation to /ai/chat with an inline AIPromptDialog modal that collects a single prompt, generates a flow via the editor AI API, imports it, and navigates to the editor with the AI panel open. Co-Authored-By: Claude Opus 4.6 * fix: add glassmorphism to AI prompt dialog + maintenance Flow Assist button - Use .glass-card-static on AIPromptDialog card for consistent design system - Add "Build with Flow Assist" button to maintenance section in CreateFlowDropdown Co-Authored-By: Claude Opus 4.6 * refactor: remove standalone Flow Assist page and old AI chat components Remove the old /ai/chat page, AI wizard modal, and all associated components/stores/types now replaced by the editor-embedded AI panel. Deleted: - AIChatBuilderPage, ai-chat/ components, aiChatStore, aiChat API, ai-chat types - AIFlowBuilderModal, ai-builder/ components, aiFlowBuilderStore Cleaned up: - Router (removed /ai/chat route) - Sidebar (removed Flow Assist nav item) - MyTreesPage (removed AI builder modal and button) - TreeLibraryPage (removed Flow Assist button) - API and type barrel exports Co-Authored-By: Claude Opus 4.6 * feat: add delta response parsing and action-type prompt dispatch Co-Authored-By: Claude Opus 4.6 * feat: add AI suggestion audit trail endpoints Create/list/resolve endpoints for tracking AI-applied changes to flows. Co-Authored-By: Claude Opus 4.6 * feat: add APScheduler task to auto-archive stale AI chat sessions Archives AI chat sessions with no activity for 30 days, runs daily at 3 AM. Co-Authored-By: Claude Opus 4.6 * docs: update project status for editor-embedded Flow Assist - Add Editor-Embedded Flow Assist to CURRENT-STATE.md in-progress items - Update CLAUDE.md: fix stale lessons (#41, #46), add new patterns (#47 editor AI architecture, #48 orphan validation) Co-Authored-By: Claude Opus 4.6 * fix: use correct model alias in AI_MODEL_TIERS standard tier The dated model ID `claude-sonnet-4-6-20250514` was causing 502 errors. Use the alias `claude-sonnet-4-6` which matches AI_MODEL_ANTHROPIC. Co-Authored-By: Claude Opus 4.6 * feat: send live flow context to AI Assist for full editor awareness The AI panel now sends the current tree structure (troubleshooting) or steps + intake form (procedural/maintenance) with each message. This gives the AI full visibility into node details, questions, descriptions, options, and intake form fields — not just the node ID. - Backend: add flow_context param to schema, endpoint, and service - Frontend: add getFlowContext callback to useEditorAI hook - TreeEditorPage: passes treeStructure as flow context - ProceduralEditorPage: passes steps + intakeForm as flow context Co-Authored-By: Claude Opus 4.6 * feat: include flow name and description in AI Assist context Both editors now send name and description alongside the flow structure, so the AI can reference what the flow is about when responding. Co-Authored-By: Claude Opus 4.6 * fix: increase AI timeout to 120s and limit retries to 1 The 45s timeout was too short for generation tasks with full flow context in the system prompt. The Anthropic SDK's default 2 retries caused requests to hang for ~136s before failing. Now: 120s timeout with max 1 retry = faster failure if it does timeout. Co-Authored-By: Claude Opus 4.6 * fix: wire AI-generated flow structures into editor stores The useEditorAI hook was ignoring result.working_tree from AI responses, so generated steps/trees never appeared in the editor. Now: - useEditorAI calls onFlowUpdate when working_tree is present in response - ProceduralEditorPage handles steps + intake form updates via replaceSteps - TreeEditorPage handles tree structure updates via replaceTreeStructure - Both stores have new bulk-replace methods for AI integration Co-Authored-By: Claude Opus 4.6 * docs: add lessons learned for full-stack integration, Anthropic retries, model tiers #49 Always verify frontend consumes backend response fields #50 Anthropic SDK max_retries=1 to avoid 3× timeout #51 AI model tier routing via settings.get_model_for_action() Co-Authored-By: Claude Opus 4.6 * fix: move AI Assist panel to full-height side layout in both editors The AI panel was nested inside the content area, only spanning the step list / canvas section. Now it sits at the outermost flex level, spanning the full page height alongside all content (toolbar, collapsible sections, steps/canvas). This prevents the panel from overlapping content and lets the editor area properly shrink. Co-Authored-By: Claude Opus 4.6 * fix: AI Assist panel as fixed right drawer (matching Copilot/Scratchpad) Convert EditorAIPanel from in-flow flex child to fixed right-side drawer overlay, same pattern as CopilotPanel and ScratchpadSidebar. The panel is fixed at right:0 spanning full viewport height, and editor pages add pr-[380px] padding when open so content shifts left without overlap. Co-Authored-By: Claude Opus 4.6 * fix: AI Assist panel sits below topbar with slide-in animation - Panel now uses top:56px to sit below the app shell topbar instead of covering it (matches the main-content grid cell area) - Added slideInRight CSS animation for smooth drawer entrance - Editor pages use dynamic paddingRight via PANEL_WIDTH constant - ChatTab upgraded: markdown rendering, CopilotPanel-style message bubbles, auto-focus input, Shift+Enter hint - All borders use --glass-border for consistent glassmorphism Co-Authored-By: Claude Opus 4.6 * fix: AI Assist panel as in-flow flex sibling (not fixed/overlay) Replace fixed positioning with in-flow flex layout. The outermost div is now a horizontal flex row: content column (flex-1 min-w-0) + panel (w-[380px] shrink-0). When the panel opens, the content column automatically shrinks — no padding hacks or z-index stacking needed. This guarantees the content shifts left and stays fully visible. Co-Authored-By: Claude Opus 4.6 * fix: AI Copilot panel as in-flow flex sibling in session navigation pages Changed CopilotPanel from fixed overlay to flex layout sibling so it pushes main content instead of covering it during active sessions. Co-Authored-By: Claude Opus 4.6 * docs: remove duplicate CLAUDE.md lessons #47-48 Co-Authored-By: Claude Opus 4.6 * feat: UI design system primitives, accessibility, and performance improvements - Add Button component with CVA variants (primary, secondary, destructive, ghost, link) - Add Input, Textarea, FormField, and Skeleton UI primitives - Add focus trapping to Modal for WCAG accessibility compliance - Add prefers-reduced-motion media query for motion-sensitive users - Add route-level ErrorBoundary wrapping via page() helper in router - Add route prefetching on sidebar nav hover for instant navigation - Add PageMeta component with OG/Twitter meta tags (react-helmet-async) - Add PageMeta to SharedSessionPage and SurveyPage for social sharing - Replace lodash with custom debounce utility (saves ~71KB bundle) Co-Authored-By: Claude Opus 4.6 * fix: mobile-responsive SurveyPage with touch-friendly targets 15+ responsive adjustments using sm: breakpoints for proper mobile display: compact padding, flex-wrap metadata, stacked email input, larger touch targets for drag-rank/range inputs, hidden brand text on small screens, and tighter line heights. Co-Authored-By: Claude Opus 4.6 * fix: survey invite links use FRONTEND_URL config instead of hardcoded URL PR environments were generating survey links pointing to production (resolutionflow.com) because the URL was hardcoded. Now uses the existing settings.FRONTEND_URL, falling back to localhost (debug) or production (release). Co-Authored-By: Claude Opus 4.6 * fix: scroll to top after survey slide transition renders Use requestAnimationFrame to defer scrollTo until after React renders the new slide content, preventing the browser from staying at the bottom of the page. Co-Authored-By: Claude Opus 4.6 * fix: scroll to top on survey slide change via useEffect requestAnimationFrame was still too early. Use a useEffect on currentSlide so the scroll fires after React commits the new slide to the DOM. Skips initial render to avoid scroll on load. Co-Authored-By: Claude Opus 4.6 * fix: survey scroll-to-top on mobile using scrollIntoView Mobile browsers (iOS Safari especially) ignore window.scrollTo. Use scrollIntoView on a ref at the top of the page instead, which works reliably across mobile and desktop browsers. Co-Authored-By: Claude Opus 4.6 * docs: add mobile scrollIntoView lesson (#52) to CLAUDE.md Co-Authored-By: Claude Opus 4.6 --------- Co-authored-by: Claude Opus 4.6 --- CLAUDE.md | 2 + backend/app/api/endpoints/admin_survey.py | 9 +- frontend/package-lock.json | 63 ++- frontend/package.json | 3 +- frontend/src/components/admin/SearchInput.tsx | 2 +- frontend/src/components/common/Modal.tsx | 55 ++- frontend/src/components/common/PageMeta.tsx | 44 ++ frontend/src/components/layout/NavItem.tsx | 3 + frontend/src/components/ui/Button.tsx | 63 +++ frontend/src/components/ui/FormField.tsx | 24 ++ frontend/src/components/ui/Input.tsx | 35 ++ frontend/src/components/ui/Skeleton.tsx | 58 +++ frontend/src/components/ui/Textarea.tsx | 35 ++ frontend/src/index.css | 12 + frontend/src/lib/debounce.ts | 27 ++ frontend/src/lib/prefetch.ts | 12 + frontend/src/lib/routePrefetch.ts | 27 ++ frontend/src/main.tsx | 29 +- frontend/src/pages/SharedSessionPage.tsx | 5 + frontend/src/pages/SurveyPage.tsx | 114 +++-- frontend/src/router.tsx | 403 ++++-------------- 21 files changed, 613 insertions(+), 412 deletions(-) create mode 100644 frontend/src/components/common/PageMeta.tsx create mode 100644 frontend/src/components/ui/Button.tsx create mode 100644 frontend/src/components/ui/FormField.tsx create mode 100644 frontend/src/components/ui/Input.tsx create mode 100644 frontend/src/components/ui/Skeleton.tsx create mode 100644 frontend/src/components/ui/Textarea.tsx create mode 100644 frontend/src/lib/debounce.ts create mode 100644 frontend/src/lib/prefetch.ts create mode 100644 frontend/src/lib/routePrefetch.ts diff --git a/CLAUDE.md b/CLAUDE.md index 1e08a8e8..341b070f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -335,6 +335,8 @@ navigate(`/trees/${newTree.id}/edit`) **51. AI model tier routing:** `config.py` has `AI_MODEL_TIERS` (fast/standard) and `ACTION_MODEL_MAP` mapping action types to tiers. Use `settings.get_model_for_action(action_type)` to resolve concrete model names. Model IDs must be valid — use alias form (`claude-sonnet-4-6`) not invented dated forms. +**52. Mobile scroll-to-top — use `scrollIntoView`, not `window.scrollTo`:** Mobile browsers (iOS Safari, Firefox Android) often ignore `window.scrollTo()`. Use a ref at the top of the page and call `ref.current.scrollIntoView({ behavior: 'smooth', block: 'start' })` instead. Trigger via `useEffect` on the state change (not inline with `setState`) so the DOM has committed before scrolling. + --- ## RBAC & Permissions diff --git a/backend/app/api/endpoints/admin_survey.py b/backend/app/api/endpoints/admin_survey.py index f998b1e4..b6603a1b 100644 --- a/backend/app/api/endpoints/admin_survey.py +++ b/backend/app/api/endpoints/admin_survey.py @@ -29,11 +29,14 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix="/admin", tags=["admin-survey"]) -FRONTEND_URL = "https://resolutionflow.com" +def _get_frontend_url() -> str: + if settings.FRONTEND_URL: + return settings.FRONTEND_URL + return "http://localhost:5173" if settings.DEBUG else "https://resolutionflow.com" def _build_invite_response(invite: SurveyInvite) -> SurveyInviteResponse: - base_url = FRONTEND_URL if not settings.DEBUG else "http://localhost:5173" + base_url = _get_frontend_url() return SurveyInviteResponse( id=str(invite.id), token=invite.token, @@ -63,7 +66,7 @@ async def create_survey_invite( if data.send_email and data.recipient_email: try: - base_url = FRONTEND_URL if not settings.DEBUG else "http://localhost:5173" + base_url = _get_frontend_url() survey_url = f"{base_url}/survey?t={invite.token}" sent = await EmailService.send_survey_invite_email( to_email=data.recipient_email, diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0a3ac2e9..e37add81 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -14,19 +14,18 @@ "@dnd-kit/utilities": "^3.2.2", "@monaco-editor/react": "^4.7.0", "@stripe/stripe-js": "^8.7.0", - "@types/lodash": "^4.17.23", "@xyflow/react": "^12.10.0", "axios": "^1.13.4", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "date-fns": "^4.1.0", "immer": "^11.1.3", - "lodash": "^4.17.23", "lucide-react": "^0.563.0", "monaco-editor": "^0.55.1", "react": "^19.2.0", "react-day-picker": "^9.13.1", "react-dom": "^19.2.0", + "react-helmet-async": "^3.0.0", "react-markdown": "^10.1.0", "react-router-dom": "^7.13.0", "recharts": "^3.7.0", @@ -2121,12 +2120,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/lodash": { - "version": "4.17.23", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.23.tgz", - "integrity": "sha512-RDvF6wTulMPjrNdCoYRC8gNR880JNGT8uB+REUpC2Ns4pRqQJhGz90wh7rgdXDPpCczF3VGktDuFGVnz8zP7HA==", - "license": "MIT" - }, "node_modules/@types/mdast": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", @@ -4643,6 +4636,15 @@ "node": ">=12" } }, + "node_modules/invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.0.0" + } + }, "node_modules/is-alphabetical": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", @@ -4818,7 +4820,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, "license": "MIT" }, "node_modules/js-yaml": { @@ -4981,12 +4982,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lodash": { - "version": "4.17.23", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", - "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", - "license": "MIT" - }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -5004,6 +4999,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -6335,6 +6342,26 @@ "react": "^19.2.4" } }, + "node_modules/react-fast-compare": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz", + "integrity": "sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==", + "license": "MIT" + }, + "node_modules/react-helmet-async": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/react-helmet-async/-/react-helmet-async-3.0.0.tgz", + "integrity": "sha512-nA3IEZfXiclgrz4KLxAhqJqIfFDuvzQwlKwpdmzZIuC1KNSghDEIXmyU0TKtbM+NafnkICcwx8CECFrZ/sL/1w==", + "license": "Apache-2.0", + "dependencies": { + "invariant": "^2.2.4", + "react-fast-compare": "^3.2.2", + "shallowequal": "^1.1.0" + }, + "peerDependencies": { + "react": "^16.6.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/react-is": { "version": "17.0.2", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", @@ -6781,6 +6808,12 @@ "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", "license": "MIT" }, + "node_modules/shallowequal": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz", + "integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==", + "license": "MIT" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 98ac3d0b..849bc248 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -19,19 +19,18 @@ "@dnd-kit/utilities": "^3.2.2", "@monaco-editor/react": "^4.7.0", "@stripe/stripe-js": "^8.7.0", - "@types/lodash": "^4.17.23", "@xyflow/react": "^12.10.0", "axios": "^1.13.4", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "date-fns": "^4.1.0", "immer": "^11.1.3", - "lodash": "^4.17.23", "lucide-react": "^0.563.0", "monaco-editor": "^0.55.1", "react": "^19.2.0", "react-day-picker": "^9.13.1", "react-dom": "^19.2.0", + "react-helmet-async": "^3.0.0", "react-markdown": "^10.1.0", "react-router-dom": "^7.13.0", "recharts": "^3.7.0", diff --git a/frontend/src/components/admin/SearchInput.tsx b/frontend/src/components/admin/SearchInput.tsx index c1726873..f6b09cca 100644 --- a/frontend/src/components/admin/SearchInput.tsx +++ b/frontend/src/components/admin/SearchInput.tsx @@ -1,6 +1,6 @@ import { useState, useEffect, useRef, useCallback } from 'react' import { Search, X } from 'lucide-react' -import { debounce } from 'lodash' +import { debounce } from '@/lib/debounce' import { cn } from '@/lib/utils' interface SearchInputProps { diff --git a/frontend/src/components/common/Modal.tsx b/frontend/src/components/common/Modal.tsx index 58262b47..da787dfd 100644 --- a/frontend/src/components/common/Modal.tsx +++ b/frontend/src/components/common/Modal.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useCallback, type ReactNode } from 'react' +import { useState, useEffect, useCallback, useRef, type ReactNode } from 'react' import { X, Maximize2, Minimize2 } from 'lucide-react' import { cn } from '@/lib/utils' @@ -14,6 +14,9 @@ interface ModalProps { allowFullScreen?: boolean } +const FOCUSABLE_SELECTOR = + 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])' + export function Modal({ isOpen, onClose, title, children, footer, size = 'md', allowFullScreen = false }: ModalProps) { const [isFullScreen, setIsFullScreen] = useState(() => { if (!allowFullScreen) return false @@ -24,6 +27,9 @@ export function Modal({ isOpen, onClose, title, children, footer, size = 'md', a } }) + const modalRef = useRef(null) + const previousFocusRef = useRef(null) + const toggleFullScreen = () => { const next = !isFullScreen setIsFullScreen(next) @@ -44,8 +50,10 @@ export function Modal({ isOpen, onClose, title, children, footer, size = 'md', a [onClose] ) + // Body overflow lock + keyboard listener useEffect(() => { if (isOpen) { + previousFocusRef.current = document.activeElement as HTMLElement document.addEventListener('keydown', handleKeyDown) document.body.style.overflow = 'hidden' } @@ -55,6 +63,50 @@ export function Modal({ isOpen, onClose, title, children, footer, size = 'md', a } }, [isOpen, handleKeyDown]) + // Focus trap: keep focus inside the modal + useEffect(() => { + if (!isOpen) { + // Restore focus when modal closes + previousFocusRef.current?.focus() + return + } + + const modal = modalRef.current + if (!modal) return + + // Auto-focus first focusable element + const timer = setTimeout(() => { + const focusable = modal.querySelectorAll(FOCUSABLE_SELECTOR) + if (focusable.length > 0) { + focusable[0].focus() + } + }, 50) + + const trapFocus = (e: KeyboardEvent) => { + if (e.key !== 'Tab') return + + const focusable = modal.querySelectorAll(FOCUSABLE_SELECTOR) + if (focusable.length === 0) return + + const first = focusable[0] + const last = focusable[focusable.length - 1] + + if (e.shiftKey && document.activeElement === first) { + e.preventDefault() + last.focus() + } else if (!e.shiftKey && document.activeElement === last) { + e.preventDefault() + first.focus() + } + } + + modal.addEventListener('keydown', trapFocus) + return () => { + clearTimeout(timer) + modal.removeEventListener('keydown', trapFocus) + } + }, [isOpen]) + if (!isOpen) return null const sizeClasses = { @@ -80,6 +132,7 @@ export function Modal({ isOpen, onClose, title, children, footer, size = 'md', a {/* Modal Content */}
and Open Graph meta tags. + * Wrap the app in (see main.tsx). + */ +export function PageMeta({ + title, + description = DEFAULT_DESCRIPTION, + ogImage, + ogType = 'website', +}: PageMetaProps) { + const fullTitle = title ? `${title} | ${SITE_NAME}` : `${SITE_NAME} - Decision Tree Platform` + + return ( + + {fullTitle} + + + {/* Open Graph */} + + + + + {ogImage && } + + {/* Twitter */} + + + + {ogImage && } + + ) +} diff --git a/frontend/src/components/layout/NavItem.tsx b/frontend/src/components/layout/NavItem.tsx index 1225eba2..26da8534 100644 --- a/frontend/src/components/layout/NavItem.tsx +++ b/frontend/src/components/layout/NavItem.tsx @@ -1,6 +1,7 @@ import { Link, useLocation } from 'react-router-dom' import type { LucideIcon } from 'lucide-react' import { cn } from '@/lib/utils' +import { prefetchForRoute } from '@/lib/routePrefetch' interface NavSubItem { href: string @@ -36,6 +37,7 @@ export function NavItem({ href, icon: Icon, label, badge, matchPaths, collapsed, return ( prefetchForRoute(href)} className={cn( 'group relative flex items-center justify-center rounded-lg p-2 transition-all duration-120', isActive @@ -61,6 +63,7 @@ export function NavItem({ href, icon: Icon, label, badge, matchPaths, collapsed,
prefetchForRoute(href)} className={cn( 'group relative flex items-center gap-3 rounded-lg px-3 py-2 text-[0.8125rem] font-medium transition-all duration-120', isActive diff --git a/frontend/src/components/ui/Button.tsx b/frontend/src/components/ui/Button.tsx new file mode 100644 index 00000000..2b584873 --- /dev/null +++ b/frontend/src/components/ui/Button.tsx @@ -0,0 +1,63 @@ +import { cva, type VariantProps } from 'class-variance-authority' +import { cn } from '@/lib/utils' +import { Spinner } from '@/components/common/Spinner' + +const buttonVariants = cva( + 'inline-flex items-center justify-center gap-2 font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 active:scale-[0.97]', + { + variants: { + variant: { + primary: + 'bg-gradient-brand text-[#101114] font-semibold shadow-lg shadow-primary/20 hover:opacity-90', + secondary: + 'bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-foreground hover:border-[rgba(255,255,255,0.12)] hover:bg-[rgba(255,255,255,0.06)]', + destructive: + 'bg-red-400/10 text-red-400 border border-red-400/20 hover:bg-red-400/20', + ghost: + 'text-muted-foreground hover:bg-accent hover:text-foreground', + link: + 'text-primary underline-offset-4 hover:underline p-0 h-auto', + }, + size: { + sm: 'h-8 px-3 text-xs rounded-lg', + md: 'h-9 px-4 text-sm rounded-[10px]', + lg: 'h-10 px-6 text-sm rounded-[10px]', + icon: 'size-9 rounded-lg', + 'icon-sm': 'size-8 rounded-lg', + }, + }, + defaultVariants: { + variant: 'primary', + size: 'md', + }, + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + loading?: boolean +} + +export function Button({ + className, + variant, + size, + loading, + children, + disabled, + ...props +}: ButtonProps) { + return ( + + ) +} + +export { buttonVariants } diff --git a/frontend/src/components/ui/FormField.tsx b/frontend/src/components/ui/FormField.tsx new file mode 100644 index 00000000..6e5faae3 --- /dev/null +++ b/frontend/src/components/ui/FormField.tsx @@ -0,0 +1,24 @@ +import type { ReactNode } from 'react' + +interface FormFieldProps { + label: string + htmlFor?: string + required?: boolean + hint?: string + children: ReactNode +} + +export function FormField({ label, htmlFor, required, hint, children }: FormFieldProps) { + return ( +
+ + {children} + {hint && ( +

{hint}

+ )} +
+ ) +} diff --git a/frontend/src/components/ui/Input.tsx b/frontend/src/components/ui/Input.tsx new file mode 100644 index 00000000..fd5505d2 --- /dev/null +++ b/frontend/src/components/ui/Input.tsx @@ -0,0 +1,35 @@ +import { cn } from '@/lib/utils' + +export interface InputProps extends React.InputHTMLAttributes { + error?: string +} + +export function Input({ className, error, id, ...props }: InputProps) { + return ( +
+ + {error && ( + + )} +
+ ) +} diff --git a/frontend/src/components/ui/Skeleton.tsx b/frontend/src/components/ui/Skeleton.tsx new file mode 100644 index 00000000..0744b535 --- /dev/null +++ b/frontend/src/components/ui/Skeleton.tsx @@ -0,0 +1,58 @@ +import { cn } from '@/lib/utils' + +interface SkeletonProps extends React.HTMLAttributes {} + +export function Skeleton({ className, ...props }: SkeletonProps) { + return ( +
+ ) +} + +export function CardSkeleton({ className }: { className?: string }) { + return ( +
+ + +
+ + +
+
+ ) +} + +export function TableRowSkeleton({ cols = 4 }: { cols?: number }) { + return ( +
+ {Array.from({ length: cols }).map((_, i) => ( + + ))} +
+ ) +} + +export function ListSkeleton({ count = 5, className }: { count?: number; className?: string }) { + return ( +
+ {Array.from({ length: count }).map((_, i) => ( +
+ +
+ + +
+
+ ))} +
+ ) +} diff --git a/frontend/src/components/ui/Textarea.tsx b/frontend/src/components/ui/Textarea.tsx new file mode 100644 index 00000000..3de30808 --- /dev/null +++ b/frontend/src/components/ui/Textarea.tsx @@ -0,0 +1,35 @@ +import { cn } from '@/lib/utils' + +export interface TextareaProps extends React.TextareaHTMLAttributes { + error?: string +} + +export function Textarea({ className, error, id, ...props }: TextareaProps) { + return ( +
+