Skip to content

Commit b71a63e

Browse files
committed
feat: React JSX Live runtime — interactive React components in markdown
- Added exec-jsx.js (658 lines): Babel transpilation, sandboxed iframe rendering, 12+ auto-detected CDN libraries - Added ⚛ React JSX Live toolbar button in Coding dropdown - jsx-autorun blocks auto-render on page load, jsx blocks have manual Run - Auto-detects Recharts, Tailwind, Lucide, Framer Motion, Chart.js, Google Fonts, and more - Fixed: exports is not defined — import/export stripping moved to pre-transpilation - Added Help Mode docs with 3 FAQ examples - 20 Playwright tests covering rendering, state, library detection, Run All pipeline
1 parent 5b47900 commit b71a63e

File tree

12 files changed

+1358
-10
lines changed

12 files changed

+1358
-10
lines changed

CHANGELOG-jsx-runtime.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# React JSX Live Runtime — Interactive React Components in Markdown
2+
3+
- Added `exec-jsx.js` — full React JSX runtime with Babel standalone transpilation, sandboxed iframe rendering, and auto-detected CDN library injection
4+
- Added `⚛ React JSX Live` button to the Coding toolbar dropdown (between HTML Live and JS)
5+
- Auto-detects and loads 12+ libraries from CDN: Recharts, Tailwind CSS, Lucide React, Framer Motion, Lodash, date-fns, dayjs, PapaParse, UUID, clsx, Chart.js, Google Fonts
6+
- `jsx-autorun` blocks auto-render on page load (same pattern as `html-autorun`) with source code hidden
7+
- `jsx` blocks show source with manual ▶ Run button
8+
- Toolbar badge shows "⚛ React JSX" for JSX blocks
9+
- Support for `export default function App()` component detection and first PascalCase function fallback
10+
- Load File button on JSX blocks to import `.jsx` files from disk
11+
- Added Help Mode documentation for React JSX Live with 3 FAQ examples (counter, Recharts chart, Tailwind styling)
12+
- Updated Code Block and Run All help descriptions to mention JSX (7 languages now)
13+
- Fixed: `exports is not defined` runtime error — moved import/export stripping to before Babel transpilation to prevent `env` preset from generating CommonJS references
14+
- Added 20 Playwright tests covering module lifecycle, block detection, rendering, interactive state, library auto-detection, complex components, and Run All pipeline
15+
16+
---
17+
18+
## Summary
19+
20+
Added a complete React JSX runtime to TextAgent, enabling users to write interactive React components directly in markdown code blocks. Components are transpiled via `@babel/standalone`, rendered in sandboxed iframes with React 18 from CDN, and automatically detect required libraries (Recharts, Tailwind, etc.) for injection. A critical bug where Babel's `env` preset generated CommonJS `exports` references was fixed by pre-processing import/export statements before transpilation.
21+
22+
---
23+
24+
## 1. React JSX Runtime Engine
25+
**Files:** `js/exec-jsx.js`
26+
**What:** New 658-line module implementing the full JSX execution pipeline: Babel lazy-loading, JSX→JS transpilation with `['env', { modules: false }], 'react'` presets, import/export pre-processing (strips ES module syntax before Babel sees it), auto-detection of 12+ libraries via `LIB_REGISTRY` regex patterns, CDN script/link injection into sandboxed `srcdoc` iframes, component detection via PascalCase function matching, toolbar with Run/Load File/language badge, and autorun support.
27+
**Impact:** Users can write `jsx-autorun` blocks with `import { useState } from "react"` and `export default function App()` and see interactive React components rendered live in the preview. Complex dashboards with state, filtering, sorting, and charts work out of the box.
28+
29+
## 2. Toolbar Integration
30+
**Files:** `index.html`, `js/coding-blocks.js`
31+
**What:** Added `⚛ React JSX Live` button to the coding dropdown in `index.html` (between HTML Live and JS). Template in `coding-blocks.js` inserts a `jsx-autorun` block with a `useState` counter component.
32+
**Impact:** One-click insertion of JSX blocks from the toolbar with a ready-to-run template.
33+
34+
## 3. Renderer & Execution Pipeline
35+
**Files:** `js/renderer.js`, `js/exec-registry.js`, `js/exec-controller.js`, `src/main.js`
36+
**What:** Added JSX block detection in `renderer.js` (lines 70-74) with `data-autorun` attribute for `jsx-autorun`; registered `jsx` and `jsx-autorun` language mappings in `exec-registry.js`; added JSX container CSS class in `exec-controller.js`; lazy-loaded `exec-jsx.js` in `main.js` Phase 3b.
37+
**Impact:** JSX blocks are fully integrated into the execution pipeline — they render in preview, execute via Run All, and support the same toolbar/autorun patterns as HTML blocks.
38+
39+
## 4. Help Mode Documentation
40+
**Files:** `js/help-mode.js`
41+
**What:** Added `[data-action="coding-jsx"]` help entry with description, 3 FAQ examples (counter, Recharts chart, Tailwind), and updated Code Block/Run All descriptions from "6 languages" to "7 languages".
42+
**Impact:** Users can discover JSX capabilities via Help Mode with copy-pasteable examples.
43+
44+
## 5. Bug Fix: `exports is not defined`
45+
**Files:** `js/exec-jsx.js`
46+
**What:** Moved import/export stripping from post-transpilation to pre-transpilation. Previously, `export default function App()` was passed to Babel which transformed it to `Object.defineProperty(exports, ...)` — but `exports` doesn't exist in browser iframes. Now imports/exports are stripped before Babel sees them, so Babel only processes plain function declarations and JSX.
47+
**Impact:** All JSX components with `export default` now render correctly instead of throwing "exports is not defined" at runtime.
48+
49+
## 6. Automated Test Suite
50+
**Files:** `tests/feature/exec-jsx.spec.js`
51+
**What:** 528-line Playwright test suite with 20 tests covering: module loading (2), block detection (4), toolbar badge (1), rendering (4), interactive state (1), library auto-detection (4), complex components (2), and Run All pipeline (2).
52+
**Impact:** Comprehensive regression coverage for the JSX runtime. All 20 tests pass.
53+
54+
---
55+
56+
## Files Changed (9 total)
57+
58+
| File | Lines Changed | Type |
59+
|------|:---:|------|
60+
| `js/exec-jsx.js` | +658 | New JSX runtime engine |
61+
| `tests/feature/exec-jsx.spec.js` | +528 | New Playwright test suite |
62+
| `index.html` | +2 | JSX button in toolbar dropdown |
63+
| `js/coding-blocks.js` | +1 −1 | JSX template already existed |
64+
| `js/renderer.js` | +10 −1 | JSX block detection in renderer |
65+
| `js/exec-registry.js` | +3 −1 | jsx/jsx-autorun language mapping |
66+
| `js/exec-controller.js` | +1 | JSX container CSS class |
67+
| `js/help-mode.js` | +15 −2 | Help docs + FAQ examples |
68+
| `src/main.js` | +1 | Lazy-load exec-jsx.js |

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
| **Sharing** | AES-256-GCM encrypted sharing via Firebase; **compact share links** (`#s=<id>`, ~36 chars vs ~111 chars) with encryption key stored server-side; **custom named links** — optionally choose your own memorable name (e.g. `#s=mynotes`) with case-insensitive uniqueness, slug validation, and reserved-word protection; read-only shared links with auto-dismiss banner + floating "Read-only" pill indicator, **clean read-only view** (composer FAB + agent panel hidden when header collapsed), optional password protection (zero-knowledge — passphrase-derived key never stored); **view-locked links** (lock recipients to PPT or Preview mode, stored in Firestore to prevent URL tampering); **editor links** — cryptographic edit key system (`&ek=<token>`) grants write access to trusted collaborators (SHA-256 verified, AES-GCM encrypted write-token, auto-save to same document); **shared versions tracking** ("Previously Shared" panel with timestamps, view-mode badges, copy/delete actions); backward-compatible with legacy `#id=...&k=...` links |
3636
| **Presentation** | Slide mode using `---` separators, keyboard navigation, multiple layouts & transitions, speaker notes, overview grid, 20+ PPT templates with image backgrounds |
3737
| **Desktop** | Native app via Neutralino.js with system tray and offline support |
38-
| **Code Execution** | 7 languages in-browser: Bash ([just-bash](https://justbash.dev/)), Math (Nerdamer), LaTeX (MathJax + Nerdamer evaluation), Python ([Pyodide](https://pyodide.org/)), HTML (sandboxed iframe, `html-autorun` for widgets/quizzes), JavaScript (sandboxed iframe), SQL ([sql.js](https://sql.js.org/) SQLite) · 25+ compiled languages via [Judge0 CE](https://ce.judge0.com): C, C++, Rust, Go, Java, TypeScript, Kotlin, Scala, Ruby, Swift, Haskell, Dart, C#, and more · **▶ Run All** notebook engine — one-click sequential execution with preflight dialog (block table with model/status), pre-execution model loading (AI + TTS auto-loaded before blocks run), progress bar, abort, per-block status badges, detailed console logging, and SQLite shared context store |
38+
| **Code Execution** | 8 languages in-browser: Bash ([just-bash](https://justbash.dev/)), Math (Nerdamer), LaTeX (MathJax + Nerdamer evaluation), Python ([Pyodide](https://pyodide.org/)), HTML (sandboxed iframe, `html-autorun` for widgets/quizzes), React JSX (`jsx-autorun` with Babel transpilation, auto-detected CDN libraries: Recharts, Tailwind, Lucide, Framer Motion, Chart.js, and 6+ more), JavaScript (sandboxed iframe), SQL ([sql.js](https://sql.js.org/) SQLite) · 25+ compiled languages via [Judge0 CE](https://ce.judge0.com): C, C++, Rust, Go, Java, TypeScript, Kotlin, Scala, Ruby, Swift, Haskell, Dart, C#, and more · **▶ Run All** notebook engine — one-click sequential execution with preflight dialog (block table with model/status), pre-execution model loading (AI + TTS auto-loaded before blocks run), progress bar, abort, per-block status badges, detailed console logging, and SQLite shared context store |
3939
| **Security** | Content Security Policy (CSP), SRI integrity hashes, XSS sanitization (DOMPurify), ReDoS protection, Firestore write-token ownership, API keys via HTTP headers, postMessage origin validation, 8-char password minimum, sandboxed code execution, Cloudflare Turnstile CAPTCHA on email endpoint, automated security scanner (`scripts/security-check.sh`) with pre-commit integration |
4040
| **AI Document Tags** | `{{@AI:}}` text generation (`@think: Yes` for deep reasoning), `{{@Image:}}` image generation (Gemini Imagen), `{{@OCR:}}` image-to-text extraction (Text/Math/Table modes via Granite Docling 258M, Florence-2 230M, or GLM-OCR 1.5B, 📷 live camera capture + 📎 image/PDF upload, PDF page rendering via pdf.js), `{{@TTS:}}` text-to-speech playback (Kokoro TTS per card, language selector, ▶ Play / ⬇ Save WAV), `{{@STT:}}` speech-to-text dictation (engine selector: Whisper/Voxtral/Web Speech API, 11 languages, Record/Stop/Insert/Clear), `{{@Translate:}}` translation (target language selector, integrated TTS pronunciation, cloud model routing), `{{@Game:}}` game builder (AI-generated or pre-built, Canvas 2D/Three.js/P5.js, import/export HTML), `{{@Draw:}}` whiteboard (Excalidraw + Mermaid, AI diagram generation with per-card model selector + 🚀 Generate, robust JSON repair for local models, Insert/PNG/SVG export, 📚 Library Browser with 29 bundled packs in 6 categories), `{{@Tools:}}` web tools (Jina Reader scrape + Jina Search, multi-URL scraping, API key modal, Accept/Reject/Copy results), `{{@Research:}}` autonomous experiment loop (Pyodide-powered, AI-driven code optimization with live results table, keep/discard metric tracking, configurable @metric/@direction/@max_iterations), `{{Annotate:}}` canvas annotation overlay (freehand pen/highlighter/eraser/shapes, `@text:` mode renders text with **Pretext-style scanline reflow** — text flows live around strokes in real-time, 📖 Present button switches to live reading/drawing mode, ↩ Undo / 🗑 Clear / 📥 PNG export), `{{@Vision:}}` omni-modal analysis (**Gemma 4 E2B/E4B** local model — image, audio, video frame extraction, text; 📷 camera capture + 📎 upload; video auto-extracted as 4 JPEG keyframes via Canvas; cyan-themed card; dynamic model switching — auto-swaps to Gemma 4 then restores prior model) — `@` prefix syntax on all tag types + metadata fields (`@name`, `@use`, `@think`, `@search`, `@prompt`, `@step`, `@upload`, `@model`, `@engine`, `@lang`, `@prebuilt`); `@model:` field persists selected model per card with intelligent defaults (OCR→`granite-docling`, TTS→`kokoro-tts`, STT→`voxtral-stt`, Image→`imagen-ultra`, Vision→`gemma4-e2b`); editable `@prompt:` textarea and `@step:` inputs in preview cards; description/prompt separation (bare text = label, `@prompt:` = AI instruction); 📎 image/PDF upload for multimodal vision analysis; per-card model selector with document-portable model persistence, concurrent block operations |
4141
| **🔌 API Calls** | `{{API:}}` REST API integration — GET/POST/PUT/DELETE methods, custom headers, JSON body, response stored in `$(api_varName)` variables; inline review panel; toolbar GET/POST buttons |
@@ -50,7 +50,7 @@
5050
| **💾 Disk Workspace** | Folder-backed storage via File System Access API — "Open Folder" in sidebar header; `.md` files read/written directly to disk; `.textagent/workspace.json` manifest; debounced autosave ("💾 Saved to disk" indicator); refresh from disk for external edits; disconnect to revert to localStorage; auto-reconnect on reload via IndexedDB handles; unified action modal for rename/duplicate/delete with confirmation; Chromium-only (hidden in unsupported browsers) |
5151
| **📈 Finance Dashboard** | Stock/crypto/index dashboard templates with live TradingView charts; dynamic grid via `data-var-prefix` (add/remove tickers in `@variables` table, grid auto-adjusts); configurable chart range (`1M`, `12M`, `36M`), interval (`D`, `W`, `M`), EMA period (default 52), and card size via `data-height`; single cards auto-expand to full width; interactive 1M/1Y/3Y range + 52D/52W/52M EMA toggle buttons; `@variables` table persists after ⚡ Vars for re-editing; JS code block generates grid HTML from variables |
5252
| **Extras** | Auto-save (localStorage + cloud), table of contents, image paste, 137+ templates (16 categories: AI, Agents, API Explorer, Coding, Creative, Documentation, Finance, Games, Maths, PPT, Project, Quiz, Science, Skills, Tables, Technical), AI Model Manager template (local model reference with sizes, privacy, and capabilities), template variable substitution (`$(varName)` with auto-detect), table spreadsheet tools (sort, filter, stats, chart, add row/col, inline cell edit, CSV/MD export), content statistics, modular codebase (13+ JS modules), fully responsive mobile UI with scrollable Quick Action Bar (Files, Search, TOC, Share, Copy, Tools, AI, Model, Upload, Help) and formatting toolbar, multi-file workspace sidebar, compact header mode with collapsible Tools dropdown (Presentation, Zen, Word Wrap, Focus, Voice, Dark Mode, Preview Theme), Clear All / Clear Selection buttons (undoable via Ctrl+Z), auto-naming (Untitled files derive name from first 10 content characters) |
53-
| **Dev Tooling** | ESLint + Prettier (lint, format:check), Playwright test suite — 572 tests across smoke, feature, integration, dev, regression, performance, quality, and security categories (import, export, share, view-mode, editor, email-to-self, secure share, startup timing, export integrity, persistence, module loading, disk workspace, context memory, exec engine, build validation, load-time, accessibility, video player, TTS, STT, file converters, stock widget, embed grid, model registry, model tag, game tag, draw docgen, readonly mode, excalidraw library, help mode, page view, table tools, API tag, Linux tag, template loading, inline rename, presentation, static analysis, code smell, XSS hardening, Florence-2 model, Docling model, GLM-OCR model, TTS download), Firestore rules validation (21 tests), automated security scanner (13 checks, 3 severity tiers), pre-commit changelog + security enforcement, GitHub Actions CI |
53+
| **Dev Tooling** | ESLint + Prettier (lint, format:check), Playwright test suite — 592 tests across smoke, feature, integration, dev, regression, performance, quality, and security categories (import, export, share, view-mode, editor, email-to-self, secure share, startup timing, export integrity, persistence, module loading, disk workspace, context memory, exec engine, exec-jsx, build validation, load-time, accessibility, video player, TTS, STT, file converters, stock widget, embed grid, model registry, model tag, game tag, draw docgen, readonly mode, excalidraw library, help mode, page view, table tools, API tag, Linux tag, template loading, inline rename, presentation, static analysis, code smell, XSS hardening, Florence-2 model, Docling model, GLM-OCR model, TTS download), Firestore rules validation (21 tests), automated security scanner (13 checks, 3 severity tiers), pre-commit changelog + security enforcement, GitHub Actions CI |
5454
| **🎥 RecStudio** | Full-screen screen & camera recorder with 4 modes (Screen only, Screen + Camera, Camera only, Whiteboard); Canvas-based compositing at 1920×1080 / 60fps; interactive teleprompter (draggable, resizable, font size A−/A+ 10–48px, scroll speed ◁/▷ 0.5x–5x, play/pause scroll, 3-level transparency toggle with readable text on any background); whiteboard with 7 tools (Pen, Highlighter, Eraser, Line, Rectangle, Ellipse, Text), 10 colors, undo/redo; PiP webcam with shape selector (Circle/Square/Full/Off); device selection dropdowns; countdown timer; recording timer; post-recording review + WebM download; all client-side via MediaRecorder + Canvas APIs |
5555

5656
## 🤖 AI Assistant
@@ -548,6 +548,7 @@ TextAgent has undergone significant evolution since its inception. What started
548548

549549
| Date | Commits | Feature / Update |
550550
|------|---------|-----------------:|
551+
| **2026-04-12** ||**React JSX Live Runtime** — new `jsx-autorun` code block type for interactive React components in markdown; `exec-jsx.js` (658 lines) with `@babel/standalone` transpilation (`['env', { modules: false }], 'react'` presets), sandboxed iframe rendering via React 18 CDN, and `LIB_REGISTRY` auto-detection of 12+ libraries (Recharts, Tailwind CSS, Lucide React, Framer Motion, Lodash, date-fns, dayjs, PapaParse, UUID, clsx, Chart.js, Google Fonts) with CDN injection; `⚛ React JSX Live` toolbar button in Coding dropdown; Help Mode docs with 3 FAQ examples; `export default function App()` component detection with PascalCase fallback; Load File button for `.jsx` import; Fixed: `exports is not defined` runtime error (import/export stripping moved to pre-transpilation to prevent Babel `env` preset from generating CommonJS references); 20 Playwright tests (module lifecycle, rendering, state, library detection, Run All pipeline) |
551552
| **2026-04-08** ||**Star on GitHub Button** — new gold/amber gradient pill button in header next to Issues button linking to the GitHub repo for starring; `.star-github-pill` CSS class with dark mode variant; fixed Issues button inline styles that prevented proper `.help-mode-pill` rendering |
552553
| **2026-04-05** || 🔬 **Interactive Periodic Table Template** — new Science template category (`bi-atom` icon) with full 118-element interactive periodic table; React + Babel `html-autorun` block; 18×10 grid layout with 11 color-coded element categories (nonmetal, noble gas, alkali, alkaline, transition, post-transition, metalloid, halogen, lanthanide, actinide, unknown); search filter and category highlight; element detail view with 4 tabbed sections (Overview, Properties, Structure, Uses & Hazards); interactive Bohr model atom visualization with concentric orbit rings, animated electrons, 3D nucleus cluster, mouse drag rotation/tilt, scroll zoom; dark/light theme toggle (30+ CSS tokens per theme); lanthanide (57–71) and actinide (89–103) rows with labels; left-aligned header controls |
553554
| **2026-04-04** | — | 🤖 **Agentic Tool Calling** — transitioned AI assistant from firehose context injection to **model-driven tool calling** for Groq cloud models; `buildToolDefinitions()` registers enabled connectors (Weather, HN, GitHub, Slack) + web search as OpenAI-format tools; model decides which tools to call via `tool_choice: 'auto'`; `executeToolCall()` runs tools in parallel; `handleToolCalls()` orchestrates two-pass generation (Pass 1: tool selection, Pass 2: synthesis with results); **query-relevance filter** (`queryNeedsConnectors()`) for local models — keyword-based gating prevents weather/news injection on general queries like "what is algebra?"; `extractLocationFromQuery()` with 5 extraction strategies (preposition patterns, weather patterns, capitalized words) for smart geocoding; softened grounding header allows general knowledge answers when connector data is irrelevant; Groq worker updated with non-streaming tool detection path and `rawMessages` for Pass 2; model-aware context budgets (4K local / 30K cloud); WebGPU buffer overflow translated to user-friendly error messages; model-size-aware context limits (0.8B→4K, 2B→8K, 4B+→32K chars) |

0 commit comments

Comments
 (0)