global: move item resolution logic to @notesnook/common

This commit is contained in:
Abdullah Atta
2024-02-05 12:13:42 +05:00
parent d3221abd7e
commit ef2d8bf5af
27 changed files with 188 additions and 288 deletions

View File

@@ -30,7 +30,7 @@ import { useMenuTrigger } from "../../hooks/use-menu";
import { MenuItem } from "@notesnook/ui";
import { navigate } from "../../navigation";
import { Tag } from "@notesnook/core";
import usePromise from "../../hooks/use-promise";
import { usePromise } from "@notesnook/common";
type HeaderProps = { readonly: boolean };
function Header(props: HeaderProps) {

View File

@@ -59,6 +59,7 @@ export function FilteredList<T>(props: FilteredListProps<T>) {
inputRef={inputRef}
data-test-id={"filter-input"}
autoFocus
sx={{ m: 0 }}
placeholder={
items.length <= 0 ? placeholders.empty : placeholders.filter
}
@@ -84,7 +85,9 @@ export function FilteredList<T>(props: FilteredListProps<T>) {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
py: 2
py: 2,
width: "100%",
mt: 1
}}
onClick={async () => {
await _createNewItem(query);

View File

@@ -31,13 +31,7 @@ import { ListLoader } from "../loaders/list-loader";
import ScrollContainer from "../scroll-container";
import { useKeyboardListNavigation } from "../../hooks/use-keyboard-list-navigation";
import { Context } from "./types";
import {
VirtualizedGrouping,
GroupingKey,
Item,
isGroupHeader
} from "@notesnook/core";
import { useResolvedItem } from "./resolved-item";
import { VirtualizedGrouping, GroupingKey, Item } from "@notesnook/core";
import {
ItemProps,
ScrollerProps,
@@ -45,6 +39,7 @@ import {
VirtuosoHandle
} from "react-virtuoso";
import Skeleton from "react-loading-skeleton";
import { useResolvedItem } from "@notesnook/common";
export const CustomScrollbarsVirtualList = forwardRef<
HTMLDivElement,

View File

@@ -26,8 +26,8 @@ import Reminder from "../reminder";
import { Context } from "./types";
import { getSortValue } from "@notesnook/core/dist/utils/grouping";
import { GroupingKey, Item } from "@notesnook/core";
import { isNoteResolvedData } from "@notesnook/common";
import { Attachment } from "../attachment";
import { isNoteResolvedData } from "./resolved-item";
const SINGLE_LINE_HEIGHT = 1.4;
const DEFAULT_LINE_HEIGHT =

View File

@@ -1,202 +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 {
Color,
Item,
ItemMap,
ItemType,
Reminder,
VirtualizedGrouping
} from "@notesnook/core";
import usePromise from "../../hooks/use-promise";
import {
NotebooksWithDateEdited,
TagsWithDateEdited,
WithDateEdited
} from "./types";
import { db } from "../../common/db";
import React from "react";
type ResolvedItemProps<TItemType extends ItemType> = {
type: TItemType;
items: VirtualizedGrouping<ItemMap[TItemType]>;
index: number;
children: (item: {
item: ItemMap[TItemType];
data: unknown;
}) => React.ReactNode;
};
export function ResolvedItem<TItemType extends ItemType>(
props: ResolvedItemProps<TItemType>
) {
const { index, items, children, type } = props;
const result = usePromise(
() => items.item(index, resolveItems),
[index, items]
);
if (result.status === "rejected" || !result.value) return null;
if (result.value.item.type !== type) return null;
return <>{children(result.value)}</>;
}
export function useResolvedItem(
props: Omit<ResolvedItemProps<ItemType>, "children" | "type">
) {
const { index, items } = props;
const result = usePromise(
() => items.item(index, resolveItems),
[index, items]
);
if (result.status === "rejected" || !result.value) return null;
return result.value;
}
function withDateEdited<
T extends { dateEdited: number } | { dateModified: number }
>(items: T[]): WithDateEdited<T> {
let latestDateEdited = 0;
items.forEach((item) => {
const date = "dateEdited" in item ? item.dateEdited : item.dateModified;
if (latestDateEdited < date) latestDateEdited = date;
});
return { dateEdited: latestDateEdited, items };
}
export async function resolveItems(ids: string[], items: Item[]) {
if (!ids.length || !items.length) return [];
const { type } = items[0];
if (type === "note") return resolveNotes(ids);
else if (type === "notebook") {
return Promise.all(ids.map((id) => db.notebooks.totalNotes(id)));
} else if (type === "tag") {
return Promise.all(
ids.map((id) => db.relations.from({ id, type: "tag" }, "note").count())
);
}
return [];
}
type NoteResolvedData = {
notebooks?: NotebooksWithDateEdited;
reminder?: Reminder;
color?: Color;
tags?: TagsWithDateEdited;
};
async function resolveNotes(ids: string[]) {
console.time("relations");
const relations = [
...(await db.relations
.to({ type: "note", ids }, ["notebook", "tag", "color"])
.get()),
...(await db.relations.from({ type: "note", ids }, "reminder").get())
];
console.timeEnd("relations");
const relationIds: {
notebooks: Set<string>;
colors: Set<string>;
tags: Set<string>;
reminders: Set<string>;
} = {
colors: new Set(),
notebooks: new Set(),
tags: new Set(),
reminders: new Set()
};
const grouped: Record<
string,
{
notebooks: string[];
color?: string;
tags: string[];
reminder?: string;
}
> = {};
for (const relation of relations) {
const noteId =
relation.toType === "reminder" ? relation.fromId : relation.toId;
const data = grouped[noteId] || {
notebooks: [],
tags: []
};
if (relation.toType === "reminder" && !data.reminder) {
data.reminder = relation.toId;
relationIds.reminders.add(relation.toId);
} else if (relation.fromType === "notebook" && data.notebooks.length < 2) {
data.notebooks.push(relation.fromId);
relationIds.notebooks.add(relation.fromId);
} else if (relation.fromType === "tag" && data.tags.length < 3) {
data.tags.push(relation.fromId);
relationIds.tags.add(relation.fromId);
} else if (relation.fromType === "color" && !data.color) {
data.color = relation.fromId;
relationIds.colors.add(relation.fromId);
}
grouped[noteId] = data;
}
console.time("resolve");
const resolved = {
notebooks: await db.notebooks.all.records(
Array.from(relationIds.notebooks)
),
tags: await db.tags.all.records(Array.from(relationIds.tags)),
colors: await db.colors.all.records(Array.from(relationIds.colors)),
reminders: await db.reminders.all.records(Array.from(relationIds.reminders))
};
console.timeEnd("resolve");
const data: NoteResolvedData[] = [];
for (const noteId of ids) {
const group = grouped[noteId];
if (!group) {
data.push({});
continue;
}
data.push({
color: group.color ? resolved.colors[group.color] : undefined,
reminder: group.reminder ? resolved.reminders[group.reminder] : undefined,
tags: withDateEdited(
group.tags.map((id) => resolved.tags[id]).filter(Boolean)
),
notebooks: withDateEdited(
group.notebooks.map((id) => resolved.notebooks[id]).filter(Boolean)
)
});
}
return data;
}
export function isNoteResolvedData(data: unknown): data is NoteResolvedData {
return (
typeof data === "object" &&
!!data &&
"notebooks" in data &&
"reminder" in data &&
"color" in data &&
"tags" in data
);
}

View File

@@ -76,9 +76,12 @@ import {
isReminderActive,
isReminderToday
} from "@notesnook/core/dist/collections/reminders";
import { getFormattedReminderTime, pluralize } from "@notesnook/common";
import {
Reminder as ReminderType,
NoteResolvedData,
getFormattedReminderTime,
pluralize
} from "@notesnook/common";
import {
Color,
Note,
Notebook as NotebookItem,
@@ -86,22 +89,14 @@ import {
DefaultColors
} from "@notesnook/core";
import { MenuItem } from "@notesnook/ui";
import {
Context,
NotebooksWithDateEdited,
TagsWithDateEdited
} from "../list-container/types";
import { Context } from "../list-container/types";
import { SchemeColors } from "@notesnook/theme";
import FileSaver from "file-saver";
type NoteProps = {
tags?: TagsWithDateEdited;
color?: Color;
notebooks?: NotebooksWithDateEdited;
type NoteProps = NoteResolvedData & {
item: Note;
context?: Context;
date: number;
reminder?: ReminderType;
simplified?: boolean;
compact?: boolean;
};
@@ -111,6 +106,7 @@ function Note(props: NoteProps) {
tags,
color,
notebooks,
attachments,
item,
date,
reminder,
@@ -121,17 +117,6 @@ function Note(props: NoteProps) {
const note = item;
const isOpened = useStore((store) => store.selectedNote === note.id);
const attachments = [];
// useAttachmentStore((store) =>
// store.attachments.filter((a) => a.noteIds.includes(note.id))
// );
const failed = [];
// useMemo(
// () => attachments.filter((a) => a.failed),
// [attachments]
// );
const primary: SchemeColors = color ? color.colorCode : "accent-selected";
return (
@@ -226,21 +211,21 @@ function Note(props: NoteProps) {
datetime={date}
/>
{attachments.length > 0 && (
{attachments?.total ? (
<Flex sx={{ alignItems: "center", justifyContent: "center" }}>
<Attachment size={13} />
<Text variant="subBody" ml={"2px"}>
{attachments.length}
{attachments.total}
</Text>
</Flex>
)}
) : null}
{failed.length > 0 && (
<Flex title={`Errors in ${failed.length} attachments.`}>
{attachments?.failed ? (
<Flex title={`Errors in ${attachments.failed} attachments.`}>
<AttachmentError size={13} color="var(--icon-error)" />
<Text ml={"2px"}>{failed.length}</Text>
<Text ml={"2px"}>{attachments.failed}</Text>
</Flex>
)}
) : null}
{note.pinned && !props.context && (
<Pin size={13} color={primary} />
@@ -289,7 +274,8 @@ export default React.memo(Note, function (prevProps, nextProps) {
prevItem.dateModified === nextItem.dateModified &&
prevProps.notebooks?.dateEdited === nextProps.notebooks?.dateEdited &&
prevProps.tags?.dateEdited === nextProps.tags?.dateEdited &&
prevProps.reminder?.dateModified === nextProps.reminder?.dateModified
prevProps.reminder?.dateModified === nextProps.reminder?.dateModified &&
prevProps.attachments === nextProps.attachments
);
});

View File

@@ -36,13 +36,11 @@ import { store as noteStore } from "../../stores/note-store";
import { AnimatedFlex } from "../animated";
import Toggle from "./toggle";
import ScrollContainer from "../scroll-container";
import { getFormattedDate } from "@notesnook/common";
import { ResolvedItem, getFormattedDate, usePromise } from "@notesnook/common";
import { ScopedThemeProvider } from "../theme-provider";
import { PreviewSession } from "../editor/types";
import usePromise from "../../hooks/use-promise";
import { ListItemWrapper } from "../list-container/list-profiles";
import { VirtualizedList } from "../virtualized-list";
import { ResolvedItem } from "../list-container/resolved-item";
import { SessionItem } from "../session-item";
import { COLORS } from "../../common/constants";
import { DefaultColors } from "@notesnook/core";

View File

@@ -23,8 +23,7 @@ import { ArrowLeft, Menu, Search, Plus, Close } from "../icons";
import { useStore } from "../../stores/app-store";
import { useStore as useSearchStore } from "../../stores/search-store";
import useMobile from "../../hooks/use-mobile";
import usePromise from "../../hooks/use-promise";
import { debounce } from "@notesnook/common";
import { debounce, usePromise } from "@notesnook/common";
import Field from "../field";
export type RouteContainerButtons = {

View File

@@ -26,7 +26,7 @@ import { useStore as useAppStore } from "../../stores/app-store";
import Field from "../field";
import { showToast } from "../../utils/toast";
import { ErrorText } from "../error-text";
import usePromise from "../../hooks/use-promise";
import { usePromise } from "@notesnook/common";
type UnlockProps = {
noteId: string;

View File

@@ -32,9 +32,9 @@ import { store as editorStore } from "../stores/editor-store";
import { Perform } from "../common/dialog-controller";
import { FilteredList } from "../components/filtered-list";
import { ItemReference, Tag } from "@notesnook/core/dist/types";
import { ResolvedItem } from "../components/list-container/resolved-item";
import { create } from "zustand";
import { VirtualizedGrouping } from "@notesnook/core";
import { ResolvedItem } from "@notesnook/common";
type SelectedReference = {
id: string;
@@ -134,6 +134,8 @@ function AddTagsDialog(props: AddTagsDialogProps) {
onCreateNewItem={async (title) => {
const tagId = await db.tags.add({ title });
if (!tagId) return;
await useStore.getState().refresh();
setTags(useStore.getState().tags);
const { selected, setSelected } = useSelectionStore.getState();
setSelected([...selected, { id: tagId, new: true, op: "add" }]);
}}

View File

@@ -29,7 +29,7 @@ import {
Text
} from "@theme-ui/components";
import { store, useStore } from "../stores/attachment-store";
import { formatBytes } from "@notesnook/common";
import { ResolvedItem, formatBytes, usePromise } from "@notesnook/common";
import Dialog from "../components/dialog";
import {
ChevronDown,
@@ -57,13 +57,11 @@ import {
VirtualizedGrouping
} from "@notesnook/core";
import { Multiselect } from "../common/multi-select";
import { ResolvedItem } from "../components/list-container/resolved-item";
import {
VirtualizedTable,
VirtualizedTableRowProps
} from "../components/virtualized-table";
import { FlexScrollContainer } from "../components/scroll-container";
import usePromise from "../hooks/use-promise";
type ToolbarAction = {
title: string;

View File

@@ -46,8 +46,7 @@ import {
TreeEnvironmentRef
} from "react-complex-tree";
import { FlexScrollContainer } from "../components/scroll-container";
import { pluralize } from "@notesnook/common";
import usePromise from "../hooks/use-promise";
import { pluralize, usePromise } from "@notesnook/common";
type MoveDialogProps = { onClose: Perform; noteIds: string[] };
type NotebookReference = {

View File

@@ -25,8 +25,7 @@ import { Reminder } from "@notesnook/core/dist/types";
import IconTag from "../components/icon-tag";
import { Clock, Refresh } from "../components/icons";
import Note from "../components/note";
import { getFormattedReminderTime } from "@notesnook/common";
import usePromise from "../hooks/use-promise";
import { getFormattedReminderTime, usePromise } from "@notesnook/common";
export type ReminderPreviewDialogProps = {
onClose: Perform;

View File

@@ -1,89 +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 { DependencyList, useEffect, useState } from "react";
export type PromiseResult<T> =
| PromisePendingResult<T>
| (PromiseSettledResult<T> & { refresh: () => void });
export interface PromisePendingResult<T> {
status: "pending";
value?: T;
}
/**
* Function that creates a promise, takes a signal to abort fetch requests.
*/
export type PromiseFactoryFn<T> = (signal: AbortSignal) => T | Promise<T>;
/**
* Takes a function that creates a Promise and returns its pending, fulfilled, or rejected result.
*
* ```ts
* const result = usePromise(() => fetch('/api/products'))
* ```
*
* Also takes a list of dependencies, when the dependencies change the promise is recreated.
*
* ```ts
* const result = usePromise(() => fetch(`/api/products/${id}`), [id])
* ```
*
* Can abort a fetch request, a [signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) is provided from the factory function to do so.
*
* ```ts
* const result = usePromise(signal => fetch(`/api/products/${id}`, { signal }), [id])
* ```
*
* @param factory Function that creates the promise.
* @param deps If present, promise will be recreated if the values in the list change.
*/
export default function usePromise<T>(
factory: PromiseFactoryFn<T>,
deps: DependencyList = []
): PromiseResult<T> {
const [result, setResult] = useState<PromiseResult<T>>({ status: "pending" });
useEffect(function effect() {
if (result.status !== "pending") {
setResult((s) => ({
...s,
status: "pending"
}));
}
const controller = new AbortController();
const { signal } = controller;
async function handlePromise() {
const [promiseResult] = await Promise.allSettled([factory(signal)]);
if (!signal.aborted) {
setResult({ ...promiseResult, refresh: effect });
}
}
handlePromise();
return () => controller.abort();
}, deps);
return result;
}