feat: Add external links to the sidebar

This commit is contained in:
Tom Moor committed 2026-11-10 07:20:35 -05:00
1 parent 309dd022f6
commit fcf3f41a58
36 files changed
+1270 -107

No files matched your search

+5 -5
View File
@@ -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: <DocumentIcon />,
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)];
@@ -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.
+4 -1
View File
@@ -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<Props> = ({
}
const nestedDocumentsCount = collection
? collection.getChildrenForDocument(document.id).length
? collection
.getChildrenForDocument(document.id)
.filter((node) => !isLinkNode(node)).length
: 0;
const canShowProgressBar = isTasks;
+4
View File
@@ -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);
`;
@@ -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<Props> = ({
[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<Props> = ({
menuOpen={menuOpen}
canCreateChild={!isDraggingAnyCollection && can.createDocument}
onCreateChild={handleNewDoc}
onCreateLink={handleNewLink}
parentRef={parentRef}
dropRef={dropRef}
isActiveDropTarget={isOver && canDrop}
@@ -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<void>;
/** 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<RefHandle>(null);
const handleAddChild = React.useCallback(
(ev: React.MouseEvent<HTMLButtonElement>) => {
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 ? (
<Fade>
{canCreateChild && (
<Tooltip content={t("New doc")}>
<NudeButton
aria-label={t("New nested document")}
onClick={handleAddChild}
>
<PlusIcon />
</NudeButton>
</Tooltip>
<NewChildMenu onNewDoc={handleAddChild} onNewLink={onCreateLink} />
)}
{rowMenu}
</Fade>
@@ -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}
@@ -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<void>;
/** 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<HTMLButtonElement>) => {
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 ? (
<Fade>
{canCreateChild && (
<Tooltip content={t("New doc")}>
<NudeButton
aria-label={t("New nested document")}
onClick={handleAddChild}
>
<PlusIcon />
</NudeButton>
</Tooltip>
<NewChildMenu onNewDoc={handleAddChild} onNewLink={onCreateLink} />
)}
{menu}
</Fade>
@@ -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({
<React.Fragment key={item.key}>
{gap > 0 && <div style={{ height: gap }} />}
<div data-index={item.index} ref={virtualizer.measureElement}>
<DocumentLink
node={row.node}
collection={collection}
membership={membership}
prefetchDocument={prefetchDocument}
isDraft={row.node.isDraft}
depth={row.depth}
index={row.index}
parentId={row.parentId}
hasChildren={row.hasChildren}
trailingAncestors={row.trailingAncestors}
/>
{isLinkNode(row.node) ? (
<ExternalLink
node={row.node}
collection={collection}
parentId={row.parentId}
depth={row.depth}
/>
) : (
<DocumentLink
node={row.node}
collection={collection}
membership={membership}
prefetchDocument={prefetchDocument}
isDraft={row.node.isDraft}
depth={row.depth}
index={row.index}
parentId={row.parentId}
hasChildren={row.hasChildren}
trailingAncestors={row.trailingAncestors}
/>
)}
</div>
</React.Fragment>
);
@@ -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: <EditIcon />,
visible: canEdit,
perform: handleEdit,
}),
createAction({
name: t("Delete"),
section: DocumentSection,
icon: <TrashIcon />,
dangerous: true,
visible: canEdit,
perform: handleDelete,
}),
],
[t, canEdit, handleEdit, handleDelete]
);
const rootAction = useMenuAction(actions);
const menu = canEdit ? (
<DropdownMenu
action={rootAction}
align="end"
ariaLabel={t("Link options")}
onOpen={handleMenuOpen}
onClose={handleMenuClose}
>
<OverflowMenuButton />
</DropdownMenu>
) : undefined;
return (
<SidebarLink
href={sanitizeUrl(node.url)}
external
depth={depth}
icon={depth === 0 ? <LinkIcon /> : undefined}
label={node.title}
contextAction={canEdit ? rootAction : undefined}
menu={menu}
$showActions={menuOpen}
/>
);
});
@@ -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<void>;
}
/**
* 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<HTMLInputElement>) => {
setUrl(ev.target.value);
},
[]
);
const handleTitleChange = React.useCallback(
(ev: React.ChangeEvent<HTMLInputElement>) => {
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 (
<form onSubmit={handleSubmit}>
<Flex column>
<Input
type="text"
inputMode="url"
label={t("URL")}
placeholder="https://"
onChange={handleUrlChange}
value={url}
maxLength={NavigationLinkValidation.maxUrlLength}
required
autoSelect
flex
/>
<Input
type="text"
label={t("Title")}
placeholder={hostname}
onChange={handleTitleChange}
value={title}
maxLength={NavigationLinkValidation.maxTitleLength}
flex
/>
</Flex>
<Flex justify="flex-end">
<Button type="submit" disabled={isSaving || !hostname}>
{isSaving ? `${t("Saving")}…` : t("Save")}
</Button>
</Flex>
</form>
);
}
@@ -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<HTMLButtonElement>) => {
ev.preventDefault();
onNewDoc();
},
[onNewDoc]
);
const actions = React.useMemo(
() => [
createAction({
name: t("Document"),
section: DocumentSection,
icon: <NewDocumentIcon />,
perform: onNewDoc,
}),
createAction({
name: `${t("Link")}…`,
section: DocumentSection,
icon: <LinkIcon />,
visible: !!onNewLink,
perform: () => onNewLink?.(),
}),
],
[t, onNewDoc, onNewLink]
);
const rootAction = useMenuAction(actions);
if (!onNewLink) {
return (
<Tooltip content={t("New doc")}>
<NudeButton aria-label={t("New nested document")} onClick={handleClick}>
<PlusIcon />
</NudeButton>
</Tooltip>
);
}
return (
<Tooltip content={t("Add")}>
<DropdownMenu action={rootAction} align="end" ariaLabel={t("Add")}>
<NudeButton>
<PlusIcon />
</NudeButton>
</DropdownMenu>
</Tooltip>
);
}
@@ -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) => (
<SharedDocumentLink
key={childNode.id}
index={index}
depth={hideRootNode ? 1 : 2}
shareId={shareId}
node={childNode}
prefetchDocument={documents.prefetchDocument}
activeDocumentId={ui.activeDocumentId}
activeDocument={documents.active}
/>
))}
{node.children.map((childNode, index) =>
isLinkNode(childNode) ? (
<ExternalLink
key={childNode.id}
node={childNode}
depth={hideRootNode ? 1 : 2}
/>
) : (
<SharedDocumentLink
key={childNode.id}
index={index}
depth={hideRootNode ? 1 : 2}
shareId={shareId}
node={childNode}
prefetchDocument={documents.prefetchDocument}
activeDocumentId={ui.activeDocumentId}
activeDocument={documents.active}
/>
)
)}
</>
);
}
@@ -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) => (
<SharedDocumentLink
shareId={shareId}
key={childNode.id}
collection={collection}
node={childNode}
activeDocumentId={activeDocumentId}
activeDocument={activeDocument}
prefetchDocument={prefetchDocument}
isDraft={childNode.isDraft}
depth={depth + 1}
index={index}
parentId={node.id}
/>
))}
nodeChildren.map((childNode, index) =>
isLinkNode(childNode) ? (
<ExternalLink
key={childNode.id}
node={childNode}
depth={depth + 1}
/>
) : (
<SharedDocumentLink
shareId={shareId}
key={childNode.id}
collection={collection}
node={childNode}
activeDocumentId={activeDocumentId}
activeDocument={activeDocument}
prefetchDocument={prefetchDocument}
isDraft={childNode.isDraft}
depth={depth + 1}
index={index}
parentId={node.id}
/>
)
)}
</>
);
}
@@ -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<NavLinkProps, "to"> & {
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 && <IconWrapper aria-hidden>{icon}</IconWrapper>}
<Label $ellipsis={ellipsis}>{label}</Label>
{external && <ExternalIcon size={16} aria-hidden />}
{unreadBadge && <UnreadBadge style={unreadStyle} />}
</Content>
);
@@ -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;
@@ -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: <LinkDialog onSubmit={handleSubmit} />,
});
},
[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: (
<LinkDialog
defaultValues={{ title: node.title, url: node.url }}
onSubmit={handleSubmit}
/>
),
});
},
[dialogs, t]
);
return { openCreate, openEdit };
}
+5 -2
View File
@@ -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,
+106
View File
@@ -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<NavigationNode, "title" | "url">,
parentDocumentId?: string
): Promise<NavigationNode> => {
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<Pick<NavigationNode, "title" | "url">>
): Promise<void> => {
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<void> => {
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;
}
@@ -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 (
@@ -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]
);
}
/**
+4 -1
View File
@@ -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) => {
@@ -323,6 +323,9 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
case "passkeys.create":
case "passkeys.update":
case "passkeys.delete":
case "collections.add_link":
case "collections.update_link":
case "collections.remove_link":
// Ignored
return;
default:
+113 -1
View File
@@ -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<Pick<NavigationNode, "title" | "url">>,
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.
*
+5
View File
@@ -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)
),
@@ -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}`)
@@ -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);
+5
View File
@@ -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, {
@@ -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();
+169 -1
View File
@@ -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<T.CollectionsAddLinkReq>) => {
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<T.CollectionsUpdateLinkReq>) => {
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<T.CollectionsRemoveLinkReq>) => {
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;
+62 -1
View File
@@ -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<typeof CollectionsMoveSchema>;
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<typeof CollectionsAddLinkSchema>;
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
>;
+2
View File
@@ -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 });
+10
View File
@@ -355,6 +355,15 @@ export type CollectionEvent = BaseEvent<Collection> & {
collectionId: string;
};
export type CollectionLinkEvent = BaseEvent<Collection> & {
name:
| "collections.add_link"
| "collections.update_link"
| "collections.remove_link";
collectionId: string;
modelId: string;
};
export type GroupUserEvent = BaseEvent<UserMembership> & {
name: "groups.add_user" | "groups.remove_user";
userId: string;
@@ -518,6 +527,7 @@ export type Event =
| CommentEvent
| StarEvent
| CollectionEvent
| CollectionLinkEvent
| CollectionUserEvent
| CollectionGroupEvent
| FileOperationEvent
+6 -4
View File
@@ -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.",
+1
View File
@@ -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. */
+11 -1
View File
@@ -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<NavigationNode, "type">): boolean =>
node.type === NavigationNodeType.Link;
export const sortNavigationNodes = (
nodes: NavigationNode[],
sort: Sort,
+8
View File
@@ -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,