A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
web: fix scroll to search result (#8290)
01zulfia349611a3062
diff --git a/apps/web/src/components/editor/index.tsx b/apps/web/src/components/editor/index.tsxindex 4e23d6a28..aa57a52ce 100644--- a/apps/web/src/components/editor/index.tsx+++ b/apps/web/src/components/editor/index.tsx@@ -242,8 +242,7 @@ const MemoizedEditorView = React.memo(EditorView, (prev, next) => {prev.session.type === next.session.type &&prev.session.needsHydration === next.session.needsHydration &&prev.session.activeBlockId === next.session.activeBlockId &&- prev.session.activeSearchResultIndex ===- next.session.activeSearchResultIndex+ prev.session.activeSearchResultId === next.session.activeSearchResultId);});function EditorView({@@ -855,28 +854,29 @@ function useScrollToBlock(session: EditorSession) {}function useScrollToSearchResult(session: EditorSession) {- const index = useEditorStore(- (store) => store.getSession(session.id)?.activeSearchResultIndex+ const id = useEditorStore(+ (store) => store.getSession(session.id)?.activeSearchResultId);useEffect(() => {- if (index === undefined) return;+ if (id === undefined) return;const scrollContainer = document.getElementById(`editorScroll_${session.id}`);scrollContainer?.closest(".active")?.classList.add("searching");- const elements = scrollContainer?.getElementsByTagName("nn-search-result");+ const element = scrollContainer?.querySelector(`nn-search-result#${id}`);setTimeout(() =>- elements- ?.item(index)- ?.scrollIntoView({ block: "center", behavior: "instant" }),+ element?.scrollIntoView({+ block: "center",+ behavior: "instant"+ }),100);useEditorStore.getState().updateSession(session.id, [session.type], {- activeSearchResultIndex: undefined+ activeSearchResultId: undefined});- }, [session.id, session.type, index]);+ }, [session.id, session.type, id]);}function isFile(e: DragEvent) {diff --git a/apps/web/src/components/search-result/index.tsx b/apps/web/src/components/search-result/index.tsxindex aaaf54dfa..0bfc16598 100644--- a/apps/web/src/components/search-result/index.tsx+++ b/apps/web/src/components/search-result/index.tsx@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { HighlightedResult } from "@notesnook/core";import { Button, Flex, Text } from "@theme-ui/components";-import React, { useState } from "react";+import React, { Fragment, useState } from "react";import { useEditorStore } from "../../stores/editor-store";import { useStore as useNoteStore } from "../../stores/note-store";import ListItem from "../list-item";@@ -112,11 +112,11 @@ function SearchResult(props: SearchResultProps) {}}>{item.title.map((match) => (- <>+ <Fragment key={match.id}><span>{match.prefix}</span><span className="match">{match.match}</span>{match.suffix ? <span>{match.suffix}</span> : null}- </>+ </Fragment>))}</Text>@@ -146,14 +146,14 @@ function SearchResult(props: SearchResultProps) {useEditorStore.getState().openSession(item.id, {rawContent: item.rawContent,force: true,- activeSearchResultIndex: findSelectedMatchIndex(item, index)+ activeSearchResultId: match[0].id});}}onMiddleClick={() => {useEditorStore.getState().openSession(item.id, {openInNewTab: true,rawContent: item.rawContent,- activeSearchResultIndex: findSelectedMatchIndex(item, index)+ activeSearchResultId: match[0].id});}}title={@@ -171,11 +171,11 @@ function SearchResult(props: SearchResultProps) {}}>{match.map((match) => (- <>+ <Fragment key={match.id}><span>{match.prefix}</span><span className="match">{match.match}</span>{match.suffix ? <span>{match.suffix}</span> : null}- </>+ </Fragment>))}</Text>}@@ -215,11 +215,3 @@ async function menuItems(color: colors[0]});}--function findSelectedMatchIndex(item: HighlightedResult, matchIndex: number) {- let activeIndex = 0;- for (let i = 0; i <= matchIndex - 1; ++i) {- activeIndex += item.content[i].length;- }- return activeIndex;-}diff --git a/apps/web/src/stores/editor-store.ts b/apps/web/src/stores/editor-store.tsindex 5117c1966..71083ee43 100644--- a/apps/web/src/stores/editor-store.ts+++ b/apps/web/src/stores/editor-store.ts@@ -85,9 +85,9 @@ export type BaseEditorSession = {*/activeBlockId?: string;/**- * The index of search result to scroll to after opening the session successfully.+ * The id of search result to scroll to after opening the session successfully.*/- activeSearchResultIndex?: number;+ activeSearchResultId?: string;};export type LockedEditorSession = BaseEditorSession & {@@ -666,7 +666,7 @@ class EditorStore extends BaseStore<EditorStore> {silent?: boolean;openInNewTab?: boolean;rawContent?: string;- activeSearchResultIndex?: number;+ activeSearchResultId?: string;} = {}): Promise<void> => {const {@@ -790,7 +790,7 @@ class EditorStore extends BaseStore<EditorStore> {id: sessionId,content,activeBlockId: options.activeBlockId,- activeSearchResultIndex: options.activeSearchResultIndex,+ activeSearchResultId: options.activeSearchResultId,tabId},options.silent@@ -814,7 +814,7 @@ class EditorStore extends BaseStore<EditorStore> {color: colors[0]?.fromId,tags,activeBlockId: options.activeBlockId,- activeSearchResultIndex: options.activeSearchResultIndex,+ activeSearchResultId: options.activeSearchResultId,tabId},options.silent@@ -835,7 +835,7 @@ class EditorStore extends BaseStore<EditorStore> {? { ...content, data: options.rawContent }: content,activeBlockId: options.activeBlockId,- activeSearchResultIndex: options.activeSearchResultIndex,+ activeSearchResultId: options.activeSearchResultId,tabId},options.silentdiff --git a/packages/core/src/api/lookup.ts b/packages/core/src/api/lookup.tsindex 2288b6bbd..8cdab505a 100644--- a/packages/core/src/api/lookup.ts+++ b/packages/core/src/api/lookup.ts@@ -62,10 +62,8 @@ type FuzzySearchField<T> = {};const MATCH_TAG_NAME = "nn-search-result";-const MATCH_TAG_OPEN = `<${MATCH_TAG_NAME}>`;-const MATCH_TAG_CLOSE = `</${MATCH_TAG_NAME}>`;const MATCH_TAG_REGEX = new RegExp(- `<${MATCH_TAG_NAME}>(.*?)<\\/${MATCH_TAG_NAME}>`,+ `<${MATCH_TAG_NAME}\\s+id="(.+?)">(.*?)<\\/${MATCH_TAG_NAME}>`,"gm");export default class Lookup {@@ -778,10 +776,11 @@ function highlightQueries(const regex = new RegExp(patterns.join("|"), "gi");let hasMatches = false;+ let matchIdCounter = 0;const result = text.replace(regex, (match) => {hasMatches = true;- return `${MATCH_TAG_OPEN}${match}${MATCH_TAG_CLOSE}`;+ return createSearchResultTag(match, `match-${++matchIdCounter}`);});return { text: result, hasMatches };@@ -796,10 +795,11 @@ export function splitHighlightedMatch(text: string): Match[][] {let matches: Match[] = [];let totalLength = 0;- for (let i = 0; i < parts.length - 1; i += 2) {+ for (let i = 0; i < parts.length - 1; i += 3) {const prefix = parts[i];- const match = parts[i + 1];- let suffix = parts.at(i + 2);+ const matchId = parts[i + 1];+ const match = parts[i + 2];+ let suffix = parts[i + 3];const matchLength = prefix.length + match.length + (suffix?.length || 0);if (totalLength > 120 && matches.length > 0) {@@ -815,14 +815,15 @@ export function splitHighlightedMatch(text: string): Match[][] {suffix,Math.max(suffix.length / 2, 60));- parts[i + 2] = remaining;+ parts[i + 3] = remaining;suffix = _suffix;}matches.push({match,prefix: prefix.replace(/\s{2,}/gm, " ").trimStart(),- suffix: suffix || ""+ suffix: suffix || "",+ id: matchId || undefined});totalLength += matchLength;@@ -944,7 +945,8 @@ function stringToMatch(str: string): Match[] {{prefix: str,match: "",- suffix: ""+ suffix: "",+ id: undefined}];}@@ -962,6 +964,7 @@ function highlightHtmlContent(html: string, queries: string[]): string {const searchRegex = new RegExp(`(${patterns.join("|")})`, "gi");let result = "";+ let matchIdCounter = 0;// Stack to track elements and their buffered contentinterface ElementInfo {@@ -981,9 +984,8 @@ function highlightHtmlContent(html: string, queries: string[]): string {// Reset regex state after testsearchRegex.lastIndex = 0;- const processed = text.replace(- searchRegex,- "<nn-search-result>$1</nn-search-result>"+ const processed = text.replace(searchRegex, (match) =>+ createSearchResultTag(match, `match-${++matchIdCounter}`));if (hasMatch) {@@ -1150,18 +1152,23 @@ function getMatchScore(function textContainsTokens(text: string, tokens: QueryTokens) {const lowerCasedText = text.toLowerCase();++ const createTagPattern = (token: string) => {+ return `<${MATCH_TAG_NAME}\\s+id="(.+?)">${token}<\\/${MATCH_TAG_NAME}>`;+ };+if (!tokens.notTokens.every(- (t) => !lowerCasedText.includes(`${MATCH_TAG_OPEN}${t}${MATCH_TAG_CLOSE}`)+ (t) => !new RegExp(createTagPattern(t), "i").test(lowerCasedText)))return false;return (tokens.andTokens.every((t) =>- lowerCasedText.includes(`${MATCH_TAG_OPEN}${t}${MATCH_TAG_CLOSE}`)+ new RegExp(createTagPattern(t), "i").test(lowerCasedText)) ||tokens.orTokens.some((t) =>- lowerCasedText.includes(`${MATCH_TAG_OPEN}${t}${MATCH_TAG_CLOSE}`)+ new RegExp(createTagPattern(t), "i").test(lowerCasedText)));}@@ -1198,3 +1205,7 @@ function transformTokens(tokens: QueryTokens | undefined) {allTokens: [...andTokens, ...orTokens]};}++function createSearchResultTag(content: string, id: string) {+ return `<${MATCH_TAG_NAME} id="${id}">${content}</${MATCH_TAG_NAME}>`;+}diff --git a/packages/core/src/types.ts b/packages/core/src/types.tsindex ec38b1e7c..aeeb6adc8 100644--- a/packages/core/src/types.ts+++ b/packages/core/src/types.ts@@ -494,6 +494,7 @@ export type Match = {prefix: string;match: string;suffix: string;+ id?: string;};export interface HighlightedResult extends BaseItem<"searchResult"> {diff --git a/packages/core/src/utils/html-parser.ts b/packages/core/src/utils/html-parser.tsindex a64ca5e90..5f8ea6a5a 100644--- a/packages/core/src/utils/html-parser.ts+++ b/packages/core/src/utils/html-parser.ts@@ -176,7 +176,7 @@ export function extractMatchingBlocks(html: string, matchTagName: string) {const parser = new Parser({ontext: (data) => (text += data),- onopentag(name) {+ onopentag(name, attributes) {if (!INLINE_TAGS.includes(name) && name !== matchTagName) {openedTag = name;text = "";@@ -184,7 +184,12 @@ export function extractMatchingBlocks(html: string, matchTagName: string) {}if (name === matchTagName) {hasMatches = true;- text += `<${name}>`;+ let tagString = `<${name}`;+ if (attributes.id) {+ tagString += ` id="${attributes.id}"`;+ }+ tagString += ">";+ text += tagString;}},onclosetag(name) {diff --git a/packages/editor/src/extensions/search-result/search-result.ts b/packages/editor/src/extensions/search-result/search-result.tsindex 5ecc8cc71..07a2b9b7e 100644--- a/packages/editor/src/extensions/search-result/search-result.ts+++ b/packages/editor/src/extensions/search-result/search-result.ts@@ -26,6 +26,18 @@ export const SearchResult = Mark.create({return [{ tag: "nn-search-result" }];},+ addAttributes() {+ return {+ id: {+ default: null,+ parseHTML: (element) => element.getAttribute("id"),+ renderHTML: (attributes) => {+ return attributes.id ? { id: attributes.id } : {};+ }+ }+ };+ },+renderHTML({ HTMLAttributes }) {return ["nn-search-result",