Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Add find and replace bar to code block editor (#6302)

Seamusf7f184273475
diff --git a/apps/web/src/features/block-code/README.md b/apps/web/src/features/block-code/README.md
index b8c57e5c19..bac2be4054 100644
--- a/apps/web/src/features/block-code/README.md
+++ b/apps/web/src/features/block-code/README.md
@@ -8,3 +8,7 @@ A block for editing code files with syntax highlighting and formatting.
- Code editing with Code Mirror
- Automatic saving of code changes
- Support for various file types and extensions
+- Find bar (`cmd+f`) with match highlighting, styled with the app's own
+ controls; replace appears only when the document is editable
+- Read-only viewers keep a caret and can select and copy code, but cannot edit
+ it (`EditorState.readOnly`, not `EditorView.editable`)
diff --git a/apps/web/src/features/block-code/component/Block.tsx b/apps/web/src/features/block-code/component/Block.tsx
index 5469317077..7cc8ea5178 100644
--- a/apps/web/src/features/block-code/component/Block.tsx
+++ b/apps/web/src/features/block-code/component/Block.tsx
@@ -35,10 +35,6 @@ export default function BlockCode() {
})
);
- createEffect(() => {
- console.log('MDOE', mode());
- });
-
return (
<DocumentBlockContainer usesCenterBar>
<Show when={!isNestedBlock} fallback={<CodeMarkdown />}>
diff --git a/apps/web/src/features/block-code/component/CodeMirror.tsx b/apps/web/src/features/block-code/component/CodeMirror.tsx
index ae99816fca..7e1d6d02be 100644
--- a/apps/web/src/features/block-code/component/CodeMirror.tsx
+++ b/apps/web/src/features/block-code/component/CodeMirror.tsx
@@ -1,6 +1,13 @@
import { indentWithTab, toggleComment } from '@codemirror/commands';
+import {
+ closeSearchPanel,
+ openSearchPanel,
+ search,
+ searchPanelOpen,
+ setSearchQuery,
+} from '@codemirror/search';
import { Compartment, EditorState, type Extension } from '@codemirror/state';
-import { EditorView, keymap } from '@codemirror/view';
+import { EditorView, keymap, type Panel } from '@codemirror/view';
import { useBlockId } from '@core/block';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
@@ -18,10 +25,28 @@ import {
createSignal,
onCleanup,
onMount,
+ Show,
} from 'solid-js';
+import { Portal } from 'solid-js/web';
import { loadLanguageFromExtensionWithFallback } from '../util/languageSupport';
+import { CodeSearchPanel } from './CodeSearchPanel';
import { macroThemeExtension } from './cmTheme';
+/**
+ * Read-only viewers keep a caret and can select text: `EditorState.readOnly`
+ * rejects edits (including replace) while leaving the content focusable, which
+ * `EditorView.editable.of(false)` would not. `inputmode` keeps the on-screen
+ * keyboard out of the way on touch devices, where there is nothing to type.
+ */
+function readOnlyExtension(readOnly: boolean): Extension {
+ return readOnly
+ ? [
+ EditorState.readOnly.of(true),
+ EditorView.contentAttributes.of({ inputmode: 'none' }),
+ ]
+ : [];
+}
+
// put this in your extensions array
export function CodeMirror() {
let containerRef!: HTMLDivElement;
@@ -55,13 +80,56 @@ export function CodeMirror() {
const throttledSave = throttle(saveNow, 5_000);
const readOnlyCompartment = new Compartment();
- const editableCompartment = new Compartment();
const languageCompartment = new Compartment();
const [languageExtension, setLanguageExtension] =
createSignal<Extension | null>(null);
let view: EditorView | undefined;
+ // The find bar lives in CodeMirror's panel slot (so match highlighting keeps
+ // working) but renders through Solid, into the host element the panel hands
+ // us, so it can use the app's own controls.
+ const [searchPanel, setSearchPanel] = createSignal<{
+ host: HTMLElement;
+ view: EditorView;
+ }>();
+ const [searchPanelState, setSearchPanelState] = createSignal<EditorState>();
+
+ const createSearchPanel = (panelView: EditorView): Panel => {
+ const host = document.createElement('div');
+ setSearchPanelState(panelView.state);
+ setSearchPanel({ host, view: panelView });
+
+ return {
+ dom: host,
+ top: true,
+ mount() {
+ // Solid fills the host in as a side effect of the signal write above,
+ // so wait a tick before reaching for the field.
+ queueMicrotask(() => {
+ const input = host.querySelector<HTMLInputElement>('[main-field]');
+ input?.focus();
+ input?.select();
+ });
+ },
+ update(update) {
+ if (
+ update.docChanged ||
+ update.selectionSet ||
+ update.startState.readOnly !== update.state.readOnly ||
+ update.transactions.some((transaction) =>
+ transaction.effects.some((effect) => effect.is(setSearchQuery))
+ )
+ ) {
+ setSearchPanelState(update.state);
+ }
+ },
+ destroy() {
+ setSearchPanel(undefined);
+ },
+ };
+ };
+
const [attach, scope] = useHotkeyDOMScope('code-mirror-editor');
registerHotkey({
@@ -79,17 +147,33 @@ export function CodeMirror() {
runWithInputFocused: true,
});
+ registerHotkey({
+ hotkey: 'cmd+f',
+ hotkeyToken: TOKENS.code.find,
+ description: 'Find in code',
+ scopeId: scope,
+ keyDownHandler: () => {
+ if (!view) return false;
+ openSearchPanel(view);
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
registerHotkey({
hotkey: 'escape',
hotkeyToken: TOKENS.code.escape,
description: 'Escape code editor',
scopeId: scope,
keyDownHandler: () => {
- if (view) {
- view.contentDOM.blur();
+ if (!view) return false;
+ // Escape closes the find bar before it gives up focus on the editor.
+ if (searchPanelOpen(view.state)) {
+ closeSearchPanel(view);
return true;
}
- return false;
+ view.contentDOM.blur();
+ return true;
},
runWithInputFocused: true,
});
@@ -104,8 +188,8 @@ export function CodeMirror() {
extensions: [
basicSetup,
keymap.of([indentWithTab]),
- readOnlyCompartment.of(EditorState.readOnly.of(readOnly())),
- editableCompartment.of(EditorView.editable.of(!readOnly())),
+ search({ top: true, createPanel: createSearchPanel }),
+ readOnlyCompartment.of(readOnlyExtension(readOnly())),
languageCompartment.of([]),
EditorView.updateListener.of((update) => {
if (!update.docChanged) return;
@@ -165,10 +249,7 @@ export function CodeMirror() {
createEffect(() => {
if (!view) return;
view.dispatch({
- effects: [
- readOnlyCompartment.reconfigure(EditorState.readOnly.of(readOnly())),
- editableCompartment.reconfigure(EditorView.editable.of(!readOnly())),
- ],
+ effects: readOnlyCompartment.reconfigure(readOnlyExtension(readOnly())),
});
});
});
@@ -178,12 +259,24 @@ export function CodeMirror() {
});
return (
- <div
- // Full-frame mobile/tablet: the floating split chrome overlays the panel, so
- // the inset lives on the CodeMirror scroller — code rests below the
- // chrome but under-scrolls it.
- class="size-full overflow-auto touch:[&_.cm-scroller]:pt-(--mobile-content-inset-top) touch:[&_.cm-scroller]:pb-(--mobile-content-inset-bottom)"
- ref={containerRef}
- />
+ <>
+ <div
+ // Full-frame mobile/tablet: the floating split chrome overlays the panel, so
+ // the inset lives on the CodeMirror scroller — code rests below the
+ // chrome but under-scrolls it.
+ class="size-full overflow-auto touch:[&_.cm-scroller]:pt-(--mobile-content-inset-top) touch:[&_.cm-scroller]:pb-(--mobile-content-inset-bottom)"
+ ref={containerRef}
+ />
+ <Show when={searchPanel()}>
+ {(panel) => (
+ <Portal mount={panel().host}>
+ <CodeSearchPanel
+ view={panel().view}
+ state={searchPanelState() ?? panel().view.state}
+ />
+ </Portal>
+ )}
+ </Show>
+ </>
);
}
diff --git a/apps/web/src/features/block-code/component/CodeSearchPanel.tsx b/apps/web/src/features/block-code/component/CodeSearchPanel.tsx
new file mode 100644
index 0000000000..8351c210cc
--- /dev/null
+++ b/apps/web/src/features/block-code/component/CodeSearchPanel.tsx
@@ -0,0 +1,287 @@
+import {
+ closeSearchPanel,
+ findNext,
+ findPrevious,
+ getSearchQuery,
+ replaceAll,
+ replaceNext,
+ SearchQuery,
+ setSearchQuery,
+} from '@codemirror/search';
+import type { EditorState } from '@codemirror/state';
+import { type EditorView, runScopeHandlers } from '@codemirror/view';
+import ReplaceAllIcon from '@phosphor/arrow-bend-double-up-right.svg';
+import ReplaceIcon from '@phosphor/arrow-bend-up-right.svg';
+import CaretDown from '@phosphor/caret-down.svg';
+import CaretRight from '@phosphor/caret-right.svg';
+import CaretUp from '@phosphor/caret-up.svg';
+import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
+import X from '@phosphor/x.svg';
+import { Button, Surface } from '@ui';
+import { createMemo, createSignal, Show } from 'solid-js';
+
+/**
+ * Counting every match in a huge file on each keystroke isn't worth it, so the
+ * tally saturates and the label reads `1000+`.
+ */
+const MATCH_COUNT_LIMIT = 1000;
+
+type MatchCount = {
+ total: number;
+ /** 1-based index of the match the selection currently sits on, else 0. */
+ current: number;
+ capped: boolean;
+};
+
+function countMatches(query: SearchQuery, state: EditorState): MatchCount {
+ if (!query.valid) return { total: 0, current: 0, capped: false };
+
+ const { from, to } = state.selection.main;
+ const cursor = query.getCursor(state);
+ let total = 0;
+ let current = 0;
+
+ for (let match = cursor.next(); !match.done; match = cursor.next()) {
+ total += 1;
+ if (match.value.from === from && match.value.to === to) current = total;
+ if (total >= MATCH_COUNT_LIMIT) return { total, current, capped: true };
+ }
+
+ return { total, current, capped: false };
+}
+
+function ModifierToggle(props: {
+ glyph: string;
+ label: string;
+ active: boolean;
+ onToggle: () => void;
+}) {
+ return (
+ <Button
+ size="icon-sm"
+ variant={props.active ? 'accent' : 'ghost'}
+ tooltip={props.label}
+ aria-pressed={props.active}
+ onClick={props.onToggle}
+ >
+ <span class="font-mono text-xxs leading-none">{props.glyph}</span>
+ </Button>
+ );
+}
+
+/**
+ * CodeMirror's search commands locate the field to focus and select through a
+ * `main-field` attribute, which isn't part of the JSX attribute types.
+ */
+function markAsMainField(element: HTMLInputElement) {
+ element.setAttribute('main-field', 'true');
+}
+
+const FIELD_CLASS =
+ 'flex h-7 w-56 max-w-full min-w-0 shrink items-center gap-1.5 rounded-md px-2';
+
+const INPUT_CLASS =
+ 'min-w-0 flex-1 border-0 bg-transparent text-sm text-ink outline-none placeholder:text-ink-placeholder focus:outline-none focus:ring-0';
+
+export type CodeSearchPanelProps = {
+ view: EditorView;
+ /** Editor state as of the last update the panel was notified about. */
+ state: EditorState;
+};
+
+/**
+ * Find (and, when the document is editable, replace) bar for the code block's
+ * CodeMirror instance. Installed through `search({ createPanel })` so that
+ * CodeMirror keeps highlighting matches for us; viewers without edit access get
+ * the find half only, since `EditorState.readOnly` rejects replacements.
+ */
+export function CodeSearchPanel(props: CodeSearchPanelProps) {
+ const [replaceOpen, setReplaceOpen] = createSignal(false);
+
+ const query = createMemo(() => getSearchQuery(props.state));
+ const matches = createMemo(() => countMatches(query(), props.state));
+ const canReplace = () => !props.state.readOnly;
+
+ const commit = (
+ changes: Partial<{
+ search: string;
+ caseSensitive: boolean;
+ regexp: boolean;
+ replace: string;
+ wholeWord: boolean;
+ }>
+ ) => {
+ const current = getSearchQuery(props.view.state);
+ props.view.dispatch({
+ effects: setSearchQuery.of(
+ new SearchQuery({
+ search: current.search,
+ caseSensitive: current.caseSensitive,
+ literal: current.literal,
+ regexp: current.regexp,
+ replace: current.replace,
+ wholeWord: current.wholeWord,
+ ...changes,
+ })
+ ),
+ });
+ };
+
+ const countLabel = () => {
+ const { search, valid } = query();
+ if (!search) return '';
+ if (!valid) return 'Invalid pattern';
+
+ const { total, current, capped } = matches();
+ if (total === 0) return 'No matches';
+
+ const totalLabel = capped ? `${MATCH_COUNT_LIMIT}+` : `${total}`;
+ if (current > 0) return `${current} of ${totalLabel}`;
+ return `${totalLabel} match${total === 1 ? '' : 'es'}`;
+ };
+
+ const close = () => {
+ closeSearchPanel(props.view);
+ };
+
+ // Escape is claimed by the code block's own hotkey scope, so this only runs
+ // when that scope is inactive; the other search bindings live in CodeMirror's
+ // `search-panel` keymap scope.
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ close();
+ return;
+ }
+ if (runScopeHandlers(props.view, event, 'search-panel')) {
+ event.preventDefault();
+ }
+ };
+
+ const onFindKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== 'Enter') return;
+ event.preventDefault();
+ if (event.shiftKey) findPrevious(props.view);
+ else findNext(props.view);
+ };
+
+ const onReplaceKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== 'Enter') return;
+ event.preventDefault();
+ replaceNext(props.view);
+ };
+
+ return (
+ <div
+ class="flex w-full flex-col gap-1 border-b border-edge-muted bg-surface p-1.5"
+ onKeyDown={onKeyDown}
+ >
+ <div class="flex min-w-0 items-center gap-1">
+ <Show when={canReplace()}>
+ <Button
+ size="icon-sm"
+ tooltip={replaceOpen() ? 'Hide replace' : 'Show replace'}
+ onClick={() => setReplaceOpen(!replaceOpen())}
+ >
+ <Show when={replaceOpen()} fallback={<CaretRight />}>
+ <CaretDown />
+ </Show>
+ </Button>
+ </Show>
+
+ <Surface depth={1} class={FIELD_CLASS}>
+ <MagnifyingGlass class="size-3.5 shrink-0 text-ink-extra-muted" />
+ <input
+ ref={markAsMainField}
+ type="text"
+ placeholder="Find"
+ aria-label="Find"
+ autocomplete="off"
+ spellcheck={false}
+ class={INPUT_CLASS}
+ value={query().search}
+ onInput={(event) => commit({ search: event.currentTarget.value })}
+ onKeyDown={onFindKeyDown}
+ />
+ </Surface>
+
+ <ModifierToggle
+ glyph="Aa"
+ label="Match case"
+ active={query().caseSensitive}
+ onToggle={() => commit({ caseSensitive: !query().caseSensitive })}
+ />
+ <ModifierToggle
+ glyph="ab"
+ label="Match whole word"
+ active={query().wholeWord}
+ onToggle={() => commit({ wholeWord: !query().wholeWord })}
+ />
+ <ModifierToggle
+ glyph=".*"
+ label="Use regular expression"
+ active={query().regexp}
+ onToggle={() => commit({ regexp: !query().regexp })}
+ />
+
+ <span class="min-w-0 flex-1 truncate px-1 text-xs text-ink-muted">
+ {countLabel()}
+ </span>
+
+ <Button
+ size="icon-sm"
+ tooltip="Previous match"
+ shortcut="shift+enter"
+ onClick={() => findPrevious(props.view)}
+ >
+ <CaretUp />
+ </Button>
+ <Button
+ size="icon-sm"
+ tooltip="Next match"
+ shortcut="enter"
+ onClick={() => findNext(props.view)}
+ >
+ <CaretDown />
+ </Button>
+ <Button size="icon-sm" tooltip="Close find" onClick={close}>
+ <X />
+ </Button>
+ </div>
+
+ <Show when={canReplace() && replaceOpen()}>
+ <div class="flex min-w-0 items-center gap-1 pl-7">
+ <Surface depth={1} class={FIELD_CLASS}>
+ <input
+ type="text"
+ placeholder="Replace"
+ aria-label="Replace"
+ autocomplete="off"
+ spellcheck={false}
+ class={INPUT_CLASS}
+ value={query().replace}
+ onInput={(event) =>
+ commit({ replace: event.currentTarget.value })
+ }
+ onKeyDown={onReplaceKeyDown}
+ />
+ </Surface>
+ <Button
+ size="icon-sm"
+ tooltip="Replace"
+ onClick={() => replaceNext(props.view)}
+ >
+ <ReplaceIcon />
+ </Button>
+ <Button
+ size="icon-sm"
+ tooltip="Replace all"
+ onClick={() => replaceAll(props.view)}
+ >
+ <ReplaceAllIcon />
+ </Button>
+ </div>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-code/component/cmTheme.ts b/apps/web/src/features/block-code/component/cmTheme.ts
index eae1aae1b1..88a0dd1242 100644
--- a/apps/web/src/features/block-code/component/cmTheme.ts
+++ b/apps/web/src/features/block-code/component/cmTheme.ts
@@ -32,6 +32,9 @@ const base = {
selection: 'rgb(from var(--color-edge) r g b / 0.6)',
menuSelected: 'var(--color-hover)',
+ searchMatch: 'rgb(from var(--color-accent) r g b / 0.2)',
+ searchMatchSelected: 'rgb(from var(--color-accent) r g b / 0.45)',
+
alt: 'var(--color-ink-extra-muted)',
edge: 'var(--color-edge)',
edge50: 'color-mix(in oklch, var(--color-edge), var(--color-surface) 50%)',
@@ -65,6 +68,9 @@ const theme = EditorView.theme({
caretColor: base.accent,
padding: '0.5rem 0',
minHeight: '100%',
+ // The block shell sets `select-none` on the frame; code itself stays
+ // selectable, including for read-only viewers.
+ userSelect: 'text',
},
'.cm-line': {
paddingLeft: '0.5rem',
@@ -111,6 +117,25 @@ const theme = EditorView.theme({
'.cm-selectionMatch': {
backgroundColor: base.selection,
},
+ '.cm-searchMatch': {
+ backgroundColor: base.searchMatch,
+ borderRadius: '0.125rem',
+ },
+ '.cm-searchMatch-selected': {
+ backgroundColor: base.searchMatchSelected,
+ },
+ // The find bar brings its own chrome (see CodeSearchPanel), so drop the
+ // default panel background and separators CodeMirror paints around it.
+ '.cm-panels': {
+ backgroundColor: 'transparent',
+ color: base.fg,
+ },
+ '.cm-panels-top': {
+ borderBottom: 'none',
+ },
+ '.cm-panels-bottom': {
+ borderTop: 'none',
+ },
'.cm-tooltip': {
backgroundColor: base.panel,
color: base.fg70,
diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.ts
index c9402241e0..eaae7f66c5 100644
--- a/apps/web/src/lib/core/hotkey/tokens.ts
+++ b/apps/web/src/lib/core/hotkey/tokens.ts
@@ -77,6 +77,7 @@ export const TOKENS = {
code: {
toggleComment: 'code.toggleComment',
escape: 'code.escape',
+ find: 'code.find',
},
// calendar