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: make `link to notebook` much more ux friendly
Abdullah Atta7ffe7f1a0c4e
diff --git a/apps/web/src/components/dialogs/move-note-dialog.tsx b/apps/web/src/components/dialogs/move-note-dialog.tsxindex 2900f64f3..d27a1a35c 100644--- a/apps/web/src/components/dialogs/move-note-dialog.tsx+++ b/apps/web/src/components/dialogs/move-note-dialog.tsx@@ -17,15 +17,8 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import {- ChangeEvent,- useCallback,- useEffect,- useMemo,- useRef,- useState-} from "react";-import { Button, Flex, Input, Text } from "@theme-ui/components";+import { ChangeEvent, useCallback, useEffect, useRef, useState } from "react";+import { Box, Button, Flex, Input, Text } from "@theme-ui/components";import * as Icon from "../icons";import { db } from "../../common/db";import Dialog from "./dialog";@@ -33,23 +26,51 @@ import Field from "../field";import { useStore, store } from "../../stores/notebook-store";import { store as notestore } from "../../stores/note-store";import { Perform } from "../../common/dialog-controller";-import { ThemeUIStyleObject } from "@theme-ui/core";import { showToast } from "../../utils/toast";import { pluralize } from "../../utils/string";+import { isMac } from "../../utils/platform";+import create from "zustand";+import { usePersistentState } from "../../hooks/use-persistent-state";type MoveDialogProps = { onClose: Perform; noteIds: string[] };-type NotebookReference = { id: string; topic: string; type: "add" | "remove" };+type NotebookReference = {+ id: string;+ topic: string;+ new: boolean;+ op: "add" | "remove";+};type Item = {id: string;type: "topic" | "notebook" | "header";title: string;};-type Notebook = Item & { topics: Item[] };+type Topic = Item & { notebookId: string };+type Notebook = Item & { topics: Topic[]; dateCreated: number };++interface ISelectionStore {+ selected: NotebookReference[];+ isMultiselect: boolean;+ setSelected(refs: NotebookReference[]): void;+ setIsMultiselect(state: boolean): void;+}+export const useSelectionStore = create<ISelectionStore>((set) => ({+ selected: [],+ isMultiselect: false,+ setSelected: (selected) => set({ selected }),+ setIsMultiselect: (isMultiselect) => set({ isMultiselect })+}));function MoveDialog({ onClose, noteIds }: MoveDialogProps) {- const [selected, setSelected] = useState<NotebookReference[]>([]);+ const { selected, setIsMultiselect, isMultiselect, setSelected } =+ useSelectionStore();++ const [suggestion, setSuggestion] = usePersistentState<NotebookReference[]>(+ "link-notebooks:suggestion",+ []+ );const refreshNotebooks = useStore((store) => store.refresh);+ const notebooks = useStore((store) => store.notebooks);const getAllNotebooks = useCallback(() => {refreshNotebooks();return (store.get().notebooks as Notebook[]).filter(@@ -57,22 +78,46 @@ function MoveDialog({ onClose, noteIds }: MoveDialogProps) {);}, [refreshNotebooks]);+ useEffect(() => {+ if (!notebooks) return;++ const selected: NotebookReference[] = [];+ for (const notebook of notebooks as Notebook[]) {+ if (notebook.type === "header") continue;+ for (const topic of notebook.topics) {+ if (topicHasNotes(topic, noteIds)) {+ selected.push({+ id: notebook.id,+ topic: topic.id,+ op: "add",+ new: false+ });+ }+ }+ }+ setSelected(selected);+ setIsMultiselect(false);+ }, [noteIds, notebooks, setSelected, setIsMultiselect]);+return (<DialogisOpen={true}- title={"Add to notebook"}- description={"You can add a single note to multiple notebooks & topics."}- onClose={onClose}- width={"30%"}+ title={"Select notebooks"}+ description={`Use ${+ isMac() ? "cmd" : "ctrl"+ }+click to select multiple topics`}+ onClose={() => onClose(false)}+ width={450}positiveButton={{- text: "Finish",+ text: "Done",disabled: !selected.length,onClick: async () => {+ setSuggestion(selected);for (const item of selected) {try {- if (item.type === "remove") {+ if (item.op === "remove") {await db.notes?.removeFromNotebook(item, ...noteIds);- } else if (item.type === "add") {+ } else if (item.op === "add") {await db.notes?.addToNotebook(item, ...noteIds);}} catch (e) {@@ -80,35 +125,29 @@ function MoveDialog({ onClose, noteIds }: MoveDialogProps) {console.error(e);}}+notestore.refresh();- const addedTopics = selected.filter((a) => a.type === "add").length;++ const addedTopics = selected.filter((a) => a.op === "add").length;const removedTopics = selected.filter(- (a) => a.type === "remove"+ (a) => a.op === "remove").length;- if (addedTopics)- showToast(- "success",- `Added ${pluralize(- noteIds.length,- "note",- "notes"- )} to ${pluralize(addedTopics, "topic", "topics")}`- );- if (removedTopics)- showToast(- "success",- `Removed ${pluralize(- noteIds.length,- "note",- "notes"- )} from ${pluralize(removedTopics, "topic", "topics")}`- );++ showToast(+ "success",+ `${pluralize(noteIds.length, "note", "notes")} added to ${pluralize(+ addedTopics,+ "topic",+ "topics"+ )} & removed from ${pluralize(removedTopics, "topic", "topics")}.`+ );+onClose(true);}}}negativeButton={{text: "Cancel",- onClick: onClose+ onClick: () => onClose(false)}}><Flex@@ -116,10 +155,30 @@ function MoveDialog({ onClose, noteIds }: MoveDialogProps) {sx={{ overflowY: "hidden", flexDirection: "column" }}data-test-id="notebook-list">- <FilteredList+ {suggestion.length > 0 && selected.length <= 0 && (+ <Flex+ sx={{+ bg: "shade",+ borderRadius: "default",+ p: 1,+ alignItems: "center",+ cursor: "pointer",+ ":hover": {+ filter: "brightness(70%)"+ }+ }}+ onClick={() => setSelected(suggestion.slice())}+ >+ <Icon.Suggestion color="primary" size={16} sx={{ mr: 1 }} />+ <Text variant="body" sx={{ color: "primary" }}>+ {stringifySelected(suggestion)}+ </Text>+ </Flex>+ )}+ <FilteredTreeplaceholders={{empty: "Add a new notebook",- filter: "Filter notebooks"+ filter: "Search or add a new notebook"}}items={getAllNotebooks}filter={(notebooks, query) =>@@ -130,82 +189,234 @@ function MoveDialog({ onClose, noteIds }: MoveDialogProps) {title})}- renderItem={(notebook, _index, refresh) => {- return (- <TreeNode- item={notebook}- items={notebook.topics}- placeholder={- <Text- variant="body"- sx={{ color: "fontTertiary", textAlign: "center" }}- >- {"You have no topics in this notebook."}- </Text>- }- isSelected={(item) => {- if (item.type === "notebook") {- return notebook.topics.some((topic) =>- topicHasNotes(topic, noteIds)- );- } else if (item.type === "topic") {- const selectedItem = selected.find(- (t) => t.topic === item.id- );- if (selectedItem?.type === "remove") return false;- return (- selectedItem?.type === "add" ||- topicHasNotes(item, noteIds)- );- }- return false;- }}- onSelected={(topic) => {- if (!topic) return;-- const opType = topicHasNotes(topic, noteIds)- ? "remove"- : "add";- setSelected((s) => {- const copy = s.slice();- const index = copy.findIndex((i) => i.topic === topic.id);- if (index === -1)- copy.push({- id: notebook.id,- topic: topic.id,- type: opType- });- else copy.splice(index, 1);- return copy;- });- }}- onCreateItem={async (title) => {- await db.notebooks?.notebook(notebook.id).topics.add(title);- refresh();- }}- />- );- }}+ renderItem={(notebook, _index, refresh, isSearching) => (+ <NotebookItem+ notebook={notebook}+ isSearching={isSearching}+ onCreateItem={async (title) => {+ await db.notebooks?.notebook(notebook.id).topics.add(title);+ refresh();+ }}+ />+ )}/></Flex>+ {isMultiselect && (+ <Button+ variant="anchor"+ onClick={() => {+ setIsMultiselect(false);+ setSelected(+ selected.filter((a) => !a.new).map((s) => ({ ...s, op: "add" }))+ );+ }}+ sx={{ textDecoration: "none", mt: 1 }}+ >+ Reset selection+ </Button>+ )}</Dialog>);}-function topicHasNotes(topic: Item, noteIds: string[]) {- const notes: string[] = db.notes?.topicReferences.get(topic.id) || [];- return noteIds.some((id) => notes.indexOf(id) > -1);+function NotebookItem(props: {+ notebook: Notebook;+ isSearching: boolean;+ onCreateItem: (title: string) => void;+}) {+ const { notebook, isSearching, onCreateItem } = props;++ const { selected, setIsMultiselect, setSelected } = useSelectionStore();++ const [isCreatingNew, setIsCreatingNew] = useState(false);+ const isSelected = isNotebookSelected(notebook, selected);++ return (+ <Box as="li">+ <Box+ as="details"+ sx={{+ "&[open] .arrow-up": { display: "block" },+ "&[open] .arrow-down": { display: "none" },+ "&[open] .title": { fontWeight: "bold" },+ "&[open] .create-topic": { display: "block" }+ }}+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ //@ts-ignore+ open={isSearching}+ >+ <Flex+ as="summary"+ sx={{+ cursor: "pointer",+ justifyContent: "space-between",+ alignItems: "center",+ bg: "bgSecondary",+ borderRadius: "default",+ p: 1,+ height: "40px"+ }}+ >+ <Flex+ sx={{ alignItems: "center" }}+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();++ setIsMultiselect(true);+ setSelected(+ selectNotebook(notebook, selected, isSelected || false)+ );+ }}+ >+ <SelectedCheck size={20} selected={isSelected} />+ <Text+ className="title"+ variant="subtitle"+ sx={{ fontWeight: "body" }}+ >+ {notebook.title}+ <Text variant="subBody" sx={{ fontWeight: "body" }}>+ {" "}+ ({pluralize(notebook.topics.length, "topic", "topics")})+ </Text>+ </Text>+ </Flex>+ <Flex sx={{ alignItems: "center" }}>+ <Button+ variant="tool"+ className="create-topic"+ sx={{ display: "none", p: 1, mr: 1 }}+ >+ <Icon.Plus+ size={18}+ title="Add a new topic"+ onClick={() => setIsCreatingNew(true)}+ />+ </Button>+ <Icon.ChevronDown+ className="arrow-down"+ size={20}+ sx={{ height: "20px" }}+ />+ <Icon.ChevronUp+ className="arrow-up"+ size={20}+ sx={{ display: "none", height: "20px" }}+ />+ </Flex>+ </Flex>+ <Box+ as="ul"+ sx={{+ listStyle: "none",+ pl: 4,+ mt: 1,+ gap: "2px",+ display: "flex",+ flexDirection: "column"+ }}+ >+ {isCreatingNew && (+ <Flex+ as="li"+ sx={{+ alignItems: "center",+ p: "small"+ }}+ >+ <SelectedCheck selected={false} />+ <Input+ variant="clean"+ data-test-id={`new-tree-item-input`}+ autoFocus+ sx={{+ bg: "bgSecondary",+ p: "small",+ border: "1px solid var(--border)"+ }}+ onBlur={() => setIsCreatingNew(false)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ setIsCreatingNew(false);+ onCreateItem(e.currentTarget.value);+ } else if (e.key === "Escape") {+ setIsCreatingNew(false);+ }+ }}+ />+ </Flex>+ )}+ {notebook.topics.map((topic) => (+ <TopicItem key={topic.id} topic={topic} />+ ))}+ </Box>+ </Box>+ </Box>+ );}-type FilteredListProps<T extends Item> = {+function TopicItem(props: { topic: Topic }) {+ const { topic } = props;++ const { selected, setIsMultiselect, setSelected, isMultiselect } =+ useSelectionStore();++ const index = findSelectionIndex(topic, selected);+ const selectedTopic = selected[index];++ return (+ <Flex+ as="li"+ key={topic.id}+ sx={{+ alignItems: "center",+ p: "small",+ borderRadius: "default",+ cursor: "pointer",+ ":hover": { bg: "hover" }+ }}+ onClick={(e) => {+ const isCtrlPressed = e.ctrlKey || e.metaKey;+ if (isCtrlPressed) setIsMultiselect(true);++ if (isMultiselect || isCtrlPressed) {+ setSelected(selectMultipleTopics(topic, selected));+ } else {+ setSelected(selectSingleTopic(topic, selected));+ }+ }}+ >+ <SelectedCheck+ selected={+ selectedTopic?.op === "remove"+ ? "remove"+ : selectedTopic?.op === "add"+ }+ />+ <Text variant="body" sx={{ fontSize: "subtitle" }}>+ {topic.title}+ </Text>+ </Flex>+ );+}++export default MoveDialog;++type FilteredTreeProps<T extends Item> = {placeholders: { filter: string; empty: string };items: () => T[];filter: (items: T[], query: string) => T[];onCreateNewItem: (title: string) => Promise<void>;- renderItem: (item: T, index: number, refresh: () => void) => JSX.Element;+ renderItem: (+ item: T,+ index: number,+ refresh: () => void,+ isSearching: boolean+ ) => JSX.Element;};-function FilteredList<T extends Item>(props: FilteredListProps<T>) {+function FilteredTree<T extends Item>(props: FilteredTreeProps<T>) {const {items: _items,filter,@@ -277,7 +488,19 @@ function FilteredList<T extends Item>(props: FilteredListProps<T>) {: { icon: Icon.Search, onClick: () => _filter(query) }}/>- <Flex mt={1} sx={{ overflowY: "hidden", flexDirection: "column" }}>+ <Flex+ as="ul"+ mt={1}+ sx={{+ overflowY: "hidden",+ listStyle: "none",+ m: 0,+ p: 0,+ gap: 1,+ display: "flex",+ flexDirection: "column"+ }}+ >{noItemsFound && (<Buttonvariant={"secondary"}@@ -295,161 +518,154 @@ function FilteredList<T extends Item>(props: FilteredListProps<T>) {<Icon.Plus size={16} color="primary" /></Button>)}- {items.map((item, index) => renderItem(item, index, refresh))}+ {items.map((item, index) => renderItem(item, index, refresh, !!query))}</Flex></>);}-export default MoveDialog;-type TreeNodeProps<T extends Item> = {- item: T;- items?: T[];- sx?: ThemeUIStyleObject;- isSelected: (item: T) => boolean;- onSelected: (item: T) => void;- onCreateItem?: (title: string) => void;- placeholder?: JSX.Element;-};+function SelectedCheck({+ selected,+ size = 20+}: {+ selected: boolean | null | "remove";+ size?: number;+}) {+ return selected === true ? (+ <Icon.CheckCircleOutline size={size} sx={{ mr: 1 }} color="primary" />+ ) : selected === null ? (+ <Icon.CheckIntermediate size={size} sx={{ mr: 1 }} color="dimPrimary" />+ ) : selected === "remove" ? (+ <Icon.CheckRemove size={size} sx={{ mr: 1 }} color="error" />+ ) : (+ <Icon.CircleEmpty size={size} sx={{ mr: 1, opacity: 0.4 }} />+ );+}-function TreeNode<T extends Item>(props: TreeNodeProps<T>) {- const { isSelected, item, items, onCreateItem, onSelected, sx, placeholder } =- props;+function createSelection(topic: Topic): NotebookReference {+ return {+ id: topic.notebookId,+ topic: topic.id,+ op: "add",+ new: true+ };+}- const [expanded, setExpanded] = useState(false);- const [isCreatingNew, setIsCreatingNew] = useState(false);- const _isSelected = useMemo(() => isSelected(item), [item, isSelected]);+function findSelectionIndex(+ topic: Topic | NotebookReference,+ array: NotebookReference[]+) {+ return "op" in topic+ ? array.findIndex((a) => a.id === topic.id && a.topic === topic.topic)+ : array.findIndex((a) => a.id === topic.notebookId && a.topic === topic.id);+}- return (- <Flex sx={{ flexDirection: "column" }} data-test-id={item.type}>- <TreeItem- title={item.title}- testId={`tree-item`}- isSelected={_isSelected}- icon={- _isSelected- ? Icon.Checkmark- : items- ? expanded- ? Icon.ChevronDown- : Icon.ChevronRight- : Icon.Topic- }- sx={{- bg: _isSelected ? "shade" : "transparent",- ...sx- }}- onExpand={() => {- if (items) {- setExpanded((s) => !s);- return;- }- onSelected(item);- }}- onCreateItem={- items && onCreateItem- ? () => {- setExpanded(true);- setIsCreatingNew(true);- }- : null- }- />- {expanded ? (- <>- {isCreatingNew ? (- <Flex sx={{ pl: 3, my: 1 }}>- <Input- data-test-id={`new-tree-item-input`}- autoFocus- sx={{ bg: "background", p: "7px" }}- placeholder="Press enter to create a new topic"- onBlur={() => setIsCreatingNew(false)}- onKeyDown={(e) => {- if (e.key === "Enter") {- setIsCreatingNew(false);- onCreateItem?.((e.target as HTMLInputElement).value);- } else if (e.key === "Escape") {- setIsCreatingNew(false);- }- }}- />- </Flex>- ) : null}- {items?.length- ? items?.map((item) => (- <TreeNode- key={item.id}- item={item}- isSelected={isSelected}- onSelected={() => onSelected(item)}- sx={{ pl: 3 }}- />- ))- : placeholder}- </>- ) : null}- </Flex>- );+function topicHasNotes(topic: Item, noteIds: string[]) {+ const notes: string[] = db.notes?.topicReferences.get(topic.id) || [];+ return noteIds.some((id) => notes.indexOf(id) > -1);}-type TreeItemProps = {- title: string;- onExpand: () => void;- icon: (props: { size: number }) => JSX.Element;- sx?: ThemeUIStyleObject;- onCreateItem?: (() => void) | null;- testId?: string;- isSelected: boolean;-};+// There are 3 cases:+// 1. Click on a notebook to select/deselect all its topics+// 2. Click on a topic to select/deselect it (and deselect all other topics)+// 3. Ctrl+click on a topic to enter multi select-function TreeItem(props: TreeItemProps) {- const {- icon: TreeItemIcon,- onCreateItem,- onExpand,- title,- sx,- testId,- isSelected- } = props;+function selectNotebook(+ notebook: Notebook,+ selected: NotebookReference[],+ isNotebookSelected: boolean+) {+ for (const topic of notebook.topics) {+ const index = findSelectionIndex(topic, selected);+ const item = selected[index];- return (- <Flex- sx={{- alignItems: "center",- p: "3px",- cursor: "pointer",- ":hover": { bg: isSelected ? "dimPrimary" : "hover" },- justifyContent: "space-between",- ...sx- }}- onClick={onExpand}- data-test-id={testId}- >- <Flex>- {TreeItemIcon && <TreeItemIcon size={18} />}- <Text- variant={"body"}- sx={{ fontSize: "subtitle" }}- data-test-id="title"- >- {title}- </Text>- </Flex>- {onCreateItem && (- <Button- variant="tool"- sx={{ p: "2px" }}- onClick={(e) => {- e.stopPropagation();- onCreateItem();- }}- data-test-id="tree-item-new"- >- <Icon.Plus size={18} />- </Button>- )}- </Flex>- );+ // 1. first reset the item's selection state+ // 2. set the new state++ if (item?.new) selected.splice(index, 1);+ else if (item && !item.new) item.op = "remove";++ if (!isNotebookSelected) {+ if (!item || item.new) selected.push(createSelection(topic));+ else if (item && !item.new) item.op = "add";+ }+ }++ return selected;+}++function selectMultipleTopics(topic: Topic, selected: NotebookReference[]) {+ const index = findSelectionIndex(topic, selected);+ const isSelected = index > -1;+ const item = selected[index];++ if (isSelected) {+ // we remove new topics & toggle old ones+ if (item.new) selected.splice(index, 1);+ else item.op = item.op === "add" ? "remove" : "add";+ } else {+ selected.push(createSelection(topic));+ }++ return selected;+}++function selectSingleTopic(topic: Topic, array: NotebookReference[]) {+ const selected: NotebookReference[] = array.filter((ref) => !ref.new);++ const index = findSelectionIndex(topic, array);+ const item = array[index];+ const isSelected = index > -1;++ if (isSelected && !item.new) {+ item.op = item.op === "add" ? "remove" : "add";+ } else if (!isSelected) {+ selected.forEach((a) => (a.op = "remove"));+ selected.push(createSelection(topic));+ }++ return selected;+}++function isNotebookSelected(notebook: Notebook, selected: NotebookReference[]) {+ const selectedTopics = notebook.topics.filter((topic) => {+ const index = findSelectionIndex(topic, selected);+ return selected[index]?.op === "add";+ });++ return !selectedTopics.length+ ? false+ : selectedTopics.length === notebook.topics.length+ ? true+ : null;+}++function stringifySelected(suggestion: NotebookReference[]) {+ const added = suggestion+ .filter((a) => a.op === "add")+ .map(resolve)+ .filter(Boolean);+ const removed = suggestion+ .filter((a) => a.op === "remove")+ .map(resolve)+ .filter(Boolean);+ if (!added.length && !removed.length) return;++ const parts = ["Add to"];+ if (added.length >= 1) parts.push(added[0]);+ if (added.length > 1) parts.push(`and ${added.length - 1} others`);++ if (removed.length >= 1) {+ parts.push("remove from");+ parts.push(added[0]);+ }+ if (removed.length > 1) parts.push(`and ${removed.length - 1} others`);++ return parts.join(" ");+}++function resolve(ref: NotebookReference) {+ const topic = db.notebooks?.notebook(ref.id)?.topics.topic(ref.topic);+ if (!topic) return undefined;+ return topic._topic.title;}diff --git a/apps/web/src/utils/platform.js b/apps/web/src/utils/platform.jsindex ffaf786de..670acc920 100644--- a/apps/web/src/utils/platform.js+++ b/apps/web/src/utils/platform.js@@ -126,6 +126,10 @@ export function isDesktop() {return "api" in window;}+export function isMac() {+ return getPlatform() === "macOS" || window.os === "darwin" || isMacStoreApp();+}+export function isMacStoreApp() {return window.os === "mas";}diff --git a/packages/core/models/topic.js b/packages/core/models/topic.jsindex 550b90982..e5b90e305 100644--- a/packages/core/models/topic.js+++ b/packages/core/models/topic.js@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.export default class Topic {/**- * @param {Object} topic+ * @param {any} topic* @param {string} notebookId* @param {import('../api').default} db*/