Compare commits

...

4 Commits

Author SHA1 Message Date
Philip Okugbe 66a754c9eb Revert "fix: prevent browser tab fallback in editor (#2123)" (#2216)
This reverts commit 1d2486455f.
2026-05-19 14:07:07 +01:00
Philip Okugbe 6cf8101ab3 feat(ee): templates (#2215)
* feat(ee): templates
* fix tree
* fix
2026-05-19 02:41:52 +01:00
Philipinho 0d6538ab1a feat: iframe configuration 2026-05-18 22:02:31 +01:00
Philip Okugbe b7b99cb3b2 fix: code splitting and editor fixes (#2211)
* fix table

* fix code splitting

* fix: editor ready check

* fix codeblock/mermaid gap cursor

* fix callout
2026-05-15 02:46:54 +01:00
49 changed files with 1108 additions and 108 deletions
+7
View File
@@ -48,6 +48,13 @@ GOTENBERG_URL=
DISABLE_TELEMETRY=false DISABLE_TELEMETRY=false
# Allow other sites to embed Docmost in an iframe.
IFRAME_EMBED_ALLOWED=false
# Only used when IFRAME_EMBED_ALLOWED=true. When empty, any origin is allowed.
# Example: https://intranet.example.com,https://portal.example.com
IFRAME_ALLOWED_ORIGINS=
# Enable debug logging in production (default: false) # Enable debug logging in production (default: false)
DEBUG_MODE=false DEBUG_MODE=false
@@ -936,6 +936,35 @@
"Page actions": "Page actions", "Page actions": "Page actions",
"Pick emoji": "Pick emoji", "Pick emoji": "Pick emoji",
"Template menu": "Template menu", "Template menu": "Template menu",
"Use": "Use",
"Use template": "Use template",
"Preview template: {{title}}": "Preview template: {{title}}",
"Use a template": "Use a template",
"Search templates...": "Search templates...",
"Search spaces...": "Search spaces...",
"No templates found": "No templates found",
"No spaces found": "No spaces found",
"Browse all templates": "Browse all templates",
"This space": "This space",
"All templates": "All templates",
"Global": "Global",
"New template": "New template",
"Edit template": "Edit template",
"Are you sure you want to delete this template?": "Are you sure you want to delete this template?",
"Template scope updated": "Template scope updated",
"Choose which space this template belongs to": "Choose which space this template belongs to",
"Scope": "Scope",
"Select scope": "Select scope",
"Title": "Title",
"Saving...": "Saving...",
"Saved": "Saved",
"Save failed. Retry": "Save failed. Retry",
"By {{name}}": "By {{name}}",
"Updated {{time}}": "Updated {{time}}",
"Choose destination": "Choose destination",
"Search pages and spaces...": "Search pages and spaces...",
"No results found": "No results found",
"You don't have permission to create pages here": "You don't have permission to create pages here",
"Chat menu": "Chat menu", "Chat menu": "Chat menu",
"API key menu": "API key menu", "API key menu": "API key menu",
"Jump to comment selection": "Jump to comment selection", "Jump to comment selection": "Jump to comment selection",
@@ -38,6 +38,16 @@
color: light-dark(var(--mantine-color-black), var(--mantine-color-white)); color: light-dark(var(--mantine-color-black), var(--mantine-color-white));
} }
} }
&[data-disabled] {
cursor: not-allowed;
opacity: 0.5;
@mixin hover {
background-color: transparent;
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));
}
}
} }
.linkIcon { .linkIcon {
@@ -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, UnstyledButton, Tooltip } from "@mantine/core";
import { import {
IconHome, IconHome,
IconClock, IconClock,
@@ -7,6 +7,7 @@ import {
IconLayoutGrid, IconLayoutGrid,
IconSettings, IconSettings,
IconUserPlus, IconUserPlus,
IconTemplate,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { Link, useLocation } from "react-router-dom"; import { Link, useLocation } from "react-router-dom";
import classes from "./global-sidebar.module.css"; import classes from "./global-sidebar.module.css";
@@ -20,12 +21,9 @@ import { useDisclosure } from "@mantine/hooks";
import { WorkspaceInviteForm } from "@/features/workspace/components/members/components/workspace-invite-form"; import { WorkspaceInviteForm } from "@/features/workspace/components/members/components/workspace-invite-form";
import { CustomAvatar } from "@/components/ui/custom-avatar"; import { CustomAvatar } from "@/components/ui/custom-avatar";
import { AvatarIconType } from "@/features/attachments/types/attachment.types"; import { AvatarIconType } from "@/features/attachments/types/attachment.types";
import { useHasFeature } from "@/ee/hooks/use-feature";
const mainNavItems = [ import { Feature } from "@/ee/features";
{ label: "Home", icon: IconHome, path: "/home" }, import { useUpgradeLabel } from "@/ee/hooks/use-upgrade-label";
{ label: "Favorites", icon: IconStar, path: "/favorites" },
{ label: "Spaces", icon: IconLayoutGrid, path: "/spaces" },
];
export default function GlobalSidebar() { export default function GlobalSidebar() {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -33,6 +31,19 @@ export default function GlobalSidebar() {
const [active, setActive] = useState(location.pathname); const [active, setActive] = useState(location.pathname);
const [mobileSidebarOpened] = useAtom(mobileSidebarAtom); const [mobileSidebarOpened] = useAtom(mobileSidebarAtom);
const toggleMobileSidebar = useToggleSidebar(mobileSidebarAtom); const toggleMobileSidebar = useToggleSidebar(mobileSidebarAtom);
const hasTemplates = useHasFeature(Feature.TEMPLATES);
const upgradeLabel = useUpgradeLabel();
const mainNavItems = [
{ label: "Home", icon: IconHome, path: "/home" },
{ label: "Favorites", icon: IconStar, path: "/favorites" },
{ label: "Spaces", icon: IconLayoutGrid, path: "/spaces" },
{
label: "Templates",
icon: IconTemplate,
path: "/templates",
disabled: !hasTemplates,
},
];
const { data: favoriteSpacesData, isPending: isFavoritesPending } = useFavoritesQuery("space"); const { data: favoriteSpacesData, isPending: isFavoritesPending } = useFavoritesQuery("space");
const favoriteSpaces = favoriteSpacesData?.pages.flatMap((p) => p.items) ?? []; const favoriteSpaces = favoriteSpacesData?.pages.flatMap((p) => p.items) ?? [];
const sortedFavoriteSpaces = [...favoriteSpaces] const sortedFavoriteSpaces = [...favoriteSpaces]
@@ -58,18 +69,37 @@ export default function GlobalSidebar() {
<div className={classes.navbar}> <div className={classes.navbar}>
<ScrollArea w="100%" style={{ flex: 1 }}> <ScrollArea w="100%" style={{ flex: 1 }}>
<div className={classes.section}> <div className={classes.section}>
{mainNavItems.map((item) => ( {mainNavItems.map((item) =>
<Link item.disabled ? (
key={item.label} <Tooltip
className={classes.link} key={item.label}
data-active={active === item.path || undefined} label={upgradeLabel}
to={item.path} position="right"
onClick={handleNavClick} withArrow
> >
<item.icon className={classes.linkIcon} stroke={2} /> <UnstyledButton
<span>{t(item.label)}</span> className={classes.link}
</Link> data-disabled
))} aria-disabled="true"
tabIndex={-1}
>
<item.icon className={classes.linkIcon} stroke={2} />
<span>{t(item.label)}</span>
</UnstyledButton>
</Tooltip>
) : (
<Link
key={item.label}
className={classes.link}
data-active={active === item.path || undefined}
to={item.path}
onClick={handleNavClick}
>
<item.icon className={classes.linkIcon} stroke={2} />
<span>{t(item.label)}</span>
</Link>
),
)}
</div> </div>
<Divider my="xs" /> <Divider my="xs" />
@@ -16,6 +16,8 @@ export function DestinationPickerModal({
loading, loading,
excludePageId, excludePageId,
pageLimit, pageLimit,
initialSpaceId,
searchSpacesOnly,
}: DestinationPickerModalProps) { }: DestinationPickerModalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [selection, setSelection] = useState<DestinationSelection | null>(null); const [selection, setSelection] = useState<DestinationSelection | null>(null);
@@ -46,6 +48,8 @@ export function DestinationPickerModal({
onSelectionChange={setSelection} onSelectionChange={setSelection}
excludePageId={excludePageId} excludePageId={excludePageId}
pageLimit={pageLimit} pageLimit={pageLimit}
initialSpaceId={initialSpaceId}
searchSpacesOnly={searchSpacesOnly}
/> />
<Group justify="flex-end" mt="md"> <Group justify="flex-end" mt="md">
@@ -13,6 +13,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-0));
transition: background-color 150ms ease; transition: background-color 150ms ease;
user-select: none; user-select: none;
@@ -22,6 +23,11 @@
var(--mantine-color-dark-6) var(--mantine-color-dark-6)
); );
} }
&:focus-visible {
outline: 2px solid var(--mantine-primary-color-filled);
outline-offset: -2px;
}
} }
.selected { .selected {
@@ -57,7 +63,7 @@
border-radius: var(--mantine-radius-sm); border-radius: var(--mantine-radius-sm);
flex-shrink: 0; flex-shrink: 0;
transition: transform 150ms ease; transition: transform 150ms ease;
color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3)); color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
@mixin hover { @mixin hover {
background-color: light-dark( background-color: light-dark(
@@ -111,7 +117,7 @@
} }
.spaceName { .spaceName {
color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3)); color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
font-size: var(--mantine-font-size-xs); font-size: var(--mantine-font-size-xs);
flex-shrink: 0; flex-shrink: 0;
} }
@@ -1,7 +1,7 @@
import { useState, useCallback } from "react"; import { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { TextInput, ScrollArea, Loader } from "@mantine/core"; import { ActionIcon, TextInput, ScrollArea, Loader } from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks"; import { useDebouncedValue } from "@mantine/hooks";
import { IconSearch, IconFile } from "@tabler/icons-react"; import { IconSearch, IconFileDescription } from "@tabler/icons-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useGetSpacesQuery } from "@/features/space/queries/space-query"; import { useGetSpacesQuery } from "@/features/space/queries/space-query";
import { useSearchSuggestionsQuery } from "@/features/search/queries/search-query"; import { useSearchSuggestionsQuery } from "@/features/search/queries/search-query";
@@ -15,23 +15,29 @@ type DestinationPickerProps = {
onSelectionChange: (selection: DestinationSelection | null) => void; onSelectionChange: (selection: DestinationSelection | null) => void;
excludePageId?: string; excludePageId?: string;
pageLimit?: number; pageLimit?: number;
initialSpaceId?: string;
searchSpacesOnly?: boolean;
}; };
export function DestinationPicker({ export function DestinationPicker({
onSelectionChange, onSelectionChange,
excludePageId, excludePageId,
pageLimit = 15, pageLimit = 15,
initialSpaceId,
searchSpacesOnly,
}: DestinationPickerProps) { }: DestinationPickerProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [selection, setSelection] = useState<DestinationSelection | null>(null); const [selection, setSelection] = useState<DestinationSelection | null>(null);
const [debouncedQuery] = useDebouncedValue(searchQuery, 300); const [debouncedQuery] = useDebouncedValue(searchQuery, 300);
const viewportRef = useRef<HTMLDivElement>(null);
const { data: spacesData, isLoading: spacesLoading } = useGetSpacesQuery({ const { data: spacesData, isLoading: spacesLoading } = useGetSpacesQuery({
limit: 100, limit: 100,
}); });
const searchEnabled = debouncedQuery && debouncedQuery.length >= 2; const searchEnabled =
!searchSpacesOnly && debouncedQuery && debouncedQuery.length >= 2;
const { data: searchData, isLoading: searchLoading } = const { data: searchData, isLoading: searchLoading } =
useSearchSuggestionsQuery({ useSearchSuggestionsQuery({
@@ -42,6 +48,18 @@ export function DestinationPicker({
const isSearching = !!searchEnabled; const isSearching = !!searchEnabled;
const filteredSpaces = useMemo(() => {
const items = spacesData?.items ?? [];
if (!searchSpacesOnly || !debouncedQuery) return items;
const fold = (s: string) =>
s
.normalize("NFD")
.replace(/[̀-ͯ]/g, "")
.toLocaleLowerCase();
const term = fold(debouncedQuery);
return items.filter((s) => fold(s.name).includes(term));
}, [spacesData, searchSpacesOnly, debouncedQuery]);
const selectedId = const selectedId =
selection?.type === "space" ? selection.spaceId : selection?.pageId ?? null; selection?.type === "space" ? selection.spaceId : selection?.pageId ?? null;
@@ -87,18 +105,48 @@ export function DestinationPicker({
[updateSelection], [updateSelection],
); );
// Pre-select space when initialSpaceId is set and spaces have loaded.
// Only runs once: skip if user has already made a selection.
useEffect(() => {
if (!initialSpaceId || selection) return;
const match = spacesData?.items?.find((s) => s.id === initialSpaceId);
if (match) {
updateSelection({ type: "space", spaceId: match.id, space: match });
requestAnimationFrame(() => {
const el = viewportRef.current?.querySelector<HTMLElement>(
`[data-space-id="${match.id}"]`,
);
el?.scrollIntoView({ block: "nearest" });
});
}
}, [initialSpaceId, selection, spacesData, updateSelection]);
return ( return (
<> <>
<TextInput <TextInput
leftSection={<IconSearch size={16} />} leftSection={<IconSearch size={16} />}
placeholder={t("Search pages and spaces...")} placeholder={
searchSpacesOnly
? t("Search spaces...")
: t("Search pages and spaces...")
}
aria-label={
searchSpacesOnly
? t("Search spaces...")
: t("Search pages and spaces...")
}
variant="filled" variant="filled"
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.currentTarget.value)} onChange={(e) => setSearchQuery(e.currentTarget.value)}
className={classes.searchInput} className={classes.searchInput}
/> />
<ScrollArea h="50vh" offsetScrollbars className={classes.scrollArea}> <ScrollArea
h="50vh"
offsetScrollbars
className={classes.scrollArea}
viewportRef={viewportRef}
>
{isSearching ? ( {isSearching ? (
searchLoading ? ( searchLoading ? (
<div className={classes.emptyState}> <div className={classes.emptyState}>
@@ -111,16 +159,28 @@ export function DestinationPicker({
<div <div
key={page.id} key={page.id}
className={classes.searchResult} className={classes.searchResult}
role="button"
tabIndex={0}
onClick={() => handleSearchResultClick(page)} onClick={() => handleSearchResultClick(page)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleSearchResultClick(page);
}
}}
> >
<div className={classes.iconWrapper}> <div className={classes.iconWrapper}>
{page.icon ? ( {page.icon ? (
page.icon page.icon
) : ( ) : (
<IconFile <ActionIcon
size={16} component="div"
color="var(--mantine-color-gray-5)" variant="transparent"
/> c="gray"
size={22}
>
<IconFileDescription size={18} />
</ActionIcon>
)} )}
</div> </div>
<div className={classes.pageTitle}> <div className={classes.pageTitle}>
@@ -141,8 +201,14 @@ export function DestinationPicker({
<div className={classes.emptyState}> <div className={classes.emptyState}>
<Loader size="xs" /> <Loader size="xs" />
</div> </div>
) : filteredSpaces.length === 0 ? (
<div className={classes.emptyState}>
{searchSpacesOnly && debouncedQuery
? t("No spaces found")
: t("No results found")}
</div>
) : ( ) : (
spacesData?.items?.map((space) => ( filteredSpaces.map((space) => (
<SpaceRow <SpaceRow
key={space.id} key={space.id}
space={space} space={space}
@@ -20,4 +20,6 @@ export type DestinationPickerModalProps = {
loading?: boolean; loading?: boolean;
excludePageId?: string; excludePageId?: string;
pageLimit?: number; pageLimit?: number;
initialSpaceId?: string;
searchSpacesOnly?: boolean;
}; };
@@ -1,5 +1,6 @@
import { useState } from "react"; import { KeyboardEvent, useState } from "react";
import { IconChevronRight, IconFile } from "@tabler/icons-react"; import { ActionIcon } from "@mantine/core";
import { IconChevronRight, IconFileDescription } from "@tabler/icons-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { IPage } from "@/features/page/types/page.types"; import { IPage } from "@/features/page/types/page.types";
import { PageChildren } from "./page-children"; import { PageChildren } from "./page-children";
@@ -36,23 +37,44 @@ export function PageRow({
.filter(Boolean) .filter(Boolean)
.join(" "); .join(" ");
const handleSelect = () => {
if (!isExcluded) onSelect(page);
};
const handleRowKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleSelect();
}
};
return ( return (
<> <>
<div <div
className={rowClasses} className={rowClasses}
style={{ paddingLeft: depth * 20 + 12 }} style={{ paddingLeft: depth * 20 + 12 }}
onClick={() => !isExcluded && onSelect(page)} role="button"
tabIndex={isExcluded ? -1 : 0}
aria-disabled={isExcluded || undefined}
onClick={handleSelect}
onKeyDown={handleRowKeyDown}
> >
{page.hasChildren ? ( {page.hasChildren ? (
<div <ActionIcon
className={`${classes.chevron} ${expanded ? classes.chevronExpanded : ""}`} className={`${classes.chevron} ${expanded ? classes.chevronExpanded : ""}`}
variant="subtle"
color="gray"
size="sm"
aria-label={expanded ? t("Collapse") : t("Expand")}
aria-expanded={expanded}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
setExpanded(!expanded); setExpanded(!expanded);
}} }}
> >
<IconChevronRight size={14} /> <IconChevronRight size={14} />
</div> </ActionIcon>
) : ( ) : (
<div style={{ width: 20, flexShrink: 0 }} /> <div style={{ width: 20, flexShrink: 0 }} />
)} )}
@@ -61,10 +83,14 @@ export function PageRow({
{page.icon ? ( {page.icon ? (
page.icon page.icon
) : ( ) : (
<IconFile <ActionIcon
size={16} component="div"
color="var(--mantine-color-gray-5)" variant="transparent"
/> c="gray"
size={22}
>
<IconFileDescription size={18} />
</ActionIcon>
)} )}
</div> </div>
@@ -1,5 +1,5 @@
import { useState } from "react"; import { KeyboardEvent, useState } from "react";
import { Tooltip } from "@mantine/core"; import { ActionIcon, Tooltip } from "@mantine/core";
import { IconChevronRight, IconLock } from "@tabler/icons-react"; import { IconChevronRight, IconLock } from "@tabler/icons-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ISpace } from "@/features/space/types/space.types"; import { ISpace } from "@/features/space/types/space.types";
@@ -42,21 +42,43 @@ export function SpaceRow({
.filter(Boolean) .filter(Boolean)
.join(" "); .join(" ");
const handleSelect = () => {
if (writable) onSelectSpace(space);
};
const handleRowKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleSelect();
}
};
const rowContent = ( const rowContent = (
<div <div
className={rowClasses} className={rowClasses}
onClick={() => writable && onSelectSpace(space)} data-space-id={space.id}
role="button"
tabIndex={writable ? 0 : -1}
aria-disabled={!writable || undefined}
onClick={handleSelect}
onKeyDown={handleRowKeyDown}
> >
{writable ? ( {writable ? (
<div <ActionIcon
className={`${classes.chevron} ${expanded ? classes.chevronExpanded : ""}`} className={`${classes.chevron} ${expanded ? classes.chevronExpanded : ""}`}
variant="subtle"
color="gray"
size="sm"
aria-label={expanded ? t("Collapse") : t("Expand")}
aria-expanded={expanded}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
setExpanded(!expanded); setExpanded(!expanded);
}} }}
> >
<IconChevronRight size={14} /> <IconChevronRight size={14} />
</div> </ActionIcon>
) : ( ) : (
<div style={{ width: 20, flexShrink: 0 }} /> <div style={{ width: 20, flexShrink: 0 }} />
)} )}
@@ -34,7 +34,7 @@ function AllowMemberTemplatesToggle() {
const [checked, setChecked] = useState( const [checked, setChecked] = useState(
workspace?.settings?.templates?.allowMemberTemplates === true, workspace?.settings?.templates?.allowMemberTemplates === true,
); );
const hasSecuritySettings = useHasFeature(Feature.SECURITY_SETTINGS); const hasTemplates = useHasFeature(Feature.TEMPLATES);
const upgradeLabel = useUpgradeLabel(); const upgradeLabel = useUpgradeLabel();
const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => { const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
@@ -54,15 +54,11 @@ function AllowMemberTemplatesToggle() {
}; };
return ( return (
<Tooltip <Tooltip label={upgradeLabel} disabled={hasTemplates} refProp="rootRef">
label={upgradeLabel}
disabled={hasSecuritySettings}
refProp="rootRef"
>
<Switch <Switch
checked={checked} checked={checked}
onChange={handleChange} onChange={handleChange}
disabled={!hasSecuritySettings} disabled={!hasTemplates}
aria-label={t("Toggle allow members to create templates")} aria-label={t("Toggle allow members to create templates")}
/> />
</Tooltip> </Tooltip>
@@ -137,7 +137,6 @@ export default function Security() {
{ max: SCIM_TOKEN_LIMIT }, { max: SCIM_TOKEN_LIMIT },
)} )}
disabled={(scimData?.items.length ?? 0) < SCIM_TOKEN_LIMIT} disabled={(scimData?.items.length ?? 0) < SCIM_TOKEN_LIMIT}
refProp="rootRef"
> >
<Button <Button
onClick={() => setCreateOpen(true)} onClick={() => setCreateOpen(true)}
@@ -8,6 +8,11 @@
@mixin hover { @mixin hover {
transform: scale(1.02); transform: scale(1.02);
} }
&:focus-visible {
outline: 2px solid var(--mantine-primary-color-filled);
outline-offset: 2px;
}
} }
.cardBody { .cardBody {
@@ -50,18 +55,27 @@
.footer { .footer {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; gap: 6px;
gap: var(--mantine-spacing-xs);
padding-top: var(--mantine-spacing-sm); padding-top: var(--mantine-spacing-sm);
margin-top: var(--mantine-spacing-lg); margin-top: var(--mantine-spacing-lg);
border-top: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-5)); border-top: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-5));
} }
.scopeDot {
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
flex-shrink: 0;
background-color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));
}
.menuTarget { .menuTarget {
opacity: 0; opacity: 0;
transition: opacity 100ms ease; transition: opacity 100ms ease;
.card:hover & { .card:hover &,
.card:focus-within & {
opacity: 1; opacity: 1;
} }
} }
@@ -1,4 +1,4 @@
import { Card, Text, ActionIcon, Menu, Group } from "@mantine/core"; import { Button, Card, Text, ActionIcon, Menu, Group } from "@mantine/core";
import { import {
IconDots, IconDots,
IconEdit, IconEdit,
@@ -12,6 +12,7 @@ import classes from "./template-card.module.css";
type TemplateCardProps = { type TemplateCardProps = {
template: ITemplate; template: ITemplate;
spaceName?: string; spaceName?: string;
onPreview: (template: ITemplate) => void;
onUse: (template: ITemplate) => void; onUse: (template: ITemplate) => void;
onEdit?: (template: ITemplate) => void; onEdit?: (template: ITemplate) => void;
onDelete?: (template: ITemplate) => void; onDelete?: (template: ITemplate) => void;
@@ -21,6 +22,7 @@ type TemplateCardProps = {
export default function TemplateCard({ export default function TemplateCard({
template, template,
spaceName, spaceName,
onPreview,
onUse, onUse,
onEdit, onEdit,
onDelete, onDelete,
@@ -34,7 +36,17 @@ export default function TemplateCard({
padding="lg" padding="lg"
className={classes.card} className={classes.card}
style={{ cursor: "pointer" }} style={{ cursor: "pointer" }}
onClick={() => onUse(template)} role="button"
tabIndex={0}
aria-label={t("Preview template: {{title}}", { title: template.title })}
onClick={() => onPreview(template)}
onKeyDown={(e) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onPreview(template);
}
}}
> >
<div className={classes.cardBody}> <div className={classes.cardBody}>
<Group justify="space-between" align="flex-start" wrap="nowrap" mb="md"> <Group justify="space-between" align="flex-start" wrap="nowrap" mb="md">
@@ -47,6 +59,17 @@ export default function TemplateCard({
)} )}
<Group gap={6} wrap="nowrap"> <Group gap={6} wrap="nowrap">
<Button
size="compact-xs"
variant="filled"
className={classes.menuTarget}
onClick={(e) => {
e.stopPropagation();
onUse(template);
}}
>
{t("Use")}
</Button>
{canManage && ( {canManage && (
<Menu width={150} shadow="md" withArrow> <Menu width={150} shadow="md" withArrow>
<Menu.Target> <Menu.Target>
@@ -91,6 +114,7 @@ export default function TemplateCard({
<div className={classes.title}>{template.title}</div> <div className={classes.title}>{template.title}</div>
<div className={classes.footer}> <div className={classes.footer}>
<span className={classes.scopeDot} aria-hidden="true" />
<Text size="sm" fw={500} c="dimmed"> <Text size="sm" fw={500} c="dimmed">
{template.spaceId ? (spaceName || t("Space")) : t("Global")} {template.spaceId ? (spaceName || t("Space")) : t("Global")}
</Text> </Text>
@@ -0,0 +1,70 @@
.row {
position: relative;
display: flex;
align-items: center;
gap: var(--mantine-spacing-sm);
padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);
border-radius: var(--mantine-radius-sm);
width: 100%;
@mixin hover {
background-color: light-dark(
var(--mantine-color-gray-1),
var(--mantine-color-dark-6)
);
}
}
.icon {
width: 22px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
font-size: 16px;
line-height: 1;
}
.title {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--mantine-font-size-sm);
text-align: left;
}
.scope {
color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));
font-size: var(--mantine-font-size-xs);
flex-shrink: 0;
transition: opacity 100ms ease;
.row:hover &,
.row:focus-within & {
opacity: 0;
}
}
.useButton {
position: absolute;
top: 50%;
right: var(--mantine-spacing-sm);
transform: translateY(-50%);
opacity: 0;
transition: opacity 100ms ease;
.row:hover &,
.row:focus-within &,
&:focus-visible {
opacity: 1;
}
}
.empty {
display: flex;
align-items: center;
justify-content: center;
padding: var(--mantine-spacing-xl);
}
@@ -0,0 +1,259 @@
import { useMemo, useState } from "react";
import {
Button,
Modal,
TextInput,
ScrollArea,
Loader,
Text,
UnstyledButton,
Group,
SegmentedControl,
} from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks";
import {
IconArrowRight,
IconSearch,
IconFileText,
} from "@tabler/icons-react";
import { Link, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
useGetTemplatesQuery,
useUseTemplateMutation,
} from "@/ee/template/queries/template-query";
import { useGetSpacesQuery } from "@/features/space/queries/space-query";
import { ITemplate } from "@/ee/template/types/template.types";
import UseTemplateModal from "@/ee/template/components/use-template-modal";
import TemplatePreviewModal from "@/ee/template/components/template-preview-modal";
import { buildPageUrl } from "@/features/page/page.utils";
import classes from "./template-picker-modal.module.css";
type TemplatePickerModalProps = {
opened: boolean;
onClose: () => void;
/** Pre-select this space in the destination picker after a template is chosen. */
initialSpaceId?: string;
};
type ScopeFilter = "current" | "all";
export default function TemplatePickerModal({
opened,
onClose,
initialSpaceId,
}: TemplatePickerModalProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const useTemplateMutation = useUseTemplateMutation();
const [query, setQuery] = useState("");
const [debouncedQuery] = useDebouncedValue(query, 200);
const [scope, setScope] = useState<ScopeFilter>(
initialSpaceId ? "current" : "all",
);
// Two-stage selection: previewing first, then destination-picker.
// `previewTemplate` is set when the user clicks a row in the picker.
// `destinationTemplate` is set when they click "Use template" in the preview.
const [previewTemplate, setPreviewTemplate] = useState<ITemplate | null>(
null,
);
const [destinationTemplate, setDestinationTemplate] =
useState<ITemplate | null>(null);
const { data, isPending } = useGetTemplatesQuery({
spaceId: scope === "current" ? initialSpaceId : undefined,
});
const { data: spacesData } = useGetSpacesQuery({ limit: 100 });
const spaceNamesById = useMemo(() => {
const map = new Map<string, string>();
spacesData?.items?.forEach((s) => map.set(s.id, s.name));
return map;
}, [spacesData]);
const filtered = useMemo(() => {
const all = data?.pages.flatMap((p) => p.items) ?? [];
const term = debouncedQuery.trim().toLowerCase();
if (!term) return all;
return all.filter((tpl) => tpl.title.toLowerCase().includes(term));
}, [data, debouncedQuery]);
const createInInitialSpace = async (tpl: ITemplate) => {
if (!initialSpaceId) return;
try {
const page = await useTemplateMutation.mutateAsync({
templateId: tpl.id,
spaceId: initialSpaceId,
});
setPreviewTemplate(null);
onClose();
const space = spacesData?.items?.find((s) => s.id === initialSpaceId);
if (page?.slugId && space?.slug) {
navigate(buildPageUrl(space.slug, page.slugId, page.title));
}
} catch {
// error notification handled by mutation's onError
}
};
const handlePick = (tpl: ITemplate) => {
setPreviewTemplate(tpl);
};
const handleQuickUse = (tpl: ITemplate) => {
if (initialSpaceId) {
createInInitialSpace(tpl);
return;
}
setDestinationTemplate(tpl);
};
const handlePreviewClose = () => {
// Closing preview returns to the picker list (no full unmount).
setPreviewTemplate(null);
};
const handlePreviewUse = () => {
if (initialSpaceId && previewTemplate) {
createInInitialSpace(previewTemplate);
return;
}
// Move from preview into destination-picker stage.
setDestinationTemplate(previewTemplate);
setPreviewTemplate(null);
};
const handleDestinationClose = () => {
setDestinationTemplate(null);
onClose();
};
const handleClose = () => {
setQuery("");
setScope(initialSpaceId ? "current" : "all");
setPreviewTemplate(null);
setDestinationTemplate(null);
onClose();
};
return (
<>
<Modal
opened={opened && !previewTemplate && !destinationTemplate}
onClose={handleClose}
size={550}
padding="lg"
yOffset="10vh"
title={<Text fw={500}>{t("Use a template")}</Text>}
>
<TextInput
leftSection={<IconSearch size={16} />}
placeholder={t("Search templates...")}
variant="filled"
value={query}
onChange={(e) => setQuery(e.currentTarget.value)}
mb="xs"
autoFocus
/>
{initialSpaceId && (
<SegmentedControl
fullWidth
size="xs"
mb="sm"
value={scope}
onChange={(v) => setScope(v as ScopeFilter)}
data={[
{ label: t("This space"), value: "current" },
{ label: t("All templates"), value: "all" },
]}
/>
)}
<ScrollArea h="50vh" offsetScrollbars>
{isPending ? (
<div className={classes.empty}>
<Loader size="xs" />
</div>
) : filtered.length === 0 ? (
<div className={classes.empty}>
<Text size="sm" c="dimmed">
{t("No templates found")}
</Text>
</div>
) : (
filtered.map((tpl) => (
<UnstyledButton
key={tpl.id}
className={classes.row}
onClick={() => handlePick(tpl)}
>
<div className={classes.icon}>
{tpl.icon ? (
<span>{tpl.icon}</span>
) : (
<IconFileText
size={16}
color="var(--mantine-color-gray-6)"
/>
)}
</div>
<div className={classes.title}>{tpl.title}</div>
<div className={classes.scope}>
{tpl.spaceId
? spaceNamesById.get(tpl.spaceId) ?? t("Space")
: t("Global")}
</div>
<Button
size="compact-xs"
variant="filled"
className={classes.useButton}
loading={useTemplateMutation.isPending}
disabled={useTemplateMutation.isPending}
onClick={(e) => {
e.stopPropagation();
handleQuickUse(tpl);
}}
>
{t("Use")}
</Button>
</UnstyledButton>
))
)}
</ScrollArea>
<Group justify="flex-end" mt="md">
<Button
component={Link}
to="/templates"
variant="subtle"
size="sm"
rightSection={<IconArrowRight size={16} />}
onClick={handleClose}
>
{t("Browse all templates")}
</Button>
</Group>
</Modal>
{previewTemplate && (
<TemplatePreviewModal
templateId={previewTemplate.id}
opened={true}
onClose={handlePreviewClose}
onUse={handlePreviewUse}
useLoading={useTemplateMutation.isPending}
/>
)}
{destinationTemplate && (
<UseTemplateModal
template={destinationTemplate}
opened={true}
onClose={handleDestinationClose}
initialSpaceId={initialSpaceId}
/>
)}
</>
);
}
@@ -9,6 +9,7 @@ type TemplatePreviewModalProps = {
onClose: () => void; onClose: () => void;
onUse: () => void; onUse: () => void;
onEdit?: () => void; onEdit?: () => void;
useLoading?: boolean;
}; };
export default function TemplatePreviewModal({ export default function TemplatePreviewModal({
@@ -17,6 +18,7 @@ export default function TemplatePreviewModal({
onClose, onClose,
onUse, onUse,
onEdit, onEdit,
useLoading,
}: TemplatePreviewModalProps) { }: TemplatePreviewModalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: template, isLoading } = useGetTemplateByIdQuery(templateId); const { data: template, isLoading } = useGetTemplateByIdQuery(templateId);
@@ -37,14 +39,19 @@ export default function TemplatePreviewModal({
</Group> </Group>
</Modal.Title> </Modal.Title>
<Group gap="sm"> <Group gap="sm">
<Button
size="xs"
onClick={onUse}
loading={useLoading}
disabled={useLoading}
>
{t("Use template")}
</Button>
{onEdit && ( {onEdit && (
<Button size="xs" variant="default" onClick={onEdit}> <Button size="xs" variant="default" onClick={onEdit}>
{t("Edit")} {t("Edit")}
</Button> </Button>
)} )}
<Button size="xs" onClick={onUse}>
{t("Use template")}
</Button>
<Modal.CloseButton /> <Modal.CloseButton />
</Group> </Group>
</Modal.Header> </Modal.Header>
@@ -10,12 +10,14 @@ type UseTemplateModalProps = {
template: ITemplate; template: ITemplate;
opened: boolean; opened: boolean;
onClose: () => void; onClose: () => void;
initialSpaceId?: string;
}; };
export default function UseTemplateModal({ export default function UseTemplateModal({
template, template,
opened, opened,
onClose, onClose,
initialSpaceId,
}: UseTemplateModalProps) { }: UseTemplateModalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -54,6 +56,8 @@ export default function UseTemplateModal({
actionLabel={t("Create page")} actionLabel={t("Create page")}
onSelect={handleSelect} onSelect={handleSelect}
loading={useTemplateMutation.isPending} loading={useTemplateMutation.isPending}
initialSpaceId={initialSpaceId ?? template.spaceId}
searchSpacesOnly
/> />
); );
} }
@@ -75,6 +75,18 @@ export default function TemplateEditor() {
const editor = useEditor({ const editor = useEditor({
extensions: templateExtensions, extensions: templateExtensions,
content: "", content: "",
editorProps: {
handleDOMEvents: {
keydown: (_view, event) => {
if (["ArrowUp", "ArrowDown", "Enter"].includes(event.key)) {
const slashCommand = document.querySelector("#slash-command");
if (slashCommand) {
return true;
}
}
},
},
},
onUpdate() { onUpdate() {
if (loadedRef.current) { if (loadedRef.current) {
markDirty(); markDirty();
@@ -160,7 +160,8 @@ export default function TemplateList() {
? spaceNameMap.get(template.spaceId) ? spaceNameMap.get(template.spaceId)
: undefined : undefined
} }
onUse={handlePreview} onPreview={handlePreview}
onUse={handleUse}
onEdit={handleEdit} onEdit={handleEdit}
onDelete={handleDelete} onDelete={handleDelete}
canManage={isWorkspaceAdmin} canManage={isWorkspaceAdmin}
@@ -6,6 +6,7 @@ import {
UseQueryResult, UseQueryResult,
InfiniteData, InfiniteData,
} from "@tanstack/react-query"; } from "@tanstack/react-query";
import { useAtom, useStore } from "jotai";
import { import {
getTemplates, getTemplates,
getTemplateById, getTemplateById,
@@ -18,6 +19,12 @@ import { ITemplate } from "@/ee/template/types/template.types";
import { IPagination } from "@/lib/types.ts"; import { IPagination } from "@/lib/types.ts";
import { notifications } from "@mantine/notifications"; import { notifications } from "@mantine/notifications";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { invalidateOnCreatePage } from "@/features/page/queries/page-query.ts";
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom.ts";
import { treeModel } from "@/features/page/tree/model/tree-model";
import { SpaceTreeNode } from "@/features/page/tree/types.ts";
import { IPage } from "@/features/page/types/page.types.ts";
import { useQueryEmit } from "@/features/websocket/use-query-emit.ts";
export function useGetTemplatesQuery(params?: { spaceId?: string }) { export function useGetTemplatesQuery(params?: { spaceId?: string }) {
const { spaceId } = params ?? {}; const { spaceId } = params ?? {};
@@ -149,13 +156,64 @@ export function useDeleteTemplateMutation() {
export function useUseTemplateMutation() { export function useUseTemplateMutation() {
const { t } = useTranslation(); const { t } = useTranslation();
const [, setTreeData] = useAtom(treeDataAtom);
const store = useStore();
const emit = useQueryEmit();
return useMutation({ return useMutation<
mutationFn: (data: { IPage,
templateId: string; Error,
spaceId: string; { templateId: string; spaceId: string; parentPageId?: string }
parentPageId?: string; >({
}) => useTemplate(data), mutationFn: (data) => useTemplate(data),
onSuccess: (page) => {
// React Query sidebar-pages cache update (same path useCreatePageMutation takes).
invalidateOnCreatePage(page);
const parentId = page.parentPageId ?? null;
const newNode: SpaceTreeNode = {
id: page.id,
slugId: page.slugId,
name: page.title,
icon: page.icon,
position: page.position,
spaceId: page.spaceId,
parentPageId: page.parentPageId,
hasChildren: false,
children: [],
};
// Only mutate the tree atom and broadcast if it currently represents
// this space. Cross-space template-use (e.g., from the gallery picking
// a different space) lets the target space's clients pick up the new
// page on their next React Query refetch (focus, navigation, etc.).
// Without this guard we'd both pollute the local tree and send a wrong
// `index` to remote clients in the target space.
const current = store.get(treeDataAtom);
const treeIsForThisSpace = current[0]?.spaceId === page.spaceId;
if (!treeIsForThisSpace) return;
const lastIndex =
parentId === null
? current.length
: (treeModel.find(current, parentId)?.children?.length ?? 0);
setTreeData((prev) =>
treeModel.insert(prev, parentId, newNode, lastIndex),
);
setTimeout(() => {
emit({
operation: "addTreeNode",
spaceId: page.spaceId,
payload: {
parentId,
index: lastIndex,
data: newNode,
},
});
}, 50);
},
onError: (error) => { onError: (error) => {
const errorMessage = error["response"]?.data?.message; const errorMessage = error["response"]?.data?.message;
notifications.show({ notifications.show({
@@ -1,5 +1,6 @@
import api from "@/lib/api-client"; import api from "@/lib/api-client";
import { ITemplate } from "@/ee/template/types/template.types"; import { ITemplate } from "@/ee/template/types/template.types";
import { IPage } from "@/features/page/types/page.types";
import { IPagination } from "@/lib/types.ts"; import { IPagination } from "@/lib/types.ts";
export async function getTemplates(params?: { export async function getTemplates(params?: {
@@ -40,7 +41,7 @@ export async function useTemplate(data: {
templateId: string; templateId: string;
spaceId: string; spaceId: string;
parentPageId?: string; parentPageId?: string;
}): Promise<any> { }): Promise<IPage> {
const req = await api.post("/templates/use", data); const req = await api.post<IPage>("/templates/use", data);
return req.data; return req.data;
} }
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react"; import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
import { useCallback } from "react"; import { useCallback } from "react";
import { Node as PMNode } from "@tiptap/pm/model"; import { Node as PMNode } from "@tiptap/pm/model";
import { isEditorReady } from "@docmost/editor-ext";
import { import {
EditorMenuProps, EditorMenuProps,
ShouldShowProps, ShouldShowProps,
@@ -46,7 +47,7 @@ export function AudioMenu({ editor }: EditorMenuProps) {
); );
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "audio"; const predicate = (node: PMNode) => node.type.name === "audio";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -16,7 +16,7 @@ import {
IconMoodSmile, IconMoodSmile,
IconNotes, IconNotes,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { CalloutType, isTextSelected } from "@docmost/editor-ext"; import { CalloutType, isEditorReady, isTextSelected } from "@docmost/editor-ext";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import EmojiPicker from "@/components/ui/emoji-picker.tsx"; import EmojiPicker from "@/components/ui/emoji-picker.tsx";
import classes from "../common/toolbar-menu.module.css"; import classes from "../common/toolbar-menu.module.css";
@@ -55,7 +55,7 @@ export function CalloutMenu({ editor }: EditorMenuProps) {
}); });
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "callout"; const predicate = (node: PMNode) => node.type.name === "callout";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -19,7 +19,7 @@ import {
IconCopy, IconCopy,
IconTrash, IconTrash,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { isTextSelected } from "@docmost/editor-ext"; import { isEditorReady, isTextSelected } from "@docmost/editor-ext";
import type { WidthMode, ColumnsLayout } from "@docmost/editor-ext"; import type { WidthMode, ColumnsLayout } from "@docmost/editor-ext";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import classes from "../common/toolbar-menu.module.css"; import classes from "../common/toolbar-menu.module.css";
@@ -82,7 +82,7 @@ export function ColumnsMenu({ editor }: EditorMenuProps) {
const shouldShow = useCallback( const shouldShow = useCallback(
({ state }: ShouldShowProps) => { ({ state }: ShouldShowProps) => {
if (!state) return false; if (!state || !isEditorReady(editor)) return false;
if (!editor.isActive("columns")) return false; if (!editor.isActive("columns")) return false;
if (isTextSelected(editor)) return false; if (isTextSelected(editor)) return false;
if (nodesWithMenus.some((name) => editor.isActive(name))) return false; if (nodesWithMenus.some((name) => editor.isActive(name))) return false;
@@ -121,7 +121,7 @@ export function ColumnsMenu({ editor }: EditorMenuProps) {
}); });
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "columns"; const predicate = (node: PMNode) => node.type.name === "columns";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react"; import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { Node as PMNode } from "@tiptap/pm/model"; import { Node as PMNode } from "@tiptap/pm/model";
import { isEditorReady } from "@docmost/editor-ext";
import { import {
EditorMenuProps, EditorMenuProps,
ShouldShowProps, ShouldShowProps,
@@ -81,7 +82,7 @@ export function DrawioMenu({ editor }: EditorMenuProps) {
); );
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "drawio"; const predicate = (node: PMNode) => node.type.name === "drawio";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -0,0 +1,14 @@
import { lazy, Suspense } from "react";
import { EditorMenuProps } from "@/features/editor/components/table/types/types.ts";
const ExcalidrawMenu = lazy(
() => import("@/features/editor/components/excalidraw/excalidraw-menu.tsx"),
);
export default function ExcalidrawMenuLazy(props: EditorMenuProps) {
return (
<Suspense fallback={null}>
<ExcalidrawMenu {...props} />
</Suspense>
);
}
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react"; import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react"; import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { Node as PMNode } from "@tiptap/pm/model"; import { Node as PMNode } from "@tiptap/pm/model";
import { isEditorReady } from "@docmost/editor-ext";
import { import {
EditorMenuProps, EditorMenuProps,
ShouldShowProps, ShouldShowProps,
@@ -94,7 +95,7 @@ export function ExcalidrawMenu({ editor }: EditorMenuProps) {
); );
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "excalidraw"; const predicate = (node: PMNode) => node.type.name === "excalidraw";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -0,0 +1,14 @@
import { lazy, Suspense } from "react";
import { NodeViewProps } from "@tiptap/react";
const ExcalidrawView = lazy(
() => import("@/features/editor/components/excalidraw/excalidraw-view.tsx"),
);
export default function ExcalidrawViewLazy(props: NodeViewProps) {
return (
<Suspense fallback={null}>
<ExcalidrawView {...props} />
</Suspense>
);
}
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react"; import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
import React, { useCallback, useRef } from "react"; import React, { useCallback, useRef } from "react";
import { Node as PMNode } from "@tiptap/pm/model"; import { Node as PMNode } from "@tiptap/pm/model";
import { isEditorReady } from "@docmost/editor-ext";
import { import {
EditorMenuProps, EditorMenuProps,
ShouldShowProps, ShouldShowProps,
@@ -56,7 +57,7 @@ export function ImageMenu({ editor }: EditorMenuProps) {
); );
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "image"; const predicate = (node: PMNode) => node.type.name === "image";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react"; import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
import { useCallback } from "react"; import { useCallback } from "react";
import { Node as PMNode } from "@tiptap/pm/model"; import { Node as PMNode } from "@tiptap/pm/model";
import { isEditorReady } from "@docmost/editor-ext";
import { import {
EditorMenuProps, EditorMenuProps,
ShouldShowProps, ShouldShowProps,
@@ -37,9 +38,8 @@ export function PdfMenu({ editor }: EditorMenuProps) {
const shouldShow = useCallback( const shouldShow = useCallback(
({ state }: ShouldShowProps) => { ({ state }: ShouldShowProps) => {
if (!state || !editor.isActive("pdf")) { if (!state || !isEditorReady(editor)) return false;
return false; if (!editor.isActive("pdf")) return false;
}
const { selection } = state; const { selection } = state;
const dom = editor.view.nodeDOM(selection.from) as HTMLElement | null; const dom = editor.view.nodeDOM(selection.from) as HTMLElement | null;
@@ -51,7 +51,7 @@ export function PdfMenu({ editor }: EditorMenuProps) {
); );
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "pdf"; const predicate = (node: PMNode) => node.type.name === "pdf";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -6,6 +6,7 @@ import { ActionIcon, Tooltip } from "@mantine/core";
import { IconTrash } from "@tabler/icons-react"; import { IconTrash } from "@tabler/icons-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Editor } from "@tiptap/core"; import { Editor } from "@tiptap/core";
import { isEditorReady } from "@docmost/editor-ext";
interface SubpagesMenuProps { interface SubpagesMenuProps {
editor: Editor; editor: Editor;
@@ -33,6 +34,7 @@ export const SubpagesMenu = React.memo(
); );
const getReferenceClientRect = useCallback(() => { const getReferenceClientRect = useCallback(() => {
if (!isEditorReady(editor)) return new DOMRect();
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "subpages"; const predicate = (node: PMNode) => node.type.name === "subpages";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -31,7 +31,12 @@ export const ColumnHandle = React.memo(function ColumnHandle({
// (the plugin re-emits `hoveringCell` with the mapped pos a tick later); // (the plugin re-emits `hoveringCell` with the mapped pos a tick later);
// unmounting the source element here would make pragmatic-dnd silently // unmounting the source element here would make pragmatic-dnd silently
// abort the active drag. // abort the active drag.
const lookupCellDom = editor.view.nodeDOM(anchorPos) as HTMLElement | null; // `nodeDOM` is typed as `Node | null` — when `anchorPos` goes stale (e.g.
// an external drop reflows the doc before the plugin re-emits
// hoveringCell), it can resolve to a Text node, on which `.closest` is
// undefined. Filter to HTMLElement so downstream consumers stay safe.
const lookupDom = editor.view.nodeDOM(anchorPos);
const lookupCellDom = lookupDom instanceof HTMLElement ? lookupDom : null;
const [cellDom, setCellDom] = useState<HTMLElement | null>(lookupCellDom); const [cellDom, setCellDom] = useState<HTMLElement | null>(lookupCellDom);
const lastCellDomRef = useRef<HTMLElement | null>(lookupCellDom); const lastCellDomRef = useRef<HTMLElement | null>(lookupCellDom);
useEffect(() => { useEffect(() => {
@@ -29,7 +29,12 @@ export const RowHandle = React.memo(function RowHandle({
// See ColumnHandle for the rationale: keep the last valid cell DOM cached // See ColumnHandle for the rationale: keep the last valid cell DOM cached
// so the handle div stays mounted across stale-anchor renders, otherwise // so the handle div stays mounted across stale-anchor renders, otherwise
// pragmatic-dnd silently aborts an in-flight drag. // pragmatic-dnd silently aborts an in-flight drag.
const lookupCellDom = editor.view.nodeDOM(anchorPos) as HTMLElement | null; // `nodeDOM` is typed as `Node | null` — when `anchorPos` goes stale (e.g.
// an external drop reflows the doc before the plugin re-emits
// hoveringCell), it can resolve to a Text node, on which `.closest` is
// undefined. Filter to HTMLElement so downstream consumers stay safe.
const lookupDom = editor.view.nodeDOM(anchorPos);
const lookupCellDom = lookupDom instanceof HTMLElement ? lookupDom : null;
const [cellDom, setCellDom] = useState<HTMLElement | null>(lookupCellDom); const [cellDom, setCellDom] = useState<HTMLElement | null>(lookupCellDom);
const lastCellDomRef = useRef<HTMLElement | null>(lookupCellDom); const lastCellDomRef = useRef<HTMLElement | null>(lookupCellDom);
useEffect(() => { useEffect(() => {
@@ -18,7 +18,7 @@ import {
IconTrashX, IconTrashX,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { BubbleMenu } from "@tiptap/react/menus"; import { BubbleMenu } from "@tiptap/react/menus";
import { isCellSelection, isTextSelected } from "@docmost/editor-ext"; import { isCellSelection, isEditorReady, isTextSelected } from "@docmost/editor-ext";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import classes from "../common/toolbar-menu.module.css"; import classes from "../common/toolbar-menu.module.css";
@@ -38,6 +38,7 @@ export const TableMenu = React.memo(
); );
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "table"; const predicate = (node: PMNode) => node.type.name === "table";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react"; import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
import { useCallback } from "react"; import { useCallback } from "react";
import { Node as PMNode } from "@tiptap/pm/model"; import { Node as PMNode } from "@tiptap/pm/model";
import { isEditorReady } from "@docmost/editor-ext";
import { import {
EditorMenuProps, EditorMenuProps,
ShouldShowProps, ShouldShowProps,
@@ -53,7 +54,7 @@ export function VideoMenu({ editor }: EditorMenuProps) {
); );
const getReferencedVirtualElement = useCallback(() => { const getReferencedVirtualElement = useCallback(() => {
if (!editor) return; if (!isEditorReady(editor)) return;
const { selection } = editor.state; const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "video"; const predicate = (node: PMNode) => node.type.name === "video";
const parent = findParentNode(predicate)(selection); const parent = findParentNode(predicate)(selection);
@@ -85,7 +85,7 @@ import AudioView from "@/features/editor/components/audio/audio-view.tsx";
import AttachmentView from "@/features/editor/components/attachment/attachment-view.tsx"; import AttachmentView from "@/features/editor/components/attachment/attachment-view.tsx";
import CodeBlockView from "@/features/editor/components/code-block/code-block-view.tsx"; import CodeBlockView from "@/features/editor/components/code-block/code-block-view.tsx";
import DrawioView from "../components/drawio/drawio-view"; import DrawioView from "../components/drawio/drawio-view";
import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-view.tsx"; import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-view-lazy.tsx";
import EmbedView from "@/features/editor/components/embed/embed-view.tsx"; import EmbedView from "@/features/editor/components/embed/embed-view.tsx";
import PdfView from "@/features/editor/components/pdf/pdf-view.tsx"; import PdfView from "@/features/editor/components/pdf/pdf-view.tsx";
import SubpagesView from "@/features/editor/components/subpages/subpages-view.tsx"; import SubpagesView from "@/features/editor/components/subpages/subpages-view.tsx";
@@ -416,7 +416,9 @@ const TEMPLATE_EXCLUDED_SLASH_ITEMS = new Set([
"Video", "Video",
"File attachment", "File attachment",
"Draw.io (diagrams.net)", "Draw.io (diagrams.net)",
"Excalidraw diagram", "Excalidraw (Whiteboard)",
"Audio",
"Synced block"
]); ]);
const TemplateSlashCommand = Command.configure({ const TemplateSlashCommand = Command.configure({
@@ -55,7 +55,7 @@ import {
handleFileDrop, handleFileDrop,
handlePaste, handlePaste,
} from "@/features/editor/components/common/editor-paste-handler.tsx"; } from "@/features/editor/components/common/editor-paste-handler.tsx";
import ExcalidrawMenu from "./components/excalidraw/excalidraw-menu"; import ExcalidrawMenu from "./components/excalidraw/excalidraw-menu-lazy";
import DrawioMenu from "./components/drawio/drawio-menu"; import DrawioMenu from "./components/drawio/drawio-menu";
import { useCollabToken } from "@/features/auth/queries/auth-query.tsx"; import { useCollabToken } from "@/features/auth/queries/auth-query.tsx";
import SearchAndReplaceDialog from "@/features/editor/components/search-and-replace/search-and-replace-dialog.tsx"; import SearchAndReplaceDialog from "@/features/editor/components/search-and-replace/search-and-replace-dialog.tsx";
@@ -238,14 +238,6 @@ export default function PageEditor({
event.preventDefault(); event.preventDefault();
return true; return true;
} }
if (event.key === "Tab") {
const editor = editorRef.current;
if (!editor) return false;
event.preventDefault();
return editor.view.someProp("handleKeyDown", (f) =>
f(editor.view, event)
);
}
if (platformModifierKey(event) && event.code === "KeyK") { if (platformModifierKey(event) && event.code === "KeyK") {
searchSpotlight.open(); searchSpotlight.open();
return true; return true;
@@ -18,6 +18,7 @@ import {
IconSettings, IconSettings,
IconStar, IconStar,
IconStarFilled, IconStarFilled,
IconTemplate,
IconTrash, IconTrash,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { import {
@@ -53,6 +54,10 @@ import {
import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts"; import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts"; import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
import { searchSpotlight } from "@/features/search/constants"; import { searchSpotlight } from "@/features/search/constants";
import TemplatePickerModal from "@/ee/template/components/template-picker-modal";
import { useHasFeature } from "@/ee/hooks/use-feature";
import { Feature } from "@/ee/features";
import { ErrorBoundary } from "react-error-boundary";
export function SpaceSidebar() { export function SpaceSidebar() {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -246,6 +251,11 @@ function SpaceMenu({
useDisclosure(false); useDisclosure(false);
const [exportOpened, { open: openExportModal, close: closeExportModal }] = const [exportOpened, { open: openExportModal, close: closeExportModal }] =
useDisclosure(false); useDisclosure(false);
const [
templatePickerOpened,
{ open: openTemplatePicker, close: closeTemplatePicker },
] = useDisclosure(false);
const hasTemplates = useHasFeature(Feature.TEMPLATES);
const { data: watchStatus } = useSpaceWatchStatusQuery(spaceId); const { data: watchStatus } = useSpaceWatchStatusQuery(spaceId);
const watchMutation = useWatchSpaceMutation(); const watchMutation = useWatchSpaceMutation();
@@ -315,6 +325,18 @@ function SpaceMenu({
{isWatching ? t("Stop watching space") : t("Watch space")} {isWatching ? t("Stop watching space") : t("Watch space")}
</Menu.Item> </Menu.Item>
{hasTemplates && canManagePages && (
<>
<Menu.Divider />
<Menu.Item
onClick={openTemplatePicker}
leftSection={<IconTemplate size={16} />}
>
{t("Templates")}
</Menu.Item>
</>
)}
{canManagePages && ( {canManagePages && (
<> <>
<Menu.Divider /> <Menu.Divider />
@@ -370,6 +392,16 @@ function SpaceMenu({
/> />
</> </>
)} )}
{hasTemplates && templatePickerOpened && (
<ErrorBoundary fallbackRender={() => null}>
<TemplatePickerModal
opened={templatePickerOpened}
onClose={closeTemplatePicker}
initialSpaceId={spaceId}
/>
</ErrorBoundary>
)}
</> </>
); );
} }
@@ -6,6 +6,7 @@ import { getAppName, isCloud } from "@/lib/config.ts";
import { Helmet } from "react-helmet-async"; import { Helmet } from "react-helmet-async";
import ManageHostname from "@/ee/components/manage-hostname.tsx"; import ManageHostname from "@/ee/components/manage-hostname.tsx";
import { Divider } from "@mantine/core"; import { Divider } from "@mantine/core";
import AllowMemberTemplates from "@/ee/security/components/allow-member-templates.tsx";
export default function WorkspaceSettings() { export default function WorkspaceSettings() {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -18,6 +19,9 @@ export default function WorkspaceSettings() {
<WorkspaceIcon /> <WorkspaceIcon />
<WorkspaceNameForm /> <WorkspaceNameForm />
<Divider my="md" />
<AllowMemberTemplates />
{isCloud() && ( {isCloud() && (
<> <>
<Divider my="md" /> <Divider my="md" />
+5 -5
View File
@@ -38,12 +38,12 @@ export default defineConfig(({ mode }) => {
build: { build: {
rolldownOptions: { rolldownOptions: {
output: { output: {
codeSplitting: { advancedChunks: {
groups: [ groups: [
{ name: "vendor-mantine", test: /@mantine/ }, {
{ name: "vendor-mermaid", test: /mermaid|cytoscape|elkjs/ }, name: "vendor-mantine",
{ name: "vendor-excalidraw", test: /excalidraw/ }, test: /[\\/]node_modules[\\/]@mantine[\\/]/,
{ name: "vendor-katex", test: /katex/ }, },
], ],
}, },
}, },
+1
View File
@@ -2,3 +2,4 @@ export * from './utils';
export * from './nanoid.utils'; export * from './nanoid.utils';
export * from './file.helper'; export * from './file.helper';
export * from './constants'; export * from './constants';
export * from './security-headers';
@@ -0,0 +1,19 @@
export type SecurityHeader = { name: string; value: string };
export function resolveFrameHeader(
iframeEmbedAllowed: boolean,
allowedOrigins: string[],
): SecurityHeader | null {
if (!iframeEmbedAllowed) {
return { name: 'X-Frame-Options', value: 'SAMEORIGIN' };
}
if (allowedOrigins.length === 0) {
return null;
}
return {
name: 'Content-Security-Policy',
value: `frame-ancestors 'self' ${allowedOrigins.join(' ')}`,
};
}
@@ -63,11 +63,9 @@ export class TemplateRepo {
if (opts?.spaceId) { if (opts?.spaceId) {
if (!accessibleSpaceIds.includes(opts.spaceId)) { if (!accessibleSpaceIds.includes(opts.spaceId)) {
query = query.where('spaceId', 'is', null); query = query.where(sql<boolean>`false`);
} else { } else {
query = query.where((eb) => query = query.where('spaceId', '=', opts.spaceId);
eb.or([eb('spaceId', '=', opts.spaceId), eb('spaceId', 'is', null)]),
);
} }
} else { } else {
query = query.where((eb) => query = query.where((eb) =>
@@ -325,4 +325,19 @@ export class EnvironmentService {
.toLowerCase(); .toLowerCase();
return disabled === 'true'; return disabled === 'true';
} }
isIframeEmbedAllowed(): boolean {
const allowed = this.configService
.get<string>('IFRAME_EMBED_ALLOWED', 'false')
.toLowerCase();
return allowed === 'true';
}
getIframeAllowedOrigins(): string[] {
const raw = this.configService.get<string>('IFRAME_ALLOWED_ORIGINS', '');
return raw
.split(',')
.map((o) => o.trim())
.filter(Boolean);
}
} }
+24
View File
@@ -12,6 +12,8 @@ import fastifyMultipart from '@fastify/multipart';
import fastifyCookie from '@fastify/cookie'; import fastifyCookie from '@fastify/cookie';
import fastifyIp from 'fastify-ip'; import fastifyIp from 'fastify-ip';
import { InternalLogFilter } from './common/logger/internal-log-filter'; import { InternalLogFilter } from './common/logger/internal-log-filter';
import { EnvironmentService } from './integrations/environment/environment.service';
import { resolveFrameHeader } from './common/helpers';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>( const app = await NestFactory.create<NestFastifyApplication>(
@@ -50,6 +52,28 @@ async function bootstrap() {
await app.register(fastifyMultipart); await app.register(fastifyMultipart);
await app.register(fastifyCookie); await app.register(fastifyCookie);
const environmentService = app.get(EnvironmentService);
const frameHeader = resolveFrameHeader(
environmentService.isIframeEmbedAllowed(),
environmentService.getIframeAllowedOrigins(),
);
if (frameHeader) {
// Skipped routes:
// /api/files/ - attachment controller sets its own CSP we'd overwrite
// /share/ 0 public share pages are safe to embed
const frameHeaderSkippedPrefixes = ['/api/files/', '/share/'];
app
.getHttpAdapter()
.getInstance()
.addHook('onSend', (req, reply, payload, done) => {
if (frameHeaderSkippedPrefixes.some((p) => req.url.startsWith(p))) {
return done(null, payload);
}
reply.header(frameHeader.name, frameHeader.value);
done(null, payload);
});
}
app app
.getHttpAdapter() .getHttpAdapter()
.getInstance() .getInstance()
@@ -162,6 +162,28 @@ export const Callout = Node.create<CalloutOptions>({
return false; return false;
} }
// Empty callout: delete the whole node so Backspace inside it isn't
// a no-op (isolating: true blocks the default join with the block
// above).
const calloutDepth = $from.depth - 1;
if (calloutDepth >= 0) {
const calloutNode = $from.node(calloutDepth);
if (
calloutNode.type === this.type &&
calloutNode.childCount === 1 &&
calloutNode.firstChild?.content.size === 0
) {
const calloutPos = $from.before(calloutDepth);
const { tr } = state;
tr.delete(calloutPos, calloutPos + calloutNode.nodeSize);
tr.setSelection(
TextSelection.near(tr.doc.resolve(calloutPos), -1),
);
view.dispatch(tr);
return true;
}
}
const previousPosition = $from.before($from.depth) - 1; const previousPosition = $from.before($from.depth) - 1;
// If nothing above to join with // If nothing above to join with
@@ -207,6 +229,56 @@ export const Callout = Node.create<CalloutOptions>({
} }
return false; return false;
}, },
// Exit the callout into a fresh paragraph below when the cursor sits
// in an empty trailing child. An empty callout (single empty
// paragraph) exits on the first Enter and keeps the empty callout
// intact; a callout with content needs the double-Enter pattern
// (first Enter splits, second Enter on the new trailing empty exits
// and removes that trailing paragraph).
Enter: ({ editor }) => {
const { state, view } = editor;
const { selection } = state;
if (!selection.empty) return false;
const { $from } = selection;
const calloutDepth = $from.depth - 1;
if (calloutDepth < 0) return false;
const calloutNode = $from.node(calloutDepth);
if (calloutNode.type !== this.type) return false;
if ($from.parent.content.size !== 0) return false;
if ($from.index(calloutDepth) !== calloutNode.childCount - 1) {
return false;
}
const paragraphType = state.schema.nodes.paragraph;
const containerDepth = calloutDepth - 1;
const container = $from.node(containerDepth);
const indexAfter = $from.indexAfter(containerDepth);
if (
!container.canReplaceWith(indexAfter, indexAfter, paragraphType)
) {
return false;
}
const calloutEnd = $from.after(calloutDepth);
const paragraph = paragraphType.create();
const { tr } = state;
if (calloutNode.childCount === 1) {
tr.insert(calloutEnd, paragraph);
tr.setSelection(TextSelection.create(tr.doc, calloutEnd + 1));
} else {
tr.delete($from.before(), $from.after());
const insertPos = tr.mapping.map(calloutEnd);
tr.insert(insertPos, paragraph);
tr.setSelection(TextSelection.create(tr.doc, insertPos + 1));
}
view.dispatch(tr);
return true;
},
}; };
}, },
@@ -1,5 +1,7 @@
import type { CodeBlockOptions } from '@tiptap/extension-code-block'; import type { CodeBlockOptions } from '@tiptap/extension-code-block';
import CodeBlock from '@tiptap/extension-code-block'; import CodeBlock from '@tiptap/extension-code-block';
import { Plugin, Selection, TextSelection } from '@tiptap/pm/state';
import { GapCursor } from '@tiptap/pm/gapcursor';
import { LowlightPlugin } from './lowlight-plugin.js'; import { LowlightPlugin } from './lowlight-plugin.js';
import { ReactNodeViewRenderer } from '@tiptap/react'; import { ReactNodeViewRenderer } from '@tiptap/react';
@@ -19,7 +21,11 @@ const TAB_CHAR = '\u00A0\u00A0';
* @see https://tiptap.dev/api/nodes/code-block-lowlight * @see https://tiptap.dev/api/nodes/code-block-lowlight
*/ */
export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
// Run ahead of Gapcursor (100) so the mermaid arrow-into-source plugin
// can intercept before gapcursor takes over.
priority: 101,
selectable: true, selectable: true,
isolating: true,
addOptions() { addOptions() {
return { return {
@@ -35,8 +41,86 @@ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
}, },
addKeyboardShortcuts() { addKeyboardShortcuts() {
const isMermaid = (node: any) =>
node?.type === this.type && node.attrs.language === 'mermaid';
return { return {
...this.parent?.(), ...this.parent?.(),
// Stop at the gap (or enter mermaid source) instead of jumping
// straight into the next block, so the user can place a cursor
// between two adjacent isolating blocks.
ArrowDown: ({ editor }) => {
const { state } = editor;
const { selection, doc } = state;
const { $from, empty } = selection;
if (!empty || $from.parent.type !== this.type) return false;
if ($from.parentOffset !== $from.parent.nodeSize - 2) return false;
const after = $from.after();
if (after >= doc.content.size) {
return editor.commands.exitCode();
}
const $after = doc.resolve(after);
const nodeAfter = $after.nodeAfter;
if (isMermaid(nodeAfter)) {
return editor.commands.command(({ tr }) => {
tr.setSelection(TextSelection.create(tr.doc, after + 1));
return true;
});
}
if (
nodeAfter?.type.spec.isolating &&
!nodeAfter.type.spec.atom
) {
return editor.commands.command(({ tr }) => {
tr.setSelection(new GapCursor(tr.doc.resolve(after)));
return true;
});
}
return editor.commands.command(({ tr }) => {
tr.setSelection(Selection.near(tr.doc.resolve(after)));
return true;
});
},
// Mirror of ArrowDown; upstream has no ArrowUp handler.
ArrowUp: ({ editor }) => {
const { state } = editor;
const { selection, doc } = state;
const { $from, empty } = selection;
if (!empty || $from.parent.type !== this.type) return false;
if ($from.parentOffset !== 0) return false;
const before = $from.before();
if (before <= 0) return false;
const $before = doc.resolve(before);
const nodeBefore = $before.nodeBefore;
if (isMermaid(nodeBefore)) {
return editor.commands.command(({ tr }) => {
tr.setSelection(TextSelection.create(tr.doc, before - 1));
return true;
});
}
if (
nodeBefore?.type.spec.isolating &&
!nodeBefore.type.spec.atom
) {
return editor.commands.command(({ tr }) => {
tr.setSelection(new GapCursor(tr.doc.resolve(before)));
return true;
});
}
return false;
},
'Mod-a': () => { 'Mod-a': () => {
if (this.editor.isActive('codeBlock')) { if (this.editor.isActive('codeBlock')) {
const { state } = this.editor; const { state } = this.editor;
@@ -84,6 +168,7 @@ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
}, },
addProseMirrorPlugins() { addProseMirrorPlugins() {
const codeBlockType = this.type;
return [ return [
...(this.parent?.() || []), ...(this.parent?.() || []),
LowlightPlugin({ LowlightPlugin({
@@ -91,6 +176,60 @@ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
lowlight: this.options.lowlight, lowlight: this.options.lowlight,
defaultLanguage: this.options.defaultLanguage, defaultLanguage: this.options.defaultLanguage,
}), }),
// Mermaid hides its <pre> when unselected, so the browser's native
// vertical caret movement skips past it. Land the cursor inside the
// source explicitly.
new Plugin({
props: {
handleKeyDown: (view, event) => {
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
return false;
}
const { state } = view;
const { selection } = state;
if (
!selection.empty ||
!(selection instanceof TextSelection)
) {
return false;
}
const { $from } = selection;
if ($from.depth === 0 || $from.parent.type === codeBlockType) {
return false;
}
const dir = event.key === 'ArrowUp' ? 'up' : 'down';
if (!view.endOfTextblock(dir)) return false;
const isMermaid = (node: any) =>
node?.type === codeBlockType && node.attrs.language === 'mermaid';
if (event.key === 'ArrowUp') {
if ($from.parentOffset !== 0) return false;
const beforePos = $from.before();
const prev = state.doc.resolve(beforePos).nodeBefore;
if (!isMermaid(prev)) return false;
const endPos = beforePos - 1;
view.dispatch(
state.tr.setSelection(
TextSelection.create(state.doc, endPos),
),
);
return true;
}
if ($from.parentOffset !== $from.parent.nodeSize - 2) return false;
const afterPos = $from.after();
const next = state.doc.resolve(afterPos).nodeAfter;
if (!isMermaid(next)) return false;
const startPos = afterPos + 1;
view.dispatch(
state.tr.setSelection(
TextSelection.create(state.doc, startPos),
),
);
return true;
},
},
}),
]; ];
}, },
}); });
+9
View File
@@ -338,6 +338,15 @@ export const isRowGripSelected = ({
return !!gripRow; return !!gripRow;
}; };
// TipTap's `editor.view` proxy throws if accessed before mount or after destroy.
// Guard floating-menu callbacks (getReferencedVirtualElement, shouldShow) with
// this before touching `editor.view.nodeDOM(...)`.
export function isEditorReady(
editor: Editor | null | undefined,
): editor is Editor {
return !!editor && editor.isInitialized;
}
export function isTextSelected(editor: Editor) { export function isTextSelected(editor: Editor) {
const { const {
state: { state: {