-
Notifications
You must be signed in to change notification settings - Fork 9
Implement SPI to support search highlight #89
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| 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 { | ||
|
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'); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.