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
feat: make toolbar configurable
thecodrr03b8e56f6cde
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 18fe9a35f..0b0555c48 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -8,6 +8,9 @@"repository": "https://github.com/streetwriters/notesnook","dependencies": {"@brixtol/currency-symbols": "^1.1.1",+ "@dnd-kit/core": "^6.0.5",+ "@dnd-kit/modifiers": "^6.0.0",+ "@dnd-kit/sortable": "^7.0.1","@mdi/js": "^6.5.95","@mdi/react": "^1.4.0","@notesnook/crypto": "^1.0.0",diff --git a/apps/web/src/common/dialog-controller.tsx b/apps/web/src/common/dialog-controller.tsxindex 975c7afc0..4b113b9cb 100644--- a/apps/web/src/common/dialog-controller.tsx+++ b/apps/web/src/common/dialog-controller.tsx@@ -167,6 +167,13 @@ export function showPromptDialog(props: {));}+export function showToolbarConfigDialog() {+ return showDialog<"ToolbarConfigDialog", string | null>(+ "ToolbarConfigDialog",+ (Dialog, perform) => <Dialog onClose={() => perform(null)} />+ );+}+export function showError(title: string, message: string) {return confirm({ title, message, yesText: "Okay" });}diff --git a/apps/web/src/common/toolbar-config.ts b/apps/web/src/common/toolbar-config.tsnew file mode 100644index 000000000..470ee55b9--- /dev/null+++ b/apps/web/src/common/toolbar-config.ts@@ -0,0 +1,52 @@+import { DEFAULT_TOOLS } from "notesnook-editor";+import { ToolbarGroupDefinition } from "notesnook-editor/dist/toolbar/types";+import { db } from "./db";++export type PresetId = "default" | "minimal" | "custom";+export type Preset = {+ id: PresetId;+ title: string;+ tools: ToolbarGroupDefinition[];+};+const presets: Record<PresetId, Preset> = {+ default: { id: "default", title: "Default", tools: DEFAULT_TOOLS.slice(1) },+ minimal: {+ id: "minimal",+ title: "Minimal",+ tools: [+ [+ "bold",+ "italic",+ "underline",+ "strikethrough",+ "code",+ "highlight",+ "textColor",+ ],+ ],+ },+ custom: { id: "custom", title: "Custom", tools: [] },+};++export function getCurrentPreset() {+ const preset = db.settings?.getToolbarConfig("desktop");+ if (!preset) return presets.default;+ switch (preset.preset as PresetId) {+ case "custom":+ presets.custom.tools = preset.config;+ return presets.custom;+ case "minimal":+ return presets.minimal;+ default:+ case "default":+ return presets.default;+ }+}++export function getAllPresets() {+ return Object.values(presets);+}++export function getPreset(id: PresetId) {+ return presets[id];+}diff --git a/apps/web/src/components/dialogs/index.js b/apps/web/src/components/dialogs/index.jsindex c0f402be7..553648511 100644--- a/apps/web/src/components/dialogs/index.js+++ b/apps/web/src/components/dialogs/index.js@@ -18,9 +18,11 @@ import { MultifactorDialog, RecoveryCodesDialog } from "./multi-factor-dialog";import OnboardingDialog from "./onboarding-dialog";import AttachmentsDialog from "./attachmentsdialog";import { Prompt } from "./prompt";+import { ToolbarConfigDialog } from "./toolbarconfigdialog";const Dialogs = {AddNotebookDialog,+ ToolbarConfigDialog,TrackingDetailsDialog,BuyDialog,Confirm,diff --git a/apps/web/src/components/dialogs/toolbar-config-dialog.tsx b/apps/web/src/components/dialogs/toolbar-config-dialog.tsxnew file mode 100644index 000000000..eac4ab68d--- /dev/null+++ b/apps/web/src/components/dialogs/toolbar-config-dialog.tsx@@ -0,0 +1,571 @@+import { Button, Flex, FlexProps, Text } from "rebass";+import { Perform } from "../../common/dialog-controller";+import Dialog from "./dialog";+import { DEFAULT_TOOLS, getToolDefinition } from "notesnook-editor";+import { ToolbarGroupDefinition } from "notesnook-editor/dist/toolbar/types";+import { Icons } from "notesnook-editor/dist/toolbar/icons";+import { Icon } from "notesnook-editor/dist/toolbar/components/icon";+import {+ closestCenter,+ DndContext,+ useSensor,+ useSensors,+ KeyboardSensor,+ PointerSensor,+ DragOverlay,+ MeasuringStrategy,+} from "@dnd-kit/core";+import {+ arrayMove,+ SortableContext,+ sortableKeyboardCoordinates,+ useSortable,+ verticalListSortingStrategy,+} from "@dnd-kit/sortable";+import { useEffect, useState } from "react";+import { CSS } from "@dnd-kit/utilities";+import { createPortal } from "react-dom";+import id from "notes-core/utils/id";+import { Label, Radio } from "@rebass/forms";+import { db } from "../../common/db";+import { useToolbarConfig } from "../editor/context";+import {+ getAllPresets,+ getCurrentPreset,+ getPreset,+ Preset,+ PresetId,+} from "../../common/toolbar-config";++export type ToolbarConfigDialogProps = {+ onClose: Perform;+};++const ReactModalContent = document.querySelector(".ReactModal__Overlay");++export function ToolbarConfigDialog(props: ToolbarConfigDialogProps) {+ const sensors = useSensors(+ useSensor(PointerSensor),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ })+ );+ const [items, setItems] = useState<TreeNode[]>([]);+ const [activeItem, setActiveItem] = useState<TreeNode>();+ const [currentPreset, setCurrentPreset] = useState<Preset>(+ getCurrentPreset()+ );+ const { setToolbarConfig } = useToolbarConfig();++ useEffect(() => {+ const items = flatten(currentPreset.tools);+ items.push(createTrash());+ setItems(items);+ }, [currentPreset]);++ return (+ <Dialog+ isOpen={true}+ title={"Configure toolbar"}+ description={"Customize the editor toolbar to fit your needs."}+ width={500}+ onClose={props.onClose}+ positiveButton={{+ text: "Save",+ onClick: async () => {+ const tools = [+ DEFAULT_TOOLS[0],+ ...unflatten(items.slice(0, items.length - 1)),+ ];++ await db.settings?.setToolbarConfig("desktop", {+ preset: currentPreset.id,+ config: currentPreset.id === "custom" ? tools : undefined,+ });++ setToolbarConfig(tools);+ props.onClose(true);+ },+ }}+ negativeButton={{ text: "Cancel", onClick: props.onClose }}+ >+ <Flex sx={{ p: 1 }}>+ {getAllPresets().map((preset) => (+ <Label variant="text.body" sx={{ alignItems: "center" }}>+ <Radio+ id={preset.id.toString()}+ name="preset"+ value={preset.id}+ checked={preset.id === currentPreset.id}+ onChange={(e) => {+ const { value } = e.target;+ setCurrentPreset(getPreset(value as PresetId));+ }}+ />+ {preset.title}+ </Label>+ ))}+ </Flex>+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragStart={(event) => {+ if (currentPreset.id !== "custom") {+ setCurrentPreset((c) => ({+ ...getPreset("custom"),+ tools: c.tools,+ }));+ }++ const { active } = event;+ const activeItem = items.find((item) => item.id === active.id);+ setActiveItem(activeItem);+ }}+ onDragEnd={(event) => {+ const { active, over } = event;+ if (activeItem && over && active.id !== over.id) {+ // const newIndex = items.findIndex((i) => i.id === over.id);+ if (isGroup(activeItem) || isSubgroup(activeItem)) {+ setItems(moveGroup(items, activeItem.id, over.id as string));+ } else {+ setItems(moveItem(items, activeItem.id, over.id as string));+ }++ setTimeout(() => {+ const element = document.getElementById(over.id as string);+ element?.scrollIntoView({ behavior: "auto", block: "nearest" });+ }, 500);+ }+ setActiveItem(undefined);+ }}+ measuring={{+ droppable: { strategy: MeasuringStrategy.Always },+ }}+ >+ <SortableContext items={items} strategy={verticalListSortingStrategy}>+ {items?.map((item, index) => {+ const deleted = isDeleted(items, item);+ return (+ <TreeNodeComponent+ key={item.id}+ item={item}+ activeItem={activeItem}+ onRemoveGroup={+ deleted+ ? undefined+ : (group) => {+ setItems(removeGroup(items, group.id));+ }+ }+ onRemoveItem={+ deleted+ ? undefined+ : (item) => {+ setItems(removeItem(items, item.id));+ }+ }+ />+ );+ })}+ {activeItem &&+ createPortal(+ <DragOverlay+ // dropAnimation={dropAnimationConfig}+ // modifiers={indicator ? [adjustTranslate] : undefined}+ >+ <TreeNodeComponent overlay item={activeItem} />+ </DragOverlay>,+ ReactModalContent || document.body+ )}+ </SortableContext>+ </DndContext>+ </Dialog>+ );+}++type TreeNodeComponentProps = {+ item: TreeNode;+ activeItem?: TreeNode;+ overlay?: boolean;+ onRemoveGroup?: (item: TreeNode) => void;+ onRemoveItem?: (item: TreeNode) => void;+};+function TreeNodeComponent(props: TreeNodeComponentProps) {+ const { item, activeItem, onRemoveGroup, onRemoveItem } = props;+ if (activeItem && isCollapsed(item, activeItem)) return null;+ const isDraggable = !isTrash(item);++ if (isGroup(item) || isSubgroup(item)) {+ return (+ <SortableWrapper+ {...props}+ draggable={isDraggable}+ onRemove={onRemoveGroup}+ sx={{+ bg: "background",+ border: "1px solid var(--border)",+ borderRadius: "default",+ p: 1,+ my: 1,+ ml: item.depth * 15,+ alignItems: "center",+ }}+ >+ {isDraggable ? (+ <Icon path={Icons.dragHandle} size={18} color="icon" />+ ) : null}+ <Text variant={"body"} sx={{ ml: 1 }}>+ {item.title}+ </Text>+ </SortableWrapper>+ );+ }++ return (+ <SortableWrapper+ {...props}+ draggable={isDraggable}+ onRemove={onRemoveItem}+ sx={{+ p: 1,+ alignItems: "center",+ justifyContent: "space-between",+ bg: "bgSecondary",+ borderRadius: "default",+ mb: 1,+ ml: item.depth * 15,+ ":last-of-type": { mb: 0 },+ }}+ >+ {item.icon && (+ <Icon path={(Icons as any)[item.icon]} size={16} color="icon" />+ )}+ <Text variant={"body"} sx={{ ml: 1 }}>+ {item.title}+ </Text>+ </SortableWrapper>+ );+}++type SortableWrapperProps = TreeNodeComponentProps &+ FlexProps & { onRemove?: (item: TreeNode) => void };++function SortableWrapper(props: SortableWrapperProps) {+ const {+ item,+ activeItem,+ overlay,+ sx,+ children,+ draggable,+ onRemove,+ ...flexProps+ } = props;+ const { attributes, listeners, setNodeRef, transform, transition } =+ useSortable({ id: item.id });+ const visibility =+ !overlay && item.id === activeItem?.id ? "hidden" : "visible";++ return (+ <Flex+ {...flexProps}+ id={overlay ? `overlay-${item.id}` : item.id}+ ref={setNodeRef}+ sx={{+ pointerEvents: draggable ? "all" : "none",+ cursor: overlay ? "grabbing" : draggable ? "grab" : "unset",+ visibility,+ transform: CSS.Transform.toString(transform),+ transition,+ justifyContent: "space-between",+ ":hover #remove-item": { opacity: 1 },+ ...sx,+ }}+ >+ <Flex+ {...listeners}+ {...attributes}+ sx={{ alignItems: "center", flex: 1 }}+ >+ {children}+ </Flex>+ {onRemove && (+ <Button+ id="remove-item"+ variant={"tool"}+ sx={{ p: "small", opacity: 0 }}+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ onRemove(item);+ }}+ >+ <Icon path={Icons.delete} size={16} color="icon" />+ </Button>+ )}+ </Flex>+ );+}++type TreeNodeType = "group" | "item";+type BaseTreeNode<Type extends TreeNodeType> = {+ type: Type;+ id: string;+ title: string;+ depth: number;+};++type Subgroup = BaseTreeNode<"group"> & {+ collapsed?: boolean;+};++type Group = BaseTreeNode<"group">;++type Item = BaseTreeNode<"item"> & {+ toolId: string;+ icon: string;+ collapsed?: boolean;+};++type TreeNode = Group | Item | Subgroup;++function flatten(+ tools: ToolbarGroupDefinition[],+ depth: number = 0+): TreeNode[] {+ let nodes: TreeNode[] = [];+ let groupCount = 1;+ for (const tool of tools) {+ if (Array.isArray(tool)) {+ const isSubgroup = depth > 0;+ const groupTitle = `${isSubgroup ? "Subgroup" : "Group"} ${groupCount}`;++ nodes.push(createGroup({ depth, title: groupTitle }));+ nodes.push(...flatten(tool as ToolbarGroupDefinition[], depth + 1));+ ++groupCount;+ } else {+ const { icon, title } = getToolDefinition(tool as any);+ nodes.push(createItem({ toolId: tool, depth, title, icon }));+ }+ }+ return nodes;+}++function unflatten(items: TreeNode[]): ToolbarGroupDefinition[] {+ let tools: ToolbarGroupDefinition[] = [];+ for (let i = 0; i < items.length; i++) {+ const item = items[i];+ if (isGroup(item) || isSubgroup(item)) {+ const group = getGroup(items, item.id);+ console.log(group?.items);+ if (!group) continue;+ tools.push(unflatten(group.items.slice(1)) as any);++ // skip all the group's items+ i += group.items.length - 1;+ } else {+ tools.push(item.toolId as any);+ }+ }+ return tools;+}++function createGroup(config: Partial<Group>): Group {+ return {+ type: "group",+ id: id(),+ depth: 0,+ title: "Group",+ ...config,+ };+}++function createItem(config: Partial<Item>): Item {+ return {+ type: "item",+ id: id(),+ depth: 0,+ title: "",+ icon: "",+ toolId: "",+ ...config,+ };+}++function createTrash() {+ return createGroup({+ id: "trash",+ depth: 0,+ title: "Disabled items",+ });+}++function moveGroup(+ items: TreeNode[],+ fromId: string,+ toId: string+): TreeNode[] {+ const newArray = items.slice();+ const fromGroup = getGroup(items, fromId);+ const toGroup = getGroup(items, toId);++ if (!fromGroup || !toGroup || !canMoveGroup(fromGroup, toGroup)) return items;++ newArray.splice(fromGroup.index, fromGroup.items.length);+ const newIndex =+ // if we are moving the group upwards+ fromGroup.index > toGroup.index+ ? toGroup.index+ : toGroup.index + toGroup.items.length - fromGroup.items.length;++ newArray.splice(+ newIndex,+ 0,+ ...fromGroup.items.map((item) => {+ if (item.depth) item.depth = toGroup.item.depth + 1;+ return item;+ })+ );+ return newArray;+}++function canMoveGroup(+ fromGroup: ResolvedGroup,+ toGroup: ResolvedGroup+): boolean {+ const hasOtherGroups =+ toGroup.items.filter((item) => isGroup(item) || isSubgroup(item)).length >+ 1;++ // 1 group can contain only 1 subgroup+ if (isSubgroup(fromGroup.item) && hasOtherGroups) return false;++ return true;+}++function moveItem(items: TreeNode[], fromId: string, toId: string): TreeNode[] {+ const fromIndex = items.findIndex((i) => i.id === fromId);+ const toIndex = items.findIndex((i) => i.id === toId);++ const fromItem = items[fromIndex];+ const toItem = items[toIndex];++ if (!fromItem || !isItem(fromItem)) return items;++ const movingToGroup = isGroup(toItem) || isSubgroup(toItem);++ // we need to adjust the item depth according to where the item+ // is going to be moved.+ if (fromItem.depth !== toItem.depth) fromItem.depth = toItem.depth;++ // if we are moving to the start of the group, we need to adjust the+ // depth accordingly.+ if (movingToGroup) fromItem.depth = toItem.depth + 1;++ return arrayMove(items, fromIndex, toIndex);+}++function removeGroup(items: TreeNode[], groupId: string): TreeNode[] {+ const newArray = items.slice();+ const fromGroup = getGroup(items, groupId);+ const toGroup = getGroup(items, "trash");++ if (!fromGroup || !toGroup) return items;++ newArray.splice(fromGroup.index, fromGroup.items.length);+ const newIndex =+ // if we are moving the group upwards+ fromGroup.index > toGroup.index+ ? toGroup.index+ : toGroup.index + toGroup.items.length - fromGroup.items.length;++ newArray.splice(+ newIndex,+ 0,+ ...fromGroup.items+ .filter((item) => isItem(item))+ .map((item) => {+ item.depth = toGroup.item.depth + 1;+ return item;+ })+ );+ return newArray;+}++function removeItem(items: TreeNode[], itemId: string): TreeNode[] {+ const toGroup = getGroup(items, "trash");+ if (!toGroup) return items;++ return moveItem(+ items,+ itemId,+ toGroup.items.length > 0+ ? toGroup.items[toGroup.items.length - 1].id+ : toGroup.item.id+ );+}++function isCollapsed(item: TreeNode, activeItem: TreeNode): boolean {+ // if a group is selected, we collapse everything else.+ if (isGroup(activeItem) && (isSubgroup(item) || isItem(item))) {+ return true;+ }++ // if a subgroup is selected, we collapse only the items.+ if (isSubgroup(activeItem) && isItem(item)) return true;++ return false;+}++function isSubgroup(item: TreeNode): item is Subgroup {+ return item.type === "group" && item.depth > 0;+}++function isGroup(item: TreeNode): item is Group {+ return item.type === "group" && item.depth === 0;+}++function isItem(item: TreeNode): item is Item {+ return item.type === "item";+}++function isTrash(item: TreeNode): boolean {+ return item.id === "trash";+}++function isDeleted(items: TreeNode[], item: TreeNode): boolean {+ const group = getItemGroup(items, item);+ return group.id === "trash";+}++function getItemGroup(items: TreeNode[], item: TreeNode) {+ const index = items.findIndex((i) => i.id === item.id);+ for (let i = index; i >= 0; --i) {+ const item = items[i];+ if (isGroup(item) || isSubgroup(item)) return item;+ }+ return items[0];+}++type ResolvedGroup = {+ index: number;+ item: Group;+ items: TreeNode[];+};+function getGroup(items: TreeNode[], groupId: string): ResolvedGroup | null {+ const index = items.findIndex((item) => item.id === groupId);+ const group = items[index];+ if (!isGroup(group) && !isSubgroup(group)) return null;++ const nextGroupIndex = items.findIndex(+ (item, i) => i > index && (item.depth === 0 || item.depth < group.depth)+ );+ return {+ index,+ item: group,+ items: items.slice(+ index,+ nextGroupIndex < 0 ? items.length : nextGroupIndex+ ),+ };+}diff --git a/apps/web/src/components/editor/context.ts b/apps/web/src/components/editor/context.tsindex 497902749..1c58d4ad4 100644--- a/apps/web/src/components/editor/context.ts+++ b/apps/web/src/components/editor/context.ts@@ -4,12 +4,14 @@ import createStore from "../../common/store";import BaseStore from "../../stores";import { UseStore } from "zustand";import shallow from "zustand/shallow";+import { ToolbarDefinition } from "notesnook-editor/dist/toolbar/types";type EditorSubState = {editor?: IEditor;canUndo?: boolean;canRedo?: boolean;searching?: boolean;+ toolbarConfig?: ToolbarDefinition;};class EditorContext extends BaseStore {subState: EditorSubState = {};@@ -57,12 +59,14 @@ export function useSearch() {return { isSearching, toggleSearch };}-// const EditorInstanceContext = React.createContext<IEditor | undefined>(-// undefined-// );--// export const EditorInstanceProvider = EditorInstanceContext.Provider;--// export function useEditorInstance() {-// return useContext(EditorInstanceContext);-// }+export function useToolbarConfig() {+ const toolbarConfig = useEditorContext(+ (store) => store.subState.toolbarConfig+ );+ const configure = useEditorContext((store) => store.configure);+ const setToolbarConfig = useCallback(+ (config: ToolbarDefinition) => configure({ toolbarConfig: config }),+ [configure]+ );+ return { toolbarConfig, setToolbarConfig };+}diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsxindex 9fa61ce85..ccfca5506 100644--- a/apps/web/src/components/editor/tiptap.tsx+++ b/apps/web/src/components/editor/tiptap.tsx@@ -7,9 +7,10 @@ import { PropsWithChildren, useEffect, useRef } from "react";import useMobile from "../../utils/use-mobile";import { Attachment } from "./plugins/picker";import { CharacterCounter, IEditor } from "./types";-import { useConfigureEditor, useSearch } from "./context";+import { useConfigureEditor, useSearch, useToolbarConfig } from "./context";import { createPortal } from "react-dom";import { AttachmentType } from "notesnook-editor/dist/extensions/attachment";+import { getCurrentPreset } from "../../common/toolbar-config";type TipTapProps = {onChange?: (content: string, counter?: CharacterCounter) => void;@@ -37,6 +38,7 @@ function TipTap(props: TipTapProps) {const isMobile = useMobile();const counter = useRef<CharacterCounter>();const configure = useConfigureEditor();+ const { toolbarConfig } = useToolbarConfig();const { isSearching, toggleSearch } = useSearch();const editor = useTiptap(@@ -52,13 +54,19 @@ function TipTap(props: TipTapProps) {editor: toIEditor(editor),canRedo: editor.can().redo(),canUndo: editor.can().undo(),+ toolbarConfig: getCurrentPreset().tools,});},onUpdate: ({ editor }) => {if (onChange) onChange(editor.getHTML(), counter.current);},onDestroy: () => {- configure({ editor: undefined });+ configure({+ editor: undefined,+ canRedo: false,+ canUndo: false,+ searching: false,+ });},onTransaction: ({ editor }) => {configure({@@ -97,9 +105,11 @@ function TipTap(props: TipTapProps) {theme={theme}location={isMobile ? "bottom" : "top"}isMobile={isMobile || false}+ tools={toolbarConfig}/></Portal><Box+ className="selectable"ref={editorContentRef}style={{flex: 1,diff --git a/apps/web/src/views/settings.js b/apps/web/src/views/settings.jsindex c31f80f1e..307b35a67 100644--- a/apps/web/src/views/settings.js+++ b/apps/web/src/views/settings.js@@ -21,6 +21,7 @@ import {showMultifactorDialog,showAttachmentsDialog,show2FARecoveryCodesDialog,+ showToolbarConfigDialog,} from "../common/dialog-controller";import { SUBSCRIPTION_STATUS } from "../common/constants";import { createBackup, importBackup, verifyAccount } from "../common";@@ -101,6 +102,7 @@ const otherItems = [function Settings(props) {const [groups, setGroups] = useState({appearance: false,+ editor: false,mfa: false,backup: false,importer: false,@@ -418,6 +420,28 @@ function Settings(props) {</>)}+ <Header+ title="Editor settings"+ isOpen={groups.editor}+ onClick={() => {+ setGroups((g) => ({ ...g, editor: !g.editor }));+ }}+ />+ {groups.editor && (+ <>+ <Button+ variant="list"+ onClick={async () => {+ await showToolbarConfigDialog();+ }}+ >+ <Tip+ text="Configure toolbar"+ tip="Customize the editor toolbar to fit your needs."+ />+ </Button>+ </>+ )}<Headertitle="Backup & restore"isOpen={groups.backup}