Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import { Extension } from '@tiptap/core';import type { EditorState } from '@tiptap/pm/state';import { SearchQuery, search, setSearchState, getMatchHighlights } from 'prosemirror-search';
/** * Matching, position mapping and replacement come from `prosemirror-search`: * hand-written position mapping is what lands a replace on the wrong words after * one edit. Everything goes through a normal transaction, so a replacement * autosaves, reindexes and undoes with Ctrl+Z like typing. */
export type FindOptions = { query: string; replace: string; caseSensitive: boolean;};
export type FindCount = { total: number; /** Counting from 1; zero when nothing is selected. */ current: number;};
/** * The count reads the decoration set the plugin built to paint the highlights, not a * second walk of the document: that repeat on every transaction is what stalled typing * on a long scene. It also cannot disagree with what the writer can see. * * `applyQuery` must have put the query in the plugin first; a state whose query was * never dispatched reports zero. */export function countMatches(state: EditorState, options: FindOptions): FindCount { if (options.query.length === 0) return { total: 0, current: 0 };
const hits = getMatchHighlights(state).find(); if (hits.length === 0) return { total: 0, current: 0 };
const { from, to } = state.selection;
return { total: hits.length, current: hits.findIndex((hit) => hit.from === from && hit.to === to) + 1 };}
/** * The module paints every match and sets the one under the selection apart with its * own class. Nothing is overlaid here: a second decoration set doing the same job * drifts out of step with the first. */export const FindExtension = Extension.create({ name: 'fablewrightFind',
addProseMirrorPlugins() { return [search()]; }});
/** * An empty query passes through so the highlights clear; otherwise the plugin keeps * the last range and matches stay lit in a scene the writer stopped searching. */export function applyQuery( state: EditorState, options: FindOptions): ReturnType<typeof setSearchState> | null { const query = new SearchQuery({ search: options.query, caseSensitive: options.caseSensitive, replace: options.replace });
if (!query.valid && options.query.length > 0) return null;
return setSearchState(state.tr, query, null);}