Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

web: use plain list instead of tree for showing search results

Abdullah Attaa6ef69905eee
diff --git a/apps/web/src/components/list-container/index.tsx b/apps/web/src/components/list-container/index.tsx
index 02bf1aad1..4ddd98fb8 100644
--- a/apps/web/src/components/list-container/index.tsx
+++ b/apps/web/src/components/list-container/index.tsx
@@ -52,7 +52,6 @@ export const CustomScrollbarsVirtualList = forwardRef<
HTMLDivElement,
ScrollerProps & ScrollContainerProps
>(function CustomScrollbarsVirtualList(props, ref) {
- console.log({ props, ref });
return (
<ScrollContainer
{...props}
diff --git a/apps/web/src/components/list-container/list-profiles.tsx b/apps/web/src/components/list-container/list-profiles.tsx
index 4ebe70448..bb48fe960 100644
--- a/apps/web/src/components/list-container/list-profiles.tsx
+++ b/apps/web/src/components/list-container/list-profiles.tsx
@@ -28,6 +28,7 @@ import { GroupingKey, Item } from "@notesnook/core";
import { isNoteResolvedData } from "@notesnook/common";
import { Attachment } from "../attachment";
import { Notebook } from "../notebook";
+import SearchResult from "../search-result";
const SINGLE_LINE_HEIGHT = 1.4;
const DEFAULT_LINE_HEIGHT =
@@ -46,6 +47,8 @@ export function ListItemWrapper(props: ListItemWrapperProps) {
const { group, compact, context, item, data } = props;
switch (item.type) {
+ case "searchResult":
+ return <SearchResult item={item} />;
case "note": {
return (
<Note
diff --git a/apps/web/src/components/search-result/index.tsx b/apps/web/src/components/search-result/index.tsx
index 9fc3d87fc..fae918337 100644
--- a/apps/web/src/components/search-result/index.tsx
+++ b/apps/web/src/components/search-result/index.tsx
@@ -19,158 +19,211 @@ 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 from "react";
+import React, { useState } from "react";
import { useEditorStore } from "../../stores/editor-store";
import ListItem from "../list-item";
import { ChevronDown, ChevronRight } from "../icons";
import { noteMenuItems } from "../note";
import { db } from "../../common/db";
+import { MenuItem } from "@notesnook/ui";
type SearchResultProps = {
item: HighlightedResult;
matchIndex?: number;
- depth: number;
- isExpandable: boolean;
- isExpanded: boolean;
- collapse: () => void;
- expand: () => void;
};
function SearchResult(props: SearchResultProps) {
- const { item, matchIndex, collapse, expand, isExpandable, isExpanded } =
- props;
+ const { item, matchIndex } = props;
const isOpened = useEditorStore((store) => store.isNoteOpen(item.id));
const match = matchIndex !== undefined ? item.content[matchIndex] : undefined;
+ const isExpandable = !match && item.content.length > 0;
+ const [isExpanded, setIsExpanded] = useState(true);
+ if (!item.title.length && !item.content.length) return null;
return (
- <ListItem
- isFocused={match ? false : isOpened}
- isCompact={!match}
- item={item}
- menuItems={async (item, ids) => {
- const note = await db.notes.note(item.id);
- if (!note) return [];
-
- const colors = await db.relations
- .to({ type: "note", id: item.id }, "color")
- .resolve();
- return noteMenuItems(note, ids, {
- locked: !!(
- await db
- .sql()
- .selectFrom("content")
- .where("noteId", "in", [note.id])
- .select(["noteId", "locked"])
- .executeTakeFirst()
- )?.locked,
- color: colors[0]
- });
- }}
- onClick={() => {
- useEditorStore.getState().openSession(item.id, {
- rawContent: item.rawContent,
- force: true,
- activeSearchResultIndex: findSelectedMatchIndex(item, matchIndex || 0)
- });
- }}
- onMiddleClick={() => {
- useEditorStore.getState().openSession(item.id, {
- openInNewTab: true,
- rawContent: item.rawContent,
- activeSearchResultIndex: findSelectedMatchIndex(item, matchIndex || 0)
- });
- }}
- title={
- <Flex sx={{ alignItems: "center", gap: "small" }}>
- {isExpandable ? (
- <Button
- variant="secondary"
- sx={{ bg: "transparent", p: 0, borderRadius: 100 }}
- onClick={(e) => {
- e.stopPropagation();
- isExpanded ? collapse() : expand();
+ <Flex sx={{ flexDirection: "column" }}>
+ <ListItem
+ isFocused={isOpened}
+ item={item}
+ menuItems={menuItems}
+ onClick={() => {
+ useEditorStore.getState().openSession(item.id, {
+ rawContent: item.rawContent,
+ force: true
+ });
+ }}
+ onMiddleClick={() => {
+ useEditorStore.getState().openSession(item.id, {
+ openInNewTab: true,
+ rawContent: item.rawContent
+ });
+ }}
+ title={
+ <Flex sx={{ alignItems: "center", gap: "small" }}>
+ {isExpandable ? (
+ <Button
+ variant="secondary"
+ sx={{
+ bg: "transparent",
+ p: 0,
+ borderRadius: 100,
+ flexShrink: 0
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ setIsExpanded((s) => !s);
+ }}
+ >
+ {isExpanded ? (
+ <ChevronDown
+ size={14}
+ color={isOpened ? "icon-selected" : "icon"}
+ />
+ ) : (
+ <ChevronRight
+ size={14}
+ color={isOpened ? "icon-selected" : "icon"}
+ />
+ )}
+ </Button>
+ ) : null}
+ <Flex
+ sx={{
+ alignItems: "center",
+ justifyContent: "space-between",
+ flex: 1
}}
>
- {isExpanded ? (
- <ChevronDown
- size={14}
- color={isOpened ? "icon-selected" : "icon"}
- />
- ) : (
- <ChevronRight
- size={14}
- color={isOpened ? "icon-selected" : "icon"}
- />
- )}
- </Button>
- ) : null}
- <Text
- data-test-id={`title`}
- variant={"body"}
- color={isOpened ? "paragraph-selected" : "paragraph"}
- sx={{
- ...(match
- ? {
- whiteSpace: "pre-wrap"
+ <Text
+ data-test-id={`title`}
+ variant={"body"}
+ color={isOpened ? "paragraph-selected" : "paragraph"}
+ sx={{
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ fontWeight: "medium",
+ display: "block",
+ ".match": {
+ bg: "accent-secondary",
+ color: "accentForeground-secondary"
}
- : {
- whiteSpace: "nowrap",
- overflow: "hidden",
- textOverflow: "ellipsis"
- }),
- fontWeight: match ? "body" : "medium",
- display: "block",
- ".match": {
- bg: "accent-secondary",
- color: "accentForeground-secondary"
- }
- }}
- >
- {match
- ? match.map((match) => (
- <>
- <span>{match.prefix}</span>
- <span className="match">{match.match}</span>
- {match.suffix ? <span>{match.suffix}</span> : null}
- </>
- ))
- : item.title.map((match) => (
+ }}
+ >
+ {item.title.map((match) => (
<>
<span>{match.prefix}</span>
<span className="match">{match.match}</span>
{match.suffix ? <span>{match.suffix}</span> : null}
</>
))}
- </Text>
- </Flex>
- }
- footer={
- match ? undefined : (
- <Text variant="subBody">
- {item.content?.reduce((count, next) => next.length + count, 0) || 0}
- </Text>
- )
- }
- sx={{
- ...(match
- ? {
- px: 1,
- borderBottom: "1px solid var(--border)"
- }
- : {
- my: "small",
- borderRadius: "default"
- }),
- mx: 1
- }}
- />
+ </Text>
+
+ <Text variant="subBody">
+ {item.content?.reduce(
+ (count, next) => next.length + count,
+ 0
+ ) || 0}
+ </Text>
+ </Flex>
+ </Flex>
+ }
+ sx={{
+ my: "small",
+ borderRadius: "default",
+ mx: 1
+ }}
+ />
+ {isExpanded
+ ? item.content.map((match, index) => (
+ <ListItem
+ key={`${item.id}${index}`}
+ isFocused={false}
+ item={item}
+ menuItems={menuItems}
+ onClick={() => {
+ useEditorStore.getState().openSession(item.id, {
+ rawContent: item.rawContent,
+ force: true,
+ activeSearchResultIndex: findSelectedMatchIndex(
+ item,
+ matchIndex || 0
+ )
+ });
+ }}
+ onMiddleClick={() => {
+ useEditorStore.getState().openSession(item.id, {
+ openInNewTab: true,
+ rawContent: item.rawContent,
+ activeSearchResultIndex: findSelectedMatchIndex(
+ item,
+ matchIndex || 0
+ )
+ });
+ }}
+ title={
+ <Text
+ data-test-id={`title`}
+ variant={"body"}
+ color={isOpened ? "paragraph-selected" : "paragraph"}
+ sx={{
+ whiteSpace: "pre-wrap",
+ fontWeight: "body",
+ display: "block",
+ ".match": {
+ bg: "accent-secondary",
+ color: "accentForeground-secondary"
+ }
+ }}
+ >
+ {match.map((match) => (
+ <>
+ <span>{match.prefix}</span>
+ <span className="match">{match.match}</span>
+ {match.suffix ? <span>{match.suffix}</span> : null}
+ </>
+ ))}
+ </Text>
+ }
+ sx={{
+ px: 1,
+ borderBottom: "1px solid var(--border)",
+ mx: 1
+ }}
+ />
+ ))
+ : null}
+ </Flex>
);
}
export default React.memo(SearchResult);
+async function menuItems(
+ item: HighlightedResult,
+ ids?: string[]
+): Promise<MenuItem[]> {
+ const note = await db.notes.note(item.id);
+ if (!note) return [];
+
+ const colors = await db.relations
+ .to({ type: "note", id: item.id }, "color")
+ .resolve();
+ return noteMenuItems(note, ids, {
+ locked: !!(
+ await db
+ .sql()
+ .selectFrom("content")
+ .where("noteId", "in", [note.id])
+ .select(["noteId", "locked"])
+ .executeTakeFirst()
+ )?.locked,
+ color: colors[0]
+ });
+}
+
function findSelectedMatchIndex(item: HighlightedResult, matchIndex: number) {
let activeIndex = 0;
for (let i = 0; i <= matchIndex - 1; ++i) {
diff --git a/apps/web/src/views/all-notes.tsx b/apps/web/src/views/all-notes.tsx
index 96dc4933c..af47f38f7 100644
--- a/apps/web/src/views/all-notes.tsx
+++ b/apps/web/src/views/all-notes.tsx
@@ -48,25 +48,6 @@ function Home() {
useStore.getState().refresh();
}, []);
- // useEffect(() => {
- // (async function () {
-
- // // const titles =
- // // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
- // // for (let i = 0; i < 10000; ++i) {
- // // await db.notes.add({
- // // title: `${
- // // titles[getRandom(0, titles.length)]
- // // } Some other title of mine`
- // // });
- // // if (i % 100 === 0) console.log(i);
- // // }
- // // console.log("DONE");
- // })();
- // }, []);
-
- if (filteredItems) return <Search items={filteredItems} refresh={refresh} />;
-
if (!notes) return <ListLoader />;
return (
<ListContainer
@@ -75,6 +56,7 @@ function Home() {
compact={isCompact}
refresh={refresh}
items={filteredItems || notes}
+ isSearching={!!filteredItems}
placeholder={<Placeholder context={filteredItems ? "search" : "notes"} />}
button={{
onClick: () => useEditorStore.getState().newSession()
diff --git a/apps/web/src/views/notes.tsx b/apps/web/src/views/notes.tsx
index 3436eb387..71fa016a5 100644
--- a/apps/web/src/views/notes.tsx
+++ b/apps/web/src/views/notes.tsx
@@ -28,7 +28,6 @@ import { db } from "../common/db";
import { handleDrop } from "../common/drop-handler";
import { useEditorStore } from "../stores/editor-store";
import { ListLoader } from "../components/loaders/list-loader";
-import Search from "./search";
type NotesProps = { header?: JSX.Element };
function Notes(props: NotesProps) {
@@ -53,9 +52,6 @@ function Notes(props: NotesProps) {
[context, contextNotes]
);
- if (filteredItems)
- return <Search items={filteredItems} refresh={refreshContext} />;
-
if (!context || !contextNotes) return <ListLoader />;
return (
<ListContainer
@@ -64,7 +60,8 @@ function Notes(props: NotesProps) {
refresh={refreshContext}
compact={isCompact}
context={context}
- items={contextNotes}
+ items={filteredItems || contextNotes}
+ isSearching={!!filteredItems}
onDrop={(e) => handleDrop(e.dataTransfer, context)}
placeholder={
<Placeholder
diff --git a/apps/web/src/views/search.tsx b/apps/web/src/views/search.tsx
deleted file mode 100644
index e33ad8ae8..000000000
--- a/apps/web/src/views/search.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-This file is part of the Notesnook project (https://notesnook.com/)
-
-Copyright (C) 2023 Streetwriters (Private) Limited
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-import { HighlightedResult, VirtualizedGrouping } from "@notesnook/core";
-import { strings } from "@notesnook/intl";
-import { Text } from "@theme-ui/components";
-import GroupHeader from "../components/group-header";
-import {
- TreeNode,
- VirtualizedTree,
- VirtualizedTreeHandle
-} from "../components/virtualized-tree";
-import { useEffect, useRef } from "react";
-import SearchResult from "../components/search-result";
-
-type NotesProps = {
- items: VirtualizedGrouping<HighlightedResult>;
- refresh: () => void;
-};
-function Search(props: NotesProps) {
- const { items, refresh } = props;
- const treeRef = useRef<
- VirtualizedTreeHandle<{
- item: HighlightedResult;
- matchIndex?: number;
- }>
- >(null);
-
- useEffect(() => {
- treeRef.current?.resetAndRefresh();
- }, [items]);
-
- return (
- <>
- {items.length === 0 ? (
- <Text
- variant="body"
- sx={{ color: "paragraph-secondary", mx: 1 }}
- data-test-id="list-placeholder"
- >
- {strings.noResultsFound()}
- </Text>
- ) : (
- <>
- <GroupHeader
- groupingKey={"search"}
- isSearching={true}
- refresh={refresh}
- title={strings.results(items.length)}
- isFocused={false}
- index={0}
- onSelectGroup={() => {}}
- groups={async () => []}
- onJump={() => {}}
- />
- <VirtualizedTree
- treeRef={treeRef}
- testId="search-results-list"
- rootId={"root"}
- getChildNodes={async (parent) => {
- const nodes: TreeNode<{
- item: HighlightedResult;
- matchIndex?: number;
- }>[] = [];
- if (parent.id === "root") {
- for (let i = 0; i < items.length; ++i) {
- const result = await items.item(i);
- if (!result.item) continue;
- nodes.push({
- data: { item: result.item },
- depth: parent.depth + 1,
- hasChildren: !!result.item.content?.length,
- id: result.item.id,
- parentId: parent.id,
- expanded: true
- });
- }
- } else {
- for (
- let i = 0;
- i < (parent.data.item.content.length || 0);
- ++i
- ) {
- nodes.push({
- data: { item: parent.data.item, matchIndex: i },
- depth: parent.depth + 1,
- parentId: parent.id,
- id: parent.id + i,
- hasChildren: false
- });
- }
- }
- return nodes;
- }}
- renderItem={({ collapse, expand, expanded, item: node }) => (
- <SearchResult
- key={node.id}
- depth={node.depth}
- isExpandable={node.hasChildren}
- item={node.data.item}
- matchIndex={node.data.matchIndex}
- isExpanded={expanded}
- collapse={collapse}
- expand={expand}
- />
- )}
- />
- </>
- )}
- </>
- );
-}
-export default Search;