Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ import { imageHoverPreview, keyboardShortcut, updateBehavior } from './src/setti
import { localized } from './src/strings';
import { macOSTahoe } from './src/utils';

import {
performSearch,
setSearchMatchIndex,
clearSearch,
searchCounterInfo,
} from './src/search';

if (window.__markeditPreviewInitialized__) {
console.error('MarkEdit Preview has already been initialized. Multiple initializations may cause unexpected behavior.');
} else {
Expand All @@ -45,6 +52,14 @@ if (window.__markeditPreviewInitialized__) {
// Allow other extensions or scripts to generate the HTML
window.MarkEditGetHtml ??= generateStaticHtml;

// Expose bridge API for CoreEditor to call functions in the preview
window.__markeditPreviewSPI__ = {
performSearch,
setSearchMatchIndex,
clearSearch,
searchCounterInfo,
};

MarkEdit.addMainMenuItem({
title: localized('viewMode'),
icon: macOSTahoe() ? 'eye' : undefined,
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@typescript-eslint/parser": "^8.32.1",
"cross-env": "^7.0.3",
"eslint": "^9.27.0",
"happy-dom": "^20.8.9",
"markedit-api": "https://github.com/MarkEdit-app/MarkEdit-api#v0.21.0",
"markedit-vite": "https://github.com/MarkEdit-app/MarkEdit-vite#v0.4.0",
"typescript": "^5.0.0",
Expand All @@ -33,6 +34,7 @@
},
"dependencies": {
"katex": "^0.16.40",
"mark.js": "^8.11.1",
"markdown-it": "^14.1.1",
"markdown-it-anchor": "^9.2.0",
"markdown-it-footnote": "^4.0.0",
Expand Down
179 changes: 179 additions & 0 deletions src/search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import Mark from 'mark.js';
import { currentViewMode, getPreviewPane, ViewMode } from './view';
import { themeName } from './settings';

const MARK_MATCH_CLASS = 'markedit-preview-mark';
const MARK_HIGHLIGHTED_CLASS = 'markedit-preview-mark-highlighted';

let isApplying = false;
let currentOptions: SearchOptions | undefined;
let currentIndex = 0;
let markElements: HTMLElement[] = [];
let contentObserver: MutationObserver | null = null;
let markStyleSheet: HTMLStyleElement | null = null;

// Mirrors CoreEditor's EditorColors.searchMatch, keyed by the plugin's themeName setting.
const searchMatchColors: Record<string, { light: string; dark: string }> = {
'github': { light: '#fae17d7f', dark: '#f2cc607f' },
'cobalt': { light: '#cad40f66', dark: '#cad40f66' },
'dracula': { light: '#ffffff40', dark: '#ffffff40' },
'minimal': { light: '#fae17d7f', dark: '#f2cc607f' },
'night-owl': { light: '#5f7e9779', dark: '#5f7e9779' },
'rose-pine': { light: '#6e6a864c', dark: '#6e6a8666' },
'solarized': { light: '#f4c09d', dark: '#584032' },
'synthwave84': { light: '#d18616bb', dark: '#d18616bb' },
'winter-is-coming': { light: '#cee1f0', dark: '#103362' },
'xcode': { light: '#e4e4e4', dark: '#545558' },
};

export interface SearchOptions {
search: string;
caseSensitive: boolean;
diacriticInsensitive: boolean;
wholeWord: boolean;
regexp: boolean;
}

export interface SearchCounterInfo {
numberOfItems: number;
currentIndex: number;
}

export function performSearch(options: SearchOptions) {
currentOptions = options;
currentIndex = 0;

if (options.search.length === 0) {
clearSearch();
return;
}

const container = getPreviewPane();
remarkWithNewOptions(container);
observeContentChanges(container);
}

export function setSearchMatchIndex(index: number) {
if (markElements.length === 0) {
return;
}

// The editor may have more matches than the rendered preview (e.g. inside code fences);
// use modulo to stay in range rather than clamping to the last element.
currentIndex = index % markElements.length;
Comment thread
cyanzhong marked this conversation as resolved.
highlightCurrent();
}

export function clearSearch() {
contentObserver?.disconnect();
contentObserver = null;
currentOptions = undefined;
currentIndex = 0;
markElements = [];
new Mark(getPreviewPane()).unmark();
}

// Returns undefined outside overlay mode so the editor's own counter is used instead.
export function searchCounterInfo(): SearchCounterInfo | undefined {
if (currentViewMode() !== ViewMode.preview) {
return undefined;
}

return { numberOfItems: markElements.length, currentIndex };
}

function remarkWithNewOptions(container: HTMLElement) {
const options = currentOptions;
if (options === undefined || options.search.length === 0) {
return;
}

if (isApplying) {
return;
}

updateStyles();
isApplying = true;

const { search, caseSensitive, wholeWord, diacriticInsensitive, regexp } = options;
const marker = new Mark(container);

const onComplete = () => {
markElements = Array.from(container.querySelectorAll<HTMLElement>(`.${MARK_MATCH_CLASS}`));
currentIndex = markElements.length > 0 ? Math.min(currentIndex, markElements.length - 1) : 0;
highlightCurrent();
isApplying = false;
};

marker.unmark({
done: () => {
if (regexp) {
try {
const flags = caseSensitive ? '' : 'i';
marker.markRegExp(new RegExp(search, flags), {
className: MARK_MATCH_CLASS,
done: onComplete,
});
} catch {
Comment thread
cyanzhong marked this conversation as resolved.
isApplying = false;
currentIndex = 0;
markElements = [];
}
} else {
marker.mark(search, {
className: MARK_MATCH_CLASS,
caseSensitive,
diacritics: diacriticInsensitive,
separateWordSearch: false,
accuracy: wholeWord ? 'exactly' : 'partially',
done: onComplete,
});
}
},
});
}

// Show the current-match indicator only when not in side-by-side mode, where
// the editor's own highlight is already visible and indices may not correspond.
function highlightCurrent() {
const shouldHighlight = currentViewMode() !== ViewMode.sideBySide;
markElements.forEach((mark, index) => {
mark.classList.toggle(MARK_HIGHLIGHTED_CLASS, shouldHighlight && index === currentIndex);
});

if (shouldHighlight && markElements.length > 0) {
markElements[currentIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}

function observeContentChanges(container: HTMLElement) {
contentObserver?.disconnect();

// Observe only direct children — fires on preview re-renders (innerHTML
// replacement) but not on mark.js changes inside nested block elements.
contentObserver = new MutationObserver(() => {
if (!isApplying) {
remarkWithNewOptions(container);
}
});

contentObserver.observe(container, { childList: true });
}

// Mirrors .cm-searchMatch / .cm-searchMatch-selected from CoreEditor's builder.ts.
// Light/dark colors follow the preview's own themeName, not the editor's active theme.
function updateStyles() {
if (markStyleSheet === null) {
markStyleSheet = document.createElement('style');
document.head.appendChild(markStyleSheet);
}

const { light, dark } = searchMatchColors[themeName] ?? searchMatchColors['github'];
markStyleSheet.textContent = [
`.${MARK_MATCH_CLASS} { background: ${light} !important; color: inherit !important; }`,
`.${MARK_HIGHLIGHTED_CLASS} { background: #ffff00 !important; color: #000000 !important; box-shadow: 0px 0px 2px 1px rgba(0, 0, 0, 0.2); }`,
'@media (prefers-color-scheme: dark) {',
` .${MARK_MATCH_CLASS} { background: ${dark} !important; }`,
'}',
].join('\n');
}
164 changes: 164 additions & 0 deletions tests/search.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// @vitest-environment happy-dom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';

const mockMatchCount = vi.hoisted(() => ({ value: 1 }));
const mockViewState = vi.hoisted(() => ({
mode: 'preview' as string,
pane: null as HTMLElement | null,
}));

vi.mock('mark.js', () => ({
default: class MockMark {
private container: Element;
constructor(container: Element) { this.container = container; }

mark(_keyword: string, options?: { className?: string; done?: (n: number) => void }) {
for (let i = 0; i < mockMatchCount.value; i++) {
const el = document.createElement('mark');
el.className = options?.className ?? '';
this.container.appendChild(el);
}
options?.done?.(mockMatchCount.value);
}

markRegExp(_re: RegExp, options?: { className?: string; done?: (n: number) => void }) {
for (let i = 0; i < mockMatchCount.value; i++) {
const el = document.createElement('mark');
el.className = options?.className ?? '';
this.container.appendChild(el);
}
options?.done?.(mockMatchCount.value);
}

unmark(options?: { done?: () => void }) {
this.container.querySelectorAll('mark').forEach(el => el.remove());
options?.done?.();
}
},
}));

vi.mock('../src/settings', () => ({ themeName: 'github' }));

vi.mock('../src/view', () => ({
ViewMode: { edit: 'edit', sideBySide: 'side-by-side', preview: 'preview' },
currentViewMode: vi.fn(() => mockViewState.mode),
getPreviewPane: vi.fn(() => mockViewState.pane),
}));

import { performSearch, setSearchMatchIndex, clearSearch, searchCounterInfo } from '../src/search';

const baseOptions = {
search: 'hello',
caseSensitive: false,
diacriticInsensitive: false,
wholeWord: false,
regexp: false,
};

beforeEach(() => {
mockViewState.pane = document.createElement('div');
document.body.appendChild(mockViewState.pane);
mockViewState.mode = 'preview';
mockMatchCount.value = 1;
clearSearch();
});

afterEach(() => {
document.body.innerHTML = '';
mockViewState.pane = null;
});

describe('searchCounterInfo', () => {
it('returns undefined in edit mode', () => {
mockViewState.mode = 'edit';
expect(searchCounterInfo()).toBeUndefined();
});

it('returns undefined in side-by-side mode', () => {
mockViewState.mode = 'side-by-side';
expect(searchCounterInfo()).toBeUndefined();
});

it('returns zero counter in preview mode with no active search', () => {
expect(searchCounterInfo()).toEqual({ numberOfItems: 0, currentIndex: 0 });
});

it('reflects mark count after search', () => {
mockMatchCount.value = 3;
performSearch(baseOptions);
expect(searchCounterInfo()).toEqual({ numberOfItems: 3, currentIndex: 0 });
});
});

describe('performSearch', () => {
it('clears marks when query is empty', () => {
mockMatchCount.value = 2;
performSearch(baseOptions);
performSearch({ ...baseOptions, search: '' });
expect(searchCounterInfo()?.numberOfItems).toBe(0);
});

it('resets currentIndex to 0 on new search', () => {
mockMatchCount.value = 3;
performSearch(baseOptions);
setSearchMatchIndex(2);
performSearch({ ...baseOptions, search: 'world' });
expect(searchCounterInfo()?.currentIndex).toBe(0);
});

it('handles regexp queries', () => {
performSearch({ ...baseOptions, regexp: true });
expect(searchCounterInfo()?.numberOfItems).toBe(1);
});

it('handles invalid regexp without throwing', () => {
expect(() => {
performSearch({ ...baseOptions, regexp: true, search: '[invalid' });
}).not.toThrow();
});
});

describe('setSearchMatchIndex', () => {
it('is a no-op when there are no marks', () => {
setSearchMatchIndex(5);
expect(searchCounterInfo()?.currentIndex).toBe(0);
});

it('sets the current index within range', () => {
mockMatchCount.value = 3;
performSearch(baseOptions);
setSearchMatchIndex(1);
expect(searchCounterInfo()?.currentIndex).toBe(1);
});

it('wraps index using modulo when out of range', () => {
mockMatchCount.value = 3;
performSearch(baseOptions);
setSearchMatchIndex(5); // 5 % 3 = 2
expect(searchCounterInfo()?.currentIndex).toBe(2);
});

it('wraps to 0 when index equals mark count', () => {
mockMatchCount.value = 3;
performSearch(baseOptions);
setSearchMatchIndex(3); // 3 % 3 = 0
expect(searchCounterInfo()?.currentIndex).toBe(0);
});
});

describe('clearSearch', () => {
it('resets mark count to 0', () => {
mockMatchCount.value = 3;
performSearch(baseOptions);
clearSearch();
expect(searchCounterInfo()?.numberOfItems).toBe(0);
});

it('resets currentIndex to 0', () => {
mockMatchCount.value = 3;
performSearch(baseOptions);
setSearchMatchIndex(2);
clearSearch();
expect(searchCounterInfo()?.currentIndex).toBe(0);
});
});
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"lib": ["es2019", "dom"],
"noImplicitAny": true,
"moduleResolution": "node",
"ignoreDeprecations": "6.0",
"strictNullChecks": true,
"importHelpers": true,
"noEmit": true,
Expand Down
Loading