Compare commits

..

1 Commits

Author SHA1 Message Date
Philipinho cc343b095a feat: sync blocks - wip 2026-05-04 18:08:34 +01:00
141 changed files with 1548 additions and 1685 deletions
@@ -416,7 +416,6 @@
"{{latestVersion}} is available": "{{latestVersion}} is available", "{{latestVersion}} is available": "{{latestVersion}} is available",
"Default page edit mode": "Default page edit mode", "Default page edit mode": "Default page edit mode",
"Choose your preferred page edit mode. Avoid accidental edits.": "Choose your preferred page edit mode. Avoid accidental edits.", "Choose your preferred page edit mode. Avoid accidental edits.": "Choose your preferred page edit mode. Avoid accidental edits.",
"Choose {{format}} file": "Choose {{format}} file",
"Reading": "Reading", "Reading": "Reading",
"Delete member": "Delete member", "Delete member": "Delete member",
"Member deleted successfully": "Member deleted successfully", "Member deleted successfully": "Member deleted successfully",
@@ -870,12 +869,6 @@
"Previous 7 days": "Previous 7 days", "Previous 7 days": "Previous 7 days",
"Previous 30 days": "Previous 30 days", "Previous 30 days": "Previous 30 days",
"Search chats...": "Search chats...", "Search chats...": "Search chats...",
"Search chats": "Search chats",
"Ask anything... Use @ to mention pages": "Ask anything... Use @ to mention pages",
"Ask anything or search your workspace": "Ask anything or search your workspace",
"Welcome to {{name}}": "Welcome to {{name}}",
"Add files": "Add files",
"Mention a page": "Mention a page",
"Start a new chat to see it here.": "Start a new chat to see it here.", "Start a new chat to see it here.": "Start a new chat to see it here.",
"Summarize this page": "Summarize this page", "Summarize this page": "Summarize this page",
"Toggle AI Chat": "Toggle AI Chat", "Toggle AI Chat": "Toggle AI Chat",
@@ -908,43 +901,16 @@
"This action cannot be undone. Your identity provider will stop syncing immediately.": "This action cannot be undone. Your identity provider will stop syncing immediately.", "This action cannot be undone. Your identity provider will stop syncing immediately.": "This action cannot be undone. Your identity provider will stop syncing immediately.",
"Toggle SCIM provisioning": "Toggle SCIM provisioning", "Toggle SCIM provisioning": "Toggle SCIM provisioning",
"Token": "Token", "Token": "Token",
"Page menu": "Page menu", "Sync block": "Sync block",
"Expand": "Expand",
"Collapse": "Collapse",
"Comment menu": "Comment menu",
"Group menu": "Group menu",
"Show hidden breadcrumbs": "Show hidden breadcrumbs",
"Breadcrumbs": "Breadcrumbs",
"Page actions": "Page actions",
"Pick emoji": "Pick emoji",
"Template menu": "Template menu",
"Chat menu": "Chat menu",
"API key menu": "API key menu",
"Jump to comment selection": "Jump to comment selection",
"Slash commands": "Slash commands",
"Mention suggestions": "Mention suggestions",
"Link suggestions": "Link suggestions",
"Diagram editor": "Diagram editor",
"Add comment": "Add comment",
"Find and replace": "Find and replace",
"Main navigation": "Main navigation",
"Space navigation": "Space navigation",
"Settings navigation": "Settings navigation",
"AI navigation": "AI navigation",
"Breadcrumb": "Breadcrumb",
"Skip to main content": "Skip to main content"
"Synced block": "Synced block",
"Create a block that stays in sync across pages.": "Create a block that stays in sync across pages.", "Create a block that stays in sync across pages.": "Create a block that stays in sync across pages.",
"Sync block name": "Sync block name",
"Editing original": "Editing original", "Editing original": "Editing original",
"Copy synced block": "Copy synced block", "Copy synced block": "Copy synced block",
"Unsync": "Unsync", "Unsync": "Unsync",
"Delete synced block": "Delete synced block", "Delete sync block": "Delete sync block",
"Synced to {{count}} other page_one": "Synced to {{count}} other page", "Synced to {{count}} other page_one": "Synced to {{count}} other page",
"Synced to {{count}} other page_other": "Synced to {{count}} other pages", "Synced to {{count}} other page_other": "Synced to {{count}} other pages",
"ORIGINAL": "ORIGINAL", "ORIGINAL": "ORIGINAL",
"THIS PAGE": "THIS PAGE", "THIS PAGE": "THIS PAGE",
"No pages": "No pages", "No pages": "No pages"
"The original synced block no longer exists": "The original synced block no longer exists",
"You don't have access to this synced block": "You don't have access to this synced block",
"Failed to load this synced block": "Failed to load this synced block"
} }
@@ -80,12 +80,6 @@ export default function AvatarUploader({
} }
}; };
const ariaLabel = {
[AvatarIconType.AVATAR]: t("Change avatar"),
[AvatarIconType.SPACE_ICON]: t("Change space icon"),
[AvatarIconType.WORKSPACE_ICON]: t("Change workspace icon"),
}[type];
const handleRemove = async () => { const handleRemove = async () => {
if (disabled) return; if (disabled) return;
@@ -110,8 +104,6 @@ export default function AvatarUploader({
ref={fileInputRef} ref={fileInputRef}
onChange={handleFileInputChange} onChange={handleFileInputChange}
accept="image/png,image/jpeg,image/jpg" accept="image/png,image/jpeg,image/jpg"
aria-label={ariaLabel}
tabIndex={-1}
style={{ display: "none" }} style={{ display: "none" }}
/> />
@@ -123,8 +115,6 @@ export default function AvatarUploader({
size={size} size={size}
avatarUrl={currentImageUrl} avatarUrl={currentImageUrl}
name={fallbackName} name={fallbackName}
aria-label={ariaLabel}
aria-haspopup="menu"
style={{ style={{
cursor: disabled || isLoading ? "default" : "pointer", cursor: disabled || isLoading ? "default" : "pointer",
opacity: isLoading ? 0.6 : 1, opacity: isLoading ? 0.6 : 1,
@@ -25,7 +25,6 @@ export default function CopyTextButton({ text, size }: CopyProps) {
variant="subtle" variant="subtle"
onClick={copy} onClick={copy}
size={size} size={size}
aria-label={copied ? t("Copied") : t("Copy")}
> >
{copied ? <IconCheck size={16} /> : <IconCopy size={16} />} {copied ? <IconCheck size={16} /> : <IconCopy size={16} />}
</ActionIcon> </ActionIcon>
@@ -4,7 +4,7 @@ import {
UnstyledButton, UnstyledButton,
Badge, Badge,
Table, Table,
ThemeIcon, ActionIcon,
Button, Button,
} from "@mantine/core"; } from "@mantine/core";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
@@ -49,9 +49,9 @@ export default function RecentChanges({ spaceId }: Props) {
> >
<Group wrap="nowrap"> <Group wrap="nowrap">
{page.icon || ( {page.icon || (
<ThemeIcon variant="transparent" color="gray" size={18}> <ActionIcon variant="transparent" color="gray" size={18}>
<IconFileDescription size={18} /> <IconFileDescription size={18} />
</ThemeIcon> </ActionIcon>
)} )}
<Text fw={500} size="md" lineClamp={1}> <Text fw={500} size="md" lineClamp={1}>
@@ -6,14 +6,12 @@ import { useTranslation } from "react-i18next";
export interface SearchInputProps { export interface SearchInputProps {
placeholder?: string; placeholder?: string;
ariaLabel?: string;
debounceDelay?: number; debounceDelay?: number;
onSearch: (value: string) => void; onSearch: (value: string) => void;
} }
export function SearchInput({ export function SearchInput({
placeholder, placeholder,
ariaLabel,
debounceDelay = 500, debounceDelay = 500,
onSearch, onSearch,
}: SearchInputProps) { }: SearchInputProps) {
@@ -30,7 +28,6 @@ export function SearchInput({
<TextInput <TextInput
size="sm" size="sm"
placeholder={placeholder || t("Search...")} placeholder={placeholder || t("Search...")}
aria-label={ariaLabel || placeholder || t("Search")}
leftSection={<IconSearch size={16} />} leftSection={<IconSearch size={16} />}
value={value} value={value}
onChange={(e) => setValue(e.currentTarget.value)} onChange={(e) => setValue(e.currentTarget.value)}
@@ -1,11 +1,11 @@
import { ThemeIcon } from "@mantine/core"; import { ActionIcon, rem } from "@mantine/core";
import React from "react"; import React from "react";
import { IconUsersGroup } from "@tabler/icons-react"; import { IconUsersGroup } from "@tabler/icons-react";
export function IconGroupCircle() { export function IconGroupCircle() {
return ( return (
<ThemeIcon variant="light" size="lg" color="gray" radius="xl"> <ActionIcon variant="light" size="lg" color="gray" radius="xl">
<IconUsersGroup stroke={1.5} /> <IconUsersGroup stroke={1.5} />
</ThemeIcon> </ActionIcon>
); );
} }
@@ -28,22 +28,4 @@
} }
} }
.skipLink {
position: fixed;
left: 8px;
top: 8px;
padding: 8px 12px;
background: var(--mantine-color-blue-6);
color: #fff;
border-radius: 4px;
text-decoration: none;
z-index: 1000;
transform: translateY(-150%);
&:focus {
transform: translateY(0);
outline: 2px solid var(--mantine-color-blue-3);
}
}
@@ -1,7 +1,6 @@
import { AppShell, Container } from "@mantine/core"; import { AppShell, Container } from "@mantine/core";
import React, { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom"; import { useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import SettingsSidebar from "@/components/settings/settings-sidebar.tsx"; import SettingsSidebar from "@/components/settings/settings-sidebar.tsx";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { import {
@@ -24,12 +23,11 @@ export default function GlobalAppShell({
}: { }: {
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const { t } = useTranslation();
useTrialEndAction(); useTrialEndAction();
const [mobileOpened] = useAtom(mobileSidebarAtom); const [mobileOpened] = useAtom(mobileSidebarAtom);
const toggleMobile = useToggleSidebar(mobileSidebarAtom); const toggleMobile = useToggleSidebar(mobileSidebarAtom);
const [desktopOpened] = useAtom(desktopSidebarAtom); const [desktopOpened] = useAtom(desktopSidebarAtom);
const [{ isAsideOpen, tab: asideTab }] = useAtom(asideStateAtom); const [{ isAsideOpen }] = useAtom(asideStateAtom);
const [sidebarWidth, setSidebarWidth] = useAtom(sidebarWidthAtom); const [sidebarWidth, setSidebarWidth] = useAtom(sidebarWidthAtom);
const [isResizing, setIsResizing] = useState(false); const [isResizing, setIsResizing] = useState(false);
const sidebarRef = useRef(null); const sidebarRef = useRef(null);
@@ -81,11 +79,7 @@ export default function GlobalAppShell({
const showGlobalSidebar = !isSpaceRoute && !isSettingsRoute && !isAiRoute; const showGlobalSidebar = !isSpaceRoute && !isSettingsRoute && !isAiRoute;
return ( return (
<> <AppShell
<a href="#main-content" className={classes.skipLink}>
{t("Skip to main content")}
</a>
<AppShell
header={{ height: 45 }} header={{ height: 45 }}
navbar={{ navbar={{
width: isSpaceRoute ? sidebarWidth : 300, width: isSpaceRoute ? sidebarWidth : 300,
@@ -111,15 +105,6 @@ export default function GlobalAppShell({
className={classes.navbar} className={classes.navbar}
withBorder={false} withBorder={false}
ref={sidebarRef} ref={sidebarRef}
aria-label={
isSpaceRoute
? t("Space navigation")
: isSettingsRoute
? t("Settings navigation")
: isAiRoute
? t("AI navigation")
: t("Main navigation")
}
> >
{isSpaceRoute && ( {isSpaceRoute && (
<div className={classes.resizeHandle} onMouseDown={startResizing} /> <div className={classes.resizeHandle} onMouseDown={startResizing} />
@@ -129,7 +114,7 @@ export default function GlobalAppShell({
{isAiRoute && <AiChatSidebar />} {isAiRoute && <AiChatSidebar />}
{showGlobalSidebar && <GlobalSidebar />} {showGlobalSidebar && <GlobalSidebar />}
</AppShell.Navbar> </AppShell.Navbar>
<AppShell.Main id="main-content"> <AppShell.Main>
{isSettingsRoute ? ( {isSettingsRoute ? (
<Container size={900} pb={80}> <Container size={900} pb={80}>
{children} {children}
@@ -140,24 +125,10 @@ export default function GlobalAppShell({
</AppShell.Main> </AppShell.Main>
{isPageRoute && ( {isPageRoute && (
<AppShell.Aside <AppShell.Aside className={classes.aside} p="md" withBorder={false}>
className={classes.aside}
p="md"
withBorder={false}
aria-label={
asideTab === "comments"
? t("Comments")
: asideTab === "toc"
? t("Table of contents")
: asideTab === "chat"
? t("AI Chat")
: undefined
}
>
<Aside /> <Aside />
</AppShell.Aside> </AppShell.Aside>
)} )}
</AppShell> </AppShell>
</>
); );
} }
@@ -50,7 +50,7 @@
.sectionHeader { .sectionHeader {
padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm); padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);
font-size: var(--mantine-font-size-xs); font-size: var(--mantine-font-size-xs);
color: var(--mantine-color-dimmed); color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-3));
font-weight: 600; font-weight: 600;
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 0.5px; letter-spacing: 0.5px;
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { ScrollArea, Text, Divider, Modal, UnstyledButton } from "@mantine/core"; import { ScrollArea, Text, Divider, Modal } from "@mantine/core";
import { import {
IconHome, IconHome,
IconClock, IconClock,
@@ -119,13 +119,17 @@ export default function GlobalSidebar() {
</ScrollArea> </ScrollArea>
<div className={classes.bottomSection}> <div className={classes.bottomSection}>
<UnstyledButton <a
className={classes.link} className={classes.link}
onClick={openInvite} onClick={(e) => {
e.preventDefault();
openInvite();
}}
href="#"
> >
<IconUserPlus className={classes.linkIcon} stroke={2} /> <IconUserPlus className={classes.linkIcon} stroke={2} />
<span>{t("Invite People")}</span> <span>{t("Invite People")}</span>
</UnstyledButton> </a>
<Link <Link
className={classes.link} className={classes.link}
data-active={active.startsWith("/settings") || undefined} data-active={active.startsWith("/settings") || undefined}
@@ -29,7 +29,7 @@ export default function AppVersion() {
> >
<Indicator <Indicator
label={t("New update")} label={t("New update")}
color="dark" color="gray"
inline inline
size={16} size={16}
position="middle-end" position="middle-end"
@@ -230,6 +230,32 @@ export default function SettingsSidebar() {
} }
const isDisabled = isItemDisabled(item); const isDisabled = isItemDisabled(item);
const linkElement = (
<Link
onMouseEnter={!isDisabled ? prefetchHandler : undefined}
className={classes.link}
data-active={active.startsWith(item.path) || undefined}
data-disabled={isDisabled || undefined}
key={item.label}
to={isDisabled ? "#" : item.path}
onClick={(e) => {
if (isDisabled) {
e.preventDefault();
return;
}
if (mobileSidebarOpened) {
toggleMobileSidebar();
}
}}
style={{
opacity: isDisabled ? 0.5 : 1,
cursor: isDisabled ? "not-allowed" : "pointer",
}}
>
<item.icon className={classes.linkIcon} stroke={2} />
<span>{t(item.label)}</span>
</Link>
);
if (isDisabled) { if (isDisabled) {
return ( return (
@@ -239,41 +265,12 @@ export default function SettingsSidebar() {
position="right" position="right"
withArrow withArrow
> >
<span {linkElement}
className={classes.link}
data-disabled
role="link"
aria-disabled="true"
tabIndex={0}
style={{
opacity: 0.5,
cursor: "not-allowed",
}}
>
<item.icon className={classes.linkIcon} stroke={2} />
<span>{t(item.label)}</span>
</span>
</Tooltip> </Tooltip>
); );
} }
return ( return linkElement;
<Link
onMouseEnter={prefetchHandler}
className={classes.link}
data-active={active.startsWith(item.path) || undefined}
key={item.label}
to={item.path}
onClick={() => {
if (mobileSidebarOpened) {
toggleMobileSidebar();
}
}}
>
<item.icon className={classes.linkIcon} stroke={2} />
<span>{t(item.label)}</span>
</Link>
);
})} })}
</div> </div>
); );
@@ -291,7 +288,7 @@ export default function SettingsSidebar() {
}} }}
variant="transparent" variant="transparent"
c="gray" c="gray"
aria-label={t("Back")} aria-label="Back"
> >
<IconArrowLeft stroke={2} /> <IconArrowLeft stroke={2} />
</ActionIcon> </ActionIcon>
@@ -1,5 +1,5 @@
import React from "react"; import React from "react";
import { Avatar, MantineColor } from "@mantine/core"; import { Avatar } from "@mantine/core";
import { getAvatarUrl } from "@/lib/config.ts"; import { getAvatarUrl } from "@/lib/config.ts";
import { AvatarIconType } from "@/features/attachments/types/attachment.types.ts"; import { AvatarIconType } from "@/features/attachments/types/attachment.types.ts";
@@ -16,39 +16,11 @@ interface CustomAvatarProps {
mt?: string | number; mt?: string | number;
} }
// `color.shade` pairs whose filled background meets WCAG AA (4.5:1) against
// white text. Avoids lime/yellow/green/orange — even their dark shades have
// weak white-text contrast.
const SAFE_INITIALS_COLORS: MantineColor[] = [
"blue.8",
"cyan.9",
"grape.7",
"indigo.7",
"pink.8",
"red.8",
"violet.7",
];
function hashName(input: string) {
let hash = 0;
for (let i = 0; i < input.length; i += 1) {
hash = (hash << 5) - hash + input.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
function pickInitialsColor(name: string) {
return SAFE_INITIALS_COLORS[hashName(name) % SAFE_INITIALS_COLORS.length];
}
export const CustomAvatar = React.forwardRef< export const CustomAvatar = React.forwardRef<
HTMLInputElement, HTMLInputElement,
CustomAvatarProps CustomAvatarProps
>(({ avatarUrl, name, type, color, ...props }: CustomAvatarProps, ref) => { >(({ avatarUrl, name, type, ...props }: CustomAvatarProps, ref) => {
const avatarLink = getAvatarUrl(avatarUrl, type); const avatarLink = getAvatarUrl(avatarUrl, type);
const resolvedColor =
!color || color === "initials" ? pickInitialsColor(name ?? "") : color;
return ( return (
<Avatar <Avatar
@@ -56,7 +28,7 @@ export const CustomAvatar = React.forwardRef<
src={avatarLink} src={avatarLink}
name={name} name={name}
alt={name} alt={name}
color={resolvedColor} color="initials"
{...props} {...props}
/> />
); );
@@ -74,18 +74,7 @@ export function PageChildren({
/> />
))} ))}
{hasNextPage && ( {hasNextPage && (
<div <div className={classes.loadMore} onClick={() => fetchNextPage()}>
className={classes.loadMore}
onClick={() => fetchNextPage()}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
fetchNextPage();
}
}}
role="button"
tabIndex={0}
>
{t("Load more")} {t("Load more")}
</div> </div>
)} )}
@@ -70,14 +70,11 @@ function EmojiPicker({
closeOnEscape={true} closeOnEscape={true}
> >
<Popover.Target ref={setTarget}> <Popover.Target ref={setTarget}>
<ActionIcon <ActionIcon
c={actionIconProps?.c || "gray"} c={actionIconProps?.c || "gray"}
variant={actionIconProps?.variant || "transparent"} variant={actionIconProps?.variant || "transparent"}
size={actionIconProps?.size} size={actionIconProps?.size}
onClick={handlers.toggle} onClick={handlers.toggle}
aria-label={t("Pick emoji")}
aria-haspopup="dialog"
aria-expanded={opened}
> >
{icon} {icon}
</ActionIcon> </ActionIcon>
@@ -132,7 +132,6 @@ export default function AiChatSidebarItem({
size="xs" size="xs"
color="gray" color="gray"
onClick={(e) => e.preventDefault()} onClick={(e) => e.preventDefault()}
aria-label={t("Chat menu")}
> >
<IconDots size={14} /> <IconDots size={14} />
</ActionIcon> </ActionIcon>
@@ -137,8 +137,7 @@ export default function AiChatSidebar() {
<TextInput <TextInput
className={classes.searchInput} className={classes.searchInput}
placeholder={t("Search chats...")} placeholder="Search chats..."
aria-label={t("Search chats")}
leftSection={<IconSearch size={14} />} leftSection={<IconSearch size={14} />}
size="xs" size="xs"
value={search} value={search}
@@ -178,7 +178,6 @@ export default function AsideChatPanel() {
href="/ai" href="/ai"
variant="subtle" variant="subtle"
color="dark" color="dark"
aria-label={t("New chat")}
onClick={handleNewChat} onClick={handleNewChat}
> >
<IconPlus size={20} stroke={1.75} /> <IconPlus size={20} stroke={1.75} />
@@ -186,23 +185,13 @@ export default function AsideChatPanel() {
</Tooltip> </Tooltip>
<Tooltip label={t("Open full page")} openDelay={250}> <Tooltip label={t("Open full page")} openDelay={250}>
<ActionIcon <ActionIcon variant="subtle" color="dark" onClick={handleExpand}>
variant="subtle"
color="dark"
aria-label={t("Open full page")}
onClick={handleExpand}
>
<IconArrowsDiagonal size={18} stroke={1.5} /> <IconArrowsDiagonal size={18} stroke={1.5} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
<Tooltip label={t("Close")} openDelay={250}> <Tooltip label={t("Close")} openDelay={250}>
<ActionIcon <ActionIcon variant="subtle" color="dark" onClick={handleClose}>
variant="subtle"
color="dark"
aria-label={t("Close")}
onClick={handleClose}
>
<IconX size={20} stroke={1.75} /> <IconX size={20} stroke={1.75} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
@@ -65,7 +65,7 @@ export default function ChatEmptyState({ isStreaming, onSend, onStop }: Props) {
isStreaming={isStreaming} isStreaming={isStreaming}
onSend={onSend} onSend={onSend}
onStop={onStop} onStop={onStop}
placeholder={t("Ask anything... Use @ to mention pages")} placeholder="Ask anything... Use @ to mention pages"
autofocus autofocus
/> />
</div> </div>
@@ -200,7 +200,7 @@ export default function ChatInput({
link: false, link: false,
}), }),
Placeholder.configure({ Placeholder.configure({
placeholder: placeholder || t("Ask anything... Use @ to mention pages"), placeholder: placeholder || "Ask anything... Use @ to mention pages",
}), }),
CharacterCount.configure({ CharacterCount.configure({
limit: 50000, limit: 50000,
@@ -225,10 +225,6 @@ export default function ChatInput({
}), }),
], ],
editorProps: { editorProps: {
attributes: {
"aria-label": placeholder || t("Ask anything... Use @ to mention pages"),
"aria-multiline": "true",
},
handleDOMEvents: { handleDOMEvents: {
keydown: (_view, event) => { keydown: (_view, event) => {
if ( if (
@@ -279,8 +275,6 @@ export default function ChatInput({
type="file" type="file"
accept={ACCEPTED_FILE_TYPES} accept={ACCEPTED_FILE_TYPES}
multiple multiple
aria-label={t("Add files")}
tabIndex={-1}
style={{ display: "none" }} style={{ display: "none" }}
onChange={(e) => handleFileSelect(e.target.files)} onChange={(e) => handleFileSelect(e.target.files)}
/> />
@@ -31,16 +31,7 @@ export default function ChatToolGroup({ toolCalls, isStreaming }: Props) {
<div className={classes.toolGroup}> <div className={classes.toolGroup}>
<div <div
className={classes.toolGroupHeader} className={classes.toolGroupHeader}
role="button"
tabIndex={0}
aria-expanded={expanded}
onClick={() => setExpanded((prev) => !prev)} onClick={() => setExpanded((prev) => !prev)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setExpanded((prev) => !prev);
}
}}
> >
{activeLabel ? ( {activeLabel ? (
<IconLoader2 size={12} className={classes.processingSpinner} /> <IconLoader2 size={12} className={classes.processingSpinner} />
@@ -98,7 +98,7 @@
font-weight: 600; font-weight: 600;
letter-spacing: 0.08em; letter-spacing: 0.08em;
text-transform: uppercase; text-transform: uppercase;
color: var(--mantine-color-dimmed); color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
margin-bottom: var(--mantine-spacing-xs); margin-bottom: var(--mantine-spacing-xs);
} }
@@ -125,7 +125,7 @@
.suggestionsLabel { .suggestionsLabel {
font-size: var(--mantine-font-size-xs); font-size: var(--mantine-font-size-xs);
font-weight: 500; font-weight: 500;
color: var(--mantine-color-dimmed); color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 0.5px; letter-spacing: 0.5px;
margin-bottom: var(--mantine-spacing-sm); margin-bottom: var(--mantine-spacing-sm);
@@ -43,7 +43,7 @@
margin-top: 6px; margin-top: 6px;
text-align: center; text-align: center;
font-size: var(--mantine-font-size-xs); font-size: var(--mantine-font-size-xs);
color: var(--mantine-color-dimmed); color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));
} }
.attachmentChips { .attachmentChips {
@@ -36,7 +36,7 @@
padding: 4px var(--mantine-spacing-xs); padding: 4px var(--mantine-spacing-xs);
font-size: var(--mantine-font-size-xs); font-size: var(--mantine-font-size-xs);
font-weight: 600; font-weight: 600;
color: var(--mantine-color-dimmed); color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
user-select: none; user-select: none;
} }
@@ -104,7 +104,7 @@
.chatItemDate { .chatItemDate {
font-size: var(--mantine-font-size-xs); font-size: var(--mantine-font-size-xs);
color: var(--mantine-color-dimmed); color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));
white-space: nowrap; white-space: nowrap;
transition: opacity 150ms; transition: opacity 150ms;
} }
@@ -44,7 +44,7 @@ export function ApiKeyTable({
<Table.Th>{t("Last used")}</Table.Th> <Table.Th>{t("Last used")}</Table.Th>
<Table.Th>{t("Expires")}</Table.Th> <Table.Th>{t("Expires")}</Table.Th>
<Table.Th>{t("Created")}</Table.Th> <Table.Th>{t("Created")}</Table.Th>
<Table.Th aria-label={t("Action")} /> <Table.Th></Table.Th>
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
@@ -106,11 +106,7 @@ export function ApiKeyTable({
<Table.Td> <Table.Td>
<Menu position="bottom-end" withinPortal> <Menu position="bottom-end" withinPortal>
<Menu.Target> <Menu.Target>
<ActionIcon <ActionIcon variant="subtle" color="gray">
variant="subtle"
color="gray"
aria-label={t("API key menu")}
>
<IconDots size={16} /> <IconDots size={16} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -1,12 +1,4 @@
import { import { ActionIcon, Group, Menu, Modal, Text, Tooltip } from "@mantine/core";
ActionIcon,
Group,
Menu,
Modal,
Text,
ThemeIcon,
Tooltip,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks"; import { useDisclosure } from "@mantine/hooks";
import { import {
IconRosetteDiscountCheckFilled, IconRosetteDiscountCheckFilled,
@@ -46,7 +38,6 @@ export function PageVerificationModal({
<Modal <Modal
opened={opened} opened={opened}
onClose={onClose} onClose={onClose}
aria-label={status === "none" ? t("Set up verification") : t("Verify page")}
title={ title={
<Group gap="xs"> <Group gap="xs">
<IconShieldCheck <IconShieldCheck
@@ -106,9 +97,9 @@ export function PageVerificationBadge({
withArrow withArrow
openDelay={250} openDelay={250}
> >
<ThemeIcon variant="subtle" color="gray"> <ActionIcon variant="subtle" color="gray">
<IconShieldCheck size={20} stroke={1.5} /> <IconShieldCheck size={20} stroke={1.5} />
</ThemeIcon> </ActionIcon>
</Tooltip> </Tooltip>
); );
} }
@@ -139,12 +130,7 @@ export function PageVerificationBadge({
</Tooltip> </Tooltip>
) : !readOnly ? ( ) : !readOnly ? (
<Tooltip label={t("Set up verification")} withArrow openDelay={250}> <Tooltip label={t("Set up verification")} withArrow openDelay={250}>
<ActionIcon <ActionIcon variant="subtle" color="gray" onClick={open}>
variant="subtle"
color="gray"
aria-label={t("Set up verification")}
onClick={open}
>
<IconShieldCheck size={20} stroke={1.5} /> <IconShieldCheck size={20} stroke={1.5} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
@@ -37,7 +37,7 @@ export function ScimTokenTable({
<Table.Th>{t("Created by")}</Table.Th> <Table.Th>{t("Created by")}</Table.Th>
<Table.Th>{t("Last used")}</Table.Th> <Table.Th>{t("Last used")}</Table.Th>
<Table.Th>{t("Created")}</Table.Th> <Table.Th>{t("Created")}</Table.Th>
<Table.Th aria-label={t("Action")} /> <Table.Th></Table.Th>
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
@@ -141,7 +141,6 @@ export default function SsoProviderList() {
<ActionIcon <ActionIcon
variant="subtle" variant="subtle"
color="gray" color="gray"
aria-label={t("Edit {{name}}", { name: provider.name })}
onClick={() => handleEdit(provider)} onClick={() => handleEdit(provider)}
> >
<IconPencil size={16} /> <IconPencil size={16} />
@@ -153,13 +152,7 @@ export default function SsoProviderList() {
withinPortal withinPortal
> >
<Menu.Target> <Menu.Target>
<ActionIcon <ActionIcon variant="subtle" color="gray">
variant="subtle"
color="gray"
aria-label={t("More actions for {{name}}", {
name: provider.name,
})}
>
<IconDots size={16} /> <IconDots size={16} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -56,7 +56,6 @@ export default function TemplateCard({
color="gray" color="gray"
className={classes.menuTarget} className={classes.menuTarget}
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
aria-label={t("Template menu")}
> >
<IconDots size={16} /> <IconDots size={16} />
</ActionIcon> </ActionIcon>
@@ -24,7 +24,7 @@ export default function TemplatePreviewModal({
const title = template?.title || t("Untitled"); const title = template?.title || t("Untitled");
return ( return (
<Modal.Root size={1200} opened={opened} onClose={onClose} aria-label={title}> <Modal.Root size={1200} opened={opened} onClose={onClose}>
<Modal.Overlay /> <Modal.Overlay />
<Modal.Content style={{ overflow: "hidden" }}> <Modal.Content style={{ overflow: "hidden" }}>
<Modal.Header> <Modal.Header>
@@ -144,7 +144,6 @@ function CommentDialog({ editor, pageId, readOnly }: CommentDialogProps) {
withCloseButton withCloseButton
withBorder withBorder
data-comment-dialog data-comment-dialog
aria-label={t("Add comment")}
> >
<Stack gap={2}> <Stack gap={2}>
<Group> <Group>
@@ -173,15 +173,6 @@ function CommentListItem({
<Box <Box
className={classes.textSelection} className={classes.textSelection}
onClick={() => handleCommentClick(comment)} onClick={() => handleCommentClick(comment)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleCommentClick(comment);
}
}}
role="button"
tabIndex={0}
aria-label={t("Jump to comment selection")}
> >
<Text size="sm">{comment?.selection}</Text> <Text size="sm">{comment?.selection}</Text>
</Box> </Box>
@@ -46,11 +46,7 @@ function CommentMenu({
return ( return (
<Menu shadow="md" width={200}> <Menu shadow="md" width={200}>
<Menu.Target> <Menu.Target>
<ActionIcon <ActionIcon variant="default" style={{ border: "none" }}>
variant="default"
style={{ border: "none" }}
aria-label={t("Comment menu")}
>
<IconDots size={20} stroke={2} /> <IconDots size={20} stroke={2} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -36,7 +36,6 @@ export default function AudioView(props: NodeViewProps) {
preload="metadata" preload="metadata"
controls controls
src={safeSrc} src={safeSrc}
aria-label={placeholder?.name || t("Audio")}
/> />
)} )}
{!safeSrc && previewSrc && ( {!safeSrc && previewSrc && (
@@ -46,7 +45,6 @@ export default function AudioView(props: NodeViewProps) {
preload="metadata" preload="metadata"
controls controls
src={previewSrc} src={previewSrc}
aria-label={placeholder?.name || t("Audio")}
/> />
<Loader size={20} pos="absolute" top={6} right={6} /> <Loader size={20} pos="absolute" top={6} right={6} />
</Group> </Group>
@@ -62,7 +60,7 @@ export default function AudioView(props: NodeViewProps) {
</Group> </Group>
)} )}
{!safeSrc && !previewSrc && !placeholder && ( {!safeSrc && !previewSrc && !placeholder && (
<audio className={classes.audio} controls aria-label={t("Audio")} /> <audio className={classes.audio} controls />
)} )}
</div> </div>
</NodeViewWrapper> </NodeViewWrapper>
@@ -172,9 +172,6 @@ export const ColorSelector: FC<ColorSelectorProps> = ({
fontWeight: 500, fontWeight: 500,
fontSize: rem(16), fontSize: rem(16),
}} }}
aria-label={t("Text color")}
aria-haspopup="dialog"
aria-expanded={isOpen}
> >
A A
</Button> </Button>
@@ -189,32 +186,20 @@ export const ColorSelector: FC<ColorSelectorProps> = ({
{t("Text color")} {t("Text color")}
</Text> </Text>
<SimpleGrid cols={5} spacing="xs"> <SimpleGrid cols={5} spacing="xs">
{TEXT_COLORS.map(({ name, color }, index) => { {TEXT_COLORS.map(({ name, color }, index) => (
const applyTextColor = () => {
if (name === "Default") {
editor.commands.unsetColor();
} else {
editor
.chain()
.focus()
.setColor(color || "")
.run();
}
setIsOpen(false);
};
return (
<Tooltip key={index} label={t(name)} withArrow> <Tooltip key={index} label={t(name)} withArrow>
<Box <Box
role="button" onClick={() => {
tabIndex={0} if (name === "Default") {
aria-label={t(name)} editor.commands.unsetColor();
aria-pressed={!!editorState[`text_${color}`]} } else {
onClick={applyTextColor} editor
onKeyDown={(e) => { .chain()
if (e.key === "Enter" || e.key === " ") { .focus()
e.preventDefault(); .setColor(color || "")
applyTextColor(); .run();
} }
setIsOpen(false);
}} }}
style={{ style={{
width: rem(28), width: rem(28),
@@ -236,8 +221,7 @@ export const ColorSelector: FC<ColorSelectorProps> = ({
A A
</Box> </Box>
</Tooltip> </Tooltip>
); ))}
})}
</SimpleGrid> </SimpleGrid>
</Box> </Box>
@@ -246,35 +230,23 @@ export const ColorSelector: FC<ColorSelectorProps> = ({
{t("Highlight color")} {t("Highlight color")}
</Text> </Text>
<SimpleGrid cols={5} spacing="xs"> <SimpleGrid cols={5} spacing="xs">
{HIGHLIGHT_COLORS.map(({ name, color }, index) => { {HIGHLIGHT_COLORS.map(({ name, color }, index) => (
const applyHighlight = () => {
if (name === "Default") {
editor.commands.unsetHighlight();
} else {
editor
.chain()
.focus()
.toggleMark("highlight", {
color: color || "",
colorName: name.toLowerCase() || "",
})
.run();
}
setIsOpen(false);
};
return (
<Tooltip key={index} label={t(name)} withArrow> <Tooltip key={index} label={t(name)} withArrow>
<Box <Box
role="button" onClick={() => {
tabIndex={0} if (name === "Default") {
aria-label={t(name)} editor.commands.unsetHighlight();
aria-pressed={!!editorState[`highlight_${color}`]} } else {
onClick={applyHighlight} editor
onKeyDown={(e) => { .chain()
if (e.key === "Enter" || e.key === " ") { .focus()
e.preventDefault(); .toggleMark("highlight", {
applyHighlight(); color: color || "",
colorName: name.toLowerCase() || "",
})
.run();
} }
setIsOpen(false);
}} }}
style={{ style={{
width: rem(28), width: rem(28),
@@ -302,8 +274,7 @@ export const ColorSelector: FC<ColorSelectorProps> = ({
)} )}
</Box> </Box>
</Tooltip> </Tooltip>
); ))}
})}
</SimpleGrid> </SimpleGrid>
</Box> </Box>
@@ -60,7 +60,7 @@ export const NodeSelector: FC<NodeSelectorProps> = ({
isCodeBlock: ctx.editor.isActive("codeBlock"), isCodeBlock: ctx.editor.isActive("codeBlock"),
isCallout: ctx.editor.isActive("callout"), isCallout: ctx.editor.isActive("callout"),
isDetails: ctx.editor.isActive("details"), isDetails: ctx.editor.isActive("details"),
isTransclusionSource: ctx.editor.isActive("transclusionSource"), isTransclusion: ctx.editor.isActive("transclusion"),
}; };
}, },
}); });
@@ -124,12 +124,6 @@ export const NodeSelector: FC<NodeSelectorProps> = ({
.run(), .run(),
isActive: () => editorState?.isBlockquote, isActive: () => editorState?.isBlockquote,
}, },
{
name: "Synced block",
icon: IconQuote,
command: () => editor.chain().focus().toggleTransclusionSource().run(),
isActive: () => editorState?.isTransclusionSource,
},
{ {
name: "Code", name: "Code",
icon: IconCode, icon: IconCode,
@@ -148,6 +142,12 @@ export const NodeSelector: FC<NodeSelectorProps> = ({
command: () => editor.chain().focus().setDetails().run(), command: () => editor.chain().focus().setDetails().run(),
isActive: () => editorState?.isDetails, isActive: () => editorState?.isDetails,
}, },
{
name: "Sync block",
icon: IconQuote,
command: () => editor.chain().focus().toggleTransclusion().run(),
isActive: () => editorState?.isTransclusion,
},
]; ];
const activeItem = items.filter((item) => item.isActive()).pop() ?? { const activeItem = items.filter((item) => item.isActive()).pop() ?? {
@@ -157,12 +157,7 @@ export const NodeSelector: FC<NodeSelectorProps> = ({
return ( return (
<Popover opened={isOpen} withArrow> <Popover opened={isOpen} withArrow>
<Popover.Target> <Popover.Target>
<Tooltip <Tooltip label={t("Turn into")} withArrow withinPortal={false} disabled={isOpen}>
label={t("Turn into")}
withArrow
withinPortal={false}
disabled={isOpen}
>
<Button <Button
className={classes.buttonRoot} className={classes.buttonRoot}
variant="default" variant="default"
@@ -170,9 +165,6 @@ export const NodeSelector: FC<NodeSelectorProps> = ({
radius="0" radius="0"
rightSection={<IconChevronDown size={16} />} rightSection={<IconChevronDown size={16} />}
onClick={() => setIsOpen(!isOpen)} onClick={() => setIsOpen(!isOpen)}
aria-label={t("Turn into")}
aria-haspopup="menu"
aria-expanded={isOpen}
> >
{t(activeItem?.name)} {t(activeItem?.name)}
</Button> </Button>
@@ -92,9 +92,6 @@ export const TextAlignmentSelector: FC<TextAlignmentProps> = ({
radius="0" radius="0"
rightSection={<IconChevronDown size={16} />} rightSection={<IconChevronDown size={16} />}
onClick={() => setIsOpen(!isOpen)} onClick={() => setIsOpen(!isOpen)}
aria-label={t("Text align")}
aria-haspopup="menu"
aria-expanded={isOpen}
> >
<activeItem.icon style={{ width: rem(16) }} stroke={2} /> <activeItem.icon style={{ width: rem(16) }} stroke={2} />
</Button> </Button>
@@ -137,13 +137,7 @@ export default function DrawioView(props: NodeViewProps) {
return ( return (
<NodeViewWrapper data-drag-handle> <NodeViewWrapper data-drag-handle>
<Modal.Root <Modal.Root opened={opened} onClose={handleClose} fullScreen closeOnEscape={false}>
opened={opened}
onClose={handleClose}
fullScreen
closeOnEscape={false}
aria-label={t("Diagram editor")}
>
<Modal.Overlay /> <Modal.Overlay />
<Modal.Content style={{ overflow: "hidden" }}> <Modal.Content style={{ overflow: "hidden" }}>
<Modal.Body pos="relative"> <Modal.Body pos="relative">
@@ -107,17 +107,7 @@ const EmojiList = ({
}, [selectedIndex]); }, [selectedIndex]);
return items.length > 0 || isLoading ? ( return items.length > 0 || isLoading ? (
<Paper <Paper id="emoji-command" p="0" shadow="md" withBorder>
id="emoji-command"
p="0"
shadow="md"
withBorder
role="listbox"
aria-label="Emoji results"
aria-activedescendant={
items.length > 0 ? `emoji-command-option-${selectedIndex}` : undefined
}
>
{isLoading && <Loader m="xs" color="blue" type="dots" />} {isLoading && <Loader m="xs" color="blue" type="dots" />}
{items.length > 0 && ( {items.length > 0 && (
<ScrollArea.Autosize <ScrollArea.Autosize
@@ -130,10 +120,6 @@ const EmojiList = ({
{items.map((item, index: number) => ( {items.map((item, index: number) => (
<ActionIcon <ActionIcon
data-item-index={index} data-item-index={index}
id={`emoji-command-option-${index}`}
role="option"
aria-selected={index === selectedIndex}
aria-label={item.id}
variant="transparent" variant="transparent"
key={item.id} key={item.id}
className={clsx(classes.menuBtn, { className={clsx(classes.menuBtn, {
@@ -102,14 +102,6 @@ export const LinkEditorPanel = ({
leftSection={<IconLink size={16} stroke={1.5} color="var(--mantine-color-dimmed)" />} leftSection={<IconLink size={16} stroke={1.5} color="var(--mantine-color-dimmed)" />}
classNames={{ input: classes.linkInput }} classNames={{ input: classes.linkInput }}
placeholder={t("Paste link or search pages")} placeholder={t("Paste link or search pages")}
aria-label={t("Paste link or search pages")}
role="combobox"
aria-expanded={showDropdown}
aria-controls="link-editor-results"
aria-autocomplete="list"
aria-activedescendant={
showDropdown ? `link-editor-option-${selectedIndex}` : undefined
}
value={state.url} value={state.url}
onChange={state.onChange} onChange={state.onChange}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
@@ -133,16 +125,10 @@ export const LinkEditorPanel = ({
scrollbarSize={6} scrollbarSize={6}
mt={state.url.length > 0 ? 8 : 0} mt={state.url.length > 0 ? 8 : 0}
styles={{ content: { minWidth: 0 } }} styles={{ content: { minWidth: 0 } }}
id="link-editor-results"
role="listbox"
aria-label={t("Link suggestions")}
> >
{showUrlItem && ( {showUrlItem && (
<UnstyledButton <UnstyledButton
data-item-index={0} data-item-index={0}
id="link-editor-option-0"
role="option"
aria-selected={selectedIndex === 0}
onClick={() => onSetLink(state.url, false)} onClick={() => onSetLink(state.url, false)}
className={clsx(classes.searchItem, { className={clsx(classes.searchItem, {
[classes.selectedSearchItem]: selectedIndex === 0, [classes.selectedSearchItem]: selectedIndex === 0,
@@ -170,9 +156,6 @@ export const LinkEditorPanel = ({
return ( return (
<UnstyledButton <UnstyledButton
data-item-index={itemIndex} data-item-index={itemIndex}
id={`link-editor-option-${itemIndex}`}
role="option"
aria-selected={itemIndex === selectedIndex}
key={page.id || index} key={page.id || index}
onClick={() => selectPage(page)} onClick={() => selectPage(page)}
className={clsx(classes.searchItem, { className={clsx(classes.searchItem, {
@@ -287,16 +287,7 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
); );
return ( return (
<Paper <Paper id="mention" shadow="md" withBorder radius="md" py={6}>
id="mention"
shadow="md"
withBorder
radius="md"
py={6}
role="listbox"
aria-label={t("Mention suggestions")}
aria-activedescendant={`mention-option-${selectedIndex}`}
>
<ScrollArea.Autosize <ScrollArea.Autosize
viewportRef={viewportRef} viewportRef={viewportRef}
mah={350} mah={350}
@@ -310,7 +301,7 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
if (item.entityType === "header") { if (item.entityType === "header") {
const isFirst = index === 0; const isFirst = index === 0;
return ( return (
<div key={`${item.label}-${index}`} role="presentation"> <div key={`${item.label}-${index}`}>
{!isFirst && <Divider my={6} />} {!isFirst && <Divider my={6} />}
<Text <Text
c="dimmed" c="dimmed"
@@ -331,9 +322,6 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
<UnstyledButton <UnstyledButton
data-item-index={index} data-item-index={index}
key={index} key={index}
id={`mention-option-${index}`}
role="option"
aria-selected={index === selectedIndex}
onClick={() => selectItem(index)} onClick={() => selectItem(index)}
className={clsx(classes.menuBtn, { className={clsx(classes.menuBtn, {
[classes.selectedItem]: index === selectedIndex, [classes.selectedItem]: index === selectedIndex,
@@ -360,9 +348,6 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
<UnstyledButton <UnstyledButton
data-item-index={index} data-item-index={index}
key={index} key={index}
id={`mention-option-${index}`}
role="option"
aria-selected={index === selectedIndex}
onClick={() => selectItem(index)} onClick={() => selectItem(index)}
className={clsx(classes.menuBtn, { className={clsx(classes.menuBtn, {
[classes.selectedItem]: index === selectedIndex, [classes.selectedItem]: index === selectedIndex,
@@ -373,7 +358,7 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
<ActionIcon <ActionIcon
variant="subtle" variant="subtle"
component="div" component="div"
aria-hidden="true" aria-label={item.label}
color="gray" color="gray"
size="sm" size="sm"
> >
@@ -405,11 +390,6 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
{(hasUsers || hasPages) && <Divider my={6} />} {(hasUsers || hasPages) && <Divider my={6} />}
<UnstyledButton <UnstyledButton
data-item-index={renderItems.indexOf(createPageItemData)} data-item-index={renderItems.indexOf(createPageItemData)}
id={`mention-option-${renderItems.indexOf(createPageItemData)}`}
role="option"
aria-selected={
renderItems.indexOf(createPageItemData) === selectedIndex
}
onClick={() => onClick={() =>
selectItem(renderItems.indexOf(createPageItemData)) selectItem(renderItems.indexOf(createPageItemData))
} }
@@ -425,7 +405,6 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
component="div" component="div"
color="gray" color="gray"
size="sm" size="sm"
aria-hidden="true"
> >
<IconPlus size={16} stroke={1.5} /> <IconPlus size={16} stroke={1.5} />
</ActionIcon> </ActionIcon>
@@ -92,20 +92,7 @@ export default function PdfView(props: NodeViewProps) {
if (hasError) { if (hasError) {
return ( return (
<NodeViewWrapper data-drag-handle> <NodeViewWrapper data-drag-handle>
<div <div data-pdf-error className={clsx(classes.pdfError, { "ProseMirror-selectednode": selected })} onClick={handleSelect}>
data-pdf-error
className={clsx(classes.pdfError, { "ProseMirror-selectednode": selected })}
onClick={handleSelect}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleSelect();
}
}}
role="button"
tabIndex={0}
aria-label={t("Failed to load PDF")}
>
<IconFileTypePdf size={32} stroke={1.5} /> <IconFileTypePdf size={32} stroke={1.5} />
<Text size="sm" c="dimmed"> <Text size="sm" c="dimmed">
{t("Failed to load PDF")} {t("Failed to load PDF")}
@@ -187,14 +187,12 @@ function SearchAndReplaceDialog({ editor, editable = true }: PageFindDialogDialo
position={{ top: 90, right: 50 }} position={{ top: 90, right: 50 }}
withBorder withBorder
transitionProps={{ transition: "slide-down" }} transitionProps={{ transition: "slide-down" }}
aria-label={t("Find and replace")}
> >
<Stack gap="xs"> <Stack gap="xs">
<Flex align="center" gap="xs"> <Flex align="center" gap="xs">
<Input <Input
ref={inputRef} ref={inputRef}
placeholder={t("Find")} placeholder={t("Find")}
aria-label={t("Find")}
leftSection={<IconSearch size={16} />} leftSection={<IconSearch size={16} />}
rightSection={ rightSection={
<Text size="xs" ta="right"> <Text size="xs" ta="right">
@@ -219,12 +217,7 @@ function SearchAndReplaceDialog({ editor, editable = true }: PageFindDialogDialo
<ActionIcon.Group> <ActionIcon.Group>
<Tooltip label={t("Previous match (Shift+Enter)")}> <Tooltip label={t("Previous match (Shift+Enter)")}>
<ActionIcon <ActionIcon variant="subtle" color="gray" onClick={previous}>
variant="subtle"
color="gray"
onClick={previous}
aria-label={t("Previous match (Shift+Enter)")}
>
<IconArrowNarrowUp <IconArrowNarrowUp
style={{ width: "70%", height: "70%" }} style={{ width: "70%", height: "70%" }}
stroke={1.5} stroke={1.5}
@@ -232,12 +225,7 @@ function SearchAndReplaceDialog({ editor, editable = true }: PageFindDialogDialo
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
<Tooltip label={t("Next match (Enter)")}> <Tooltip label={t("Next match (Enter)")}>
<ActionIcon <ActionIcon variant="subtle" color="gray" onClick={next}>
variant="subtle"
color="gray"
onClick={next}
aria-label={t("Next match (Enter)")}
>
<IconArrowNarrowDown <IconArrowNarrowDown
style={{ width: "70%", height: "70%" }} style={{ width: "70%", height: "70%" }}
stroke={1.5} stroke={1.5}
@@ -249,8 +237,6 @@ function SearchAndReplaceDialog({ editor, editable = true }: PageFindDialogDialo
variant="subtle" variant="subtle"
color={caseSensitive.color} color={caseSensitive.color}
onClick={() => caseSensitiveToggle()} onClick={() => caseSensitiveToggle()}
aria-label={t("Match case (Alt+C)")}
aria-pressed={caseSensitive.isCaseSensitive}
> >
<IconLetterCase <IconLetterCase
style={{ width: "70%", height: "70%" }} style={{ width: "70%", height: "70%" }}
@@ -264,8 +250,6 @@ function SearchAndReplaceDialog({ editor, editable = true }: PageFindDialogDialo
variant="subtle" variant="subtle"
color={replaceButton.color} color={replaceButton.color}
onClick={() => replaceButtonToggle()} onClick={() => replaceButtonToggle()}
aria-label={t("Replace")}
aria-pressed={replaceButton.isReplaceShow}
> >
<IconReplace <IconReplace
style={{ width: "70%", height: "70%" }} style={{ width: "70%", height: "70%" }}
@@ -275,12 +259,7 @@ function SearchAndReplaceDialog({ editor, editable = true }: PageFindDialogDialo
</Tooltip> </Tooltip>
)} )}
<Tooltip label={t("Close (Escape)")}> <Tooltip label={t("Close (Escape)")}>
<ActionIcon <ActionIcon variant="subtle" color="gray" onClick={closeDialog}>
variant="subtle"
color="gray"
onClick={closeDialog}
aria-label={t("Close (Escape)")}
>
<IconX style={{ width: "70%", height: "70%" }} stroke={1.5} /> <IconX style={{ width: "70%", height: "70%" }} stroke={1.5} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
@@ -290,7 +269,6 @@ function SearchAndReplaceDialog({ editor, editable = true }: PageFindDialogDialo
<Flex align="center" gap="xs"> <Flex align="center" gap="xs">
<Input <Input
placeholder={t("Replace")} placeholder={t("Replace")}
aria-label={t("Replace")}
leftSection={<IconReplace size={16} />} leftSection={<IconReplace size={16} />}
rightSection={<div></div>} rightSection={<div></div>}
rightSectionPointerEvents="all" rightSectionPointerEvents="all"
@@ -86,15 +86,7 @@ const CommandList = ({
}, [selectedIndex]); }, [selectedIndex]);
return flatItems.length > 0 ? ( return flatItems.length > 0 ? (
<Paper <Paper id="slash-command" shadow="md" p="xs" withBorder>
id="slash-command"
shadow="md"
p="xs"
withBorder
role="listbox"
aria-label={t("Slash commands")}
aria-activedescendant={`slash-command-option-${selectedIndex}`}
>
<ScrollArea <ScrollArea
viewportRef={viewportRef} viewportRef={viewportRef}
h={350} h={350}
@@ -102,30 +94,22 @@ const CommandList = ({
scrollbarSize={8} scrollbarSize={8}
overscrollBehavior="contain" overscrollBehavior="contain"
> >
{(() => { {Object.entries(items).map(([category, categoryItems]) => (
let flatIndex = -1; <div key={category}>
return Object.entries(items).map(([category, categoryItems]) => (
<div key={category} role="group" aria-label={category}>
<Text c="dimmed" mb={4} fw={500} tt="capitalize"> <Text c="dimmed" mb={4} fw={500} tt="capitalize">
{category} {category}
</Text> </Text>
{categoryItems.map((item: SlashMenuItemType) => { {categoryItems.map((item: SlashMenuItemType, index: number) => (
flatIndex += 1;
const itemIndex = flatIndex;
return (
<UnstyledButton <UnstyledButton
data-item-index={itemIndex} data-item-index={index}
key={itemIndex} key={index}
id={`slash-command-option-${itemIndex}`} onClick={() => selectItem(index)}
role="option"
aria-selected={itemIndex === selectedIndex}
onClick={() => selectItem(itemIndex)}
className={clsx(classes.menuBtn, { className={clsx(classes.menuBtn, {
[classes.selectedItem]: itemIndex === selectedIndex, [classes.selectedItem]: index === selectedIndex,
})} })}
> >
<Group> <Group>
<ActionIcon variant="default" component="div" aria-hidden="true"> <ActionIcon variant="default" component="div">
<item.icon size={18} /> <item.icon size={18} />
</ActionIcon> </ActionIcon>
@@ -140,11 +124,9 @@ const CommandList = ({
</div> </div>
</Group> </Group>
</UnstyledButton> </UnstyledButton>
); ))}
})}
</div> </div>
)); ))}
})()}
</ScrollArea> </ScrollArea>
</Paper> </Paper>
) : null; ) : null;
@@ -232,15 +232,7 @@ const CommandGroups: SlashMenuGroupedItemsType = {
{ {
title: "Audio", title: "Audio",
description: "Upload any audio from your device.", description: "Upload any audio from your device.",
searchTerms: [ searchTerms: ["audio", "music", "sound", "mp3", "media", "file", "attachment"],
"audio",
"music",
"sound",
"mp3",
"media",
"file",
"attachment",
],
icon: IconMusic, icon: IconMusic,
command: ({ editor, range }) => { command: ({ editor, range }) => {
editor.chain().focus().deleteRange(range).run(); editor.chain().focus().deleteRange(range).run();
@@ -487,12 +479,12 @@ const CommandGroups: SlashMenuGroupedItemsType = {
}, },
}, },
{ {
title: "Synced block", title: "Sync block",
description: "Create a block that stays in sync across pages.", description: "Create a block that stays in sync across pages.",
searchTerms: [ searchTerms: [
"sync", "sync",
"synced", "synced",
"synced block", "sync block",
"excerpt", "excerpt",
"transclusion", "transclusion",
"reusable", "reusable",
@@ -500,12 +492,7 @@ const CommandGroups: SlashMenuGroupedItemsType = {
], ],
icon: IconRotate2, icon: IconRotate2,
command: ({ editor, range }: CommandProps) => { command: ({ editor, range }: CommandProps) => {
editor editor.chain().focus().deleteRange(range).insertTransclusion().run();
.chain()
.focus()
.deleteRange(range)
.insertTransclusionSource()
.run();
}, },
}, },
{ {
@@ -92,17 +92,8 @@ export default function StatusView(props: NodeViewProps) {
colorClassMap[color], colorClassMap[color],
)} )}
onClick={() => isEditable && setOpened(true)} onClick={() => isEditable && setOpened(true)}
onKeyDown={(e) => {
if (isEditable && (e.key === "Enter" || e.key === " ")) {
e.preventDefault();
setOpened(true);
}
}}
role="button" role="button"
tabIndex={0} tabIndex={0}
aria-label={text || "SET STATUS"}
aria-haspopup="dialog"
aria-expanded={opened}
> >
{text || "SET STATUS"} {text || "SET STATUS"}
</span> </span>
@@ -136,16 +127,6 @@ export default function StatusView(props: NodeViewProps) {
)} )}
style={{ backgroundColor: bg }} style={{ backgroundColor: bg }}
onClick={() => handleColorChange(name)} onClick={() => handleColorChange(name)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleColorChange(name);
}
}}
role="button"
tabIndex={0}
aria-label={name}
aria-pressed={color === name}
> >
{color === name && <IconCheck size={14} />} {color === name && <IconCheck size={14} />}
</Box> </Box>
@@ -7,11 +7,16 @@ export default function ErrorPlaceholder() {
return ( return (
<div className={classes.placeholder}> <div className={classes.placeholder}>
<IconAlertTriangle <IconAlertTriangle
size={18} size={20}
stroke={1.6} stroke={1.5}
className={classes.placeholderIcon} className={classes.placeholderIcon}
/> />
<span>{t("Failed to load this synced block")}</span> <div className={classes.placeholderTitle}>
{t("Failed to load transclusion")}
</div>
<div className={classes.placeholderSubtext}>
{t("An error occurred while rendering this reference")}
</div>
</div> </div>
); );
} }
@@ -6,8 +6,11 @@ export default function NoAccessPlaceholder() {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<div className={classes.placeholder}> <div className={classes.placeholder}>
<IconEyeOff size={18} stroke={1.6} className={classes.placeholderIcon} /> <IconEyeOff size={20} stroke={1.5} className={classes.placeholderIcon} />
<span>{t("You don't have access to this synced block")}</span> <div className={classes.placeholderTitle}>{t("No access")}</div>
<div className={classes.placeholderSubtext}>
{t("You don't have access to this content")}
</div>
</div> </div>
); );
} }
@@ -1,4 +1,4 @@
import { IconInfoCircle } from "@tabler/icons-react"; import { IconQuestionMark } from "@tabler/icons-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import classes from "./transclusion.module.css"; import classes from "./transclusion.module.css";
@@ -6,12 +6,19 @@ export default function NotFoundPlaceholder() {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<div className={classes.placeholder}> <div className={classes.placeholder}>
<IconInfoCircle <IconQuestionMark
size={18} size={20}
stroke={1.6} stroke={1.5}
className={classes.placeholderIcon} className={classes.placeholderIcon}
/> />
<span>{t("The original synced block no longer exists")}</span> <div className={classes.placeholderTitle}>
{t("Synced block unavailable")}
</div>
<div className={classes.placeholderSubtext}>
{t(
"The source may have been removed, or embedding it here would create a loop.",
)}
</div>
</div> </div>
); );
} }
@@ -2,12 +2,14 @@ import { EditorProvider } from "@tiptap/react";
import { useMemo } from "react"; import { useMemo } from "react";
import { mainExtensions } from "@/features/editor/extensions/extensions"; import { mainExtensions } from "@/features/editor/extensions/extensions";
import { UniqueID } from "@docmost/editor-ext"; import { UniqueID } from "@docmost/editor-ext";
import { TransclusionLookupProvider } from "./transclusion-lookup-context";
type Props = { type Props = {
hostPageId: string;
content: unknown; content: unknown;
}; };
export default function TransclusionContent({ content }: Props) { export default function TransclusionContent({ hostPageId, content }: Props) {
const extensions = useMemo(() => { const extensions = useMemo(() => {
const filtered = mainExtensions.filter( const filtered = mainExtensions.filter(
(e: any) => e.name !== "uniqueID" && e.name !== "globalDragHandle", (e: any) => e.name !== "uniqueID" && e.name !== "globalDragHandle",
@@ -15,7 +17,7 @@ export default function TransclusionContent({ content }: Props) {
return [ return [
...filtered, ...filtered,
UniqueID.configure({ UniqueID.configure({
types: ["heading", "paragraph", "transclusionSource"], types: ["heading", "paragraph", "transclusion"],
updateDocument: false, updateDocument: false,
}), }),
]; ];
@@ -30,19 +32,21 @@ export default function TransclusionContent({ content }: Props) {
const stop = (e: React.SyntheticEvent) => e.stopPropagation(); const stop = (e: React.SyntheticEvent) => e.stopPropagation();
return ( return (
<div <TransclusionLookupProvider hostPageId={hostPageId}>
onMouseDown={stop} <div
onClick={stop} onMouseDown={stop}
onDragStart={stop} onClick={stop}
onDragOver={stop} onDragStart={stop}
onDrop={stop} onDragOver={stop}
> onDrop={stop}
<EditorProvider >
editable={false} <EditorProvider
immediatelyRender={true} editable={false}
extensions={extensions} immediatelyRender={true}
content={content as any} extensions={extensions}
/> content={content as any}
</div> />
</div>
</TransclusionLookupProvider>
); );
} }
@@ -7,10 +7,7 @@ import React, {
useRef, useRef,
useState, useState,
} from "react"; } from "react";
import { import { lookupTransclusion } from "@/features/transclusion/services/transclusion-api";
lookupTransclusion,
lookupTransclusionForShare,
} from "@/features/transclusion/services/transclusion-api";
import type { TransclusionLookup } from "@/features/transclusion/types/transclusion.types"; import type { TransclusionLookup } from "@/features/transclusion/types/transclusion.types";
type LookupKey = string; // `${sourcePageId}::${transclusionId}` type LookupKey = string; // `${sourcePageId}::${transclusionId}`
@@ -37,24 +34,18 @@ const TransclusionLookupContext = createContext<ContextValue | null>(null);
export function TransclusionLookupProvider({ export function TransclusionLookupProvider({
children, children,
shareId,
}: { }: {
children: React.ReactNode;
/** /**
* When set, lookups go through the share-scoped public endpoint and are * Retained for API compatibility with previous callers that passed the
* gated by the share graph (source page must have its own share or inherit * host page id; no longer used internally now that cycle prevention lives
* one). Used by the public share viewer; left undefined in the authenticated * on the server side and lookups are stateless.
* app, where personal permissions gate access.
*/ */
shareId?: string; hostPageId?: string;
children: React.ReactNode;
}) { }) {
const subscribersRef = useRef(new Map<LookupKey, Subscriber[]>()); const subscribersRef = useRef(new Map<LookupKey, Subscriber[]>());
const queueRef = useRef(new Set<LookupKey>()); const queueRef = useRef(new Set<LookupKey>());
const tickRef = useRef<ReturnType<typeof setTimeout> | null>(null); const tickRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Read inside flush() via ref so changing share context doesn't churn the
// memoized callbacks (and thus doesn't re-render every consumer).
const shareIdRef = useRef<string | undefined>(shareId);
shareIdRef.current = shareId;
// Last looked-up value for each key. Re-subscribers (e.g. when the editor // Last looked-up value for each key. Re-subscribers (e.g. when the editor
// remounts after switching from static to live) get this immediately // remounts after switching from static to live) get this immediately
// instead of triggering a duplicate fetch. // instead of triggering a duplicate fetch.
@@ -90,13 +81,7 @@ export function TransclusionLookupProvider({
}; };
try { try {
const activeShareId = shareIdRef.current; const { items } = await lookupTransclusion({ references });
const { items } = activeShareId
? await lookupTransclusionForShare({
shareId: activeShareId,
references,
})
: await lookupTransclusion({ references });
for (const r of items) { for (const r of items) {
const key = `${r.sourcePageId}::${r.transclusionId}`; const key = `${r.sourcePageId}::${r.transclusionId}`;
resultCacheRef.current.set(key, r); resultCacheRef.current.set(key, r);
@@ -2,8 +2,8 @@ import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { ActionIcon, Menu, Tooltip } from "@mantine/core"; import { ActionIcon, Menu, Tooltip } from "@mantine/core";
import { import {
IconDots, IconDots,
IconExternalLink,
IconLinkOff, IconLinkOff,
IconPencil,
IconRefresh, IconRefresh,
IconTrash, IconTrash,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
@@ -87,13 +87,10 @@ function TransclusionReferenceBody({
); );
const sourcePageHref = (() => { const sourcePageHref = (() => {
const source = referencesQuery.data?.source; const source = referencesQuery.data?.source;
const base = source?.spaceSlug if (source?.spaceSlug) {
? buildPageUrl(source.spaceSlug, source.slugId, source.title) return buildPageUrl(source.spaceSlug, source.slugId, source.title);
: sourcePageId }
? `/p/${sourcePageId}` return sourcePageId ? `/p/${sourcePageId}` : null;
: null;
if (!base) return null;
return transclusionId ? `${base}#${transclusionId}` : base;
})(); })();
const handleUnsync = async () => { const handleUnsync = async () => {
@@ -121,11 +118,7 @@ function TransclusionReferenceBody({
return ( return (
<> <>
{isEditable && ( {isEditable && (
<div <div className={classes.includeControls} contentEditable={false}>
className={classes.includeControls}
contentEditable={false}
onMouseDown={(e) => e.preventDefault()}
>
{sourcePageId && transclusionId && hostPageId && ( {sourcePageId && transclusionId && hostPageId && (
<SyncBlockReferencesDropdown <SyncBlockReferencesDropdown
sourcePageId={sourcePageId} sourcePageId={sourcePageId}
@@ -149,19 +142,15 @@ function TransclusionReferenceBody({
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
{sourcePageHref && ( {sourcePageHref && (
<Tooltip label={t("Edit source")}> <Tooltip label={t("Go to source page")}>
<ActionIcon <ActionIcon
component={Link} component={Link}
to={sourcePageHref} to={sourcePageHref}
variant="subtle" variant="subtle"
color="gray" color="gray"
size="sm" size="sm"
style={{
textDecoration: "none",
borderBottom: "none",
}}
> >
<IconPencil size={14} /> <IconExternalLink size={14} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
)} )}
@@ -201,7 +190,10 @@ function TransclusionReferenceBody({
) : !result ? ( ) : !result ? (
<div style={{ minHeight: 24 }} /> <div style={{ minHeight: 24 }} />
) : !("status" in result) ? ( ) : !("status" in result) ? (
<TransclusionContent content={result.content} /> <TransclusionContent
hostPageId={hostPageId ?? sourcePageId}
content={result.content}
/>
) : result.status === "no_access" ? ( ) : result.status === "no_access" ? (
<NoAccessPlaceholder /> <NoAccessPlaceholder />
) : ( ) : (
@@ -56,21 +56,17 @@ export default function TransclusionView(props: NodeViewProps) {
}; };
const handleUnsync = () => { const handleUnsync = () => {
editor.chain().focus().unsyncTransclusionSource().run(); editor.chain().focus().unsyncTransclusion().run();
}; };
return ( return (
<NodeViewWrapper <NodeViewWrapper
className={classes.transclusionWrap} className={classes.transclusionWrap}
data-drag-handle
data-menu-open={openMenus > 0 ? "true" : "false"} data-menu-open={openMenus > 0 ? "true" : "false"}
data-id={transclusionId ?? undefined}
> >
{isEditable && ( {isEditable && (
<div <div className={classes.transclusionControls} contentEditable={false}>
className={classes.transclusionControls}
contentEditable={false}
onMouseDown={(e) => e.preventDefault()}
>
{sourcePageId && transclusionId && ( {sourcePageId && transclusionId && (
<SyncBlockReferencesDropdown <SyncBlockReferencesDropdown
sourcePageId={sourcePageId} sourcePageId={sourcePageId}
@@ -113,7 +109,7 @@ export default function TransclusionView(props: NodeViewProps) {
leftSection={<IconTrash size={14} />} leftSection={<IconTrash size={14} />}
onClick={() => deleteNode()} onClick={() => deleteNode()}
> >
{t("Delete synced block")} {t("Delete sync block")}
</Menu.Item> </Menu.Item>
</Menu.Dropdown> </Menu.Dropdown>
</Menu> </Menu>
@@ -1,22 +1,33 @@
.placeholder { .placeholder {
display: flex; display: flex;
flex-direction: row; flex-direction: column;
align-items: center; align-items: center;
gap: 8px; justify-content: center;
padding: 8px 12px; gap: 4px;
padding: var(--mantine-spacing-md);
border-radius: var(--mantine-radius-md); border-radius: var(--mantine-radius-md);
background: light-dark( background: light-dark(
var(--mantine-color-gray-0), var(--mantine-color-gray-0),
var(--mantine-color-dark-6) var(--mantine-color-dark-6)
); );
border: 1px dashed
light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1)); color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));
font-size: var(--mantine-font-size-sm);
user-select: none;
} }
.placeholderIcon { .placeholderIcon {
flex: none; color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));
}
.placeholderTitle {
font-weight: 600;
font-size: var(--mantine-font-size-sm);
}
.placeholderSubtext {
font-size: var(--mantine-font-size-xs);
color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2)); color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
text-align: center;
} }
.transclusionBadge { .transclusionBadge {
@@ -39,18 +50,15 @@
margin-right: -3rem; margin-right: -3rem;
width: calc(100% + 6rem); width: calc(100% + 6rem);
padding: 0.5em 3rem; padding: 0.5em 3rem;
border-radius: 8px; border-radius: 4px;
border: 2px solid transparent; border: 1px solid transparent;
transition: border 0.3s; transition: border 0.3s;
} }
.transclusionWrap:hover, .transclusionWrap:hover,
.transclusionWrap:focus-within { .transclusionWrap:focus-within {
border: 2px solid border: 1px solid
light-dark( light-dark(var(--mantine-color-gray-3), var(--mantine-color-gray-7));
var(--mantine-color-orange-2),
color-mix(in srgb, var(--mantine-color-orange-9), transparent 55%)
);
} }
.transclusionControls { .transclusionControls {
@@ -96,32 +104,22 @@
background: var(--mantine-color-default-border); background: var(--mantine-color-default-border);
} }
.transclusionControls a[href],
.includeControls a[href] {
color: var(--ai-color);
border-bottom: none;
font-weight: inherit;
}
.includeWrap { .includeWrap {
position: relative; position: relative;
margin-left: -3rem; margin-left: -3rem;
margin-right: -3rem; margin-right: -3rem;
width: calc(100% + 6rem); width: calc(100% + 6rem);
padding: 0.5em 0; padding: 0.5em 0;
border-radius: 8px; border-radius: 4px;
border: 2px solid transparent; border: 1px solid transparent;
transition: border 0.3s; transition: border 0.3s;
} }
.includeWrap:hover, .includeWrap:hover,
.includeWrap[data-focused="true"], .includeWrap[data-focused="true"],
.includeWrap[data-menu-open="true"] { .includeWrap[data-menu-open="true"] {
border: 2px solid border: 1px solid
light-dark( light-dark(var(--mantine-color-gray-3), var(--mantine-color-gray-7));
var(--mantine-color-orange-2),
color-mix(in srgb, var(--mantine-color-orange-9), transparent 55%)
);
} }
.includeControls { .includeControls {
@@ -161,7 +159,7 @@
pointer-events: auto; pointer-events: auto;
} }
:global(.react-renderer.node-transclusionSource.ProseMirror-selectednode), :global(.react-renderer.node-transclusion.ProseMirror-selectednode),
:global(.react-renderer.node-transclusionReference.ProseMirror-selectednode) { :global(.react-renderer.node-transclusionReference.ProseMirror-selectednode) {
outline: none; outline: none;
} }
@@ -185,14 +183,6 @@
.includeControls { .includeControls {
display: none !important; display: none !important;
} }
.transclusionWrap,
.includeWrap {
border: none !important;
margin-left: 0 !important;
margin-right: 0 !important;
width: 100% !important;
padding: 0 !important;
}
} }
.editingOriginalTag { .editingOriginalTag {
@@ -47,7 +47,6 @@ export default function VideoView(props: NodeViewProps) {
preload="metadata" preload="metadata"
controls controls
src={getFileUrl(src)} src={getFileUrl(src)}
aria-label={placeholder?.name || t("Video")}
/> />
)} )}
{!src && previewSrc && ( {!src && previewSrc && (
@@ -57,7 +56,6 @@ export default function VideoView(props: NodeViewProps) {
preload="metadata" preload="metadata"
controls controls
src={previewSrc} src={previewSrc}
aria-label={placeholder?.name || t("Video")}
/> />
<Loader size={20} pos="absolute" top={6} right={6} /> <Loader size={20} pos="absolute" top={6} right={6} />
</Group> </Group>
@@ -73,7 +71,7 @@ export default function VideoView(props: NodeViewProps) {
</Group> </Group>
)} )}
{!src && !previewSrc && !placeholder && ( {!src && !previewSrc && !placeholder && (
<video className={classes.video} controls aria-label={t("Video")} /> <video className={classes.video} controls />
)} )}
</div> </div>
</NodeViewWrapper> </NodeViewWrapper>
@@ -396,7 +396,7 @@ const GlobalDragHandle = Extension.create({
addOptions() { addOptions() {
return { return {
dragHandleWidth: 20, dragHandleWidth: 20,
scrollThreshold: 100, scrollTreshold: 100,
excludedTags: [], excludedTags: [],
customNodes: [], customNodes: [],
}; };
@@ -51,7 +51,7 @@ import {
Columns, Columns,
Column, Column,
Status, Status,
TransclusionSource, Transclusion,
TransclusionReference, TransclusionReference,
} from "@docmost/editor-ext"; } from "@docmost/editor-ext";
import { import {
@@ -171,7 +171,7 @@ export const mainExtensions = [
SharedStorage, SharedStorage,
Heading, Heading,
UniqueID.configure({ UniqueID.configure({
types: ["heading", "paragraph", "transclusionSource"], types: ["heading", "paragraph", "transclusion"],
filterTransaction: (transaction) => !isChangeOrigin(transaction), filterTransaction: (transaction) => !isChangeOrigin(transaction),
}), }),
Placeholder.configure({ Placeholder.configure({
@@ -220,7 +220,7 @@ export const mainExtensions = [
Typography, Typography,
TrailingNode, TrailingNode,
GlobalDragHandle.configure({ GlobalDragHandle.configure({
customNodes: ["transclusionSource", "transclusionReference"], customNodes: ["transclusion", "transclusionReference"],
}), }),
TextStyle, TextStyle,
Color, Color,
@@ -357,7 +357,7 @@ export const mainExtensions = [
Status.configure({ Status.configure({
view: StatusView, view: StatusView,
}), }),
TransclusionSource.configure({ Transclusion.configure({
view: TransclusionView, view: TransclusionView,
}), }),
TransclusionReference.configure({ TransclusionReference.configure({
@@ -401,7 +401,7 @@ export default function PageEditor({
}, [yjsConnectionStatus, isSynced]); }, [yjsConnectionStatus, isSynced]);
return ( return (
<TransclusionLookupProvider> <TransclusionLookupProvider hostPageId={pageId}>
{showStatic ? ( {showStatic ? (
<EditorProvider <EditorProvider
editable={false} editable={false}
@@ -15,20 +15,12 @@ interface PageEditorProps {
title: string; title: string;
content: any; content: any;
pageId?: string; pageId?: string;
/**
* When rendering inside a public share, pass the share's id (or key). Lookups
* for transclusion content then resolve against the share graph instead of
* the viewer's personal permissions, so a share never leaks source content
* that isn't itself shared.
*/
shareId?: string;
} }
export default function ReadonlyPageEditor({ export default function ReadonlyPageEditor({
title, title,
content, content,
pageId, pageId,
shareId,
}: PageEditorProps) { }: PageEditorProps) {
const [, setReadOnlyEditor] = useAtom(readOnlyEditorAtom); const [, setReadOnlyEditor] = useAtom(readOnlyEditorAtom);
const isComponentMounted = useRef(false); const isComponentMounted = useRef(false);
@@ -74,7 +66,7 @@ export default function ReadonlyPageEditor({
]; ];
return ( return (
<TransclusionLookupProvider shareId={shareId}> <TransclusionLookupProvider hostPageId={pageId ?? "anonymous"}>
<div className="page-title"> <div className="page-title">
<EditorProvider <EditorProvider
editable={false} editable={false}
@@ -53,17 +53,15 @@ export default function StarButton(props: StarButtonProps) {
} }
}; };
const label = isFavorited
? t("Remove from favorites")
: t("Add to favorites");
return ( return (
<Tooltip label={label} openDelay={250} withArrow> <Tooltip
label={isFavorited ? t("Remove from favorites") : t("Add to favorites")}
openDelay={250}
withArrow
>
<ActionIcon <ActionIcon
variant="subtle" variant="subtle"
color={isFavorited ? "yellow" : "gray"} color={isFavorited ? "yellow" : "gray"}
aria-label={label}
aria-pressed={isFavorited}
onClick={handleToggle} onClick={handleToggle}
loading={isPending} loading={isPending}
> >
@@ -53,7 +53,7 @@ export default function GroupActionMenu() {
arrowPosition="center" arrowPosition="center"
> >
<Menu.Target> <Menu.Target>
<ActionIcon variant="light" aria-label={t("Group menu")}> <ActionIcon variant="light">
<IconDots size={20} stroke={2} /> <IconDots size={20} stroke={2} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -54,7 +54,7 @@ export default function GroupMembersList() {
<Table.Tr> <Table.Tr>
<Table.Th>{t("User")}</Table.Th> <Table.Th>{t("User")}</Table.Th>
<Table.Th>{t("Status")}</Table.Th> <Table.Th>{t("Status")}</Table.Th>
<Table.Th aria-label={t("Action")} /> <Table.Th></Table.Th>
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
@@ -4,7 +4,7 @@ import {
UnstyledButton, UnstyledButton,
Badge, Badge,
Table, Table,
ThemeIcon, ActionIcon,
Button, Button,
} from "@mantine/core"; } from "@mantine/core";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
@@ -61,13 +61,13 @@ export default function CreatedByMe({ spaceId }: Props) {
> >
<Group wrap="nowrap"> <Group wrap="nowrap">
{page.icon || ( {page.icon || (
<ThemeIcon <ActionIcon
variant="transparent" variant="transparent"
color="gray" color="gray"
size={18} size={18}
> >
<IconFileDescription size={18} /> <IconFileDescription size={18} />
</ThemeIcon> </ActionIcon>
)} )}
<Text fw={500} size="md" lineClamp={1}> <Text fw={500} size="md" lineClamp={1}>
{page.title || t("Untitled")} {page.title || t("Untitled")}
@@ -4,7 +4,7 @@ import {
UnstyledButton, UnstyledButton,
Badge, Badge,
Table, Table,
ThemeIcon, ActionIcon,
Button, Button,
} from "@mantine/core"; } from "@mantine/core";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
@@ -62,13 +62,13 @@ export default function FavoritesPages({ spaceId }: Props) {
> >
<Group wrap="nowrap"> <Group wrap="nowrap">
{fav.page.icon || ( {fav.page.icon || (
<ThemeIcon <ActionIcon
variant="transparent" variant="transparent"
color="gray" color="gray"
size={18} size={18}
> >
<IconFileDescription size={18} /> <IconFileDescription size={18} />
</ThemeIcon> </ActionIcon>
)} )}
<Text fw={500} size="md" lineClamp={1}> <Text fw={500} size="md" lineClamp={1}>
{fav.page.title || t("Untitled")} {fav.page.title || t("Untitled")}
@@ -16,7 +16,7 @@
.subtitle { .subtitle {
font-size: var(--mantine-font-size-sm); font-size: var(--mantine-font-size-sm);
color: var(--mantine-color-dimmed); color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
text-align: center; text-align: center;
margin-top: 6px; margin-top: 6px;
margin-bottom: var(--mantine-spacing-lg); margin-bottom: var(--mantine-spacing-lg);
@@ -58,9 +58,6 @@ export function NotificationPopover() {
variant="subtle" variant="subtle"
color="dark" color="dark"
size="sm" size="sm"
aria-label={t("Notifications")}
aria-haspopup="dialog"
aria-expanded={opened}
onClick={() => setOpened((o) => !o)} onClick={() => setOpened((o) => !o)}
> >
<Indicator <Indicator
@@ -22,7 +22,6 @@ export default function HistoryModal({ pageId, pageTitle }: Props) {
opened={isModalOpen} opened={isModalOpen}
onClose={() => setModalOpen(false)} onClose={() => setModalOpen(false)}
fullScreen fullScreen
aria-label={t("Page history")}
> >
<Modal.Overlay /> <Modal.Overlay />
<Modal.Content style={{ overflow: "hidden" }}> <Modal.Content style={{ overflow: "hidden" }}>
@@ -50,7 +49,6 @@ export default function HistoryModal({ pageId, pageTitle }: Props) {
size={1400} size={1400}
opened={isModalOpen} opened={isModalOpen}
onClose={() => setModalOpen(false)} onClose={() => setModalOpen(false)}
aria-label={t("Page history")}
> >
<Modal.Overlay /> <Modal.Overlay />
<Modal.Content style={{ overflow: "hidden" }}> <Modal.Content style={{ overflow: "hidden" }}>
@@ -19,7 +19,6 @@ import { buildPageUrl } from "@/features/page/page.utils.ts";
import { usePageQuery } from "@/features/page/queries/page-query.ts"; import { usePageQuery } from "@/features/page/queries/page-query.ts";
import { extractPageSlugId } from "@/lib"; import { extractPageSlugId } from "@/lib";
import { useMediaQuery } from "@mantine/hooks"; import { useMediaQuery } from "@mantine/hooks";
import { useTranslation } from "react-i18next";
function getTitle(name: string, icon: string) { function getTitle(name: string, icon: string) {
if (icon) { if (icon) {
@@ -29,7 +28,6 @@ function getTitle(name: string, icon: string) {
} }
export default function Breadcrumb() { export default function Breadcrumb() {
const { t } = useTranslation();
const treeData = useAtomValue(treeDataAtom); const treeData = useAtomValue(treeDataAtom);
const [breadcrumbNodes, setBreadcrumbNodes] = useState< const [breadcrumbNodes, setBreadcrumbNodes] = useState<
SpaceTreeNode[] | null SpaceTreeNode[] | null
@@ -82,7 +80,7 @@ export default function Breadcrumb() {
)); ));
const renderAnchor = useCallback( const renderAnchor = useCallback(
(node: SpaceTreeNode, isCurrent = false) => ( (node: SpaceTreeNode) => (
<Tooltip label={node.name} key={node.id}> <Tooltip label={node.name} key={node.id}>
<Anchor <Anchor
component={Link} component={Link}
@@ -91,7 +89,6 @@ export default function Breadcrumb() {
fz="sm" fz="sm"
key={node.id} key={node.id}
className={classes.truncatedText} className={classes.truncatedText}
aria-current={isCurrent ? "page" : undefined}
> >
{getTitle(node.name, node.icon)} {getTitle(node.name, node.icon)}
</Anchor> </Anchor>
@@ -118,11 +115,7 @@ export default function Breadcrumb() {
key="hidden-nodes" key="hidden-nodes"
> >
<Popover.Target> <Popover.Target>
<ActionIcon <ActionIcon color="gray" variant="transparent">
color="gray"
variant="transparent"
aria-label={t("Show hidden breadcrumbs")}
>
<IconDots size={20} stroke={2} /> <IconDots size={20} stroke={2} />
</ActionIcon> </ActionIcon>
</Popover.Target> </Popover.Target>
@@ -131,13 +124,11 @@ export default function Breadcrumb() {
</Popover.Dropdown> </Popover.Dropdown>
</Popover>, </Popover>,
//renderAnchor(secondLastNode), //renderAnchor(secondLastNode),
renderAnchor(lastNode, true), renderAnchor(lastNode),
]; ];
} }
return breadcrumbNodes.map((node, i) => return breadcrumbNodes.map(renderAnchor);
renderAnchor(node, i === breadcrumbNodes.length - 1),
);
}; };
const getMobileBreadcrumbItems = () => { const getMobileBreadcrumbItems = () => {
@@ -153,12 +144,8 @@ export default function Breadcrumb() {
key="mobile-hidden-nodes" key="mobile-hidden-nodes"
> >
<Popover.Target> <Popover.Target>
<Tooltip label={t("Breadcrumbs")}> <Tooltip label="Breadcrumbs">
<ActionIcon <ActionIcon color="gray" variant="transparent">
color="gray"
variant="transparent"
aria-label={t("Breadcrumbs")}
>
<IconCornerDownRightDouble size={20} stroke={2} /> <IconCornerDownRightDouble size={20} stroke={2} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
@@ -170,18 +157,16 @@ export default function Breadcrumb() {
]; ];
} }
return breadcrumbNodes.map((node, i) => return breadcrumbNodes.map(renderAnchor);
renderAnchor(node, i === breadcrumbNodes.length - 1),
);
}; };
return ( return (
<nav aria-label={t("Breadcrumb")} className={classes.breadcrumbDiv}> <div className={classes.breadcrumbDiv}>
{breadcrumbNodes && ( {breadcrumbNodes && (
<Breadcrumbs className={classes.breadcrumbs}> <Breadcrumbs className={classes.breadcrumbs}>
{isMobile ? getMobileBreadcrumbItems() : getBreadcrumbItems()} {isMobile ? getMobileBreadcrumbItems() : getBreadcrumbItems()}
</Breadcrumbs> </Breadcrumbs>
)} )}
</nav> </div>
); );
} }
@@ -1,4 +1,4 @@
import { ActionIcon, Group, Menu, Text, ThemeIcon, Tooltip } from "@mantine/core"; import { ActionIcon, Group, Menu, Text, Tooltip } from "@mantine/core";
import { import {
IconArrowRight, IconArrowRight,
IconArrowsHorizontal, IconArrowsHorizontal,
@@ -99,7 +99,6 @@ export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
<ActionIcon <ActionIcon
variant="subtle" variant="subtle"
color="dark" color="dark"
aria-label={t("Comments")}
onClick={() => toggleAside("comments")} onClick={() => toggleAside("comments")}
> >
<IconMessage size={20} stroke={2} /> <IconMessage size={20} stroke={2} />
@@ -110,7 +109,6 @@ export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
<ActionIcon <ActionIcon
variant="subtle" variant="subtle"
color="dark" color="dark"
aria-label={t("Table of contents")}
onClick={() => toggleAside("toc")} onClick={() => toggleAside("toc")}
> >
<IconList size={20} stroke={2} /> <IconList size={20} stroke={2} />
@@ -207,11 +205,7 @@ function PageActionMenu({ readOnly }: PageActionMenuProps) {
arrowPosition="center" arrowPosition="center"
> >
<Menu.Target> <Menu.Target>
<ActionIcon <ActionIcon variant="subtle" color="dark">
variant="subtle"
color="dark"
aria-label={t("Page actions")}
>
<IconDots size={20} /> <IconDots size={20} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -422,15 +416,9 @@ function ConnectionWarning() {
openDelay={250} openDelay={250}
withArrow withArrow
> >
<ThemeIcon <ActionIcon variant="default" c="red" style={{ border: "none" }}>
variant="default"
c="red"
role="status"
aria-label={t("Real-time editor connection lost. Retrying...")}
style={{ border: "none" }}
>
<IconWifiOff size={20} stroke={2} /> <IconWifiOff size={20} stroke={2} />
</ThemeIcon> </ActionIcon>
</Tooltip> </Tooltip>
); );
} }
@@ -67,7 +67,7 @@ export default function PageImportModal({
<Modal.Content style={{ overflow: "hidden" }}> <Modal.Content style={{ overflow: "hidden" }}>
<Modal.Header py={0}> <Modal.Header py={0}>
<Modal.Title fw={500}>{t("Import pages")}</Modal.Title> <Modal.Title fw={500}>{t("Import pages")}</Modal.Title>
<Modal.CloseButton aria-label={t("Close")} /> <Modal.CloseButton />
</Modal.Header> </Modal.Header>
<Modal.Body> <Modal.Body>
<ImportFormatSelection spaceId={spaceId} onClose={onClose} /> <ImportFormatSelection spaceId={spaceId} onClose={onClose} />
@@ -332,15 +332,7 @@ function ImportFormatSelection({ spaceId, onClose }: ImportFormatSelection) {
return ( return (
<> <>
<SimpleGrid cols={2}> <SimpleGrid cols={2}>
<FileButton <FileButton onChange={handleFileUpload} accept=".md" multiple resetRef={markdownFileRef}>
onChange={handleFileUpload}
accept=".md"
multiple
resetRef={markdownFileRef}
inputProps={{
"aria-label": t("Choose {{format}} file", { format: "Markdown" }),
}}
>
{(props) => ( {(props) => (
<Button <Button
justify="start" justify="start"
@@ -353,15 +345,7 @@ function ImportFormatSelection({ spaceId, onClose }: ImportFormatSelection) {
)} )}
</FileButton> </FileButton>
<FileButton <FileButton onChange={handleFileUpload} accept="text/html" multiple resetRef={htmlFileRef}>
onChange={handleFileUpload}
accept="text/html"
multiple
resetRef={htmlFileRef}
inputProps={{
"aria-label": t("Choose {{format}} file", { format: "HTML" }),
}}
>
{(props) => ( {(props) => (
<Button <Button
justify="start" justify="start"
@@ -379,9 +363,6 @@ function ImportFormatSelection({ spaceId, onClose }: ImportFormatSelection) {
accept=".docx" accept=".docx"
multiple multiple
resetRef={docxFileRef} resetRef={docxFileRef}
inputProps={{
"aria-label": t("Choose {{format}} file", { format: "Word (DOCX)" }),
}}
> >
{(props) => ( {(props) => (
<Tooltip <Tooltip
@@ -406,9 +387,6 @@ function ImportFormatSelection({ spaceId, onClose }: ImportFormatSelection) {
accept=".pdf" accept=".pdf"
multiple multiple
resetRef={pdfFileRef} resetRef={pdfFileRef}
inputProps={{
"aria-label": t("Choose {{format}} file", { format: "PDF" }),
}}
> >
{(props) => ( {(props) => (
<Tooltip <Tooltip
@@ -432,9 +410,6 @@ function ImportFormatSelection({ spaceId, onClose }: ImportFormatSelection) {
onChange={(file) => handleZipUpload(file, "notion")} onChange={(file) => handleZipUpload(file, "notion")}
accept="application/zip" accept="application/zip"
resetRef={notionFileRef} resetRef={notionFileRef}
inputProps={{
"aria-label": t("Choose {{format}} file", { format: "Notion" }),
}}
> >
{(props) => ( {(props) => (
<Button <Button
@@ -451,9 +426,6 @@ function ImportFormatSelection({ spaceId, onClose }: ImportFormatSelection) {
onChange={(file) => handleZipUpload(file, "confluence")} onChange={(file) => handleZipUpload(file, "confluence")}
accept="application/zip" accept="application/zip"
resetRef={confluenceFileRef} resetRef={confluenceFileRef}
inputProps={{
"aria-label": t("Choose {{format}} file", { format: "Confluence" }),
}}
> >
{(props) => ( {(props) => (
<Tooltip <Tooltip
@@ -491,9 +463,6 @@ function ImportFormatSelection({ spaceId, onClose }: ImportFormatSelection) {
onChange={(file) => handleZipUpload(file, "generic")} onChange={(file) => handleZipUpload(file, "generic")}
accept="application/zip" accept="application/zip"
resetRef={zipFileRef} resetRef={zipFileRef}
inputProps={{
"aria-label": t("Choose {{format}} file", { format: "ZIP" }),
}}
> >
{(props) => ( {(props) => (
<Group justify="center"> <Group justify="center">
@@ -19,7 +19,7 @@ export default function TrashPageContentModal({
const title = pageTitle || t("Untitled"); const title = pageTitle || t("Untitled");
return ( return (
<Modal.Root size={1200} opened={opened} onClose={onClose} aria-label={t("Preview")}> <Modal.Root size={1200} opened={opened} onClose={onClose}>
<Modal.Overlay /> <Modal.Overlay />
<Modal.Content style={{ overflow: "hidden" }}> <Modal.Content style={{ overflow: "hidden" }}>
<Modal.Header> <Modal.Header>
@@ -129,7 +129,7 @@ export default function Trash() {
<Table.Th style={{ whiteSpace: "nowrap" }}> <Table.Th style={{ whiteSpace: "nowrap" }}>
{t("Deleted at")} {t("Deleted at")}
</Table.Th> </Table.Th>
<Table.Th aria-label={t("Action")} /> <Table.Th></Table.Th>
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
@@ -458,8 +458,6 @@ interface CreateNodeProps {
} }
function CreateNode({ node, treeApi, onExpandTree }: CreateNodeProps) { function CreateNode({ node, treeApi, onExpandTree }: CreateNodeProps) {
const { t } = useTranslation();
function handleCreate() { function handleCreate() {
if (node.data.hasChildren && node.children.length === 0) { if (node.data.hasChildren && node.children.length === 0) {
node.toggle(); node.toggle();
@@ -477,7 +475,6 @@ function CreateNode({ node, treeApi, onExpandTree }: CreateNodeProps) {
<ActionIcon <ActionIcon
variant="transparent" variant="transparent"
c="gray" c="gray"
aria-label={t("Create page")}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@@ -594,7 +591,6 @@ function NodeMenu({ node, treeApi, spaceId }: NodeMenuProps) {
<ActionIcon <ActionIcon
variant="transparent" variant="transparent"
c="gray" c="gray"
aria-label={t("Page menu")}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@@ -729,8 +725,6 @@ interface PageArrowProps {
} }
function PageArrow({ node, onExpandTree }: PageArrowProps) { function PageArrow({ node, onExpandTree }: PageArrowProps) {
const { t } = useTranslation();
useEffect(() => { useEffect(() => {
if (node.isOpen) { if (node.isOpen) {
onExpandTree(); onExpandTree();
@@ -742,8 +736,6 @@ function PageArrow({ node, onExpandTree }: PageArrowProps) {
size={20} size={20}
variant="subtle" variant="subtle"
c="gray" c="gray"
aria-label={node.isOpen ? t("Collapse") : t("Expand")}
aria-expanded={node.isInternal ? node.isOpen : undefined}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@@ -47,7 +47,6 @@ export function SearchMobileControl({ onSearch }: SearchMobileControlProps) {
<ActionIcon <ActionIcon
variant="subtle" variant="subtle"
color="dark" color="dark"
aria-label={t("Search")}
onClick={onSearch} onClick={onSearch}
size="sm" size="sm"
> >
@@ -37,7 +37,7 @@ export default function SessionList() {
<Table.Tr> <Table.Tr>
<Table.Th>{t("Device Name")}</Table.Th> <Table.Th>{t("Device Name")}</Table.Th>
<Table.Th>{t("Last Active")}</Table.Th> <Table.Th>{t("Last Active")}</Table.Th>
<Table.Th aria-label={t("Action")} /> <Table.Th />
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
@@ -94,7 +94,7 @@ export default function SessionList() {
<Table.Tr> <Table.Tr>
<Table.Th>{t("Device Name")}</Table.Th> <Table.Th>{t("Device Name")}</Table.Th>
<Table.Th>{t("Last Active")}</Table.Th> <Table.Th>{t("Last Active")}</Table.Th>
{otherSessions.length > 0 && <Table.Th aria-label={t("Action")} />} {otherSessions.length > 0 && <Table.Th />}
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
@@ -75,7 +75,7 @@ export default function ShareActionMenu({ share }: Props) {
arrowPosition="center" arrowPosition="center"
> >
<Menu.Target> <Menu.Target>
<ActionIcon variant="subtle" c="gray" aria-label={t("More options")}> <ActionIcon variant="subtle" c="gray">
<IconDots size={20} stroke={2} /> <IconDots size={20} stroke={2} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -148,7 +148,6 @@ export default function ShareShell({
onClick={toggleTocMobile} onClick={toggleTocMobile}
hiddenFrom="sm" hiddenFrom="sm"
size="sm" size="sm"
aria-label={t("Table of contents")}
> >
<IconList size={20} stroke={2} /> <IconList size={20} stroke={2} />
</ActionIcon> </ActionIcon>
@@ -158,7 +157,6 @@ export default function ShareShell({
<ActionIcon <ActionIcon
variant="default" variant="default"
style={{ border: "none" }} style={{ border: "none" }}
aria-label={t("Table of contents")}
onClick={toggleToc} onClick={toggleToc}
visibleFrom="sm" visibleFrom="sm"
size="sm" size="sm"
@@ -143,7 +143,7 @@ export default function SpaceMembersList({
<Table.Tr> <Table.Tr>
<Table.Th>{t("Member")}</Table.Th> <Table.Th>{t("Member")}</Table.Th>
<Table.Th>{t("Role")}</Table.Th> <Table.Th>{t("Role")}</Table.Th>
<Table.Th aria-label={t("Action")} /> <Table.Th></Table.Th>
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
@@ -49,15 +49,15 @@ function WatchButton({ spaceId, watchedIds, size = 16 }: { spaceId: string; watc
} }
}; };
const label = isWatching ? t("Stop watching space") : t("Watch space");
return ( return (
<Tooltip label={label} openDelay={250} withArrow> <Tooltip
label={isWatching ? t("Stop watching space") : t("Watch space")}
openDelay={250}
withArrow
>
<ActionIcon <ActionIcon
variant="subtle" variant="subtle"
color={isWatching ? "blue" : "gray"} color={isWatching ? "blue" : "gray"}
aria-label={label}
aria-pressed={isWatching}
onClick={handleToggle} onClick={handleToggle}
loading={isPending} loading={isPending}
> >
@@ -111,7 +111,7 @@ export default function AllSpacesList({
<Table.Tr> <Table.Tr>
<Table.Th>{t("Space")}</Table.Th> <Table.Th>{t("Space")}</Table.Th>
<Table.Th>{t("Members")}</Table.Th> <Table.Th>{t("Members")}</Table.Th>
<Table.Th w={130} aria-label={t("Action")} /> <Table.Th w={130}></Table.Th>
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
@@ -168,11 +168,7 @@ export default function AllSpacesList({
<WatchButton spaceId={space.id} watchedIds={watchedIds} size={16} /> <WatchButton spaceId={space.id} watchedIds={watchedIds} size={16} />
<Menu position="bottom-end"> <Menu position="bottom-end">
<Menu.Target> <Menu.Target>
<ActionIcon <ActionIcon variant="subtle" color="gray">
variant="subtle"
color="gray"
aria-label={t("Space menu")}
>
<IconDots size={16} /> <IconDots size={16} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -11,14 +11,6 @@ export async function lookupTransclusion(params: {
return r.data; return r.data;
} }
export async function lookupTransclusionForShare(params: {
shareId: string;
references: Array<{ sourcePageId: string; transclusionId: string }>;
}): Promise<{ items: TransclusionLookup[] }> {
const r = await api.post("/shares/transclusion/lookup", params);
return r.data;
}
export async function listReferences(params: { export async function listReferences(params: {
sourcePageId: string; sourcePageId: string;
transclusionId: string; transclusionId: string;
@@ -83,11 +83,7 @@ export default function MemberActionMenu({ userId, deactivatedAt }: Props) {
arrowPosition="center" arrowPosition="center"
> >
<Menu.Target> <Menu.Target>
<ActionIcon <ActionIcon variant="subtle" c="gray">
variant="subtle"
c="gray"
aria-label={t("Member actions")}
>
<IconDots size={20} stroke={2} /> <IconDots size={20} stroke={2} />
</ActionIcon> </ActionIcon>
</Menu.Target> </Menu.Target>
@@ -34,7 +34,6 @@ export default function WorkspaceInvitesTable() {
<Table.Th>{t("Email")}</Table.Th> <Table.Th>{t("Email")}</Table.Th>
<Table.Th>{t("Role")}</Table.Th> <Table.Th>{t("Role")}</Table.Th>
<Table.Th>{t("Date")}</Table.Th> <Table.Th>{t("Date")}</Table.Th>
<Table.Th aria-label={t("Action")} />
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
@@ -61,7 +61,6 @@ export default function WorkspaceMembersTable() {
<Table.Th>{t("User")}</Table.Th> <Table.Th>{t("User")}</Table.Th>
<Table.Th>{t("Status")}</Table.Th> <Table.Th>{t("Status")}</Table.Th>
<Table.Th>{t("Role")}</Table.Th> <Table.Th>{t("Role")}</Table.Th>
<Table.Th aria-label={t("Action")} />
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
@@ -6,7 +6,7 @@ import {
Table, Table,
Container, Container,
Title, Title,
ThemeIcon, ActionIcon,
Button, Button,
} from "@mantine/core"; } from "@mantine/core";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
@@ -71,13 +71,13 @@ export default function FavoritesPage() {
> >
<Group wrap="nowrap"> <Group wrap="nowrap">
{fav.page.icon || ( {fav.page.icon || (
<ThemeIcon <ActionIcon
variant="transparent" variant="transparent"
color="gray" color="gray"
size={18} size={18}
> >
<IconFileDescription size={18} /> <IconFileDescription size={18} />
</ThemeIcon> </ActionIcon>
)} )}
<Text fw={500} size="md" lineClamp={1}> <Text fw={500} size="md" lineClamp={1}>
{fav.page.title || t("Untitled")} {fav.page.title || t("Untitled")}
@@ -65,7 +65,6 @@ export default function SharedPage() {
title={data.page.title} title={data.page.title}
content={data.page.content} content={data.page.content}
pageId={data.page.id} pageId={data.page.id}
shareId={data.share.id}
/> />
</Container> </Container>
+1 -1
View File
@@ -71,7 +71,7 @@ export const mantineCssResolver: CSSVariablesResolver = (theme) => ({
"--input-error-size": theme.fontSizes.sm, "--input-error-size": theme.fontSizes.sm,
}, },
light: { light: {
"--mantine-color-dimmed": "#4b5563", "--mantine-color-dimmed": "#6b7280",
"--mantine-color-dark-light-color": "#4e5359", "--mantine-color-dark-light-color": "#4e5359",
"--mantine-color-dark-light-hover": "var(--mantine-color-gray-light-hover)", "--mantine-color-dark-light-hover": "var(--mantine-color-gray-light-hover)",
}, },
+3 -1
View File
@@ -63,6 +63,8 @@
"@nestjs/throttler": "^6.5.0", "@nestjs/throttler": "^6.5.0",
"@nestjs/websockets": "^11.1.19", "@nestjs/websockets": "^11.1.19",
"@node-saml/passport-saml": "^5.1.0", "@node-saml/passport-saml": "^5.1.0",
"@react-email/components": "1.0.10",
"@react-email/render": "2.0.4",
"@socket.io/redis-adapter": "^8.3.0", "@socket.io/redis-adapter": "^8.3.0",
"ai": "^6.0.134", "ai": "^6.0.134",
"ai-sdk-ollama": "^3.8.1", "ai-sdk-ollama": "^3.8.1",
@@ -106,7 +108,6 @@
"postgres": "^3.4.8", "postgres": "^3.4.8",
"postmark": "^4.0.7", "postmark": "^4.0.7",
"react": "^18.3.1", "react": "^18.3.1",
"react-email": "6.0.8",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2", "rxjs": "^7.8.2",
"sanitize-filename": "1.6.3", "sanitize-filename": "1.6.3",
@@ -145,6 +146,7 @@
"jest": "^30.3.0", "jest": "^30.3.0",
"kysely-codegen": "^0.20.0", "kysely-codegen": "^0.20.0",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"react-email": "5.2.10",
"source-map-support": "^0.5.21", "source-map-support": "^0.5.21",
"supertest": "^7.2.2", "supertest": "^7.2.2",
"ts-jest": "^29.4.6", "ts-jest": "^29.4.6",
@@ -1,4 +1,10 @@
import { Logger, Module, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import {
Global,
Logger,
Module,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { AuthenticationExtension } from './extensions/authentication.extension'; import { AuthenticationExtension } from './extensions/authentication.extension';
import { PersistenceExtension } from './extensions/persistence.extension'; import { PersistenceExtension } from './extensions/persistence.extension';
import { CollaborationGateway } from './collaboration.gateway'; import { CollaborationGateway } from './collaboration.gateway';
@@ -13,9 +19,6 @@ import { CollaborationHandler } from './collaboration.handler';
import { CollabHistoryService } from './services/collab-history.service'; import { CollabHistoryService } from './services/collab-history.service';
import { WatcherModule } from '../core/watcher/watcher.module'; import { WatcherModule } from '../core/watcher/watcher.module';
import { TransclusionService } from '../core/page/transclusion/transclusion.service'; import { TransclusionService } from '../core/page/transclusion/transclusion.service';
import { TransclusionModule } from '../core/page/transclusion/transclusion.module';
import { StorageModule } from '../integrations/storage/storage.module';
import { EnvironmentModule } from '../integrations/environment/environment.module';
@Module({ @Module({
providers: [ providers: [
@@ -29,14 +32,7 @@ import { EnvironmentModule } from '../integrations/environment/environment.modul
TransclusionService, TransclusionService,
], ],
exports: [CollaborationGateway], exports: [CollaborationGateway],
imports: [ imports: [TokenModule, WatcherModule],
TokenModule,
WatcherModule,
StorageModule.forRootAsync({
imports: [EnvironmentModule],
}),
TransclusionModule,
],
}) })
export class CollaborationModule implements OnModuleInit, OnModuleDestroy { export class CollaborationModule implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(CollaborationModule.name); private readonly logger = new Logger(CollaborationModule.name);
@@ -40,7 +40,7 @@ import {
Status, Status,
addUniqueIdsToDoc, addUniqueIdsToDoc,
htmlToMarkdown, htmlToMarkdown,
TransclusionSource, Transclusion,
TransclusionReference, TransclusionReference,
} from '@docmost/editor-ext'; } from '@docmost/editor-ext';
import { generateText, getSchema, JSONContent } from '@tiptap/core'; import { generateText, getSchema, JSONContent } from '@tiptap/core';
@@ -103,7 +103,7 @@ export const tiptapExtensions = [
Columns, Columns,
Column, Column,
Status, Status,
TransclusionSource, Transclusion,
TransclusionReference, TransclusionReference,
] as any; ] as any;
@@ -165,7 +165,7 @@ export class PersistenceExtension implements Extension {
} }
if (page) { if (page) {
await this.syncTransclusion(pageId, page.workspaceId, tiptapJson); await this.syncTransclusion(pageId, tiptapJson);
} }
if (page) { if (page) {
@@ -250,31 +250,19 @@ export class PersistenceExtension implements Extension {
*/ */
private async syncTransclusion( private async syncTransclusion(
pageId: string, pageId: string,
workspaceId: string,
tiptapJson: unknown, tiptapJson: unknown,
): Promise<void> { ): Promise<void> {
try { try {
await this.transclusionService.syncPageTransclusions( await this.transclusionService.syncPageTransclusions(pageId, tiptapJson);
pageId,
workspaceId,
tiptapJson,
);
} catch (err) { } catch (err) {
this.logger.error( this.logger.error(`Failed to sync transclusions for page ${pageId}`, err);
{ err, pageId },
'Failed to sync transclusions for page',
);
} }
try { try {
await this.transclusionService.syncPageReferences( await this.transclusionService.syncPageReferences(pageId, tiptapJson);
pageId,
workspaceId,
tiptapJson,
);
} catch (err) { } catch (err) {
this.logger.error( this.logger.error(
{ err, pageId }, `Failed to sync transclusion references for page ${pageId}`,
'Failed to sync transclusion references for page', err,
); );
} }
} }
+3 -3
View File
@@ -62,14 +62,14 @@ function applyMarkToYFragment(
) { ) {
let pos = 0; let pos = 0;
const processItem = (item: any, parentNodeName?: string): boolean => { const processItem = (item: any): boolean => {
if (pos >= to) return false; if (pos >= to) return false;
if (item instanceof Y.XmlText) { if (item instanceof Y.XmlText) {
const textLength = item.length; const textLength = item.length;
const itemEnd = pos + textLength; const itemEnd = pos + textLength;
if (itemEnd > from && pos < to && parentNodeName !== 'codeBlock') { if (itemEnd > from && pos < to) {
const formatFrom = Math.max(0, from - pos); const formatFrom = Math.max(0, from - pos);
const formatTo = Math.min(textLength, to - pos); const formatTo = Math.min(textLength, to - pos);
const formatLength = formatTo - formatFrom; const formatLength = formatTo - formatFrom;
@@ -82,7 +82,7 @@ function applyMarkToYFragment(
} else if (item instanceof Y.XmlElement) { } else if (item instanceof Y.XmlElement) {
pos++; // Opening tag pos++; // Opening tag
for (let i = 0; i < item.length; i++) { for (let i = 0; i < item.length; i++) {
if (!processItem(item.get(i), item.nodeName)) return false; if (!processItem(item.get(i))) return false;
} }
pos++; // Closing tag pos++; // Closing tag
} }
@@ -1,13 +0,0 @@
const ATTACHMENT_NODE_TYPES = [
'attachment',
'image',
'video',
'audio',
'pdf',
'excalidraw',
'drawio',
];
export function isAttachmentNode(nodeType: string): boolean {
return ATTACHMENT_NODE_TYPES.includes(nodeType);
}
@@ -1,2 +1,2 @@
export * from './generateHTML'; export * from './generateHTML.js';
export * from './generateJSON'; export * from './generateJSON.js';
@@ -11,7 +11,6 @@ import {
INTERNAL_LINK_REGEX, INTERNAL_LINK_REGEX,
extractPageSlugId, extractPageSlugId,
} from '../../../integrations/export/utils'; } from '../../../integrations/export/utils';
import { isAttachmentNode } from './attachment-node-types';
export interface MentionNode { export interface MentionNode {
id: string; id: string;
@@ -123,7 +122,18 @@ export function getProsemirrorContent(content: any) {
); );
} }
export { isAttachmentNode }; export function isAttachmentNode(nodeType: string) {
const attachmentNodeTypes = [
'attachment',
'image',
'video',
'audio',
'pdf',
'excalidraw',
'drawio',
];
return attachmentNodeTypes.includes(nodeType);
}
export function getAttachmentIds(prosemirrorJson: any) { export function getAttachmentIds(prosemirrorJson: any) {
const doc = jsonToNode(prosemirrorJson); const doc = jsonToNode(prosemirrorJson);
@@ -677,11 +677,7 @@ export class PageService {
// pages never have prior rows so we can skip the diff and just bulk-insert. // pages never have prior rows so we can skip the diff and just bulk-insert.
try { try {
await this.transclusionService.insertTransclusionsForPages( await this.transclusionService.insertTransclusionsForPages(
insertablePages.map((p) => ({ insertablePages.map((p) => ({ id: p.id, content: p.content })),
id: p.id,
workspaceId: p.workspaceId,
content: p.content,
})),
); );
} catch (err) { } catch (err) {
this.logger.error( this.logger.error(
@@ -692,11 +688,7 @@ export class PageService {
try { try {
await this.transclusionService.insertReferencesForPages( await this.transclusionService.insertReferencesForPages(
insertablePages.map((p) => ({ insertablePages.map((p) => ({ id: p.id, content: p.content })),
id: p.id,
workspaceId: p.workspaceId,
content: p.content,
})),
); );
} catch (err) { } catch (err) {
this.logger.error( this.logger.error(
@@ -4,7 +4,6 @@ import {
IsArray, IsArray,
IsString, IsString,
IsUUID, IsUUID,
MaxLength,
ValidateNested, ValidateNested,
} from 'class-validator'; } from 'class-validator';
@@ -13,7 +12,6 @@ export class LookupReferenceDto {
sourcePageId!: string; sourcePageId!: string;
@IsString() @IsString()
@MaxLength(36)
transclusionId!: string; transclusionId!: string;
} }
@@ -17,13 +17,13 @@ describe('collectTransclusionsFromPmJson', () => {
expect(collectTransclusionsFromPmJson(doc)).toEqual([]); expect(collectTransclusionsFromPmJson(doc)).toEqual([]);
}); });
it('extracts a top-level transclusion with id and content', () => { it('extracts a top-level transclusion with id, name and content', () => {
const doc = { const doc = {
type: 'doc', type: 'doc',
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 'abc123' }, attrs: { id: 'abc123', name: 'Pricing' },
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Body' }] }], content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Body' }] }],
}, },
], ],
@@ -31,6 +31,7 @@ describe('collectTransclusionsFromPmJson', () => {
const got = collectTransclusionsFromPmJson(doc); const got = collectTransclusionsFromPmJson(doc);
expect(got).toHaveLength(1); expect(got).toHaveLength(1);
expect(got[0].transclusionId).toBe('abc123'); expect(got[0].transclusionId).toBe('abc123');
expect(got[0].name).toBe('Pricing');
expect(got[0].content).toEqual({ expect(got[0].content).toEqual({
type: 'doc', type: 'doc',
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Body' }] }], content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Body' }] }],
@@ -41,7 +42,7 @@ describe('collectTransclusionsFromPmJson', () => {
const doc = { const doc = {
type: 'doc', type: 'doc',
content: [ content: [
{ type: 'transclusionSource', attrs: {}, content: [{ type: 'paragraph' }] }, { type: 'transclusion', attrs: {}, content: [{ type: 'paragraph' }] },
], ],
}; };
expect(collectTransclusionsFromPmJson(doc)).toEqual([]); expect(collectTransclusionsFromPmJson(doc)).toEqual([]);
@@ -51,8 +52,8 @@ describe('collectTransclusionsFromPmJson', () => {
const doc = { const doc = {
type: 'doc', type: 'doc',
content: [ content: [
{ type: 'transclusionSource', attrs: { id: 'a' }, content: [{ type: 'paragraph' }] }, { type: 'transclusion', attrs: { id: 'a' }, content: [{ type: 'paragraph' }] },
{ type: 'transclusionSource', attrs: { id: 'b' }, content: [{ type: 'paragraph' }] }, { type: 'transclusion', attrs: { id: 'b', name: 'Two' }, content: [{ type: 'paragraph' }] },
], ],
}; };
const got = collectTransclusionsFromPmJson(doc); const got = collectTransclusionsFromPmJson(doc);
@@ -64,11 +65,11 @@ describe('collectTransclusionsFromPmJson', () => {
type: 'doc', type: 'doc',
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 'outer' }, attrs: { id: 'outer' },
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 'inner' }, attrs: { id: 'inner' },
content: [{ type: 'paragraph' }], content: [{ type: 'paragraph' }],
}, },
@@ -87,7 +88,7 @@ describe('collectTransclusionsFromPmJson', () => {
{ {
type: 'column', type: 'column',
content: [ content: [
{ type: 'transclusionSource', attrs: { id: 'inCol' }, content: [{ type: 'paragraph' }] }, { type: 'transclusion', attrs: { id: 'inCol' }, content: [{ type: 'paragraph' }] },
], ],
}, },
], ],
@@ -101,24 +102,13 @@ describe('collectTransclusionsFromPmJson', () => {
const doc = { const doc = {
type: 'doc', type: 'doc',
content: [ content: [
{ { type: 'transclusion', attrs: { id: 'dup', name: 'first' }, content: [{ type: 'paragraph' }] },
type: 'transclusionSource', { type: 'transclusion', attrs: { id: 'dup', name: 'second' }, content: [{ type: 'paragraph' }] },
attrs: { id: 'dup' },
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'first' }] }],
},
{
type: 'transclusionSource',
attrs: { id: 'dup' },
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'second' }] }],
},
], ],
}; };
const got = collectTransclusionsFromPmJson(doc); const got = collectTransclusionsFromPmJson(doc);
expect(got).toHaveLength(1); expect(got).toHaveLength(1);
expect(got[0].content).toEqual({ expect(got[0].name).toBe('second');
type: 'doc',
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'second' }] }],
});
}); });
}); });
@@ -149,7 +139,7 @@ describe('collectReferencesFromPmJson', () => {
], ],
}; };
expect(collectReferencesFromPmJson(doc)).toEqual([ expect(collectReferencesFromPmJson(doc)).toEqual([
{ sourcePageId: 'p1', transclusionId: 'e1' }, { containingTransclusionId: null, sourcePageId: 'p1', transclusionId: 'e1' },
]); ]);
}); });
@@ -190,17 +180,17 @@ describe('collectReferencesFromPmJson', () => {
], ],
}; };
expect(collectReferencesFromPmJson(doc)).toEqual([ expect(collectReferencesFromPmJson(doc)).toEqual([
{ sourcePageId: 'p1', transclusionId: 'e1' }, { containingTransclusionId: null, sourcePageId: 'p1', transclusionId: 'e1' },
{ sourcePageId: 'p2', transclusionId: 'e2' }, { containingTransclusionId: null, sourcePageId: 'p2', transclusionId: 'e2' },
]); ]);
}); });
it('does not recurse into a transclusion source (schema forbids references inside)', () => { it('also finds references nested inside a transclusion (source) node', () => {
const doc = { const doc = {
type: 'doc', type: 'doc',
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 'src1' }, attrs: { id: 'src1' },
content: [ content: [
{ {
@@ -211,10 +201,12 @@ describe('collectReferencesFromPmJson', () => {
}, },
], ],
}; };
expect(collectReferencesFromPmJson(doc)).toEqual([]); expect(collectReferencesFromPmJson(doc)).toEqual([
{ containingTransclusionId: 'src1', sourcePageId: 'p1', transclusionId: 'e1' },
]);
}); });
it('dedupes identical (sourcePageId, transclusionId) pairs', () => { it('dedupes identical (containingTransclusionId, sourcePageId, transclusionId) triples', () => {
const doc = { const doc = {
type: 'doc', type: 'doc',
content: [ content: [
@@ -233,8 +225,8 @@ describe('collectReferencesFromPmJson', () => {
], ],
}; };
expect(collectReferencesFromPmJson(doc)).toEqual([ expect(collectReferencesFromPmJson(doc)).toEqual([
{ sourcePageId: 'p1', transclusionId: 'e1' }, { containingTransclusionId: null, sourcePageId: 'p1', transclusionId: 'e1' },
{ sourcePageId: 'p2', transclusionId: 'e2' }, { containingTransclusionId: null, sourcePageId: 'p2', transclusionId: 'e2' },
]); ]);
}); });
}); });
@@ -25,10 +25,10 @@ describe('TransclusionController.lookup', () => {
controller = module.get(TransclusionController); controller = module.get(TransclusionController);
}); });
const user = { id: 'u1', workspaceId: 'w1' } as any; const user = { id: 'u1' } as any;
const ref = { sourcePageId: 'p1', transclusionId: 'e1' }; const ref = { sourcePageId: 'p1', transclusionId: 'e1' };
it('passes the references, viewer id and workspace id through to the service and returns its result', async () => { it('returns content when lookup succeeds', async () => {
service.lookup.mockResolvedValue({ service.lookup.mockResolvedValue({
items: [ items: [
{ {
@@ -43,6 +43,36 @@ describe('TransclusionController.lookup', () => {
const out = await controller.lookup({ references: [ref] } as any, user); const out = await controller.lookup({ references: [ref] } as any, user);
expect(out.items[0]).not.toHaveProperty('status'); expect(out.items[0]).not.toHaveProperty('status');
expect((out.items[0] as any).content).toEqual({ type: 'doc' }); expect((out.items[0] as any).content).toEqual({ type: 'doc' });
expect(service.lookup).toHaveBeenCalledWith([ref], 'u1', 'w1'); expect(service.lookup).toHaveBeenCalledWith([ref], 'u1');
});
it('returns no_access when service says no_access', async () => {
service.lookup.mockResolvedValue({
items: [
{
sourcePageId: 'p1',
transclusionId: 'e1',
status: 'no_access',
},
],
} as any);
const out = await controller.lookup({ references: [ref] } as any, user);
expect((out.items[0] as { status?: string }).status).toBe('no_access');
});
it('returns not_found when service says not_found', async () => {
service.lookup.mockResolvedValue({
items: [
{
sourcePageId: 'p1',
transclusionId: 'e1',
status: 'not_found',
},
],
} as any);
const out = await controller.lookup({ references: [ref] } as any, user);
expect((out.items[0] as { status?: string }).status).toBe('not_found');
}); });
}); });
@@ -1,12 +1,11 @@
import { Test } from '@nestjs/testing'; import { Test } from '@nestjs/testing';
import { TransclusionService } from '../transclusion.service'; import { TransclusionService } from '../transclusion.service';
import { PageTransclusionsRepo } from '@docmost/db/repos/page-transclusions/page-transclusions.repo'; import { PageTransclusionsRepo } from '@docmost/db/repos/page-transclusions/page-transclusions.repo';
import { PageTransclusionReferencesRepo } from '@docmost/db/repos/page-transclusions/page-transclusion-references.repo'; import { PageTransclusionReferencesRepo } from '@docmost/db/repos/page-transclusion-references/page-transclusion-references.repo';
import { PageRepo } from '@docmost/db/repos/page/page.repo'; import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo'; import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
import { AttachmentRepo } from '@docmost/db/repos/attachment/attachment.repo'; import { AttachmentRepo } from '@docmost/db/repos/attachment/attachment.repo';
import { StorageService } from '../../../../integrations/storage/storage.service'; import { StorageService } from '../../../../integrations/storage/storage.service';
import { PageAccessService } from '../../page-access/page-access.service';
describe('TransclusionService.syncPageTransclusions', () => { describe('TransclusionService.syncPageTransclusions', () => {
let service: TransclusionService; let service: TransclusionService;
@@ -28,7 +27,6 @@ describe('TransclusionService.syncPageTransclusions', () => {
{ provide: PagePermissionRepo, useValue: {} }, { provide: PagePermissionRepo, useValue: {} },
{ provide: AttachmentRepo, useValue: {} }, { provide: AttachmentRepo, useValue: {} },
{ provide: StorageService, useValue: {} }, { provide: StorageService, useValue: {} },
{ provide: PageAccessService, useValue: {} },
], ],
}).compile(); }).compile();
service = module.get(TransclusionService); service = module.get(TransclusionService);
@@ -36,7 +34,6 @@ describe('TransclusionService.syncPageTransclusions', () => {
}); });
const pageId = '00000000-0000-0000-0000-000000000001'; const pageId = '00000000-0000-0000-0000-000000000001';
const workspaceId = '00000000-0000-0000-0000-000000000099';
it('inserts new transclusions that did not exist before', async () => { it('inserts new transclusions that did not exist before', async () => {
repo.findByPageId.mockResolvedValue([]); repo.findByPageId.mockResolvedValue([]);
@@ -44,14 +41,14 @@ describe('TransclusionService.syncPageTransclusions', () => {
type: 'doc', type: 'doc',
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 'a' }, attrs: { id: 'a', name: 'Hello' },
content: [{ type: 'paragraph' }], content: [{ type: 'paragraph' }],
}, },
], ],
}; };
const result = await service.syncPageTransclusions(pageId, workspaceId, pm); const result = await service.syncPageTransclusions(pageId, pm);
expect(result).toEqual({ inserted: 1, updated: 0, deleted: 0 }); expect(result).toEqual({ inserted: 1, updated: 0, deleted: 0 });
expect(repo.insert).toHaveBeenCalledTimes(1); expect(repo.insert).toHaveBeenCalledTimes(1);
@@ -59,6 +56,7 @@ describe('TransclusionService.syncPageTransclusions', () => {
expect.objectContaining({ expect.objectContaining({
pageId, pageId,
transclusionId: 'a', transclusionId: 'a',
name: 'Hello',
}), }),
undefined, undefined,
); );
@@ -66,46 +64,43 @@ describe('TransclusionService.syncPageTransclusions', () => {
expect(repo.deleteByPageAndTransclusionIds).not.toHaveBeenCalled(); expect(repo.deleteByPageAndTransclusionIds).not.toHaveBeenCalled();
}); });
it('updates transclusions whose content changed', async () => { it('updates transclusions whose name or content changed', async () => {
repo.findByPageId.mockResolvedValue([ repo.findByPageId.mockResolvedValue([
{ {
id: 'row1', id: 'row1',
pageId, pageId,
transclusionId: 'a', transclusionId: 'a',
name: 'Old',
content: { type: 'doc', content: [{ type: 'paragraph' }] }, content: { type: 'doc', content: [{ type: 'paragraph' }] },
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
} as any, } as any,
]); ]);
const newContent = {
type: 'doc',
content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'X' }] },
],
};
const pm = { const pm = {
type: 'doc', type: 'doc',
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 'a' }, attrs: { id: 'a', name: 'New' },
content: newContent.content, content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'X' }] },
],
}, },
], ],
}; };
const result = await service.syncPageTransclusions(pageId, workspaceId, pm); const result = await service.syncPageTransclusions(pageId, pm);
expect(result).toEqual({ inserted: 0, updated: 1, deleted: 0 }); expect(result).toEqual({ inserted: 0, updated: 1, deleted: 0 });
expect(repo.update).toHaveBeenCalledWith( expect(repo.update).toHaveBeenCalledWith(
pageId, pageId,
'a', 'a',
expect.objectContaining({ content: newContent }), expect.objectContaining({ name: 'New' }),
undefined, undefined,
); );
}); });
it('skips update when content is unchanged', async () => { it('skips update when name and content are unchanged', async () => {
const sameContent = { const sameContent = {
type: 'doc', type: 'doc',
content: [{ type: 'paragraph' }], content: [{ type: 'paragraph' }],
@@ -115,6 +110,7 @@ describe('TransclusionService.syncPageTransclusions', () => {
id: 'row1', id: 'row1',
pageId, pageId,
transclusionId: 'a', transclusionId: 'a',
name: 'Same',
content: sameContent, content: sameContent,
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
@@ -124,14 +120,14 @@ describe('TransclusionService.syncPageTransclusions', () => {
type: 'doc', type: 'doc',
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 'a' }, attrs: { id: 'a', name: 'Same' },
content: sameContent.content, content: sameContent.content,
}, },
], ],
}; };
const result = await service.syncPageTransclusions(pageId, workspaceId, pm); const result = await service.syncPageTransclusions(pageId, pm);
expect(result).toEqual({ inserted: 0, updated: 0, deleted: 0 }); expect(result).toEqual({ inserted: 0, updated: 0, deleted: 0 });
expect(repo.update).not.toHaveBeenCalled(); expect(repo.update).not.toHaveBeenCalled();
@@ -143,6 +139,7 @@ describe('TransclusionService.syncPageTransclusions', () => {
id: 'r', id: 'r',
pageId, pageId,
transclusionId: 'gone', transclusionId: 'gone',
name: null,
content: { type: 'doc', content: [] }, content: { type: 'doc', content: [] },
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
@@ -150,7 +147,7 @@ describe('TransclusionService.syncPageTransclusions', () => {
]); ]);
const pm = { type: 'doc', content: [{ type: 'paragraph' }] }; const pm = { type: 'doc', content: [{ type: 'paragraph' }] };
const result = await service.syncPageTransclusions(pageId, workspaceId, pm); const result = await service.syncPageTransclusions(pageId, pm);
expect(result).toEqual({ inserted: 0, updated: 0, deleted: 1 }); expect(result).toEqual({ inserted: 0, updated: 0, deleted: 1 });
expect(repo.deleteByPageAndTransclusionIds).toHaveBeenCalledWith( expect(repo.deleteByPageAndTransclusionIds).toHaveBeenCalledWith(
@@ -162,12 +159,28 @@ describe('TransclusionService.syncPageTransclusions', () => {
it('handles empty doc → noop', async () => { it('handles empty doc → noop', async () => {
repo.findByPageId.mockResolvedValue([]); repo.findByPageId.mockResolvedValue([]);
const result = await service.syncPageTransclusions(pageId, workspaceId, null); const result = await service.syncPageTransclusions(pageId, null);
expect(result).toEqual({ inserted: 0, updated: 0, deleted: 0 }); expect(result).toEqual({ inserted: 0, updated: 0, deleted: 0 });
expect(repo.insert).not.toHaveBeenCalled(); expect(repo.insert).not.toHaveBeenCalled();
expect(repo.update).not.toHaveBeenCalled(); expect(repo.update).not.toHaveBeenCalled();
expect(repo.deleteByPageAndTransclusionIds).not.toHaveBeenCalled(); expect(repo.deleteByPageAndTransclusionIds).not.toHaveBeenCalled();
}); });
it('passes through the trx parameter to repo calls', async () => {
repo.findByPageId.mockResolvedValue([]);
const trx = { mock: 'trx' } as any;
const pm = {
type: 'doc',
content: [
{ type: 'transclusion', attrs: { id: 'a' }, content: [{ type: 'paragraph' }] },
],
};
await service.syncPageTransclusions(pageId, pm, trx);
expect(repo.findByPageId).toHaveBeenCalledWith(pageId, trx);
expect(repo.insert).toHaveBeenCalledWith(expect.anything(), trx);
});
}); });
describe('TransclusionService.syncPageReferences', () => { describe('TransclusionService.syncPageReferences', () => {
@@ -180,6 +193,8 @@ describe('TransclusionService.syncPageReferences', () => {
findByReferencePageId: jest.fn(), findByReferencePageId: jest.fn(),
insertMany: jest.fn(), insertMany: jest.fn(),
deleteByReferenceAndKeys: jest.fn(), deleteByReferenceAndKeys: jest.fn(),
findCyclicEdgesForSource: jest.fn().mockResolvedValue([]),
deleteByIds: jest.fn(),
}; };
const module = await Test.createTestingModule({ const module = await Test.createTestingModule({
providers: [ providers: [
@@ -190,7 +205,6 @@ describe('TransclusionService.syncPageReferences', () => {
{ provide: PagePermissionRepo, useValue: {} }, { provide: PagePermissionRepo, useValue: {} },
{ provide: AttachmentRepo, useValue: {} }, { provide: AttachmentRepo, useValue: {} },
{ provide: StorageService, useValue: {} }, { provide: StorageService, useValue: {} },
{ provide: PageAccessService, useValue: {} },
], ],
}).compile(); }).compile();
service = module.get(TransclusionService); service = module.get(TransclusionService);
@@ -198,7 +212,6 @@ describe('TransclusionService.syncPageReferences', () => {
}); });
const referencePageId = '00000000-0000-0000-0000-000000000001'; const referencePageId = '00000000-0000-0000-0000-000000000001';
const workspaceId = '00000000-0000-0000-0000-000000000099';
it('inserts new loose references, no deletes when none existed', async () => { it('inserts new loose references, no deletes when none existed', async () => {
refRepo.findByReferencePageId.mockResolvedValue([]); refRepo.findByReferencePageId.mockResolvedValue([]);
@@ -216,20 +229,20 @@ describe('TransclusionService.syncPageReferences', () => {
], ],
}; };
const result = await service.syncPageReferences(referencePageId, workspaceId, pm); const result = await service.syncPageReferences(referencePageId, pm);
expect(result).toEqual({ inserted: 2, deleted: 0 }); expect(result).toEqual({ inserted: 2, deleted: 0 });
expect(refRepo.insertMany).toHaveBeenCalledWith( expect(refRepo.insertMany).toHaveBeenCalledWith(
[ [
{ {
workspaceId,
referencePageId, referencePageId,
containingTransclusionId: null,
sourcePageId: 'p1', sourcePageId: 'p1',
transclusionId: 'e1', transclusionId: 'e1',
}, },
{ {
workspaceId,
referencePageId, referencePageId,
containingTransclusionId: null,
sourcePageId: 'p2', sourcePageId: 'p2',
transclusionId: 'e2', transclusionId: 'e2',
}, },
@@ -237,15 +250,17 @@ describe('TransclusionService.syncPageReferences', () => {
undefined, undefined,
); );
expect(refRepo.deleteByReferenceAndKeys).not.toHaveBeenCalled(); expect(refRepo.deleteByReferenceAndKeys).not.toHaveBeenCalled();
// Loose references never seed cycle detection.
expect(refRepo.findCyclicEdgesForSource).not.toHaveBeenCalled();
}); });
it('ignores references nested inside a source (schema-forbidden)', async () => { it('records the containing transclusion when references nest in a source', async () => {
refRepo.findByReferencePageId.mockResolvedValue([]); refRepo.findByReferencePageId.mockResolvedValue([]);
const pm = { const pm = {
type: 'doc', type: 'doc',
content: [ content: [
{ {
type: 'transclusionSource', type: 'transclusion',
attrs: { id: 's1' }, attrs: { id: 's1' },
content: [ content: [
{ {
@@ -257,10 +272,62 @@ describe('TransclusionService.syncPageReferences', () => {
], ],
}; };
const result = await service.syncPageReferences(referencePageId, workspaceId, pm); const result = await service.syncPageReferences(referencePageId, pm);
expect(result).toEqual({ inserted: 1, deleted: 0 });
expect(refRepo.insertMany).toHaveBeenCalledWith(
[
{
referencePageId,
containingTransclusionId: 's1',
sourcePageId: 'p2',
transclusionId: 'e2',
},
],
undefined,
);
expect(refRepo.findCyclicEdgesForSource).toHaveBeenCalledWith(
'p2',
'e2',
undefined,
);
});
it('deletes edges that close a cycle and excludes them from the inserted count', async () => {
refRepo.findByReferencePageId.mockResolvedValue([]);
refRepo.findCyclicEdgesForSource.mockResolvedValue([
{
id: 'closing-edge-id',
referencePageId,
containingTransclusionId: 's1',
sourcePageId: 'p2',
transclusionId: 'e2',
createdAt: new Date(),
} as any,
]);
const pm = {
type: 'doc',
content: [
{
type: 'transclusion',
attrs: { id: 's1' },
content: [
{
type: 'transclusionReference',
attrs: { sourcePageId: 'p2', transclusionId: 'e2' },
},
],
},
],
};
const result = await service.syncPageReferences(referencePageId, pm);
expect(result).toEqual({ inserted: 0, deleted: 0 }); expect(result).toEqual({ inserted: 0, deleted: 0 });
expect(refRepo.insertMany).not.toHaveBeenCalled(); expect(refRepo.deleteByIds).toHaveBeenCalledWith(
['closing-edge-id'],
undefined,
);
}); });
it('deletes references that no longer appear', async () => { it('deletes references that no longer appear', async () => {
@@ -268,6 +335,7 @@ describe('TransclusionService.syncPageReferences', () => {
{ {
id: 'r1', id: 'r1',
referencePageId, referencePageId,
containingTransclusionId: null,
sourcePageId: 'p1', sourcePageId: 'p1',
transclusionId: 'e1', transclusionId: 'e1',
createdAt: new Date(), createdAt: new Date(),
@@ -275,13 +343,14 @@ describe('TransclusionService.syncPageReferences', () => {
]); ]);
const pm = { type: 'doc', content: [{ type: 'paragraph' }] }; const pm = { type: 'doc', content: [{ type: 'paragraph' }] };
const result = await service.syncPageReferences(referencePageId, workspaceId, pm); const result = await service.syncPageReferences(referencePageId, pm);
expect(result).toEqual({ inserted: 0, deleted: 1 }); expect(result).toEqual({ inserted: 0, deleted: 1 });
expect(refRepo.deleteByReferenceAndKeys).toHaveBeenCalledWith( expect(refRepo.deleteByReferenceAndKeys).toHaveBeenCalledWith(
referencePageId, referencePageId,
[ [
{ {
containingTransclusionId: null,
sourcePageId: 'p1', sourcePageId: 'p1',
transclusionId: 'e1', transclusionId: 'e1',
}, },
@@ -296,6 +365,7 @@ describe('TransclusionService.syncPageReferences', () => {
{ {
id: 'r', id: 'r',
referencePageId, referencePageId,
containingTransclusionId: null,
sourcePageId: 'p1', sourcePageId: 'p1',
transclusionId: 'e1', transclusionId: 'e1',
createdAt: new Date(), createdAt: new Date(),
@@ -311,10 +381,32 @@ describe('TransclusionService.syncPageReferences', () => {
], ],
}; };
const result = await service.syncPageReferences(referencePageId, workspaceId, pm); const result = await service.syncPageReferences(referencePageId, pm);
expect(result).toEqual({ inserted: 0, deleted: 0 }); expect(result).toEqual({ inserted: 0, deleted: 0 });
expect(refRepo.insertMany).not.toHaveBeenCalled(); expect(refRepo.insertMany).not.toHaveBeenCalled();
expect(refRepo.deleteByReferenceAndKeys).not.toHaveBeenCalled(); expect(refRepo.deleteByReferenceAndKeys).not.toHaveBeenCalled();
}); });
it('passes through trx parameter to repo calls', async () => {
refRepo.findByReferencePageId.mockResolvedValue([]);
const trx = { mock: 'trx' } as any;
const pm = {
type: 'doc',
content: [
{
type: 'transclusionReference',
attrs: { sourcePageId: 'p1', transclusionId: 'e1' },
},
],
};
await service.syncPageReferences(referencePageId, pm, trx);
expect(refRepo.findByReferencePageId).toHaveBeenCalledWith(
referencePageId,
trx,
);
expect(refRepo.insertMany).toHaveBeenCalledWith(expect.anything(), trx);
});
}); });
@@ -24,8 +24,7 @@ export class TransclusionController {
async lookup(@Body() dto: LookupDto, @AuthUser() user: User) { async lookup(@Body() dto: LookupDto, @AuthUser() user: User) {
return this.transclusionService.lookup( return this.transclusionService.lookup(
dto.references, dto.references,
user.id, user?.id ?? null,
user.workspaceId,
); );
} }
@@ -39,7 +38,6 @@ export class TransclusionController {
sourcePageId: dto.sourcePageId, sourcePageId: dto.sourcePageId,
transclusionId: dto.transclusionId, transclusionId: dto.transclusionId,
viewerUserId: user.id, viewerUserId: user.id,
workspaceId: user.workspaceId,
}); });
} }
@@ -53,7 +51,7 @@ export class TransclusionController {
dto.referencePageId, dto.referencePageId,
dto.sourcePageId, dto.sourcePageId,
dto.transclusionId, dto.transclusionId,
user, user.id,
); );
} }
} }

Some files were not shown because too many files have changed in this diff Show More