Files
gitmost/apps/client/src/features/page/tree/components/space-tree-row.tsx
T
agent_coder 1bcc96685e perf(client): cut background re-renders + duplicate work (#344)
Outside the editor the UI did background work on every tree event, socket
reconnect, and navigation. Tree infra (virtualization/memo/O(N) utils) was
already good — the cost was in the subscriptions and duplicates around it.
Client-only; behavior 1:1.

- Setter-only atom subscriptions → useSetAtom: space-tree-row, use-tree-mutation,
  use-tree-socket no longer subscribe every visible row to the WHOLE treeDataAtom
  value (a tree event re-rendered all ~20-30 rows, bypassing the DocTreeRow memo).
  space-tree-node-menu / mention-list read the tree imperatively (store.get) in
  their handlers only. breadcrumb.tsx uses a selectAtom slice (ancestor chain +
  field equality) instead of the whole-tree subscription.
- Socket handler cleanup (BUG): use-tree-socket + use-query-subscription now
  socket.off() their named handlers on cleanup (were accumulating listeners on
  every reconnect → duplicated invalidations/tree-walks). Mirrors
  use-notification-socket.
- Field-update tree path: invalidateOnUpdatePage does a pointwise patch of the
  cached embed subtrees instead of a blanket invalidatePageTree() (refetch storm);
  structural events keep the blanket invalidate.
- usePageMetaQuery: a content-less select slice for the 13 peripheral subscribers
  that read only title/permissions/id, so they stop re-rendering every ~3s while
  typing / on every collab page.updated (page.tsx keeps the full query for content).
- page.tsx: skeleton + placeholderData keepPreviousData (no blank flash on nav).
- Removed refetchOnMount:true where socket/mutation invalidation already keeps the
  cache fresh (favorite/space/space-watcher/workspace). KEPT it on the 3 queries
  with NO other freshness path (trash-list, created-by, recent-changes) — the
  global default is refetchOnMount:false, so those overrides are load-bearing.
- Small: resize mousemove/up attached only while dragging; per-row emoji-picker
  keydown gated on `opened`; AiChatWindow queries enabled only when the window is
  open.

Gate: client tsc 0, client vitest page+websocket 200 passed (+editor suites),
build ok.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 04:37:35 +03:00

339 lines
9.4 KiB
TypeScript

import { useRef } from "react";
import { Link, useParams } from "react-router-dom";
import { useAtom, useSetAtom } from "jotai";
import { useTranslation } from "react-i18next";
import { ActionIcon, rem, Tooltip } from "@mantine/core";
import {
IconChevronDown,
IconChevronRight,
IconClockHour4,
IconFileDescription,
IconPlus,
IconPointFilled,
IconTemplate,
} from "@tabler/icons-react";
import EmojiPicker from "@/components/ui/emoji-picker.tsx";
import { queryClient } from "@/main.tsx";
import { buildPageUrl } from "@/features/page/page.utils.ts";
import { getPageById } from "@/features/page/services/page-service.ts";
import {
useUpdatePageMutation,
fetchAllAncestorChildren,
} from "@/features/page/queries/page-query.ts";
import { useQueryEmit } from "@/features/websocket/use-query-emit.ts";
import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom.ts";
import { treeModel } from "@/features/page/tree/model/tree-model";
import { useTreeMutation } from "@/features/page/tree/hooks/use-tree-mutation.ts";
import type { SpaceTreeNode } from "@/features/page/tree/types.ts";
import type { RenderRowProps } from "./doc-tree";
import { NodeMenu } from "./space-tree-node-menu";
import classes from "@/features/page/tree/styles/tree.module.css";
import { updateTreeNodeIcon } from "@/features/page/tree/utils/utils.ts";
type SpaceTreeRowProps = RenderRowProps<SpaceTreeNode> & {
readOnly: boolean;
};
export function SpaceTreeRow({
node,
isOpen,
hasChildren,
toggleOpen,
rowRef,
tabIndex,
treeItemProps,
readOnly,
}: SpaceTreeRowProps) {
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 emit = useQueryEmit();
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [mobileSidebarOpened] = useAtom(mobileSidebarAtom);
const toggleMobileSidebar = useToggleSidebar(mobileSidebarAtom);
const canEdit = !readOnly && node.canEdit !== false;
const pageUrl = buildPageUrl(spaceSlug, node.slugId, node.name);
const prefetchPage = () => {
timerRef.current = setTimeout(async () => {
const page = await queryClient.fetchQuery({
queryKey: ["pages", node.id],
queryFn: () => getPageById({ pageId: node.id }),
staleTime: 5 * 60 * 1000,
});
if (page?.slugId) {
queryClient.setQueryData(["pages", page.slugId], page);
}
}, 150);
};
const cancelPagePrefetch = () => {
if (timerRef.current) {
window.clearTimeout(timerRef.current);
timerRef.current = null;
}
};
const handleUpdateNodeIcon = (nodeId: string, newIcon: string | null) => {
setTreeData((prev) =>
updateTreeNodeIcon(prev, nodeId, newIcon),
);
};
const handleEmojiIconClick = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
};
const handleEmojiSelect = (emoji: { native: string }) => {
handleUpdateNodeIcon(node.id, emoji.native);
updatePageMutation
.mutateAsync({ pageId: node.id, icon: emoji.native })
.then((data) => {
setTimeout(() => {
emit({
operation: "updateOne",
spaceId: node.spaceId,
entity: ["pages"],
id: node.id,
payload: { icon: emoji.native, parentPageId: data.parentPageId },
});
}, 50);
});
};
const handleRemoveEmoji = () => {
handleUpdateNodeIcon(node.id, null);
updatePageMutation.mutateAsync({ pageId: node.id, icon: null });
setTimeout(() => {
emit({
operation: "updateOne",
spaceId: node.spaceId,
entity: ["pages"],
id: node.id,
payload: { icon: null },
});
}, 50);
};
const handleLoadChildren = async () => {
if (!node.hasChildren) return;
try {
const childrenTree = await fetchAllAncestorChildren({
pageId: node.id,
spaceId: node.spaceId,
});
setTreeData((prev) =>
treeModel.appendChildren(prev, node.id, childrenTree),
);
} catch (error) {
console.error("Failed to fetch children:", error);
}
};
return (
<Link
ref={rowRef as React.Ref<HTMLAnchorElement>}
to={pageUrl}
className={classes.node}
tabIndex={tabIndex}
{...treeItemProps}
onClick={() => {
if (mobileSidebarOpened) {
toggleMobileSidebar();
}
}}
onMouseEnter={prefetchPage}
onMouseLeave={cancelPagePrefetch}
>
<PageArrow
isOpen={isOpen}
hasChildren={hasChildren}
onToggle={toggleOpen}
/>
<div onClick={handleEmojiIconClick} style={{ marginRight: "4px" }}>
<EmojiPicker
onEmojiSelect={handleEmojiSelect}
icon={
node.icon ? node.icon : <IconFileDescription size="18" />
}
readOnly={!canEdit}
removeEmojiAction={handleRemoveEmoji}
actionIconProps={{ tabIndex: -1 }}
/>
</div>
<span className={classes.text}>{node.name || t("Untitled")}</span>
{node.isTemplate === true && (
<Tooltip label={t("Template")} withArrow>
<IconTemplate
size={14}
stroke={1.5}
// Visual-only indicator: subtle and never shrinks. Pointer events
// stay enabled so the Tooltip's hover handlers fire; clicks fall
// through to the row link since no stopPropagation is used.
style={{
flexShrink: 0,
marginLeft: rem(4),
color: "var(--mantine-color-dimmed)",
}}
aria-label={t("Template")}
role="img"
/>
</Tooltip>
)}
{node.temporaryExpiresAt && (
<Tooltip
// Children ride along to trash with the note (recursive removePage).
label={t("Temporary note — moves to trash unless made permanent")}
withArrow
>
<IconClockHour4
size={14}
stroke={1.5}
// Same visual-only indicator pattern as the template icon, but
// orange to flag the impending death timer.
style={{
flexShrink: 0,
marginLeft: rem(4),
color: "var(--mantine-color-orange-6)",
}}
aria-label={t("Temporary note")}
role="img"
/>
</Tooltip>
)}
<div className={classes.actions}>
<NodeMenu node={node} canEdit={canEdit} />
{canEdit && (
<CreateNode
node={node}
isOpen={isOpen}
hasChildren={hasChildren}
onToggle={toggleOpen}
onExpandTree={handleLoadChildren}
/>
)}
</div>
</Link>
);
}
interface PageArrowProps {
isOpen: boolean;
hasChildren: boolean;
onToggle: () => void;
}
function PageArrow({ isOpen, hasChildren, onToggle }: PageArrowProps) {
const { t } = useTranslation();
if (!hasChildren) {
return (
<span
aria-hidden
className={classes.actionIcon}
style={{
width: 20,
height: 20,
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
}}
>
<IconPointFilled size={8} />
</span>
);
}
return (
<ActionIcon
size={20}
variant="subtle"
color="gray"
className={classes.actionIcon}
aria-label={isOpen ? t("Collapse") : t("Expand")}
aria-expanded={isOpen}
tabIndex={-1}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onToggle();
}}
>
{isOpen ? (
<IconChevronDown stroke={2} size={18} />
) : (
<IconChevronRight stroke={2} size={18} />
)}
</ActionIcon>
);
}
interface CreateNodeProps {
node: SpaceTreeNode;
isOpen: boolean;
hasChildren: boolean;
onToggle: () => void;
onExpandTree: () => Promise<void> | void;
}
function CreateNode({
node,
isOpen,
hasChildren,
onToggle,
onExpandTree,
}: CreateNodeProps) {
const { t } = useTranslation();
const { handleCreate } = useTreeMutation(node.spaceId);
async function handleClickCreate() {
if (node.hasChildren && !hasChildren) {
// Expand and lazy-load before creating a child. handleCreate reads the
// latest tree imperatively (via useStore) so we no longer need a
// setTimeout to wait for React to rerun the closure with fresh data.
if (!isOpen) onToggle();
await onExpandTree();
} else if (!isOpen) {
onToggle();
}
handleCreate(node.id);
}
return (
<ActionIcon
size={20}
variant="subtle"
color="gray"
className={classes.actionIcon}
aria-label={t("Create subpage of {{name}}", { name: node.name || t("Untitled") })}
tabIndex={-1}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleClickCreate();
}}
>
<IconPlus style={{ width: rem(20), height: rem(20) }} stroke={2} />
</ActionIcon>
);
}