Skip to content

feat(editor): CodeMirror editable text/code editor (#862) - #872

Merged
softmarshmallow merged 3 commits into
mainfrom
feat/codemirror-text-editor
Jun 19, 2026
Merged

softmarshmallow merged 3 commits into
mainfrom
feat/codemirror-text-editor

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds an owned CodeMirror 6 binding as the editable text surface for the desktop workbench. Resolves #862.

  • .md / .markdown open in an editable editor with a Streamdown preview toggle.
  • Every other text format now opens editable (superseding the read-only Shiki text viewer) — the editable fallback the workbench needs regardless of markdown.

Why CodeMirror (not a WYSIWYG/Notion-style wrapper)

A real source editor round-trips byte-for-byte (serialization is identity), so it safely backs both the markdown case and the generic fallback without a lossy IR. We wire @codemirror/* directly — a thin React mount with compartments for language/theme/readOnly — not @uiw/react-codemirror. The component lives in components/codemirror, a sibling of components/monaco, and is host-agnostic.

What's included

  • components/codemirror — the owned mount (CodeMirrorEditor + CodeMirrorHandle) and lazy filename→language resolution (@codemirror/language-data; .jsonc/.json5 aliased to JSON).
  • editor-pane-code-editor.tsx — the editable pane; reuses the editor-agnostic feat(desktop): watch workspace files — refresh open editor + file tree on external change, with save-conflict guard (VSCode model) #805 save/dirty/conflict machinery from the SVG pane.
  • editor-pane-save-ui.tsx — shared dirty badge / save-error toast / conflict dialog, extracted from the SVG pane (which now imports them).
  • Routing (editor-pane-tab.tsx) — .md → markdown editor, catch-all text → code editor; drops the hand-kept Shiki ext→lang map.
  • UI demo at /ui/components/codemirror (registered in the dev UI nav).

Notable: no built-in find/replace

CodeMirror's findNext/findPrevious open the search panel whenever the query is empty (their searchCommand fallback to openSearchPanel), so the panel can't be cleanly suppressed while using those commands. Find is therefore fully owned: a query StateField drives a match highlighter and selection-based next/prev, and basicSetup's search keys are overridden at highest precedence so nothing can reach openSearchPanel. The result is a minimal custom find bar (search + highlight + next/prev, no replace).

Verification

  • tsc 0 errors, oxlint clean, oxfmt clean.
  • Component + demo verified live in the browser: renders/edits, markdown + embedded-code highlighting, language-preset swap, opaque gutter (masks content on horizontal scroll), and the find bar — including the regression that empty-query Enter and Mod-g never open the built-in panel.

Scope / reviewer notes

  • The pane is desktop-only (talks to the Electron workspace fs bridge), so its live edit→save→conflict flow isn't exercisable from a plain web dev server; verified by code + the host-agnostic component verified in-browser.
  • The now-orphaned read-only MarkdownViewer/TextViewer/ShikiBlock in editor-pane-viewers.tsx are left for a focused follow-up cleanup (kept out to keep this diff reviewable).

Summary by CodeRabbit

  • New Features
    • Added a CodeMirror-based code editor with syntax highlighting and preset document templates.
    • Included an integrated find experience with next/previous navigation and match highlighting.
    • Added read-only mode toggle support for the editor surface and demo page.
    • Implemented save conflict detection with options to keep editing, reload, or overwrite.
    • Added unsaved-changes and saving visual indicators, plus save error toasts.
    • Enabled markdown edit/preview within the code editor and added a new dev UI entry for CodeMirror.

Adds an owned CodeMirror 6 binding as the editable text surface for the
desktop workbench. `.md`/`.markdown` open in an editable editor with a
Streamdown preview toggle, and every other text format now opens editable
too (superseding the read-only Shiki text viewer) — the editable fallback
the workbench needs regardless of markdown.

Why CodeMirror (not a WYSIWYG wrapper): a real source editor round-trips
byte-for-byte (serialization is identity), so it safely backs both the
markdown case and the generic fallback. The binding is owned directly over
`@codemirror/*` (no `@uiw/react-codemirror`) — a thin React mount with
compartments for language/theme/readOnly. Lives in `components/codemirror`,
a sibling of `components/monaco`.

- Reuses the editor-agnostic #805 save/dirty/conflict machinery from the SVG
  pane; extracts the shared save chrome into `editor-pane-save-ui.tsx`.
- Language resolved lazily from the filename via `@codemirror/language-data`;
  `.jsonc`/`.json5` aliased to JSON.
- Find: NO built-in find/replace panel. CodeMirror's `findNext`/`findPrevious`
  open the panel whenever the query is empty (their `searchCommand` fallback),
  so search is fully owned — a query StateField drives a match highlighter and
  selection-based next/prev, and basicSetup's search keys are overridden so
  nothing can reach `openSearchPanel`.
- Adds a UI demo at /ui/components/codemirror (registered in the dev UI nav).

The pane is desktop-only (talks to the workspace fs bridge); the editor
component and its demo are host-agnostic and verified in the browser.
@vercel

vercel Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
grida Ready Ready Preview, Comment Jun 19, 2026 9:28am
6 Skipped Deployments
Project Deployment Actions Updated (UTC)
code Ignored Ignored Jun 19, 2026 9:28am
docs Ignored Ignored Preview Jun 19, 2026 9:28am
legacy Ignored Ignored Jun 19, 2026 9:28am
backgrounds Skipped Skipped Jun 19, 2026 9:28am
blog Skipped Skipped Jun 19, 2026 9:28am
viewer Skipped Skipped Jun 19, 2026 9:28am

Request Review

@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

An error occurred during the review process. Please try again later.

Walkthrough

Introduces a CodeMirror 6 React binding (CodeMirrorEditor) with an owned find system, lazy language resolution, and compartment-based live reconfiguration. Uses it in a new EditorPaneCodeEditor workspace pane that handles file loading, dirty tracking with mtime preconditions, save/conflict/error UI, and a Streamdown markdown preview toggle. Extracts shared save UI from the SVG editor pane and updates the file-mode dispatcher to route text and markdown files through the new editor.

Changes

CodeMirror editor binding and workspace text/markdown pane

Layer / File(s) Summary
Dependencies and language resolution
editor/package.json, editor/components/codemirror/languages.ts
Adds @codemirror/* and codemirror packages to dependencies. Introduces resolveLanguage(relPath) via LanguageDescription.matchFilename with jsonc/json5 aliasing, and re-exports languages as codeLanguages.
CodeMirrorEditor component
editor/components/codemirror/index.tsx
Exports CodeMirrorHandle and CodeMirrorEditorProps. Defines baseTheme/themeExtension, an owned find StateField and ViewPlugin with case-insensitive match decorations and gotoMatch navigation, mounts a single EditorView with Compartments for language/theme/readOnly, overrides Mod-f and navigation keymaps, and exposes getValue/setValue/focus via useImperativeHandle. Renders a find overlay UI.
Shared save UI extraction
editor/scaffolds/desktop/workbench/editor-pane-save-ui.tsx, editor/scaffolds/desktop/workbench/editor-pane-svg-editor.tsx
Extracts SaveConflictDialog, DirtyBadge, and SaveErrorToast into a dedicated module. Updates editor-pane-svg-editor.tsx to import from that module instead of local definitions.
Workspace code editor pane
editor/scaffolds/desktop/workbench/editor-pane-code-editor.tsx
Implements EditorPaneCodeEditor (file load/error shell) and Surface: dirty/version tracking with monotonic counters, commitWrite with expectedMtime precondition, reloadFromDisk with redundant-reload suppression, overwriteAnyway, useWorkspaceChanges reload listener, Cmd+S handler, edit/preview toggle, and render with Streamdown overlay, DirtyBadge, SaveErrorToast, and SaveConflictDialog.
Editor tab dispatcher update
editor/scaffolds/desktop/workbench/editor-pane-tab.tsx
Renames markdown mode to "markdown-editor", removes the lang field and Shiki imports from the "text" variant, routes both modes through EditorPaneCodeEditor, and simplifies detectFileMode to fall through to "text" without extension-to-language lookup.
Dev demo page and nav entry
editor/app/(dev)/ui/_nav.ts, editor/app/(dev)/ui/components/codemirror/page.tsx
Adds CodeMirrorDemoPage with preset documents, async language resolution with cancellation, read-only toggle, and serialized output panel. Registers the page in uiNavGroups as "Code Editor (CodeMirror)".

Sequence Diagram

sequenceDiagram
  participant User
  participant EditorPaneCodeEditor
  participant CodeMirrorEditor
  participant WorkspaceBridge
  participant SaveConflictDialog

  User->>EditorPaneCodeEditor: open file (workspaceId, relPath)
  EditorPaneCodeEditor->>WorkspaceBridge: readFile(relPath)
  WorkspaceBridge-->>EditorPaneCodeEditor: content + mtime
  EditorPaneCodeEditor->>CodeMirrorEditor: mount with initialValue + language

  User->>CodeMirrorEditor: edit document
  CodeMirrorEditor->>EditorPaneCodeEditor: onDocChange()
  EditorPaneCodeEditor->>EditorPaneCodeEditor: bump contentVersion, mark dirty

  User->>EditorPaneCodeEditor: Cmd+S
  EditorPaneCodeEditor->>CodeMirrorEditor: getValue()
  CodeMirrorEditor-->>EditorPaneCodeEditor: current doc string
  EditorPaneCodeEditor->>WorkspaceBridge: writeFile(content, expectedMtime)

  alt conflict
    WorkspaceBridge-->>EditorPaneCodeEditor: mtime mismatch error
    EditorPaneCodeEditor->>SaveConflictDialog: open
    User->>SaveConflictDialog: Overwrite
    SaveConflictDialog->>EditorPaneCodeEditor: overwriteAnyway()
    EditorPaneCodeEditor->>WorkspaceBridge: writeFile(content, no mtime guard)
    WorkspaceBridge-->>EditorPaneCodeEditor: ok
  else success
    WorkspaceBridge-->>EditorPaneCodeEditor: ok
    EditorPaneCodeEditor->>EditorPaneCodeEditor: update storedMtime, re-baseline dirty
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • gridaco/grida#750: Also modifies editor/app/(dev)/ui/_nav.ts to extend uiNavGroups with new nav entries, the same pattern used here to add the CodeMirror demo page.

Suggested labels

ux

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(editor): CodeMirror editable text/code editor' accurately describes the main change: adding CodeMirror 6 as an editable text/code editor component for the workspace editor pane.
Linked Issues check ✅ Passed The PR addresses all key coding objectives from issue #862: CodeMirror 6 source editor with language resolution, Streamdown preview toggle for markdown, custom find implementation, save/conflict machinery reuse, routing integration, and editable markdown promotion.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the PR objectives: CodeMirror component/demo, editor pane integration, save UI extraction, and routing updates. No extraneous changes detected outside issue #862 requirements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/codemirror-text-editor

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 879f5716b4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@editor/app/`(dev)/ui/components/codemirror/page.tsx:
- Around line 101-105: The useEffect hook calls
languageFor(PRESETS[activeIndex]) and chains a .then() to handle the resolved
extension, but there is no error handling for promise rejections. If the
language load fails, this will cause an unhandled rejection and leave the UI in
an inconsistent state. Add a .catch() handler after the .then() to catch any
errors from the language loading promise and set the language to undefined as a
fallback, ensuring the cancelled flag check is also applied in the catch block.

In `@editor/scaffolds/desktop/workbench/editor-pane-code-editor.tsx`:
- Around line 312-326: The CodeMirrorEditor component in this pane does not
regain focus when the tab becomes active after being hidden, because the
autoFocus prop only affects focus at mount time. Add a useEffect hook that
watches the active prop and programmatically focuses the editor using the
handleRef reference whenever active becomes true. This ensures that when a user
switches to this tab, focus is restored to the editor so typing works
immediately without requiring a manual click.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f7bf01c5-81ed-4acc-96e6-8703bebc314b

📥 Commits

Reviewing files that changed from the base of the PR and between 739b03f and 879f571.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (9)
  • editor/app/(dev)/ui/_nav.ts
  • editor/app/(dev)/ui/components/codemirror/page.tsx
  • editor/components/codemirror/index.tsx
  • editor/components/codemirror/languages.ts
  • editor/package.json
  • editor/scaffolds/desktop/workbench/editor-pane-code-editor.tsx
  • editor/scaffolds/desktop/workbench/editor-pane-save-ui.tsx
  • editor/scaffolds/desktop/workbench/editor-pane-svg-editor.tsx
  • editor/scaffolds/desktop/workbench/editor-pane-tab.tsx

When a markdown tab was in Preview and reloadFromDisk ran (clean watcher
refresh, or the conflict dialog's "Reload from disk"), only the hidden
CodeMirror doc was updated — the preview overlay kept rendering the stale
pre-reload snapshot while the pane was re-baselined clean. Sync
previewContent to the reloaded bytes too.
CodeRabbit review #872:
- Lazy grammar loads (`resolveLanguage` / demo `languageFor`) had no rejection
  path; a failed dynamic import would surface as an unhandled rejection. Add a
  `.catch` that falls back to plain text. Applied to both the pane and the demo
  (the pane had the same pattern CodeRabbit flagged on the demo).
- Tabs stay mounted across switches, so `autoFocus` (mount-only) didn't refocus
  when the pane became active again. Focus the editor on activate (skipping the
  read-only markdown preview overlay) so typing lands without a click.
@vercel
vercel Bot temporarily deployed to Preview – blog June 19, 2026 09:25 Inactive
@vercel
vercel Bot temporarily deployed to Preview – viewer June 19, 2026 09:25 Inactive
@vercel
vercel Bot temporarily deployed to Preview – backgrounds June 19, 2026 09:25 Inactive
@softmarshmallow
softmarshmallow merged commit dcd16fc into main Jun 19, 2026
6 checks passed

This branch was successfully deployed

2 active (1 outdated) and 3 inactive deployments
Preview – grida — a3dc1d7f Deployed Jun 19, 2026 by vercel[bot]
Preview – blog — a3dc1d7f Deployed Jun 19, 2026 by vercel[bot]
Preview – viewer — a3dc1d7f Deployed Jun 19, 2026 by vercel[bot]
Preview – backgrounds — a3dc1d7f Deployed Jun 19, 2026 by vercel[bot]
Preview – docs — 879f5716 Deployed Jun 19, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(desktop): editable Markdown editor for workspace .md files — source-fidelity (CodeMirror + Streamdown), not TipTap

1 participant