SoLoVault Relinking License Copyright (c) 2026 SoLoVision LLC. All rights reserved. This patch is SoLoVision LLC's proprietary Corresponding Application Code for the SoLoVault web client. It is provided only to meet SoLoVision's obligations under section 4(d)(0) of the GNU Lesser General Public License v3. You may copy, apply and modify this patch, and build and use the resulting client, solely to recombine or relink it with a modified version of OpenPGP.js, @openpgp/hkp-client or any other LGPL-licensed library contained in the client, and to debug such modifications, including by reverse engineering. No other right is granted. This licence does not restrict any right you have under the LGPL, the GPL, the MPL or the Apache License 2.0 in the open-source components or in the unmodified Psono source, which remain under their own licences. THE PATCH IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. diff --git a/src/js/components/base-title.tsx b/src/js/components/base-title.tsx index b384d45..a1412a1 100644 --- a/src/js/components/base-title.tsx +++ b/src/js/components/base-title.tsx @@ -1,22 +1,22 @@ -import Paper from "@mui/material/Paper"; +import Typography from "@mui/material/Typography"; import { makeStyles } from "@mui/styles"; import PropTypes from "prop-types"; import React from "react"; import { useTranslation } from "react-i18next"; const useStyles = makeStyles((theme) => ({ + // SoLoVault: a plain page heading on the canvas, not a separate grey bar. title: { - backgroundColor: theme.palette.baseTitleBackground.main, - textAlign: "right", - fontSize: "16px", - paddingTop: theme.spacing(1), - paddingBottom: theme.spacing(1), - paddingLeft: "15px", - paddingRight: "15px", - marginBottom: "15px", + backgroundColor: "transparent", + textAlign: "left", + fontSize: "20px", + fontWeight: 600, + lineHeight: 1.3, + padding: "24px 15px 16px", color: theme.palette.background.default, [theme.breakpoints.up("sm")]: { - fontSize: "20px", + fontSize: "22px", + padding: "28px 15px 18px", }, }, sessionExpirationTimer: { @@ -44,9 +44,9 @@ const BaseTitle = (props: BaseTitleProps) => { {/**/} {/* {t("AUTOMATIC_SIGN_OFF_IN", {time: '00:00:00'})}*/} {/**/} - + {children} - + ); }; diff --git a/src/js/components/base.tsx b/src/js/components/base.tsx index ec5ff93..b41016c 100644 --- a/src/js/components/base.tsx +++ b/src/js/components/base.tsx @@ -2,6 +2,7 @@ import { makeStyles } from "@mui/styles"; import PropTypes from "prop-types"; import React from "react"; import deviceService from "../services/device"; +import { BackgroundProgress } from "./dialogs/progress"; import Sidebar from "./sidebar"; import Topbar from "./topbar"; @@ -12,7 +13,7 @@ const useStyles = makeStyles((theme) => ({ }, // necessary for content to be below app bar toolbar: { - minHeight: deviceService.hasTitlebar() ? "82px" : "50px", + minHeight: deviceService.hasTitlebar() ? "88px" : "56px", flexShrink: 0, }, fullContent: { @@ -68,6 +69,7 @@ const Base = (props: BaseProps) => { {children} + ); }; diff --git a/src/js/components/datastore-tree/datastore-tree-virtual-element.tsx b/src/js/components/datastore-tree/datastore-tree-virtual-element.tsx index 5287a54..7f960f7 100644 --- a/src/js/components/datastore-tree/datastore-tree-virtual-element.tsx +++ b/src/js/components/datastore-tree/datastore-tree-virtual-element.tsx @@ -10,9 +10,12 @@ import type { import type { DatastoreTreeListData, DatastoreNodePath, + DatastoreTreeFolderNode, } from "../../../types/datastore-ui"; import DatastoreTreeFolder from "./datastore-tree-folder"; import DatastoreTreeItem from "./datastore-tree-item"; +import { beginPointerDrag, dropTargetRef } from "./drag"; +import { handleSelectClick, keepTextUnselected } from "./select"; const useStyles = makeStyles((theme) => ({ virtualizedElement: { @@ -40,6 +43,14 @@ const useStyles = makeStyles((theme) => ({ top: -10, }, }, + // SoLoVault: drag and drop. + draggable: { + userSelect: "none", + WebkitTouchCallout: "none", + }, + dragging: { + opacity: 0.45, + }, })); const DatastoreTreeVirtualElement = ({ @@ -56,11 +67,52 @@ const DatastoreTreeVirtualElement = ({ datastore, getIsExpandedFolder, onUpdateExpandFolderProperty, + drag, + selectAnchor, } = data; const content = items[index]; const isExpanded = getIsExpandedFolder(content); + // SoLoVault: rows drag like files in File Explorer and drop onto folders + // (see drag.ts). + const rights = content.share_rights; + const canDrag = + !offline && + !!props.onDropNode && + !(rights && rights.delete === false) && + (!props.canDragNode || props.canDragNode(content)) && + (content.is_folder ? !!props.onMoveFolder : !!props.onMoveEntry); + const onPointerDown = (event: React.PointerEvent) => { + if (!canDrag) return; + beginPointerDrag(event, { + node: content, + canDrop: (node, target) => + !props.canDropNode || props.canDropNode(node, target), + onDrop: props.onDropNode!, + onDragChange: drag.setNode, + }); + }; + const onClickCapture = (event: React.MouseEvent) => { + handleSelectClick(event, { + items, + index, + anchor: selectAnchor, + onSelectRows: props.onSelectRows, + selectOnClick: props.selectRowsOnClick, + }); + }; + const folderTarget = content.is_folder + ? { + node: content as DatastoreTreeFolderNode, + open: () => { + if (!getIsExpandedFolder(content)) { + onUpdateExpandFolderProperty(content.id, false); + } + }, + } + : null; + // Keep undefined < length false for the first row, as in the JS comparison. const isFirstInFolder = items[index - 1]?.path?.length! < content.path.length; @@ -93,7 +145,17 @@ const DatastoreTreeVirtualElement = ({ const nodePath = getNodePathById(content.id, content.path, datastore, [], -1); return ( -
+
{content.path.map((item, index, items) => (
({ + useTranslation: () => ({ t: (key: string) => key }), +})); +jest.mock("../../services/store", () => ({ + getStore: () => ({ getState: () => ({ server: {} }) }), +})); +jest.mock("../../services/secret", () => ({ __esModule: true, default: {} })); +jest.mock("../entry-icon", () => ({ __esModule: true, default: () => null })); +jest.mock("../gateway-launch-button", () => ({ + __esModule: true, + default: () => null, +})); + +// SoLoVault drag and drop. Synthetic rows only. +const folder: DatastoreTreeFolderNode = { + id: "work", + name: "Work", + path: ["work"], + is_folder: true, +}; +const otherFolder: DatastoreTreeFolderNode = { + id: "home", + name: "Home", + path: ["home"], + is_folder: true, +}; +const item: DatastoreTreeItemNode = { + id: "item", + name: "Example login", + path: ["home", "item"], + is_folder: false, + type: "website_password", + secret_id: "secret", +}; +const datastore = { folders: [folder, otherFolder] } as unknown as Datastore; +const theme = createTheme({ + palette: { + blueBackground: { main: "#eee" }, + lightBackground: { main: "#fff" }, + greyText: { main: "#888" }, + }, +}); + +function pointer(type: string, x: number, y: number, pointerType = "mouse") { + const event = new MouseEvent(type, { + bubbles: true, + cancelable: true, + clientX: x, + clientY: y, + button: 0, + }); + Object.defineProperties(event, { + pointerId: { value: 1 }, + pointerType: { value: pointerType }, + isPrimary: { value: true }, + }); + return event; +} + +describe("Datastore tree drag and drop", () => { + let container: HTMLDivElement; + let drag: DatastoreTreeDrag; + const onDropNode = jest.fn(); + const onExpand = jest.fn(); + beforeEach(() => { + jest.clearAllMocks(); + jest.useFakeTimers(); + container = document.createElement("div"); + document.body.appendChild(container); + drag = { + node: null, + setNode(node: DatastoreTreeNode | null) { + drag.node = node; + }, + }; + }); + afterEach(() => { + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + container.remove(); + jest.runOnlyPendingTimers(); + jest.useRealTimers(); + }); + function render(rows: DatastoreTreeNode[], actions: DatastoreTreeActions) { + act(() => { + ReactDOM.render( + + {rows.map((row, index) => ( + {}, + onMoveEntry: () => {}, + onMoveFolder: () => {}, + ...actions, + }, + offline: false, + datastore, + getIsExpandedFolder: () => false, + onUpdateExpandFolderProperty: onExpand, + drag, + }} + /> + ))} + , + container, + ); + }); + } + // Rows are 46px apart; elementFromPoint (absent in jsdom) maps y to a row. + function layout(rows: HTMLElement[], extra: HTMLElement[] = []) { + document.elementFromPoint = (x: number, y: number) => + [...extra, ...rows][Math.floor(y / 46)] ?? null; + } + function press(row: HTMLElement, pointerType = "mouse") { + act(() => { + row.querySelector("button")!.dispatchEvent( + pointer("pointerdown", 5, 5, pointerType), + ); + }); + } + function move(y: number) { + act(() => { + window.dispatchEvent(pointer("pointermove", 20, y)); + }); + } + function release(y: number) { + act(() => { + window.dispatchEvent(pointer("pointerup", 20, y)); + }); + } + function rows() { + return Array.from( + container.querySelectorAll("[class*='virtualizedElement']"), + ); + } + + it("moves an entry dropped onto a folder", () => { + render([folder, item], { onDropNode }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(itemRow); + move(60); + expect(drag.node).toBe(item); + expect(document.querySelector(".solovault-drag-ghost")?.textContent).toBe( + "Example login", + ); + move(10); + expect(folderRow.classList.contains("solovault-drop-over")).toBe(true); + release(10); + expect(onDropNode).toHaveBeenCalledWith(item, folder); + expect(drag.node).toBeNull(); + expect(document.querySelector(".solovault-drag-ghost")).toBeNull(); + }); + + it("drops into the folder a reused row shows when released", () => { + render([folder, item], { onDropNode }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(itemRow); + move(60); + move(10); + // The list scrolled and the virtualized row now shows another folder. + const archive: DatastoreTreeFolderNode = { + id: "archive", + name: "Archive", + path: ["archive"], + is_folder: true, + }; + dropTargetRef({ node: archive })(folderRow); + release(10); + expect(onDropNode).toHaveBeenCalledWith(item, archive); + }); + + it("leaves a plain click alone, and swallows the click after a drop", () => { + const onSelectItem = jest.fn(); + render([folder, item], { onDropNode, onSelectItem }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + const click = () => + act(() => { + itemRow.querySelector("button")!.click(); + }); + press(itemRow); + release(5); + expect(drag.node).toBeNull(); + click(); + expect(onSelectItem).toHaveBeenCalledTimes(1); + press(itemRow); + move(60); + move(10); + release(10); + click(); + expect(onSelectItem).toHaveBeenCalledTimes(1); + act(() => { + jest.advanceTimersByTime(100); + }); + click(); + expect(onSelectItem).toHaveBeenCalledTimes(2); + }); + + it("swallows a late click after a touch drop, then clicks work again", () => { + const onSelectItem = jest.fn(); + render([folder, item], { onDropNode, onSelectItem }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + const click = () => + act(() => { + itemRow.querySelector("button")!.click(); + }); + press(itemRow, "touch"); + act(() => { + jest.advanceTimersByTime(450); + }); + move(10); + release(10); + expect(onDropNode).toHaveBeenCalledWith(item, folder); + act(() => { + jest.advanceTimersByTime(300); + }); + click(); + expect(onSelectItem).not.toHaveBeenCalled(); + click(); + expect(onSelectItem).toHaveBeenCalledTimes(1); + }); + + it("stops swallowing clicks when none follows the drop", () => { + const onSelectItem = jest.fn(); + render([folder, item], { onDropNode, onSelectItem }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(itemRow); + move(60); + move(10); + release(10); + act(() => { + jest.advanceTimersByTime(1100); + }); + act(() => { + itemRow.querySelector("button")!.click(); + }); + expect(onSelectItem).toHaveBeenCalledTimes(1); + }); + + it("cancels with Escape without opening the row on release", () => { + const onSelectItem = jest.fn(); + render([folder, item], { onDropNode, onSelectItem }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + const click = () => + act(() => { + itemRow.querySelector("button")!.click(); + }); + press(itemRow); + move(60); + act(() => { + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + }); + expect(drag.node).toBeNull(); + act(() => { + jest.advanceTimersByTime(2000); + }); + release(60); + click(); + expect(onDropNode).not.toHaveBeenCalled(); + expect(onSelectItem).not.toHaveBeenCalled(); + click(); + expect(onSelectItem).toHaveBeenCalledTimes(1); + }); + + it("leaves a click on another control alone right after a drop", () => { + const onSelectItem = jest.fn(); + render([folder, item], { onDropNode, onSelectItem }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + const other = document.createElement("button"); + const onOther = jest.fn(); + other.addEventListener("click", onOther); + document.body.appendChild(other); + press(itemRow); + move(60); + move(10); + release(10); + act(() => { + other.click(); + }); + expect(onOther).toHaveBeenCalledTimes(1); + // The late click from the drag itself is still swallowed. + act(() => { + itemRow.querySelector("button")!.click(); + }); + expect(onSelectItem).not.toHaveBeenCalled(); + other.remove(); + }); + + it("forgets an Escape-cancelled drag released outside the window", () => { + const onSelectItem = jest.fn(); + render([folder, item], { onDropNode, onSelectItem }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(itemRow); + move(60); + act(() => { + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + window.dispatchEvent(new Event("blur")); + }); + // A new press and click with the same mouse pointer id. + press(itemRow); + release(5); + act(() => { + itemRow.querySelector("button")!.click(); + }); + expect(onSelectItem).toHaveBeenCalledTimes(1); + }); + + it("never starts a drag from the checkbox or the menu button", () => { + render([folder, item], { onDropNode, allowMultiselect: true }); + const [, itemRow] = rows(); + act(() => { + itemRow + .querySelector("input")! + .dispatchEvent(pointer("pointerdown", 5, 5)); + }); + move(60); + expect(drag.node).toBeNull(); + }); + + it("drags by touch only after a press and hold, so swiping still scrolls", () => { + render([folder, item], { onDropNode }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(itemRow, "touch"); + move(80); + act(() => { + jest.advanceTimersByTime(500); + }); + expect(drag.node).toBeNull(); + press(itemRow, "touch"); + act(() => { + jest.advanceTimersByTime(500); + }); + expect(drag.node).toBe(item); + move(10); + release(10); + expect(onDropNode).toHaveBeenCalledWith(item, folder); + }); + + it("opens a closed folder after hovering over it while dragging", () => { + render([folder, item], { onDropNode }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(itemRow); + move(60); + move(10); + act(() => { + jest.advanceTimersByTime(800); + }); + expect(onExpand).toHaveBeenCalledWith("work", false); + release(10); + }); + + it("refuses a drop the vault would not allow", () => { + render([folder, item], { onDropNode, canDropNode: () => false }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(itemRow); + move(60); + move(10); + expect(folderRow.classList.contains("solovault-drop-over")).toBe(false); + release(10); + expect(onDropNode).not.toHaveBeenCalled(); + }); + + it("never drops a folder onto itself, and entries are not drop targets", () => { + render([folder, item], { onDropNode }); + const [folderRow, itemRow] = rows(); + layout([folderRow, itemRow]); + press(folderRow); + move(30); + move(10); + release(10); + press(folderRow); + move(60); + release(60); + expect(onDropNode).not.toHaveBeenCalled(); + }); + + it("does not drag rows where moving is not offered", () => { + render([folder, item], {}); + const [, itemRow] = rows(); + press(itemRow); + move(60); + expect(drag.node).toBeNull(); + release(60); + const readOnly = { + ...item, + share_rights: { read: true, write: true, grant: false, delete: false }, + }; + render([folder, readOnly as DatastoreTreeItemNode], { onDropNode }); + press(rows()[1]); + move(60); + expect(drag.node).toBeNull(); + release(60); + }); + + it("rejects shared folders, shared descendants, and sources without delete rights at drag start", () => { + const sharedFolder = { ...folder, id: "shared", share_id: "share" }; + const folderWithSharedChild = { + ...folder, + id: "parent", + folders: [{ ...otherFolder, share_id: "nested-share" }], + }; + const noDelete = { + ...item, + id: "readonly", + share_rights: { read: true, write: true, grant: true, delete: false }, + }; + render( + [sharedFolder, folderWithSharedChild, noDelete] as DatastoreTreeNode[], + { + onDropNode, + canDragNode: (node) => + node.is_folder ? isMovableFolder(node) : isMovableItem(node), + }, + ); + for (const row of rows()) { + press(row); + move(60); + expect(drag.node).toBeNull(); + release(60); + } + }); +}); diff --git a/src/js/components/datastore-tree/drag.ts b/src/js/components/datastore-tree/drag.ts new file mode 100644 index 0000000..ddbd5ea --- /dev/null +++ b/src/js/components/datastore-tree/drag.ts @@ -0,0 +1,314 @@ +// SoLoVault: drag and drop in the datastore tree. It uses pointer events, not +// the browser's own drag and drop, so it works the same with a mouse, a pen +// and touch (press and hold), in every browser, and leaves clicks, checkboxes +// and menus on the rows alone. The tree fields join the shared tree types +// here, so the upstream type files stay as they are. +import type React from "react"; +import type { + DatastoreTreeFolderNode, + DatastoreTreeNode, +} from "../../../types/datastore-ui"; + +/** The row being dragged, shared by every row of one tree. */ +export interface DatastoreTreeDrag { + node: DatastoreTreeNode | null; + setNode: (node: DatastoreTreeNode | null) => void; +} + +declare module "../../../types/datastore-ui" { + interface DatastoreTreeActions { + canDragNode?: (node: DatastoreTreeNode) => boolean; + // A null target is the top level. + canDropNode?: ( + node: DatastoreTreeNode, + target: DatastoreTreeFolderNode | null, + ) => boolean; + onDropNode?: ( + node: DatastoreTreeNode, + target: DatastoreTreeFolderNode | null, + ) => void; + } + interface DatastoreTreeListData { + drag: DatastoreTreeDrag; + } +} + +/** A place a row can be dropped: a folder, or null for the top level. */ +export interface DropTarget { + node: DatastoreTreeFolderNode | null; + open?: () => void; +} + +export interface PointerDragOptions { + node: DatastoreTreeNode; + canDrop: ( + node: DatastoreTreeNode, + target: DatastoreTreeFolderNode | null, + ) => boolean; + onDrop: ( + node: DatastoreTreeNode, + target: DatastoreTreeFolderNode | null, + ) => void; + onDragChange: (node: DatastoreTreeNode | null) => void; +} + +export const DROP_ATTRIBUTE = "data-solovault-drop"; +// Mouse and pen start dragging after this many pixels; touch after a hold. +const MOVE_THRESHOLD = 6; +const TOUCH_HOLD = 400; +const TOUCH_SLOP = 8; +// How long a dragged row waits over a closed folder before opening it. +const OPEN_FOLDER_DELAY = 700; +const EDGE = 48; +// A click on the dragged row that follows a drag must not open it. Touch +// browsers can send it a few hundred ms late; if none comes, clicks resume. +// Clicks anywhere else are never touched. +const CLICK_GRACE = 1000; + +function swallowNextClick(row: Element) { + let timer: number | undefined; + const swallow = (click: Event) => { + if (!row.contains(click.target as Node)) return; + click.preventDefault(); + click.stopPropagation(); + stop(); + }; + const stop = () => { + window.clearTimeout(timer); + window.removeEventListener("click", swallow, true); + }; + window.addEventListener("click", swallow, true); + timer = window.setTimeout(stop, CLICK_GRACE); +} + +const targets = new WeakMap(); + +/** A ref that makes an element a drop target. */ +export function dropTargetRef(target: DropTarget | null) { + return (element: HTMLElement | null) => { + if (!element) return; + if (target) { + targets.set(element, target); + element.setAttribute(DROP_ATTRIBUTE, ""); + } else { + targets.delete(element); + element.removeAttribute(DROP_ATTRIBUTE); + } + }; +} + +let styled = false; +function addStyles() { + if (styled || typeof document === "undefined") return; + styled = true; + const style = document.createElement("style"); + style.textContent = ` +.solovault-drop-over{border-radius:6px;box-shadow:inset 0 0 0 2px #d9232e!important;background-color:rgba(217,35,46,.06)!important} +body.solovault-dragging,body.solovault-dragging *{cursor:grabbing!important;user-select:none!important;-webkit-user-select:none!important} +.solovault-drag-ghost{position:fixed;z-index:2000;pointer-events:none;max-width:260px;padding:6px 10px;border:1px solid #e2e8f0;border-radius:6px;background:#fff;color:#0f172a;font:500 13px Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;box-shadow:0 8px 24px rgba(15,23,42,.15);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}`; + document.head.appendChild(style); +} + +function scroller(element: Element | null): HTMLElement | null { + for (let el = element?.parentElement; el; el = el.parentElement) { + const overflow = getComputedStyle(el).overflowY; + if ( + (overflow === "auto" || overflow === "scroll") && + el.scrollHeight > el.clientHeight + ) { + return el; + } + } + return null; +} + +/** Starts watching a press on a row; it becomes a drag once it moves (or is held, on touch). */ +export function beginPointerDrag( + event: React.PointerEvent, + options: PointerDragOptions, +) { + if (event.button !== 0 || !event.isPrimary) return; + // The checkbox, the gear menu and links keep working as before. + if ((event.target as Element).closest("input, a, [aria-label='settings']")) { + return; + } + addStyles(); + const { node } = options; + const pointerId = event.pointerId; + const touch = event.pointerType === "touch"; + const startX = event.clientX; + const startY = event.clientY; + const row = event.currentTarget as Element; + const list = scroller(row); + let x = startX; + let y = startY; + let active = false; + let ghost: HTMLElement | null = null; + let over: Element | null = null; + let overTarget: DropTarget | null = null; + let openTimer: number | undefined; + let frame: number | undefined; + const holdTimer = touch + ? window.setTimeout(() => activate(), TOUCH_HOLD) + : undefined; + + const valid = (target: DropTarget | undefined): target is DropTarget => + !!target && + (!target.node || + (target.node.id !== node.id && !target.node.path.includes(node.id))) && + options.canDrop(node, target.node); + + function setOver(element: Element | null, target: DropTarget | null) { + // A virtualized row element can be reused for another folder. + if (element === over && target === overTarget) return; + over?.classList.remove("solovault-drop-over"); + window.clearTimeout(openTimer); + over = element; + overTarget = target; + if (!element || !target) return; + element.classList.add("solovault-drop-over"); + if (target.open) { + const open = target.open; + openTimer = window.setTimeout(open, OPEN_FOLDER_DELAY); + } + } + + function hitTest() { + const element = + document.elementFromPoint(x, y)?.closest(`[${DROP_ATTRIBUTE}]`) ?? null; + const target = element ? targets.get(element) : undefined; + if (element && valid(target)) setOver(element, target); + else setOver(null, null); + } + + function autoScroll() { + frame = undefined; + if (!active || !list) return; + const box = list.getBoundingClientRect(); + const step = + y < box.top + EDGE + ? -Math.ceil((box.top + EDGE - y) / 4) + : y > box.bottom - EDGE + ? Math.ceil((y - box.bottom + EDGE) / 4) + : 0; + if (step) { + list.scrollTop += step; + hitTest(); + frame = window.requestAnimationFrame(autoScroll); + } + } + + function activate() { + if (active) return; + active = true; + document.body.classList.add("solovault-dragging"); + ghost = document.createElement("div"); + ghost.className = "solovault-drag-ghost"; + ghost.textContent = node.name || ""; + document.body.appendChild(ghost); + place(); + options.onDragChange(node); + if (touch && navigator.vibrate) navigator.vibrate(10); + } + + function place() { + if (!ghost) return; + ghost.style.left = `${x + 14}px`; + ghost.style.top = `${y + 10}px`; + } + + function onMove(e: PointerEvent) { + if (e.pointerId !== pointerId) return; + x = e.clientX; + y = e.clientY; + const moved = Math.hypot(x - startX, y - startY); + if (!active) { + if (touch) { + // Moving before the hold ends is a scroll, not a drag. + if (moved > TOUCH_SLOP) finish(); + return; + } + if (moved < MOVE_THRESHOLD) return; + activate(); + } + e.preventDefault(); + place(); + hitTest(); + if (frame === undefined) frame = window.requestAnimationFrame(autoScroll); + } + + function onUp(e: PointerEvent) { + if (e.pointerId !== pointerId) return; + if (active) { + x = e.clientX; + y = e.clientY; + hitTest(); + } + const target = active ? overTarget : null; + const dragged = active; + finish(); + if (!dragged) return; + swallowNextClick(row); + if (target) options.onDrop(node, target.node); + } + + function onKey(e: KeyboardEvent) { + if (e.key !== "Escape") return; + const dragged = active; + finish(); + if (!dragged) return; + // Cancelled: releasing the button afterwards must not open the row. + // A release the page never sees (outside the window) ends with the + // next press or when the window loses focus. + const release = (e: PointerEvent) => { + if (e.pointerId !== pointerId) return; + stop(); + if (e.type === "pointerup") swallowNextClick(row); + }; + const stop = () => { + window.removeEventListener("pointerup", release, true); + window.removeEventListener("pointercancel", release, true); + window.removeEventListener("pointerdown", stop, true); + window.removeEventListener("blur", stop); + }; + window.addEventListener("pointerup", release, true); + window.addEventListener("pointercancel", release, true); + window.addEventListener("pointerdown", stop, true); + window.addEventListener("blur", stop); + } + + // While dragging by touch, the page must not scroll or open a menu. + function stopTouch(e: Event) { + if (active) e.preventDefault(); + } + function stopMenu(e: Event) { + if (active || touch) e.preventDefault(); + } + + function finish() { + window.clearTimeout(holdTimer); + window.clearTimeout(openTimer); + if (frame !== undefined) window.cancelAnimationFrame(frame); + over?.classList.remove("solovault-drop-over"); + ghost?.remove(); + document.body.classList.remove("solovault-dragging"); + window.removeEventListener("pointermove", onMove, true); + window.removeEventListener("pointerup", onUp, true); + window.removeEventListener("pointercancel", finish, true); + window.removeEventListener("keydown", onKey, true); + document.removeEventListener("touchmove", stopTouch); + window.setTimeout( + () => document.removeEventListener("contextmenu", stopMenu, true), + 0, + ); + if (active) options.onDragChange(null); + active = false; + } + + window.addEventListener("pointermove", onMove, true); + window.addEventListener("pointerup", onUp, true); + window.addEventListener("pointercancel", finish, true); + window.addEventListener("keydown", onKey, true); + document.addEventListener("touchmove", stopTouch, { passive: false }); + document.addEventListener("contextmenu", stopMenu, true); +} diff --git a/src/js/components/datastore-tree/index.tsx b/src/js/components/datastore-tree/index.tsx index 416d35d..1ba54ed 100644 --- a/src/js/components/datastore-tree/index.tsx +++ b/src/js/components/datastore-tree/index.tsx @@ -19,6 +19,8 @@ import type { DatastoreTreeNode, DatastoreTreeListData, } from "../../../types/datastore-ui"; +import { dropTargetRef, type DatastoreTreeDrag } from "./drag"; +import "./select"; import datastorePassword from "../../services/datastore-password"; import deviceService from "../../services/device"; import offlineCache from "../../services/offline-cache"; @@ -151,6 +153,28 @@ const useStyles = makeStyles((theme) => ({ height: deviceService.hasTitlebar() ? "calc(100vh - 232px)" : "calc(100vh - 200px)", + // SoLoVault: room for the top-level drop zone above the list. + display: "flex", + flexDirection: "column", + }, + treeList: { + flex: 1, + minHeight: 0, + }, + rootDropZone: { + flex: "none", + display: "flex", + alignItems: "center", + gap: "8px", + height: "40px", + margin: "2px 0 4px", + padding: "0 12px", + boxSizing: "border-box", + border: "1px dashed #cbd5e1", + borderRadius: "6px", + backgroundColor: "#f8fafc", + color: "#64748b", + fontSize: "13px", }, })); @@ -170,6 +194,30 @@ const DatastoreTree = (props: DatastoreTreeProps) => { const [searchCollapsedFolders, setSearchCollapsedFolders] = React.useState< Record >({}); + // SoLoVault: the row being dragged (drag.ts). The state shows the + // top-level drop zone. + const draggedRef = React.useRef(null); + const [dragged, setDragged] = React.useState(null); + const drag: DatastoreTreeDrag = { + get node() { + return draggedRef.current; + }, + setNode: (node) => { + draggedRef.current = node; + setDragged(node); + }, + }; + // SoLoVault: where a Shift+click range starts (select.ts). + const selectAnchor = React.useRef(null); + // A new selection never ranges from a row picked in an earlier one. + React.useEffect(() => { + if (!props.allowMultiselect) selectAnchor.current = null; + }, [props.allowMultiselect]); + const rootTarget = React.useMemo(() => ({ node: null }), []); + const canDropOnRoot = + !!dragged && + !!props.onDropNode && + (!props.canDropNode || props.canDropNode(dragged, null)); const getIsExpandedFolder = (folder: Datastore) => { if (folder.datastore_id) return true; @@ -527,6 +575,16 @@ const DatastoreTree = (props: DatastoreTreeProps) => { } else { return (
+ {canDropOnRoot && ( +
+ + Drop here to move to the top level +
+ )} +
{({ height, width }: { height: number; width: number }) => ( @@ -541,12 +599,15 @@ const DatastoreTree = (props: DatastoreTreeProps) => { items: datastoreItems, getIsExpandedFolder, onUpdateExpandFolderProperty, + drag, + selectAnchor, }} > {DatastoreTreeVirtualElement} )} +
); } diff --git a/src/js/components/datastore-tree/select.test.tsx b/src/js/components/datastore-tree/select.test.tsx new file mode 100644 index 0000000..2b23fbf --- /dev/null +++ b/src/js/components/datastore-tree/select.test.tsx @@ -0,0 +1,334 @@ +import { createTheme, ThemeProvider } from "@mui/material/styles"; +import React from "react"; +import ReactDOM from "react-dom"; +import { act } from "react-dom/test-utils"; +import type { Datastore } from "../../../types/datastore"; +import type { + DatastoreTreeActions, + DatastoreTreeFolderNode, + DatastoreTreeItemNode, + DatastoreTreeNode, +} from "../../../types/datastore-ui"; +import DatastoreTree from "./index"; +import DatastoreTreeVirtualElement from "./datastore-tree-virtual-element"; +import type { DatastoreTreeDrag } from "./drag"; + +jest.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), + Trans: ({ children }: { children: React.ReactNode }) => children, + initReactI18next: { type: "3rdParty", init: () => {} }, +})); +jest.mock("../../services/store", () => ({ + getStore: () => ({ getState: () => ({ server: {}, client: {}, user: {} }) }), +})); +jest.mock("../../services/secret", () => ({ __esModule: true, default: {} })); +jest.mock("../entry-icon", () => ({ __esModule: true, default: () => null })); +jest.mock("../gateway-launch-button", () => ({ + __esModule: true, + default: () => null, +})); + +jest.mock("react-router-dom", () => ({ + useHistory: () => ({ push: () => {} }), +})); +jest.mock("react-virtualized-auto-sizer", () => ({ + __esModule: true, + default: ({ + children, + }: { + children: (size: { height: number; width: number }) => React.ReactNode; + }) => children({ height: 600, width: 600 }), +})); + +// SoLoVault: File Explorer-style selecting. Synthetic rows only. + +// Each test starts well after the last one's clicks, so none reads as the +// second half of a double-click. +let clock = 0; +beforeEach(() => { + clock += 60_000; + jest.spyOn(Date, "now").mockImplementation(() => clock); +}); +afterEach(() => { + jest.restoreAllMocks(); +}); +const folder: DatastoreTreeFolderNode = { + id: "work", + name: "Work", + path: ["work"], + is_folder: true, +}; +const otherFolder: DatastoreTreeFolderNode = { + id: "home", + name: "Home", + path: ["home"], + is_folder: true, +}; +const entry = (id: string): DatastoreTreeItemNode => ({ + id, + name: `Example ${id}`, + path: [id], + is_folder: false, + type: "website_password", + secret_id: `secret-${id}`, +}); +const [first, second, third] = ["first", "second", "third"].map(entry); +const datastore = { + folders: [folder, otherFolder], + items: [first, second, third], +} as unknown as Datastore; +const theme = createTheme({ + palette: { + blueBackground: { main: "#eee" }, + lightBackground: { main: "#fff" }, + greyText: { main: "#888" }, + }, +}); + +describe("Datastore tree selecting", () => { + let container: HTMLDivElement; + const onSelectRows = jest.fn(); + const onSelectItem = jest.fn(); + const onEditEntry = jest.fn(); + const drag: DatastoreTreeDrag = { node: null, setNode: () => {} }; + const rows: DatastoreTreeNode[] = [folder, first, second, third]; + beforeEach(() => { + jest.clearAllMocks(); + container = document.createElement("div"); + document.body.appendChild(container); + }); + afterEach(() => { + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + container.remove(); + }); + function render(actions: DatastoreTreeActions = {}) { + const selectAnchor = { current: null as string | null }; + act(() => { + ReactDOM.render( + + {rows.map((row, index) => ( + {}, + onSelectRows, + onSelectItem, + onEditEntry, + allowMultiselect: true, + ...actions, + }, + offline: false, + datastore, + getIsExpandedFolder: () => false, + onUpdateExpandFolderProperty: () => {}, + drag, + selectAnchor, + }} + /> + ))} + , + container + ); + }); + } + function rowName(index: number) { + return container + .querySelectorAll("[class*='virtualizedElement']") + [index].querySelector("button")!; + } + function click(target: Element, modifiers: MouseEventInit = {}) { + act(() => { + target.dispatchEvent( + new MouseEvent("click", { + bubbles: true, + cancelable: true, + ...modifiers, + }) + ); + }); + } + + it("toggles one row with Ctrl+click or Cmd+click, without opening it", () => { + render(); + click(rowName(1), { ctrlKey: true }); + click(rowName(3), { metaKey: true }); + expect(onSelectRows.mock.calls).toEqual([ + [[first], false, false], + [[third], false, false], + ]); + expect(onEditEntry).not.toHaveBeenCalled(); + }); + + it("selects the rows between the last click and a Shift+click", () => { + render(); + click(rowName(3), { ctrlKey: true }); + click(rowName(1), { shiftKey: true }); + expect(onSelectRows).toHaveBeenLastCalledWith([first, second, third], true); + }); + + it("starts a Shift+click range at a ticked checkbox, which ticks only itself", () => { + render(); + const box = container.querySelectorAll("input")[1]; + click(box, { shiftKey: true }); + expect(onSelectRows).not.toHaveBeenCalled(); + expect(onSelectItem).toHaveBeenCalledWith( + first, + first.path, + expect.anything() + ); + click(rowName(2), { shiftKey: true }); + expect(onSelectRows).toHaveBeenLastCalledWith([first, second], true); + }); + + it("selects just the clicked entry, which shows the checkboxes", () => { + render({ allowMultiselect: false }); + click(rowName(2), { detail: 1 }); + expect(onSelectRows).toHaveBeenCalledWith([second], false, true); + expect(onEditEntry).not.toHaveBeenCalled(); + expect(onSelectItem).not.toHaveBeenCalled(); + }); + + it("opens an entry on a double-click", () => { + render(); + click(rowName(2), { detail: 1 }); + click(rowName(2), { detail: 2 }); + expect(onSelectRows).toHaveBeenCalledTimes(1); + expect(onEditEntry).toHaveBeenCalledTimes(1); + }); + + it("opens an entry on a double-tap reported as two single clicks", () => { + render(); + click(rowName(2), { detail: 1 }); + clock += 300; + click(rowName(2), { detail: 1 }); + expect(onEditEntry).toHaveBeenCalledTimes(1); + // Slower clicks select it again instead. + clock += 1000; + click(rowName(2), { detail: 1 }); + expect(onSelectRows).toHaveBeenCalledTimes(2); + expect(onEditEntry).toHaveBeenCalledTimes(1); + }); + + it("opens the entry when the second click lands on the checkbox that just appeared", () => { + render(); + click(rowName(2), { detail: 1 }); + const box = container.querySelectorAll("input")[2] as HTMLInputElement; + click(box, { detail: 2 }); + expect(onEditEntry).toHaveBeenCalledTimes(1); + expect(onSelectItem).not.toHaveBeenCalled(); + // Later, the checkbox ticks the row as before. + clock += 1000; + click(box, { detail: 1 }); + expect(onSelectItem).toHaveBeenCalledTimes(1); + expect(onEditEntry).toHaveBeenCalledTimes(1); + }); + + it("opens folders on a plain click", () => { + render(); + click(rowName(0), { detail: 1 }); + expect(onSelectRows).not.toHaveBeenCalled(); + }); + + it("opens an entry with Enter and leaves the row's menu alone", () => { + render(); + // A keyboard click has no pointer (detail 0). + click(rowName(2)); + expect(onEditEntry).toHaveBeenCalledTimes(1); + const settings = container + .querySelectorAll("[class*='virtualizedElement']")[2] + .querySelector("[aria-label='settings']")!; + click(settings, { ctrlKey: true }); + expect(onSelectRows).not.toHaveBeenCalled(); + }); + + it("selects entries with a plain click while the Select button is on, and still opens folders", () => { + render({ selectRowsOnClick: true }); + click(rowName(2)); + expect(onSelectRows).toHaveBeenCalledWith([second], false, false); + expect(onEditEntry).not.toHaveBeenCalled(); + click(rowName(0), { detail: 1 }); + expect(onSelectRows).toHaveBeenCalledTimes(1); + }); +}); + +describe("Datastore tree selecting, through the whole tree", () => { + let container: HTMLDivElement; + const onSelectRows = jest.fn(); + const tree = { + datastore_id: "store", + folders: [], + items: [first, second, third], + } as unknown as Datastore; + beforeEach(() => { + jest.clearAllMocks(); + container = document.createElement("div"); + document.body.appendChild(container); + }); + afterEach(() => { + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + container.remove(); + }); + function render(allowMultiselect: boolean) { + act(() => { + ReactDOM.render( + + {}} + onSelectRows={onSelectRows} + onSelectItem={() => {}} + onEditEntry={() => {}} + allowMultiselect={allowMultiselect} + selectRowsOnClick={allowMultiselect} + /> + , + container + ); + }); + } + function rowName(name: string) { + return Array.from(container.querySelectorAll("button")).find((button) => + button.getAttribute("aria-label")?.startsWith(name) + )!; + } + function click(target: Element, modifiers: MouseEventInit = {}) { + act(() => { + target.dispatchEvent( + new MouseEvent("click", { + bubbles: true, + cancelable: true, + ...modifiers, + }) + ); + }); + } + + it("ranges from the last click while selecting", () => { + render(true); + click(rowName("Example first")); + click(rowName("Example third"), { shiftKey: true }); + expect(onSelectRows.mock.calls).toEqual([ + [[first], false, false], + [[first, second, third], true], + ]); + }); + + it("starts a fresh selection without the old range start", () => { + render(true); + click(rowName("Example first")); + // Done, then Select again: nothing is selected any more. + render(false); + render(true); + click(rowName("Example third"), { shiftKey: true }); + expect(onSelectRows).toHaveBeenLastCalledWith([third], false, false); + }); +}); diff --git a/src/js/components/datastore-tree/select.ts b/src/js/components/datastore-tree/select.ts new file mode 100644 index 0000000..ced6ace --- /dev/null +++ b/src/js/components/datastore-tree/select.ts @@ -0,0 +1,132 @@ +// SoLoVault: select rows the way File Explorer does. A click or tap on an +// entry selects just that entry and shows the checkboxes; a double-click, +// double-tap or Enter opens it; folders still open on a click. Ctrl+click +// (Cmd+click on a Mac) adds or removes one row, Shift+click adds every row from +// the last one clicked. With the toolbar's Select button on, a tap adds or +// removes the entry instead. The checkboxes keep working as before. The tree +// fields join the shared tree types here, so the upstream type files stay as +// they are. +import type React from "react"; +import type { + DatastoreTreeActions, + DatastoreTreeNode, +} from "../../../types/datastore-ui"; + +declare module "../../../types/datastore-ui" { + interface DatastoreTreeActions { + // range: Shift+click, add the rows; only: a plain click, select just + // these rows; otherwise toggle the one row. + onSelectRows?: ( + nodes: DatastoreTreeNode[], + range: boolean, + only?: boolean + ) => void; + // A plain click on an entry toggles it (the Select button is on). + selectRowsOnClick?: boolean; + } + interface DatastoreTreeListData { + // The id of the row a Shift+click range starts from. + selectAnchor?: { current: string | null }; + } +} + +/** The row's own checkbox, or null when the click was elsewhere. */ +function checkboxOf(row: Element, target: Element) { + const input = target.closest("input[type='checkbox']"); + return input && row.contains(input) ? input : null; +} + +/** True for a click on the row's name or icon. */ +function onRowName(row: Element, target: Element) { + return target.closest("button") === row.querySelector("button"); +} + +// Some touch browsers report each tap of a double-tap as a single click. +const DOUBLE_CLICK_MS = 500; +let lastClick: { id: string; at: number } | null = null; + +let opening = false; + +/** True soon after a plain click on the same row's name. */ +function followsClick(id: string) { + return lastClick?.id === id && Date.now() - lastClick.at < DOUBLE_CLICK_MS; +} + +/** True for the second click of a double-click or double-tap on the row. */ +function isDoubleClick(event: React.MouseEvent, id: string) { + const repeat = event.detail >= 2 || followsClick(id); + lastClick = repeat ? null : { id, at: Date.now() }; + return repeat; +} + +/** Opens the row's entry or folder, as a plain click on its name did before. */ +function openRow(row: Element) { + opening = true; + try { + row.querySelector("button")?.click(); + } finally { + opening = false; + } +} + +/** + * Handles a click on a row before the row sees it. Returns true when it was a + * selection click, which then neither opens the entry nor expands the folder. + */ +export function handleSelectClick( + event: React.MouseEvent, + options: { + items: readonly DatastoreTreeNode[]; + index: number; + anchor: { current: string | null } | undefined; + onSelectRows: DatastoreTreeActions["onSelectRows"]; + selectOnClick?: boolean; + } +): boolean { + const { items, index, anchor, onSelectRows, selectOnClick } = options; + const row = event.currentTarget as Element; + const target = event.target as Element; + if (opening || !onSelectRows || !anchor || event.button !== 0) return false; + const node = items[index]; + if (checkboxOf(row, target)) { + // The first click of a double-click showed the checkboxes, which moved + // the name over: the second one lands here and still opens the entry. + if (followsClick(node.id)) { + lastClick = null; + event.preventDefault(); + event.stopPropagation(); + openRow(row); + return true; + } + // A checkbox ticks only its own row, with or without Shift held, as it + // always has; the next Shift+click range starts there. + lastClick = null; + anchor.current = node.id; + return false; + } + if (!onRowName(row, target)) return false; + const toggle = event.ctrlKey || event.metaKey; + const plain = !toggle && !event.shiftKey; + // Enter (a click with no pointer), folders and double-clicks open the + // entry or folder, as a plain click did before. + if (plain && !selectOnClick && event.detail === 0) return false; + if (plain && (node.is_folder || isDoubleClick(event, node.id))) return false; + const from = anchor.current + ? items.findIndex((item) => item.id === anchor.current) + : -1; + event.preventDefault(); + event.stopPropagation(); + if (event.shiftKey && !toggle && from !== -1) { + const [start, end] = from < index ? [from, index] : [index, from]; + onSelectRows(items.slice(start, end + 1), true); + } else { + anchor.current = node.id; + onSelectRows([node], false, plain && !selectOnClick); + } + return true; +} + +/** Shift+click would otherwise highlight the text between the two clicks. */ +export function keepTextUnselected(event: React.MouseEvent) { + if (event.shiftKey && event.button === 0) event.preventDefault(); +} diff --git a/src/js/components/dialogs/edit-entry.tsx b/src/js/components/dialogs/edit-entry.tsx index b48b3bb..6993753 100644 --- a/src/js/components/dialogs/edit-entry.tsx +++ b/src/js/components/dialogs/edit-entry.tsx @@ -72,6 +72,7 @@ import notification from "../../services/notification"; import offlineCache from "../../services/offline-cache"; import { getPasskeyUrl } from "../../services/passkey-url"; import secretService from "../../services/secret"; +import openEntry from "../open-entry"; import { getStore } from "../../services/store"; import ConnectionEntryFields from "../connection-entry-fields"; import GatewayLaunchButton from "../gateway-launch-button"; @@ -510,7 +511,7 @@ const DialogEditEntry = (props: DialogEditEntryProps) => { useHotkeys("alt+u", () => { // open url - secretService.onItemClick(item as SecretReference); + openEntry(item as SecretReference); }); useHotkeys("alt+shift+u", () => { @@ -1747,7 +1748,7 @@ const DialogEditEntry = (props: DialogEditEntryProps) => { const linkItem = (event: React.MouseEvent) => { event.stopPropagation(); - secretService.onItemClick(item as SecretReference); + openEntry(item as SecretReference); }; const onLinkShare = () => { diff --git a/src/js/components/dialogs/progress.test.tsx b/src/js/components/dialogs/progress.test.tsx new file mode 100644 index 0000000..a4c5ab4 --- /dev/null +++ b/src/js/components/dialogs/progress.test.tsx @@ -0,0 +1,216 @@ +// biome-ignore lint/correctness/noUnusedImports: this test uses the classic JSX transform. +import React from "react"; +import ReactDOM from "react-dom"; +import { act } from "react-dom/test-utils"; +import DialogProgress, { + BackgroundProgress, + beginBackgroundOperation, + dismissBackgroundProgress, + reportBackgroundProgress, + runBackgroundBatch, + useBackgroundOperationPending, +} from "./progress"; + +const PendingProbe = () => ( + +); + +// SoLoVault: progress shows as a card that does not block the page. +describe("Background progress", () => { + let container: HTMLDivElement; + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + }); + afterEach(() => { + act(() => { + ReactDOM.unmountComponentAtNode(container); + reportBackgroundProgress(100); + }); + container.remove(); + }); + + it("guards the tab synchronously at 0% until a pending operation settles", () => { + act(() => { + ReactDOM.render(, container); + }); + let operation!: ReturnType; + act(() => { + operation = beginBackgroundOperation("Moving 1 item"); + }); + const pendingAtZero = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(pendingAtZero); + expect(pendingAtZero.defaultPrevented).toBe(true); + expect(container.textContent).toContain("Moving 1 item"); + + act(() => operation.report(100)); + const pendingAtOneHundred = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(pendingAtOneHundred); + expect(pendingAtOneHundred.defaultPrevented).toBe(true); + + act(() => operation.finish("success", "Moved 1 item")); + const settled = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(settled); + expect(settled.defaultPrevented).toBe(false); + expect(container.textContent).toContain("Moved 1 item"); + }); + + it("keeps global pending state across page mounts until true completion", () => { + const operation = beginBackgroundOperation("Emptying trash"); + act(() => { + ReactDOM.render(, container); + }); + expect(container.firstElementChild?.getAttribute("data-pending")).toBe("yes"); + + act(() => { + ReactDOM.unmountComponentAtNode(container); + ReactDOM.render(, container); + operation.report(100); + }); + expect(container.firstElementChild?.getAttribute("data-pending")).toBe("yes"); + + act(() => operation.finish("failure", "Trash state is uncertain")); + expect(container.firstElementChild?.getAttribute("data-pending")).toBe("no"); + }); + + it("reports a rejected second request as partial and permits a later batch", async () => { + act(() => { + ReactDOM.render(, container); + }); + const calls: string[] = []; + let result!: Awaited>>; + await act(async () => { + result = await runBackgroundBatch({ + items: ["first", "second", "third"], + runningMessage: "Moving 3 items", + successMessage: "Moved 3 items", + item: async (item) => { + calls.push(item); + if (item === "second") throw new Error("synthetic rejection"); + }, + }); + }); + expect(result.outcome).toBe("partial"); + expect(result.completed).toEqual(["first"]); + expect(result.remaining).toEqual(["second", "third"]); + expect(calls).toEqual(["first", "second"]); + expect(container.textContent).toContain("1 of 3 completed; 2 remaining"); + + await act(async () => { + result = await runBackgroundBatch({ + items: ["later"], + runningMessage: "Moving 1 item", + successMessage: "Moved 1 item", + item: async () => {}, + }); + }); + expect(result.outcome).toBe("success"); + expect(container.textContent).toContain("Moved 1 item"); + }); + + it("treats a falsy rejection reason as failure", async () => { + let result!: Awaited>>; + await act(async () => { + result = await runBackgroundBatch({ + items: ["item"], + runningMessage: "Moving 1 item", + successMessage: "Moved 1 item", + item: () => Promise.reject(undefined), + }); + }); + expect(result.outcome).toBe("failure"); + expect(result.completed).toEqual([]); + expect(result.remaining).toEqual(["item"]); + }); + + it("rejects an overlapping batch without replacing the active status", async () => { + act(() => { + ReactDOM.render(, container); + }); + let resolve!: () => void; + const pending = new Promise((done) => { + resolve = done; + }); + let first!: ReturnType>; + act(() => { + first = runBackgroundBatch({ + items: ["first"], + runningMessage: "First operation", + successMessage: "First completed", + item: () => pending, + }); + }); + let competing!: Awaited>>; + await act(async () => { + competing = await runBackgroundBatch({ + items: ["second"], + runningMessage: "Second operation", + successMessage: "Second completed", + item: async () => {}, + }); + }); + expect(competing.outcome).toBe("failure"); + expect(competing.remaining).toEqual(["second"]); + expect(container.textContent).toContain("First operation"); + expect(container.textContent).not.toContain("Second operation"); + expect(container.textContent).toContain( + "Another vault operation is already running", + ); + act(() => dismissBackgroundProgress()); + expect(container.textContent).toContain("First operation"); + await act(async () => { + resolve(); + await first; + }); + }); + + it("dismisses a settled card without affecting the next operation", () => { + act(() => { + ReactDOM.render(, container); + const operation = beginBackgroundOperation("First operation"); + operation.finish("success", "First completed"); + }); + expect(container.textContent).toContain("First completed"); + act(() => dismissBackgroundProgress()); + expect(container.querySelector('[role="status"]')).toBeNull(); + + let next!: ReturnType; + act(() => { + next = beginBackgroundOperation("Next operation"); + }); + expect(container.textContent).toContain("Next operation"); + act(() => next.finish("success", "Next completed")); + }); + + it("shows a non-blocking card while work runs and warns before the tab closes", () => { + act(() => { + ReactDOM.render(, container); + }); + expect(container.querySelector('[role="status"]')).toBeNull(); + act(() => reportBackgroundProgress(40)); + const card = container.querySelector('[role="status"]'); + expect(card?.textContent).toContain("Working in the background · 40%"); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + const event = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + act(() => reportBackgroundProgress(100)); + expect(container.textContent).toContain("Vault operation completed"); + const after = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(after); + expect(after.defaultPrevented).toBe(false); + }); + + it("keeps showing progress on the next page after the first one closes", () => { + act(() => { + ReactDOM.render( + , + container, + ); + }); + act(() => { + ReactDOM.render(, container); + }); + expect(container.textContent).toContain("30%"); + }); +}); diff --git a/src/js/components/dialogs/progress.tsx b/src/js/components/dialogs/progress.tsx index 2d0bedc..ae76763 100644 --- a/src/js/components/dialogs/progress.tsx +++ b/src/js/components/dialogs/progress.tsx @@ -1,6 +0,0 @@ -import { Grid } from "@mui/material"; -import MuiAlert from "@mui/material/Alert"; -import Box from "@mui/material/Box"; -import Dialog from "@mui/material/Dialog"; -import DialogContent from "@mui/material/DialogContent"; -import DialogTitle from "@mui/material/DialogTitle"; @@ -7,0 +2,2 @@ import LinearProgress from "@mui/material/LinearProgress"; +import Paper from "@mui/material/Paper"; +import Typography from "@mui/material/Typography"; @@ -9 +4,0 @@ import React from "react"; -import { useTranslation } from "react-i18next"; @@ -16,3 +11,147 @@ export interface DialogProgressProps { -const DialogProgress = (props: DialogProgressProps) => { - const { open, percentageComplete } = props; - const { t } = useTranslation(); +// SoLoVault: long operations (moving, deleting, emptying the trash) run in the +// background instead of behind a blocking dialog, so people can keep working +// and move to other pages. Progress lives here, outside any one page, and +// every page shows it (BackgroundProgress in base.tsx). The work happens in +// this browser, because only it holds the keys, so closing the tab asks first. +export type BackgroundOutcome = "success" | "failure" | "partial"; +type BackgroundState = { + id: number; + phase: "idle" | "pending" | BackgroundOutcome; + percent: number; + message: string; + notice?: string; +}; + +let state: BackgroundState = { + id: 0, + phase: "idle", + percent: 0, + message: "", +}; +let nextId = 1; +let activeId: number | null = null; +let legacyOperation: BackgroundOperation | null = null; +const listeners = new Set<(value: BackgroundState) => void>(); +const warnBeforeUnload = (event: BeforeUnloadEvent) => { + event.preventDefault(); + event.returnValue = ""; +}; + +const publish = (next: BackgroundState) => { + state = next; + listeners.forEach((listener) => { + listener(next); + }); +}; + +export interface BackgroundOperation { + id: number; + report: (value: number) => void; + finish: (outcome: BackgroundOutcome, message: string) => void; +} + +export interface BackgroundBatchResult { + outcome: BackgroundOutcome; + completed: T[]; + remaining: T[]; + error?: unknown; +} + +export async function runBackgroundBatch(options: { + items: readonly T[]; + runningMessage: string; + successMessage: string; + item: (value: T, index: number) => Promise; + onItemComplete?: (value: T, index: number) => void; +}): Promise> { + let operation: BackgroundOperation; + try { + operation = beginBackgroundOperation(options.runningMessage); + } catch (error) { + return { + outcome: "failure", + completed: [], + remaining: options.items.slice(), + error, + }; + } + const completed: T[] = []; + let error: unknown; + let failed = false; + let result!: BackgroundBatchResult; + try { + for (let index = 0; index < options.items.length; index++) { + const value = options.items[index]; + await options.item(value, index); + completed.push(value); + options.onItemComplete?.(value, index); + operation.report(((index + 1) / options.items.length) * 100); + } + } catch (caught) { + failed = true; + error = caught; + } finally { + const remaining = options.items.slice(completed.length); + const outcome: BackgroundOutcome = failed + ? completed.length > 0 + ? "partial" + : "failure" + : "success"; + const message = failed + ? completed.length > 0 + ? `${completed.length} of ${options.items.length} completed; ${remaining.length} remaining` + : `Could not complete ${options.runningMessage.toLowerCase()}` + : options.successMessage; + operation.finish(outcome, message); + result = { outcome, completed, remaining, error }; + } + return result; +} + +export function beginBackgroundOperation(message: string): BackgroundOperation { + if (activeId !== null) { + publish({ + ...state, + notice: + "Another vault operation is already running. Wait for it to finish before trying again.", + }); + throw new Error("Another vault operation is already running."); + } + const id = nextId++; + activeId = id; + window.addEventListener("beforeunload", warnBeforeUnload); + publish({ id, phase: "pending", percent: 0, message, notice: undefined }); + return { + id, + report(value) { + if (activeId !== id) return; + publish({ ...state, percent: Math.max(0, Math.min(100, value)) }); + }, + finish(outcome, message) { + if (activeId !== id) return; + activeId = null; + window.removeEventListener("beforeunload", warnBeforeUnload); + publish({ ...state, phase: outcome, message }); + }, + }; +} + +export function dismissBackgroundProgress() { + if (activeId !== null || state.phase === "idle") return; + publish({ id: state.id, phase: "idle", percent: 0, message: "" }); +} + +export function useBackgroundOperationPending() { + const [pending, setPending] = React.useState(state.phase === "pending"); + React.useEffect(() => { + const update = (value: BackgroundState) => { + setPending(value.phase === "pending"); + }; + listeners.add(update); + update(state); + return () => { + listeners.delete(update); + }; + }, []); + return pending; +} @@ -19,0 +159,26 @@ const DialogProgress = (props: DialogProgressProps) => { +export function reportBackgroundProgress(value: number) { + if (activeId !== null) { + publish({ ...state, percent: value }); + if (value === 100 && legacyOperation?.id === activeId) { + legacyOperation.finish("success", "Vault operation completed"); + legacyOperation = null; + } + } else if (value < 100) { + legacyOperation = beginBackgroundOperation("Vault operation in progress"); + legacyOperation.report(value); + } else if (value === 100) { + publish({ id: state.id, phase: "idle", percent: 0, message: "" }); + } +} + +export const BackgroundProgress = () => { + const [value, setValue] = React.useState(state); + React.useEffect(() => { + listeners.add(setValue); + setValue(state); + return () => { + listeners.delete(setValue); + }; + }, []); + if (value.phase === "idle") return null; + const running = value.phase === "pending"; @@ -21,6 +186,17 @@ const DialogProgress = (props: DialogProgressProps) => { - { - - {t("OPERATION_IN_PROGRESS")} - - - - - - {t("OPERATION_IN_PROGRESS_PLEASE_WAIT")} - - - - - - - - - - {percentageComplete} % - - - - - - - + {value.notice && ( + + {value.notice} + + )} + + {value.message} + + + {running + ? `Working in the background · ${Math.round(value.percent)}%. Keep this tab open until it finishes.` + : value.phase === "success" + ? "Completed successfully." + : value.phase === "partial" + ? "The operation stopped before completion. Refresh and review the affected items before retrying." + : "The operation could not be confirmed. Refresh and review the affected items before retrying."} + + {running && ( + + )} + {!running && ( + + )} + @@ -70,0 +242,10 @@ const DialogProgress = (props: DialogProgressProps) => { +// Kept for the places that showed the old blocking dialog: they now report to +// the background card instead. +const DialogProgress = (props: DialogProgressProps) => { + const { open, percentageComplete } = props; + React.useEffect(() => { + reportBackgroundProgress(open ? percentageComplete : 100); + }, [open, percentageComplete]); + return null; +}; + diff --git a/src/js/components/dialogs/trash-bin.test.tsx b/src/js/components/dialogs/trash-bin.test.tsx new file mode 100644 index 0000000..f9774eb --- /dev/null +++ b/src/js/components/dialogs/trash-bin.test.tsx @@ -0,0 +1,158 @@ +import React from "react"; +import ReactDOM from "react-dom"; +import { act } from "react-dom/test-utils"; +import type { Datastore } from "../../../types/datastore"; +import widgetService from "../../services/widget"; +import DialogTrashBin, { deleteTrashEntryInBackground } from "./trash-bin"; +import { BackgroundProgress, reportBackgroundProgress } from "./progress"; + +jest.mock("../../services/widget", () => ({ + __esModule: true, + default: { deleteItemPermanent: jest.fn() }, +})); +jest.mock("../../services/datastore-password", () => ({ + __esModule: true, + default: { + getFolderPath: () => "Vault", + abbreviateFolderPath: (value: string) => value, + }, +})); +jest.mock("../../services/helper", () => ({ + __esModule: true, + default: { duplicateObject: (value: unknown) => structuredClone(value) }, +})); +jest.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); +jest.mock("../table", () => ({ __esModule: true, default: () => null })); +jest.mock("../button-danger", () => ({ + __esModule: true, + default: (props: React.ButtonHTMLAttributes) => ( + : null, +})); + +const deferred = () => { + let resolve!: () => void; + let reject!: (reason: Error) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +}; + +const datastore = (ids: string[]): Datastore => + ({ + id: "vault", + folders: [], + items: ids.map((id) => ({ + id, + name: id, + deleted: true, + share_rights: { read: true, write: true, grant: true, delete: true }, + })), + }) as unknown as Datastore; + +describe("Trash background deletion", () => { + const mockDeleteItemPermanent = + widgetService.deleteItemPermanent as jest.MockedFunction< + typeof widgetService.deleteItemPermanent + >; + let container: HTMLDivElement; + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + mockDeleteItemPermanent.mockReset(); + }); + afterEach(() => { + act(() => { + ReactDOM.unmountComponentAtNode(container); + reportBackgroundProgress(100); + }); + container.remove(); + }); + + it("survives dialog unmount, reports a rejected second deletion, and recovers", async () => { + const first = deferred(); + mockDeleteItemPermanent + .mockReturnValueOnce(first.promise) + .mockRejectedValueOnce(new Error("synthetic rejection")); + const onClose = jest.fn(() => { + act(() => { + ReactDOM.render(, container); + }); + }); + await act(async () => { + ReactDOM.render( + <> + + + , + container, + ); + }); + const click = (label: string) => + act(() => { + Array.from(document.querySelectorAll("button")) + .find((button) => button.textContent === label)! + .click(); + }); + click("DELETE_ALL"); + click("CONFIRM_DELETE"); + expect(onClose).toHaveBeenCalled(); + expect(mockDeleteItemPermanent).toHaveBeenCalledTimes(1); + expect(container.textContent).toContain("Emptying trash (3 items)"); + const pending = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(pending); + expect(pending.defaultPrevented).toBe(true); + + await act(async () => { + first.resolve(); + await first.promise; + await Promise.resolve(); + }); + expect(mockDeleteItemPermanent).toHaveBeenCalledTimes(2); + expect(container.textContent).toContain("1 of 3 completed; 2 remaining"); + const settled = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(settled); + expect(settled.defaultPrevented).toBe(false); + + mockDeleteItemPermanent.mockResolvedValueOnce(undefined); + await act(async () => { + ReactDOM.render( + {}} datastore={datastore(["later"])} />, + container, + ); + }); + click("DELETE_ALL"); + click("CONFIRM_DELETE"); + await act(async () => { + await Promise.resolve(); + }); + expect(mockDeleteItemPermanent).toHaveBeenCalledTimes(3); + }); + + it("keeps one permanent deletion pending and reports failure", async () => { + const pending = deferred(); + mockDeleteItemPermanent.mockReturnValueOnce(pending.promise); + let settled = false; + const deletion = deleteTrashEntryInBackground( + datastore(["one"]), + { path: ["one"], item: datastore(["one"]).items![0], type: "item" }, + ).then((result) => { + settled = true; + return result; + }); + await Promise.resolve(); + expect(settled).toBe(false); + + pending.reject(new Error("synthetic permanent-delete failure")); + expect((await deletion).outcome).toBe("failure"); + }); +}); diff --git a/src/js/components/dialogs/trash-bin.tsx b/src/js/components/dialogs/trash-bin.tsx index 28a83da..39fb253 100644 --- a/src/js/components/dialogs/trash-bin.tsx +++ b/src/js/components/dialogs/trash-bin.tsx @@ -25 +25 @@ import Table from "../table"; -import DialogProgress from "./progress"; +import { runBackgroundBatch } from "./progress"; @@ -38,0 +39,34 @@ interface TrashEntry { +export const emptyTrashInBackground = ( + datastore: Datastore, + trashEntries: readonly TrashEntry[], +) => + runBackgroundBatch({ + items: trashEntries, + runningMessage: `Emptying trash (${trashEntries.length} items)`, + successMessage: `Trash emptied (${trashEntries.length} items deleted)`, + item: async (entry) => { + await widgetService.deleteItemPermanent( + datastore, + entry.path, + "password", + ); + }, + }); + +export const deleteTrashEntryInBackground = ( + datastore: Datastore, + entry: TrashEntry, +) => + runBackgroundBatch({ + items: [entry], + runningMessage: "Permanently deleting item", + successMessage: "Item permanently deleted", + item: async (item) => { + await widgetService.deleteItemPermanent( + datastore, + item.path, + "password", + ); + }, + }); + @@ -56,2 +90 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { - const [deleteAllInProgress, setDeleteAllInProgress] = useState(false); - const [deleteAllProgress, setDeleteAllProgress] = useState(0); + const isMounted = React.useRef(true); @@ -60,0 +94 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { + isMounted.current = true; @@ -62,0 +97 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { + isMounted.current = false; @@ -184 +219 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { - const deletePermanentConfirmed = () => { + const deletePermanentConfirmed = async () => { @@ -187,2 +222,4 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { - widgetService.deleteItemPermanent(datastore, entry["path"], "password"); - removeEntry(entryIndexBeingDeleted); + const result = await deleteTrashEntryInBackground(datastore, entry); + if (isMounted.current && result.completed.length > 0) { + removeEntry(entryIndexBeingDeleted); + } @@ -201,41 +238,8 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { - setDeleteAllInProgress(true); - setDeleteAllProgress(0); - - const entryIds = entries.map((entry) => entry[0]); - const entriesFullSnapshot = helper.duplicateObject(entriesFull); - const totalEntries = entryIds.length; - const deletedIds: string[] = []; - - for (let i = 0; i < entryIds.length; i++) { - const entryId = entryIds[i]; - const entry = entriesFullSnapshot[entryId]; - - if (entry) { - await widgetService.deleteItemPermanent( - datastore, - entry["path"], - "password", - ); - deletedIds.push(entryId); - - // Update state immediately after each deletion - setEntries((prevEntries) => { - return prevEntries.filter((e) => !deletedIds.includes(e[0])); - }); - - setEntriesFull((prevEntriesFull) => { - const newEntriesFull = helper.duplicateObject(prevEntriesFull); - delete newEntriesFull[entryId]; - return newEntriesFull; - }); - } - - const progress = Math.round(((i + 1) / totalEntries) * 100); - setDeleteAllProgress(progress); - - // Small delay to allow UI to update - await new Promise((resolve) => setTimeout(resolve, 100)); - } - - setDeleteAllInProgress(false); - setDeleteAllProgress(0); + const snapshot = entries + .map((entry) => entriesFull[entry[0]]) + .filter((entry): entry is TrashEntry => Boolean(entry)); + // Starting the batch installs the unload guard synchronously. The global + // owner keeps it alive after this dialog is dismissed or unmounted. + const deletion = emptyTrashInBackground(datastore, snapshot); + onClose(); + await deletion; @@ -341 +345 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { - disabled={entries.length === 0 || deleteAllInProgress} + disabled={entries.length === 0} @@ -349 +352,0 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { - disabled={deleteAllInProgress} @@ -388,6 +390,0 @@ const DialogTrashBin = (props: DialogTrashBinProps) => { - {deleteAllInProgress && ( - - )} diff --git a/src/js/components/open-entry.test.ts b/src/js/components/open-entry.test.ts new file mode 100644 index 0000000..8b42f8a --- /dev/null +++ b/src/js/components/open-entry.test.ts @@ -0,0 +1,96 @@ +import openEntry from "./open-entry"; +import deviceService from "../services/device"; +import notification from "../services/notification"; +import secretService from "../services/secret"; +import type { SecretContent, SecretReference } from "../../types/vault"; + +describe("opening an entry's web address from the web app", () => { + let content: SecretContent; + let tab: { opener: unknown; location: { href: string }; close: jest.Mock }; + const item = { + type: "website_password", + secret_id: "secret", + secret_key: "key", + } as SecretReference; + + beforeEach(() => { + jest.spyOn(secretService, "readSecret").mockImplementation(async () => content); + jest.spyOn(secretService, "onItemClick").mockImplementation(() => {}); + tab = { opener: window, location: { href: "" }, close: jest.fn() }; + jest.spyOn(window, "open").mockReturnValue(tab as unknown as Window); + jest.spyOn(notification, "errorSend").mockImplementation(() => {}); + }); + + afterEach(() => jest.restoreAllMocks()); + + it("opens the site in a new tab cut off from the vault, not open-secret.html", async () => { + content = { website_password_url: "example.com/login" }; + await openEntry(item); + expect(window.open).toHaveBeenCalledWith("", "_blank"); + expect(tab.opener).toBeNull(); + expect(tab.location.href).toBe("https://example.com/login"); + expect(secretService.onItemClick).not.toHaveBeenCalled(); + }); + + it("opens bookmarks too", async () => { + content = { bookmark_url: "https://example.org/" }; + await openEntry({ ...item, type: "bookmark" }); + expect(tab.location.href).toBe("https://example.org/"); + }); + + it("opens passkeys using their relying party address", async () => { + content = { passkey_rp_id: "example.net" }; + await openEntry({ ...item, type: "passkey" }); + expect(tab.location.href).toBe("https://example.net"); + }); + + it("delegates non-web entries without opening a tab or reading the secret", async () => { + const note = { ...item, type: "note" } as SecretReference; + await openEntry(note); + expect(window.open).not.toHaveBeenCalled(); + expect(secretService.readSecret).not.toHaveBeenCalled(); + expect(secretService.onItemClick).toHaveBeenCalledWith(note); + }); + + it("closes the tab and says why when there is no address", async () => { + content = { website_password_url: "" }; + await openEntry(item); + expect(tab.close).toHaveBeenCalled(); + expect(notification.errorSend).toHaveBeenCalledWith("This entry has no web address to open."); + }); + + it("refuses script addresses", async () => { + content = { website_password_url: "javascript://%0aalert(1)" }; + await openEntry(item); + expect(tab.location.href).toBe(""); + expect(tab.close).toHaveBeenCalled(); + }); + + it.each(["https://", "http://", "https://[bad"])( + "closes the click-opened tab for malformed address %s", + async (address) => { + content = { website_password_url: address }; + await openEntry(item); + expect(window.open).toHaveBeenCalledWith("", "_blank"); + expect(tab.location.href).toBe(""); + expect(tab.close).toHaveBeenCalledTimes(1); + expect(notification.errorSend).toHaveBeenCalledWith("This entry's web address can't be opened."); + }, + ); + + it("closes the click-opened tab when decryption fails", async () => { + jest.spyOn(secretService, "readSecret").mockRejectedValueOnce(new Error("Unable to read entry")); + await openEntry(item); + expect(window.open).toHaveBeenCalledWith("", "_blank"); + expect(tab.location.href).toBe(""); + expect(tab.close).toHaveBeenCalledTimes(1); + expect(notification.errorSend).toHaveBeenCalledWith("Unable to read entry"); + }); + + it("leaves the extension's handling alone", async () => { + jest.spyOn(deviceService, "isWebclient").mockReturnValue(false); + await openEntry(item); + expect(window.open).not.toHaveBeenCalled(); + expect(secretService.onItemClick).toHaveBeenCalledWith(item); + }); +}); diff --git a/src/js/components/open-entry.ts b/src/js/components/open-entry.ts new file mode 100644 index 0000000..1821f28 --- /dev/null +++ b/src/js/components/open-entry.ts @@ -0,0 +1,88 @@ +/** + * Opens a website password, bookmark or passkey's web address in a new tab. + * + * The web app decrypts the entry in the vault's own tab. Upstream sends it to + * open-secret.html in a new tab instead, which can't reach this tab's unlocked + * vault and stays on "Decrypting" forever. The browser extension and desktop + * app keep upstream's handling. + */ + +import DOMPurify from "dompurify"; +import deviceService from "../services/device"; +import notification from "../services/notification"; +import { getPasskeyUrl } from "../services/passkey-url"; +import secretService from "../services/secret"; +import type { SecretContent, SecretReference } from "../../types/vault"; + +const OPENS_IN_TAB = ["website_password", "bookmark", "passkey", "elster_certificate"]; + +function entryUrl(type: string, content: SecretContent): string { + let url = + type === "website_password" + ? content.website_password_url + : type === "passkey" + ? getPasskeyUrl(content) + : type === "bookmark" + ? content.bookmark_url + : "https://www.elster.de/eportal/login/softpse"; + if (!url) { + throw new Error("This entry has no web address to open."); + } + if (!url.includes("://")) { + url = "https://" + url; + } + if (!/^https?:\/\//i.test(url) || !DOMPurify.isValidAttribute("a", "href", url)) { + throw new Error("This entry's web address can't be opened."); + } + try { + const parsed = new URL(url); + if (!parsed.hostname || !["http:", "https:"].includes(parsed.protocol)) { + throw new Error(); + } + } catch { + throw new Error("This entry's web address can't be opened."); + } + return url; +} + +/** + * Opens the tab during the click so browsers don't block it, and cuts it off + * from the vault before it loads the site. + */ +function openInNewTab(item: SecretReference) { + const tab = window.open("", "_blank"); + if (tab) { + tab.opener = null; + } + return secretService + .readSecret(item.secret_id, item.secret_key) + .then((content) => entryUrl(item.type!, content)) + .then( + (url) => { + if (tab) { + tab.location.href = url; + } else { + window.open(url, "_blank", "noopener,noreferrer"); + } + }, + (error: unknown) => { + tab?.close(); + notification.errorSend( + error instanceof Error ? error.message : "This entry could not be opened. Try again.", + ); + }, + ); +} + +function openEntry(item: SecretReference) { + if ( + deviceService.isWebclient() && + !deviceService.isElectron() && + OPENS_IN_TAB.includes(item.type!) + ) { + return openInNewTab(item); + } + return secretService.onItemClick(item); +} + +export default openEntry; diff --git a/src/js/components/search.tsx b/src/js/components/search.tsx index 36d2fa7..8129820 100644 --- a/src/js/components/search.tsx +++ b/src/js/components/search.tsx @@ -1,3 +1,4 @@ +import SearchIcon from "@mui/icons-material/Search"; import BackspaceOutlinedIcon from "@mui/icons-material/BackspaceOutlined"; import IconButton from "@mui/material/IconButton"; import InputAdornment from "@mui/material/InputAdornment"; @@ -20,20 +21,21 @@ const useStyles = makeStyles((theme) => ({ "&.Mui-focused": { borderColor: alpha(theme.palette.primary.main, 0.55), }, + minHeight: "38px", + paddingLeft: "10px", + }, + searchIcon: { + color: "#64748b", + fontSize: "20px", }, inputInput: { padding: theme.spacing(1, 1, 1, 0), fontSize: "0.875em", // vertical padding + font size from searchIcon paddingLeft: "1em", - transition: theme.transitions.create("width"), + // SoLoVault: the field takes the room it is given; the toolbar sizes it. width: "100%", - [theme.breakpoints.up("sm")]: { - width: "14ch", - "&:focus": { - width: "24ch", - }, - }, + minWidth: "14ch", }, })); @@ -58,6 +60,7 @@ const Search = (props: SearchProps) => { <> } classes={{ root: classes.inputRoot, input: classes.inputInput, diff --git a/src/js/components/sidebar.tsx b/src/js/components/sidebar.tsx index cd11048..b46e608 100644 --- a/src/js/components/sidebar.tsx +++ b/src/js/components/sidebar.tsx @@ -1,5 +1,8 @@ import GroupIcon from "@mui/icons-material/Group"; -import HomeIcon from "@mui/icons-material/Home"; +import ImportExportIcon from "@mui/icons-material/ImportExport"; +import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined"; +import SmartToyOutlinedIcon from "@mui/icons-material/SmartToyOutlined"; +import VpnKeyOutlinedIcon from "@mui/icons-material/VpnKeyOutlined"; import LinkIcon from "@mui/icons-material/Link"; import PersonIcon from "@mui/icons-material/Person"; import ShareIcon from "@mui/icons-material/Share"; @@ -44,7 +47,7 @@ const useStyles = makeStyles((theme) => ({ backgroundColor: theme.palette.blueBackground.main, }, toolbar: { - minHeight: deviceService.hasTitlebar() ? "82px" : "50px", + minHeight: deviceService.hasTitlebar() ? "88px" : "56px", }, drawerPaper: { width: drawerWidth, @@ -52,6 +55,8 @@ const useStyles = makeStyles((theme) => ({ color: theme.palette.lightGreyText.main, }, listItemRootActive: { + paddingTop: "7px", + paddingBottom: "7px", "&:hover": { backgroundColor: theme.palette.lightBackground.main, color: theme.palette.blueBackground.main, @@ -69,6 +74,8 @@ const useStyles = makeStyles((theme) => ({ }, }, listItemRoot: { + paddingTop: "7px", + paddingBottom: "7px", "&:hover": { backgroundColor: theme.palette.lightBackground.main, color: theme.palette.blueBackground.main, @@ -90,6 +97,7 @@ const useStyles = makeStyles((theme) => ({ }, listItemText: { fontSize: "0.875rem", + margin: 0, "& .MuiBadge-badge": { fontSize: "0.75rem", height: "15px", @@ -113,6 +121,8 @@ const useStyles = makeStyles((theme) => ({ subHeader: { color: theme.palette.lightGreyText.main, backgroundColor: "transparent", + lineHeight: "28px", + marginTop: "12px", }, version: { color: alpha(theme.palette.greyText.main, 0.5), @@ -186,228 +196,121 @@ const Sidebar = (props: SidebarProps) => { } } + // SoLoVault: one compact menu in three groups, with plain names. + const navItem = ( + to: string, + match: RegExp, + icon: React.ReactNode, + label: React.ReactNode, + ) => ( + setMobileOpen(false)} + classes={{ + root: isSelected(match) ? classes.listItemRootActive : classes.listItemRoot, + }} + selected={isSelected(match)} + > + + {icon} + + + + ); + const drawer = (
{isSmUp &&
} - - - {t("NAVIGATION")} - - - - - - - - {!offlineMode && ( - - - - - - {t("PENDING_REQUESTS")} - - } - /> - - )} - {!offlineMode && ( - - - - - - + + Vault + {navItem( + "/", + /^\/$|^\/datastore/, + , + "All items", )} - {!offlineMode && ( - - - - - - {t("GROUPS")} - + {!offlineMode && + navItem( + "/security-report", + /^\/security-report$/, + , + + Security check + , + )} + + {!offlineMode && ( + + Sharing + {navItem( + "/share/pendingshares", + /^\/share\/pendingshares$/, + , + - - )} - {!offlineMode && ( - - - - - - {t("SECURITY_REPORT")} - + Shared with me + , + )} + {navItem( + "/share/users", + /^\/share\/users$/, + , + "Trusted people", + )} + {navItem( + "/groups", + /^\/groups$/, + , + - - )} - {!offlineMode && - !getStore().getState().server.complianceDisableLinkShares && ( - - - - - - + Groups + , )} - - {moreLinks && moreLinks.length > 0 && ( - <> - - {t("MORE")} - - - {moreLinks - .filter((link) => - DOMPurify.isValidAttribute("a", "href", link.href), - ) - .map((link, index) => ( - - - {link.class && } - - - - ))} - - + {!getStore().getState().server.complianceDisableLinkShares && + navItem( + "/active-link-shares", + /^\/active-link-shares/, + , + "Shared links", + )} + + )} + {!offlineMode && ( + + Manage + {!getStore().getState().server.complianceDisableApiKeys && + navItem( + "/other/api-keys", + /^\/other\/api-keys$/, + , + "Agent keys", + )} + {navItem( + "/other/import", + /^\/other\/(import|export)$/, + , + "Import and export", + )} + {navItem( + "/settings", + /^\/(settings|account)|^\/other\/(?!api-keys$|import$|export$)/, + , + "Settings", + )} + )} -
PSONO: {version}
); diff --git a/src/js/components/topbar.tsx b/src/js/components/topbar.tsx index 35a0aae..f976b1d 100644 --- a/src/js/components/topbar.tsx +++ b/src/js/components/topbar.tsx @@ -3,7 +3,11 @@ import AddIcon from "@mui/icons-material/Add"; import AirplanemodeActiveIcon from "@mui/icons-material/AirplanemodeActive"; import CheckBoxIcon from "@mui/icons-material/CheckBox"; import CheckBoxOutlineBlankIcon from "@mui/icons-material/CheckBoxOutlineBlank"; +import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined"; import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import LockOutlinedIcon from "@mui/icons-material/LockOutlined"; +import PersonIcon from "@mui/icons-material/Person"; +import PhotoCameraOutlinedIcon from "@mui/icons-material/PhotoCameraOutlined"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import MenuIcon from "@mui/icons-material/Menu"; import SettingsIcon from "@mui/icons-material/Settings"; @@ -15,13 +19,19 @@ import Avatar from "@mui/material/Avatar"; import Badge from "@mui/material/Badge"; import Button from "@mui/material/Button"; import ButtonGroup from "@mui/material/ButtonGroup"; +import CircularProgress from "@mui/material/CircularProgress"; import Container from "@mui/material/Container"; +import Dialog from "@mui/material/Dialog"; +import DialogActions from "@mui/material/DialogActions"; +import DialogContent from "@mui/material/DialogContent"; +import DialogTitle from "@mui/material/DialogTitle"; import Divider from "@mui/material/Divider"; import FormControl from "@mui/material/FormControl"; import FormControlLabel from "@mui/material/FormControlLabel"; import Hidden from "@mui/material/Hidden"; import IconButton from "@mui/material/IconButton"; import ListItemIcon from "@mui/material/ListItemIcon"; +import ListItemText from "@mui/material/ListItemText"; import Menu from "@mui/material/Menu"; import MenuItem from "@mui/material/MenuItem"; import Switch from "@mui/material/Switch"; @@ -35,7 +45,6 @@ import { useTranslation } from "react-i18next"; import { useSelector } from "react-redux"; import { Link } from "react-router-dom"; import action from "../actions/bound-action-creators"; -import avatarService from "../services/avatar"; import datastoreService from "../services/datastore"; import offlineCache from "../services/offline-cache"; import { getStore } from "../services/store"; @@ -56,9 +65,7 @@ const useStyles = makeStyles((theme) => ({ }, backgroundColor: theme.palette.appBarBackground.main, color: theme.palette.appBarText.main, - borderColor: theme.palette.appBarBackground.main, - borderStyle: "solid", - borderWidth: "1px", + borderBottom: "1px solid #e2e8f0", boxShadow: "none", }, appBarReadOnly: { @@ -75,8 +82,129 @@ const useStyles = makeStyles((theme) => ({ boxShadow: "none", }, topLogo: { + display: "flex", + alignItems: "center", + height: "32px", + padding: "0 8px", + [theme.breakpoints.up("sm")]: { + width: "208px", + }, + "& img": { + maxHeight: "28px", + maxWidth: "170px", + objectFit: "contain", + }, + }, + spacer: { + flexGrow: 1, + }, + datastoreButton: { + textTransform: "none", + marginRight: theme.spacing(1), + color: "#0f172a", + borderColor: "#cbd5e1", + }, + accountButton: { + textTransform: "none", + color: "#0f172a", + fontWeight: 500, + padding: "6px 10px", + borderRadius: "8px", + "&:hover": { + backgroundColor: "#f1f4f8", + }, + }, + accountName: { + fontSize: "13px", + maxWidth: "240px", + overflow: "hidden", + textOverflow: "ellipsis", + whiteSpace: "nowrap", + [theme.breakpoints.down("sm")]: { + display: "none", + }, + }, + menuPaper: { + width: "300px", + maxWidth: "calc(100vw - 16px)", + border: "1px solid #e2e8f0", + borderRadius: "12px", + boxShadow: "0 12px 32px rgba(15,23,42,0.12)", + }, + menuHeader: { + display: "flex", + alignItems: "center", + gap: "12px", + margin: "4px 8px 8px", padding: "10px", - height: "100%", + borderRadius: "10px", + backgroundColor: "#f1f4f8", + }, + menuHeaderText: { + minWidth: 0, + }, + menuAvatar: { + width: 40, + height: 40, + backgroundColor: "rgba(217,35,46,0.08)", + color: "#d9232e", + fontWeight: 600, + }, + menuItem: { + borderRadius: "8px", + margin: "0 6px", + padding: "8px 10px", + alignItems: "flex-start", + whiteSpace: "normal", + }, + menuItemText: { + margin: 0, + "& .MuiListItemText-primary": { + fontSize: "14px", + fontWeight: 500, + color: "#0f172a", + }, + "& .MuiListItemText-secondary": { + fontSize: "12px", + color: "#64748b", + }, + }, + menuIconBox: { + minWidth: "38px !important", + paddingTop: "2px", + color: "#475569", + }, + signOutItem: { + "& .MuiListItemText-primary": { + color: "#d9232e !important", + }, + "& .MuiListItemIcon-root": { + color: "#d9232e", + }, + }, + photoPreview: { + width: 96, + height: 96, + margin: "8px auto 16px", + fontSize: "36px", + backgroundColor: "rgba(217,35,46,0.08)", + color: "#d9232e", + }, + photoError: { + color: "#9c2028", + textAlign: "center", + marginTop: "8px", + }, + menuCaption: { + color: "#64748b", + display: "block", + }, + menuName: { + color: "#0f172a", + fontWeight: 600, + overflow: "hidden", + textOverflow: "ellipsis", + whiteSpace: "nowrap", }, menuButton: { marginRight: theme.spacing(2), @@ -99,22 +227,20 @@ const useStyles = makeStyles((theme) => ({ display: "inline", }, avatar: { - width: 25, - height: 25, - marginLeft: "6px", - marginRight: "6px", + width: 30, + height: 30, + marginRight: "8px", + fontSize: "14px", + fontWeight: 600, + backgroundColor: "rgba(217,35,46,0.08)", + color: "#d9232e", }, avatarPlaceholder: { - width: 25, - height: 25, - backgroundColor: "#999", - paddingTop: "6px", - marginLeft: "6px", - marginRight: "6px", - color: "white", - "& > *:first-child": { - fontSize: "28px", - }, + width: 28, + height: 28, + marginRight: "8px", + backgroundColor: "rgba(217,35,46,0.08)", + color: "#d9232e", }, overlayIcon: { position: "absolute", @@ -137,8 +263,10 @@ const useStyles = makeStyles((theme) => ({ }, toolbar: { display: "flex", - alignItems: "center", // Align items vertically in the middle - justifyContent: "space-between", // This might be adjusted based on your design + alignItems: "center", + minHeight: "56px !important", + height: "56px", + padding: "0 12px 0 8px", }, signInTextContainer: { display: "flex", @@ -149,6 +277,130 @@ const useStyles = makeStyles((theme) => ({ export type TopbarProps = MobileNavigationProps; +interface SoloVaultProfile { + email: string | null; + name: string | null; + photo: string | null; + uploaded: boolean; +} + +declare global { + interface Window { + solovaultAccount?: { + profile: () => Promise; + uploadPhoto: (file: File) => Promise; + removePhoto: () => Promise; + openAccountPassword?: () => void; + }; + } +} + +const initialOf = (profile: SoloVaultProfile | null) => + (profile?.name || profile?.email || "").trim().charAt(0).toUpperCase(); + +// The account photo, or the first letter of the name, or a person icon. +const ProfileAvatar = ({ + profile, + className, +}: { + profile: SoloVaultProfile | null; + className: string; +}) => { + const [failed, setFailed] = useState(""); + const photo = profile?.photo && profile.photo !== failed ? profile.photo : ""; + return ( + setFailed(profile?.photo || ""), + }} + > + {initialOf(profile) || } + + ); +}; + +const ProfilePhotoDialog = ({ + profile, + onClose, + onChanged, +}: { + profile: SoloVaultProfile | null; + onClose: () => void; + onChanged: () => Promise; +}) => { + const classes = useStyles(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const input = React.useRef(null); + const run = async (step: () => Promise) => { + setBusy(true); + setError(""); + try { + await step(); + await onChanged(); + } catch (e) { + setError(e instanceof Error ? e.message : "Something went wrong. Try again."); + } + setBusy(false); + }; + return ( + + Profile photo + + + + {profile?.uploaded + ? "You're using a photo you uploaded." + : profile?.photo + ? "You're using the photo from your Google account." + : "Add a photo so you know which account is signed in."} + + {error && ( + + {error} + + )} + { + const file = event.target.files?.[0]; + event.target.value = ""; + if (file) run(() => window.solovaultAccount!.uploadPhoto(file)); + }} + /> + + + {profile?.uploaded && ( + + )} + + + + + ); +}; + const Topbar = (props: TopbarProps) => { const { mobileOpen, setMobileOpen } = props; const { t } = useTranslation(); @@ -163,7 +415,8 @@ const Topbar = (props: TopbarProps) => { const [datastores, setDatastores] = React.useState( [], ); - const [profilePic, setProfilePic] = useState(""); + const [profile, setProfile] = useState(null); + const [photoOpen, setPhotoOpen] = useState(false); const settingsDatastore = useSelector((state) => state.settingsDatastore); const passwordDatastore = useSelector((state) => @@ -184,14 +437,21 @@ const Topbar = (props: TopbarProps) => { let isSubscribed = true; React.useEffect(() => { reloadDatastoreOverview(); - loadAvatar(); + loadProfile(); + window.addEventListener("solovault:account-ready", loadProfile); return () => { isSubscribed = false; + window.removeEventListener("solovault:account-ready", loadProfile); }; }, []); - const loadAvatar = async () => { - setProfilePic((await avatarService.readAvatarCached()) || ""); + // SoLoVault: the account's name, email and photo (an uploaded one, or + // the one from Google) come from the account entry around the vault. + const loadProfile = async () => { + const account = window.solovaultAccount; + if (!account) return; + const next = await account.profile(); + if (isSubscribed) setProfile(next); }; const reloadDatastoreOverview = () => { @@ -260,346 +520,296 @@ const Topbar = (props: TopbarProps) => { window.location.href = "logout-success.html"; }; + // SoLoVault: the account entry outside the vault client owns locking and + // account sign-out. It listens for these and cancels the event; without it + // (plain vault client) sign-out falls back to the vault client's own. + const askAccountEntry = (name: string) => + !window.dispatchEvent(new CustomEvent(name, { cancelable: true })); + const lockVault = () => { + closeTopMenu(); + askAccountEntry("solovault:lock"); + }; + const signOut = () => { + closeTopMenu(); + if (!askAccountEntry("solovault:sign-out")) logout(); + }; + return ( - - - - - - - - -
- {datastores && datastores.length > 1 && ( -
- - - - - - - - - - {datastores.map((datastore, index) => { - return ( - { - onDatastoreSwitchClick(datastore); - }} - key={index} - > - - {datastore.is_default ? ( - - ) : ( - - )} - - - {datastore.description} - - - ); - })} - {!offlineCache.isActive() && [ - , - - - - - - {t("CREATE_NEW_DATASTORE")} - - , - ]} - -
- )} -
- - - {(settingsDatastore.showNoSaveToggle || - settingsDatastore.noSaveMode) && ( - - { - toggleNoSaveMode(event.target.checked); - }} - disabled={!settingsDatastore.showNoSaveToggle} - /> - - )} - - {profilePic ? ( - - ) : ( - - - - )} - - - - } - > - - - - - - - - -
- {(settingsDatastore.showNoSaveToggle || - settingsDatastore.noSaveMode) && ( - - - { - toggleNoSaveMode(event.target.checked); - }} - disabled={!settingsDatastore.showNoSaveToggle} - /> - } - labelPlacement="end" - label={undefined} - /> - - - )} - {t("SIGNED_IN_AS")}  - + + + + + + +
+ {datastores && datastores.length > 1 && ( + <> + + + {datastores.map((datastore, index) => { + return ( + { + onDatastoreSwitchClick(datastore); + }} + key={index} > - - - -
- - - {!offlineCache.isActive() && ( - - + {datastore.is_default ? ( + + ) : ( + + )} - {t("ACCOUNT")} + + {datastore.description} + - )} - {!offlineCache.isActive() && ( - - - - - {t("SETTINGS")} - - )} - {!offlineCache.isActive() && ( - - - - - {t("OTHER")} - - )} - {!offlineCache.isActive() && - !getStore().getState().server - .complianceDisableOfflineMode && ( - - - - - {t("GO_OFFLINE")} - - )} - {offlineCache.isActive() && - !getStore().getState().server - .complianceDisableOfflineMode && ( - - - - - {t("GO_ONLINE")} - - )} - - + ); + })} + {!offlineCache.isActive() && [ + , + - + - {t("LOGOUT")} - - + + {t("CREATE_NEW_DATASTORE")} + + , + ]} + + + )} + {(settingsDatastore.showNoSaveToggle || settingsDatastore.noSaveMode) && ( + + { + toggleNoSaveMode(event.target.checked); + }} + disabled={!settingsDatastore.showNoSaveToggle} + /> + + )} + + +
+ +
+ + {profile?.name || profile?.email || getStore().getState().user.username} + + {profile?.name && profile?.email && ( + + {profile.email} + + )}
- - + {window.solovaultAccount && ( + { + closeTopMenu(); + setPhotoOpen(true); + }} + > + + + + + + )} + {!offlineCache.isActive() && ( + + + + + + + )} + {!offlineCache.isActive() && + !getStore().getState().server.complianceDisableOfflineMode && ( + + + + + + + )} + {offlineCache.isActive() && + !getStore().getState().server.complianceDisableOfflineMode && ( + + + + + + + )} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + {photoOpen && ( + setPhotoOpen(false)} + onChanged={loadProfile} + /> + )} {goOfflineOpen && ( setGoOfflineOpen(false)} /> )} - {changeAccountOpen && ( - setChangeAccountOpen(false)} - /> - )} {createDatastoreOpen && ( ( return call(method, endpoint, data, headers, sessionSecretKey); } +/** + * SoLoVault: when a datastore and the entries in it were last written, used to + * notice changes made on other devices. It runs every few seconds, so a busy + * or restarting server must not sign anyone out the way other calls do. + * + * @param {string} token authentication token of the user + * @param {string} sessionSecretKey The session secret key + * @param {uuid} datastoreId The datastore ID + * + * @returns {Promise} Returns a promise with the datastore's write dates + */ +function readMetadataDatastore( + token: AuthToken, + sessionSecretKey: SessionSecretKey, + datastoreId: string, +): Promise> { + return _statelessCall( + "GET", + "/metadata-datastore/" + datastoreId + "/", + null, + { Authorization: "Token " + token }, + sessionSecretKey, + getStore().getState().server.url, + device.getDeviceFingerprint(), + ); +} + +interface DatastoreMetadata { + write_date: string; + secrets?: { id: string; write_date: string }[]; + shares?: { id: string; write_date: string }[]; +} + /** * Returns the gateway clusters available to the current user. */ @@ -4938,6 +4971,7 @@ const apiClientService = { readSecretHistory: readSecretHistory, readHistory: readHistory, readDatastore: readDatastore, + readMetadataDatastore: readMetadataDatastore, getGatewayClusters: getGatewayClusters, launchGateway: launchGateway, writeDatastore: writeDatastore, diff --git a/src/js/services/datastore-password-settlement.test.ts b/src/js/services/datastore-password-settlement.test.ts new file mode 100644 index 0000000..db4d68b --- /dev/null +++ b/src/js/services/datastore-password-settlement.test.ts @@ -0,0 +1,53 @@ +import datastorePasswordService from "./datastore-password"; +import datastoreService from "./datastore"; +import shareService from "./share"; + +describe("password datastore save settlement", () => { + afterEach(() => jest.restoreAllMocks()); + + it("waits for every started write before propagating a falsy rejection", async () => { + const datastore = { + datastore_id: "datastore-1", + folders: [], + items: [], + }; + const share = { + id: "share-node", + share_id: "share-1", + share_secret_key: "synthetic-key", + folders: [], + items: [], + }; + jest + .spyOn(shareService, "getClosestParentShare") + .mockReturnValueOnce({ closest_share: datastore } as never) + .mockReturnValueOnce({ closest_share: share } as never); + let rejectRoot!: (reason?: unknown) => void; + jest.spyOn(datastoreService, "saveDatastoreContent").mockReturnValue( + new Promise((_, reject) => { + rejectRoot = reject; + }) as never, + ); + let resolveShare!: (value: string) => void; + jest.spyOn(shareService, "writeShare").mockReturnValue( + new Promise((resolve) => { + resolveShare = resolve; + }) as never, + ); + + let settled = false; + const save = datastorePasswordService.saveDatastoreContent(datastore, [ + ["root-change"], + ["share-change"], + ]); + save.finally(() => (settled = true)).catch(() => {}); + rejectRoot(undefined); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + + resolveShare("share-write-complete"); + await expect(save).rejects.toBeUndefined(); + expect(settled).toBe(true); + }); +}); diff --git a/src/js/services/datastore-password.ts b/src/js/services/datastore-password.ts index 77d07a5..348a2be 100644 --- a/src/js/services/datastore-password.ts +++ b/src/js/services/datastore-password.ts @@ -972 +972,9 @@ function saveDatastoreContent(datastore: Datastore, paths: DatastorePath[]) { - return Promise.all(promises); + return Promise.allSettled(promises).then((results) => { + const failure = results.find( + (result): result is PromiseRejectedResult => result.status === "rejected", + ); + if (failure) { + return Promise.reject(failure.reason); + } + return results.map((result) => (result as PromiseFulfilledResult).value); + }); diff --git a/src/js/services/datastore.ts b/src/js/services/datastore.ts index 41a0008..aaaab5f 100644 --- a/src/js/services/datastore.ts +++ b/src/js/services/datastore.ts @@ -585 +585 @@ function saveDatastoreContentWithId( -) { +): Promise { @@ -590 +590 @@ function saveDatastoreContentWithId( - const onError = () => { + const onError = (error: unknown) => { @@ -592 +592 @@ function saveDatastoreContentWithId( - return undefined; + throw error; @@ -595 +595 @@ function saveDatastoreContentWithId( - const onError = () => { + const onError = (error: unknown) => { @@ -597 +597 @@ function saveDatastoreContentWithId( - return undefined; + throw error; @@ -706 +706 @@ function saveDatastoreContent( -) { +): Promise { @@ -720 +720 @@ function saveDatastoreContent( - const onError = () => { + const onError = (error: unknown) => { @@ -722 +722 @@ function saveDatastoreContent( - return undefined; + throw error; diff --git a/src/js/services/file-link.ts b/src/js/services/file-link.ts index 32c4df5..bdd2133 100644 --- a/src/js/services/file-link.ts +++ b/src/js/services/file-link.ts @@ -113 +113 @@ function moveFileLink( - const onError = () => { + const onError = (error: unknown) => { @@ -116,0 +117 @@ function moveFileLink( + throw error; @@ -146,2 +147,2 @@ function deleteFileLink(linkId: string) { - const onError = () => { - // pass + const onError = (error: unknown) => { + throw error; diff --git a/src/js/services/mutation-rejections.test.ts b/src/js/services/mutation-rejections.test.ts new file mode 100644 index 0000000..641f2ca --- /dev/null +++ b/src/js/services/mutation-rejections.test.ts @@ -0,0 +1,88 @@ +import apiClient from "./api-client"; +import cryptoLibrary from "./crypto-library"; +import datastoreService from "./datastore"; +import fileLinkService from "./file-link"; +import secretLinkService from "./secret-link"; +import shareLinkService from "./share-link"; + +jest.mock("./api-client", () => ({ + __esModule: true, + default: { + readDatastore: jest.fn(), + writeDatastore: jest.fn(), + moveSecretLink: jest.fn(), + deleteSecretLink: jest.fn(), + moveFileLink: jest.fn(), + deleteFileLink: jest.fn(), + moveShareLink: jest.fn(), + deleteShareLink: jest.fn(), + }, +})); +jest.mock("./store", () => ({ + getStore: () => ({ + getState: () => ({ user: {} }), + }), +})); +jest.mock("./notification", () => ({ + __esModule: true, + default: { errorSend: jest.fn() }, +})); + +const api = apiClient as unknown as Record; + +describe("mutation API rejection propagation", () => { + afterEach(() => { + jest.restoreAllMocks(); + jest.clearAllMocks(); + }); + + it("propagates move and delete API rejections from every link service", async () => { + const cases: Array<[string, () => Promise]> = [ + ["moveSecretLink", () => secretLinkService.moveSecretLink("link", "share")], + ["deleteSecretLink", () => secretLinkService.deleteSecretLink("link")], + ["moveFileLink", () => fileLinkService.moveFileLink("link", "share")], + ["deleteFileLink", () => fileLinkService.deleteFileLink("link")], + ["moveShareLink", () => shareLinkService.moveShareLink("link", "share")], + ["deleteShareLink", () => shareLinkService.deleteShareLink("link")], + ]; + for (const [method, mutate] of cases) { + const failure = new Error(`synthetic ${method} rejection`); + api[method].mockRejectedValueOnce(failure); + await expect(mutate()).rejects.toBe(failure); + } + }); + + it("propagates datastore encryption and API write rejections", async () => { + api.readDatastore.mockResolvedValueOnce({ + data: { + secret_key: "cipher-key", + secret_key_nonce: "key-nonce", + data: "", + data_nonce: "data-nonce", + }, + }); + jest.spyOn(cryptoLibrary, "decryptSecretKey").mockReturnValue("plain-key"); + const encrypt = jest.spyOn(cryptoLibrary, "encryptData"); + await datastoreService.getDatastoreWithId("datastore-1"); + const content = { + datastore_id: "datastore-1", + folders: [], + items: [], + }; + const encryptionFailure = new Error("synthetic encryption rejection"); + encrypt.mockImplementationOnce(() => { + throw encryptionFailure; + }); + await expect( + datastoreService.saveDatastoreContent("password", "default", content), + ).rejects.toBe(encryptionFailure); + + encrypt.mockReturnValue({ text: "ciphertext", nonce: "nonce" }); + const failure = new Error("synthetic datastore write rejection"); + api.writeDatastore.mockRejectedValueOnce(failure); + + await expect( + datastoreService.saveDatastoreContent("password", "default", content), + ).rejects.toBe(failure); + }); +}); diff --git a/src/js/services/secret-link.ts b/src/js/services/secret-link.ts index 165cba6..864cdc6 100644 --- a/src/js/services/secret-link.ts +++ b/src/js/services/secret-link.ts @@ -120 +120 @@ function moveSecretLink( - const onError = () => { + const onError = (error: unknown) => { @@ -123,0 +124 @@ function moveSecretLink( + throw error; @@ -155,2 +156,2 @@ function deleteSecretLink(linkId: string, logAuditTitle?: string) { - const onError = () => { - // pass + const onError = (error: unknown) => { + throw error; diff --git a/src/js/services/share-link.ts b/src/js/services/share-link.ts index 8ba1eb0..e2ecb08 100644 --- a/src/js/services/share-link.ts +++ b/src/js/services/share-link.ts @@ -61,2 +61,2 @@ function moveShareLink( - const onError = () => { - // pass + const onError = (error: unknown) => { + throw error; @@ -87,2 +87,2 @@ function deleteShareLink(linkId: string) { - const onError = () => { - // pass + const onError = (error: unknown) => { + throw error; diff --git a/src/js/services/widget-lifetime.test.ts b/src/js/services/widget-lifetime.test.ts new file mode 100644 index 0000000..8d46885 --- /dev/null +++ b/src/js/services/widget-lifetime.test.ts @@ -0,0 +1,274 @@ +import React from "react"; +import ReactDOM from "react-dom"; +import { act } from "react-dom/test-utils"; +import { BackgroundProgress, reportBackgroundProgress, runBackgroundBatch } from "../components/dialogs/progress"; +import datastoreService from "./datastore"; +import datastorePasswordService from "./datastore-password"; +import secretLinkService from "./secret-link"; +import shareService from "./share"; +import shareLinkService from "./share-link"; +import widgetService from "./widget"; + +jest.mock("./notification", () => ({ + __esModule: true, + default: { errorSend: jest.fn(), successSend: jest.fn() }, +})); + +const rootDatastore = () => ({ + datastore_id: "datastore-1", + items: [{ id: "item-1", name: "Synthetic item" }], + folders: [], +}); + +const moveDatastore = (share_id?: string) => ({ + datastore_id: "datastore-1", + items: [{ + id: "item-1", + name: "Synthetic item", + parent_datastore_id: "datastore-1", + share_rights: { read: true, write: true, grant: true, delete: true }, + }], + folders: [{ + id: "target-1", + name: "Target", + parent_datastore_id: "datastore-1", + ...(share_id ? { share_id } : {}), + share_rights: { read: true, write: true, grant: true, delete: true }, + items: [], + }], +}); + +const movePasswordItem = (itemPath: string[], targetPath: string[]) => + widgetService.moveItem( + { datastore_id: "datastore-1" }, itemPath, targetPath, "items", "password", + )!; + +const deletePasswordItem = () => + widgetService.deleteItemPermanent(rootDatastore(), ["item-1"], "password")!; + +const mockClosestParent = (closest_share: Record, relative_path = ["item-1"]) => + jest.spyOn(shareService, "getClosestParentShare").mockReturnValue({ + closest_share, + relative_path, + path_to_share: [], + }); + +const mockLinkDiscovery = () => { + jest.spyOn(datastorePasswordService, "saveDatastoreContent").mockResolvedValue([]); + jest.spyOn(datastorePasswordService, "handleDatastoreContentChanged").mockImplementation(() => {}); + jest.spyOn(datastorePasswordService, "getAllChildSharesByPath").mockImplementation(() => {}); + jest.spyOn(datastorePasswordService, "getAllSecretLinks").mockReturnValue([ + { id: "link-1", name: "Synthetic", path: [] }, + ] as never); + jest.spyOn(datastorePasswordService, "getAllFileLinks").mockReturnValue([]); +}; + +const expectPendingRejection = async (mutation: Promise, failure: Error) => { + let settled = false; + mutation.finally(() => (settled = true)).catch(() => {}); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + await expect(mutation).rejects.toBe(failure); + expect(settled).toBe(true); +}; + +describe("widget mutation promise lifetime", () => { + afterEach(() => { + jest.restoreAllMocks(); + act(() => reportBackgroundProgress(100)); + }); + + it.each(["move", "delete-root", "delete-share", "move-same-parent"])( + "keeps the global %s operation pending until every link settles", + async (scenario) => { + const container = document.createElement("div"); + document.body.appendChild(container); + act(() => { ReactDOM.render(React.createElement(BackgroundProgress), container); }); + const failure = new Error(`synthetic ${scenario} link failure`); + let resolveDeferred!: () => void; + const deferred = new Promise((resolve) => (resolveDeferred = resolve)); + const mutate = (id: string) => + id === "reject-link" ? Promise.reject(failure) : deferred; + const refreshed = moveDatastore(scenario === "move" ? "share-1" : undefined); + jest.spyOn(datastorePasswordService, "saveDatastoreContent").mockResolvedValue([]); + jest.spyOn(datastorePasswordService, "handleDatastoreContentChanged").mockImplementation(() => {}); + jest.spyOn(datastorePasswordService, "getAllFileLinks").mockReturnValue([]); + jest.spyOn(datastorePasswordService, "getAllSecretLinks").mockReturnValue( + scenario === "move-same-parent" + ? [] + : ([ + { id: "pending-link", name: "Pending", path: [] }, + { id: "reject-link", name: "Rejected", path: [] }, + ] as never), + ); + jest.spyOn(datastorePasswordService, "getAllChildSharesByPath").mockImplementation( + (_path, _datastore, shares) => { + if (scenario === "move-same-parent") { + shares.push( + { share: { id: "pending-link" }, path: [] }, + { share: { id: "reject-link" }, path: [] }, + ); + } + }, + ); + jest.spyOn(secretLinkService, "onSecretMoved").mockImplementation(mutate); + jest.spyOn(secretLinkService, "deleteSecretLink").mockImplementation(mutate); + jest.spyOn(shareLinkService, "onShareMoved").mockImplementation((id) => mutate(id) as never); + + let mutation: () => Promise; + if (scenario.startsWith("move")) { + jest.spyOn(datastorePasswordService, "getPasswordDatastore").mockResolvedValue(refreshed); + jest.spyOn(shareService, "getClosestParentShare").mockReturnValue({ + closest_share: + scenario === "move" ? { share_id: "share-1" } : { datastore_id: "datastore-1" }, + relative_path: [], + path_to_share: [], + }); + mutation = () => movePasswordItem(["item-1"], ["target-1"]); + } else { + jest.spyOn(shareService, "getClosestParentShare").mockReturnValue({ + closest_share: + scenario === "delete-share" + ? { share_id: "share-1", share_secret_key: "synthetic" } + : { datastore_id: "datastore-1" }, + relative_path: ["item-1"], + path_to_share: [], + }); + jest.spyOn(datastoreService, "getDatastoreWithId").mockResolvedValue(refreshed); + jest.spyOn(shareService, "readShare").mockResolvedValue({ data: refreshed } as never); + jest.spyOn(shareService, "writeShare").mockResolvedValue({} as never); + mutation = deletePasswordItem; + } + + let operation!: ReturnType>; + act(() => { + operation = runBackgroundBatch({ + items: [scenario], + runningMessage: `Running ${scenario}`, + successMessage: "Unexpected success", + item: mutation, + }); + }); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 125)); + }); + expect(container.textContent).toContain(`Running ${scenario}`); + const pending = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(pending); + expect(pending.defaultPrevented).toBe(true); + + let result!: Awaited; + await act(async () => { + resolveDeferred(); + result = await operation; + }); + expect(result.outcome).toBe("failure"); + expect(result.remaining).toEqual([scenario]); + expect(result.error).toBe(failure); + expect(container.textContent).toContain("Could not complete"); + const settled = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(settled); + expect(settled.defaultPrevented).toBe(false); + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + container.remove(); + }, + ); + + it("keeps markItemAsDeleted pending until the root datastore save settles", async () => { + const refreshed = rootDatastore(); + mockClosestParent({ datastore_id: "datastore-1" }); + jest.spyOn(datastoreService, "getDatastoreWithId").mockResolvedValue(refreshed); + jest.spyOn(datastorePasswordService, "handleDatastoreContentChanged").mockImplementation(() => {}); + let resolveSave!: () => void; + jest.spyOn(datastorePasswordService, "saveDatastoreContent").mockReturnValue( + new Promise((resolve) => (resolveSave = resolve)) as never, + ); + + let settled = false; + const mutation = widgetService.markItemAsDeleted( + rootDatastore(), + ["item-1"], + "password", + ); + if (!mutation) throw new Error("Expected a password mutation promise"); + const operation = mutation.then(() => (settled = true)); + await Promise.resolve(); + await Promise.resolve(); + + expect(settled).toBe(false); + resolveSave(); + await operation; + expect(settled).toBe(true); + }); + + it("propagates a root datastore refresh rejection", async () => { + const failure = new Error("synthetic read failure"); + mockClosestParent({ datastore_id: "datastore-1" }); + jest.spyOn(datastoreService, "getDatastoreWithId").mockRejectedValue(failure); + + await expect( + widgetService.markItemAsDeleted(rootDatastore(), ["item-1"], "password"), + ).rejects.toBe(failure); + }); + + it("propagates a share write rejection from markItemAsDeleted", async () => { + const failure = new Error("synthetic share write failure"); + mockClosestParent({ share_id: "share-1", share_secret_key: "synthetic" }); + jest.spyOn(shareService, "readShare").mockResolvedValue({ data: rootDatastore() } as never); + jest.spyOn(shareService, "writeShare").mockRejectedValue(failure); + + await expect( + widgetService.markItemAsDeleted(rootDatastore(), ["item-1"], "password"), + ).rejects.toBe(failure); + }); + + it("keeps permanent deletion pending through delayed link cleanup and propagates rejection", async () => { + const failure = new Error("synthetic link failure"); + const refreshed = rootDatastore(); + mockClosestParent({ datastore_id: "datastore-1" }); + jest.spyOn(datastoreService, "getDatastoreWithId").mockResolvedValue(refreshed); + mockLinkDiscovery(); + jest.spyOn(secretLinkService, "deleteSecretLink").mockRejectedValue(failure); + + const mutation = deletePasswordItem(); + if (!mutation) throw new Error("Expected a password mutation promise"); + await expectPendingRejection(mutation, failure); + }); + + it("keeps moveItem pending through delayed secret-link updates and propagates rejection", async () => { + const failure = new Error("synthetic move-link failure"); + const refreshed = moveDatastore("share-2"); + jest.spyOn(datastorePasswordService, "getPasswordDatastore").mockResolvedValue(refreshed); + mockLinkDiscovery(); + mockClosestParent({ share_id: "share-2", share_secret_key: "synthetic" }, []); + jest.spyOn(secretLinkService, "onSecretMoved").mockRejectedValue(failure); + + const mutation = movePasswordItem(["item-1"], ["target-1"]); + if (!mutation) throw new Error("Expected a password mutation promise"); + await expectPendingRejection(mutation, failure); + }); + + it("rejects an attempted move when the refreshed source is missing", async () => { + jest.spyOn(datastorePasswordService, "getPasswordDatastore").mockResolvedValue({ + datastore_id: "datastore-1", + items: [], + folders: [], + }); + + await expect(movePasswordItem(["missing-item"], [])).rejects.toThrow("source"); + }); + + it("rejects an attempted move when refreshed destination rights refuse it", async () => { + jest.spyOn(window, "alert").mockImplementation(() => {}); + const refused = moveDatastore(); + refused.folders[0].share_rights.write = false; + jest.spyOn(datastorePasswordService, "getPasswordDatastore").mockResolvedValue(refused); + + await expect( + movePasswordItem(["item-1"], ["target-1"]), + ).rejects.toThrow("permitted"); + }); +}); diff --git a/src/js/services/widget.test.ts b/src/js/services/widget.test.ts index 9fbf20c..e22561e 100644 --- a/src/js/services/widget.test.ts +++ b/src/js/services/widget.test.ts @@ -5,0 +6 @@ import secretService from "./secret"; +import secretLinkService from "./secret-link"; @@ -59,0 +61 @@ describe("Service: widgetService - moveItem test suite", () => { + jest.spyOn(secretLinkService, "onSecretMoved").mockResolvedValue(undefined); @@ -72,7 +74,9 @@ describe("Service: widgetService - moveItem test suite", () => { - await widgetService.moveItem( - datastore, - itemPath, - targetPath, - "invalid", - "password", - ); + await expect( + widgetService.moveItem( + datastore, + itemPath, + targetPath, + "invalid", + "password", + ), + ).rejects.toThrow("The requested move type is invalid."); @@ -476,7 +480,9 @@ describe("Service: widgetService - moveItem test suite", () => { - await widgetService.moveItem( - { datastore_id: "ds1" }, - ["item1"], - ["folder1"], - "items", - "password", - ); + await expect( + widgetService.moveItem( + { datastore_id: "ds1" }, + ["item1"], + ["folder1"], + "items", + "password", + ), + ).rejects.toThrow("The move is no longer permitted."); @@ -519,7 +525,9 @@ describe("Service: widgetService - moveItem test suite", () => { - await widgetService.moveItem( - { datastore_id: "ds1" }, - ["item1"], - ["folder1"], - "items", - "password", - ); + await expect( + widgetService.moveItem( + { datastore_id: "ds1" }, + ["item1"], + ["folder1"], + "items", + "password", + ), + ).rejects.toThrow("The move is no longer permitted."); @@ -612,7 +620,9 @@ describe("Service: widgetService - moveItem test suite", () => { - await widgetService.moveItem( - { datastore_id: "ds1" }, - ["folder1"], - ["target1"], - "folders", - "password", - ); + await expect( + widgetService.moveItem( + { datastore_id: "ds1" }, + ["folder1"], + ["target1"], + "folders", + "password", + ), + ).rejects.toThrow("The move is no longer permitted."); @@ -726,9 +736,9 @@ describe("Service: widgetService - moveItem test suite", () => { - // When element is not found, findInDatastore throws RangeError - // and moveItem catches it gracefully - await widgetService.moveItem( - { datastore_id: "ds1" }, - ["nonexistent"], - ["folder1"], - "items", - "password", - ); + await expect( + widgetService.moveItem( + { datastore_id: "ds1" }, + ["nonexistent"], + ["folder1"], + "items", + "password", + ), + ).rejects.toThrow("The move source no longer exists."); diff --git a/src/js/services/widget.ts b/src/js/services/widget.ts index 7cc8435..fc02eee 100644 --- a/src/js/services/widget.ts +++ b/src/js/services/widget.ts @@ -40,0 +41,17 @@ export interface WidgetManager { +const runAfterDelay = (delay: number, mutation: () => Promise) => + new Promise((resolve, reject) => { + setTimeout(() => { + Promise.resolve() + .then(mutation) + .then(() => resolve(), reject); + }, delay); + }); + +const settleMutations = async (mutations: Promise[]) => { + const results = await Promise.allSettled(mutations); + const failure = results.find( + (result): result is PromiseRejectedResult => result.status === "rejected", + ); + if (failure) throw failure.reason; +}; + @@ -685 +702 @@ function moveItem( - return; + return Promise.reject(new Error("The requested move type is invalid.")); @@ -717,2 +734,2 @@ function moveItem( - } catch (e) { - return; + } catch (_error) { + throw new Error("The move source no longer exists."); @@ -728 +745 @@ function moveItem( - return; + throw new Error("The move is no longer permitted."); @@ -791,0 +809 @@ function moveItem( + const linkMutations: Promise[] = []; @@ -795,3 +813,4 @@ function moveItem( - ((child_share) => { - timeout = timeout + 50; - setTimeout(() => { + timeout = timeout + 50; + const childShare = child_shares[i]; + linkMutations.push( + runAfterDelay(timeout, () => { @@ -799 +818 @@ function moveItem( - target_path_copy.concat(child_share.path), + target_path_copy.concat(childShare.path), @@ -806,3 +825,6 @@ function moveItem( - shareLinkService.onShareMoved(child_share.share.id, closest_parent); - }, timeout); - })(child_shares[i]); + return shareLinkService.onShareMoved( + childShare.share.id, + closest_parent, + ); + }), + ); @@ -812,0 +835 @@ function moveItem( + await settleMutations(linkMutations); @@ -818,6 +841,7 @@ function moveItem( - ((secret_link) => { - timeout = timeout + 50; - if (onOpenRequest) { - onOpenRequest(); - } - setTimeout(() => { + timeout = timeout + 50; + const secretLink = secret_links[i]; + if (onOpenRequest) { + onOpenRequest(); + } + linkMutations.push( + runAfterDelay(timeout, async () => { @@ -825 +849 @@ function moveItem( - target_path_copy2.concat(secret_link.path), + target_path_copy2.concat(secretLink.path), @@ -832 +856,3 @@ function moveItem( - const onError = (result: unknown) => { + try { + await secretLinkService.onSecretMoved(secretLink.id, closest_parent); + } finally { @@ -836,12 +862,3 @@ function moveItem( - }; - - const onSuccess = (content: unknown) => { - if (onClosedRequest) { - onClosedRequest(); - } - }; - secretLinkService - .onSecretMoved(secret_link.id, closest_parent) - .then(onSuccess, onError); - }, timeout); - })(secret_links[i]); + } + }), + ); @@ -852,3 +869,4 @@ function moveItem( - ((file_link) => { - timeout = timeout + 50; - setTimeout(() => { + timeout = timeout + 50; + const fileLink = file_links[i]; + linkMutations.push( + runAfterDelay(timeout, () => { @@ -856 +874 @@ function moveItem( - target_path_copy2.concat(file_link.path), + target_path_copy2.concat(fileLink.path), @@ -862,3 +880,3 @@ function moveItem( - fileLinkService.onFileMoved(file_link.id, closest_parent); - }, timeout); - })(file_links[i]); + return fileLinkService.onFileMoved(fileLink.id, closest_parent); + }), + ); @@ -891,0 +910 @@ function moveItem( + await settleMutations(linkMutations); @@ -917 +936 @@ function markItemAsDeleted( - let onSuccess, onError; + let onSuccess; @@ -938 +957 @@ function markItemAsDeleted( - onSuccess = (result: ShareContent | undefined) => { + onSuccess = async (result: ShareContent | undefined) => { @@ -948 +967 @@ function markItemAsDeleted( - shareService.writeShare( + await shareService.writeShare( @@ -956,3 +974,0 @@ function markItemAsDeleted( - onError = (e: unknown) => { - // pass - }; @@ -964 +980 @@ function markItemAsDeleted( - .then(onSuccess, onError); + .then(onSuccess); @@ -967,5 +983 @@ function markItemAsDeleted( - onError = (result: unknown) => { - // pass - }; - - onSuccess = (result: Datastore | undefined) => { + onSuccess = async (result: Datastore | undefined) => { @@ -981 +993 @@ function markItemAsDeleted( - datastorePasswordService.saveDatastoreContent(datastore, [ + await datastorePasswordService.saveDatastoreContent(datastore, [ @@ -989 +1001 @@ function markItemAsDeleted( - .then(onSuccess, onError); + .then(onSuccess); @@ -1379 +1391 @@ function deleteItemPermanent( - let onSuccess, onError; + let onSuccess; @@ -1408 +1420 @@ function deleteItemPermanent( - onSuccess = (result: ShareContent | undefined) => { + onSuccess = async (result: ShareContent | undefined) => { @@ -1448 +1460 @@ function deleteItemPermanent( - shareService.writeShare( + await shareService.writeShare( @@ -1454,0 +1467 @@ function deleteItemPermanent( + const linkMutations: Promise[] = []; @@ -1459,6 +1472,7 @@ function deleteItemPermanent( - ((child_share) => { - timeout = timeout + 50; - setTimeout(() => { - shareLinkService.onShareDeleted(child_share.share.id); - }, timeout); - })(childShares[i]); + timeout = timeout + 50; + const childShare = childShares[i]; + linkMutations.push( + runAfterDelay(timeout, () => + shareLinkService.onShareDeleted(childShare.share.id), + ), + ); @@ -1468,9 +1482,7 @@ function deleteItemPermanent( - ((secretLink) => { - timeout = timeout + 50; - setTimeout(() => { - secretLinkService.deleteSecretLink( - secretLink.id, - secretLink.name, - ); - }, timeout); - })(secretLinks[i]); + timeout = timeout + 50; + const secretLink = secretLinks[i]; + linkMutations.push( + runAfterDelay(timeout, () => + secretLinkService.deleteSecretLink(secretLink.id, secretLink.name), + ), + ); @@ -1481,6 +1493,7 @@ function deleteItemPermanent( - ((file_link) => { - timeout = timeout + 50; - setTimeout(() => { - fileLinkService.onFileDeleted(file_link.id); - }, timeout); - })(fileLinks[i]); + timeout = timeout + 50; + const fileLink = fileLinks[i]; + linkMutations.push( + runAfterDelay(timeout, () => + fileLinkService.onFileDeleted(fileLink.id), + ), + ); @@ -1489,4 +1502 @@ function deleteItemPermanent( - }; - - onError = (e: unknown) => { - // pass + await settleMutations(linkMutations); @@ -1499 +1509 @@ function deleteItemPermanent( - .then(onSuccess, onError); + .then(onSuccess); @@ -1502,5 +1512 @@ function deleteItemPermanent( - onError = (result: unknown) => { - // pass - }; - - onSuccess = (result: Datastore | undefined) => { + onSuccess = async (result: Datastore | undefined) => { @@ -1546 +1552 @@ function deleteItemPermanent( - datastorePasswordService.saveDatastoreContent(datastore, [ + await datastorePasswordService.saveDatastoreContent(datastore, [ @@ -1550,0 +1557 @@ function deleteItemPermanent( + const linkMutations: Promise[] = []; @@ -1555,6 +1562,7 @@ function deleteItemPermanent( - ((child_share) => { - timeout = timeout + 50; - setTimeout(() => { - shareLinkService.onShareDeleted(child_share.share.id); - }, timeout); - })(childShares[i]); + timeout = timeout + 50; + const childShare = childShares[i]; + linkMutations.push( + runAfterDelay(timeout, () => + shareLinkService.onShareDeleted(childShare.share.id), + ), + ); @@ -1564,9 +1572,7 @@ function deleteItemPermanent( - ((secretLink) => { - timeout = timeout + 50; - setTimeout(() => { - secretLinkService.deleteSecretLink( - secretLink.id, - secretLink.name, - ); - }, timeout); - })(secretLinks[i]); + timeout = timeout + 50; + const secretLink = secretLinks[i]; + linkMutations.push( + runAfterDelay(timeout, () => + secretLinkService.deleteSecretLink(secretLink.id, secretLink.name), + ), + ); @@ -1577,6 +1583,7 @@ function deleteItemPermanent( - ((file_link) => { - timeout = timeout + 50; - setTimeout(() => { - fileLinkService.onFileDeleted(file_link.id); - }, timeout); - })(fileLinks[i]); + timeout = timeout + 50; + const fileLink = fileLinks[i]; + linkMutations.push( + runAfterDelay(timeout, () => + fileLinkService.onFileDeleted(fileLink.id), + ), + ); @@ -1584 +1590,0 @@ function deleteItemPermanent( - @@ -1585,0 +1592 @@ function deleteItemPermanent( + await settleMutations(linkMutations); @@ -1590 +1597 @@ function deleteItemPermanent( - .then(onSuccess, onError); + .then(onSuccess); diff --git a/src/js/views/datastore/datastore-reload.test.ts b/src/js/views/datastore/datastore-reload.test.ts new file mode 100644 index 0000000..215d07b --- /dev/null +++ b/src/js/views/datastore/datastore-reload.test.ts @@ -0,0 +1,46 @@ +import datastorePasswordService from "../../services/datastore-password"; +import { reloadPasswordDatastore } from "./datastore-reload"; + +let mockLocked = false; + +jest.mock("../../services/offline-cache", () => ({ + __esModule: true, + default: { isActive: () => mockLocked, isLocked: () => mockLocked }, +})); +jest.mock("../../services/datastore-password", () => ({ + __esModule: true, + default: { getPasswordDatastore: jest.fn() }, +})); + +describe("datastore reload", () => { + beforeEach(() => { + mockLocked = false; + jest.clearAllMocks(); + }); + + it("settles only after the actual datastore read and preserves rejection", async () => { + const failure = new Error("datastore unavailable"); + const read = datastorePasswordService.getPasswordDatastore as jest.Mock; + read.mockRejectedValueOnce(failure); + const loaded = jest.fn(); + + await expect( + reloadPasswordDatastore(jest.fn(), loaded), + ).rejects.toBe(failure); + expect(loaded).not.toHaveBeenCalled(); + + read.mockResolvedValueOnce({ datastore_id: "store" }); + await reloadPasswordDatastore(jest.fn(), loaded); + expect(loaded).toHaveBeenCalledWith({ datastore_id: "store" }); + }); + + it("does not report success before a locked cache can be read", async () => { + mockLocked = true; + const onLocked = jest.fn(); + await expect( + reloadPasswordDatastore(onLocked, jest.fn()), + ).rejects.toThrow("offline cache locked"); + expect(onLocked).toHaveBeenCalledTimes(1); + expect(datastorePasswordService.getPasswordDatastore).not.toHaveBeenCalled(); + }); +}); diff --git a/src/js/views/datastore/datastore-reload.ts b/src/js/views/datastore/datastore-reload.ts new file mode 100644 index 0000000..26d0ace --- /dev/null +++ b/src/js/views/datastore/datastore-reload.ts @@ -0,0 +1,17 @@ +import type { Datastore } from "../../../types/datastore"; +import datastorePasswordService from "../../services/datastore-password"; +import offlineCacheService from "../../services/offline-cache"; + +export class DatastoreReloadDeferredError extends Error {} + +/** The real vault read used by both the screen and live-sync retry contract. */ +export function reloadPasswordDatastore( + onLocked: () => void, + onLoaded: (datastore: Datastore | undefined) => void, +): Promise { + if (offlineCacheService.isActive() && offlineCacheService.isLocked()) { + onLocked(); + return Promise.reject(new DatastoreReloadDeferredError("offline cache locked")); + } + return datastorePasswordService.getPasswordDatastore().then(onLoaded); +} diff --git a/src/js/views/datastore/datastore-operations.test.tsx b/src/js/views/datastore/datastore-operations.test.tsx new file mode 100644 index 0000000..a2bffdf --- /dev/null +++ b/src/js/views/datastore/datastore-operations.test.tsx @@ -0,0 +1,242 @@ +import React from "react"; +import ReactDOM from "react-dom"; +import { act } from "react-dom/test-utils"; +import type { Datastore } from "../../../types/datastore"; +import type { + DatastoreSelection, + DatastoreTreeNode, +} from "../../../types/datastore-ui"; +import { + BackgroundProgress, + reportBackgroundProgress, +} from "../../components/dialogs/progress"; +import widgetService from "../../services/widget"; +import { + areAllSelectionsMovable, + deleteItemInBackground, + deleteSelectionsInBackground, + moveSelectionsInBackground, + remainingSelection, + settleSelectionAfterOperation, +} from "./datastore-operations"; + +const item = (id: string, overrides = {}) => + ({ + id, + name: id, + path: ["source", id], + is_folder: false, + type: "website_password", + secret_id: `secret-${id}`, + ...overrides, + }) as DatastoreTreeNode; + +const selection = ( + node: DatastoreTreeNode, +): DatastoreSelection => ({ + item: node, + path: node.path, +}); + +const datastore = { + datastore_id: "datastore-1", + items: [], + folders: [], +} as Datastore; + +describe("datastore background operations", () => { + afterEach(() => { + jest.restoreAllMocks(); + reportBackgroundProgress(100); + }); + + it("keeps a single page move pending at 0 without legacy request callbacks", async () => { + const container = document.createElement("div"); + document.body.appendChild(container); + act(() => { + ReactDOM.render(, container); + }); + let resolveMove!: () => void; + const move = jest + .spyOn(widgetService, "moveItem") + .mockReturnValue( + new Promise((resolve) => (resolveMove = resolve)) as never, + ); + let settled = false; + let operation!: ReturnType; + act(() => { + operation = moveSelectionsInBackground({ + datastore, + moving: [selection(item("first"))], + targetPath: [], + type: "items", + isDestinationAllowed: () => true, + }).then((result) => { + settled = true; + return result; + }); + }); + + await Promise.resolve(); + expect(settled).toBe(false); + expect(move).toHaveBeenCalledTimes(1); + expect(move.mock.calls[0]).toHaveLength(5); + expect(container.textContent).toContain("0%"); + act(() => reportBackgroundProgress(100)); + expect(container.textContent).toContain("100%"); + const pending = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(pending); + expect(pending.defaultPrevented).toBe(true); + + await act(async () => { + resolveMove(); + expect((await operation).outcome).toBe("success"); + }); + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + container.remove(); + }); + + it("retains the rejected second move and permits the next page operation", async () => { + const failure = new Error("synthetic second move failure"); + const move = jest + .spyOn(widgetService, "moveItem") + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(failure); + const first = selection(item("first")); + const second = selection(item("second")); + const result = await moveSelectionsInBackground({ + datastore, + moving: [first, second], + targetPath: [], + type: "items", + isDestinationAllowed: () => true, + }); + + expect(result.outcome).toBe("partial"); + expect(result.completed).toEqual([first]); + expect(remainingSelection(result)).toEqual({ second }); + + move.mockResolvedValueOnce(undefined); + const recovery = await moveSelectionsInBackground({ + datastore, + moving: result.remaining, + targetPath: [], + type: "items", + isDestinationAllowed: () => true, + }); + expect(recovery.outcome).toBe("success"); + expect(recovery.remaining).toEqual([]); + }); + + it("retains the rejected second mass-delete selection", async () => { + const first = selection(item("first")); + const second = selection(item("second")); + jest + .spyOn(widgetService, "markItemAsDeleted") + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(new Error("synthetic second delete failure")); + + const result = await deleteSelectionsInBackground({ + datastore, + selected: [first, second], + }); + expect(result.outcome).toBe("partial"); + expect(result.completed).toEqual([first]); + expect(remainingSelection(result)).toEqual({ second }); + }); + + it("keeps a neighboring single delete pending and reports its rejection", async () => { + let rejectDelete!: (reason: Error) => void; + jest.spyOn(widgetService, "markItemAsDeleted").mockReturnValue( + new Promise((_, reject) => { + rejectDelete = reject; + }) as never, + ); + let settled = false; + const deletion = deleteItemInBackground({ + datastore, + path: ["item"], + label: "item", + }).then((result) => { + settled = true; + return result; + }); + await Promise.resolve(); + expect(settled).toBe(false); + + rejectDelete(new Error("synthetic delete failure")); + expect((await deletion).outcome).toBe("failure"); + }); + + it("rejects a selected drag batch when any source is forbidden", () => { + const dragged = selection(item("dragged")); + const forbidden = selection( + item("forbidden", { + share_rights: { read: true, write: true, grant: true, delete: false }, + }), + ); + expect(areAllSelectionsMovable([dragged])).toBe(true); + expect(areAllSelectionsMovable([dragged, forbidden])).toBe(false); + }); + + it("keeps global operation state safe when the page-level view unmounts", async () => { + const container = document.createElement("div"); + document.body.appendChild(container); + let resolveMove!: () => void; + jest + .spyOn(widgetService, "moveItem") + .mockReturnValue( + new Promise((resolve) => (resolveMove = resolve)) as never, + ); + const consoleError = jest + .spyOn(console, "error") + .mockImplementation(() => {}); + const operation = moveSelectionsInBackground({ + datastore, + moving: [selection(item("first"))], + targetPath: [], + type: "items", + isDestinationAllowed: () => true, + }); + const reload = jest.fn(); + const PageOperationHarness = () => { + const mounted = React.useRef(true); + const [, setSelected] = React.useState< + Record> + >({}); + const [, setControlsVisible] = React.useState(false); + React.useEffect(() => { + operation.then((result) => + settleSelectionAfterOperation(result, () => mounted.current, { + reload, + setSelection: setSelected, + setControlsVisible, + }), + ); + return () => { + mounted.current = false; + }; + }, []); + return null; + }; + act(() => { + ReactDOM.render(, container); + }); + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + resolveMove(); + await operation; + await Promise.resolve(); + expect(reload).not.toHaveBeenCalled(); + expect( + consoleError.mock.calls.some((call) => + String(call[0]).includes("state update on an unmounted component"), + ), + ).toBe(false); + consoleError.mockRestore(); + container.remove(); + }); +}); diff --git a/src/js/views/datastore/datastore-operations.ts b/src/js/views/datastore/datastore-operations.ts new file mode 100644 index 0000000..a6c0bba --- /dev/null +++ b/src/js/views/datastore/datastore-operations.ts @@ -0,0 +1,134 @@ +import type { + Datastore, + DatastoreItem, + DatastorePath, +} from "../../../types/datastore"; +import type { + DatastoreSelection, + DatastoreTreeNode, +} from "../../../types/datastore-ui"; +import { runBackgroundBatch } from "../../components/dialogs/progress"; +import datastoreService from "../../services/datastore"; +import widgetService from "../../services/widget"; +import { isMovableFolder, isMovableItem } from "./move-eligibility"; + +export const sameFolderPath = (a: DatastorePath, b: DatastorePath) => + a.length === b.length && a.every((id, index) => id === b[index]); + +export const isSelectionMovable = ( + selection: DatastoreSelection, +) => + selection.item.is_folder + ? isMovableFolder(selection.item) + : isMovableItem(selection.item); + +export const areAllSelectionsMovable = ( + moving: readonly DatastoreSelection[], +) => moving.every(isSelectionMovable); + +export const remainingSelection = (result: { + remaining: readonly DatastoreSelection[]; +}) => + Object.fromEntries( + result.remaining.map((selection) => [selection.item.id, selection]), + ) as Record>; + +export function settleSelectionAfterOperation( + result: { + completed: readonly DatastoreSelection[]; + remaining: readonly DatastoreSelection[]; + }, + isMounted: () => boolean, + callbacks: { + reload: () => void; + setSelection: ( + selection: Record>, + ) => void; + setControlsVisible: (visible: boolean) => void; + }, +) { + if (!isMounted()) return; + if (result.completed.length > 0) callbacks.reload(); + callbacks.setSelection(remainingSelection(result)); + callbacks.setControlsVisible(result.remaining.length > 0); +} + +export function moveSelectionsInBackground(options: { + datastore: Datastore; + moving: readonly DatastoreSelection[]; + targetPath: DatastorePath; + type: "folders" | "items"; + isDestinationAllowed: ( + target: DatastoreItem, + selection: DatastoreSelection, + ) => boolean; +}) { + const { datastore, moving, targetPath, type, isDestinationAllowed } = options; + return runBackgroundBatch({ + items: moving, + runningMessage: `Moving ${moving.length} ${moving.length === 1 ? "item" : "items"}`, + successMessage: `Moved ${moving.length} ${moving.length === 1 ? "item" : "items"}`, + item: async (selection) => { + if ( + sameFolderPath(selection.path.slice(0, -1), targetPath) || + targetPath.includes(selection.item.id) + ) { + throw new Error("This move is no longer valid."); + } + const targetMatch = targetPath.length + ? datastoreService.findInDatastore(targetPath, datastore) + : null; + const target = targetMatch + ? targetMatch[0][targetMatch[1]] + : ({ ...datastore, path: [] } as DatastoreItem); + if ( + !isSelectionMovable(selection) || + !isDestinationAllowed(target, selection) + ) { + throw new Error("This item can no longer be moved to that folder."); + } + await widgetService.moveItem( + datastore, + selection.path, + targetPath, + type, + "password", + ); + }, + }); +} + +export function deleteSelectionsInBackground(options: { + datastore: Datastore; + selected: readonly DatastoreSelection[]; +}) { + const { datastore, selected } = options; + return runBackgroundBatch({ + items: selected, + runningMessage: `Deleting ${selected.length} ${selected.length === 1 ? "item" : "items"}`, + successMessage: `Deleted ${selected.length} ${selected.length === 1 ? "item" : "items"}`, + item: async (selection) => { + await widgetService.markItemAsDeleted( + datastore, + selection.path, + "password", + ); + }, + }); +} + +export function deleteItemInBackground(options: { + datastore: Datastore; + path: DatastorePath; + label: "item" | "folder"; +}) { + const { datastore, path, label } = options; + return runBackgroundBatch({ + items: [path], + runningMessage: `Deleting ${label}`, + successMessage: `Deleted ${label}`, + item: async (itemPath) => { + await widgetService.markItemAsDeleted(datastore, itemPath, "password"); + }, + }); +} diff --git a/src/js/views/datastore/index.tsx b/src/js/views/datastore/index.tsx index 6c98720..f1d55aa 100644 --- a/src/js/views/datastore/index.tsx +++ b/src/js/views/datastore/index.tsx @@ -28,6 +28,7 @@ import type { ContextMenuPosition, DatastoreFilters, DatastoreSelection, + DatastoreTreeFolderNode, DatastoreTreeNode, FolderSelection, } from "../../../types/datastore-ui"; @@ -43,13 +44,12 @@ import DialogCreateLinkShare from "../../components/dialogs/create-link-share"; import DialogEditEntry from "../../components/dialogs/edit-entry"; import DialogEditFolder from "../../components/dialogs/edit-folder"; import DialogError from "../../components/dialogs/error"; -import DialogNewEntry from "../../components/dialogs/new-entry"; import DialogNewFolder from "../../components/dialogs/new-folder"; -import DialogProgress from "../../components/dialogs/progress"; import DialogRightsOverview from "../../components/dialogs/rights-overview"; import DialogSelectFolder from "../../components/dialogs/select-folder"; import DialogUnlockOfflineCache from "../../components/dialogs/unlock-offline-cache"; import DialogVerify from "../../components/dialogs/verify"; +import { useBackgroundOperationPending } from "../../components/dialogs/progress"; import FilterSideBar from "../../components/filter-sidebar"; import datastoreService from "../../services/datastore"; import datastorePasswordService from "../../services/datastore-password"; @@ -57,11 +57,22 @@ import fileTransferService from "../../services/file-transfer"; import itemBlueprintService from "../../services/item-blueprint"; import notification from "../../services/notification"; import offlineCacheService from "../../services/offline-cache"; -import secretService from "../../services/secret"; +import openEntry from "../../components/open-entry"; import { getStore } from "../../services/store"; import widget from "../../services/widget"; -import widgetService from "../../services/widget"; +import { useLiveVaultSync } from "./live-sync"; +import { reloadPasswordDatastore } from "./datastore-reload"; import DatastoreToolbar from "./toolbar"; +import { + areAllSelectionsMovable, + deleteItemInBackground, + deleteSelectionsInBackground, + moveSelectionsInBackground as runMoveSelectionsInBackground, + sameFolderPath, + settleSelectionAfterOperation, +} from "./datastore-operations"; +import { isMovableFolder, isMovableItem } from "./move-eligibility"; +import { useNewEntryDialog } from "./new-entry-dialog"; const useStyles = makeStyles((theme) => ({ root: { @@ -124,11 +135,6 @@ interface NewFolderData { path: DatastorePath; } -interface NewEntryData extends NewFolderData { - parentShareId?: string; - parentDatastoreId?: string; -} - const DatastoreView = ( props: Omit, "children">, ) => { @@ -140,7 +146,6 @@ const DatastoreView = ( secretType?: string; secretId?: string; }>(); - const [progress, setProgress] = React.useState(0); const serverStatus = useSelector((state) => state.server.status); const passwordDatastore = useSelector((state) => state.user.userDatastoreOverview?.datastores?.find( @@ -162,6 +167,10 @@ const DatastoreView = ( >({}); const [showMassOperationControls, setShowMassOperationControls] = useState(); + // SoLoVault: the toolbar's Select button keeps the checkboxes on without a + // keyboard (touch screens), until Done. + const [selectMode, setSelectMode] = useState(false); + const selecting = !!showMassOperationControls || selectMode; const [error, setError] = useState<{ title: string; description: string; @@ -181,9 +190,6 @@ const DatastoreView = ( {}, ); - const [newEntryOpen, setNewEntryOpen] = useState(false); - const [newEntryData, setNewEntryData] = useState>({}); - const [editFolderOpen, setEditFolderOpen] = useState(false); const [editFolderData, setEditFolderData] = useState<{ node?: DatastoreFolder; @@ -222,6 +228,7 @@ const DatastoreView = ( ); const [tags, setTags] = useState([]); const datastoreSaveInProgress = useRef(false); + const backgroundOperationPending = useBackgroundOperationPending(); const [preselectItem, setPreselectItem] = useState( null, @@ -247,14 +254,15 @@ const DatastoreView = ( }, ); - let isSubscribed = true; + const isSubscribed = useRef(true); React.useEffect(() => { + isSubscribed.current = true; return () => { - isSubscribed = false; + isSubscribed.current = false; }; }, []); React.useEffect(() => { - loadDatastore(); + void loadDatastore().catch(() => {}); }, [passwordDatastore]); // Add beforeunload event handler to warn user when closing tab with unsaved changes @@ -274,55 +282,11 @@ const DatastoreView = ( }; }, [editEntryDirty]); - const progressDialogOpen = progress !== 0 && progress !== 100; - let openRequests = 0; - let closedRequests = 0; - - const onStartProgress = () => { - openRequests = openRequests + 1; - setProgress(Math.round((closedRequests / openRequests) * 1000) / 10); - }; - const onCloseProgress = () => { - closedRequests = closedRequests + 1; - setProgress(Math.round((closedRequests / openRequests) * 1000) / 10); - }; - + const currentSelection = massOperationSelected; const isSelected = (item: DatastoreItem) => { return Object.hasOwn(massOperationSelected, item.id); }; - const isMovableItem = (item: DatastoreItem) => { - return ( - !Object.hasOwn(item, "share_id") && - (!Object.hasOwn(item, "share_rights") || - item.share_rights!.delete !== false) - ); - }; - - const hasSharedChild = (item: Datastore): boolean => { - if (item.items) { - for (const child of item.items) { - if (Object.hasOwn(child, "share_id")) { - return true; - } - } - } - - if (item.folders) { - for (const child of item.folders) { - if (Object.hasOwn(child, "share_id") || hasSharedChild(child)) { - return true; - } - } - } - - return false; - }; - - const isMovableFolder = (item: DatastoreItem) => { - return isMovableItem(item) && !hasSharedChild(item); - }; - const hasGrantRights = (item: Datastore) => { return !Object.hasOwn(item, "share_rights") || item.share_rights!.grant; }; @@ -347,7 +311,16 @@ const DatastoreView = ( ); }; - const isSelectable = (item: DatastoreTreeNode) => { + // SoLoVault: the selection and mode can be passed in, so a Shift+click range + // checks each row against the rows added before it (onSelectRows). + const isSelectable = ( + item: DatastoreTreeNode, + massOperationSelected: Record< + string, + DatastoreSelection + > = currentSelection, + showMassOperationControls: boolean = selecting, + ) => { if (!showMassOperationControls) { return true; } @@ -377,23 +350,41 @@ const DatastoreView = ( return hasSameParent(item, selectedItem) && defaultIsSelectable; }; - const loadDatastore = () => { - if (offlineCacheService.isActive() && offlineCacheService.isLocked()) { - setUnlockOfflineCache(true); - } else { - datastorePasswordService - .getPasswordDatastore() - .then(onNewDatastoreLoaded); - } + const loadDatastore = (): Promise => { + return reloadPasswordDatastore( + () => setUnlockOfflineCache(true), + onNewDatastoreLoaded, + ); }; + // SoLoVault: the New entry dialog with its Folder row. + const newEntry = useNewEntryDialog(datastore, (save, onSuccess) => + persistDatastoreChange(save, onSuccess), + ); + // SoLoVault: show changes made on other devices without a page reload. + useLiveVaultSync( + datastore?.datastore_id, + loadDatastore, + editEntryDirty || + newFolderOpen || + newEntry.isOpen || + editFolderOpen || + rightsOverviewOpen || + createLinkShareOpen || + unlockOfflineCache || + moveEntryData.length > 0 || + moveFolderData.length > 0 || + backgroundOperationPending || + Object.keys(massOperationSelected).length > 0, + ); + const onUnlockOfflineCacheClosed = () => { setUnlockOfflineCache(false); datastorePasswordService.getPasswordDatastore().then(onNewDatastoreLoaded); }; const onNewDatastoreLoaded = (data: Datastore | undefined) => { - if (!isSubscribed) { + if (!isSubscribed.current) { return; } setDatastore(data); @@ -505,41 +496,10 @@ const DatastoreView = ( }); }; - const onNewEntryCreate = (item: DatastoreItem) => { - // called once someone clicked the CREATE button in the dialog closes with the new name - return persistDatastoreChange( - () => - widget.newItemSave( - item, - datastore!, - newEntryData.parent, - newEntryData.path!, - datastorePasswordService, - ), - () => setNewEntryOpen(false), - ); - }; const onNewEntry = (parent: Datastore, path: DatastorePath) => { onContextMenuClose(); // called whenever someone clicks on a new entry Icon - setNewEntryOpen(true); - - let parentShareId = parent.parent_share_id; - let parentDatastoreId = parent.parent_datastore_id; - - if (Object.hasOwn(parent, "datastore_id")) { - parentShareId = undefined; - parentDatastoreId = parent.datastore_id; - } else if (Object.hasOwn(parent, "share_id")) { - parentShareId = parent.share_id; - parentDatastoreId = undefined; - } - setNewEntryData({ - parent: parent, - path: path, - parentShareId: parentShareId, - parentDatastoreId: parentDatastoreId, - }); + newEntry.open(parent, path); }; const onEditFolderSave = (node: Datastore & { color?: string | null }) => { @@ -622,7 +582,7 @@ const DatastoreView = ( }; const onSelectEntry = (item: DatastoreTreeNode, path: DatastorePath) => { - if (showMassOperationControls) { + if (selecting) { const newMassOperationSelected = { ...massOperationSelected, }; @@ -641,31 +601,74 @@ const DatastoreView = ( } }; + // SoLoVault: clicks, Ctrl/Cmd+clicks and Shift+clicks on rows + // (datastore-tree/select.ts). + const onSelectRows = ( + nodes: DatastoreTreeNode[], + range: boolean, + only = false, + ) => { + const next = only ? {} : { ...massOperationSelected }; + for (const node of nodes) { + if (Object.hasOwn(next, node.id)) { + if (!range) delete next[node.id]; + continue; + } + if (isSelectable(node, next, true)) { + next[node.id] = { item: node, path: node.path }; + } + } + setMassOperationSelected(next); + setShowMassOperationControls(Object.keys(next).length > 0); + }; + + const onToggleSelecting = () => { + if (selecting) { + setMassOperationSelected({}); + setShowMassOperationControls(false); + setSelectMode(false); + } else { + setSelectMode(true); + } + }; + const onCloneEntry = async (item: DatastoreItem, path: DatastorePath) => { await widget.cloneItem(datastore!, item, path); - loadDatastore(); + void loadDatastore().catch(() => {}); }; const onDeleteEntry = async (item: DatastoreItem, path: DatastorePath) => { - await widget.markItemAsDeleted(datastore!, path, "password"); - forceUpdate(); + const result = await deleteItemInBackground({ + datastore: datastore!, + path, + label: "item", + }); + if (isSubscribed.current && result.completed.length > 0) forceUpdate(); }; const onDeleteFolder = async (item: DatastoreFolder, path: DatastorePath) => { - await widget.markItemAsDeleted(datastore!, path, "password"); - forceUpdate(); + const result = await deleteItemInBackground({ + datastore: datastore!, + path, + label: "folder", + }); + if (isSubscribed.current && result.completed.length > 0) forceUpdate(); }; const onDeleteItemFromEditModal = async () => { - await widget.markItemAsDeleted(datastore!, editEntryData.path!, "password"); - forceUpdate(); + const result = await deleteItemInBackground({ + datastore: datastore!, + path: editEntryData.path!, + label: "item", + }); + if (isSubscribed.current && result.completed.length > 0) forceUpdate(); }; const onLinkItem = (item: DatastoreItem, path: DatastorePath) => { if (item.type === "file") { return fileTransferService.onItemClick(item); } else { - return secretService.onItemClick(item as SecretReference); + return openEntry(item as SecretReference); } }; @@ -679,24 +682,21 @@ const DatastoreView = ( }; const onSelectNodeForMoveFolder = async (breadcrumbs: FolderSelection) => { - for (const index in moveFolderData) { - await widgetService.moveItem( - datastore!, - moveFolderData[index].path, - breadcrumbs["id_breadcrumbs"], - "folders", - "password", - onStartProgress, - onCloseProgress, - ); - } - setMoveFolderData([]); - setShowMassOperationControls(false); - setMassOperationSelected({}); - loadDatastore(); + const result = await moveSelectionsInBackground( + moveFolderData, + breadcrumbs["id_breadcrumbs"], + "folders", + ); + if (!isSubscribed.current) return; + setMoveFolderData(result.remaining as DatastoreSelection[]); + settleMassSelection(result); }; - const isSelectableForMoveFolder = (node: DatastoreItem) => { + const isSelectableForMoveFolder = ( + node: DatastoreItem, + moving: DatastoreSelection[] = moveFolderData as DatastoreSelection[], + ) => { + const moveFolderData = moving; // filter out targets that the folder itself or are inside of that folder for (const folderData of moveFolderData) { if (node.path!.includes(folderData.item.id)) { @@ -742,31 +742,25 @@ const DatastoreView = ( }; const onSelectNodeForMoveEntry = async (breadcrumbs: FolderSelection) => { - for (const index in moveEntryData) { - onStartProgress(); - } - - for (const index in moveEntryData) { - await widgetService.moveItem( - datastore!, - moveEntryData[index].path, - breadcrumbs["id_breadcrumbs"], - "items", - "password", - ); - onCloseProgress(); - } - setMoveEntryData([]); - setShowMassOperationControls(false); - setMassOperationSelected({}); - loadDatastore(); + const result = await moveSelectionsInBackground( + moveEntryData, + breadcrumbs["id_breadcrumbs"], + "items", + ); + if (!isSubscribed.current) return; + setMoveEntryData(result.remaining as DatastoreSelection[]); + settleMassSelection(result); }; - const isSelectableForMoveEntry = (node: DatastoreItem) => { + const isSelectableForMoveEntry = ( + node: DatastoreItem, + moving: DatastoreSelection[] = moveEntryData as DatastoreSelection[], + ) => { + const moveEntryData = moving; // filter out all targets that are a share if the item is not allowed to be shared // yet don't filter out entries that are just moved within a share if ( - !moveEntryData[0].item.share_rights!.grant && + !hasGrantRights(moveEntryData[0].item) && node.share_id && (!moveEntryData[0].item.parent_share_id || moveEntryData[0].item.parent_share_id !== node.share_id) @@ -776,7 +770,7 @@ const DatastoreView = ( // filter out all targets that are inside of a share if the item is not allowed to be shared // yet don't filter out entries that are just moved within a share if ( - !moveEntryData[0].item.share_rights!.grant && + !hasGrantRights(moveEntryData[0].item) && node.parent_share_id && (!moveEntryData[0].item.parent_share_id || moveEntryData[0].item.parent_share_id !== node.parent_share_id) @@ -800,6 +794,43 @@ const DatastoreView = ( return false; }; + const moveSelectionsInBackground = ( + moving: readonly DatastoreSelection[], + targetPath: DatastorePath, + type: "folders" | "items", + ) => + runMoveSelectionsInBackground({ + datastore: datastore!, + moving: moving as DatastoreSelection[], + targetPath, + type, + isDestinationAllowed: (target, selection) => + selection.item.is_folder + ? isSelectableForMoveFolder(target, [selection]) + : isSelectableForMoveEntry(target, [selection]), + }); + + const settleMassSelection = (result: { + completed: readonly DatastoreSelection[]; + remaining: readonly DatastoreSelection[]; + }) => { + settleSelectionAfterOperation( + { + completed: result.completed as DatastoreSelection[], + remaining: result.remaining as DatastoreSelection[], + }, + () => isSubscribed.current, + { + reload: loadDatastore, + setSelection: setMassOperationSelected, + setControlsVisible: (visible) => { + setShowMassOperationControls(visible); + if (!visible) setSelectMode(false); + }, + }, + ); + }; + const onLinkShare = (item: DatastoreItem, path: DatastorePath) => { setCreateLinkShareData({ item: item, @@ -861,15 +892,75 @@ const DatastoreView = ( }); } + // SoLoVault: drag and drop. A dragged row that is part of a ticked + // selection carries the whole selection with it. + const draggedSelection = ( + node: DatastoreTreeNode, + ): DatastoreSelection[] => { + if (Object.hasOwn(massOperationSelected, node.id)) { + return Object.values(massOperationSelected); + } + return [{ item: node, path: node.path }]; + }; + + const canDropNode = ( + node: DatastoreTreeNode, + target: DatastoreTreeFolderNode | null, + ) => { + const targetPath: DatastorePath = target ? target.path : []; + const targetNode = (target ?? { ...datastore!, path: [] }) as DatastoreItem; + const moving = draggedSelection(node).filter( + (selection) => !sameFolderPath(selection.path.slice(0, -1), targetPath), + ); + if (moving.length === 0) { + return false; + } + if (!areAllSelectionsMovable(moving)) { + return false; + } + if (moving.some((selection) => targetPath.includes(selection.item.id))) { + return false; + } + return node.is_folder + ? isSelectableForMoveFolder(targetNode, moving as DatastoreSelection[]) + : isSelectableForMoveEntry(targetNode, moving as DatastoreSelection[]); + }; + + const onDropNode = async ( + node: DatastoreTreeNode, + target: DatastoreTreeFolderNode | null, + ) => { + if (!canDropNode(node, target)) { + return; + } + const targetPath: DatastorePath = target ? target.path : []; + const moving = draggedSelection(node).filter( + (selection) => !sameFolderPath(selection.path.slice(0, -1), targetPath), + ); + const result = await moveSelectionsInBackground( + moving, + targetPath, + node.is_folder ? "folders" : "items", + ); + if (!isSubscribed.current) return; + if (Object.hasOwn(massOperationSelected, node.id)) { + settleMassSelection(result); + } else if (result.completed.length > 0) { + void loadDatastore().catch(() => {}); + } + }; + return ( - {t("DATASTORE")} + All items 0 } @@ -884,25 +975,12 @@ const DatastoreView = ( } }} onMassDelete={async () => { - for (const key in massOperationSelected) { - if (!Object.hasOwn(massOperationSelected, key)) { - continue; - } - onStartProgress(); - } - - for (const key in massOperationSelected) { - if (!Object.hasOwn(massOperationSelected, key)) { - continue; - } - await onDeleteEntry( - massOperationSelected[key].item, - massOperationSelected[key].path, - ); - onCloseProgress(); - } - setMassOperationSelected({}); - setShowMassOperationControls(false); + const selected = Object.values(massOperationSelected); + const result = await deleteSelectionsInBackground({ + datastore: datastore!, + selected, + }); + settleMassSelection(result); }} search={search} setSearch={setSearch} @@ -926,7 +1004,12 @@ const DatastoreView = ( > + node.is_folder + ? isMovableFolder(node) + : isMovableItem(node) + } + canDropNode={canDropNode} + onDropNode={onDropNode} + onSelectRows={onSelectRows} + selectRowsOnClick={selectMode} + allowMultiselect={selecting} isSelected={isSelected} isSelectable={isSelectable} deleteFolderLabel={t("MOVE_TO_TRASH")} @@ -987,7 +1079,7 @@ const DatastoreView = ( ? { top: contextMenuPosition.mouseY, left: contextMenuPosition.mouseX, - } + } : undefined } onContextMenu={(event) => { @@ -1022,15 +1114,7 @@ const DatastoreView = ( onCreate={onNewFolderCreate} /> )} - {newEntryOpen && ( - setNewEntryOpen(false)} - onCreate={onNewEntryCreate} - parentDatastoreId={newEntryData.parentDatastoreId} - parentShareId={newEntryData.parentShareId} - /> - )} + {newEntry.dialog} {editFolderOpen && ( - {progressDialogOpen && ( - - )} - {editEntryConfirmDialog && ( ({ + getStore: () => ({ + getState: () => ({ + server: { url: "https://api.test" }, + user: { token: mockToken }, + }), + }), +})); +jest.mock("../../services/device", () => ({ + __esModule: true, + default: { getDeviceFingerprint: () => "fingerprint" }, +})); +jest.mock("../../services/offline-cache", () => ({ + __esModule: true, + default: { get: jest.fn().mockResolvedValue(null), set: jest.fn() }, +})); +jest.mock("../../services/user", () => ({ + __esModule: true, + default: { + isLoggedIn: () => true, + logout: jest.fn(), + }, +})); +jest.mock("../../services/crypto-library", () => ({ + __esModule: true, + default: { + encryptData: jest.fn(() => ({ text: "encrypted", nonce: "nonce" })), + decryptData: jest.fn(), + }, +})); + +describe("API client: SoLoVault change check", () => { + beforeEach(() => { + jest.clearAllMocks(); + jest.spyOn(console, "log").mockImplementation(() => {}); + mockToken = "current-token"; + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + for (const status of [401, 502, 503]) { + it(`never signs out on ${status}`, async () => { + const response: Partial = { + ok: false, + status, + statusText: "Unavailable", + text: jest.fn().mockResolvedValue(""), + }; + globalThis.fetch = jest + .fn, Parameters>() + .mockResolvedValue(response as Response); + + await expect( + apiClient.readMetadataDatastore( + "current-token", + "session-key", + "datastore-id", + ), + ).rejects.toEqual(expect.anything()); + + expect(user.logout).not.toHaveBeenCalled(); + expect((globalThis.fetch as jest.Mock).mock.calls[0][0]).toBe( + "https://api.test/metadata-datastore/datastore-id/", + ); + }); + } +}); diff --git a/src/js/views/datastore/live-sync.test.tsx b/src/js/views/datastore/live-sync.test.tsx new file mode 100644 index 0000000..8481007 --- /dev/null +++ b/src/js/views/datastore/live-sync.test.tsx @@ -0,0 +1,176 @@ +import React from "react"; +import ReactDOM from "react-dom"; +import { act } from "react-dom/test-utils"; +import apiClient from "../../services/api-client"; +import datastorePasswordService from "../../services/datastore-password"; +import { reloadPasswordDatastore } from "./datastore-reload"; +import { changeStamp, useLiveVaultSync } from "./live-sync"; + +jest.mock("../../services/api-client", () => ({ + __esModule: true, + default: { readMetadataDatastore: jest.fn() }, +})); +jest.mock("../../services/offline-cache", () => ({ + __esModule: true, + default: { isActive: () => false }, +})); +jest.mock("../../services/datastore-password", () => ({ + __esModule: true, + default: { getPasswordDatastore: jest.fn() }, +})); +jest.mock("../../services/store", () => ({ + getStore: () => ({ + getState: () => ({ user: { token: "token", sessionSecretKey: "key" } }), + }), +})); + +const read = apiClient.readMetadataDatastore as jest.Mock; +const readDatastore = datastorePasswordService.getPasswordDatastore as jest.Mock; + +function Probe(props: { reload: () => Promise; paused: boolean }) { + useLiveVaultSync("store", props.reload, props.paused, 1000); + return null; +} + +describe("Live vault sync", () => { + let container: HTMLDivElement; + let written: string; + const reload = jest.fn(); + + const render = (paused: boolean) => + act(() => { + ReactDOM.render(, container); + }); + const tick = async () => { + await act(async () => { + jest.advanceTimersByTime(1000); + await Promise.resolve(); + await Promise.resolve(); + }); + }; + + beforeEach(() => { + jest.useFakeTimers(); + container = document.createElement("div"); + written = "2026-10-25T10:00:00Z"; + reload.mockReset(); + read.mockReset(); + readDatastore.mockReset(); + read.mockImplementation(() => + Promise.resolve({ + data: { + write_date: "2026-10-25T09:00:00Z", + secrets: [{ id: "a", write_date: written }], + }, + }), + ); + }); + + it("retries the initial stamp through the real datastore reload helper", async () => { + readDatastore + .mockRejectedValueOnce(new Error("datastore unavailable")) + .mockResolvedValueOnce({ datastore_id: "store" }); + const onLoaded = jest.fn(); + const realReload = () => reloadPasswordDatastore(jest.fn(), onLoaded); + + act(() => { + ReactDOM.render( + , + container, + ); + }); + await tick(); + expect(readDatastore).toHaveBeenCalledTimes(1); + expect(onLoaded).not.toHaveBeenCalled(); + await tick(); + expect(readDatastore).toHaveBeenCalledTimes(2); + expect(onLoaded).toHaveBeenCalledWith({ datastore_id: "store" }); + await tick(); + expect(readDatastore).toHaveBeenCalledTimes(2); + }); + + afterEach(() => { + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + jest.useRealTimers(); + }); + + it("reloads only when something was written elsewhere", async () => { + render(false); + await tick(); + await tick(); + expect(reload).toHaveBeenCalledTimes(1); + + written = "2026-10-25T10:05:00Z"; + await tick(); + expect(reload).toHaveBeenCalledTimes(2); + await tick(); + expect(reload).toHaveBeenCalledTimes(2); + }); + + it("waits while paused and catches up afterwards", async () => { + render(false); + await tick(); + render(true); + const calls = read.mock.calls.length; + written = "2026-10-25T10:05:00Z"; + await tick(); + expect(read.mock.calls.length).toBe(calls); + expect(reload).toHaveBeenCalledTimes(1); + + render(false); + await tick(); + expect(reload).toHaveBeenCalledTimes(2); + }); + + it("keeps going when the server does not answer", async () => { + render(false); + await tick(); + read.mockImplementationOnce(() => + Promise.reject({ errors: ["SERVER_OFFLINE"] }), + ); + await tick(); + written = "2026-10-25T10:05:00Z"; + await tick(); + expect(reload).toHaveBeenCalledTimes(2); + }); + + it("retries the same metadata stamp when the datastore read fails", async () => { + render(false); + await tick(); + written = "2026-10-25T10:05:00Z"; + reload + .mockRejectedValueOnce(new Error("datastore unavailable")) + .mockResolvedValueOnce(undefined); + + await tick(); + expect(reload).toHaveBeenCalledTimes(2); + await tick(); + expect(reload).toHaveBeenCalledTimes(3); + await tick(); + expect(reload).toHaveBeenCalledTimes(3); + }); + + it("stops when the vault page closes", async () => { + render(false); + await tick(); + act(() => { + ReactDOM.unmountComponentAtNode(container); + }); + const calls = read.mock.calls.length; + await tick(); + expect(read.mock.calls.length).toBe(calls); + }); + + it("builds the same stamp whatever order the server lists entries in", () => { + const a = { id: "a", write_date: "1" }; + const b = { id: "b", write_date: "2" }; + expect(changeStamp({ write_date: "x", secrets: [a, b] })).toBe( + changeStamp({ write_date: "x", secrets: [b, a] }), + ); + expect(changeStamp({ write_date: "x", secrets: [a] })).not.toBe( + changeStamp({ write_date: "y", secrets: [a] }), + ); + }); +}); diff --git a/src/js/views/datastore/live-sync.ts b/src/js/views/datastore/live-sync.ts new file mode 100644 index 0000000..04fd195 --- /dev/null +++ b/src/js/views/datastore/live-sync.ts @@ -0,0 +1,109 @@ +/** + * SoLoVault: keeps the open vault in step with changes made on other devices. + * While the tab is visible it asks the server every few seconds when the vault + * and each entry were last written (nothing secret) and reloads the vault only + * when that moved. Returning to the tab checks straight away. + */ +import React from "react"; +import apiClient from "../../services/api-client"; +import offlineCacheService from "../../services/offline-cache"; +import { getStore } from "../../services/store"; + +export const LIVE_SYNC_INTERVAL_MS = 10000; + +interface WriteDate { + id: string; + write_date: string; +} + +/** One string that changes whenever anything in the datastore was written. */ +export function changeStamp(meta: { + write_date?: string; + secrets?: WriteDate[]; + shares?: WriteDate[]; +}): string { + const entries = [ + ...(meta.secrets || []).map((s) => s.id + "@" + s.write_date), + ...(meta.shares || []).map((s) => "s" + s.id + "@" + s.write_date), + ].sort(); + return (meta.write_date || "") + "|" + entries.join(","); +} + +/** + * Calls reload() when the datastore changed elsewhere. Nothing is checked while + * paused (a dialog is open, unsaved edits) or the tab is hidden; the first check + * afterwards catches up. + */ +export function useLiveVaultSync( + datastoreId: string | undefined, + reload: () => Promise, + paused: boolean, + intervalMs: number = LIVE_SYNC_INTERVAL_MS, +): void { + const reloadRef = React.useRef(reload); + reloadRef.current = reload; + const pausedRef = React.useRef(paused); + pausedRef.current = paused; + + React.useEffect(() => { + if (!datastoreId) { + return; + } + let stopped = false; + let checking = false; + let last: string | null = null; + const canCommit = () => + !stopped && + !pausedRef.current && + !document.hidden && + !offlineCacheService.isActive(); + + const check = async () => { + if ( + stopped || + checking || + pausedRef.current || + document.hidden || + offlineCacheService.isActive() + ) { + return; + } + checking = true; + try { + const user = getStore().getState().user; + const response = await apiClient.readMetadataDatastore( + user.token, + user.sessionSecretKey, + datastoreId, + ); + const stamp = changeStamp(response.data); + if (canCommit() && (last === null || stamp !== last)) { + await reloadRef.current(); + } + if (canCommit()) { + last = stamp; + } + } catch { + // Offline or the server is busy: try again on the next tick. + } finally { + checking = false; + } + }; + const onVisible = () => { + if (!document.hidden) { + check(); + } + }; + + check(); + const timer = window.setInterval(check, intervalMs); + document.addEventListener("visibilitychange", onVisible); + window.addEventListener("focus", onVisible); + return () => { + stopped = true; + window.clearInterval(timer); + document.removeEventListener("visibilitychange", onVisible); + window.removeEventListener("focus", onVisible); + }; + }, [datastoreId, intervalMs]); +} diff --git a/src/js/views/datastore/move-eligibility.ts b/src/js/views/datastore/move-eligibility.ts new file mode 100644 index 0000000..905af9c --- /dev/null +++ b/src/js/views/datastore/move-eligibility.ts @@ -0,0 +1,16 @@ +import type { Datastore, DatastoreItem } from "../../../types/datastore"; + +export const isMovableItem = (item: DatastoreItem) => + !Object.hasOwn(item, "share_id") && + (!Object.hasOwn(item, "share_rights") || item.share_rights!.delete !== false); + +const hasSharedChild = (item: Datastore): boolean => + Boolean(item.items?.some((child) => Object.hasOwn(child, "share_id"))) || + Boolean( + item.folders?.some( + (child) => Object.hasOwn(child, "share_id") || hasSharedChild(child), + ), + ); + +export const isMovableFolder = (item: DatastoreItem) => + isMovableItem(item) && !hasSharedChild(item); diff --git a/src/js/views/datastore/toolbar.tsx b/src/js/views/datastore/toolbar.tsx index dd293c1..812ec4b 100644 --- a/src/js/views/datastore/toolbar.tsx +++ b/src/js/views/datastore/toolbar.tsx @@ -2,10 +2,13 @@ import AddIcon from "@mui/icons-material/Add"; import CreateNewFolderIcon from "@mui/icons-material/CreateNewFolder"; import DeleteIcon from "@mui/icons-material/Delete"; import DeleteSweepIcon from "@mui/icons-material/DeleteSweep"; +import ChecklistIcon from "@mui/icons-material/Checklist"; +import DoneIcon from "@mui/icons-material/Done"; import FilterListIcon from "@mui/icons-material/FilterList"; import MenuOpenIcon from "@mui/icons-material/MenuOpen"; import OpenWithIcon from "@mui/icons-material/OpenWith"; import { Badge } from "@mui/material"; +import Button from "@mui/material/Button"; import Divider from "@mui/material/Divider"; import IconButton from "@mui/material/IconButton"; import ListItemIcon from "@mui/material/ListItemIcon"; @@ -27,6 +30,14 @@ import Search from "../../components/search"; const useStyles = makeStyles((theme) => ({ toolbarRoot: { backgroundColor: theme.palette.baseTitleBackground.main, + paddingLeft: "0 !important", + paddingRight: "0 !important", + paddingBottom: "12px", + minHeight: "auto !important", + height: "auto !important", + "& .MuiDivider-root": { + display: "none", + }, }, toolbarTitle: { display: "none", @@ -40,13 +51,31 @@ const useStyles = makeStyles((theme) => ({ "&:hover": { backgroundColor: alpha(theme.palette.lightBackground.main, 0.45), }, - marginLeft: "auto", - position: "absolute", - right: 0, - [theme.breakpoints.up("sm")]: { - marginRight: theme.spacing(1), + // SoLoVault: search first and wide, then the actions, all in one row. + display: "flex", + flexWrap: "wrap", + alignItems: "center", + gap: "8px", + width: "100%", + "& > :first-child": { + flex: "1 1 220px", + minWidth: 0, + }, + }, + quietButton: { + color: "#0f172a", + borderColor: "#cbd5e1", + backgroundColor: "#fff", + "&:hover": { + borderColor: "#94a3b8", + backgroundColor: "#f8fafc", }, }, + newButton: { + textTransform: "none", + whiteSpace: "nowrap", + height: "38px", + }, iconButton: { padding: 10, display: "inline-flex", @@ -75,6 +104,8 @@ interface DatastoreToolbarProps { onMassDelete: () => void; onMassMove: () => void; hasMassOperationSelected: boolean; + selecting?: boolean; + onToggleSelecting?: () => void; toggleShowFilter?: () => void; filterCount: number; } @@ -89,6 +120,8 @@ const DatastoreToolbar = ({ onMassDelete, onMassMove, hasMassOperationSelected, + selecting, + onToggleSelecting, toggleShowFilter, filterCount, }: DatastoreToolbarProps) => { @@ -116,7 +149,6 @@ const DatastoreToolbar = ({ }; return ( - {t("DATASTORE")} {newSecurityReportRequired && (
{!offlineMode && ( - - - + <> + + + {onToggleSelecting && ( + + + + )} + )} - handleClose(event as React.SyntheticEvent)} - onContextMenu={(event) => { - event.preventDefault(); - event.stopPropagation(); - }} - > - { - setAnchorEl(null); - onNewFolder(); - }} - > - - - - - {t("NEW_FOLDER")} - - - { - setAnchorEl(null); - onNewEntry(); - }} - > - - - - - {t("NEW_ENTRY")} - - - {!offlineMode && hasMassOperationSelected && ( <> diff --git a/src/js/views/index.tsx b/src/js/views/index.tsx index 1ffd502..a93dd69 100644 --- a/src/js/views/index.tsx +++ b/src/js/views/index.tsx @@ -37,6 +37,7 @@ import PopupPgpWriteView from "./popup-pgp-write"; import PrivacyPolicyView from "./privacy-policy"; import RegisterView from "./register"; import SecurityReportView from "./security-report"; +import SolovaultSettingsView from "./solovault-settings"; import SettingsView from "./settings"; import TrustedUsersView from "./trusted-users"; @@ -271,13 +272,13 @@ const IndexView = (props: object) => { - + - + - + diff --git a/src/js/views/open-secret/index.tsx b/src/js/views/open-secret/index.tsx index bc6da8f..d84a3c7 100644 --- a/src/js/views/open-secret/index.tsx +++ b/src/js/views/open-secret/index.tsx @@ -1,6 +1,5 @@ import { makeStyles } from "@mui/styles"; import React, { useState } from "react"; -import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import type { AuthErrorData } from "../../../types/auth"; import ConfigLogo from "../../components/config-logo"; @@ -10,17 +9,34 @@ import offlineCacheService from "../../services/offline-cache"; import secret from "../../services/secret"; const useStyles = makeStyles((theme) => ({ + page: { + position: "fixed", + inset: 0, + backgroundColor: "#f7f7f8", + overflow: "auto", + }, + logo: { + display: "block", + maxWidth: "100%", + maxHeight: 48, + margin: "0 auto", + }, + backLink: { + display: "inline-block", + marginTop: 16, + color: theme.palette.primary.main, + fontWeight: 600, + }, loadingLock: { width: 340, - padding: 20, - position: "absolute", - top: "50%", - left: "50%", - marginTop: -70, - marginLeft: -170, - borderRadius: 4, - backgroundColor: theme.palette.blueBackground.main, - color: theme.palette.lightGreyText.main, + maxWidth: "calc(100% - 32px)", + boxSizing: "border-box", + margin: "max(32px, calc(50vh - 120px)) auto 32px", + padding: 24, + borderRadius: 12, + backgroundColor: "#ffffff", + boxShadow: "0 8px 30px rgba(17, 24, 39, 0.08)", + color: "#374151", textAlign: "center", }, loadingLockLogo: { @@ -29,7 +45,7 @@ const useStyles = makeStyles((theme) => ({ height: 130, }, loadingLockLogoUnloaded: { - color: theme.palette.background.default, + color: "#e5e7eb", position: "absolute", top: 0, marginLeft: "50%", @@ -50,21 +66,16 @@ const useStyles = makeStyles((theme) => ({ loadingLockText: { marginTop: 20, }, - infolabel: { - position: "absolute", - top: 10, - right: 10, - color: theme.palette.lightGreyText.main, - textDecoration: "none", - }, error: { paddingTop: 20, }, })); +const NOT_OPENED = + "This entry couldn't be opened in this tab. Go back to your vault and open it from there."; + const OpenSecretView = () => { const classes = useStyles(); - const { t } = useTranslation(); const [percent, setPercentage] = React.useState(0); const [unlockOfflineCache, setUnlockOfflineCache] = React.useState(false); const [errors, setErrors] = useState([]); @@ -81,6 +92,9 @@ const OpenSecretView = () => { secret.redirectSecret(type, secretId).then( () => { setPercentage(100); + // Upstream resolves without opening anything when this tab can't + // read the entry; say so instead of "Opening…" forever. + window.setTimeout(() => setErrors([NOT_OPENED]), 3000); }, (error: AuthErrorData) => { console.log(error); @@ -98,47 +112,51 @@ const OpenSecretView = () => { }; return ( -
- - -