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
refactor: cleanup context menu logic
thecodrr3015a6076451
diff --git a/apps/web/src/components/dropdown-button/index.js b/apps/web/src/components/dropdown-button/index.jsindex 3938b069e..34023d507 100644--- a/apps/web/src/components/dropdown-button/index.js+++ b/apps/web/src/components/dropdown-button/index.js@@ -1,9 +1,10 @@import { Button, Flex } from "rebass";-import { useOpenContextMenu } from "../../utils/useContextMenu";+import { useMenuTrigger } from "../../hooks/use-menu";import { ChevronDown } from "../icons";export default function DropdownButton({ title, options }) {- const openContextMenu = useOpenContextMenu();+ const { openMenu } = useMenuTrigger();+if (!options || !options.length) return null;return (<Flex>@@ -20,9 +21,7 @@ export default function DropdownButton({ title, options }) {borderBottomLeftRadius: 0,borderTopLeftRadius: 0,}}- onClick={(event) =>- openContextMenu(event, options.slice(1), { title })- }+ onClick={() => openMenu(options.slice(1), { title })}><ChevronDown color="static" size={18} /></Button>diff --git a/apps/web/src/components/global-menu-wrapper/index.js b/apps/web/src/components/global-menu-wrapper/index.jsindex 395fc5ba2..c4d8f9256 100644--- a/apps/web/src/components/global-menu-wrapper/index.js+++ b/apps/web/src/components/global-menu-wrapper/index.js@@ -1,48 +1,71 @@-import React, { useEffect } from "react";import Menu from "../menu";-import useContextMenu from "../../utils/useContextMenu";-import { useAnimation } from "framer-motion";+import { useMenuTrigger, useMenu, getPosition } from "../../hooks/use-menu";+import Modal from "react-modal";+import { Box } from "rebass";function GlobalMenuWrapper() {- const [items, title, data, state, closeMenu] = useContextMenu();- const animation = useAnimation();- useEffect(() => {- if (state === "open") {- const menu = document.getElementById("globalContextMenu");- menu.style.display = "block";- animation.start({- opacity: 1,- transition: { duration: 0.2 },- });- } else if (state === "close") {- animation- .start({- opacity: 0,- transition: { duration: 0.1 },- })- .then(() => {- const menu = document.getElementById("globalContextMenu");- menu.style.display = "none";- });- }- }, [state, animation]);+ const { isOpen, closeMenu } = useMenuTrigger();+ const { items, data } = useMenu();return (- <>- <Menu- id="globalContextMenu"- menuItems={items}- state={state}- title={title}- data={data}- style={{- position: "absolute",- display: "none",+ <Modal+ role="menu"+ isOpen={isOpen}+ shouldCloseOnEsc+ shouldReturnFocusAfterClose+ shouldCloseOnOverlayClick+ shouldFocusAfterRender+ onRequestClose={closeMenu}+ id={"globalContextMenu"}+ overlayElement={(props, contentEl) => (+ <Box+ {...props}+ onContextMenu={(e) => {+ e.preventDefault();+ closeMenu();+ }}+ >+ {contentEl}+ </Box>+ )}+ onAfterOpen={({ contentEl: menu }) => {+ if (!menu) return;+ const position = getPosition(menu);+ menu.style.top = position.top + "px";+ menu.style.left = position.left + "px";+ }}+ contentElement={(props, children) => (+ <Box+ {...props}+ style={{}}+ sx={{+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ display: "flex",+ width: "fit-content",+ height: "fit-content",+ position: "absolute",+ backgroundColor: undefined,+ padding: 0,+ zIndex: 0,+ outline: 0,+ }}+ >+ {children}+ </Box>+ )}+ style={{+ content: {},+ overlay: {zIndex: 999,- }}- closeMenu={closeMenu}- />- </>+ background: "transparent",+ },+ }}+ >+ <Menu items={items} data={data} closeMenu={closeMenu} />+ </Modal>);}export default GlobalMenuWrapper;diff --git a/apps/web/src/components/group-header/index.js b/apps/web/src/components/group-header/index.jsindex 58007c4cf..cfa2ec623 100644--- a/apps/web/src/components/group-header/index.js+++ b/apps/web/src/components/group-header/index.js@@ -1,9 +1,9 @@import * as Icon from "../icons";-import React, { useMemo, useState } from "react";+import { useMemo, useState } from "react";import { Button, Flex, Text } from "rebass";import { AnimatedFlex } from "../animated";import { db } from "../../common/db";-import { useOpenContextMenu } from "../../utils/useContextMenu";+import { useMenuTrigger } from "../../hooks/use-menu";import { useStore as useNoteStore } from "../../stores/note-store";import { useStore as useNotebookStore } from "../../stores/notebook-store";import useMobile from "../../utils/use-mobile";@@ -19,87 +19,121 @@ const groupByToTitleMap = {const menuItems = [{- key: "sortDirection:asc",- title: () => "Order by ascending",+ key: "sortDirection",+ title: "Order by",+ icon: ({ groupOptions }) =>+ groupOptions.sortDirection === "asc"+ ? groupOptions.sortBy === "title"+ ? Icon.OrderAtoZ+ : Icon.OrderOldestNewest+ : groupOptions.sortBy === "title"+ ? Icon.OrderZtoA+ : Icon.OrderNewestOldest,+ items: map([+ {+ key: "asc",+ title: ({ groupOptions }) =>+ groupOptions.sortBy === "title" ? "A - Z" : "Oldest - newest",+ },+ {+ key: "desc",+ title: ({ groupOptions }) =>+ groupOptions.sortBy === "title" ? "Z - A" : "Newest - oldest",+ },+ ]),},- { key: "sortDirection:desc", title: () => "Order by descending" },- { key: "orderSeperator", type: "seperator" },{- key: "sortBy:dateCreated",- title: () => "Sort by date created",- show: (type) => type !== "trash",+ key: "sortBy",+ title: "Sort by",+ icon: Icon.SortBy,+ items: map([+ {+ key: "dateCreated",+ title: "Date created",+ hidden: ({ type }) => type === "trash",+ },+ {+ key: "dateEdited",+ title: "Date edited",+ hidden: ({ type }) => type === "trash" || type === "tags",+ },+ {+ key: "dateDeleted",+ title: "Date deleted",+ hidden: ({ type }) => type !== "trash",+ },+ {+ key: "dateModified",+ title: "Date modified",+ hidden: ({ type }) => type !== "tags",+ },+ {+ key: "title",+ title: "Title",+ hidden: ({ groupOptions, parent }, item) => {+ return (+ parent?.key === "sortBy" &&+ item.key === "title" &&+ groupOptions.groupBy !== "abc"+ );+ },+ },+ ]),},{- key: "sortBy:dateEdited",- title: () => "Sort by date edited",- show: (type) => type !== "trash" && type !== "tags",+ key: "groupBy",+ title: "Group by",+ icon: Icon.GroupBy,+ items: map([+ { key: "default", title: "Default" },+ { key: "year", title: "Year" },+ { key: "month", title: "Month" },+ { key: "week", title: "Week" },+ { key: "abc", title: "A - Z" },+ ]),},- {- key: "sortBy:dateDeleted",- title: () => "Sort by date deleted",- show: (type) => type === "trash",- },- {- key: "sortBy:dateModified",- title: () => "Sort by date modified",- show: (type) => type === "tags",- },- {- key: "sortBy:title",- title: () => "Sort by title",- },- { key: "sortSeperator", type: "seperator" },- { key: "groupBy:default", title: () => "Group by default" },- { key: "groupBy:year", title: () => "Group by year" },- { key: "groupBy:month", title: () => "Group by month" },- { key: "groupBy:week", title: () => "Group by week" },- { key: "groupBy:abc", title: () => "Group by A - Z" },];-function changeGroupOptions({ groupOptions, type, refresh }, { key: itemKey }) {- let [key, value] = itemKey.split(":");- groupOptions[key] = value;- if (key === "groupBy") {- if (value === "abc") groupOptions.sortBy = "title";+function changeGroupOptions({ groupOptions, type, refresh, parent }, item) {+ if (!parent) return false;++ groupOptions[parent.key] = item.key;+ if (parent.key === "groupBy") {+ if (item.key === "abc") groupOptions.sortBy = "title";else groupOptions.sortBy = "dateEdited";}db.settings.setGroupOptions(type, groupOptions);refresh();}-const getMenuItems = (groupOptions, type) => {- return menuItems.reduce((items, item) => {- switch (item.type) {- case "seperator":- items.push(item);- break;- default: {- let [key, value] = item.key.split(":");-- item.checked = groupOptions[key] === value;-- if (key === "sortBy") {- if (value === "title")- item.disabled = () => groupOptions.groupBy !== "abc";- else item.disabled = () => groupOptions.groupBy === "abc";- }+function isChecked({ groupOptions, parent }, item) {+ if (!parent) return false;+ return groupOptions[parent.key] === item.key;+}- item.onClick = changeGroupOptions;- if (!item.show || item.show(type)) items.push(item);- break;- }- }+function isDisabled({ groupOptions, parent }, item) {+ return (+ parent?.key === "sortBy" &&+ item.key === "title" &&+ groupOptions.groupBy === "abc"+ );+}- return items;+function map(items) {+ return items.map((item) => {+ item.checked = isChecked;+ item.onClick = changeGroupOptions;+ item.disabled = isDisabled;+ return item;}, []);-};+}function GroupHeader(props) {const { title, groups, onJump, index, type, refresh } = props;const [groupOptions, setGroupOptions] = useState(db.settings.getGroupOptions(type));- const openContextMenu = useOpenContextMenu();+ const { openMenu } = useMenuTrigger();const notesViewMode = useNoteStore((store) => store.viewMode);const setNotesViewMode = useNoteStore((store) => store.setViewMode);const notebooksViewMode = useNotebookStore((store) => store.viewMode);@@ -130,11 +164,11 @@ function GroupHeader(props) {e.stopPropagation();const items = groups.map((group) => ({key: group.title,- title: () => group.title,+ title: group.title,onClick: () => onJump(group.title),checked: group.title === title,}));- openContextMenu(e, items, {+ openMenu(items, {title: "Jump to group",});}}@@ -172,8 +206,7 @@ function GroupHeader(props) {const groupOptions = db.settings.getGroupOptions(type);setGroupOptions(groupOptions);- const items = getMenuItems(groupOptions, type);- openContextMenu(e, items, {+ openMenu(menuItems, {title: "Group & sort",groupOptions,refresh,diff --git a/apps/web/src/components/icons/index.js b/apps/web/src/components/icons/index.jsindex 2c4ab0a07..8a59ac4eb 100644--- a/apps/web/src/components/icons/index.js+++ b/apps/web/src/components/icons/index.js@@ -127,6 +127,12 @@ import {mdiLinkVariantOff,mdiNetworkOffOutline,mdiCheckNetworkOutline,+ mdiSort,+ mdiOrderAlphabeticalAscending,+ mdiOrderAlphabeticalDescending,+ mdiOrderNumericDescending,+ mdiOrderNumericAscending,+ mdiSelectGroup,} from "@mdi/js";import { useTheme } from "emotion-theming";import { AnimatedFlex } from "../animated";@@ -149,7 +155,7 @@ function Icon({ title, name, size = 24, color = "icon", stroke, rotate }) {}function createIcon(name, rotate = false) {- return function (props) {+ return function NNIcon(props) {const [isHovering, setIsHovering] = useState();return (<AnimatedFlex@@ -267,6 +273,7 @@ export const Fullscreen = createIcon(mdiFullscreen);export const ExitFullscreen = createIcon(mdiFullscreenExit);export const Announcement = createIcon(mdiBullhorn);export const Publish = createIcon(mdiCloudUploadOutline);+export const Colors = createIcon(mdiPaletteOutline);export const Published = createIcon(mdiCloudCheckOutline);export const Copy = createIcon(mdiContentCopy);export const Select = createIcon(mdiCheckboxMultipleMarkedCircleOutline);@@ -321,3 +328,10 @@ export const ShortcutLink = createIcon(mdiLinkVariant);export const RemoveShortcutLink = createIcon(mdiLinkVariantOff);export const Offline = createIcon(mdiNetworkOffOutline);export const Online = createIcon(mdiCheckNetworkOutline);++export const SortBy = createIcon(mdiSort);+export const GroupBy = createIcon(mdiSelectGroup);+export const OrderAtoZ = createIcon(mdiOrderAlphabeticalAscending);+export const OrderZtoA = createIcon(mdiOrderAlphabeticalDescending);+export const OrderOldestNewest = createIcon(mdiOrderNumericDescending);+export const OrderNewestOldest = createIcon(mdiOrderNumericAscending);diff --git a/apps/web/src/components/list-item/index.js b/apps/web/src/components/list-item/index.jsindex 5bb2a4419..abdbf17e8 100644--- a/apps/web/src/components/list-item/index.js+++ b/apps/web/src/components/list-item/index.js@@ -5,7 +5,7 @@ import {store as selectionStore,useStore as useSelectionStore,} from "../../stores/selection-store";-import { useOpenContextMenu } from "../../utils/useContextMenu";+import { useMenuTrigger } from "../../hooks/use-menu";import { SELECTION_OPTIONS_MAP } from "../../common";import Config from "../../utils/config";import { db } from "../../common/db";@@ -102,8 +102,7 @@ function ListItem(props) {const isSelected =selectedItems.findIndex((item) => props.item.id === item.id) > -1;const selectItem = useSelectionStore((store) => store.selectItem);-- const openContextMenu = useOpenContextMenu();+ const { isOpen: isContextMenuOpen, openMenu } = useMenuTrigger();const toggleSelection = useCallback(function toggleSelection() {@@ -147,10 +146,14 @@ function ListItem(props) {return (<Flex- bg={isSelected ? "bgSecondary" : background}- onContextMenu={(e) =>- openContextMenu(e, menuItems, props.menu?.extraData, false)- }+ bg={isSelected || isContextMenuOpen ? "bgSecondary" : background}+ onContextMenu={(e) => {+ e.preventDefault();+ openMenu(menuItems, {+ title: props.item.title,+ ...props.menu?.extraData,+ });+ }}p={2}py={isCompact ? 1 : 2}tabIndex={0}diff --git a/apps/web/src/components/menu/colors.js b/apps/web/src/components/menu/colors.jsdeleted file mode 100644index 472f0fad4..000000000--- a/apps/web/src/components/menu/colors.js+++ /dev/null@@ -1,46 +0,0 @@-import React from "react";-import { COLORS } from "../../common";-import * as Icon from "../icons/index";-import { useStore } from "../../stores/note-store";-import { Flex } from "rebass";-import useMobile from "../../utils/use-mobile";--function Colors(props) {- const { id, color } = props.note;- const setColor = useStore((store) => store.setColor);- const isMobile = useMobile();-- return (- <Flex flexWrap="wrap">- {COLORS.map((label) => (- <Flex- sx={{ position: "relative" }}- onClick={() => setColor(id, label.toLowerCase())}- key={label}- justifyContent="center"- alignItems="center"- >- <Icon.Circle- size={isMobile ? 45 : 25}- style={{ cursor: "pointer" }}- color={label.toLowerCase()}- strokeWidth={0}- data-test-id={`menuitem-colors-${label}`}- />- {color === label.toLowerCase() && (- <Icon.Checkmark- data-test-id={`menuitem-colors-${label}-check`}- sx={{- position: "absolute",- cursor: "pointer",- }}- color="static"- size={isMobile ? 24 : 14}- />- )}- </Flex>- ))}- </Flex>- );-}-export default Colors;diff --git a/apps/web/src/components/menu/index.js b/apps/web/src/components/menu/index.jsindex 52f058116..736899864 100644--- a/apps/web/src/components/menu/index.js+++ b/apps/web/src/components/menu/index.js@@ -1,147 +1,131 @@import { useAnimation } from "framer-motion";-import { Check } from "../icons";-import React, { useEffect, useMemo } from "react";+import { Check, ChevronRight, Pro } from "../icons";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { Flex, Box, Text, Button } from "rebass";-import { useIsUserPremium } from "../../hooks/use-is-user-premium";import useMobile from "../../utils/use-mobile";import { AnimatedFlex } from "../animated";-function Menu(props) {- const { menuItems, data, closeMenu, id, style, sx, state } = props;- const isUserPremium = useIsUserPremium();+function useMenuFocus(items) {+ const [focusIndex, setFocusIndex] = useState(-1);+ const [isSubmenuOpen, setIsSubmenuOpen] = useState(false);++ const onKeyDown = useCallback(+ (e) => {+ const isSeperator = (i) => items && items[i]?.type === "seperator";+ const moveDown = (i) => (i < items.length - 1 ? ++i : 0);+ const moveUp = (i) => (i > 0 ? --i : items.length - 1);+ const hasSubmenu = (i) => items && items[i]?.hasSubmenu;+ const openSubmenu = (index) => {+ if (!hasSubmenu(index)) return;+ setIsSubmenuOpen(true);+ };++ const closeSubmenu = (index) => {+ if (!hasSubmenu(index)) return;+ setIsSubmenuOpen(false);+ };++ setFocusIndex((i) => {+ let nextIndex = i;++ switch (e.key) {+ case "ArrowUp":+ if (isSubmenuOpen) break;+ nextIndex = moveUp(i);+ if (isSeperator(nextIndex)) nextIndex = moveUp(nextIndex);+ break;+ case "ArrowDown":+ if (isSubmenuOpen) break;+ nextIndex = moveDown(i);+ if (isSeperator(nextIndex)) nextIndex = moveDown(nextIndex);+ break;+ case "ArrowRight":+ openSubmenu(i);+ break;+ case "ArrowLeft":+ closeSubmenu(i);+ break;+ default:+ break;+ }++ return nextIndex;+ });+ },+ [items, isSubmenuOpen]+ );++ useEffect(() => {+ window.addEventListener("keydown", onKeyDown);+ return () => {+ window.removeEventListener("keydown", onKeyDown);+ };+ }, [onKeyDown]);++ return [focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen];+}++function Menu({ items, data, closeMenu }) {const isMobile = useMobile();+ const [focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen] =+ useMenuFocus(items);+const Container = useMemo(() => (isMobile ? MobileMenuContainer : MenuContainer),[isMobile]);return (- <Container id={id} title={data?.title} style={style} sx={sx} state={state}>- {menuItems.map(- (- {- title,- key,- onClick,- component: Component,- color,- isPro,- isNew,- disabled,- disableReason,- checked,- icon: Icon,- type,- },- index- ) =>- type === "seperator" ? (- <Box- key={key}- width="95%"- height="0.5px"- bg="border"- my={2}- alignSelf="center"- />- ) : (- <Button- variant="menuitem"- color={color || "text"}- display="flex"- alignItems="center"- justifyContent="center"- title={- (disabled && disabled(data) && disableReason) || title(data)- }- disabled={disabled && disabled(data)}- data-test-id={`menuitem-${title(data)- .split(" ")- .join("")- .toLowerCase()}`}- key={key}- onClick={async (e) => {- e.stopPropagation();- if (closeMenu) {- closeMenu();- }-- if (!Component) {- onClick(data, menuItems[index]);- }- }}- >- {Icon && (- <Icon- color={color || "text"}- size={15}- sx={{ mr: 2, ml: -1 }}- />- )}- {Component ? (- <Component data={data} />- ) : (- <Text- as="span"- textAlign="left"- fontFamily="body"- fontSize="menu"- flex={1}- >- {title(data)}- </Text>- )}- {isPro && !isUserPremium && (- <Text- fontSize="subBody"- bg="primary"- color="static"- px={1}- sx={{ borderRadius: "default" }}- >- Pro- </Text>- )}- {isNew && (- <Text- fontSize="subBody"- bg="primary"- color="static"- px={1}- sx={{ borderRadius: "default" }}- >- NEW- </Text>- )}- {checked && <Check size={14} />}- </Button>- )- )}+ <Container title={data?.title}>+ {items.map((item, index) => (+ <MenuItem+ key={item.key}+ index={index}+ item={item}+ data={data}+ onClose={closeMenu}+ isFocused={focusIndex === index}+ isSubmenuOpen={focusIndex === index && isSubmenuOpen}+ onHover={() => {+ setFocusIndex(index);+ setIsSubmenuOpen((state) => {+ return item.items?.length ? true : state ? false : state;+ });+ }}+ />+ ))}</Container>);}-export default React.memo(Menu, (prev, next) => {- return prev.state === next.state;-});+export default React.memo(Menu);-function MenuContainer({ id, style, sx, title, children }) {+function MenuContainer({ title, children }) {return (<Flex- id={id}+ as="ul"+ tabIndex={-1}bg="background"py={1}- style={style}+ flexDirection={"column"}sx={{position: "relative",- width: "11em",+ listStyle: "none",+ padding: 0,+ margin: 0,borderRadius: "default",- boxShadow: "0px 10px 10px 0px #00000022",- border: "1px solid",- borderColor: "border",- ...sx,+ boxShadow: "0px 0px 10px 0px #00000022",+ border: "1px solid var(--border)",+ minWidth: 200,+ maxWidth: 500,}}>- <Flex flexDirection="column" width="100%">+ {title && (<TextfontFamily="body"fontSize="subtitle"@@ -150,10 +134,10 @@ function MenuContainer({ id, style, sx, title, children }) {px={3}sx={{ borderBottom: "1px solid", borderBottomColor: "border" }}>- {title || "Properties"}+ {title}</Text>- {children}- </Flex>+ )}+ {children}</Flex>);}@@ -215,3 +199,112 @@ function MobileMenuContainer({ style, id, state, title, children }) {</Flex>);}++function MenuItem({ item, data, isFocused, isSubmenuOpen, onClose, onHover }) {+ const {+ title,+ key,+ onClick,+ color,+ items,+ icon: Icon,+ iconColor,+ type,+ tooltip,+ isDisabled,+ isChecked,+ hasSubmenu,+ isPremium,+ } = item;+ const itemRef = useRef();++ useEffect(() => {+ if (isFocused) itemRef.current?.focus();+ }, [isFocused]);++ const onAction = useCallback(+ (e) => {+ e.stopPropagation();+ if (onClose) onClose();+ onClick(data, item);+ },+ [onClick, onClose, item, data]+ );++ if (type === "seperator")+ return (+ <Box+ as="li"+ key={key}+ width="95%"+ height="0.5px"+ bg="border"+ my={2}+ alignSelf="center"+ />+ );++ return (+ <Flex+ as="li"+ flexDirection={"column"}+ flex={1}+ sx={{ position: "relative" }}+ onMouseOver={onHover}+ >+ <Button+ data-test-id={`menuitem-${title.split(" ").join("").toLowerCase()}`}+ key={key}+ ref={itemRef}+ tabIndex={-1}+ variant="menuitem"+ display="flex"+ alignItems={"center"}+ justifyContent={"space-between"}+ title={tooltip}+ disabled={isDisabled}+ onClick={onAction}+ onKeyUp={(e) => {+ if (e.key === "Enter") onAction(e);+ }}+ sx={{+ bg: isFocused ? "hover" : "transparent",+ }}+ >+ <Flex>+ {Icon && (+ <Icon color={iconColor || "text"} size={15} sx={{ mr: 2 }} />+ )}+ <Text+ as="span"+ fontFamily="body"+ fontSize="menu"+ color={color || "text"}+ >+ {title}+ </Text>+ {isPremium && <Pro size={14} color="primary" sx={{ ml: 1 }} />}+ </Flex>+ <Flex>+ {isChecked && <Check size={14} />}+ {hasSubmenu && <ChevronRight size={14} />}+ </Flex>+ </Button>+ {hasSubmenu && isSubmenuOpen && (+ <Flex+ sx={{+ position: "absolute",+ top: 0,+ left: itemRef.current?.offsetWidth,+ }}+ >+ <Menu+ items={items}+ onClose={onClose}+ data={{ ...data, parent: item, title: undefined }}+ />+ </Flex>+ )}+ </Flex>+ );+}diff --git a/apps/web/src/components/navigation-menu/navigation-item.js b/apps/web/src/components/navigation-menu/navigation-item.jsindex 68f806c87..de6a566d2 100644--- a/apps/web/src/components/navigation-menu/navigation-item.js+++ b/apps/web/src/components/navigation-menu/navigation-item.js@@ -1,7 +1,6 @@-import React from "react";import { Button, Text } from "rebass";import { useStore as useAppStore } from "../../stores/app-store";-import { useOpenContextMenu } from "../../utils/useContextMenu";+import { useMenuTrigger } from "../../hooks/use-menu";import useMobile from "../../utils/use-mobile";import useTablet from "../../utils/use-tablet";import * as Icons from "../icons";@@ -9,9 +8,9 @@ import * as Icons from "../icons";function NavigationItem(props) {const { icon: Icon, color, title, isLoading, isShortcut, isNew } = props;const toggleSideMenu = useAppStore((store) => store.toggleSideMenu);+ const { openMenu } = useMenuTrigger();const isMobile = useMobile();const isTablet = useTablet();- const openContextMenu = useOpenContextMenu();return (<Button@@ -29,9 +28,10 @@ function NavigationItem(props) {}}label={title}title={title}- onContextMenu={(event) => {+ onContextMenu={(e) => {if (!props.menu) return;- openContextMenu(event, props.menu.items, props.menu.extraData, false);+ e.preventDefault();+ openMenu(props.menu.items, props.menu.extraData, false);}}onClick={() => {if (isMobile) toggleSideMenu(false);diff --git a/apps/web/src/components/note/index.js b/apps/web/src/components/note/index.jsindex 2eb2c0315..80ab40d86 100644--- a/apps/web/src/components/note/index.js+++ b/apps/web/src/components/note/index.js@@ -6,7 +6,6 @@ import ListItem from "../list-item";import { showMoveNoteDialog } from "../../common/dialog-controller";import { store, useStore } from "../../stores/note-store";import { db } from "../../common/db";-import Colors from "../menu/colors";import { showExportDialog } from "../../common/dialog-controller";import { showItemDeletedToast } from "../../common/toasts";import { showUnpinnedToast } from "../../common/toasts";@@ -15,6 +14,7 @@ import { hashNavigate, navigate } from "../../navigation";import { showPublishView } from "../publish-view";import Vault from "../../common/vault";import IconTag from "../icon-tag";+import { COLORS } from "../../common";function Note(props) {const { tags, notebook, item, index, context, attachments, date } = props;@@ -195,46 +195,60 @@ const pin = (note) => {const menuItems = [{- key: "colors",- title: () => "Colors",- component: ({ data }) => <Colors note={data.note} />,- },- {- key: "publish",- disabled: ({ note }) => !db.monographs.isPublished(note.id) && note.locked,- disableReason: "You cannot publish a locked note.",- icon: Icon.Publish,- title: ({ note }) =>- db.monographs.isPublished(note.id) ? "Unpublish" : "Publish",+ key: "pin",+ title: ({ note }) => (note.pinned ? "Unpin" : "Pin"),+ icon: Icon.Pin,onClick: async ({ note }) => {- await showPublishView(note.id, "bottom");+ await pin(note);},},+ {+ key: "favorite",+ title: ({ note }) => (note.favorite ? "Unfavorite" : "Favorite"),+ icon: Icon.StarOutline,+ onClick: ({ note }) => store.favorite(note),+ },{key: "addtonotebook",- title: () => "Add to notebook(s)",+ title: "Add to notebook(s)",icon: Icon.AddToNotebook,onClick: async ({ note }) => {await showMoveNoteDialog([note.id]);},},{- key: "pin",- title: ({ note }) => (note.pinned ? "Unpin" : "Pin"),- icon: Icon.Pin,- onClick: async ({ note }) => {- await pin(note);- },+ key: "colors",+ title: "Assign color",+ icon: Icon.Colors,+ items: COLORS.map((label) => ({+ key: label,+ title: db.colors.alias(label.toLowerCase()) || label.toLowerCase(),+ icon: Icon.Circle,+ iconColor: label.toLowerCase(),+ checked: ({ note }) => {+ return note.color === label.toLowerCase();+ },+ onClick: ({ note }) => {+ const { id } = note;+ store.setColor(id, label.toLowerCase());+ },+ })),},+{- key: "favorite",- title: ({ note }) => (note.favorite ? "Unfavorite" : "Favorite"),- icon: Icon.StarOutline,- onClick: ({ note }) => store.favorite(note),+ key: "publish",+ disabled: ({ note }) => !db.monographs.isPublished(note.id) && note.locked,+ disableReason: "You cannot publish a locked note.",+ icon: Icon.Publish,+ title: ({ note }) =>+ db.monographs.isPublished(note.id) ? "Unpublish" : "Publish",+ onClick: async ({ note }) => {+ await showPublishView(note.id, "bottom");+ },},{key: "export",- title: () => "Export",+ title: "Export",icon: Icon.Export,onClick: async ({ note }) => {if (note.locked) {@@ -262,10 +276,12 @@ const menuItems = [},isPro: true,},+{key: "movetotrash",- title: () => "Move to trash",+ title: "Move to trash",color: "red",+ iconColor: "red",icon: Icon.Trash,disabled: ({ note }) => db.monographs.isPublished(note.id),disableReason: "Please unpublish this note to move it to trash",@@ -282,7 +298,7 @@ const topicNoteMenuItems = [...menuItems,{key: "removefromtopic",- title: () => "Remove from topic",+ title: "Remove from topic",icon: Icon.TopicRemove,color: "red",onClick: async ({ note, context }) => {diff --git a/apps/web/src/components/notebook/index.js b/apps/web/src/components/notebook/index.jsindex a70eedbc4..fce8dce8f 100644--- a/apps/web/src/components/notebook/index.js+++ b/apps/web/src/components/notebook/index.js@@ -104,7 +104,7 @@ const pin = (notebook) => {const menuItems = [{- title: () => "Edit",+ title: "Edit",icon: Icon.NotebookEdit,onClick: ({ notebook }) => hashNavigate(`/notebooks/${notebook.id}/edit`),},@@ -122,7 +122,7 @@ const menuItems = [onClick: ({ notebook }) => appStore.pinItemToMenu(notebook),},{- title: () => "Move to trash",+ title: "Move to trash",color: "red",icon: Icon.Trash,onClick: async ({ notebook }) => {diff --git a/apps/web/src/components/tag/index.js b/apps/web/src/components/tag/index.jsindex ad02e608f..256e7d09b 100644--- a/apps/web/src/components/tag/index.js+++ b/apps/web/src/components/tag/index.js@@ -11,7 +11,7 @@ import { showToast } from "../../utils/toast";const menuItems = [{- title: () => "Rename tag",+ title: "Rename tag",icon: Icon.Edit,onClick: ({ tag }) => {hashNavigate(`/tags/${tag.id}/edit`);@@ -25,7 +25,7 @@ const menuItems = [},{color: "error",- title: () => "Delete",+ title: "Delete",icon: Icon.DeleteForver,onClick: async ({ tag }) => {if (tag.noteIds.includes(editorStore.get().session.id))diff --git a/apps/web/src/components/topic/index.js b/apps/web/src/components/topic/index.jsindex b2e488576..f2f20f751 100644--- a/apps/web/src/components/topic/index.js+++ b/apps/web/src/components/topic/index.js@@ -58,7 +58,7 @@ const generalTopicMenuItems = [const menuItems = [{key: "edit",- title: () => "Edit",+ title: "Edit",icon: Icon.Edit,onClick: ({ topic }) =>hashNavigate(`/notebooks/${topic.notebookId}/topics/${topic.id}/edit`),@@ -66,7 +66,7 @@ const menuItems = [...generalTopicMenuItems,{key: "delete",- title: () => "Delete",+ title: "Delete",icon: Icon.Trash,color: "red",onClick: async ({ topic }) => {diff --git a/apps/web/src/components/trash-item/index.js b/apps/web/src/components/trash-item/index.jsindex 703a0fd4f..23b4656a2 100644--- a/apps/web/src/components/trash-item/index.js+++ b/apps/web/src/components/trash-item/index.js@@ -34,7 +34,7 @@ export default TrashItem;const menuItems = [{- title: () => "Restore",+ title: "Restore",icon: Icon.Restore,onClick: ({ item }) => {store.restore(item.id);@@ -47,7 +47,7 @@ const menuItems = [},},{- title: () => "Delete",+ title: "Delete",icon: Icon.DeleteForver,color: "red",onClick: ({ item }) => {diff --git a/apps/web/src/hooks/use-menu.js b/apps/web/src/hooks/use-menu.jsnew file mode 100644index 000000000..9b294279c--- /dev/null+++ b/apps/web/src/hooks/use-menu.js@@ -0,0 +1,185 @@+import create from "zustand";+import shallow from "zustand/shallow";+import { isUserPremium } from "./use-is-user-premium";++const mousePosition = {};+window.addEventListener("mousemove", (e) => {+ const { x, y } = getMousePosition(e);+ mousePosition.x = x;+ mousePosition.y = y;+});++const useMenuStore = create((set) => ({+ isOpen: false,+ items: [],+ title: undefined,+ data: undefined,+ open: (items, data) =>+ set(() => ({ isOpen: true, items: mapMenuItems(items, data), data })),+ close: () => set(() => ({ isOpen: false, items: [] })),+}));++export function useMenuTrigger() {+ const isOpen = useMenuStore((store) => store.isOpen);+ const [open, close] = useMenuStore(+ (store) => [store.open, store.close],+ shallow+ );++ return {+ openMenu: open,+ closeMenu: close,+ isOpen,+ };+}++export function useMenu() {+ const [items, data] = useMenuStore((store) => [store.items, store.data]);+ return { items, data };+}++/**+ *+ * @param {HTMLElement} element+ * @param {"mouse"|HTMLElement} relativeTo+ * @param {"right"|"below"|"left"|"top"} location+ * @returns+ */+export function getPosition(element, relativeTo = "mouse", location) {+ const { x, y, width, height } =+ relativeTo === "mouse" ? mousePosition : getElementPosition(relativeTo);++ const elementWidth = element.offsetWidth;+ const elementHeight = element.offsetHeight;++ const windowWidth = window.document.body.offsetWidth;+ const windowHeight = window.document.body.offsetHeight;++ let position = { top: undefined, left: undefined };++ if (windowWidth - x < elementWidth) {+ position.left = windowWidth - elementWidth;+ } else {+ position.left = x;++ if (location === "right") position.top += width;+ else if (location === "left") position.top -= width;+ }++ if (windowHeight - y < elementHeight) {+ position.top = windowHeight - elementHeight;+ } else {+ position.top = y;+ if (location === "below") position.top += height;+ else if (location === "top") position.top -= height;+ }++ return position;+}++function getMousePosition(e) {+ var posx = 0;+ var posy = 0;++ if (!e) e = window.event;++ if (e.pageX || e.pageY) {+ posx = e.pageX;+ posy = e.pageY;+ } else if (e.clientX || e.clientY) {+ posx =+ e.clientX ++ document.body.scrollLeft ++ document.documentElement.scrollLeft;+ posy =+ e.clientY + document.body.scrollTop + document.documentElement.scrollTop;+ }++ return {+ x: posx,+ y: posy,+ };+}++/**+ *+ * @param {HTMLElement} element+ */+function getElementPosition(element) {+ return {+ x: element.offsetLeft,+ y: element.offsetTop,+ width: element.offsetWidth,+ height: element.offsetHeight,+ };+}++function mapMenuItems(items, data) {+ return items.reduce((prev, item) => {+ const {+ key,+ onClick,+ color,+ disableReason,+ disabled,+ hidden,+ checked,+ items,+ isPro,+ isNew,+ type,+ iconColor,+ } = item;++ const isHidden = hidden && hidden(data, item);+ if (isHidden) return prev;++ const isSeperator = type === "seperator";+ if (isSeperator) {+ prev.push({ isSeperator: true });+ return prev;+ }++ const title = resolveProp(item.title, data, item);+ const icon = resolveProp(item.icon, data, item);+ const isChecked = resolveProp(checked, data, item);+ const isDisabled = resolveProp(disabled, data, item);++ const tooltip = (isDisabled && disableReason) || item.tooltip || title;+ const isPremium = isPro && !isUserPremium();+ const hasSubmenu = items?.length > 0;++ const menuItem = {+ type,+ title,+ key,+ onClick,+ tooltip,++ isChecked,+ isDisabled,+ isHidden,+ hasSubmenu,+ isNew,+ isPremium,++ icon,+ color,+ iconColor,++ items,+ };++ prev.push(menuItem);++ return prev;+ }, []);+}++function resolveProp(prop, data, item) {+ const isFunction = typeof prop === "function";+ if (isFunction) {+ return prop.name === "NNIcon" ? prop : prop(data, item);+ }+ return prop;+}diff --git a/apps/web/src/theme/variants/button.js b/apps/web/src/theme/variants/button.jsindex a7ceacd6b..9d7bf1f1b 100644--- a/apps/web/src/theme/variants/button.js+++ b/apps/web/src/theme/variants/button.js@@ -173,8 +173,9 @@ class MenuItem {borderRadius: 0,color: "text",cursor: "pointer",- ":hover:not(:disabled)": {+ ":hover:not(:disabled),:focus:not(:disabled)": {backgroundColor: "hover",+ boxShadow: "none",},":active:not(:disabled)": {backgroundColor: "border",diff --git a/apps/web/src/utils/useContextMenu.js b/apps/web/src/utils/useContextMenu.jsdeleted file mode 100644index cdd38fde2..000000000--- a/apps/web/src/utils/useContextMenu.js+++ /dev/null@@ -1,134 +0,0 @@-import { useCallback, useEffect, useState } from "react";--var currentEvent = undefined;-function closeMenu() {- window.dispatchEvent(- new CustomEvent("globalcontextmenu", { detail: { state: "close" } })- );- window.removeEventListener("click", onWindowClick);- window.removeEventListener("keydown", onKeyDown);- window.removeEventListener("blur", onWindowClick);-}--function getGlobalMenu() {- return document.getElementById("globalContextMenu");-}--function onKeyDown(event) {- if (event.keyCode === 27) closeMenu();-}--function onWindowClick(event) {- if (- event === currentEvent.nativeEvent ||- event.target === currentEvent.target- )- return;-- closeMenu();-}--// updated positionMenu function-function openMenu(e) {- e.preventDefault();- const menu = getGlobalMenu();- if (menu.style.display === "block") {- closeMenu();- return;- }- currentEvent = e;-- menu.style.display = "block";-- const clickCoords = getPosition(e);- const clickCoordsX = clickCoords.x;- const clickCoordsY = clickCoords.y;-- const menuWidth = menu.offsetWidth + 4;- const menuHeight = menu.offsetHeight + 4;-- const windowWidth = window.document.body.offsetWidth;- const windowHeight = window.document.body.offsetHeight;-- if (windowWidth - clickCoordsX < menuWidth) {- menu.style.left = windowWidth - menuWidth + "px";- } else {- menu.style.left = clickCoordsX + "px";- }-- if (windowHeight - clickCoordsY < menuHeight) {- menu.style.top = windowHeight - menuHeight + "px";- } else {- menu.style.top = clickCoordsY + "px";- }-- window.addEventListener("keydown", onKeyDown);- window.addEventListener("click", onWindowClick);- window.addEventListener("blur", onWindowClick);-}--function getPosition(e) {- var posx = 0;- var posy = 0;-- if (!e) e = window.event;-- if (e.pageX || e.pageY) {- posx = e.pageX;- posy = e.pageY;- } else if (e.clientX || e.clientY) {- posx =- e.clientX +- document.body.scrollLeft +- document.documentElement.scrollLeft;- posy =- e.clientY + document.body.scrollTop + document.documentElement.scrollTop;- }-- return {- x: posx,- y: posy,- };-}--function useContextMenu() {- const [items, setItems] = useState([]);- const [title, setTitle] = useState();- const [state, setState] = useState();- const [data, setData] = useState();- useEffect(() => {- const onGlobalContextMenu = (e) => {- const { items, title, internalEvent, data, state } = e.detail;- setState(state);- if (state === "close") {- return;- }- setItems(items);- setTitle(title);- setData(data);- openMenu(internalEvent);- };- window.addEventListener("globalcontextmenu", onGlobalContextMenu);- return () => {- window.removeEventListener("globalcontextmenu", onGlobalContextMenu);- };- }, []);- return [items, title, data, state, closeMenu];-}--export function useOpenContextMenu() {- return useCallback((event, items, data) => {- window.dispatchEvent(- new CustomEvent("globalcontextmenu", {- detail: {- state: "open",- items,- data,- internalEvent: event,- },- })- );- }, []);-}--export default useContextMenu;