iterate.com / ui

git clone https://git.iterate.com/repos/ui

ui / src / components / docs-editor / extensions.tsmain at d68d7e1

// Carried over from iterate/docs@fba5c21 (packages/docs-app/src/editor/extensions.ts).
// The doc editor: CodeMirror over the file's markdown with Atomic's Obsidian-style live preview
// (@atomic-editor/editor, assembled as its own AtomicCodeMirrorEditor component does). Rich and
// Markdown mode are the same editor with the preview in or out of `preview`, so the text, the
// selection and the undo history carry across a switch. Undo is Yjs's (doc-session.ts): it undoes
// this person's edits and leaves everyone else's.
import {
  atomicEditorTheme,
  atomicMarkdownSyntax,
  autoCloseCodeFence,
  extendEmphasisPair,
  highlightMarkdown,
  imageBlocks,
  inlinePreview,
  startAsteriskList,
  tables,
} from "@atomic-editor/editor";
import { ATOMIC_CODE_LANGUAGES } from "@atomic-editor/editor/code-languages";
import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
import { defaultKeymap, indentWithTab } from "@codemirror/commands";
import { markdown, markdownKeymap, markdownLanguage } from "@codemirror/lang-markdown";
import { indentOnInput, LanguageDescription } from "@codemirror/language";
import { search, searchKeymap } from "@codemirror/search";
import { Compartment, EditorState, Prec, type Extension } from "@codemirror/state";
import {
  drawSelection,
  dropCursor,
  EditorView,
  highlightActiveLine,
  highlightSpecialChars,
  keymap,
  rectangularSelection,
} from "@codemirror/view";
import { promptLink, toggleWrap } from "./commands.ts";
import { frontmatterProperties } from "./frontmatter.ts";
import { sourceEditorExtensions } from "#/lib/source-editor.ts";

/** A markdown file's two views of one editor, Rich (the live preview) and Markdown. */
export type EditorMode = "rich" | "markdown";

/** The live preview: what Markdown mode takes out. */
export function previewExtensions(mode: EditorMode): Extension {
  return mode === "rich" ? [frontmatterProperties, tables(), imageBlocks(), inlinePreview()] : [];
}

/** Formatting shortcuts. `stopPropagation`: the app shell's sidebar toggles on Cmd/Ctrl-B from a
 *  window listener, which a handled key must not reach. */
const formattingKeymap = Prec.highest(
  keymap.of(
    [
      { key: "Mod-b", run: (view: EditorView) => toggleWrap(view, "**") },
      { key: "Mod-i", run: (view: EditorView) => toggleWrap(view, "_") },
      { key: "Mod-e", run: (view: EditorView) => toggleWrap(view, "`") },
      { key: "Mod-Shift-x", run: (view: EditorView) => toggleWrap(view, "~~") },
      { key: "Mod-k", run: promptLink },
    ].map((binding) => ({ ...binding, preventDefault: true, stopPropagation: true })),
  ),
);

/** Atomic's colours from the page's tokens (src/styles/globals.css and tokens.css): Atomic's own
 *  defaults are a dark theme, inline code and code blocks' syntax colours included (the `hl-`
 *  ones; a fence's language name is `hl-variable`). The tokens follow the page's light or dark. Its
 *  stylesheet is in dist/docs-editor.css, which the page links in place of styles.css. */
const theme = EditorView.theme({
  "&": {
    "--atomic-editor-fg": "var(--foreground)",
    "--atomic-editor-fg-muted": "var(--muted-foreground)",
    "--atomic-editor-fg-faint": "var(--muted-foreground)",
    "--atomic-editor-bg": "var(--background)",
    "--atomic-editor-bg-surface": "var(--popover)",
    "--atomic-editor-bg-panel": "var(--muted)",
    "--atomic-editor-border": "var(--border)",
    "--atomic-editor-accent": "var(--primary)",
    "--atomic-editor-accent-bright": "var(--foreground)",
    "--atomic-editor-accent-soft": "var(--accent)",
    "--atomic-editor-link": "var(--primary)",
    "--atomic-editor-link-hover": "var(--foreground)",
    "--atomic-editor-code-bg": "var(--muted)",
    "--atomic-editor-selection-bg": "var(--accent)",
    "--atomic-editor-font": "var(--font-sans, system-ui)",
    "--atomic-editor-measure": "100%",
    "--atomic-editor-hl-comment": "var(--muted-foreground)",
    "--atomic-editor-hl-escape": "var(--info)",
    "--atomic-editor-hl-function": "var(--chart-5)",
    "--atomic-editor-hl-invalid": "var(--destructive)",
    "--atomic-editor-hl-keyword": "var(--chart-2)",
    "--atomic-editor-hl-number": "var(--info)",
    "--atomic-editor-hl-operator": "var(--chart-2)",
    "--atomic-editor-hl-property": "var(--info)",
    "--atomic-editor-hl-regexp": "var(--chart-1)",
    "--atomic-editor-hl-string": "var(--chart-1)",
    "--atomic-editor-hl-tag": "var(--success)",
    "--atomic-editor-hl-type": "var(--warning)",
    "--atomic-editor-hl-variable": "var(--foreground)",
    fontSize: "15px",
  },
  "&.cm-focused": { outline: "none" },
  ".cm-content": { padding: "8px 0 30vh" },
  ".cm-line": { lineHeight: "1.7" },
});

/** Find in the file, Cmd/Ctrl-F (`searchKeymap`, ahead of the default keymap so Escape closes it):
 *  CodeMirror draws only the lines near the screen, so the browser's find misses the rest. The
 *  panel goes in the page's sticky bar (doc-session.ts `mountPanels`), and a match lands mid-page,
 *  clear of the bars above and below. */
const find = [
  search({
    top: true,
    scrollToMatch: (range) => EditorView.scrollIntoView(range, { y: "center" }),
  }),
  // over Atomic's theme, whose panel is dark and its buttons CodeMirror's dark gradients
  Prec.highest(
    EditorView.theme({
      ".cm-panels": {
        backgroundColor: "var(--background)",
        color: "var(--foreground)",
        borderTop: "1px solid var(--border)",
      },
      ".cm-panel.cm-search": { padding: "6px 36px 6px 16px", fontSize: "13px" },
      ".cm-panel.cm-search input[type=text], .cm-panel.cm-search button": {
        height: "26px",
        margin: "2px 6px 2px 0",
        borderRadius: "0",
        border: "1px solid var(--border)",
        backgroundColor: "var(--background)",
        backgroundImage: "none",
        color: "var(--foreground)",
        fontSize: "13px",
      },
      ".cm-panel.cm-search input[type=text]": { width: "16rem", padding: "0 8px" },
      ".cm-panel.cm-search input[type=text]:focus": {
        outline: "none",
        borderColor: "var(--foreground)",
      },
      ".cm-panel.cm-search button": { padding: "0 10px" },
      ".cm-panel.cm-search button:hover": { backgroundColor: "var(--accent)" },
      ".cm-panel.cm-search label": { color: "var(--muted-foreground)", fontSize: "13px" },
      ".cm-panel.cm-search input[type=checkbox]": { accentColor: "var(--foreground)" },
      ".cm-panel.cm-search button[name=close]": {
        top: "8px",
        right: "12px",
        border: "none",
        padding: "0 6px",
        fontSize: "18px",
        color: "var(--muted-foreground)",
      },
      // blue, apart from comments' yellow (comment-marks.ts)
      ".cm-searchMatch": { backgroundColor: "color-mix(in oklab, var(--info) 18%, transparent)" },
      ".cm-searchMatch.cm-searchMatch-selected": {
        backgroundColor: "color-mix(in oklab, var(--info) 38%, transparent)",
        outline: "1px solid var(--info)",
      },
    }),
  ),
];

/** Everything but the preview, which `preview` holds so a mode switch can swap it. */
export function docEditorExtensions(options: {
  mode: EditorMode;
  preview: Compartment;
}): Extension {
  return [
    highlightSpecialChars(),
    drawSelection(),
    dropCursor(),
    EditorState.allowMultipleSelections.of(true),
    indentOnInput(),
    rectangularSelection(),
    highlightActiveLine(),
    closeBrackets(),
    startAsteriskList,
    extendEmphasisPair,
    autoCloseCodeFence,
    EditorView.lineWrapping,
    // code blocks highlight in their fence's language, each grammar fetched when a doc first uses it
    markdown({
      base: markdownLanguage,
      codeLanguages: ATOMIC_CODE_LANGUAGES,
      extensions: highlightMarkdown,
    }),
    atomicMarkdownSyntax,
    atomicEditorTheme,
    theme,
    formattingKeymap,
    find,
    // Tab indents the line, which nests a list item, and the editor keeps focus (indentWithTab):
    // Escape then Tab moves focus on, as CodeMirror's docs on trapping Tab describe.
    keymap.of([
      ...closeBracketsKeymap,
      ...searchKeymap,
      ...markdownKeymap,
      indentWithTab,
      ...defaultKeymap,
    ]),
    options.preview.of(previewExtensions(options.mode)),
  ];
}

/** Source files use the repo IDE's setup, with Yjs undo and the doc's sticky find panel. */
export function codeEditorExtensions(options: { language: Extension }): Extension {
  return [sourceEditorExtensions({ history: "external" }), find, options.language];
}

/** The language a file is written in, by its name, from the same list code blocks use; none for
 *  a name no language claims. Each grammar is fetched the first time it's needed. */
export async function codeLanguage(path: string): Promise<Extension> {
  const description = LanguageDescription.matchFilename(ATOMIC_CODE_LANGUAGES, path);
  return description ? await description.load() : [];
}