mkeditor
CLAUDE.md234 starsChanged 7 months agoMITView on GitHub
Electron-based markdown editor built around Monaco. The same TypeScript bundle ships as a desktop app (Electron wraps it) and as a pure web app (deployed to GitHub Pages). Current version: 4.0.0. The renderer is React 19 + shadcn/ui + Tailwind v4 on top of a set of plain-TS managers (Monaco, files, settings, markdown, IPC bridge). Migration history: docs/REACT_MIGRATION.md. Subsystem READMEs: src/app/README.md, src/browser/README.md, src/browser/extensions/README.md. For deeper detail see docs/ARCHITECTURE.md. For planned work see docs/ROADMAP.md. The same renderer bundle detects which mode…
The file
We split this CLAUDE.md into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 21
Web: no bridge. Settings + last-edited content go to localStorage (mkeditor-settings, mkeditor-export-settings, mkeditor-content).
- Very specific: line 60
When adding new cross-boundary functionality, follow this same seam pattern — don't add new imports from react/ into core/.
- Very specific: line 108
Single Monaco instance: Only EditorManager.create(...) calls editor.create(...).
- Very specific: line 113
Mode flag: Every persistence-touching subsystem takes mode: 'web' | 'desktop'.
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
MKEditor — Project Context
Electron-based markdown editor built around Monaco. The same TypeScript bundle ships as a desktop app (Electron wraps it) and as a pure web app (deployed to GitHub Pages). Current version: 4.0.0.
The renderer is React 19 + shadcn/ui + Tailwind v4 on top of a set of plain-TS managers (Monaco, files, settings, markdown, IPC bridge). Migration history: docs/REACT_MIGRATION.md. Subsystem READMEs: src/app/README.md, src/browser/README.md, src/browser/extensions/README.md. For deeper detail see docs/ARCHITECTURE.md. For planned work see docs/ROADMAP.md.
Repo Layout
- src/app/ — Electron main process (Node). Compiled by
tscvia scripts/compile-app.mjs todist/app/. - src/browser/ — Renderer (Monaco + React). Bundled by webpack to
dist/mkeditor.bundle.js+dist/mkeditor.bundle.css. - locale/ — i18next JSON resources, one folder per language. Build step combines per-namespace JSON into
all.jsonvia scripts/combine-locales.mjs. - tests/ — Jest + jsdom. Manager-level suites at the root; React component tests (RTL) under
tests/react/. Mocks forelectron,monaco-editor, CSS imports under tests/mocks/. - @types/index.d.ts — Global window augmentations (
window.executionBridge,window.mked,window.logger,window.setLanguage). - build/ — Installer resources (icons, license).
Two Runtime Modes
The same renderer bundle detects which mode it's running in via getExecutionBridge():
- Desktop:
window.executionBridgeis injected by the Electron preload (src/app/preload.ts). Three sibling JSON files persist under~/.mkeditor/:settings.json(editor + export preferences),session.json(tabs, active tab, workspace folder, per-tab cursor/scroll/folding — restored on relaunch), andassistant.json(AI Assistant config + conversation history; API keys live in itskeyssection, encrypted with ElectronsafeStorageand never crossing IPC in plaintext). File tree sidebar visible. Files open through IPC. - Web: no bridge. Settings + last-edited content go to
localStorage(mkeditor-settings,mkeditor-export-settings,mkeditor-content). Sidebar collapsed by default, "delete content" button shown in the toolbar. Exports use the File System Access API orwindow.open+print()for PDF.
Mode branching lives in index.ts, EditorManager, SettingsProvider, ExportSettingsProvider, and a few React components that conditionally render desktop-only chrome.
IPC Bridge Model
Channels are whitelisted in preload.ts:
- Renderer → Main (
to:*):to:title:set,to:editor:state,to:settings:save,to:html:export,to:pdf:export,to:file:*,to:folder:*,to:i18n:set,to:ai:*(config get/set, key set/clear, chat, cancel, tool-result, conversations save/flush, ollama list). - Main → Renderer (
from:*):from:theme:set,from:settings:set,from:file:*,from:folder:*,from:modal:open,from:command:palette,from:notification:display,from:path:*,from:i18n:set,from:ai:*(config, chunk, tool-call, done, error, ollama:models, conversations, conversations:flush-request),from:assistant:toggle.
Additionally window.mked exposes synchronous/invoke helpers for the mked:// link provider, app locale, and path resolution. window.logger forwards renderer logs to electron-log via an ipcMain.on('log', …) handler in AppBridge.ts.
Notifications cross the bridge as { status, key, values? } (i18n) or { status, message } (plain). BridgeListeners.ts translates and surfaces them via sonnerToast (the sonner <Toaster /> in <App>).
Renderer Composition Root
src/browser/index.ts wires the system at boot:
- Register FontAwesome icons (icons.ts) and pre-build the (now tiny) i18n binding for the splash
<h1>(i18n.ts). - Initialise i18n with the user's locale (prefetch combined bundle, set
<html lang>early, apply translations on load). - Construct an EditorDispatcher and an EditorManager — Monaco is not created yet; that's
<EditorHost>'s job inside the React tree. createRoot(#react-root).render(<App initialManagers onEditorReady />)mounts the full provider tree synchronously, including the<ModalsBridge>/<PromptsBridge>/<PropertiesBridge>sentinels that install module-level seams.<EditorHost>'suseEffectcallseditorManager.create({mount, watch:true})once, then firesonReady().onEditorReady(inindex.ts) attaches providers (SettingsProvider,ExportSettingsProvider,CommandProvider,CompletionProvider) and, on desktop, constructsBridgeManager(with itsFileManager+FileTreeManager), wiressetPersistHandlercallbacks from each settings provider intobridgeManager.saveSettingsToFile, and pushes the updated managers back into React state viasetReactManagers. The splash fades out.
Manager / React Separation
The governing rule: Managers own data and IPC. React owns UI and presentation.
- Managers under src/browser/core/ (
EditorManager,FileManager,FileTreeManager,BridgeManager, providers,Markdown,HTMLExporter) and seam files at src/browser/ (dom.ts,notify.ts,splash.ts,util.ts,i18n.ts) do not import React or Radix. - React components under src/browser/react/ do not import
ipcRenderer, touchwindow.executionBridge, or read/writelocalStoragedirectly. - Reactive manager state crosses the boundary via
subscribe(listener) → unsubscribe+getSnapshot()(stable reference between emits). React contexts (FilesContext,FileTreeContext,SettingsContext,ExportSettingsContext) pull throughuseSyncExternalStore. - Imperative cross-boundary calls (e.g.,
BridgeListeners.from:modal:openopening a React Dialog,FileManager.closeTabopening a React confirm) go through module-level*Externalfunctions registered by React at mount time:openModalExternal(ModalsContext)openPromptExternal/confirmExternal/promptExternal(PromptsContext)showPropertiesExternal(PropertiesContext)sonnerToast(src/browser/notify.ts)
When adding new cross-boundary functionality, follow this same seam pattern — don't add new imports from react/ into core/.
Core Subsystems (renderer)
- EditorManager — owns the single Monaco instance; watch loop fires
dispatcher.render()(~150ms after a change) to trigger<PreviewPane>re-render and word/character count recompute. - Markdown — markdown-it instance with
AlertBlock,LineNumber,LinkTarget,ImageStyle,TableStyle, KaTeX, and highlight.js (specific languages registered eagerly). - FileManager — open file tabs (
Map<path, ITextModel>), drag-to-reorder viareorderTabs, close-with-unsaved-prompt viaopenPromptExternal, untitled counter. - FileTreeManager — explorer tree model + lazy-load via bridge. React
<FileTreePanel>renders from the snapshot. - BridgeManager — wires FileManager/FileTreeManager into IPC.
- BridgeListeners — central place where
from:*channels mutate renderer state (modals, properties, notifications, files, theme, settings, i18n). - HTMLExporter — builds standalone HTML (with optional CDN-linked Bootstrap/FontAwesome/highlight.js/KaTeX for the export), strips internal scroll-sync attrs, exports via Electron save dialog or web File System Access API.
- AssistantManager — chat state owner (provider tabs, conversations, in-flight call map, streaming buffers, draft input). Standard
subscribe/getSnapshot. Desktop-only — never constructed in web mode. See docs/AI_ASSISTANT.md + docs/ARCHITECTURE.md §4.14. - AssistantTools — tool catalog (
read_file,write_file,edit_file, …) + dispatcher into FileManager/FileTreeManager/EditorManager. Write-class tools route throughconfirmExternalunless the conversation's auto-accept toggle is on. - Providers in core/providers/:
SettingsProvider— Monaco options +<body data-theme>flip + Monaco theme. Exposessubscribe/getSnapshot/updateSetting+setPersistHandler(fn).ExportSettingsProvider— live preview style sync + debounced persist (same observable surface).CommandProvider— Monaco actions + chord keys (Ctrl+L → Petc.). The toolbar registerssetOpenDropdown(fn)so CommandProvider can open the Popover for chord-mode.CompletionProvider— regex-triggered fenced-block proposals + auto-list continuation.MkedLinkProvider— resolves*.mdrelative links tomked://open?path=….
Core Subsystems (main process)
- main.ts — single-instance lock, log truncation, autoUpdater,
mked://protocol scheme registration, BrowserWindow withcontextIsolation: true+nodeIntegration: false, system tray,did-finish-loadsends theme + settings + opens initial file. - AppBridge —
ipcMain.on(...)for everyto:*channel; delegates toAppStorage/AppSettings. Also handlesmked://URL parsing. - AppStorage — file/folder CRUD, save dialogs, PDF generation via offscreen
BrowserWindow.printToPDF, directory tree builder (filters.mdand directories). - AppSettings —
~/.mkeditor/settings.jsonload/validate/merge-defaults/save. - AppMenu — application menu and tray menu. Menu items send
from:*channels that the renderer turns into actions. - AppAssistant — Vercel AI SDK wrapper. Owns the upstream stream,
AbortControllerper call, error→code mapping (invalid_key,rate_limited,context_window_exceeded,ollama_unreachable,network_error,unknown). Desktop-only; the renderer never sees an API key. See docs/AI_ASSISTANT.md. - AssistantKeyStore — Electron
safeStorage-encrypted blob for API keys, stored in thekeyssection of~/.mkeditor/assistant.json. Plaintext never crosses IPC. - AssistantConfig — non-secret config (enabled flags, models, baseUrl) + persisted conversation history. Atomic tmp+rename writes, 500 ms debounce.
Build & Run
npm run build-editor— generates src/browser/version.ts frompackage.json#version, combines locales, runs webpack (webpack.config.js). Output:dist/.npm run build-app—tscoversrc/app/*.tsintodist/app/.npm run serve-web— http-server ondist/.npm run serve-app—electron .(usesdist/app/main.js).npm run make-installer— clean → build editor → build app →electron-builder(output inreleases/<platform>/<arch>/).npm test— Jest, jsdom env, with mocks forelectron/monaco-editor/CSS.npm run lint— ESLint flat config (eslint.config.mjs) onsrc.
i18n
13 supported locales (en, de, es, fr, it, nl, pt, ru, uk, tr, zh, ja, ko). Build combines per-namespace JSON into all.json per locale; loader prefers all.json and falls back to per-namespace fetches. Main process never runs i18next — it sends i18n keys to the renderer instead. The legacy data-i18n-* walker remains in i18n.ts only for the splash <h1>; React components translate via useTranslation.
Conventions Worth Knowing
- Manager/React separation. See the section above. New cross-boundary functionality goes through the established seam pattern.
- Single Monaco instance. Only
EditorManager.create(...)callseditor.create(...);<EditorHost>'suseEffecthas[]deps so it never re-mounts. - Reactive provider surface. Any state that React needs to render is exposed by its owning manager as
subscribe/getSnapshot. Don't duplicate manager state in React component state. - shadcn copy-in pattern. UI primitives live in src/browser/react/components/ui/. When adding a new Radix-backed primitive, copy the existing minimal wrapper style (forwardRef +
cn(...)+ theme tokens). - Tailwind theme tokens. Light +
[data-theme='dark']definitions in tailwind.css.--primaryis the MKEditor brand teal (#519088). - Providers are attached imperatively via
manager.provide(key, instance)inonEditorReady. The provider maps live in interfaces/Providers.ts. - Mode flag. Every persistence-touching subsystem takes
mode: 'web' | 'desktop'. Avoid sprinklingif (window.executionBridge)checks. - File tree filter.
readDirectoryreturns only.mdfiles and directories. - CSP-safe
mked://protocol is registered as privileged in main.ts and handled in AppBridge.handleMkedUrl — opens a linked markdown doc in a new tab inside the running instance. - Logging: renderer calls
window.logger.info(...)→ preloadipcRenderer.send('log', …)→ main forwards to electron-log. Log file at~/.mkeditor/main.log, truncated on each launch. - Exported HTML still CDN-loads Bootstrap. The markdown-it extensions emit Bootstrap class names (
alert alert-info,img-fluid,table table-sm ...) for the exported document. The bundled renderer no longer ships Bootstrap CSS; the live preview gets minimal fallback styling in_preview.scss.
Planned Direction
The React migration is complete. Subsequent UI/UX iteration and a DI/wiring cleanup are open follow-ups. See docs/ROADMAP.md for current status and open questions.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

