Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ccee32cb0b | |||
| 79a461f79d |
@@ -67,20 +67,14 @@ export default function GlobalAppShell({
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// Attach the global mousemove/mouseup only WHILE resizing (started on the
|
||||
// handle's mousedown via startResizing → isResizing=true) and detach on
|
||||
// mouseup (stopResizing → isResizing=false). Previously these listeners were
|
||||
// attached for the whole app lifetime, so every mouse move over the app ran
|
||||
// the resize handler.
|
||||
// https://codesandbox.io/p/sandbox/kz9de
|
||||
if (!isResizing) return;
|
||||
//https://codesandbox.io/p/sandbox/kz9de
|
||||
window.addEventListener("mousemove", resize);
|
||||
window.addEventListener("mouseup", stopResizing);
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", resize);
|
||||
window.removeEventListener("mouseup", stopResizing);
|
||||
};
|
||||
}, [isResizing, resize, stopResizing]);
|
||||
}, [resize, stopResizing]);
|
||||
|
||||
const location = useLocation();
|
||||
const isSettingsRoute = location.pathname.startsWith("/settings");
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
Button,
|
||||
useMantineColorScheme,
|
||||
} from "@mantine/core";
|
||||
import { useClickOutside, useDisclosure } from "@mantine/hooks";
|
||||
import { useClickOutside, useDisclosure, useWindowEvent } from "@mantine/hooks";
|
||||
import { Suspense } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -57,22 +57,14 @@ function EmojiPicker({
|
||||
[dropdown, target],
|
||||
);
|
||||
|
||||
// We need this because the default Mantine popover closeOnEscape does not work.
|
||||
// Attach the global keydown ONLY while the picker is open (every tree row
|
||||
// renders an EmojiPicker, so an always-on window listener meant ~20-30 idle
|
||||
// keydown handlers firing on each keystroke).
|
||||
useEffect(() => {
|
||||
if (!opened) return;
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
handlers.close();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handleKeydown);
|
||||
return () => window.removeEventListener("keydown", handleKeydown);
|
||||
}, [opened, handlers]);
|
||||
// We need this because the default Mantine popover closeOnEscape does not work
|
||||
useWindowEvent("keydown", (event) => {
|
||||
if (opened && event.key === "Escape") {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
handlers.close();
|
||||
}
|
||||
});
|
||||
|
||||
// emoji-mart's built-in autoFocus calls .focus() without preventScroll, which
|
||||
// makes the browser scroll every scrollable ancestor of the search input to
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
desktopSidebarAtom,
|
||||
mobileSidebarAtom,
|
||||
} from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { extractPageSlugId } from "@/lib";
|
||||
import {
|
||||
AI_CHATS_RQ_KEY,
|
||||
@@ -230,9 +230,7 @@ export default function AiChatWindow() {
|
||||
// left partly off-screen).
|
||||
const [geom, setGeom] = useAtom(aiChatWindowGeomAtom);
|
||||
|
||||
// Gated on windowOpen: the chat list is only needed once the window is open,
|
||||
// so a closed window issues no chat-list request/refetch on navigation.
|
||||
const { data: chats } = useAiChatsQuery(windowOpen);
|
||||
const { data: chats } = useAiChatsQuery();
|
||||
// Roles for the new-chat picker (any member may list them). Only fetched while
|
||||
// the window is open.
|
||||
const { data: roles } = useAiRolesQuery(windowOpen);
|
||||
@@ -244,10 +242,8 @@ export default function AiChatWindow() {
|
||||
[roles],
|
||||
);
|
||||
|
||||
// Gated on windowOpen too: no message history is fetched while the window is
|
||||
// closed (it is loaded when the window opens with an active chat).
|
||||
const { data: messageRows, isLoading: messagesLoading } =
|
||||
useAiChatMessagesQuery(activeChatId ?? undefined, windowOpen);
|
||||
useAiChatMessagesQuery(activeChatId ?? undefined);
|
||||
|
||||
// #184 reconnect-and-live-follow. Whether detached agent runs are enabled for
|
||||
// this workspace. The reconnect endpoint itself is NOT flag-gated server-side
|
||||
@@ -400,7 +396,7 @@ export default function AiChatWindow() {
|
||||
// reads/writes via its CASL-enforced page tools using the id.
|
||||
const pageRouteMatch = useMatch("/s/:spaceSlug/p/:pageSlug");
|
||||
const pageSlug = pageRouteMatch?.params?.pageSlug;
|
||||
const { data: openPageData } = usePageMetaQuery({
|
||||
const { data: openPageData } = usePageQuery({
|
||||
pageId: extractPageSlugId(pageSlug),
|
||||
});
|
||||
const openPage = openPageData
|
||||
|
||||
@@ -57,12 +57,8 @@ export const AI_CHAT_MESSAGES_RQ_KEY = (chatId: string) => [
|
||||
];
|
||||
export const AI_CHAT_RUN_RQ_KEY = (chatId: string) => ["ai-chat-run", chatId];
|
||||
|
||||
/**
|
||||
* Paginated list of the current user's chats (auto-loads further pages).
|
||||
* `enabled` (default true) lets the AI chat window skip fetching while it is
|
||||
* closed — the list is only needed once the window is open.
|
||||
*/
|
||||
export function useAiChatsQuery(enabled: boolean = true) {
|
||||
/** Paginated list of the current user's chats (auto-loads further pages). */
|
||||
export function useAiChatsQuery() {
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: AI_CHATS_RQ_KEY,
|
||||
queryFn: ({ pageParam }) => getAiChats({ cursor: pageParam, limit: 50 }),
|
||||
@@ -71,7 +67,6 @@ export function useAiChatsQuery(enabled: boolean = true) {
|
||||
lastPage.meta.hasNextPage
|
||||
? (lastPage.meta.nextCursor ?? undefined)
|
||||
: undefined,
|
||||
enabled,
|
||||
});
|
||||
|
||||
const data = useMemo<IPagination<IAiChat> | undefined>(() => {
|
||||
@@ -94,10 +89,7 @@ export function useAiChatsQuery(enabled: boolean = true) {
|
||||
* Load all persisted messages of a chat (oldest first), flattening the
|
||||
* paginated server response. Used to seed `useChat` initial messages.
|
||||
*/
|
||||
export function useAiChatMessagesQuery(
|
||||
chatId: string | undefined,
|
||||
enabled: boolean = true,
|
||||
) {
|
||||
export function useAiChatMessagesQuery(chatId: string | undefined) {
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: AI_CHAT_MESSAGES_RQ_KEY(chatId ?? ""),
|
||||
queryFn: ({ pageParam }) =>
|
||||
@@ -107,7 +99,7 @@ export function useAiChatMessagesQuery(
|
||||
lastPage.meta.hasNextPage
|
||||
? (lastPage.meta.nextCursor ?? undefined)
|
||||
: undefined,
|
||||
enabled: !!chatId && enabled,
|
||||
enabled: !!chatId,
|
||||
});
|
||||
|
||||
// useInfiniteQuery only fetches the first page on its own. The hook's contract
|
||||
|
||||
@@ -15,7 +15,6 @@ vi.mock("@/features/comment/components/comment-editor", () => ({
|
||||
// case renders in isolation.
|
||||
vi.mock("@/features/page/queries/page-query.ts", () => ({
|
||||
usePageQuery: () => ({ data: undefined, isLoading: false, isError: false }),
|
||||
usePageMetaQuery: () => ({ data: undefined, isLoading: false, isError: false }),
|
||||
}));
|
||||
vi.mock("@/features/share/queries/share-query.ts", () => ({
|
||||
useSharePageQuery: () => ({ data: undefined }),
|
||||
|
||||
@@ -22,7 +22,7 @@ import CommentEditor from "@/features/comment/components/comment-editor";
|
||||
import CommentActions from "@/features/comment/components/comment-actions";
|
||||
import { useFocusWithin } from "@mantine/hooks";
|
||||
import { IComment } from "@/features/comment/types/comment.types.ts";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { extractPageSlugId } from "@/lib";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useGetSpaceBySlugQuery } from "@/features/space/queries/space-query.ts";
|
||||
@@ -56,7 +56,7 @@ export function buildChildrenByParent(
|
||||
function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { pageSlug } = useParams();
|
||||
const { data: page } = usePageMetaQuery({ pageId: extractPageSlugId(pageSlug) });
|
||||
const { data: page } = usePageQuery({ pageId: extractPageSlugId(pageSlug) });
|
||||
const {
|
||||
data: comments,
|
||||
isLoading: isCommentsLoading,
|
||||
|
||||
@@ -24,7 +24,7 @@ import classes from "./link.module.css";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { INTERNAL_LINK_REGEX } from "@/lib/constants";
|
||||
import { LinkEditorPanel } from "@/features/editor/components/link/link-editor-panel.tsx";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { useSharePageQuery } from "@/features/share/queries/share-query.ts";
|
||||
import { buildSharedPageUrl } from "@/features/page/page.utils.ts";
|
||||
import { extractPageSlugId } from "@/lib";
|
||||
@@ -83,7 +83,7 @@ export default function LinkView(props: MarkViewProps) {
|
||||
const isPopoverVisible = popoverState !== "closed";
|
||||
const activeView = isPopoverVisible ? popoverState : lastOpenState.current;
|
||||
|
||||
const { data: linkedPage } = usePageMetaQuery({
|
||||
const { data: linkedPage } = usePageQuery({
|
||||
pageId: isPopoverVisible && slugId && !isShareRoute ? slugId : null,
|
||||
});
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import { IconFileDescription, IconPlus } from "@tabler/icons-react";
|
||||
import { useSpaceQuery } from "@/features/space/queries/space-query.ts";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { v7 as uuid7 } from "uuid";
|
||||
import { useAtom, useSetAtom, useStore } from "jotai";
|
||||
import { useAtom } from "jotai";
|
||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||
import {
|
||||
MentionListProps,
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
import { IPage } from "@/features/page/types/page.types";
|
||||
import {
|
||||
useCreatePageMutation,
|
||||
usePageMetaQuery,
|
||||
usePageQuery,
|
||||
} from "@/features/page/queries/page-query";
|
||||
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom";
|
||||
import { treeModel } from "@/features/page/tree/model/tree-model";
|
||||
@@ -50,16 +50,12 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
|
||||
const [countAnnouncement, setCountAnnouncement] = useState("");
|
||||
const [selectionAnnouncement, setSelectionAnnouncement] = useState("");
|
||||
const { pageSlug, spaceSlug } = useParams();
|
||||
const { data: page } = usePageMetaQuery({ pageId: extractPageSlugId(pageSlug) });
|
||||
const { data: page } = usePageQuery({ pageId: extractPageSlugId(pageSlug) });
|
||||
const { data: space } = useSpaceQuery(spaceSlug);
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const [renderItems, setRenderItems] = useState<MentionSuggestionItem[]>([]);
|
||||
const { t } = useTranslation();
|
||||
// Setter-only: the tree value is read only imperatively inside createPage
|
||||
// (via `store` below), never at render, so useSetAtom avoids re-rendering the
|
||||
// mention popup on any tree event.
|
||||
const setData = useSetAtom(treeDataAtom);
|
||||
const store = useStore();
|
||||
const [data, setData] = useAtom(treeDataAtom);
|
||||
const createPageMutation = useCreatePageMutation();
|
||||
const emit = useQueryEmit();
|
||||
const isInCommentContext = props.isInCommentContext ?? false;
|
||||
@@ -276,11 +272,9 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
|
||||
children: [],
|
||||
};
|
||||
|
||||
// Read the live tree imperatively at call time.
|
||||
const currentTree = store.get(treeDataAtom);
|
||||
const lastIndex = currentTree.length;
|
||||
const lastIndex = data.length;
|
||||
|
||||
setData(treeModel.insert(currentTree, parentId, newNode, lastIndex));
|
||||
setData(treeModel.insert(data, parentId, newNode, lastIndex));
|
||||
|
||||
props.command({
|
||||
id: uuid7(),
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
|
||||
import { ActionIcon, Anchor, Text } from "@mantine/core";
|
||||
import { IconFileDescription } from "@tabler/icons-react";
|
||||
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { useSharePageQuery } from "@/features/share/queries/share-query.ts";
|
||||
import {
|
||||
buildPageUrl,
|
||||
@@ -36,7 +36,7 @@ export function MentionContent({ attrs }: { attrs: MentionAttrs }) {
|
||||
data: page,
|
||||
isLoading,
|
||||
isError,
|
||||
} = usePageMetaQuery({ pageId: isPageMention && !isShareRoute ? slugId : null });
|
||||
} = usePageQuery({ pageId: isPageMention && !isShareRoute ? slugId : null });
|
||||
|
||||
const { data: sharedPage } = useSharePageQuery({
|
||||
pageId: isPageMention && isShareRoute ? slugId : undefined,
|
||||
|
||||
@@ -24,6 +24,7 @@ export function useFavoritesQuery(type?: FavoriteType, spaceId?: string) {
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.meta.hasNextPage ? lastPage.meta.nextCursor : undefined,
|
||||
refetchOnMount: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -31,6 +32,7 @@ export function useFavoriteIds(type: FavoriteType, spaceId?: string): Set<string
|
||||
const { data } = useQuery({
|
||||
queryKey: ["favorite-ids", type, spaceId],
|
||||
queryFn: () => getFavoriteIds(type, spaceId),
|
||||
refetchOnMount: true,
|
||||
});
|
||||
|
||||
const items = data?.items;
|
||||
|
||||
@@ -12,7 +12,7 @@ import { useAtomValue } from "jotai";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { extractPageSlugId } from "@/lib";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms.ts";
|
||||
import { useBacklinksCountQuery } from "@/features/page-details/queries/backlinks-query.ts";
|
||||
import { BacklinksModal } from "./backlinks-modal";
|
||||
@@ -23,7 +23,7 @@ import { LabelsSection } from "@/features/label/components/labels-section.tsx";
|
||||
|
||||
export function PageDetailsAside() {
|
||||
const { pageSlug } = useParams();
|
||||
const { data: page } = usePageMetaQuery({
|
||||
const { data: page } = usePageQuery({
|
||||
pageId: extractPageSlugId(pageSlug),
|
||||
});
|
||||
const pageEditor = useAtomValue(pageEditorAtom);
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { SpaceTreeNode } from "@/features/page/tree/types";
|
||||
|
||||
// breadcrumb.tsx transitively imports @/main.tsx (via usePageMetaQuery ->
|
||||
// queryClient), whose module body calls ReactDOM.createRoot on a null root in
|
||||
// jsdom. Stub it so importing the pure helper under test doesn't run that
|
||||
// (breadcrumbPathEqual does not use queryClient, so a dummy is enough).
|
||||
vi.mock("@/main.tsx", () => ({ queryClient: {} }));
|
||||
|
||||
import { breadcrumbPathEqual } from "./breadcrumb";
|
||||
|
||||
// breadcrumbPathEqual is the ONLY point where a false-positive equality would
|
||||
// leave a stale/incorrect breadcrumb trail on screen: it decides whether the
|
||||
// selectAtom hands back the same reference (no re-render) for the ancestor chain.
|
||||
// Pin both directions — a too-loose equality goes stale on a rename; a too-tight
|
||||
// one loses the perf win.
|
||||
const node = (over: Partial<SpaceTreeNode>): SpaceTreeNode =>
|
||||
({ id: "a", slugId: "sa", name: "A", icon: "📄", ...over }) as SpaceTreeNode;
|
||||
|
||||
describe("breadcrumbPathEqual", () => {
|
||||
it("both null → true", () => {
|
||||
expect(breadcrumbPathEqual(null, null)).toBe(true);
|
||||
});
|
||||
|
||||
it("same reference → true", () => {
|
||||
const p = [node({})];
|
||||
expect(breadcrumbPathEqual(p, p)).toBe(true);
|
||||
});
|
||||
|
||||
it("equal by id/slugId/name/icon (different arrays) → true", () => {
|
||||
expect(breadcrumbPathEqual([node({})], [node({})])).toBe(true);
|
||||
});
|
||||
|
||||
it("one side null → false", () => {
|
||||
expect(breadcrumbPathEqual([node({})], null)).toBe(false);
|
||||
expect(breadcrumbPathEqual(null, [node({})])).toBe(false);
|
||||
});
|
||||
|
||||
it("different length → false", () => {
|
||||
expect(
|
||||
breadcrumbPathEqual([node({})], [node({}), node({ id: "b" })]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["name", "icon", "slugId", "id"] as const)(
|
||||
"a changed %s → false (breadcrumb must re-render)",
|
||||
(field) => {
|
||||
expect(
|
||||
breadcrumbPathEqual([node({})], [node({ [field]: "CHANGED" })]),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,7 @@
|
||||
import { useAtomValue } from "jotai";
|
||||
import { selectAtom } from "jotai/utils";
|
||||
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom.ts";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { computeBreadcrumbState } from "./breadcrumb.utils";
|
||||
import { findBreadcrumbPath } from "@/features/page/tree/utils";
|
||||
import {
|
||||
Button,
|
||||
Anchor,
|
||||
@@ -20,7 +18,7 @@ import { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
||||
import { IPage } from "@/features/page/types/page.types.ts";
|
||||
import { buildPageUrl } from "@/features/page/page.utils.ts";
|
||||
import {
|
||||
usePageMetaQuery,
|
||||
usePageQuery,
|
||||
usePageBreadcrumbsQuery,
|
||||
} from "@/features/page/queries/page-query.ts";
|
||||
import { extractPageSlugId } from "@/lib";
|
||||
@@ -34,84 +32,39 @@ function getTitle(name: string, icon: string) {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equality over a breadcrumb chain by the only fields the breadcrumb renders
|
||||
* (id, slugId, name, icon). Lets the selectAtom below hand back the SAME
|
||||
* reference when an unrelated tree mutation leaves THIS page's ancestor chain
|
||||
* visually unchanged, so the breadcrumb no longer re-renders on every tree
|
||||
* event (it previously subscribed to the whole treeDataAtom).
|
||||
*/
|
||||
export function breadcrumbPathEqual(
|
||||
a: SpaceTreeNode[] | null,
|
||||
b: SpaceTreeNode[] | null,
|
||||
): boolean {
|
||||
if (a === b) return true;
|
||||
if (!a || !b || a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (
|
||||
a[i].id !== b[i].id ||
|
||||
a[i].slugId !== b[i].slugId ||
|
||||
a[i].name !== b[i].name ||
|
||||
a[i].icon !== b[i].icon
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export default function Breadcrumb() {
|
||||
const { t } = useTranslation();
|
||||
const treeData = useAtomValue(treeDataAtom);
|
||||
const [breadcrumbNodes, setBreadcrumbNodes] = useState<
|
||||
SpaceTreeNode[] | null
|
||||
>(null);
|
||||
const { pageSlug, spaceSlug } = useParams();
|
||||
const { data: currentPage } = usePageMetaQuery({
|
||||
const { data: currentPage } = usePageQuery({
|
||||
pageId: extractPageSlugId(pageSlug),
|
||||
});
|
||||
const currentPageId = currentPage?.id;
|
||||
// The page's own ancestor chain, fetched independently of the lazily-built
|
||||
// sidebar tree so a deep page doesn't render a blank breadcrumb for seconds
|
||||
// while the tree backfills (#218).
|
||||
const { data: ancestors } = usePageBreadcrumbsQuery(currentPageId);
|
||||
const { data: ancestors } = usePageBreadcrumbsQuery(currentPage?.id);
|
||||
const isMobile = useMediaQuery("(max-width: 48em)");
|
||||
|
||||
// Narrowed subscription: instead of subscribing to the whole treeDataAtom and
|
||||
// recomputing on every tree event, derive ONLY the current page's ancestor
|
||||
// chain. The custom equality returns the previous reference when that chain is
|
||||
// visually unchanged, so an unrelated tree mutation no longer re-renders this
|
||||
// component. Mirrors computeBreadcrumbState's tree-hit branch
|
||||
// (findBreadcrumbPath); the tree-miss/ancestors fallback is applied below.
|
||||
const treePathAtom = useMemo(
|
||||
() =>
|
||||
selectAtom(
|
||||
treeDataAtom,
|
||||
(tree): SpaceTreeNode[] | null =>
|
||||
currentPageId ? findBreadcrumbPath(tree, currentPageId) : null,
|
||||
breadcrumbPathEqual,
|
||||
),
|
||||
[currentPageId],
|
||||
);
|
||||
const treePath = useAtomValue(treePathAtom);
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentPage) return;
|
||||
|
||||
// Selection/mapping + stale-clearing live in a pure, unit-tested helper
|
||||
// (#218). The tree-hit chain (treePath) always wins when present; otherwise
|
||||
// fall back to the page's own ancestors and the stale-clearing logic — this
|
||||
// reproduces computeBreadcrumbState(fullTree, ancestors, …) exactly, since
|
||||
// its tree-hit branch is precisely findBreadcrumbPath(fullTree, pageId).
|
||||
// (#218). It resolves the correct chain when possible and, on a transient
|
||||
// miss, clears a chain left over from a previously-viewed page instead of
|
||||
// showing the wrong trail — while keeping a chain already resolved for THIS
|
||||
// page to avoid a blank flash.
|
||||
setBreadcrumbNodes((previous) =>
|
||||
treePath ??
|
||||
computeBreadcrumbState(
|
||||
null,
|
||||
treeData,
|
||||
ancestors as IPage[] | undefined,
|
||||
currentPage.id,
|
||||
previous,
|
||||
),
|
||||
);
|
||||
}, [currentPage?.id, treePath, ancestors]);
|
||||
}, [currentPage?.id, treeData, ancestors]);
|
||||
|
||||
const HiddenNodesTooltipContent = () =>
|
||||
breadcrumbNodes?.slice(1, -1).map((node) => (
|
||||
|
||||
@@ -24,7 +24,7 @@ import { historyAtoms } from "@/features/page-history/atoms/history-atoms.ts";
|
||||
import { useDisclosure, useHotkeys } from "@mantine/hooks";
|
||||
import { useClipboard } from "@/hooks/use-clipboard";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import {
|
||||
useToggleTemporaryMutation,
|
||||
syncTemporaryExpiresInCache,
|
||||
@@ -67,7 +67,7 @@ export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
|
||||
const commentsTriggerProps = useAsideTriggerProps("comments");
|
||||
const tocTriggerProps = useAsideTriggerProps("toc");
|
||||
const { pageSlug } = useParams();
|
||||
const { data: page } = usePageMetaQuery({
|
||||
const { data: page } = usePageQuery({
|
||||
pageId: extractPageSlugId(pageSlug),
|
||||
});
|
||||
const isDeleted = !!page?.deletedAt;
|
||||
@@ -146,7 +146,7 @@ function PageActionMenu({ readOnly }: PageActionMenuProps) {
|
||||
const [, setHistoryModalOpen] = useAtom(historyAtoms);
|
||||
const clipboard = useClipboard({ timeout: 500 });
|
||||
const { pageSlug, spaceSlug } = useParams();
|
||||
const { data: page, isLoading } = usePageMetaQuery({
|
||||
const { data: page, isLoading } = usePageQuery({
|
||||
pageId: extractPageSlugId(pageSlug),
|
||||
});
|
||||
const { handleDelete } = useTreeMutation(page?.spaceId ?? "");
|
||||
|
||||
@@ -10,7 +10,7 @@ import { IconClockHour4, IconTrash } from "@tabler/icons-react";
|
||||
import { useState } from "react";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { useTreeMutation } from "@/features/page/tree/hooks/use-tree-mutation.ts";
|
||||
import {
|
||||
useToggleTemporaryMutation,
|
||||
@@ -35,7 +35,7 @@ type TemporaryNoteBannerProps = {
|
||||
*/
|
||||
export function TemporaryNoteBanner({ slugId }: TemporaryNoteBannerProps) {
|
||||
const { t } = useTranslation();
|
||||
const { data: page } = usePageMetaQuery({ pageId: slugId });
|
||||
const { data: page } = usePageQuery({ pageId: slugId });
|
||||
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
||||
const spaceAbility = useSpaceAbility(space?.membership?.permissions);
|
||||
const expiresTimeAgo = useTimeAgo(page?.temporaryExpiresAt);
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import type { IPage } from "@/features/page/types/page.types";
|
||||
|
||||
// A fresh QueryClient stands in for the app singleton (importing the real
|
||||
// @/main.tsx would run ReactDOM.createRoot, which has no DOM root in jsdom). The
|
||||
// factory constructs it (QueryClient can't be referenced in vi.hoisted — that
|
||||
// runs before imports resolve); we import the SAME mocked instance back to seed
|
||||
// and assert on it.
|
||||
vi.mock("@/main.tsx", async () => {
|
||||
const { QueryClient } = await import("@tanstack/react-query");
|
||||
return { queryClient: new QueryClient() };
|
||||
});
|
||||
|
||||
import { queryClient as h_qc } from "@/main.tsx";
|
||||
import { invalidateOnUpdatePage } from "./page-query";
|
||||
|
||||
const h = { qc: h_qc };
|
||||
|
||||
// invalidateOnUpdatePage is the field-only (title/icon) tree path: instead of a
|
||||
// blanket invalidate it patches the affected node IN PLACE in every cached embed
|
||||
// subtree. The undefined-guard is LOAD-BEARING: a title-only socket event carries
|
||||
// icon:undefined, and without the guard `{...p, icon: undefined}` would WIPE the
|
||||
// icon in every cached subtree.
|
||||
const page = (over: Partial<IPage>): IPage =>
|
||||
({ id: "p1", title: "Old", icon: "📄", spaceId: "s1" }) as IPage &
|
||||
typeof over as IPage;
|
||||
|
||||
describe("invalidateOnUpdatePage — pointwise embed-cache patch", () => {
|
||||
beforeEach(() => {
|
||||
h.qc.clear();
|
||||
});
|
||||
|
||||
it("title-only event updates title but PRESERVES the icon (undefined-guard)", () => {
|
||||
const key = ["page-tree", "parent-1"];
|
||||
h.qc.setQueryData<IPage[]>(key, [
|
||||
{ id: "p1", title: "Old", icon: "📄", spaceId: "s1" } as IPage,
|
||||
{ id: "p2", title: "Other", icon: "📁", spaceId: "s1" } as IPage,
|
||||
]);
|
||||
|
||||
// icon passed as undefined (a title-only update)
|
||||
invalidateOnUpdatePage(
|
||||
"s1",
|
||||
"parent-1",
|
||||
"p1",
|
||||
"New Title",
|
||||
undefined as unknown as string,
|
||||
);
|
||||
|
||||
const patched = h.qc.getQueryData<IPage[]>(key)!;
|
||||
const p1 = patched.find((p) => p.id === "p1")!;
|
||||
const p2 = patched.find((p) => p.id === "p2")!;
|
||||
expect(p1.title).toBe("New Title");
|
||||
expect(p1.icon).toBe("📄"); // preserved, not wiped
|
||||
// Sibling node untouched.
|
||||
expect(p2.title).toBe("Other");
|
||||
expect(p2.icon).toBe("📁");
|
||||
});
|
||||
|
||||
it("icon-only event updates icon but preserves the title", () => {
|
||||
const key = ["page-tree", "parent-1"];
|
||||
h.qc.setQueryData<IPage[]>(key, [
|
||||
{ id: "p1", title: "Keep", icon: "📄", spaceId: "s1" } as IPage,
|
||||
]);
|
||||
|
||||
invalidateOnUpdatePage(
|
||||
"s1",
|
||||
"parent-1",
|
||||
"p1",
|
||||
undefined as unknown as string,
|
||||
"🚀",
|
||||
);
|
||||
|
||||
const p1 = h.qc.getQueryData<IPage[]>(key)!.find((p) => p.id === "p1")!;
|
||||
expect(p1.icon).toBe("🚀");
|
||||
expect(p1.title).toBe("Keep");
|
||||
});
|
||||
|
||||
it("does not touch a subtree that lacks the updated node", () => {
|
||||
const otherKey = ["page-tree", "unrelated"];
|
||||
const before = [
|
||||
{ id: "x1", title: "X", icon: "❌", spaceId: "s1" } as IPage,
|
||||
];
|
||||
h.qc.setQueryData<IPage[]>(otherKey, before);
|
||||
|
||||
invalidateOnUpdatePage("s1", "parent-1", "p1", "New", "🚀");
|
||||
|
||||
// Same reference back — the subtree without p1 is left as-is.
|
||||
expect(h.qc.getQueryData<IPage[]>(otherKey)).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -51,10 +51,6 @@ export function usePageQuery(
|
||||
queryFn: () => getPageById(pageInput),
|
||||
enabled: !!pageInput.pageId,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
// Keep the previously-loaded page visible while navigating to a new one
|
||||
// instead of flashing a blank/skeleton frame (the new page's content
|
||||
// streams in when ready). isLoading stays true only for the very first load.
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -70,61 +66,6 @@ export function usePageQuery(
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* A page view that omits the large, frequently-changing `content` field. Every
|
||||
* other field is preserved, so consumers that read only metadata (title, icon,
|
||||
* permissions, id, creator, timestamps, …) keep working unchanged.
|
||||
*/
|
||||
export type IPageMeta = Omit<IPage, "content">;
|
||||
|
||||
function selectPageMeta(page: IPage): IPageMeta {
|
||||
// Drop `content`; react-query's structural sharing (replaceEqualDeep) then
|
||||
// returns the SAME reference whenever the remaining fields are unchanged, so a
|
||||
// pure content churn (typing / debouncedUpdateContent, collab `page.updated`)
|
||||
// no longer changes this slice's identity and its ~13 subscribers don't
|
||||
// re-render on every keystroke wave.
|
||||
const { content: _content, ...meta } = page;
|
||||
return meta as IPageMeta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata-only variant of {@link usePageQuery}. Shares the SAME query cache
|
||||
* entry (`["pages", pageId]`, full object incl. content), but this hook returns
|
||||
* a stable content-less slice so peripheral subscribers stop re-rendering on
|
||||
* every content update. Use it anywhere the full `content` is not read.
|
||||
*/
|
||||
export function usePageMetaQuery(
|
||||
pageInput: Partial<IPageInput>,
|
||||
): UseQueryResult<IPageMeta, Error> {
|
||||
const query = useQuery({
|
||||
queryKey: ["pages", pageInput.pageId],
|
||||
queryFn: () => getPageById(pageInput),
|
||||
enabled: !!pageInput.pageId,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
select: selectPageMeta,
|
||||
// Match usePageQuery: keep the previous page's metadata visible while
|
||||
// navigating so the periphery (header, breadcrumb, …) doesn't flash blank.
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
|
||||
// Mirror usePageQuery's cross-key alias write so a page fetched by one
|
||||
// identifier is also cached under the other. The cache stores the FULL page
|
||||
// (select only narrows what THIS hook returns), so read the full object back
|
||||
// from the cache and alias THAT — never the content-less slice.
|
||||
useEffect(() => {
|
||||
if (!query.data) return;
|
||||
const full = queryClient.getQueryData<IPage>(["pages", pageInput.pageId]);
|
||||
if (!full) return;
|
||||
if (isValidUuid(pageInput.pageId)) {
|
||||
queryClient.setQueryData(["pages", full.slugId], full);
|
||||
} else {
|
||||
queryClient.setQueryData(["pages", full.id], full);
|
||||
}
|
||||
}, [query.data]);
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
export function useCreatePageMutation() {
|
||||
const { t } = useTranslation();
|
||||
return useMutation<IPage, Error, Partial<IPageInput>>({
|
||||
@@ -410,12 +351,6 @@ export function useRecentChangesQuery(spaceId?: string) {
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.meta.hasNextPage ? lastPage.meta.nextCursor : undefined,
|
||||
// KEEP refetchOnMount:true (against the global default false): recent-changes
|
||||
// IS invalidated on page create/update/move/delete, but invalidateQueries only
|
||||
// marks an UNMOUNTED query stale — it doesn't refetch it. The widget isn't
|
||||
// always mounted, so an event that lands while it's unmounted leaves it stale,
|
||||
// and the global refetchOnMount:false would not re-fetch on remount. The mount
|
||||
// refetch closes that gap.
|
||||
refetchOnMount: true,
|
||||
});
|
||||
}
|
||||
@@ -432,9 +367,6 @@ export function useCreatedByQuery(params?: {
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.meta.hasNextPage ? lastPage.meta.nextCursor : undefined,
|
||||
// KEEP refetchOnMount:true: the "created-by" key is never invalidated (no
|
||||
// socket/mutation path), so the mount refetch is its ONLY freshness mechanism
|
||||
// — without it the list shows stale cache on navigation.
|
||||
refetchOnMount: true,
|
||||
});
|
||||
}
|
||||
@@ -448,14 +380,8 @@ export function useDeletedPagesQuery(
|
||||
queryFn: () => getDeletedPages(spaceId, params),
|
||||
enabled: !!spaceId,
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 0,
|
||||
// KEEP refetchOnMount:true: ["trash-list"] IS invalidated by the
|
||||
// move-to-trash / delete / restore mutations, but invalidateQueries only marks
|
||||
// an unmounted query stale — it doesn't refetch it. The trash panel isn't
|
||||
// usually mounted when a page is trashed, so on opening it the global
|
||||
// refetchOnMount:false would show a stale list; the mount refetch closes that.
|
||||
// (Do NOT remove the three trash-list invalidations — they are not dead code.)
|
||||
refetchOnMount: true,
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -590,35 +516,7 @@ export function invalidateOnUpdatePage(
|
||||
title: string,
|
||||
icon: string,
|
||||
) {
|
||||
// Scoped page-tree refresh (was a blanket `invalidatePageTree()`): this is the
|
||||
// FIELD-only update path (title/icon — no structural change), and the sidebar
|
||||
// tree is already updated pointwise (applyUpdateOne / optimistic setData) plus
|
||||
// via the sidebar-pages cache below. Invalidating ALL ["page-tree"] queries
|
||||
// here refetched every open recursive subpages-embed block on each
|
||||
// rename/icon-change — pure duplicate work. Instead patch just the affected
|
||||
// node IN PLACE in every cached embed subtree: same visible result, no network
|
||||
// churn, no full embed-tree rebuild. Structural events (create/move/delete)
|
||||
// keep the blanket invalidate in their own helpers.
|
||||
const pageTreeMatches = queryClient.getQueriesData<IPage[]>({
|
||||
queryKey: ["page-tree"],
|
||||
});
|
||||
pageTreeMatches.forEach(([key, items]) => {
|
||||
if (!items || !items.some((p) => p.id === id)) return;
|
||||
queryClient.setQueryData<IPage[]>(key, (old) =>
|
||||
old?.map((p) =>
|
||||
p.id === id
|
||||
? {
|
||||
...p,
|
||||
// Guard undefined so a title-only event can't wipe the icon (and
|
||||
// vice versa) in the embed cache.
|
||||
...(title !== undefined ? { title } : {}),
|
||||
...(icon !== undefined ? { icon } : {}),
|
||||
}
|
||||
: p,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
invalidatePageTree();
|
||||
let queryKey: QueryKey = null;
|
||||
if (parentPageId === null) {
|
||||
queryKey = ["root-sidebar-pages", spaceId];
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useRestorePageModal } from "@/features/page/hooks/use-restore-page-moda
|
||||
import { useDeletePageModal } from "@/features/page/hooks/use-delete-page-modal.tsx";
|
||||
import {
|
||||
useDeletePageMutation,
|
||||
usePageMetaQuery,
|
||||
usePageQuery,
|
||||
useRestorePageMutation,
|
||||
} from "@/features/page/queries/page-query.ts";
|
||||
import { getSpaceUrl } from "@/lib/config.ts";
|
||||
@@ -25,7 +25,7 @@ type DeletedPageBannerProps = {
|
||||
export function DeletedPageBanner({ slugId }: DeletedPageBannerProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { data: page } = usePageMetaQuery({ pageId: slugId });
|
||||
const { data: page } = usePageQuery({ pageId: slugId });
|
||||
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
||||
const spaceAbility = useSpaceAbility(space?.membership?.permissions);
|
||||
const deletedTimeAgo = useTimeAgo(page?.deletedAt);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useSetAtom, useStore } from "jotai";
|
||||
import { useAtom } from "jotai";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { ActionIcon, Menu, rem } from "@mantine/core";
|
||||
@@ -52,11 +52,7 @@ export function NodeMenu({ node, canEdit }: NodeMenuProps) {
|
||||
const clipboard = useClipboard({ timeout: 500 });
|
||||
const { spaceSlug } = useParams();
|
||||
const { handleDelete } = useTreeMutation(node.spaceId);
|
||||
// Setter-only: the tree value is read only imperatively inside the duplicate
|
||||
// handler (via `store` below), never at render, so useSetAtom avoids
|
||||
// re-rendering every row's NodeMenu on any tree event.
|
||||
const setData = useSetAtom(treeDataAtom);
|
||||
const store = useStore();
|
||||
const [data, setData] = useAtom(treeDataAtom);
|
||||
const emit = useQueryEmit();
|
||||
const [exportOpened, { open: openExportModal, close: closeExportModal }] =
|
||||
useDisclosure(false);
|
||||
@@ -129,8 +125,8 @@ export function NodeMenu({ node, canEdit }: NodeMenuProps) {
|
||||
try {
|
||||
const duplicatedPage = await duplicatePage({ pageId: node.id });
|
||||
|
||||
// figure out parent + insertion index (read the live tree imperatively)
|
||||
const siblings = treeModel.siblingsOf(store.get(treeDataAtom), node.id);
|
||||
// figure out parent + insertion index
|
||||
const siblings = treeModel.siblingsOf(data, node.id);
|
||||
const parentId = siblings?.parentId ?? null;
|
||||
const currentIndex = siblings?.index ?? 0;
|
||||
const newIndex = currentIndex + 1;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useRef } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { useAtom, useSetAtom } from "jotai";
|
||||
import { useAtom } from "jotai";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionIcon, rem, Tooltip } from "@mantine/core";
|
||||
import {
|
||||
@@ -51,11 +51,7 @@ export function SpaceTreeRow({
|
||||
const { t } = useTranslation();
|
||||
const { spaceSlug } = useParams();
|
||||
const updatePageMutation = useUpdatePageMutation();
|
||||
// Setter-only: subscribing to the whole treeDataAtom (via useAtom) re-rendered
|
||||
// every virtualized row on any tree event, bypassing the DocTreeRow memo. This
|
||||
// row never reads the tree value, only writes it, so useSetAtom avoids the
|
||||
// value subscription.
|
||||
const setTreeData = useSetAtom(treeDataAtom);
|
||||
const [, setTreeData] = useAtom(treeDataAtom);
|
||||
const emit = useQueryEmit();
|
||||
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [mobileSidebarOpened] = useAtom(mobileSidebarAtom);
|
||||
|
||||
@@ -35,7 +35,6 @@ vi.mock("@/features/page/queries/page-query.ts", () => ({
|
||||
isFetching: false,
|
||||
}),
|
||||
usePageQuery: () => ({ data: undefined }),
|
||||
usePageMetaQuery: () => ({ data: undefined }),
|
||||
fetchAllAncestorChildren: (...args: unknown[]) =>
|
||||
fetchAllAncestorChildrenMock(...args),
|
||||
}));
|
||||
|
||||
@@ -26,7 +26,6 @@ vi.mock("@/features/page/queries/page-query.ts", () => ({
|
||||
isFetching: false,
|
||||
}),
|
||||
usePageQuery: () => ({ data: undefined }),
|
||||
usePageMetaQuery: () => ({ data: undefined }),
|
||||
fetchAllAncestorChildren: vi.fn(),
|
||||
}));
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { notifications } from "@mantine/notifications";
|
||||
import {
|
||||
fetchAllAncestorChildren,
|
||||
useGetRootSidebarPagesQuery,
|
||||
usePageMetaQuery,
|
||||
usePageQuery,
|
||||
} from "@/features/page/queries/page-query.ts";
|
||||
import classes from "@/features/page/tree/styles/tree.module.css";
|
||||
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom.ts";
|
||||
@@ -76,7 +76,7 @@ const SpaceTree = forwardRef<SpaceTreeApi, SpaceTreeProps>(function SpaceTree(
|
||||
const [isDataLoaded, setIsDataLoaded] = useState(false);
|
||||
const spaceIdRef = useRef(spaceId);
|
||||
spaceIdRef.current = spaceId;
|
||||
const { data: currentPage } = usePageMetaQuery({
|
||||
const { data: currentPage } = usePageQuery({
|
||||
pageId: extractPageSlugId(pageSlug),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback } from "react";
|
||||
import { useSetAtom, useStore } from "jotai";
|
||||
import { useAtom, useSetAtom, useStore } from "jotai";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
@@ -34,10 +34,7 @@ export type UseTreeMutation = {
|
||||
|
||||
export function useTreeMutation(spaceId: string): UseTreeMutation {
|
||||
const { t } = useTranslation();
|
||||
// Setter-only: this hook never reads the tree reactively (handlers read the
|
||||
// live value imperatively via `store` below), so useSetAtom avoids
|
||||
// re-rendering SpaceSidebar on every tree event.
|
||||
const setData = useSetAtom(treeDataAtom);
|
||||
const [, setData] = useAtom(treeDataAtom);
|
||||
// `store` reads the *current* treeDataAtom imperatively in handlers — avoids
|
||||
// stale-closure issues when the caller updates the tree (e.g. lazy-load
|
||||
// children) and then immediately invokes a handler.
|
||||
|
||||
@@ -28,7 +28,6 @@ vi.mock("@/features/share/queries/share-query.ts", () => ({
|
||||
|
||||
vi.mock("@/features/page/queries/page-query.ts", () => ({
|
||||
usePageQuery: () => ({ data: { id: "page-1", title: "Doc" } }),
|
||||
usePageMetaQuery: () => ({ data: { id: "page-1", title: "Doc" } }),
|
||||
}));
|
||||
|
||||
vi.mock("@/features/space/queries/space-query.ts", () => ({
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { extractPageSlugId, getPageIcon } from "@/lib";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||
import CopyTextButton from "@/components/common/copy.tsx";
|
||||
import { getAppUrl } from "@/lib/config.ts";
|
||||
import { buildPageUrl } from "@/features/page/page.utils.ts";
|
||||
@@ -37,7 +37,7 @@ export default function ShareModal({ readOnly }: ShareModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const { pageSlug } = useParams();
|
||||
const pageSlugId = extractPageSlugId(pageSlug);
|
||||
const { data: page } = usePageMetaQuery({ pageId: pageSlugId });
|
||||
const { data: page } = usePageQuery({ pageId: pageSlugId });
|
||||
const pageId = page?.id;
|
||||
const { data: share } = useShareForPageQuery(pageId);
|
||||
const { spaceSlug } = useParams();
|
||||
|
||||
@@ -38,11 +38,6 @@ export function useGetSpacesQuery(
|
||||
queryKey: ["spaces", params],
|
||||
queryFn: () => getSpaces(params),
|
||||
placeholderData: keepPreviousData,
|
||||
// KEEP refetchOnMount:true (against the global default false): the ["spaces"]
|
||||
// key is invalidated only by same-tab mutations (no socket path), so a
|
||||
// cross-actor change — an admin adding/removing THIS user from a space — has
|
||||
// no local mutation or socket event and would leave the space list stale until
|
||||
// a hard reload. The mount refetch is its only cross-actor freshness path.
|
||||
refetchOnMount: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export function useWatchedSpaceIds(): Set<string> {
|
||||
const { data } = useQuery({
|
||||
queryKey: [WATCHED_SPACE_IDS_KEY],
|
||||
queryFn: () => getWatchedSpaceIds(),
|
||||
refetchOnMount: true,
|
||||
});
|
||||
|
||||
const items = data?.items;
|
||||
|
||||
@@ -19,11 +19,7 @@ export const useQuerySubscription = () => {
|
||||
const [socket] = useAtom(socketAtom);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!socket) return;
|
||||
// Named handler + off() cleanup (mirrors use-notification-socket). Without
|
||||
// cleanup, every socket recreation / effect re-run stacked another listener,
|
||||
// so a single broadcast fired duplicated invalidateQueries / setQueryData.
|
||||
const handleMessage = (event) => {
|
||||
socket?.on("message", (event) => {
|
||||
const data: WebSocketEvent = event;
|
||||
|
||||
let entity = null;
|
||||
@@ -167,11 +163,6 @@ export const useQuerySubscription = () => {
|
||||
});
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
socket.on("message", handleMessage);
|
||||
return () => {
|
||||
socket.off("message", handleMessage);
|
||||
};
|
||||
});
|
||||
}, [queryClient, socket]);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect } from "react";
|
||||
import { socketAtom } from "@/features/websocket/atoms/socket-atom.ts";
|
||||
import { useAtom, useSetAtom } from "jotai";
|
||||
import { useAtom } from "jotai";
|
||||
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom.ts";
|
||||
import { WebSocketEvent } from "@/features/websocket/types";
|
||||
import { SpaceTreeNode } from "@/features/page/tree/types.ts";
|
||||
@@ -16,10 +16,7 @@ import localEmitter from "@/lib/local-emitter.ts";
|
||||
|
||||
export const useTreeSocket = () => {
|
||||
const [socket] = useAtom(socketAtom);
|
||||
// Setter-only: this hook writes the tree from socket events but never reads it
|
||||
// reactively, so useSetAtom avoids re-rendering UserProvider (its host) on
|
||||
// every tree event.
|
||||
const setTreeData = useSetAtom(treeDataAtom);
|
||||
const [, setTreeData] = useAtom(treeDataAtom);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -40,11 +37,7 @@ export const useTreeSocket = () => {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!socket) return;
|
||||
// Named handler + off() cleanup (mirrors use-notification-socket). Without
|
||||
// cleanup, every socket recreation / effect re-run stacked another listener,
|
||||
// so a single broadcast fired duplicated tree walks after each reconnect.
|
||||
const handleMessage = (event: WebSocketEvent) => {
|
||||
socket?.on("message", (event: WebSocketEvent) => {
|
||||
switch (event.operation) {
|
||||
case "updateOne":
|
||||
if (event.entity[0] === "pages") {
|
||||
@@ -71,11 +64,6 @@ export const useTreeSocket = () => {
|
||||
});
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
socket.on("message", handleMessage);
|
||||
return () => {
|
||||
socket.off("message", handleMessage);
|
||||
};
|
||||
}, [socket, queryClient, setTreeData]);
|
||||
});
|
||||
}, [socket]);
|
||||
};
|
||||
|
||||
@@ -243,5 +243,6 @@ export function useAppVersion(
|
||||
queryFn: () => getAppVersion(),
|
||||
staleTime: 60 * 60 * 1000, // 1 hr
|
||||
enabled: isEnabled,
|
||||
refetchOnMount: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useEffect } from "react";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query";
|
||||
import { usePageQuery } from "@/features/page/queries/page-query";
|
||||
import { buildPageUrl } from "@/features/page/page.utils.ts";
|
||||
import { extractPageSlugId } from "@/lib";
|
||||
import { Error404 } from "@/components/ui/error-404.tsx";
|
||||
@@ -11,7 +11,7 @@ export default function PageRedirect() {
|
||||
data: page,
|
||||
isLoading: pageIsLoading,
|
||||
isError,
|
||||
} = usePageMetaQuery({ pageId: extractPageSlugId(pageSlug) });
|
||||
} = usePageQuery({ pageId: extractPageSlugId(pageSlug) });
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useTranslation } from "react-i18next";
|
||||
import React from "react";
|
||||
import { EmptyState } from "@/components/ui/empty-state.tsx";
|
||||
import { IconAlertTriangle, IconFileOff } from "@tabler/icons-react";
|
||||
import { Button, Skeleton } from "@mantine/core";
|
||||
import { Button } from "@mantine/core";
|
||||
import { Link } from "react-router-dom";
|
||||
import { ErrorBoundary } from "react-error-boundary";
|
||||
const MemoizedFullEditor = React.memo(FullEditor);
|
||||
@@ -58,7 +58,7 @@ function PageContent({ pageSlug }: { pageSlug: string | undefined }) {
|
||||
(space?.settings?.comments?.allowViewerComments === true);
|
||||
|
||||
if (isLoading) {
|
||||
return <PageSkeleton />;
|
||||
return <></>;
|
||||
}
|
||||
|
||||
if (isError || !page) {
|
||||
@@ -87,7 +87,7 @@ function PageContent({ pageSlug }: { pageSlug: string | undefined }) {
|
||||
}
|
||||
|
||||
if (!space) {
|
||||
return <PageSkeleton />;
|
||||
return <></>;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -116,18 +116,3 @@ function PageContent({ pageSlug }: { pageSlug: string | undefined }) {
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Lightweight loading placeholder shown instead of a blank fragment while the
|
||||
// page (or its space) is loading, so navigation into a not-yet-cached page no
|
||||
// longer flashes empty. Approximates the title + first content lines.
|
||||
function PageSkeleton() {
|
||||
return (
|
||||
<div>
|
||||
<Skeleton height={34} width="45%" mt="xl" radius="sm" />
|
||||
<Skeleton height={16} mt="xl" radius="sm" />
|
||||
<Skeleton height={16} mt="sm" radius="sm" />
|
||||
<Skeleton height={16} mt="sm" width="85%" radius="sm" />
|
||||
<Skeleton height={16} mt="sm" width="70%" radius="sm" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -55,10 +55,15 @@ describe('stabilizePageFile — normalize-on-write fixpoint (SPEC §11)', () =>
|
||||
const file2 = await stabilizePageFile(doc2, meta);
|
||||
expect(file2).toBe(file1);
|
||||
|
||||
// The materialized diagram default is present in the stabilized body (proof
|
||||
// that the convergence pass actually ran, not just that two naive exports
|
||||
// happened to match).
|
||||
expect(body1).toContain('data-align="center"');
|
||||
// The drawio node was materialized to its canonical HTML form by the
|
||||
// convergence pass — a bare `{ src }` doc node becomes the full
|
||||
// `<div data-type="drawio" data-src=...>` — proof the pass actually ran, not
|
||||
// just two naive exports happening to match. Assert on the stable canonical
|
||||
// markers rather than `data-align="center"`: center is a schema default the
|
||||
// converter may omit (see prosemirror-markdown media-html.ts), so it is not
|
||||
// a reliable convergence proof.
|
||||
expect(body1).toContain('data-type="drawio"');
|
||||
expect(body1).toContain('data-src="/d.drawio"');
|
||||
});
|
||||
|
||||
it('already-stable content is unchanged by the pass (idempotent)', async () => {
|
||||
|
||||
@@ -48,6 +48,52 @@ export interface ConvertProseMirrorToMarkdownOptions {
|
||||
dropResolvedCommentAnchors?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjacent sibling lists that share a markdown MARKER FAMILY re-parse as ONE
|
||||
* merged list — bulletList and taskList both emit `- ` markers (→ a single
|
||||
* `<ul>`), and two orderedLists both emit `1.` markers (→ a single `<ol>`). The
|
||||
* cross-type case is real data loss the editor CAN produce (e.g. a taskList
|
||||
* followed by a bulletList: the merged `<ul>` has a mix of checkbox and plain
|
||||
* items, so `bridgeTaskLists` refuses to convert it and every taskItem loses its
|
||||
* checkbox). Between two such adjacent list children we emit an empty HTML comment
|
||||
* `<!-- -->`: marked renders it as its own HTML block that interrupts the list, so
|
||||
* the two lists stay distinct; on import the comment is inert (parseAttachedComment
|
||||
* → null) and dropped by generateJSON, and re-export re-inserts it, so the marker
|
||||
* is byte-stable. It fires ONLY between two adjacent same-family list nodes — no
|
||||
* separator is emitted for any other join, so non-list output is unchanged.
|
||||
*/
|
||||
const LIST_MARKER_SEPARATOR = "<!-- -->";
|
||||
function listMarkerFamily(type: string | undefined): "ul" | "ol" | null {
|
||||
if (type === "bulletList" || type === "taskList") return "ul";
|
||||
if (type === "orderedList") return "ol";
|
||||
return null;
|
||||
}
|
||||
function adjacentListsMerge(
|
||||
prevType: string | undefined,
|
||||
curType: string | undefined,
|
||||
): boolean {
|
||||
const a = listMarkerFamily(prevType);
|
||||
return a !== null && a === listMarkerFamily(curType);
|
||||
}
|
||||
/**
|
||||
* Render each block child, inserting a `<!-- -->` separator entry between any two
|
||||
* adjacent same-marker-family list nodes (see LIST_MARKER_SEPARATOR). Callers
|
||||
* join the returned strings with their own context separator.
|
||||
*/
|
||||
function renderBlockChildren(
|
||||
children: any[],
|
||||
render: (n: any) => string,
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
let prevType: string | undefined;
|
||||
for (const child of children) {
|
||||
if (adjacentListsMerge(prevType, child?.type)) out.push(LIST_MARKER_SEPARATOR);
|
||||
out.push(render(child));
|
||||
prevType = child?.type;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ProseMirror/TipTap JSON content to Markdown
|
||||
* Supports all Docmost-specific node types and extensions
|
||||
@@ -347,9 +393,15 @@ export function convertProseMirrorToMarkdown(
|
||||
// lossless (the body survives) and byte-stable (it re-exports identically),
|
||||
// so it is deliberately not treated as data loss.
|
||||
const parts: string[] = [];
|
||||
let prevDocType: string | undefined;
|
||||
for (const child of nodeContent) {
|
||||
if (child?.type === "footnotesList") continue;
|
||||
// Keep adjacent same-family sibling lists distinct (see renderBlockChildren).
|
||||
if (adjacentListsMerge(prevDocType, child?.type)) {
|
||||
parts.push(LIST_MARKER_SEPARATOR);
|
||||
}
|
||||
parts.push(processNode(child));
|
||||
prevDocType = child?.type;
|
||||
}
|
||||
for (const [id, def] of footnoteDefs) {
|
||||
if (!referencedFootnoteIds.has(id)) {
|
||||
@@ -599,20 +651,34 @@ export function convertProseMirrorToMarkdown(
|
||||
return processTaskItem(node);
|
||||
|
||||
case "listItem":
|
||||
return nodeContent.map(processNode).join("\n");
|
||||
// Direct-listItem path (lists normally render via processListItem, which
|
||||
// handles the marker + indentation). Blank line between block children so
|
||||
// multiple paragraphs do not merge on re-parse; a `<!-- -->` entry
|
||||
// (renderBlockChildren) separates adjacent sibling lists.
|
||||
return renderBlockChildren(nodeContent, processNode).join("\n\n");
|
||||
|
||||
case "blockquote":
|
||||
case "blockquote": {
|
||||
// Prefix EVERY line of EVERY child with "> " and separate block-level
|
||||
// children with a blank ">" line so code blocks / multi-paragraph
|
||||
// quotes round-trip correctly.
|
||||
return nodeContent
|
||||
.map((n: any) =>
|
||||
// quotes round-trip correctly. A `> <!-- -->` separator line is inserted
|
||||
// between two adjacent same-family sibling lists (renderBlockChildren)
|
||||
// so they stay distinct inside the quote.
|
||||
const bqParts: string[] = [];
|
||||
let prevBqType: string | undefined;
|
||||
for (const n of nodeContent) {
|
||||
if (adjacentListsMerge(prevBqType, n?.type)) {
|
||||
bqParts.push(`> ${LIST_MARKER_SEPARATOR}`);
|
||||
}
|
||||
bqParts.push(
|
||||
processNode(n)
|
||||
.split("\n")
|
||||
.map((line: string) => (line.length ? `> ${line}` : ">"))
|
||||
.join("\n"),
|
||||
)
|
||||
.join("\n>\n");
|
||||
);
|
||||
prevBqType = n?.type;
|
||||
}
|
||||
return bqParts.join("\n>\n");
|
||||
}
|
||||
|
||||
case "horizontalRule":
|
||||
return "---";
|
||||
@@ -787,9 +853,12 @@ export function convertProseMirrorToMarkdown(
|
||||
// blockquote-prefixed; a blank line becomes a bare `>` so the callout is
|
||||
// not split.
|
||||
const calloutType = (node.attrs?.type || "info").toLowerCase();
|
||||
const calloutBody = nodeContent
|
||||
.map(processNode)
|
||||
.join("\n")
|
||||
const calloutBody = renderBlockChildren(nodeContent, processNode)
|
||||
// Blank line between block children (rendered as a bare `>` after the
|
||||
// prefix pass below) so multiple paragraphs stay separate nodes instead
|
||||
// of merging on re-parse — same rule blockquote already uses. A
|
||||
// `<!-- -->` entry (renderBlockChildren) separates adjacent sibling lists.
|
||||
.join("\n\n")
|
||||
.split("\n")
|
||||
.map((l: string) => (l.length ? `> ${l}` : ">"))
|
||||
.join("\n");
|
||||
@@ -809,7 +878,10 @@ export function convertProseMirrorToMarkdown(
|
||||
return `<summary>${renderInlineChildren(nodeContent)}</summary>\n\n`;
|
||||
|
||||
case "detailsContent":
|
||||
return `${nodeContent.map(processNode).join("\n")}\n`;
|
||||
// Blank line between block children so multiple paragraphs in a details
|
||||
// body survive as separate nodes (a single "\n" merges them on re-parse);
|
||||
// a `<!-- -->` entry (renderBlockChildren) separates adjacent sibling lists.
|
||||
return `${renderBlockChildren(nodeContent, processNode).join("\n\n")}\n`;
|
||||
|
||||
case "mathInline": {
|
||||
// #293 canon #6: inline math serializes as Obsidian-native `$LaTeX$`
|
||||
@@ -1338,11 +1410,19 @@ export function convertProseMirrorToMarkdown(
|
||||
// The code itself is element TEXT content (between <code> tags), so it
|
||||
// must escape < > & — NOT the attribute escaper. The language rides in
|
||||
// a class ATTRIBUTE, so it uses escapeAttr.
|
||||
//
|
||||
// Read the child text RAW (as `case "codeBlock"` does) and keep it
|
||||
// VERBATIM — do NOT strip the trailing newline. Unlike the markdown fence
|
||||
// path (which strips then relies on marked re-adding one `\n`), the schema
|
||||
// codeBlock parseHTML reads the `<code>` text content back byte-for-byte,
|
||||
// so stripping here would drop a trailing newline the node legitimately
|
||||
// carries and break the round trip inside a column/cell.
|
||||
const code = escapeHtmlText(
|
||||
children
|
||||
.map(processNode)
|
||||
.join("")
|
||||
.replace(/\n+$/, ""),
|
||||
.map((child: any) =>
|
||||
typeof child?.text === "string" ? child.text : "",
|
||||
)
|
||||
.join(""),
|
||||
);
|
||||
const cls = lang ? ` class="language-${escapeAttr(lang)}"` : "";
|
||||
return `<pre><code${cls}>${code}</code></pre>`;
|
||||
@@ -1484,6 +1564,13 @@ export function convertProseMirrorToMarkdown(
|
||||
const indent = " ".repeat(indentWidth);
|
||||
const lines: string[] = [];
|
||||
childStrings.forEach((child, childIndex) => {
|
||||
// Separate consecutive block children with a BLANK line so the item is a
|
||||
// CommonMark "loose" list item and each block stays its own node. Without
|
||||
// it, a second paragraph (`- a\n b`) is re-parsed as a lazy continuation
|
||||
// of the first and the two merge into one paragraph — silent data loss.
|
||||
// The blank line still sits INSIDE the item (the following block keeps the
|
||||
// continuation indent), so nested lists/code blocks remain nested.
|
||||
if (childIndex > 0) lines.push("");
|
||||
child.split("\n").forEach((line, lineIndex) => {
|
||||
if (childIndex === 0 && lineIndex === 0) {
|
||||
// First physical line of the first block gets the marker.
|
||||
@@ -1500,7 +1587,9 @@ export function convertProseMirrorToMarkdown(
|
||||
|
||||
const processListItem = (item: any, prefix: string): string => {
|
||||
const itemContent = item.content || [];
|
||||
const childStrings = itemContent.map(processNode);
|
||||
// A `<!-- -->` entry separates two adjacent same-family sublists inside the
|
||||
// item so they do not merge on re-parse (see renderBlockChildren).
|
||||
const childStrings = renderBlockChildren(itemContent, processNode);
|
||||
if (childStrings.length === 0) return prefix;
|
||||
// The rendered marker is `${prefix} ` (prefix + one space), so its width —
|
||||
// and thus the continuation indent — is prefix.length + 1. This is correct
|
||||
@@ -1514,7 +1603,9 @@ export function convertProseMirrorToMarkdown(
|
||||
const checkbox = checked ? "[x]" : "[ ]";
|
||||
const prefix = `- ${checkbox}`;
|
||||
const itemContent = item.content || [];
|
||||
const childStrings = itemContent.map(processNode);
|
||||
// A `<!-- -->` entry separates two adjacent same-family sublists inside the
|
||||
// item so they do not merge on re-parse (see renderBlockChildren).
|
||||
const childStrings = renderBlockChildren(itemContent, processNode);
|
||||
// An empty task item still needs its checkbox marker; without this guard
|
||||
// the indent below produces "" and the "- [ ]"/"- [x]" row disappears.
|
||||
if (childStrings.length === 0) return prefix;
|
||||
|
||||
@@ -270,9 +270,10 @@ const CALLOUT_CLOSE_RE = /^:::\s*$/;
|
||||
* optional title after the type is allowed but ignored (the Docmost callout
|
||||
* schema has no title). The body is the following contiguous blockquote lines.
|
||||
*/
|
||||
const CALLOUT_BQ_OPEN_RE = /^>\s*\[!(\w+)\]/;
|
||||
/** Matches any blockquote continuation line (`>` … ). */
|
||||
const BLOCKQUOTE_LINE_RE = /^>/;
|
||||
// The callout's own `>` marker may be preceded by an ENCLOSING container prefix:
|
||||
// list-item indentation (` `) and/or blockquote markers (`> `). Group 1 captures
|
||||
// that prefix (lazily, so the LAST `>` before `[!type]` is the callout's own).
|
||||
const CALLOUT_BQ_OPEN_RE = /^([>\s]*?)>\s*\[!(\w+)\]/;
|
||||
/** Matches the start/end of a code fence (``` or ~~~), capturing the marker. */
|
||||
const CODE_FENCE_RE = /^(\s*)(`{3,}|~{3,})/;
|
||||
|
||||
@@ -402,20 +403,47 @@ async function preprocessCallouts(markdown: string): Promise<string> {
|
||||
// recurse so nested callouts (`> > [!type]`) are handled, then emit the same
|
||||
// callout div the `:::` path produces. A normal blockquote (no `[!type]` on
|
||||
// its first line) does not match and stays a blockquote.
|
||||
//
|
||||
// PREFIX-aware: a callout nested inside a list item and/or a blockquote is
|
||||
// serialized with the enclosing container prefix in front of its own `>`
|
||||
// marker — ` > [!type]` (list indent) or `> > [!type]` (blockquote). We
|
||||
// capture that prefix, take only continuation lines carrying `prefix>`, strip
|
||||
// it, and re-apply the prefix to the emitted HTML block so the callout div
|
||||
// stays WITHIN its container (an unprefixed div would escape and re-parse as
|
||||
// a top-level callout / plain blockquote — silent structure loss).
|
||||
const bqOpen = line.match(CALLOUT_BQ_OPEN_RE);
|
||||
if (bqOpen) {
|
||||
const type = bqOpen[1].toLowerCase();
|
||||
const prefix = bqOpen[1];
|
||||
const type = bqOpen[2].toLowerCase();
|
||||
const cont = prefix + ">"; // a body line = prefix + the callout's own `>`
|
||||
const bodyLines: string[] = [];
|
||||
let j = i + 1;
|
||||
for (; j < lines.length; j++) {
|
||||
if (!BLOCKQUOTE_LINE_RE.test(lines[j])) break;
|
||||
bodyLines.push(lines[j].replace(/^>\s?/, ""));
|
||||
if (!lines[j].startsWith(cont)) break;
|
||||
// Drop the prefix + `>` + one optional space, leaving the body content.
|
||||
bodyLines.push(lines[j].slice(prefix.length).replace(/^>\s?/, ""));
|
||||
}
|
||||
const inner = await transform(bodyLines);
|
||||
const renderedInner = await markedInstance.parse(inner);
|
||||
out.push(
|
||||
`\n<div data-type="callout" data-callout-type="${type}">${renderedInner}</div>\n`,
|
||||
);
|
||||
const block = `<div data-type="callout" data-callout-type="${type}">${renderedInner}</div>`;
|
||||
if (prefix.length === 0) {
|
||||
// Top-level callout: blank lines isolate the HTML block.
|
||||
out.push(`\n${block}\n`);
|
||||
} else if (prefix.includes(">")) {
|
||||
// Enclosing BLOCKQUOTE: prefix every line and add NO surrounding blank
|
||||
// lines — a blank line would terminate the blockquote and split the
|
||||
// callout out of it.
|
||||
out.push(block.split("\n").map((l) => prefix + l).join("\n"));
|
||||
} else {
|
||||
// Pure LIST-ITEM indentation: re-indent and keep the blank-line
|
||||
// separators (a loose list item), so the div sits at the marker column.
|
||||
out.push(
|
||||
`\n${block
|
||||
.split("\n")
|
||||
.map((l) => (l.length ? prefix + l : l))
|
||||
.join("\n")}\n`,
|
||||
);
|
||||
}
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
@@ -597,6 +625,40 @@ function bridgeTaskLists(html: string): string {
|
||||
* (null from parseAttachedComment), an unknown name, a wrong-position comment, or
|
||||
* an unknown/empty attr value is ignored.
|
||||
*/
|
||||
/**
|
||||
* A directive comment is in ATTACHED position when it sits inside a `<p>`/`<hN>`
|
||||
* textblock — bound to that block's text (the `attrs`/`img` conventions). Every
|
||||
* other parent (body, document level, a block container like blockquote/details/
|
||||
* li/column div) is STANDALONE position, where a lone-block directive
|
||||
* (subpages/pagebreak/pageembed/transclusion) is materialized. Broadening
|
||||
* standalone beyond body/document is what lets these nodes survive NESTED inside
|
||||
* a blockquote/callout/details/list item (previously dropped -> silent data loss).
|
||||
*/
|
||||
function isAttachedPosition(tag: string): boolean {
|
||||
return tag === "p" || /^h[1-6]$/.test(tag);
|
||||
}
|
||||
|
||||
/**
|
||||
* Place a materialized standalone-directive element in the DOM: replace the
|
||||
* comment IN PLACE when it has a real element parent inside <body> (body itself
|
||||
* or a nested block container), preserving document order; queue it as a leading
|
||||
* div only when the comment is at document level (no parentElement) or directly
|
||||
* under `<html>` (outside <body>, which `document.body.innerHTML` would drop).
|
||||
*/
|
||||
function placeStandalone(
|
||||
comment: any,
|
||||
el: any,
|
||||
tag: string,
|
||||
leadingDivs: any[],
|
||||
): void {
|
||||
if (comment.parentElement && tag !== "html") {
|
||||
comment.replaceWith(el);
|
||||
} else {
|
||||
comment.remove();
|
||||
leadingDivs.push(el);
|
||||
}
|
||||
}
|
||||
|
||||
function applyCommentDirectives(html: string): string {
|
||||
// Cheap early-out: no comments at all -> nothing to intercept.
|
||||
if (!html.includes("<!--")) return html;
|
||||
@@ -664,13 +726,13 @@ function applyCommentDirectives(html: string): string {
|
||||
|
||||
if (parsed.name === "subpages" || parsed.name === "pagebreak") {
|
||||
// #293 canon #5 STANDALONE machinery. A lone comment line is rendered by
|
||||
// marked as an HTML block; the parser places it either directly under
|
||||
// <body> (when other content surrounds it) or at document level (when it
|
||||
// leads the output). Both are STANDALONE position. A `subpages`/`pagebreak`
|
||||
// comment sitting inside a `<p>`/`<hN>` (or any other element) is attached
|
||||
// position -> INERT.
|
||||
const standalone = tag === "" || tag === "body" || tag === "html";
|
||||
if (!standalone) continue; // wrong position -> inert
|
||||
// marked as its own HTML block; the parser places it under <body>, at
|
||||
// document level (leading), or — when the directive is NESTED — inside a
|
||||
// block CONTAINER (`<blockquote>` for blockquote/callout, `<details>`,
|
||||
// `<li>`, a column `<div>`, …). All of those are STANDALONE position. Only a
|
||||
// comment ATTACHED inside a `<p>`/`<hN>` (bound to that block's text) is
|
||||
// attached position -> INERT.
|
||||
if (isAttachedPosition(tag)) continue; // wrong position -> inert
|
||||
const div = document.createElement("div");
|
||||
if (parsed.name === "pagebreak") {
|
||||
div.setAttribute("data-type", "pageBreak");
|
||||
@@ -680,26 +742,18 @@ function applyCommentDirectives(html: string): string {
|
||||
div.setAttribute("data-recursive", "true");
|
||||
}
|
||||
}
|
||||
if (tag === "body") {
|
||||
// In-body: replace in place so surrounding content keeps its order.
|
||||
comment.replaceWith(div);
|
||||
} else {
|
||||
// Document-level (leading): drop the stray comment and queue the div to
|
||||
// be prepended into body below.
|
||||
comment.remove();
|
||||
leadingDivs.push(div);
|
||||
}
|
||||
placeStandalone(comment, div, tag, leadingDivs);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parsed.name === "pageembed" || parsed.name === "transclusion") {
|
||||
// #293 canon #8 STANDALONE media. Like subpages/pagebreak: a lone comment
|
||||
// line placed under <body> or at document level (leading). An attached-
|
||||
// position comment (inside a <p>/<hN> with a sibling) is INERT. We rebuild
|
||||
// the schema div the raw-HTML path emits (media-html.ts) from the decoded
|
||||
// attrs so serialize/parse stay in sync.
|
||||
const standalone = tag === "" || tag === "body" || tag === "html";
|
||||
if (!standalone) continue; // wrong position -> inert
|
||||
// line placed under <body>, at document level (leading), or NESTED inside a
|
||||
// block container (blockquote/callout/details/li/column). An ATTACHED-
|
||||
// position comment (inside a `<p>`/`<hN>`) is INERT. We rebuild the schema
|
||||
// div the raw-HTML path emits (media-html.ts) from the decoded attrs so
|
||||
// serialize/parse stay in sync.
|
||||
if (isAttachedPosition(tag)) continue; // wrong position -> inert
|
||||
const el = buildElement(
|
||||
parsed.name === "pageembed"
|
||||
? pageEmbedToHtml({ sourcePageId: parsed.attrs.sourcePageId })
|
||||
@@ -709,12 +763,7 @@ function applyCommentDirectives(html: string): string {
|
||||
}),
|
||||
);
|
||||
if (!el) continue; // defensive: builder always yields an element
|
||||
if (tag === "body") {
|
||||
comment.replaceWith(el);
|
||||
} else {
|
||||
comment.remove();
|
||||
leadingDivs.push(el);
|
||||
}
|
||||
placeStandalone(comment, el, tag, leadingDivs);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -806,18 +855,36 @@ function applyCommentDirectives(html: string): string {
|
||||
|
||||
if (!parent) continue; // attrs comment must have an element parent
|
||||
if (parsed.name !== "attrs") continue; // unknown name -> inert
|
||||
// #293 canon #9 ATTACHED attrs: honored only in attached position.
|
||||
const isBlock = tag === "p" || /^h[1-6]$/.test(tag);
|
||||
if (!isBlock) continue; // misplaced comment -> inert
|
||||
const align = parsed.attrs.textAlign;
|
||||
if (typeof align === "string" && align) {
|
||||
// Re-express as an inline style; the schema's textAlign parseHTML reads
|
||||
// `el.style.textAlign` back onto the paragraph/heading node.
|
||||
parent.style.textAlign = align;
|
||||
// #293 canon #9 ATTACHED attrs: honored only in attached position.
|
||||
if (tag === "p" || /^h[1-6]$/.test(tag)) {
|
||||
// A real <p>/<hN> host (loose list item, top-level block, …): re-express as
|
||||
// an inline style; the schema's textAlign parseHTML reads `el.style.textAlign`
|
||||
// back onto the paragraph/heading node.
|
||||
if (typeof align === "string" && align) parent.style.textAlign = align;
|
||||
comment.remove();
|
||||
} else if (tag === "li" || tag === "td" || tag === "th") {
|
||||
// TIGHT list item / GFM table cell: marked emits the paragraph's inline
|
||||
// content DIRECTLY inside the <li>/<td>/<th> with NO <p> wrapper, so there
|
||||
// is no element to carry the style — generateJSON materializes the
|
||||
// paragraph later. Wrap the host's LEADING inline content (everything up to
|
||||
// the comment; any trailing block child such as a nested list stays put) in
|
||||
// a <p> carrying the alignment, so the materialized paragraph re-reads it.
|
||||
if (typeof align === "string" && align) {
|
||||
const p = document.createElement("p");
|
||||
p.style.textAlign = align;
|
||||
while (parent.firstChild && parent.firstChild !== comment) {
|
||||
p.appendChild(parent.firstChild);
|
||||
}
|
||||
parent.insertBefore(p, comment);
|
||||
}
|
||||
comment.remove();
|
||||
} else {
|
||||
// Misplaced `attrs` comment (not a textblock/li/cell host): inert. Consume
|
||||
// it anyway so no attached marker ever survives into the parsed body
|
||||
// (matches the pre-existing "consume regardless" behaviour).
|
||||
comment.remove();
|
||||
}
|
||||
// Consume the marker regardless (unknown keys are simply ignored) so no
|
||||
// attached comment ever survives into the parsed body.
|
||||
comment.remove();
|
||||
}
|
||||
// Prepend any document-level (leading) standalone divs into body, preserving
|
||||
// their document order relative to each other and ahead of existing content.
|
||||
|
||||
@@ -46,7 +46,11 @@ export function videoToHtml(attrs: Record<string, any>): string {
|
||||
if (attrs.width != null) parts.push(`width="${escapeAttr(attrs.width)}"`);
|
||||
if (attrs.height != null) parts.push(`height="${escapeAttr(attrs.height)}"`);
|
||||
if (attrs.size != null) parts.push(`data-size="${escapeAttr(attrs.size)}"`);
|
||||
if (attrs.align) parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
// align default is "center" (schema): OMIT it so a bare/center node stays
|
||||
// clean and parse's re-materialized "center" default is not a P2 churn — only
|
||||
// a genuinely non-default left/right emits data-align (mirrors imageToHtml).
|
||||
if (attrs.align && attrs.align !== "center")
|
||||
parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
if (attrs.aspectRatio != null)
|
||||
parts.push(`data-aspect-ratio="${escapeAttr(attrs.aspectRatio)}"`);
|
||||
return `<div><video ${parts.join(" ")}></video></div>`;
|
||||
@@ -62,7 +66,9 @@ export function youtubeToHtml(attrs: Record<string, any>): string {
|
||||
parts.push(`data-width="${escapeAttr(attrs.width)}"`);
|
||||
if (attrs.height != null)
|
||||
parts.push(`data-height="${escapeAttr(attrs.height)}"`);
|
||||
if (attrs.align) parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
// "center" is the schema default -> omit (see videoToHtml rationale).
|
||||
if (attrs.align && attrs.align !== "center")
|
||||
parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
return `<div ${parts.join(" ")}></div>`;
|
||||
}
|
||||
|
||||
@@ -97,7 +103,9 @@ export function diagramToHtml(
|
||||
if (attrs.size != null) parts.push(`data-size="${escapeAttr(attrs.size)}"`);
|
||||
if (attrs.aspectRatio != null)
|
||||
parts.push(`data-aspect-ratio="${escapeAttr(attrs.aspectRatio)}"`);
|
||||
if (attrs.align) parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
// "center" is the schema default -> omit (see videoToHtml rationale).
|
||||
if (attrs.align && attrs.align !== "center")
|
||||
parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
if (attrs.attachmentId)
|
||||
parts.push(`data-attachment-id="${escapeAttr(attrs.attachmentId)}"`);
|
||||
return `<div ${parts.join(" ")}></div>`;
|
||||
@@ -110,10 +118,18 @@ export function embedToHtml(attrs: Record<string, any>): string {
|
||||
`data-src="${escapeAttr(attrs.src ?? "")}"`,
|
||||
`data-provider="${escapeAttr(attrs.provider ?? "")}"`,
|
||||
];
|
||||
if (attrs.align) parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
if (attrs.width != null)
|
||||
// "center" is the schema default -> omit (see videoToHtml rationale).
|
||||
if (attrs.align && attrs.align !== "center")
|
||||
parts.push(`data-align="${escapeAttr(attrs.align)}"`);
|
||||
// embed width/height default to the NUMBERS 800/600 (schema). Getting a data-
|
||||
// attribute back always yields a STRING, so emitting the default here would
|
||||
// round-trip 800 -> "800" (a number->string P1 divergence canonicalize does
|
||||
// NOT normalize). OMIT the defaults so parse re-materializes the numeric
|
||||
// default instead — mirrors the top-level embed path (markdown-converter.ts),
|
||||
// which also emits width/height only when they differ from 800/600.
|
||||
if (attrs.width != null && attrs.width !== 800)
|
||||
parts.push(`data-width="${escapeAttr(attrs.width)}"`);
|
||||
if (attrs.height != null)
|
||||
if (attrs.height != null && attrs.height !== 600)
|
||||
parts.push(`data-height="${escapeAttr(attrs.height)}"`);
|
||||
return `<div ${parts.join(" ")}></div>`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
/**
|
||||
* Nested whole-document generator (#351, PR 2) — "variant A": a random walk over
|
||||
* the schema's ContentMatch automaton.
|
||||
*
|
||||
* Where the FLAT generator (node-generators.ts) emits `{doc:[ <one target> ]}`,
|
||||
* this module produces arbitrarily DEEP, valid ProseMirror documents. Validity is
|
||||
* NOT hand-asserted: it comes straight from the schema. To fill a container's
|
||||
* block content we start at `nodeType.contentMatch` and walk the automaton —
|
||||
* enumerate the legal next node types (`match.edge(i).type`), let fast-check pick
|
||||
* one (or STOP once `match.validEnd`), generate that child RECURSIVELY, then
|
||||
* advance the automaton via `match.matchType(childType)`. A bad walk therefore
|
||||
* cannot emit a structurally-invalid doc (the `generator validity` test guards
|
||||
* this with `schema.nodeFromJSON(json).check()`).
|
||||
*
|
||||
* ── What the walk drives, and what it delegates ──────────────────────────────
|
||||
* The walk owns BLOCK STRUCTURE (which blocks nest inside which containers, in
|
||||
* what order and how deep). Two things it deliberately delegates, to avoid
|
||||
* REGRESSING the byte-stable space the flat suite already proved empirically:
|
||||
*
|
||||
* - INLINE content of textblocks (paragraph/heading/codeBlock/detailsSummary)
|
||||
* is filled from text-arbitraries.ts — the exact hostile-but-byte-stable
|
||||
* inline corpus the flat suite established. Walking the inline ContentMatch
|
||||
* instead would re-derive (and re-fail) the text-space limitations the flat
|
||||
* suite already pins, which is not this generator's job.
|
||||
* - Node ATTRS come from nodeAttrsArb(type, 'p1') — the round-trip-safe
|
||||
* attribute space. Attribute-degenerate fuzzing (P2/P3 over 'fuzz') is the
|
||||
* flat suite's concern; the nested suite isolates STRUCTURAL round-trip, so
|
||||
* it stays in 'p1' and does not re-litigate frozen/pinned attributes.
|
||||
*
|
||||
* ── Coordination the automaton cannot express ────────────────────────────────
|
||||
* A ContentMatch guarantees a child SEQUENCE is legal, but not cross-sibling
|
||||
* invariants. Two nodes need coordination the walk injects by hand:
|
||||
* - `table`: GFM needs a RECTANGULAR grid with column-consistent alignment.
|
||||
* The automaton happily allows ragged rows / per-cell align, which are not a
|
||||
* converter bug — just a malformed table. So a table is generated ATOMICALLY
|
||||
* (same shape the flat suite proved) rather than walked.
|
||||
* - `columns`: the `layout` attr must agree with the column COUNT. We pick the
|
||||
* layout, derive the count, then walk each column's block body normally — so
|
||||
* columns still gain real nested content, only the count is coordinated.
|
||||
*
|
||||
* ── Excluded from the nested walk ────────────────────────────────────────────
|
||||
* Footnote nodes (footnoteReference / footnotesList / footnoteDefinition) need a
|
||||
* DOCUMENT-GLOBAL id match between a reference and its definition. That
|
||||
* coordination is owned by the flat suite's `footnotes` generator; placing them
|
||||
* independently here would fabricate id mismatches that look like converter bugs
|
||||
* but are generator defects. They are filtered out of the walk (documented in
|
||||
* EXCLUDED). The completeness contract lives in the FLAT suite and is unaffected.
|
||||
*
|
||||
* ── Termination / budgets ────────────────────────────────────────────────────
|
||||
* Two bounds keep every doc finite and the suite fast:
|
||||
* - MAX_DEPTH — a hard cap on block-nesting depth. A precomputed `minDepth`
|
||||
* fixpoint (the minimum extra nesting a subtree of each type needs to be
|
||||
* valid) lets the walk pick a CONTAINER child only when there is depth
|
||||
* headroom to complete it — so the walk can never paint itself into a corner
|
||||
* where a required child cannot fit (no invalid docs, guaranteed termination).
|
||||
* - NODE_BUDGET — a soft cap on total nodes; as it runs low the walk biases
|
||||
* toward STOP (when validEnd) or toward cheap terminating children.
|
||||
*/
|
||||
import fc from 'fast-check';
|
||||
import { getSchema } from '@tiptap/core';
|
||||
import { docmostExtensions } from '../../src/lib/docmost-schema.js';
|
||||
import { nodeAttrsArb } from './attr-arbitraries.js';
|
||||
import {
|
||||
inlineContentArb,
|
||||
headingInlineContentArb,
|
||||
plainInlineContentArb,
|
||||
phraseArb,
|
||||
} from './text-arbitraries.js';
|
||||
|
||||
/** The exact ProseMirror schema the converter targets (built per the issue). */
|
||||
export const schema = getSchema(docmostExtensions as never);
|
||||
|
||||
/** Hard cap on block-nesting depth (doc = depth 0). Kept in the issue's 4–5 band. */
|
||||
export const MAX_DEPTH = 4;
|
||||
/**
|
||||
* Soft cap on total node count per generated document. Kept moderate: every P1/P2
|
||||
* run parses the emitted markdown through jsdom (heavy), so 100+ node docs across
|
||||
* hundreds of runs exhaust the worker heap. 60 still yields deeply-nested docs
|
||||
* (depth 4) while keeping the suite within memory.
|
||||
*/
|
||||
export const NODE_BUDGET = 60;
|
||||
|
||||
/**
|
||||
* Nodes kept OUT of the nested walk: footnote nodes need a doc-global id match a
|
||||
* local walk cannot coordinate (owned by the flat suite's `footnotes` generator).
|
||||
*/
|
||||
const EXCLUDED = new Set<string>([
|
||||
'footnoteReference',
|
||||
'footnotesList',
|
||||
'footnoteDefinition',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Structural-only children that carry `group: "block"` in the schema and so leak
|
||||
* into EVERY block container's ContentMatch, even though the editor only ever
|
||||
* places them inside their one true parent. Choosing them freely (e.g. a bare
|
||||
* `column` at the document root) fabricates documents no editor produces and that
|
||||
* the converter is not designed to round-trip — a GENERATOR artifact, not a
|
||||
* converter bug. They are admitted ONLY when the container being filled is their
|
||||
* dedicated parent. (`column` is in fact always built inside columnsArb, so this
|
||||
* just double-guards it.)
|
||||
*/
|
||||
const DEDICATED_PARENT: Record<string, string> = {
|
||||
column: 'columns',
|
||||
detailsSummary: 'details',
|
||||
detailsContent: 'details',
|
||||
};
|
||||
|
||||
/** Is child type `t` legal as a freely-chosen child of container `parentType`? */
|
||||
function childAllowedUnder(t: string, parentType: string): boolean {
|
||||
const dedicated = DEDICATED_PARENT[t];
|
||||
return dedicated === undefined || dedicated === parentType;
|
||||
}
|
||||
|
||||
/** Textblock (inlineContent) types — filled from the proven inline corpus. */
|
||||
function isTextblock(typeName: string): boolean {
|
||||
return !!schema.nodes[typeName]?.isTextblock;
|
||||
}
|
||||
/** Leaf/atom types — no content, only generated attrs. */
|
||||
function isLeaf(typeName: string): boolean {
|
||||
return !!schema.nodes[typeName]?.isLeaf;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// minDepth fixpoint: the minimum EXTRA block-nesting depth a valid subtree
|
||||
// rooted at each node type requires. Leaves and textblocks need 0 (a textblock
|
||||
// is satisfied by inline content, no block recursion). A container needs
|
||||
// 1 + the cheapest way to satisfy its ContentMatch. Computed as a min–max path
|
||||
// to `validEnd` over the automaton, iterated to a fixpoint over node types.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Cheapest (min over reachable validEnd of max child minDepth) to complete a match. */
|
||||
function minCompletion(
|
||||
match: any,
|
||||
md: Record<string, number>,
|
||||
seen: Set<any>,
|
||||
parentType: string,
|
||||
): number {
|
||||
let best = match.validEnd ? 0 : Infinity;
|
||||
if (seen.has(match)) return best; // a cycle never completes more cheaply
|
||||
seen.add(match);
|
||||
for (let i = 0; i < match.edgeCount; i++) {
|
||||
const edge = match.edge(i);
|
||||
const t = edge.type.name;
|
||||
if (EXCLUDED.has(t) || t === 'text') continue;
|
||||
if (!childAllowedUnder(t, parentType)) continue;
|
||||
const childCost = md[t];
|
||||
if (childCost === undefined || childCost === Infinity) continue;
|
||||
const rest = minCompletion(edge.next, md, seen, parentType);
|
||||
if (rest === Infinity) continue;
|
||||
best = Math.min(best, Math.max(childCost, rest));
|
||||
}
|
||||
seen.delete(match);
|
||||
return best;
|
||||
}
|
||||
|
||||
function computeMinDepth(): Record<string, number> {
|
||||
const md: Record<string, number> = {};
|
||||
for (const name of Object.keys(schema.nodes)) {
|
||||
md[name] = isLeaf(name) || isTextblock(name) ? 0 : Infinity;
|
||||
}
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const name of Object.keys(schema.nodes)) {
|
||||
if (md[name] === 0) continue; // leaves/textblocks fixed at 0
|
||||
const nt: any = schema.nodes[name];
|
||||
const completion = minCompletion(nt.contentMatch, md, new Set(), name);
|
||||
const next = completion === Infinity ? Infinity : 1 + completion;
|
||||
if (next < md[name]) {
|
||||
md[name] = next;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return md;
|
||||
}
|
||||
|
||||
const MIN_DEPTH = computeMinDepth();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Leaf / textblock builders (attrs from 'p1', inline from the proven corpus).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function attachAttrs(typeName: string, base: Record<string, unknown> = {}) {
|
||||
return nodeAttrsArb(typeName, 'p1', base).map((attrs) => {
|
||||
const node: any = { type: typeName };
|
||||
if (Object.keys(attrs).length) node.attrs = attrs;
|
||||
return node;
|
||||
});
|
||||
}
|
||||
|
||||
/** A leaf/atom block: attrs only, no content. */
|
||||
function leafArb(typeName: string): fc.Arbitrary<any> {
|
||||
return attachAttrs(typeName);
|
||||
}
|
||||
|
||||
/** A textblock, inline content taken from the byte-stable flat corpus. */
|
||||
function textblockArb(typeName: string): fc.Arbitrary<any> {
|
||||
if (typeName === 'codeBlock') {
|
||||
return fc
|
||||
.tuple(
|
||||
nodeAttrsArb('codeBlock', 'p1'),
|
||||
// Fenced code re-imports with a TRAILING NEWLINE (flat suite finding);
|
||||
// author it so the doc is already at the round-trip fixpoint.
|
||||
fc.array(phraseArb, { minLength: 1, maxLength: 3 }).map((l) => l.join('\n') + '\n'),
|
||||
)
|
||||
.map(([attrs, code]) => ({
|
||||
type: 'codeBlock',
|
||||
...(Object.keys(attrs).length ? { attrs } : {}),
|
||||
content: [{ type: 'text', text: code }],
|
||||
}));
|
||||
}
|
||||
const inline =
|
||||
typeName === 'heading'
|
||||
? headingInlineContentArb
|
||||
: typeName === 'detailsSummary'
|
||||
? plainInlineContentArb
|
||||
: inlineContentArb;
|
||||
return fc
|
||||
.tuple(nodeAttrsArb(typeName, 'p1'), inline)
|
||||
.map(([attrs, content]) => ({
|
||||
type: typeName,
|
||||
...(Object.keys(attrs).length ? { attrs } : {}),
|
||||
content,
|
||||
}));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Coordinated builders: table (atomic, rectangular, column-consistent align)
|
||||
// and columns (layout coupled to count, bodies walked).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** A rectangular GFM-safe table (mirrors the flat suite's proven shape). */
|
||||
function tableArb(): fc.Arbitrary<any> {
|
||||
return fc.integer({ min: 1, max: 3 }).chain((cols) => {
|
||||
// One alignment per COLUMN, identical on header + every body cell, so the
|
||||
// second export cannot re-align and churn.
|
||||
const alignsArb = fc.array(fc.constantFrom(undefined, 'left', 'center', 'right'), {
|
||||
minLength: cols,
|
||||
maxLength: cols,
|
||||
});
|
||||
const cell = (header: boolean, align?: string) =>
|
||||
phraseArb.map((t) => ({
|
||||
type: header ? 'tableHeader' : 'tableCell',
|
||||
attrs: { colspan: 1, rowspan: 1, ...(align ? { align } : {}) },
|
||||
content: [{ type: 'paragraph', content: [{ type: 'text', text: t }] }],
|
||||
}));
|
||||
return alignsArb.chain((aligns) => {
|
||||
const headerRow = fc
|
||||
.tuple(...aligns.map((a) => cell(true, a)))
|
||||
.map((cells) => ({ type: 'tableRow', content: cells }));
|
||||
const bodyRow = fc
|
||||
.tuple(...aligns.map((a) => cell(false, a)))
|
||||
.map((cells) => ({ type: 'tableRow', content: cells }));
|
||||
return fc
|
||||
.tuple(headerRow, fc.array(bodyRow, { minLength: 1, maxLength: 2 }))
|
||||
.map(([h, body]) => ({ type: 'table', content: [h, ...body] }));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** A columns block: layout ↔ count coupled, each column body walked as blocks. */
|
||||
function columnsArb(depth: number, budget: number): fc.Arbitrary<any> {
|
||||
return fc
|
||||
.constantFrom('two_equal', 'three_equal', 'left_sidebar', 'right_sidebar')
|
||||
.chain((layout) => {
|
||||
const count = layout === 'three_equal' ? 3 : 2;
|
||||
const columnType: any = schema.nodes.column;
|
||||
// Split the remaining budget across the fixed number of columns.
|
||||
const per = Math.max(2, Math.floor((budget - 1) / count));
|
||||
return nodeAttrsArb('columns', 'p1', { layout, widthMode: 'normal' }).chain((attrs) =>
|
||||
fc
|
||||
.tuple(
|
||||
...Array.from({ length: count }, () =>
|
||||
fillMatch(columnType.contentMatch, depth + 1, per, 'column').map(({ children }) => ({
|
||||
type: 'column',
|
||||
content: children,
|
||||
})),
|
||||
),
|
||||
)
|
||||
.map((cols) => ({ type: 'columns', attrs, content: cols })),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The ContentMatch walk.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Count every node in a subtree (block + inline), for budget accounting. */
|
||||
function countNodes(node: any): number {
|
||||
let n = 1;
|
||||
for (const c of node.content ?? []) n += countNodes(c);
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Build a single child node of a given type at `depth`, within `budget`. */
|
||||
function blockNode(typeName: string, depth: number, budget: number): fc.Arbitrary<any> {
|
||||
if (typeName === 'table') return tableArb();
|
||||
if (typeName === 'columns') return columnsArb(depth, budget);
|
||||
if (isTextblock(typeName)) return textblockArb(typeName);
|
||||
if (isLeaf(typeName)) return leafArb(typeName);
|
||||
// Generic container: attrs from 'p1', block content from the automaton walk.
|
||||
const nt: any = schema.nodes[typeName];
|
||||
return nodeAttrsArb(typeName, 'p1').chain((attrs) =>
|
||||
fillMatch(nt.contentMatch, depth, budget - 1, typeName).map(({ children }) => {
|
||||
const node: any = { type: typeName };
|
||||
if (Object.keys(attrs).length) node.attrs = attrs;
|
||||
if (children.length) node.content = children;
|
||||
return node;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill a container's block content by walking its ContentMatch automaton from
|
||||
* `match`. Returns the children array plus the budget left after them.
|
||||
*/
|
||||
function fillMatch(
|
||||
match: any,
|
||||
depth: number,
|
||||
budget: number,
|
||||
parentType: string,
|
||||
): fc.Arbitrary<{ children: any[]; budget: number }> {
|
||||
const canStop = match.validEnd;
|
||||
// A child lives at depth+1; only pick it if its subtree can complete within
|
||||
// MAX_DEPTH. This headroom rule is what makes the walk deadlock-free.
|
||||
const headroom = MAX_DEPTH - (depth + 1);
|
||||
const edges: { t: string; next: any }[] = [];
|
||||
if (headroom >= 0) {
|
||||
for (let i = 0; i < match.edgeCount; i++) {
|
||||
const edge = match.edge(i);
|
||||
const t = edge.type.name;
|
||||
if (EXCLUDED.has(t) || t === 'text') continue;
|
||||
if (!childAllowedUnder(t, parentType)) continue;
|
||||
if ((MIN_DEPTH[t] ?? Infinity) > headroom) continue;
|
||||
edges.push({ t, next: edge.next });
|
||||
}
|
||||
}
|
||||
|
||||
// Decide the next action: STOP (if allowed) or extend with one more child.
|
||||
// Bias toward stopping when the budget is spent; force a child only when the
|
||||
// match is not yet at a valid end.
|
||||
const pool: { weight: number; arbitrary: fc.Arbitrary<{ t: string; next: any } | null> }[] = [];
|
||||
const canGo = edges.length > 0 && (budget > 0 || !canStop);
|
||||
if (canStop) {
|
||||
// Stop is weighted higher when the budget is low so docs stay bounded.
|
||||
pool.push({ weight: budget > 0 ? 2 : 5, arbitrary: fc.constant(null) });
|
||||
}
|
||||
if (canGo && !(canStop && budget <= 0)) {
|
||||
pool.push({ weight: 3, arbitrary: fc.constantFrom(...edges) });
|
||||
}
|
||||
// Forced continuation: not a valid end yet and (budget exhausted) — must place
|
||||
// a mandatory child regardless of budget.
|
||||
if (pool.length === 0) {
|
||||
if (edges.length > 0) {
|
||||
pool.push({ weight: 1, arbitrary: fc.constantFrom(...edges) });
|
||||
} else {
|
||||
// No legal child and not required to place one: stop with what we have.
|
||||
return fc.constant({ children: [], budget });
|
||||
}
|
||||
}
|
||||
|
||||
return fc.oneof(...pool).chain((choice) => {
|
||||
if (choice === null) return fc.constant({ children: [], budget });
|
||||
return blockNode(choice.t, depth + 1, budget).chain((node) => {
|
||||
const cost = countNodes(node);
|
||||
return fillMatch(choice.next, depth, budget - cost, parentType).map(
|
||||
({ children, budget: left }) => ({
|
||||
children: [node, ...children],
|
||||
budget: left,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The nested-document arbitrary: a valid, arbitrarily-deep ProseMirror doc built
|
||||
* by walking the schema from the document root. Attrs stay in the round-trip-safe
|
||||
* 'p1' space; inline content reuses the byte-stable flat corpus.
|
||||
*/
|
||||
export const docArb: fc.Arbitrary<any> = fillMatch(
|
||||
schema.nodes.doc.contentMatch,
|
||||
0,
|
||||
NODE_BUDGET,
|
||||
'doc',
|
||||
).map(({ children }) => ({ type: 'doc', content: children }));
|
||||
|
||||
/** The precomputed minDepth table, exported for inspection/debugging. */
|
||||
export { MIN_DEPTH };
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import fc from 'fast-check';
|
||||
// Real converters. Importing markdownToProseMirror (transitively, via index)
|
||||
// mutates the global DOM via jsdom at module load — expected, required for
|
||||
// @tiptap/html's generateJSON under Node (same as the flat sibling suite).
|
||||
import {
|
||||
convertProseMirrorToMarkdown,
|
||||
markdownToProseMirror,
|
||||
docsCanonicallyEqual,
|
||||
canonicalizeContent,
|
||||
} from '../../src/lib/index.js';
|
||||
import { firstDivergence } from '../roundtrip-helpers.js';
|
||||
import { schema, docArb } from './doc-generator.js';
|
||||
|
||||
// Each run does a real convert + jsdom parse; give ample headroom so the suite
|
||||
// is deterministic under parallel worker load (matching the flat sibling suite).
|
||||
vi.setConfig({ testTimeout: 60000 });
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// #351 PR 2 — GENERATIVE round-trip over NESTED (whole-document) docs produced
|
||||
// by the ContentMatch random walk (doc-generator.ts). The invariants mirror the
|
||||
// flat suite, plus a parser-fuzz totality property (P4):
|
||||
//
|
||||
// P1 — semantic round-trip: docsCanonicallyEqual(mdToPm(pmToMd(d)), d)
|
||||
// P2 — byte fixpoint (2nd pass): pmToMd(mdToPm(pmToMd(d))) === pmToMd(d)
|
||||
// (the FIRST pass may normalize once; the SECOND pass must be a fixpoint)
|
||||
// P3 — totality: neither converter throws; bounded.
|
||||
// P4 — parser fuzz totality: for ANY string, markdownToProseMirror does NOT
|
||||
// throw and returns a SCHEMA-VALID document.
|
||||
//
|
||||
// GUARDRAIL: a P1/P2/P3/P4 failure means the generator FOUND A REAL CONVERTER
|
||||
// BUG. These invariants are kept STRICT — no it.fails / skip / weakening. A
|
||||
// failure prints the shrunk minimal counterexample for triage.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SEED = 20250705;
|
||||
// The nested walk builds far heavier docs than the flat suite (each P1/P2 run
|
||||
// parses the emitted markdown through jsdom), so keep the run count moderate to
|
||||
// hold runtime and worker memory in budget while still exercising deep
|
||||
// structures. P4 (cheap string parsing) runs at a higher count below.
|
||||
const NUM_RUNS = 100;
|
||||
|
||||
const pmToMd = (doc: unknown): string => convertProseMirrorToMarkdown(doc);
|
||||
const mdToPm = (md: string): Promise<any> => markdownToProseMirror(md);
|
||||
|
||||
async function roundTrip(doc: unknown): Promise<{ md1: string; md2: string; doc2: any }> {
|
||||
const md1 = pmToMd(doc);
|
||||
const doc2 = await mdToPm(md1);
|
||||
const md2 = pmToMd(doc2);
|
||||
return { md1, md2, doc2 };
|
||||
}
|
||||
|
||||
describe('#351 nested generative round-trip — generator validity', () => {
|
||||
it('every generated nested doc passes schema.nodeFromJSON(...).check()', () => {
|
||||
// A nested generator that emits an invalid ProseMirror document is a
|
||||
// GENERATOR bug — the ContentMatch walk must only produce schema-valid docs.
|
||||
fc.assert(
|
||||
fc.property(docArb, (doc) => {
|
||||
schema.nodeFromJSON(doc).check(); // throws on an invalid doc
|
||||
return true;
|
||||
}),
|
||||
{ numRuns: NUM_RUNS * 2, seed: SEED },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ── STATUS: P1/P2/P3/P4 all GREEN. The nested generator originally surfaced a
|
||||
// batch of real converter bugs; all were fixed in the serializer/parser (see the
|
||||
// #351 hand-off). For the record, the classes it found and that are now fixed:
|
||||
// • Loose (multi-block) list items / task items / callouts / details bodies were
|
||||
// joined with a single "\n", so every block after the first merged into the
|
||||
// first paragraph on re-parse (silent content loss) — now blank-line separated.
|
||||
// • Paragraph `textAlign` was dropped inside a TIGHT list item (no <p> host).
|
||||
// • A nested codeBlock lost its trailing newline on the raw-HTML path.
|
||||
// • Media (embed/video/youtube/drawio/excalidraw) inside `columns` churned a
|
||||
// default `data-align` and coerced embed's numeric width/height to strings.
|
||||
// • pageBreak / pageEmbed / subpages / transclusion were dropped when nested in
|
||||
// blockquote / callout / details / list item (standalone-comment position).
|
||||
// • Callouts nested in a list item or a blockquote (` > [!type]` / `> > [!type]`)
|
||||
// were re-parsed as plain blockquotes (prefix-unaware callout preprocessor).
|
||||
// • Two adjacent sibling lists sharing a marker family (bulletList/taskList →
|
||||
// `<ul>`; orderedList → `<ol>`) merged into one list on re-parse — and for the
|
||||
// cross-type case (taskList beside bulletList) the merged `<ul>` LOST every
|
||||
// taskItem checkbox. The serializer now emits a `<!-- -->` separator between
|
||||
// such adjacent lists (markdown-converter.ts renderBlockChildren), so they stay
|
||||
// distinct and round-trip; the generator therefore emits them freely again.
|
||||
describe('#351 nested generative round-trip — properties', () => {
|
||||
it('P1 — semantic round-trip: docsCanonicallyEqual(mdToPm(pmToMd(d)), d)', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(docArb, async (doc) => {
|
||||
const { doc2 } = await roundTrip(doc);
|
||||
if (!docsCanonicallyEqual(doc2, doc)) {
|
||||
const div = firstDivergence(
|
||||
JSON.parse(JSON.stringify(canonicalizeContent(doc2))),
|
||||
JSON.parse(JSON.stringify(canonicalizeContent(doc))),
|
||||
);
|
||||
throw new Error(
|
||||
`P1 divergence @ ${div?.path}: got=${JSON.stringify(div?.a)} want=${JSON.stringify(div?.b)}`,
|
||||
);
|
||||
}
|
||||
}),
|
||||
{ numRuns: NUM_RUNS, seed: SEED },
|
||||
);
|
||||
});
|
||||
|
||||
it('P2 — byte fixpoint: pmToMd(mdToPm(pmToMd(d))) === pmToMd(d)', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(docArb, async (doc) => {
|
||||
const { md1, md2 } = await roundTrip(doc);
|
||||
expect(md2).toBe(md1);
|
||||
}),
|
||||
{ numRuns: NUM_RUNS, seed: SEED },
|
||||
);
|
||||
});
|
||||
|
||||
it('P3 — totality: neither converter throws', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(docArb, async (doc) => {
|
||||
await roundTrip(doc);
|
||||
}),
|
||||
{ numRuns: NUM_RUNS, seed: SEED },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P4 — parser fuzz. Independent of the doc generator: for ANY input string the
|
||||
// PARSER (markdownToProseMirror) must be TOTAL — never throw — and must always
|
||||
// return a schema-valid document. The corpus mixes raw unicode strings with
|
||||
// strings assembled from markdown-significant fragments (headings, list bullets,
|
||||
// fences, pipes, thematic breaks, HTML-ish snippets) to probe the block/inline
|
||||
// parsers on hostile but plausible input.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mdFragmentArb: fc.Arbitrary<string> = fc.constantFrom(
|
||||
'# ', '## ', '### ###', '- ', '* ', '+ ', '1. ', '> ', '>> ',
|
||||
'```', '```js', '~~~', '---', '***', '___', '| a | b |', '|---|---|',
|
||||
'[link](http://x)', '', '**', '__', '~~', '`code`',
|
||||
'<div>', '</div>', '<b>', '<!-- c -->', '<table>', '<br>', '&',
|
||||
'\t', '\n', ' ', '\\', '^[fn]', '[^1]:', '- [ ] ', '- [x] ',
|
||||
'$$', '$x$', ':::', '{.class}', '\u0000', '\uFEFF', '😀', 'مرحبا',
|
||||
);
|
||||
|
||||
// Full-unicode strings (fast-check v4 replaced fullUnicodeString with the
|
||||
// `unit: 'binary'` string option, which draws over the whole code-point range).
|
||||
const fullUnicodeStringArb = (max?: number) =>
|
||||
fc.string({ unit: 'binary', ...(max !== undefined ? { maxLength: max } : {}) });
|
||||
|
||||
const assembledMarkdownArb: fc.Arbitrary<string> = fc
|
||||
.array(fc.oneof(mdFragmentArb, fc.string(), fullUnicodeStringArb(8)), {
|
||||
minLength: 1,
|
||||
maxLength: 12,
|
||||
})
|
||||
.map((parts) => parts.join(''));
|
||||
|
||||
const parserInputArb: fc.Arbitrary<string> = fc.oneof(
|
||||
{ weight: 2, arbitrary: fc.string() },
|
||||
{ weight: 2, arbitrary: fullUnicodeStringArb() },
|
||||
{ weight: 3, arbitrary: assembledMarkdownArb },
|
||||
{ weight: 1, arbitrary: fc.array(mdFragmentArb, { minLength: 1, maxLength: 8 }).map((p) => p.join('\n')) },
|
||||
);
|
||||
|
||||
describe('#351 parser fuzz — totality on arbitrary input (P4)', () => {
|
||||
it('P4 — markdownToProseMirror never throws and always returns a schema-valid doc', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(parserInputArb, async (s) => {
|
||||
let result: any;
|
||||
try {
|
||||
result = await mdToPm(s);
|
||||
} catch (e: any) {
|
||||
throw new Error(`P4 parser THREW on input ${JSON.stringify(s)}: ${e?.message ?? e}`);
|
||||
}
|
||||
try {
|
||||
schema.nodeFromJSON(result).check();
|
||||
} catch (e: any) {
|
||||
throw new Error(
|
||||
`P4 parser produced an INVALID doc for input ${JSON.stringify(s)}: ${e?.message ?? e}\n` +
|
||||
`doc=${JSON.stringify(result).slice(0, 600)}`,
|
||||
);
|
||||
}
|
||||
}),
|
||||
{ numRuns: NUM_RUNS * 2, seed: SEED },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -374,7 +374,9 @@ describe('converter gap coverage — emission branches (specs 1–11)', () => {
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(out).toBe('- [ ] top\n - child');
|
||||
// Block children of a task item are blank-line separated (loose list) per the
|
||||
// #351 fix; the sublist stays at the fixed 2-column continuation indent.
|
||||
expect(out).toBe('- [ ] top\n\n - child');
|
||||
});
|
||||
|
||||
// 10. A bulletList inside a blockquote: each list line independently prefixed.
|
||||
|
||||
@@ -198,7 +198,11 @@ describe('convertProseMirrorToMarkdown', () => {
|
||||
}),
|
||||
);
|
||||
// First line carries the marker; the nested list is indented 2 columns.
|
||||
expect(out).toBe('- parent\n - child');
|
||||
// Block children of a list item are separated by a BLANK line (loose list):
|
||||
// this is the #351 fix — a single "\n" let a following block merge into the
|
||||
// first paragraph on re-parse (silent content loss). The blank line stays
|
||||
// inside the item, so the sublist remains nested at the 2-col marker column.
|
||||
expect(out).toBe('- parent\n\n - child');
|
||||
});
|
||||
|
||||
it('nested ordered list indents by the wider 3-col marker width', () => {
|
||||
@@ -219,8 +223,9 @@ describe('convertProseMirrorToMarkdown', () => {
|
||||
],
|
||||
}),
|
||||
);
|
||||
// "1. " is 3 columns wide, so the continuation indent is 3 spaces.
|
||||
expect(out).toBe('1. parent\n 1. child');
|
||||
// "1. " is 3 columns wide, so the continuation indent is 3 spaces. Block
|
||||
// children are blank-line separated (loose list) per the #351 fix.
|
||||
expect(out).toBe('1. parent\n\n 1. child');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -539,11 +544,12 @@ describe('convertProseMirrorToMarkdown', () => {
|
||||
);
|
||||
|
||||
// The 10th marker is the 4-column "10. "; the nested sublist line must be
|
||||
// indented exactly 4 spaces (prefix.length 3 + 1), NOT 3.
|
||||
expect(out).toContain('10. j\n 1. x');
|
||||
// indented exactly 4 spaces (prefix.length 3 + 1), NOT 3. Block children are
|
||||
// blank-line separated (loose list) per the #351 fix.
|
||||
expect(out).toContain('10. j\n\n 1. x');
|
||||
// Guard against the off-by-one (3-space) regression that would re-parse
|
||||
// the sublist as loose/sibling content on import.
|
||||
expect(out).not.toContain('10. j\n 1. x');
|
||||
expect(out).not.toContain('10. j\n\n 1. x');
|
||||
// And the single-digit items keep the narrower 3-column marker (no body
|
||||
// continuation here, but the marker itself must stay "1. ".."9. ").
|
||||
expect(out.startsWith('1. a\n2. b\n')).toBe(true);
|
||||
@@ -580,17 +586,18 @@ describe('convertProseMirrorToMarkdown', () => {
|
||||
content: [para(text('line1')), para(text('line2'))],
|
||||
}),
|
||||
);
|
||||
// NOTE(review): the spec predicted ':::warning\nline1\n\nline2\n:::' (a
|
||||
// The converter joins the callout's rendered children with a single '\n'
|
||||
// and emits an Obsidian-native callout: a `> [!type]` opener plus one
|
||||
// `>`-prefixed body line per content line. We pin the lowercasing
|
||||
// (WARNING -> warning) and the multi-child join.
|
||||
expect(out).toBe('> [!warning]\n> line1\n> line2');
|
||||
// The converter emits an Obsidian-native callout: a `> [!type]` opener plus
|
||||
// one `>`-prefixed body line per content line. Block children are separated
|
||||
// by a blank `>` line (#351 fix): a single '\n' let the two paragraphs merge
|
||||
// into one on re-parse. We pin the lowercasing (WARNING -> warning) and the
|
||||
// blank-line-separated multi-child join.
|
||||
expect(out).toBe('> [!warning]\n> line1\n>\n> line2');
|
||||
// The type is lowercased (an uppercase `[!WARNING]` would not re-import).
|
||||
expect(out.startsWith('> [!warning]\n')).toBe(true);
|
||||
expect(out).not.toContain('[!WARNING]');
|
||||
// Both paragraph children are present, each blockquote-prefixed.
|
||||
expect(out).toContain('> line1\n> line2');
|
||||
// Both paragraph children are present, each blockquote-prefixed, blank-`>`
|
||||
// separated so they stay distinct paragraphs on re-parse.
|
||||
expect(out).toContain('> line1\n>\n> line2');
|
||||
});
|
||||
|
||||
// Spec 4 — blockquote per-line prefixer over a multi-line nested callout.
|
||||
@@ -607,13 +614,11 @@ describe('convertProseMirrorToMarkdown', () => {
|
||||
],
|
||||
}),
|
||||
);
|
||||
// NOTE(review): the spec predicted '> :::info\n> a\n>\n> b\n> :::',
|
||||
// assuming the nested callout body contains a blank line between 'a' and
|
||||
// The nested callout renders as an Obsidian callout '> [!info]\n> a\n> b'
|
||||
// (single-'\n' join, no blank line). The outer blockquote prefixer then
|
||||
// prefixes each of those lines with '> ' again, yielding a doubly-nested
|
||||
// blockquote — the realistic per-line-prefix loop over a multi-line child.
|
||||
expect(out).toBe('> > [!info]\n> > a\n> > b');
|
||||
// The nested callout renders as an Obsidian callout '> [!info]\n> a\n>\n> b'
|
||||
// (blank-`>` separated children per the #351 fix). The outer blockquote
|
||||
// prefixer then prefixes each of those lines with '> ' again, yielding a
|
||||
// doubly-nested blockquote — the per-line-prefix loop over a multi-line child.
|
||||
expect(out).toBe('> > [!info]\n> > a\n> >\n> > b');
|
||||
// Every produced line carries the '> ' prefix (no line escapes to col 0).
|
||||
for (const line of out.split('\n')) {
|
||||
expect(line.startsWith('>')).toBe(true);
|
||||
|
||||
Reference in New Issue
Block a user