diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index c5ac4603ca..2bd8b6a75f 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -51,6 +51,7 @@ import { UserPreference, } from "@shared/types"; import { isMobile } from "@shared/utils/browser"; +import { isLinkNode } from "@shared/utils/collections"; import { Week } from "@shared/utils/time"; import type UserMembership from "~/models/UserMembership"; import Document from "~/models/Document"; @@ -135,10 +136,9 @@ export const openDocument = createActionWithChildren({ keywords: "go to", icon: , children: ({ stores, activeDocumentId, t }) => { - const nodes = stores.collections.navigationNodes.reduce( - (acc, node) => [...acc, ...node.children], - [] as NavigationNode[] - ); + const nodes = stores.collections.navigationNodes + .reduce((acc, node) => [...acc, ...node.children], [] as NavigationNode[]) + .filter((node) => !isLinkNode(node)); const documents = stores.documents.orderedData; // Documents already listed under "Recently viewed" are skipped so that they @@ -1359,7 +1359,7 @@ export const openRandomDocument = createAction({ perform: ({ stores, activeDocumentId }) => { const nodes = stores.collections.navigationNodes .reduce((acc, node) => [...acc, ...node.children], [] as NavigationNode[]) - .filter((node) => node.id !== activeDocumentId); + .filter((node) => node.id !== activeDocumentId && !isLinkNode(node)); const random = nodes[Math.round(Math.random() * nodes.length)]; diff --git a/app/components/CommandBar/SharedSearchActions.tsx b/app/components/CommandBar/SharedSearchActions.tsx index aa943d4a48..bf95420342 100644 --- a/app/components/CommandBar/SharedSearchActions.tsx +++ b/app/components/CommandBar/SharedSearchActions.tsx @@ -5,6 +5,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import useShare from "@shared/hooks/useShare"; import { NavigationNodeType, type NavigationNode } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; import { flattenTree } from "@shared/utils/tree"; import { createAction } from "~/actions"; import { RecentSection, SearchResultsSection } from "~/actions/sections"; @@ -28,7 +29,7 @@ const serverSearchDelay = 350; * document for document shares – only the latter are searchable. */ const isDocumentNode = (node: NavigationNode) => - node.type !== NavigationNodeType.Collection; + node.type !== NavigationNodeType.Collection && !isLinkNode(node); /** * Registers search result actions in the command bar scoped to a public share. diff --git a/app/components/DocumentMeta.tsx b/app/components/DocumentMeta.tsx index 32103aa3d7..94043931a7 100644 --- a/app/components/DocumentMeta.tsx +++ b/app/components/DocumentMeta.tsx @@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import styled from "styled-components"; import { ellipsis } from "@shared/styles"; +import { isLinkNode } from "@shared/utils/collections"; import type Document from "~/models/Document"; import type Revision from "~/models/Revision"; import DocumentBreadcrumb from "~/components/DocumentBreadcrumb"; @@ -166,7 +167,9 @@ const DocumentMeta: React.FC = ({ } const nestedDocumentsCount = collection - ? collection.getChildrenForDocument(document.id).length + ? collection + .getChildrenForDocument(document.id) + .filter((node) => !isLinkNode(node)).length : 0; const canShowProgressBar = isTasks; diff --git a/app/components/Icons/ArrowIcon.tsx b/app/components/Icons/ArrowIcon.tsx index 2507323410..a89bb3d22e 100644 --- a/app/components/Icons/ArrowIcon.tsx +++ b/app/components/Icons/ArrowIcon.tsx @@ -14,3 +14,7 @@ export const ArrowDownIcon = styled(ArrowRightIcon)` export const ArrowLeftIcon = styled(ArrowRightIcon)` transform: rotate(180deg); `; + +export const ArrowUpRightIcon = styled(ArrowRightIcon)` + transform: rotate(-45deg); +`; diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx index 70cdecc898..8c7a205d26 100644 --- a/app/components/Sidebar/components/CollectionLink.tsx +++ b/app/components/Sidebar/components/CollectionLink.tsx @@ -14,6 +14,7 @@ import * as Scenes from "~/routes/scenes"; import useBoolean from "~/hooks/useBoolean"; import { documentEditPath } from "~/utils/routeHelpers"; import { useDropToChangeCollection } from "../hooks/useDragAndDrop"; +import { useLinkDialog } from "../hooks/useLinkDialog"; import CollectionLinkChildren from "./CollectionLinkChildren"; import CollectionRow from "./CollectionRow"; import { useSidebarContext } from "./SidebarContext"; @@ -91,6 +92,11 @@ const CollectionLink: React.FC = ({ [user, sidebarContext, history, collection, documents] ); + const linkDialog = useLinkDialog(); + const handleNewLink = React.useCallback(() => { + linkDialog.openCreate(collection, undefined, handleExpand); + }, [linkDialog, collection, handleExpand]); + const contextMenuAction = useCollectionMenuAction({ collectionId: collection.id, onRename: handleRename, @@ -124,6 +130,7 @@ const CollectionLink: React.FC = ({ menuOpen={menuOpen} canCreateChild={!isDraggingAnyCollection && can.createDocument} onCreateChild={handleNewDoc} + onCreateLink={handleNewLink} parentRef={parentRef} dropRef={dropRef} isActiveDropTarget={isOver && canDrop} diff --git a/app/components/Sidebar/components/CollectionRow.tsx b/app/components/Sidebar/components/CollectionRow.tsx index a72e1173fd..4a9f2130dd 100644 --- a/app/components/Sidebar/components/CollectionRow.tsx +++ b/app/components/Sidebar/components/CollectionRow.tsx @@ -1,6 +1,5 @@ import type { Location, LocationDescriptor } from "history"; import { observer } from "mobx-react"; -import { PlusIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { mergeRefs } from "react-merge-refs"; @@ -11,11 +10,10 @@ import type Collection from "~/models/Collection"; import EditableTitle, { type RefHandle } from "~/components/EditableTitle"; import Fade from "~/components/Fade"; import CollectionIcon from "~/components/Icons/CollectionIcon"; -import NudeButton from "~/components/NudeButton"; -import Tooltip from "~/components/Tooltip"; import useBoolean from "~/hooks/useBoolean"; import { ActionContextProvider } from "~/hooks/useActionContext"; import DropToImport from "./DropToImport"; +import { NewChildMenu } from "./NewChildMenu"; import Relative from "./Relative"; import SidebarLink from "./SidebarLink"; import { StaticLink } from "./StaticLink"; @@ -72,6 +70,8 @@ export type CollectionRowProps = { /** When true, the "+" new-child button is rendered in the menu slot. */ canCreateChild?: boolean; + /** Opens the dialog to add a link below the row. When omitted, links cannot be added. */ + onCreateLink?: () => void; /** Submit handler for the inline new-child title input. */ onCreateChild?: (title: string) => Promise; /** Depth of the inline new-child SidebarLink. Defaults to one level below the row. */ @@ -112,6 +112,7 @@ function CollectionRow({ menuOpen, canCreateChild, onCreateChild, + onCreateLink, newChildDepth, parentRef, dropRef, @@ -132,14 +133,10 @@ function CollectionRow({ useBoolean(); const newChildTitleRef = React.useRef(null); - const handleAddChild = React.useCallback( - (ev: React.MouseEvent) => { - ev.preventDefault(); - setIsAddingNewChild(); - onExpand?.(); - }, - [setIsAddingNewChild, onExpand] - ); + const handleAddChild = React.useCallback(() => { + setIsAddingNewChild(); + onExpand?.(); + }, [setIsAddingNewChild, onExpand]); const handleNewChildSubmit = React.useCallback( async (value: string) => { @@ -194,14 +191,7 @@ function CollectionRow({ const menuElement = menuVisible ? ( {canCreateChild && ( - - - - - + )} {rowMenu} diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 47c6ac3358..c5add7d4e0 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -29,6 +29,7 @@ import { useDropToReorderDocument, useDropToReparentDocument, } from "../hooks/useDragAndDrop"; +import { useLinkDialog } from "../hooks/useLinkDialog"; import { useSidebarExpansion } from "./SidebarExpansionContext"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; @@ -273,6 +274,13 @@ const DocumentLink = observer(function DocumentLink({ ] ); + const linkDialog = useLinkDialog(); + const handleNewLink = React.useCallback(() => { + if (collection) { + linkDialog.openCreate(collection, node.id, handleExpand); + } + }, [linkDialog, collection, node.id, handleExpand]); + const contextMenuAction = useDocumentMenuAction({ documentId: node.id, onRename: handleRename, @@ -357,6 +365,7 @@ const DocumentLink = observer(function DocumentLink({ menuOpen={menuOpen} canCreateChild={can.createChildDocument} onCreateChild={handleNewDoc} + onCreateLink={collection && !isDraft ? handleNewLink : undefined} contextAction={contextMenuAction} isActiveOverride={isActiveCheck} onClickIntent={handlePrefetch} diff --git a/app/components/Sidebar/components/DocumentRow.tsx b/app/components/Sidebar/components/DocumentRow.tsx index eda31ebb72..9035b862de 100644 --- a/app/components/Sidebar/components/DocumentRow.tsx +++ b/app/components/Sidebar/components/DocumentRow.tsx @@ -1,6 +1,5 @@ import type { Location, LocationDescriptor } from "history"; import { observer } from "mobx-react"; -import { PlusIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import type { match } from "react-router"; @@ -9,11 +8,10 @@ import { DocumentValidation } from "@shared/validations"; import type Document from "~/models/Document"; import EditableTitle, { type RefHandle } from "~/components/EditableTitle"; import Fade from "~/components/Fade"; -import NudeButton from "~/components/NudeButton"; -import Tooltip from "~/components/Tooltip"; import useBoolean from "~/hooks/useBoolean"; import { ActionContextProvider } from "~/hooks/useActionContext"; import DropToImport from "./DropToImport"; +import { NewChildMenu } from "./NewChildMenu"; import Relative from "./Relative"; import SidebarLink from "./SidebarLink"; import { StaticLink } from "./StaticLink"; @@ -92,6 +90,8 @@ export type DocumentRowProps = { /** When true, the "+" new-child button is rendered in the menu slot. */ canCreateChild?: boolean; + /** Opens the dialog to add a link below the row. When omitted, links cannot be added. */ + onCreateLink?: () => void; /** Submit handler for the inline new-child title input. */ onCreateChild?: (title: string) => Promise; /** Depth of the inline new-child SidebarLink. Defaults to `depth + 1`. */ @@ -145,6 +145,7 @@ function DocumentRow({ menuOpen, canCreateChild, onCreateChild, + onCreateLink, newChildDepth, contextAction, isActiveOverride, @@ -180,14 +181,10 @@ function DocumentRow({ [hasChildren, expanded, onExpand, onCollapse] ); - const handleAddChild = React.useCallback( - (ev: React.MouseEvent) => { - ev.preventDefault(); - setIsAddingNewChild(); - onExpand?.(); - }, - [setIsAddingNewChild, onExpand] - ); + const handleAddChild = React.useCallback(() => { + setIsAddingNewChild(); + onExpand?.(); + }, [setIsAddingNewChild, onExpand]); const handleNewChildSubmit = React.useCallback( async (value: string) => { @@ -224,14 +221,7 @@ function DocumentRow({ const menuElement = menuVisible ? ( {canCreateChild && ( - - - - - + )} {menu} diff --git a/app/components/Sidebar/components/DocumentTree.tsx b/app/components/Sidebar/components/DocumentTree.tsx index deae349cde..51358d029d 100644 --- a/app/components/Sidebar/components/DocumentTree.tsx +++ b/app/components/Sidebar/components/DocumentTree.tsx @@ -5,7 +5,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import scrollIntoView from "scroll-into-view-if-needed"; import type { NavigationNode } from "@shared/types"; -import { sortNavigationNodes } from "@shared/utils/collections"; +import { isLinkNode, sortNavigationNodes } from "@shared/utils/collections"; import { flattenExpandedTree, type FlattenedTreeNode, @@ -19,6 +19,7 @@ import { useComputed } from "~/hooks/useComputed"; import useStores from "~/hooks/useStores"; import { useScrollMargin } from "../hooks/useScrollMargin"; import DocumentLink from "./DocumentLink"; +import { ExternalLink } from "./ExternalLink"; import { useDraggedItemId, useSidebarScrollElement } from "./DragActiveContext"; import { isActiveSidebarContext, useSidebarContext } from "./SidebarContext"; import { useSidebarExpansion } from "./SidebarExpansionContext"; @@ -212,15 +213,17 @@ export const DocumentTree = observer(function DocumentTree({ const getNavigationItems = React.useCallback( () => - rows.map((row) => ({ - id: row.node.id, - url: row.node.url, - title: row.node.title, - sidebarContext, - collapsedChildren: expansion.isExpanded(row.node.id) - ? undefined - : row.node.children, - })), + rows + .filter((row) => !isLinkNode(row.node)) + .map((row) => ({ + id: row.node.id, + url: row.node.url, + title: row.node.title, + sidebarContext, + collapsedChildren: expansion.isExpanded(row.node.id) + ? undefined + : row.node.children, + })), [rows, expansion, sidebarContext] ); useSidebarNavigation(containerRef, getNavigationItems); @@ -252,18 +255,27 @@ export const DocumentTree = observer(function DocumentTree({ {gap > 0 &&
}
- + {isLinkNode(row.node) ? ( + + ) : ( + + )}
); diff --git a/app/components/Sidebar/components/ExternalLink.tsx b/app/components/Sidebar/components/ExternalLink.tsx new file mode 100644 index 0000000000..0ad88fdd49 --- /dev/null +++ b/app/components/Sidebar/components/ExternalLink.tsx @@ -0,0 +1,109 @@ +import { observer } from "mobx-react"; +import { EditIcon, LinkIcon, TrashIcon } from "outline-icons"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import type { NavigationNode } from "@shared/types"; +import { errToString } from "@shared/utils/error"; +import { sanitizeUrl } from "@shared/utils/urls"; +import type Collection from "~/models/Collection"; +import { DropdownMenu } from "~/components/Menu/DropdownMenu"; +import { OverflowMenuButton } from "~/components/Menu/OverflowMenuButton"; +import { createAction } from "~/actions"; +import { DocumentSection } from "~/actions/sections"; +import useBoolean from "~/hooks/useBoolean"; +import { useMenuAction } from "~/hooks/useMenuAction"; +import usePolicy from "~/hooks/usePolicy"; +import { useLinkDialog } from "../hooks/useLinkDialog"; +import SidebarLink from "./SidebarLink"; + +interface Props { + /** The link node to render. */ + node: NavigationNode; + /** The collection that contains the link, required to edit it. */ + collection?: Collection; + /** Id of the document that contains the link, if any. */ + parentId?: string; + /** Indentation depth of the row. */ + depth: number; +} + +/** + * A sidebar row for a link to an external location, which opens in a new tab. + */ +export const ExternalLink = observer(function ExternalLink({ + node, + collection, + parentId, + depth, +}: Props) { + const { t } = useTranslation(); + const linkDialog = useLinkDialog(); + const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean(); + const canCollection = usePolicy(collection); + const canParent = usePolicy(parentId); + const canEdit = + !!collection && + (parentId ? canParent.createChildDocument : canCollection.createDocument); + + const handleEdit = React.useCallback(() => { + if (collection) { + linkDialog.openEdit(collection, node); + } + }, [linkDialog, collection, node]); + + const handleDelete = React.useCallback(async () => { + try { + await collection?.removeLink(node.id); + } catch (err) { + toast.error(errToString(err)); + } + }, [collection, node.id]); + + const actions = React.useMemo( + () => [ + createAction({ + name: `${t("Edit")}…`, + section: DocumentSection, + icon: , + visible: canEdit, + perform: handleEdit, + }), + createAction({ + name: t("Delete"), + section: DocumentSection, + icon: , + dangerous: true, + visible: canEdit, + perform: handleDelete, + }), + ], + [t, canEdit, handleEdit, handleDelete] + ); + const rootAction = useMenuAction(actions); + + const menu = canEdit ? ( + + + + ) : undefined; + + return ( + : undefined} + label={node.title} + contextAction={canEdit ? rootAction : undefined} + menu={menu} + $showActions={menuOpen} + /> + ); +}); diff --git a/app/components/Sidebar/components/LinkDialog.tsx b/app/components/Sidebar/components/LinkDialog.tsx new file mode 100644 index 0000000000..b8f327f658 --- /dev/null +++ b/app/components/Sidebar/components/LinkDialog.tsx @@ -0,0 +1,106 @@ +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; +import { isUrl, sanitizeUrl } from "@shared/utils/urls"; +import { NavigationLinkValidation } from "@shared/validations"; +import Button from "~/components/Button"; +import Flex from "~/components/Flex"; +import Input from "~/components/Input"; + +/** The values that can be edited in the link dialog. */ +export interface LinkDialogValues { + /** Title of the link. */ + title: string; + /** External url that the link points to. */ + url: string; +} + +interface Props { + /** Values to start with, when editing an existing link. */ + defaultValues?: LinkDialogValues; + /** Called with the values when the form is submitted. */ + onSubmit: (values: LinkDialogValues) => Promise; +} + +/** + * A form to create or edit a sidebar link to an external location. + */ +export function LinkDialog({ defaultValues, onSubmit }: Props) { + const { t } = useTranslation(); + const [url, setUrl] = React.useState(defaultValues?.url ?? ""); + const [title, setTitle] = React.useState(defaultValues?.title ?? ""); + const [isSaving, setIsSaving] = React.useState(false); + + const normalizedUrl = sanitizeUrl(url) ?? ""; + const isValidUrl = isUrl(normalizedUrl); + const hostname = isValidUrl ? new URL(normalizedUrl).hostname : undefined; + + const handleUrlChange = React.useCallback( + (ev: React.ChangeEvent) => { + setUrl(ev.target.value); + }, + [] + ); + + const handleTitleChange = React.useCallback( + (ev: React.ChangeEvent) => { + setTitle(ev.target.value); + }, + [] + ); + + const handleSubmit = React.useCallback( + async (ev: React.SyntheticEvent) => { + ev.preventDefault(); + if (!hostname) { + return; + } + + setIsSaving(true); + try { + await onSubmit({ + url: normalizedUrl, + title: title.trim() || hostname, + }); + } catch (err) { + toast.error(errToString(err)); + setIsSaving(false); + } + }, + [onSubmit, normalizedUrl, hostname, title] + ); + + return ( +
+ + + + + + + +
+ ); +} diff --git a/app/components/Sidebar/components/NewChildMenu.tsx b/app/components/Sidebar/components/NewChildMenu.tsx new file mode 100644 index 0000000000..bc92d52b28 --- /dev/null +++ b/app/components/Sidebar/components/NewChildMenu.tsx @@ -0,0 +1,71 @@ +import { LinkIcon, NewDocumentIcon, PlusIcon } from "outline-icons"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { DropdownMenu } from "~/components/Menu/DropdownMenu"; +import NudeButton from "~/components/NudeButton"; +import Tooltip from "~/components/Tooltip"; +import { createAction } from "~/actions"; +import { DocumentSection } from "~/actions/sections"; +import { useMenuAction } from "~/hooks/useMenuAction"; + +interface Props { + /** Called to start creating a nested document. */ + onNewDoc: () => void; + /** Called to start creating a link. When omitted, the button creates a document directly. */ + onNewLink?: () => void; +} + +/** + * The "+" button on a sidebar row, which adds a nested document or link. + */ +export function NewChildMenu({ onNewDoc, onNewLink }: Props) { + const { t } = useTranslation(); + + const handleClick = React.useCallback( + (ev: React.MouseEvent) => { + ev.preventDefault(); + onNewDoc(); + }, + [onNewDoc] + ); + + const actions = React.useMemo( + () => [ + createAction({ + name: t("Document"), + section: DocumentSection, + icon: , + perform: onNewDoc, + }), + createAction({ + name: `${t("Link")}…`, + section: DocumentSection, + icon: , + visible: !!onNewLink, + perform: () => onNewLink?.(), + }), + ], + [t, onNewDoc, onNewLink] + ); + const rootAction = useMenuAction(actions); + + if (!onNewLink) { + return ( + + + + + + ); + } + + return ( + + + + + + + + ); +} diff --git a/app/components/Sidebar/components/SharedCollectionLink.tsx b/app/components/Sidebar/components/SharedCollectionLink.tsx index 212a25389d..d43cb0b12c 100644 --- a/app/components/Sidebar/components/SharedCollectionLink.tsx +++ b/app/components/Sidebar/components/SharedCollectionLink.tsx @@ -2,8 +2,10 @@ import { observer } from "mobx-react"; import { useTranslation } from "react-i18next"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; import useStores from "~/hooks/useStores"; import { sharedModelPath } from "~/utils/routeHelpers"; +import { ExternalLink } from "./ExternalLink"; import { SharedDocumentLink } from "./SharedDocumentLink"; import SidebarLink from "./SidebarLink"; @@ -40,18 +42,26 @@ function CollectionLink({ node, shareId, hideRootNode }: Props) { isActive={() => ui.activeCollectionId === node.id} /> )} - {node.children.map((childNode, index) => ( - - ))} + {node.children.map((childNode, index) => + isLinkNode(childNode) ? ( + + ) : ( + + ) + )} ); } diff --git a/app/components/Sidebar/components/SharedDocumentLink.tsx b/app/components/Sidebar/components/SharedDocumentLink.tsx index 47760bd581..ef4348831b 100644 --- a/app/components/Sidebar/components/SharedDocumentLink.tsx +++ b/app/components/Sidebar/components/SharedDocumentLink.tsx @@ -3,10 +3,12 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; import type Collection from "~/models/Collection"; import type Document from "~/models/Document"; import useStores from "~/hooks/useStores"; import { sharedModelPath } from "~/utils/routeHelpers"; +import { ExternalLink } from "./ExternalLink"; import { useSidebarExpansion } from "./SidebarExpansionContext"; import SidebarLink from "./SidebarLink"; @@ -130,21 +132,29 @@ function DocumentLink({ isActive={() => !!isActiveDocument} /> {expanded && - nodeChildren.map((childNode, index) => ( - - ))} + nodeChildren.map((childNode, index) => + isLinkNode(childNode) ? ( + + ) : ( + + ) + )} ); } diff --git a/app/components/Sidebar/components/SidebarLink.tsx b/app/components/Sidebar/components/SidebarLink.tsx index 1c5211788a..accab8a248 100644 --- a/app/components/Sidebar/components/SidebarLink.tsx +++ b/app/components/Sidebar/components/SidebarLink.tsx @@ -4,6 +4,7 @@ import styled, { useTheme, css } from "styled-components"; import { breakpoint } from "@shared/styles/breakpoint"; import { ellipsis, hover, s } from "@shared/styles"; import { isMobile } from "@shared/utils/browser"; +import { ArrowUpRightIcon } from "~/components/Icons/ArrowIcon"; import { UnreadBadge } from "~/components/UnreadBadge"; import useClickIntent from "~/hooks/useClickIntent"; import { undraggableOnDesktop } from "~/styles"; @@ -86,6 +87,8 @@ type Props = Omit & { scrollIntoViewIfNeeded?: boolean; /** Optional context menu action to display */ contextAction?: ActionWithChildren | ActionFactory; + /** Whether the link points to an external location, opened in a new tab */ + external?: boolean; }; const activeDropStyle = { @@ -118,6 +121,7 @@ function SidebarLink({ disabled, unreadBadge, contextAction, + external, ellipsis = true, ref, ...rest @@ -192,6 +196,7 @@ function SidebarLink({ )} {icon && {icon}} + {external && } {unreadBadge && } ); @@ -226,6 +231,8 @@ function SidebarLink({ onMouseLeave={handleMouseLeave} onDragEnter={handleMouseEnter} href={href} + target={external ? "_blank" : undefined} + rel={external ? "noopener noreferrer" : undefined} className={className} ref={ref} {...rest} @@ -271,6 +278,13 @@ export const IconWrapper = styled.span` transition: opacity 200ms ease-in-out; `; +const ExternalIcon = styled(ArrowUpRightIcon)` + flex-shrink: 0; + align-self: center; + margin-inline-start: 4px; + color: ${s("textTertiary")}; +`; + const Content = styled.span` display: flex; align-items: start; diff --git a/app/components/Sidebar/hooks/useLinkDialog.tsx b/app/components/Sidebar/hooks/useLinkDialog.tsx new file mode 100644 index 0000000000..98eae09017 --- /dev/null +++ b/app/components/Sidebar/hooks/useLinkDialog.tsx @@ -0,0 +1,58 @@ +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import type { NavigationNode } from "@shared/types"; +import type Collection from "~/models/Collection"; +import useStores from "~/hooks/useStores"; +import { LinkDialog, type LinkDialogValues } from "../components/LinkDialog"; + +/** + * Returns functions that open the dialog to add or edit a sidebar link. + * + * @returns functions to open the create and edit dialogs. + */ +export function useLinkDialog() { + const { dialogs } = useStores(); + const { t } = useTranslation(); + + const openCreate = React.useCallback( + ( + collection: Collection, + parentDocumentId?: string, + onCreated?: () => void + ) => { + const handleSubmit = async (values: LinkDialogValues) => { + await collection.addLink(values, parentDocumentId); + onCreated?.(); + dialogs.closeAllModals(); + }; + + dialogs.openModal({ + title: t("Add link"), + content: , + }); + }, + [dialogs, t] + ); + + const openEdit = React.useCallback( + (collection: Collection, node: NavigationNode) => { + const handleSubmit = async (values: LinkDialogValues) => { + await collection.updateLink(node.id, values); + dialogs.closeAllModals(); + }; + + dialogs.openModal({ + title: t("Edit link"), + content: ( + + ), + }); + }, + [dialogs, t] + ); + + return { openCreate, openEdit }; +} diff --git a/app/hooks/useCollectionTrees.ts b/app/hooks/useCollectionTrees.ts index a106ce8fa9..0c20f6ff74 100644 --- a/app/hooks/useCollectionTrees.ts +++ b/app/hooks/useCollectionTrees.ts @@ -1,6 +1,6 @@ import type { CollectionSort, NavigationNode } from "@shared/types"; import { NavigationNodeType } from "@shared/types"; -import { sortNavigationNodes } from "@shared/utils/collections"; +import { isLinkNode, sortNavigationNodes } from "@shared/utils/collections"; import { useComputed } from "~/hooks/useComputed"; import useStores from "~/hooks/useStores"; import type Collection from "~/models/Collection"; @@ -66,7 +66,10 @@ function annotateNodes( return []; } - return sortNavigationNodes(nodes, sort, false).map((node) => { + // Links are not documents, so they cannot be a destination or be selected. + const documents = nodes.filter((node) => !isLinkNode(node)); + + return sortNavigationNodes(documents, sort, false).map((node) => { const annotated: NavigationNode = { ...node, type: node.type ?? NavigationNodeType.Document, diff --git a/app/models/Collection.ts b/app/models/Collection.ts index 792ba38d57..68c7ec98c8 100644 --- a/app/models/Collection.ts +++ b/app/models/Collection.ts @@ -373,6 +373,87 @@ export default class Collection extends ParanoidModel { travelNodes(this.documents); } + /** + * Adds a link to an external location to the collection structure. + * + * @param attributes The title and url of the link. + * @param parentDocumentId The id of the document to add the link below, if any. + * @returns A promise that resolves to the new link node. + */ + addLink = async ( + attributes: Pick, + parentDocumentId?: string + ): Promise => { + const res = await client.post("/collections.add_link", { + id: this.id, + parentDocumentId, + ...attributes, + }); + invariant(res?.data, "Data should be available"); + + runInAction(() => { + if (!this.documents) { + return; + } + if (!parentDocumentId) { + this.documents = [...this.documents, res.data]; + return; + } + this.documents = this.mapNodes(this.documents, (node) => + node.id === parentDocumentId + ? { ...node, children: [...node.children, res.data] } + : node + ); + }); + + return res.data; + }; + + /** + * Updates a link to an external location in the collection structure. + * + * @param linkId The id of the link. + * @param attributes The title and url of the link. + * @returns A promise that resolves when the link is updated. + */ + updateLink = async ( + linkId: string, + attributes: Partial> + ): Promise => { + const res = await client.post("/collections.update_link", { + id: this.id, + linkId, + ...attributes, + }); + invariant(res?.data, "Data should be available"); + + runInAction(() => { + if (!this.documents) { + return; + } + this.documents = this.mapNodes(this.documents, (node) => + node.id === linkId ? { ...res.data, children: node.children } : node + ); + }); + }; + + /** + * Removes a link to an external location from the collection structure. + * + * @param linkId The id of the link. + * @returns A promise that resolves when the link is removed. + */ + removeLink = async (linkId: string): Promise => { + await client.post("/collections.remove_link", { + id: this.id, + linkId, + }); + + runInAction(() => { + this.removeDocument(linkId); + }); + }; + @action updateIndex(index: string) { this.index = index; @@ -494,5 +575,30 @@ export default class Collection extends ParanoidModel { } } + /** + * Returns a copy of the given tree with each node replaced by the result of + * the callback. Children of a replaced node are not visited, and unchanged + * nodes keep their reference. + * + * @param nodes The nodes to map. + * @param callback Returns the replacement for a node, or the node itself. + * @returns The mapped nodes. + */ + private mapNodes( + nodes: NavigationNode[], + callback: (node: NavigationNode) => NavigationNode + ): NavigationNode[] { + return nodes.map((node) => { + const result = callback(node); + if (result !== node) { + return result; + } + const children = this.mapNodes(node.children ?? [], callback); + return children.every((child, index) => child === node.children[index]) + ? node + : { ...node, children }; + }); + } + private isFetching = false; } diff --git a/app/scenes/Collection/components/CollectionMeta.tsx b/app/scenes/Collection/components/CollectionMeta.tsx index 1599679ca0..cb7dfb8099 100644 --- a/app/scenes/Collection/components/CollectionMeta.tsx +++ b/app/scenes/Collection/components/CollectionMeta.tsx @@ -4,6 +4,7 @@ import { useEffect } from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { breakpoint } from "@shared/styles/breakpoint"; +import { isLinkNode } from "@shared/utils/collections"; import { flattenTree } from "@shared/utils/tree"; import type Collection from "~/models/Collection"; import Flex from "~/components/Flex"; @@ -39,7 +40,9 @@ export const CollectionMeta = observer(function CollectionMeta_({ }, [collection]); const documentCount = collection.documents - ? flattenTree(collection.asNavigationNode).length - 1 + ? flattenTree(collection.asNavigationNode).filter( + (node) => !isLinkNode(node) + ).length - 1 : undefined; return ( diff --git a/app/scenes/Document/components/References.tsx b/app/scenes/Document/components/References.tsx index 8a6e170538..7ad56ea898 100644 --- a/app/scenes/Document/components/References.tsx +++ b/app/scenes/Document/components/References.tsx @@ -17,6 +17,7 @@ import ReferenceListItem, { } from "./ReferenceListItem"; import useShare from "@shared/hooks/useShare"; import type { NavigationNode } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; import { flattenTree } from "@shared/utils/tree"; type Props = { @@ -163,7 +164,7 @@ function useChildren( document: Document, sharedTree: NavigationNode | undefined ): NavigationNode[] { - return useMemo(() => { + const children = useMemo(() => { if (!sharedTree) { return document.children; } @@ -185,6 +186,11 @@ function useChildren( return findChildren(sharedTree) || []; }, [document.id, document.children, sharedTree]); + + return useMemo( + () => children.filter((node) => !isLinkNode(node)), + [children] + ); } /** diff --git a/app/scenes/DocumentDelete.tsx b/app/scenes/DocumentDelete.tsx index a8d05716b9..05125881ac 100644 --- a/app/scenes/DocumentDelete.tsx +++ b/app/scenes/DocumentDelete.tsx @@ -3,6 +3,7 @@ import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; +import { isLinkNode } from "@shared/utils/collections"; import { errToString } from "@shared/utils/error"; import type Document from "~/models/Document"; import Button from "~/components/Button"; @@ -28,7 +29,9 @@ function DocumentDelete({ document, onSubmit }: Props) { ? collections.get(document.collectionId) : undefined; const nestedDocumentsCount = collection - ? collection.getChildrenForDocument(document.id).length + ? collection + .getChildrenForDocument(document.id) + .filter((node) => !isLinkNode(node)).length : 0; const handleSubmit = React.useCallback( async (ev: React.SyntheticEvent) => { diff --git a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts index 007c32466c..874f6e1855 100644 --- a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts +++ b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts @@ -323,6 +323,9 @@ export default class DeliverWebhookTask extends BaseTask { case "passkeys.create": case "passkeys.update": case "passkeys.delete": + case "collections.add_link": + case "collections.update_link": + case "collections.remove_link": // Ignored return; default: diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 6eec80aa63..c84815004e 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -52,7 +52,7 @@ import type { } from "@shared/types"; import { CollectionPermission, NavigationNodeType } from "@shared/types"; import { UrlHelper } from "@shared/utils/UrlHelper"; -import { sortNavigationNodes } from "@shared/utils/collections"; +import { isLinkNode, sortNavigationNodes } from "@shared/utils/collections"; import slugify from "@server/utils/slugify"; import { CollectionValidation, @@ -1250,6 +1250,9 @@ class Collection extends ParanoidModel< const allDocumentIds: string[] = []; const loopChildren = (node: NavigationNode) => { + if (isLinkNode(node)) { + return; + } allDocumentIds.push(node.id); (node.children ?? []).forEach((childNode) => { loopChildren(childNode); @@ -1260,6 +1263,115 @@ class Collection extends ParanoidModel< return allDocumentIds; }; + /** + * Finds a link node in the documentStructure. + * + * @param linkId the id of the link node. + * @returns the link node and the id of its parent document, or undefined if not found. + */ + findLinkInStructure = ( + linkId: string + ): { node: NavigationNode; parentDocumentId?: string } | undefined => { + const search = ( + nodes: NavigationNode[], + parentDocumentId?: string + ): { node: NavigationNode; parentDocumentId?: string } | undefined => { + for (const node of nodes) { + if (node.id === linkId && isLinkNode(node)) { + return { node, parentDocumentId }; + } + const result = search(node.children ?? [], node.id); + if (result) { + return result; + } + } + return undefined; + }; + + return search(this.documentStructure ?? []); + }; + + /** + * Adds a link node to the documentStructure, at the end of the given parent. + * + * @param node the link node to add. + * @param parentDocumentId the id of the parent document, or undefined for the root. + * @param options options passed to save. + * @returns the updated collection. + */ + addLinkToStructure = async ( + node: NavigationNode, + parentDocumentId: string | undefined, + options?: { transaction?: Transaction | null } + ) => { + const structure = this.documentStructure ?? []; + + if (!parentDocumentId) { + this.documentStructure = [...structure, node]; + } else { + const place = (nodes: NavigationNode[]): NavigationNode[] => + nodes.map((child) => + child.id === parentDocumentId + ? { ...child, children: [...(child.children ?? []), node] } + : { ...child, children: place(child.children ?? []) } + ); + this.documentStructure = place(structure); + } + + this.changed("documentStructure", true); + return this.save({ ...options, fields: ["documentStructure"] }); + }; + + /** + * Updates the title and url of a link node in the documentStructure. + * + * @param linkId the id of the link node. + * @param attributes the attributes to update. + * @param options options passed to save. + * @returns the updated collection. + */ + updateLinkInStructure = async ( + linkId: string, + attributes: Partial>, + options?: { transaction?: Transaction | null } + ) => { + const update = (nodes: NavigationNode[]): NavigationNode[] => + nodes.map((node) => + node.id === linkId && isLinkNode(node) + ? { + ...node, + title: attributes.title ?? node.title, + url: attributes.url ?? node.url, + } + : { ...node, children: update(node.children ?? []) } + ); + + this.documentStructure = update(this.documentStructure ?? []); + this.changed("documentStructure", true); + return this.save({ ...options, fields: ["documentStructure"] }); + }; + + /** + * Removes a link node from the documentStructure. + * + * @param linkId the id of the link node. + * @param options options passed to save. + * @returns the updated collection. + */ + removeLinkFromStructure = async ( + linkId: string, + options?: { transaction?: Transaction | null } + ) => { + const remove = (nodes: NavigationNode[]): NavigationNode[] => + nodes + .filter((node) => !(node.id === linkId && isLinkNode(node))) + .map((node) => ({ ...node, children: remove(node.children ?? []) })); + + this.documentStructure = remove(this.documentStructure ?? []); + this.changed("documentStructure", true); + return this.save({ ...options, fields: ["documentStructure"] }); + }; + /** * Returns a JSON representation of this collection suitable for use in the frontend navigation. * diff --git a/server/presenters/navigationNode.ts b/server/presenters/navigationNode.ts index 72eafa0a6c..96517fd477 100644 --- a/server/presenters/navigationNode.ts +++ b/server/presenters/navigationNode.ts @@ -1,10 +1,14 @@ import type { Team } from "@server/models"; import type { NavigationNode } from "@shared/types"; +import { NavigationNodeType } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; export interface PresentedNavigationNode { id: string; title: string; url: string; + /** Set for links to external locations, which are not documents. */ + type?: NavigationNodeType.Link; children: PresentedNavigationNode[]; } @@ -26,6 +30,7 @@ export default function presentNavigationNode( url: /^https?:\/\//.test(node.url) ? node.url : new URL(node.url, team.url).href, + type: isLinkNode(node) ? NavigationNodeType.Link : undefined, children: (node.children ?? []).map((child) => presentNavigationNode(team, child) ), diff --git a/server/queues/processors/WebsocketsProcessor.ts b/server/queues/processors/WebsocketsProcessor.ts index a213933c31..5a7d5f1bde 100644 --- a/server/queues/processors/WebsocketsProcessor.ts +++ b/server/queues/processors/WebsocketsProcessor.ts @@ -459,6 +459,28 @@ export default class WebsocketsProcessor { }); } + case "collections.add_link": + case "collections.update_link": + case "collections.remove_link": { + const collection = await Collection.findOne({ + where: { id: event.collectionId }, + attributes: ["id", "updatedAt"], + }); + if (!collection) { + return; + } + + return socketio.to(`collection-${collection.id}`).emit("entities", { + event: event.name, + collectionIds: [ + { + id: collection.id, + updatedAt: collection.updatedAt, + }, + ], + }); + } + case "collections.move": { return socketio .to(`collection-${event.collectionId}`) diff --git a/server/queues/tasks/ExportDocumentTreeTask.ts b/server/queues/tasks/ExportDocumentTreeTask.ts index 04c584e13e..3bb134b09a 100644 --- a/server/queues/tasks/ExportDocumentTreeTask.ts +++ b/server/queues/tasks/ExportDocumentTreeTask.ts @@ -4,6 +4,7 @@ import type { ZipFile } from "yazl"; import { errToString } from "@shared/utils/error"; import type { NavigationNode } from "@shared/types"; import { FileOperationFormat } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; import Logger from "@server/logging/Logger"; import type { Collection } from "@server/models"; import Attachment from "@server/models/Attachment"; @@ -439,6 +440,10 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { format: FileOperationFormat ) { for (const node of nodes) { + if (isLinkNode(node)) { + continue; + } + const title = serializeFilename(node.title) || "Untitled"; const extension = ExportDocumentTreeTask.extensionForFormat(format); diff --git a/server/queues/tasks/ExportJSONTask.ts b/server/queues/tasks/ExportJSONTask.ts index 443d717303..ba8b0b7662 100644 --- a/server/queues/tasks/ExportJSONTask.ts +++ b/server/queues/tasks/ExportJSONTask.ts @@ -1,6 +1,7 @@ import type { ZipFile } from "yazl"; import { omit } from "es-toolkit/compat"; import type { NavigationNode } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; import env from "@server/env"; import type { Collection, FileOperation } from "@server/models"; import { Attachment, Document } from "@server/models"; @@ -98,6 +99,10 @@ export default class ExportJSONTask extends ExportTask { const addDocumentTree = async (nodes: NavigationNode[]) => { for (const node of nodes) { + if (isLinkNode(node)) { + continue; + } + const result = await sequelizeReadOnly.transaction( async (transaction) => { const document = await Document.findByPk(node.id, { diff --git a/server/routes/api/collections/collections.test.ts b/server/routes/api/collections/collections.test.ts index c9d16e58f5..51d9affa1b 100644 --- a/server/routes/api/collections/collections.test.ts +++ b/server/routes/api/collections/collections.test.ts @@ -6,6 +6,7 @@ import { } from "@shared/types"; import { DeprecationValidation } from "@shared/validations"; import { + Collection, Document, UserMembership, GroupMembership, @@ -999,6 +1000,239 @@ describe("#collections.add_user", () => { }); }); +describe("#collections.add_link", () => { + it("should add a link to the root of the collection", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + + const res = await server.post("/api/collections.add_link", user, { + body: { + id: collection.id, + title: "Status page", + url: "https://status.example.com", + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.type).toEqual("link"); + expect(body.data.title).toEqual("Status page"); + expect(body.data.url).toEqual("https://status.example.com"); + + const reloaded = await Collection.findByPk(collection.id, { + includeDocumentStructure: true, + rejectOnEmpty: true, + }); + expect(reloaded.documentStructure).toEqual([body.data]); + expect(reloaded.getAllDocumentIds()).toEqual([]); + }); + + it("should add a link below a document", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/collections.add_link", user, { + body: { + id: collection.id, + parentDocumentId: document.id, + title: "Design", + url: "https://example.com/design", + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + const reloaded = await Collection.findByPk(collection.id, { + includeDocumentStructure: true, + rejectOnEmpty: true, + }); + expect(reloaded.getDocumentTree(document.id)?.children).toEqual([ + body.data, + ]); + }); + + it("should not allow a parent document in another collection", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + }); + + const res = await server.post("/api/collections.add_link", user, { + body: { + id: collection.id, + parentDocumentId: document.id, + title: "Design", + url: "https://example.com/design", + }, + }); + + expect(res.status).toEqual(400); + }); + + it("should not allow unsafe urls", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + + const res = await server.post("/api/collections.add_link", user, { + body: { + id: collection.id, + title: "Unsafe", + url: "javascript:alert(1)", + }, + }); + + expect(res.status).toEqual(400); + }); + + it("should require permission to create documents", async () => { + const viewer = await buildViewer(); + const collection = await buildCollection({ + teamId: viewer.teamId, + }); + + const res = await server.post("/api/collections.add_link", viewer, { + body: { + id: collection.id, + title: "Status page", + url: "https://status.example.com", + }, + }); + + expect(res.status).toEqual(403); + }); +}); + +describe("#collections.update_link", () => { + it("should update a link", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const created = await server.post("/api/collections.add_link", user, { + body: { + id: collection.id, + title: "Status page", + url: "https://status.example.com", + }, + }); + const link = (await created.json()).data; + + const res = await server.post("/api/collections.update_link", user, { + body: { + id: collection.id, + linkId: link.id, + title: "Status", + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.title).toEqual("Status"); + expect(body.data.url).toEqual("https://status.example.com"); + }); + + it("should not update a document", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/collections.update_link", user, { + body: { + id: collection.id, + linkId: document.id, + url: "https://example.com", + }, + }); + + expect(res.status).toEqual(404); + }); +}); + +describe("#collections.remove_link", () => { + it("should remove a link", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const created = await server.post("/api/collections.add_link", user, { + body: { + id: collection.id, + title: "Status page", + url: "https://status.example.com", + }, + }); + const link = (await created.json()).data; + + const res = await server.post("/api/collections.remove_link", user, { + body: { + id: collection.id, + linkId: link.id, + }, + }); + + expect(res.status).toEqual(200); + const reloaded = await Collection.findByPk(collection.id, { + includeDocumentStructure: true, + rejectOnEmpty: true, + }); + expect(reloaded.documentStructure).toEqual([]); + }); + + it("should require permission to create documents", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const viewer = await buildViewer({ teamId: user.teamId }); + const created = await server.post("/api/collections.add_link", user, { + body: { + id: collection.id, + title: "Status page", + url: "https://status.example.com", + }, + }); + const link = (await created.json()).data; + + const res = await server.post("/api/collections.remove_link", viewer, { + body: { + id: collection.id, + linkId: link.id, + }, + }); + + expect(res.status).toEqual(403); + }); +}); + describe("#collections.add_group", () => { it("should preserve existing permission when permission is omitted", async () => { const admin = await buildAdmin(); diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 725060b5a3..79e69ad870 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -10,10 +10,13 @@ import { FileOperationFormat, ImportState, IntegrationService, + NavigationNodeType, + type NavigationNode, UserRole, } from "@shared/types"; import { ImportValidation } from "@shared/validations"; import collectionDuplicator from "@server/commands/collectionDuplicator"; +import { authorizeDocumentCreate } from "@server/commands/documentCreator"; import teamUpdater from "@server/commands/teamUpdater"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; @@ -28,6 +31,7 @@ import { Group, Attachment, Document, + Event, Import, FileOperation, } from "@server/models"; @@ -52,7 +56,7 @@ import { collectionIndexing } from "@server/utils/indexing"; import { QueryHelper } from "@server/storage/QueryHelper"; import pagination from "../middlewares/pagination"; import * as T from "./schema"; -import { InvalidRequestError } from "@server/errors"; +import { InvalidRequestError, NotFoundError } from "@server/errors"; const router = new Router(); @@ -186,6 +190,91 @@ router.post( } ); +router.post( + "collections.add_link", + auth(), + validate(T.CollectionsAddLinkSchema), + transaction(), + async (ctx: APIContext) => { + const { transaction } = ctx.state; + const { id, parentDocumentId, title, url } = ctx.input.body; + + const collection = await loadCollectionForLink(ctx, id, parentDocumentId); + const node: NavigationNode = { + id: randomUUID(), + type: NavigationNodeType.Link, + title, + url, + children: [], + }; + + await collection.addLinkToStructure(node, parentDocumentId ?? undefined, { + transaction, + }); + await Event.createFromContext(ctx, { + name: "collections.add_link", + collectionId: collection.id, + modelId: node.id, + data: { title, url }, + }); + + ctx.body = { + data: node, + }; + } +); + +router.post( + "collections.update_link", + auth(), + validate(T.CollectionsUpdateLinkSchema), + transaction(), + async (ctx: APIContext) => { + const { transaction } = ctx.state; + const { id, linkId, title, url } = ctx.input.body; + + const collection = await loadCollectionForExistingLink(ctx, id, linkId); + await collection.updateLinkInStructure( + linkId, + { title, url }, + { transaction } + ); + await Event.createFromContext(ctx, { + name: "collections.update_link", + collectionId: collection.id, + modelId: linkId, + data: { title, url }, + }); + + ctx.body = { + data: collection.findLinkInStructure(linkId)?.node, + }; + } +); + +router.post( + "collections.remove_link", + auth(), + validate(T.CollectionsRemoveLinkSchema), + transaction(), + async (ctx: APIContext) => { + const { transaction } = ctx.state; + const { id, linkId } = ctx.input.body; + + const collection = await loadCollectionForExistingLink(ctx, id, linkId); + await collection.removeLinkFromStructure(linkId, { transaction }); + await Event.createFromContext(ctx, { + name: "collections.remove_link", + collectionId: collection.id, + modelId: linkId, + }); + + ctx.body = { + success: true, + }; + } +); + router.post( "collections.import", rateLimiter(RateLimiterStrategy.TenPerHour), @@ -971,4 +1060,83 @@ router.post( } ); +/** + * Authorizes the user to change links at the given location, with the same + * rules as creating a document there, and loads the collection with its + * structure locked for update. + * + * @param ctx the API context. + * @param collectionId the id of the collection. + * @param parentDocumentId the id of the parent document, if any. + * @returns the collection, with its documentStructure. + */ +async function loadCollectionForLink( + ctx: APIContext, + collectionId: string, + parentDocumentId: string | null | undefined +) { + const { transaction } = ctx.state; + const { collection } = await authorizeDocumentCreate(ctx, { + collectionId, + parentDocumentId, + }); + + // With a parent document, the collection is resolved from the parent. + if (collection?.id !== collectionId) { + throw InvalidRequestError("Parent document is not in the collection"); + } + + const locked = await Collection.findByPk(collection.id, { + includeDocumentStructure: true, + rejectOnEmpty: true, + transaction, + lock: transaction.LOCK.NO_KEY_UPDATE, + }); + + if (parentDocumentId && !locked.getDocumentTree(parentDocumentId)) { + throw InvalidRequestError("Parent document is not in the collection"); + } + + return locked; +} + +/** + * Loads the collection that contains the given link, after authorizing the + * user to change links at its location. + * + * @param ctx the API context. + * @param collectionId the id of the collection. + * @param linkId the id of the link. + * @returns the collection, with its documentStructure. + * @throws NotFoundError if the link is not in the collection. + */ +async function loadCollectionForExistingLink( + ctx: APIContext, + collectionId: string, + linkId: string +) { + const { user } = ctx.state.auth; + const existing = await Collection.findByPk(collectionId, { + userId: user.id, + includeDocumentStructure: true, + transaction: ctx.state.transaction, + }); + authorize(user, "readDocument", existing); + + const link = existing.findLinkInStructure(linkId); + if (!link) { + throw NotFoundError("Link not found"); + } + + const collection = await loadCollectionForLink( + ctx, + existing.id, + link.parentDocumentId + ); + if (!collection.findLinkInStructure(linkId)) { + throw NotFoundError("Link not found"); + } + return collection; +} + export default router; diff --git a/server/routes/api/collections/schema.ts b/server/routes/api/collections/schema.ts index 8e45e563eb..532997d4b2 100644 --- a/server/routes/api/collections/schema.ts +++ b/server/routes/api/collections/schema.ts @@ -6,7 +6,11 @@ import { CollectionStatusFilter, FileOperationFormat, } from "@shared/types"; -import { DeprecationValidation } from "@shared/validations"; +import { isUrl } from "@shared/utils/urls"; +import { + DeprecationValidation, + NavigationLinkValidation, +} from "@shared/validations"; import { Collection } from "@server/models"; import { zodIconType, zodIdType, zodShareIdType } from "@server/utils/zod"; import { ValidateColor, ValidateIndex } from "@server/validation"; @@ -313,3 +317,60 @@ export const CollectionsMoveSchema = BaseSchema.extend({ }); export type CollectionsMoveReq = z.infer; + +const LinkTitleSchema = z + .string() + .trim() + .min(1) + .max(NavigationLinkValidation.maxTitleLength); + +const LinkUrlSchema = z + .string() + .trim() + .max(NavigationLinkValidation.maxUrlLength) + .refine((url) => isUrl(url), { message: "Must be a valid url" }); + +/** Links are changed by collection id, so that it can be compared to the parent's. */ +const LinkCollectionIdSchema = z.object({ + /** Id of the collection that contains the link. */ + id: z.uuid(), +}); + +export const CollectionsAddLinkSchema = BaseSchema.extend({ + body: LinkCollectionIdSchema.extend({ + /** Id of the document to add the link below, if any. */ + parentDocumentId: z.uuid().nullish(), + /** Title of the link. */ + title: LinkTitleSchema, + /** External url that the link points to. */ + url: LinkUrlSchema, + }), +}); + +export type CollectionsAddLinkReq = z.infer; + +export const CollectionsUpdateLinkSchema = BaseSchema.extend({ + body: LinkCollectionIdSchema.extend({ + /** Id of the link to update. */ + linkId: z.uuid(), + /** Title of the link. */ + title: LinkTitleSchema.optional(), + /** External url that the link points to. */ + url: LinkUrlSchema.optional(), + }), +}); + +export type CollectionsUpdateLinkReq = z.infer< + typeof CollectionsUpdateLinkSchema +>; + +export const CollectionsRemoveLinkSchema = BaseSchema.extend({ + body: LinkCollectionIdSchema.extend({ + /** Id of the link to remove. */ + linkId: z.uuid(), + }), +}); + +export type CollectionsRemoveLinkReq = z.infer< + typeof CollectionsRemoveLinkSchema +>; diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index cbcdace6e3..8a6b4ebe9c 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -19,6 +19,7 @@ import { StatusFilter, UserRole, } from "@shared/types"; +import { isLinkNode } from "@shared/utils/collections"; import { subtractDate } from "@shared/utils/date"; import slugify from "@server/utils/slugify"; import { Day } from "@shared/utils/time"; @@ -310,6 +311,7 @@ router.post( }); authorize(user, "readDocument", collection); documentIds = (collection.documentStructure || []) + .filter((node) => !isLinkNode(node)) .slice(offset, offset + limit) .map((node) => node.id); where[Op.and].push({ id: documentIds }); diff --git a/server/types.ts b/server/types.ts index 207ace7720..9a862fb601 100644 --- a/server/types.ts +++ b/server/types.ts @@ -355,6 +355,15 @@ export type CollectionEvent = BaseEvent & { collectionId: string; }; +export type CollectionLinkEvent = BaseEvent & { + name: + | "collections.add_link" + | "collections.update_link" + | "collections.remove_link"; + collectionId: string; + modelId: string; +}; + export type GroupUserEvent = BaseEvent & { name: "groups.add_user" | "groups.remove_user"; userId: string; @@ -518,6 +527,7 @@ export type Event = | CommentEvent | StarEvent | CollectionEvent + | CollectionLinkEvent | CollectionUserEvent | CollectionGroupEvent | FileOperationEvent diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index c755118dbf..5f3116e4e4 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -700,7 +700,6 @@ "Archived collections": "Archived collections", "Empty": "Empty", "New doc": "New doc", - "New nested document": "New nested document", "No collections": "No collections", "Hide": "Hide", "Starred": "Starred", @@ -709,13 +708,16 @@ "Move up": "Move up", "Move down": "Move down", "Import files": "Import files", + "Link options": "Link options", "Section options": "Section options", "Recent": "Recent", "Go back": "Go back", "Go forward": "Go forward", + "URL": "URL", + "Title": "Title", + "New nested document": "New nested document", "Could not load shared documents": "Could not load shared documents", "Show more": "Show more", - "Link options": "Link options", "Could not load starred documents": "Could not load starred documents", "Up to date": "Up to date", "{{ releasesBehind }} versions behind": "{{ releasesBehind }} version behind", @@ -724,6 +726,8 @@ "{{ documentName }} cannot be moved within {{ parentDocumentName }}": "{{ documentName }} cannot be moved within {{ parentDocumentName }}", "You can’t reorder documents in an alphabetically sorted collection": "You can’t reorder documents in an alphabetically sorted collection", "{{ documentName }} cannot be moved here": "{{ documentName }} cannot be moved here", + "Add link": "Add link", + "Edit link": "Edit link", "Integrations": "Integrations", "Back to app": "Back to app", "Installation": "Installation", @@ -1407,7 +1411,6 @@ "Never used": "Never used", "Are you sure you want to revoke access?": "Are you sure you want to revoke access?", "Are you sure you want to delete the {{ appName }} application? This cannot be undone.": "Are you sure you want to delete the {{ appName }} application? This cannot be undone.", - "Title": "Title", "Shared by": "Shared by", "Date shared": "Date shared", "Last accessed": "Last accessed", @@ -1808,7 +1811,6 @@ "Updating": "Updating", "Provide a descriptive name for this webhook and the URL we should send a POST request to when matching events are created.": "Provide a descriptive name for this webhook and the URL we should send a POST request to when matching events are created.", "A memorable identifier": "A memorable identifier", - "URL": "URL", "Webhook delivery over http is insecure – use https if possible": "Webhook delivery over http is insecure – use https if possible", "Signing secret": "Signing secret", "Subscribe to all events, groups, or individual events. We recommend only subscribing to the minimum number of events that your application needs to function.": "Subscribe to all events, groups, or individual events. We recommend only subscribing to the minimum number of events that your application needs to function.", diff --git a/shared/types/navigation.ts b/shared/types/navigation.ts index 8e98499305..821a36a6e8 100644 --- a/shared/types/navigation.ts +++ b/shared/types/navigation.ts @@ -4,6 +4,7 @@ export enum NavigationNodeType { Document = "document", UserMembership = "userMembership", GroupMembership = "groupMembership", + Link = "link", } /** A node in a navigation tree, such as a collection's document structure. */ diff --git a/shared/utils/collections.ts b/shared/utils/collections.ts index 9e679979c2..19e858e0af 100644 --- a/shared/utils/collections.ts +++ b/shared/utils/collections.ts @@ -1,4 +1,4 @@ -import type { NavigationNode } from "../types"; +import { NavigationNodeType, type NavigationNode } from "../types"; import shallowEqual from "./shallowEqual"; import naturalSort from "./naturalSort"; @@ -7,6 +7,16 @@ type Sort = { direction: "asc" | "desc"; }; +/** + * Returns whether the node is a link to an external location, rather than a + * document. + * + * @param node The navigation node to check. + * @returns true if the node is a link. + */ +export const isLinkNode = (node: Pick): boolean => + node.type === NavigationNodeType.Link; + export const sortNavigationNodes = ( nodes: NavigationNode[], sort: Sort, diff --git a/shared/validations.ts b/shared/validations.ts index 1e48bb8a4f..3610922827 100644 --- a/shared/validations.ts +++ b/shared/validations.ts @@ -73,6 +73,14 @@ export const DeprecationValidation = { maxReasonLength: 2000, }; +export const NavigationLinkValidation = { + /** The maximum length of the link title */ + maxTitleLength: 100, + + /** The maximum length of the link url */ + maxUrlLength: 2048, +}; + export const DocumentValidation = { /** The maximum length of the document title */ maxTitleLength: 100,