Compare commits

..

2 Commits

Author SHA1 Message Date
Philip Okugbe 537e45bc11 feat: page details section and backlinks (#2186)
* feat: page details section and backlinks
2026-05-09 17:03:08 +01:00
Philip Okugbe bdc369fce0 feat(editor): fixed toolbar preference (#2185)
* feat(editor): fixed toolbar preference

* remove key

* cleanup translation strings

* update axios
2026-05-09 13:27:03 +01:00
21 changed files with 942 additions and 10 deletions
@@ -970,5 +970,18 @@
"Experimental": "Experimental", "Experimental": "Experimental",
"Strikethrough": "Strikethrough", "Strikethrough": "Strikethrough",
"Undo": "Undo", "Undo": "Undo",
"Redo": "Redo" "Redo": "Redo",
"Backlinks": "Backlinks",
"Last updated by": "Last updated by",
"Last updated": "Last updated",
"Stats": "Stats",
"Word count": "Word count",
"Characters": "Characters",
"Incoming links": "Incoming links",
"Outgoing links": "Outgoing links",
"Incoming links ({{count}})": "Incoming links ({{count}})",
"Outgoing links ({{count}})": "Outgoing links ({{count}})",
"No pages link here yet.": "No pages link here yet.",
"This page doesn't link to other pages yet.": "This page doesn't link to other pages yet.",
"Verified until {{date}}": "Verified until {{date}}"
} }
@@ -8,6 +8,7 @@ import { TableOfContents } from "@/features/editor/components/table-of-contents/
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms.ts"; import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms.ts";
import AsideChatPanel from "@/ee/ai-chat/components/aside-chat-panel"; import AsideChatPanel from "@/ee/ai-chat/components/aside-chat-panel";
import { PageDetailsAside } from "@/features/page-details/components/page-details-aside.tsx";
export default function Aside() { export default function Aside() {
const [{ tab }] = useAtom(asideStateAtom); const [{ tab }] = useAtom(asideStateAtom);
@@ -30,6 +31,10 @@ export default function Aside() {
component = <AsideChatPanel />; component = <AsideChatPanel />;
title = "AI Chat"; title = "AI Chat";
break; break;
case "details":
component = <PageDetailsAside />;
title = "Details";
break;
default: default:
component = null; component = null;
title = null; title = null;
@@ -147,7 +147,9 @@ export default function GlobalAppShell({
? t("Table of contents") ? t("Table of contents")
: asideTab === "chat" : asideTab === "chat"
? t("AI Chat") ? t("AI Chat")
: undefined : asideTab === "details"
? t("Details")
: undefined
} }
> >
<Aside /> <Aside />
@@ -10,6 +10,7 @@ export const desktopSidebarAtom = atomWithWebStorage<boolean>(
export const desktopAsideAtom = atom<boolean>(false); export const desktopAsideAtom = atom<boolean>(false);
// Valid `tab` values: "" | "comments" | "toc" | "chat" | "details"
type AsideStateType = { type AsideStateType = {
tab: string; tab: string;
isAsideOpen: boolean; isAsideOpen: boolean;
@@ -118,10 +118,20 @@ export function PageVerificationBadge({
if (status === "none" && readOnly) return null; if (status === "none" && readOnly) return null;
const tooltipLabel =
status === "verified" && verificationInfo?.expiresAt
? t("Verified until {{date}}", {
date: new Date(verificationInfo.expiresAt).toLocaleDateString(
undefined,
{ month: "long", day: "numeric", year: "numeric" },
),
})
: getStatusLabel(status, t);
return ( return (
<> <>
{status !== "none" ? ( {status !== "none" ? (
<Tooltip label={getStatusLabel(status, t)} withArrow openDelay={250}> <Tooltip label={tooltipLabel} withArrow openDelay={250}>
<Group <Group
gap={4} gap={4}
onClick={open} onClick={open}
@@ -3,14 +3,17 @@ import React from "react";
import { TitleEditor } from "@/features/editor/title-editor"; import { TitleEditor } from "@/features/editor/title-editor";
import PageEditor from "@/features/editor/page-editor"; import PageEditor from "@/features/editor/page-editor";
import { import {
ActionIcon,
Container, Container,
Divider, Divider,
Group, Group,
Popover, Popover,
Stack, Stack,
Text, Text,
Tooltip,
UnstyledButton, UnstyledButton,
} from "@mantine/core"; } from "@mantine/core";
import { IconInfoCircle } from "@tabler/icons-react";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { userAtom } from "@/features/user/atoms/current-user-atom.ts"; import { userAtom } from "@/features/user/atoms/current-user-atom.ts";
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx"; import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
@@ -19,6 +22,8 @@ import { useTranslation } from "react-i18next";
import { IContributor } from "@/features/page/types/page.types.ts"; import { IContributor } from "@/features/page/types/page.types.ts";
import { FixedToolbar } from "@/features/editor/components/fixed-toolbar/fixed-toolbar"; import { FixedToolbar } from "@/features/editor/components/fixed-toolbar/fixed-toolbar";
import { PageEditMode } from "@/features/user/types/user.types.ts"; import { PageEditMode } from "@/features/user/types/user.types.ts";
import useToggleAside from "@/hooks/use-toggle-aside.tsx";
import clsx from "clsx";
const MemoizedTitleEditor = React.memo(TitleEditor); const MemoizedTitleEditor = React.memo(TitleEditor);
const MemoizedPageEditor = React.memo(PageEditor); const MemoizedPageEditor = React.memo(PageEditor);
@@ -101,6 +106,7 @@ function PageByline({
readOnly, readOnly,
}: PageBylineProps) { }: PageBylineProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const toggleAside = useToggleAside();
const otherContributors = (contributors ?? []).filter( const otherContributors = (contributors ?? []).filter(
(c) => c.id !== creator?.id, (c) => c.id !== creator?.id,
@@ -110,8 +116,8 @@ function PageByline({
<Group <Group
gap="sm" gap="sm"
mb="md" mb="md"
className="print-hide" className={clsx("print-hide", classes.byline)}
style={{ marginTop: "-0.5em", paddingLeft: "3rem" }} style={{ marginTop: "-0.5em" }}
> >
{creator && ( {creator && (
<Popover position="bottom-start" shadow="md" width={280} withArrow> <Popover position="bottom-start" shadow="md" width={280} withArrow>
@@ -173,6 +179,17 @@ function PageByline({
</Popover.Dropdown> </Popover.Dropdown>
</Popover> </Popover>
)} )}
<Tooltip label={t("Details")} withArrow openDelay={250}>
<ActionIcon
variant="subtle"
color="gray"
aria-label={t("Details")}
onClick={() => toggleAside("details")}
>
<IconInfoCircle size={20} stroke={1.5} />
</ActionIcon>
</Tooltip>
<PageVerificationBadge readOnly={readOnly} /> <PageVerificationBadge readOnly={readOnly} />
</Group> </Group>
); );
@@ -9,3 +9,15 @@
} }
} }
.byline {
padding-left: 3rem;
@media (max-width: $mantine-breakpoint-sm) {
padding-left: 1rem;
}
@media print {
padding-left: 0;
}
}
@@ -0,0 +1,113 @@
import {
Button,
Center,
Group,
Loader,
Stack,
Text,
UnstyledButton,
} from "@mantine/core";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useBacklinksQuery } from "@/features/page-details/queries/backlinks-query.ts";
import {
BacklinkDirection,
IBacklinkPageItem,
} from "@/features/page-details/types/backlink.types.ts";
import { buildPageUrl } from "@/features/page/page.utils.ts";
import { getPageIcon } from "@/lib";
interface BacklinksListProps {
pageId: string;
direction: BacklinkDirection;
enabled: boolean;
onItemClick: () => void;
}
export function BacklinksList({
pageId,
direction,
enabled,
onItemClick,
}: BacklinksListProps) {
const { t } = useTranslation();
const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
useBacklinksQuery(pageId, direction, enabled);
if (!enabled) return null;
if (isLoading) {
return (
<Center py="sm">
<Loader size="sm" />
</Center>
);
}
const items: IBacklinkPageItem[] =
data?.pages.flatMap((page) => page.items) ?? [];
if (items.length === 0) {
return (
<Text c="dimmed" size="sm" py="md">
{direction === "incoming"
? t("No pages link here yet.")
: t("This page doesn't link to other pages yet.")}
</Text>
);
}
const handleClick = (e: React.MouseEvent) => {
if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) {
return;
}
onItemClick();
};
return (
<Stack gap={4}>
{items.map((item) => (
<UnstyledButton
key={item.id}
component={Link}
to={
item.space?.slug
? buildPageUrl(
item.space.slug,
item.slugId,
item.title ?? undefined,
)
: "#"
}
onClick={handleClick}
style={{ padding: "8px 4px", borderRadius: 4, userSelect: "none" }}
>
<Group gap="xs" wrap="nowrap">
{getPageIcon(item.icon ?? "")}
<Stack gap={0} style={{ flex: 1, minWidth: 0 }}>
<Text size="sm" fw={500} lineClamp={1}>
{item.title || t("Untitled")}
</Text>
{item.space?.name && (
<Text size="xs" c="dimmed" lineClamp={1}>
{item.space.name}
</Text>
)}
</Stack>
</Group>
</UnstyledButton>
))}
{hasNextPage && (
<Button
variant="subtle"
size="xs"
loading={isFetchingNextPage}
onClick={() => fetchNextPage()}
mt="xs"
>
{t("Load more")}
</Button>
)}
</Stack>
);
}
@@ -0,0 +1,62 @@
import { Modal, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useBacklinksCountQuery } from "@/features/page-details/queries/backlinks-query.ts";
import { BacklinksList } from "./backlinks-list";
interface BacklinksModalProps {
pageId: string;
opened: boolean;
onClose: () => void;
}
export function BacklinksModal({
pageId,
opened,
onClose,
}: BacklinksModalProps) {
const { t } = useTranslation();
const { data: counts } = useBacklinksCountQuery(pageId);
return (
<Modal.Root opened={opened} onClose={onClose} size={640} yOffset="10vh">
<Modal.Overlay />
<Modal.Content>
<Modal.Header>
<Modal.Title fw={500}>{t("Backlinks")}</Modal.Title>
<Modal.CloseButton />
</Modal.Header>
<Modal.Body>
<Stack gap="lg">
<Stack gap="xs">
<Text size="sm" fw={500} c="dimmed">
{t("Incoming links ({{count}})", {
count: counts?.incoming ?? 0,
})}
</Text>
<BacklinksList
pageId={pageId}
direction="incoming"
enabled={opened}
onItemClick={onClose}
/>
</Stack>
<Stack gap="xs">
<Text size="sm" fw={500} c="dimmed">
{t("Outgoing links ({{count}})", {
count: counts?.outgoing ?? 0,
})}
</Text>
<BacklinksList
pageId={pageId}
direction="outgoing"
enabled={opened}
onItemClick={onClose}
/>
</Stack>
</Stack>
</Modal.Body>
</Modal.Content>
</Modal.Root>
);
}
@@ -0,0 +1,233 @@
import {
Divider,
Group,
Skeleton,
Stack,
Text,
UnstyledButton,
} from "@mantine/core";
import { IconChevronRight } from "@tabler/icons-react";
import { useDisclosure } from "@mantine/hooks";
import { useAtomValue } from "jotai";
import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { extractPageSlugId } from "@/lib";
import { usePageQuery } from "@/features/page/queries/page-query.ts";
import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms.ts";
import { useBacklinksCountQuery } from "@/features/page-details/queries/backlinks-query.ts";
import { BacklinksModal } from "./backlinks-modal";
import { formattedDate, timeAgo } from "@/lib/time.ts";
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
export function PageDetailsAside() {
const { pageSlug } = useParams();
const { data: page } = usePageQuery({
pageId: extractPageSlugId(pageSlug),
});
const pageEditor = useAtomValue(pageEditorAtom);
const { data: counts, isLoading: countsLoading } = useBacklinksCountQuery(page?.id);
const [modalOpened, { open: openModal, close: closeModal }] =
useDisclosure(false);
if (!page) return null;
const wordCount: number =
pageEditor?.storage?.characterCount?.words?.() ?? 0;
const characterCount: number =
pageEditor?.storage?.characterCount?.characters?.() ?? 0;
return (
<>
<Stack gap="md">
<PeopleSection
creator={page.creator}
lastUpdatedBy={page.lastUpdatedBy}
/>
<Divider />
<StatsSection
wordCount={wordCount}
characterCount={characterCount}
createdAt={page.createdAt}
updatedAt={page.updatedAt}
/>
<Divider />
<BacklinksSection
incomingCount={counts?.incoming ?? 0}
outgoingCount={counts?.outgoing ?? 0}
isLoading={countsLoading}
onClick={openModal}
/>
</Stack>
<BacklinksModal
pageId={page.id}
opened={modalOpened}
onClose={closeModal}
/>
</>
);
}
function PeopleSection({
creator,
lastUpdatedBy,
}: {
creator: { id: string; name: string; avatarUrl: string } | null;
lastUpdatedBy: { id: string; name: string; avatarUrl: string } | null;
}) {
const { t } = useTranslation();
return (
<Stack gap="xs">
<PersonRow label={t("Created by")} person={creator} />
<PersonRow label={t("Last updated by")} person={lastUpdatedBy} />
</Stack>
);
}
function PersonRow({
label,
person,
}: {
label: string;
person: { id: string; name: string; avatarUrl: string } | null;
}) {
return (
<Group justify="space-between" wrap="nowrap">
<Text size="sm" c="dimmed">
{label}
</Text>
{person ? (
<Group gap={6} wrap="nowrap">
<CustomAvatar
avatarUrl={person.avatarUrl}
name={person.name}
size={20}
radius="xl"
/>
<Text size="sm" lineClamp={1}>
{person.name}
</Text>
</Group>
) : (
<Text size="sm" c="dimmed">
</Text>
)}
</Group>
);
}
function StatsSection({
wordCount,
characterCount,
createdAt,
updatedAt,
}: {
wordCount: number;
characterCount: number;
createdAt: Date | string;
updatedAt: Date | string;
}) {
const { t } = useTranslation();
return (
<Stack gap="xs">
<Text size="xs" fw={500} c="dimmed">
{t("Stats")}
</Text>
<StatRow label={t("Word count")} value={String(wordCount)} />
<StatRow label={t("Characters")} value={String(characterCount)} />
<StatRow
label={t("Created")}
value={formattedDate(new Date(createdAt))}
/>
<StatRow
label={t("Last updated")}
value={timeAgo(new Date(updatedAt))}
/>
</Stack>
);
}
function StatRow({ label, value }: { label: string; value: string }) {
return (
<Group justify="space-between" wrap="nowrap">
<Text size="sm" c="dimmed">
{label}
</Text>
<Text size="sm">{value}</Text>
</Group>
);
}
function BacklinksSection({
incomingCount,
outgoingCount,
isLoading,
onClick,
}: {
incomingCount: number;
outgoingCount: number;
isLoading: boolean;
onClick: () => void;
}) {
const { t } = useTranslation();
return (
<Stack gap="xs">
<Text size="xs" fw={500} c="dimmed">
{t("Backlinks")}
</Text>
<BacklinksRow
label={t("Incoming links")}
count={incomingCount}
isLoading={isLoading}
onClick={onClick}
/>
<BacklinksRow
label={t("Outgoing links")}
count={outgoingCount}
isLoading={isLoading}
onClick={onClick}
/>
</Stack>
);
}
function BacklinksRow({
label,
count,
isLoading,
onClick,
}: {
label: string;
count: number;
isLoading: boolean;
onClick: () => void;
}) {
return (
<UnstyledButton
onClick={onClick}
style={{
padding: "4px 4px",
borderRadius: 4,
}}
>
<Group justify="space-between" wrap="nowrap">
<Text size="sm" c="dimmed">
{label}
</Text>
<Group gap={6} wrap="nowrap">
{isLoading ? (
<Skeleton height={18} width={20} />
) : (
<Text size="sm">{count}</Text>
)}
<IconChevronRight size={16} stroke={2} color="var(--mantine-color-dimmed)" />
</Group>
</Group>
</UnstyledButton>
);
}
@@ -0,0 +1,45 @@
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import {
getBacklinks,
getBacklinksCount,
} from "@/features/page-details/services/backlinks-service.ts";
import {
BacklinkDirection,
IBacklinkCount,
} from "@/features/page-details/types/backlink.types.ts";
const BACKLINKS_STALE_TIME = 30 * 1000;
const BACKLINKS_PAGE_LIMIT = 100;
export function useBacklinksCountQuery(pageId: string | undefined) {
return useQuery<IBacklinkCount>({
queryKey: ["backlinks-count", pageId],
queryFn: () => getBacklinksCount(pageId as string),
enabled: !!pageId,
staleTime: BACKLINKS_STALE_TIME,
});
}
export function useBacklinksQuery(
pageId: string | undefined,
direction: BacklinkDirection,
enabled: boolean,
) {
return useInfiniteQuery({
queryKey: ["backlinks", pageId, direction],
queryFn: ({ pageParam }) =>
getBacklinks({
pageId: pageId as string,
direction,
cursor: pageParam,
limit: BACKLINKS_PAGE_LIMIT,
}),
enabled: enabled && !!pageId,
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) =>
lastPage.meta.hasNextPage
? (lastPage.meta.nextCursor ?? undefined)
: undefined,
staleTime: BACKLINKS_STALE_TIME,
});
}
@@ -0,0 +1,26 @@
import api from "@/lib/api-client";
import { IPagination } from "@/lib/types.ts";
import {
IBacklinkCount,
IBacklinkPageItem,
IBacklinksListParams,
} from "@/features/page-details/types/backlink.types.ts";
export async function getBacklinksCount(
pageId: string,
): Promise<IBacklinkCount> {
const req = await api.post<IBacklinkCount>("/pages/backlinks-count", {
pageId,
});
return req.data;
}
export async function getBacklinks(
params: IBacklinksListParams,
): Promise<IPagination<IBacklinkPageItem>> {
const req = await api.post<IPagination<IBacklinkPageItem>>(
"/pages/backlinks",
params,
);
return req.data;
}
@@ -0,0 +1,23 @@
export type BacklinkDirection = "incoming" | "outgoing";
export interface IBacklinkCount {
incoming: number;
outgoing: number;
}
export interface IBacklinkPageItem {
id: string;
slugId: string;
title: string | null;
icon: string | null;
spaceId: string;
space: { id: string; slug: string; name: string } | null;
updatedAt: string;
}
export interface IBacklinksListParams {
pageId: string;
direction: BacklinkDirection;
cursor?: string;
limit?: number;
}
@@ -0,0 +1,11 @@
import { IsIn, IsNotEmpty, IsString } from 'class-validator';
import { PageIdDto } from './page.dto';
export type BacklinkDirection = 'incoming' | 'outgoing';
export class BacklinksListDto extends PageIdDto {
@IsString()
@IsNotEmpty()
@IsIn(['incoming', 'outgoing'])
direction: BacklinkDirection;
}
@@ -11,6 +11,7 @@ import {
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { PageService } from './services/page.service'; import { PageService } from './services/page.service';
import { BacklinkService } from './services/backlink.service';
import { PageAccessService } from './page-access/page-access.service'; import { PageAccessService } from './page-access/page-access.service';
import { CreatePageDto } from './dto/create-page.dto'; import { CreatePageDto } from './dto/create-page.dto';
import { UpdatePageDto } from './dto/update-page.dto'; import { UpdatePageDto } from './dto/update-page.dto';
@@ -38,6 +39,7 @@ import { RecentPageDto } from './dto/recent-page.dto';
import { CreatedByUserDto } from './dto/created-by-user.dto'; import { CreatedByUserDto } from './dto/created-by-user.dto';
import { DuplicatePageDto } from './dto/duplicate-page.dto'; import { DuplicatePageDto } from './dto/duplicate-page.dto';
import { DeletedPageDto } from './dto/deleted-page.dto'; import { DeletedPageDto } from './dto/deleted-page.dto';
import { BacklinksListDto } from './dto/backlink.dto';
import { import {
jsonToHtml, jsonToHtml,
jsonToMarkdown, jsonToMarkdown,
@@ -58,6 +60,7 @@ export class PageController {
private readonly pageHistoryService: PageHistoryService, private readonly pageHistoryService: PageHistoryService,
private readonly spaceAbility: SpaceAbilityFactory, private readonly spaceAbility: SpaceAbilityFactory,
private readonly pageAccessService: PageAccessService, private readonly pageAccessService: PageAccessService,
private readonly backlinkService: BacklinkService,
@Inject(AUDIT_SERVICE) private readonly auditService: IAuditService, @Inject(AUDIT_SERVICE) private readonly auditService: IAuditService,
) {} ) {}
@@ -96,6 +99,42 @@ export class PageController {
return { ...page, permissions }; return { ...page, permissions };
} }
@HttpCode(HttpStatus.OK)
@Post('backlinks-count')
async getBacklinksCount(
@Body() dto: PageIdDto,
@AuthUser() user: User,
): Promise<{ incoming: number; outgoing: number }> {
const page = await this.pageRepo.findById(dto.pageId);
if (!page) {
throw new NotFoundException('Page not found');
}
await this.pageAccessService.validateCanView(page, user);
return this.backlinkService.countByPageId(page.id, user.id);
}
@HttpCode(HttpStatus.OK)
@Post('backlinks')
async getBacklinks(
@Body() dto: BacklinksListDto,
@Body() pagination: PaginationOptions,
@AuthUser() user: User,
) {
const page = await this.pageRepo.findById(dto.pageId);
if (!page) {
throw new NotFoundException('Page not found');
}
await this.pageAccessService.validateCanView(page, user);
return this.backlinkService.findByPageId(
page.id,
dto.direction,
user.id,
pagination,
);
}
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Post('create') @Post('create')
async create( async create(
+13 -2
View File
@@ -3,6 +3,7 @@ import { PageService } from './services/page.service';
import { PageController } from './page.controller'; import { PageController } from './page.controller';
import { PageHistoryService } from './services/page-history.service'; import { PageHistoryService } from './services/page-history.service';
import { TrashCleanupService } from './services/trash-cleanup.service'; import { TrashCleanupService } from './services/trash-cleanup.service';
import { BacklinkService } from './services/backlink.service';
import { StorageModule } from '../../integrations/storage/storage.module'; import { StorageModule } from '../../integrations/storage/storage.module';
import { CollaborationModule } from '../../collaboration/collaboration.module'; import { CollaborationModule } from '../../collaboration/collaboration.module';
import { WatcherModule } from '../watcher/watcher.module'; import { WatcherModule } from '../watcher/watcher.module';
@@ -10,8 +11,18 @@ import { TransclusionModule } from './transclusion/transclusion.module';
@Module({ @Module({
controllers: [PageController], controllers: [PageController],
providers: [PageService, PageHistoryService, TrashCleanupService], providers: [
PageService,
PageHistoryService,
TrashCleanupService,
BacklinkService,
],
exports: [PageService, PageHistoryService], exports: [PageService, PageHistoryService],
imports: [StorageModule, CollaborationModule, WatcherModule, TransclusionModule], imports: [
StorageModule,
CollaborationModule,
WatcherModule,
TransclusionModule,
],
}) })
export class PageModule {} export class PageModule {}
@@ -0,0 +1,163 @@
import { Test } from '@nestjs/testing';
import { BacklinkService } from './backlink.service';
import { BacklinkRepo } from '@docmost/db/repos/backlink/backlink.repo';
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
describe('BacklinkService.countByPageId', () => {
let service: BacklinkService;
let backlinkRepo: jest.Mocked<BacklinkRepo>;
let permissionRepo: jest.Mocked<PagePermissionRepo>;
const pageId = '00000000-0000-0000-0000-000000000001';
const userId = '00000000-0000-0000-0000-000000000099';
beforeEach(async () => {
const backlinkRepoMock: jest.Mocked<Partial<BacklinkRepo>> = {
findRelatedPageIds: jest.fn(),
findPagesByIdsPaginated: jest.fn(),
};
const permissionRepoMock: jest.Mocked<Partial<PagePermissionRepo>> = {
filterAccessiblePageIds: jest.fn(),
};
const module = await Test.createTestingModule({
providers: [
BacklinkService,
{ provide: BacklinkRepo, useValue: backlinkRepoMock },
{ provide: PagePermissionRepo, useValue: permissionRepoMock },
],
}).compile();
service = module.get(BacklinkService);
backlinkRepo = module.get(BacklinkRepo) as jest.Mocked<BacklinkRepo>;
permissionRepo = module.get(
PagePermissionRepo,
) as jest.Mocked<PagePermissionRepo>;
});
it('returns post-filter counts for both directions', async () => {
backlinkRepo.findRelatedPageIds.mockImplementation(async (_id, dir) =>
dir === 'incoming' ? ['a', 'b', 'c'] : ['x', 'y'],
);
permissionRepo.filterAccessiblePageIds.mockImplementation(
async ({ pageIds }) =>
pageIds.filter((id) => id !== 'b' && id !== 'y'),
);
const result = await service.countByPageId(pageId, userId);
expect(result).toEqual({ incoming: 2, outgoing: 1 });
expect(permissionRepo.filterAccessiblePageIds).toHaveBeenCalledWith({
pageIds: ['a', 'b', 'c'],
userId,
});
expect(permissionRepo.filterAccessiblePageIds).toHaveBeenCalledWith({
pageIds: ['x', 'y'],
userId,
});
});
it('skips the permission filter when there are no candidates', async () => {
backlinkRepo.findRelatedPageIds.mockResolvedValue([]);
permissionRepo.filterAccessiblePageIds.mockResolvedValue([]);
const result = await service.countByPageId(pageId, userId);
expect(result).toEqual({ incoming: 0, outgoing: 0 });
expect(permissionRepo.filterAccessiblePageIds).not.toHaveBeenCalled();
});
it('passes the userId to findRelatedPageIds so the repo can apply space membership filtering', async () => {
backlinkRepo.findRelatedPageIds.mockResolvedValue([]);
await service.countByPageId(pageId, userId);
expect(backlinkRepo.findRelatedPageIds).toHaveBeenCalledWith(
pageId,
'incoming',
userId,
);
expect(backlinkRepo.findRelatedPageIds).toHaveBeenCalledWith(
pageId,
'outgoing',
userId,
);
});
});
describe('BacklinkService.findByPageId', () => {
let service: BacklinkService;
let backlinkRepo: jest.Mocked<BacklinkRepo>;
let permissionRepo: jest.Mocked<PagePermissionRepo>;
const pageId = '00000000-0000-0000-0000-000000000001';
const userId = '00000000-0000-0000-0000-000000000099';
beforeEach(async () => {
const backlinkRepoMock: jest.Mocked<Partial<BacklinkRepo>> = {
findRelatedPageIds: jest.fn(),
findPagesByIdsPaginated: jest.fn(),
};
const permissionRepoMock: jest.Mocked<Partial<PagePermissionRepo>> = {
filterAccessiblePageIds: jest.fn(),
};
const module = await Test.createTestingModule({
providers: [
BacklinkService,
{ provide: BacklinkRepo, useValue: backlinkRepoMock },
{ provide: PagePermissionRepo, useValue: permissionRepoMock },
],
}).compile();
service = module.get(BacklinkService);
backlinkRepo = module.get(BacklinkRepo) as jest.Mocked<BacklinkRepo>;
permissionRepo = module.get(
PagePermissionRepo,
) as jest.Mocked<PagePermissionRepo>;
});
it('passes filtered ids through to the paginated repo call', async () => {
backlinkRepo.findRelatedPageIds.mockResolvedValue(['a', 'b']);
permissionRepo.filterAccessiblePageIds.mockResolvedValue(['a']);
backlinkRepo.findPagesByIdsPaginated.mockResolvedValue({
items: [],
meta: {
limit: 20,
hasNextPage: false,
hasPrevPage: false,
nextCursor: null,
prevCursor: null,
},
} as any);
await service.findByPageId(pageId, 'incoming', userId, { limit: 20 } as any);
expect(backlinkRepo.findPagesByIdsPaginated).toHaveBeenCalledWith(
['a'],
expect.objectContaining({ limit: 20 }),
);
});
it('hands an empty list to the repo when there are no accessible ids', async () => {
backlinkRepo.findRelatedPageIds.mockResolvedValue([]);
backlinkRepo.findPagesByIdsPaginated.mockResolvedValue({
items: [],
meta: {
limit: 20,
hasNextPage: false,
hasPrevPage: false,
nextCursor: null,
prevCursor: null,
},
} as any);
await service.findByPageId(pageId, 'incoming', userId, { limit: 20 } as any);
expect(backlinkRepo.findPagesByIdsPaginated).toHaveBeenCalledWith(
[],
expect.objectContaining({ limit: 20 }),
);
expect(permissionRepo.filterAccessiblePageIds).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,56 @@
import { Injectable } from '@nestjs/common';
import { BacklinkRepo } from '@docmost/db/repos/backlink/backlink.repo';
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
export type BacklinkDirection = 'incoming' | 'outgoing';
@Injectable()
export class BacklinkService {
constructor(
private readonly backlinkRepo: BacklinkRepo,
private readonly pagePermissionRepo: PagePermissionRepo,
) {}
async countByPageId(
pageId: string,
userId: string,
): Promise<{ incoming: number; outgoing: number }> {
const [incomingIds, outgoingIds] = await Promise.all([
this.accessibleRelatedIds(pageId, 'incoming', userId),
this.accessibleRelatedIds(pageId, 'outgoing', userId),
]);
return { incoming: incomingIds.length, outgoing: outgoingIds.length };
}
async findByPageId(
pageId: string,
direction: BacklinkDirection,
userId: string,
pagination: PaginationOptions,
) {
const accessibleIds = await this.accessibleRelatedIds(
pageId,
direction,
userId,
);
return this.backlinkRepo.findPagesByIdsPaginated(accessibleIds, pagination);
}
private async accessibleRelatedIds(
pageId: string,
direction: BacklinkDirection,
userId: string,
): Promise<string[]> {
const candidateIds = await this.backlinkRepo.findRelatedPageIds(
pageId,
direction,
userId,
);
if (candidateIds.length === 0) return [];
return this.pagePermissionRepo.filterAccessiblePageIds({
pageIds: candidateIds,
userId,
});
}
}
@@ -7,10 +7,20 @@ import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
import { dbOrTx } from '@docmost/db/utils'; import { dbOrTx } from '@docmost/db/utils';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectKysely } from 'nestjs-kysely'; import { InjectKysely } from 'nestjs-kysely';
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
import {
executeWithCursorPagination,
emptyCursorPaginationResult,
} from '@docmost/db/pagination/cursor-pagination';
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
import { jsonObjectFrom } from 'kysely/helpers/postgres';
@Injectable() @Injectable()
export class BacklinkRepo { export class BacklinkRepo {
constructor(@InjectKysely() private readonly db: KyselyDB) {} constructor(
@InjectKysely() private readonly db: KyselyDB,
private readonly spaceMemberRepo: SpaceMemberRepo,
) {}
async findById( async findById(
backlinkId: string, backlinkId: string,
@@ -69,4 +79,84 @@ export class BacklinkRepo {
const db = dbOrTx(this.db, trx); const db = dbOrTx(this.db, trx);
await db.deleteFrom('backlinks').where('id', '=', backlinkId).execute(); await db.deleteFrom('backlinks').where('id', '=', backlinkId).execute();
} }
async findRelatedPageIds(
pageId: string,
direction: 'incoming' | 'outgoing',
userId: string,
): Promise<string[]> {
const userSpaceIds = this.spaceMemberRepo.getUserSpaceIdsQuery(userId);
if (direction === 'incoming') {
const rows = await this.db
.selectFrom('backlinks')
.innerJoin('pages', 'pages.id', 'backlinks.sourcePageId')
.select('backlinks.sourcePageId as relatedId')
.where('backlinks.targetPageId', '=', pageId)
.where('pages.deletedAt', 'is', null)
.where('pages.spaceId', 'in', userSpaceIds)
.execute();
return rows.map((r) => r.relatedId);
}
const rows = await this.db
.selectFrom('backlinks')
.innerJoin('pages', 'pages.id', 'backlinks.targetPageId')
.select('backlinks.targetPageId as relatedId')
.where('backlinks.sourcePageId', '=', pageId)
.where('pages.deletedAt', 'is', null)
.where('pages.spaceId', 'in', userSpaceIds)
.execute();
return rows.map((r) => r.relatedId);
}
async findPagesByIdsPaginated(
pageIds: string[],
pagination: PaginationOptions,
) {
if (pageIds.length === 0) {
return emptyCursorPaginationResult<{
id: string;
slugId: string;
title: string | null;
icon: string | null;
spaceId: string;
updatedAt: Date;
space: { id: string; slug: string; name: string } | null;
}>(pagination.limit);
}
const query = this.db
.selectFrom('pages')
.select((eb) => [
'pages.id',
'pages.slugId',
'pages.title',
'pages.icon',
'pages.spaceId',
'pages.updatedAt',
jsonObjectFrom(
eb
.selectFrom('spaces')
.select(['spaces.id', 'spaces.slug', 'spaces.name'])
.whereRef('spaces.id', '=', 'pages.spaceId'),
).as('space'),
])
.where('pages.deletedAt', 'is', null)
.where('pages.id', 'in', pageIds);
return executeWithCursorPagination(query, {
perPage: pagination.limit,
cursor: pagination.cursor,
beforeCursor: pagination.beforeCursor,
fields: [
{ expression: 'pages.updatedAt', direction: 'desc', key: 'updatedAt' },
{ expression: 'pages.id', direction: 'desc', key: 'id' },
],
parseCursor: (cursor) => ({
updatedAt: new Date(cursor.updatedAt),
id: cursor.id,
}),
});
}
} }
+1 -1
View File
@@ -3,7 +3,7 @@ import { TableCell as TiptapTableCell } from "@tiptap/extension-table";
export const TableCell = TiptapTableCell.extend({ export const TableCell = TiptapTableCell.extend({
name: "tableCell", name: "tableCell",
content: content:
"(paragraph | heading | bulletList | orderedList | taskList | blockquote | callout | image | video | attachment | mathBlock | details | codeBlock)+", "(paragraph | heading | bulletList | orderedList | taskList | blockquote | callout | image | video | audio | subpages | attachment | mathBlock | details | codeBlock)+",
addAttributes() { addAttributes() {
return { return {
+1 -1
View File
@@ -3,7 +3,7 @@ import { TableHeader as TiptapTableHeader } from "@tiptap/extension-table";
export const TableHeader = TiptapTableHeader.extend({ export const TableHeader = TiptapTableHeader.extend({
name: "tableHeader", name: "tableHeader",
content: content:
"(paragraph | heading | bulletList | orderedList | taskList | blockquote | callout | image | video | attachment | mathBlock | details | codeBlock)+", "(paragraph | heading | bulletList | orderedList | taskList | blockquote | callout | image | video | audio | subpages | attachment | mathBlock | details | codeBlock)+",
addAttributes() { addAttributes() {
return { return {