Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

fix: perf improvements for documents (#70802)

Uladzimir Havenchyk52d5e7876790
diff --git a/frontend/src/metabase/documents/components/DocumentHeader.tsx b/frontend/src/metabase/documents/components/DocumentHeader.tsx
index 449100fc226..5718535aa09 100644
--- a/frontend/src/metabase/documents/components/DocumentHeader.tsx
+++ b/frontend/src/metabase/documents/components/DocumentHeader.tsx
@@ -2,6 +2,7 @@ import { useCallback, useState } from "react";
import { Link } from "react-router";
import { c, t } from "ttag";
+import { useListCommentsQuery } from "metabase/api";
import {
DateTime,
getFormattedTime,
@@ -29,6 +30,7 @@ import type { Document } from "metabase-types/api";
import { DocumentPublicLinkPopover } from "../../embedding/components/PublicLinkPopover";
import { trackDocumentPrint } from "../analytics";
import { DOCUMENT_TITLE_MAX_LENGTH } from "../constants";
+import { getListCommentsQuery } from "../utils/api";
import S from "./DocumentHeader.module.css";
@@ -53,7 +55,6 @@ interface DocumentHeaderProps {
onToggleBookmark: () => void;
onArchive: () => void;
onShowHistory: () => void;
- hasComments?: boolean;
}
export const DocumentHeader = ({
@@ -71,8 +72,13 @@ export const DocumentHeader = ({
onToggleBookmark,
onArchive,
onShowHistory,
- hasComments = false,
}: DocumentHeaderProps) => {
+ const { hasComments } = useListCommentsQuery(getListCommentsQuery(document), {
+ selectFromResult: ({ data }) => ({
+ hasComments: !isNewDocument && !!data?.comments?.length,
+ }),
+ });
+
const isPublicSharingEnabled = useSetting("enable-public-sharing");
const isAdmin = useSelector(getUserIsAdmin);
const [isPublicLinkPopoverOpen, setIsPublicLinkPopoverOpen] = useState(false);
diff --git a/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx b/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx
index f1ec7139c29..2e2825e0664 100644
--- a/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx
+++ b/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx
@@ -1,5 +1,6 @@
import userEvent from "@testing-library/user-event";
+import { setupCommentEndpoints } from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
import { createMockDocument, createMockUser } from "metabase-types/api/mocks";
@@ -28,7 +29,6 @@ const setup = ({
onToggleBookmark = jest.fn(),
onArchive = jest.fn(),
onShowHistory = jest.fn(),
- onToggleComments = jest.fn(),
} = {}) => {
const props = {
document,
@@ -44,9 +44,13 @@ const setup = ({
onToggleBookmark,
onArchive,
onShowHistory,
- onToggleComments,
};
+ setupCommentEndpoints([], {
+ target_type: "document",
+ target_id: document.id,
+ });
+
renderWithProviders(<DocumentHeader {...props} />, {
storeInitialState: {
currentUser: createMockUser({ is_superuser: isAdmin }),
diff --git a/frontend/src/metabase/documents/components/DocumentPage.tsx b/frontend/src/metabase/documents/components/DocumentPage.tsx
index 6e93dfca44b..89cb2deff52 100644
--- a/frontend/src/metabase/documents/components/DocumentPage.tsx
+++ b/frontend/src/metabase/documents/components/DocumentPage.tsx
@@ -26,7 +26,6 @@ import {
useDeleteBookmarkMutation,
useGetDocumentQuery,
useListBookmarksQuery,
- useListCommentsQuery,
useUpdateDocumentMutation,
} from "metabase/api";
import { canonicalCollectionId } from "metabase/collections/utils";
@@ -77,7 +76,6 @@ import {
getSelectedEmbedIndex,
getSelectedQuestionId,
} from "../selectors";
-import { getListCommentsQuery } from "../utils/api";
import { DocumentArchivedEntityBanner } from "./DocumentArchivedEntityBanner";
import { DocumentHeader } from "./DocumentHeader";
@@ -153,12 +151,6 @@ export const DocumentPage = ({
documentData = undefined;
}
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(documentData),
- );
- const hasComments =
- !!commentsData?.comments && commentsData.comments.length > 0;
-
const canWrite =
!documentData?.archived && (isNewDocument || documentData?.can_write);
@@ -505,7 +497,6 @@ export const DocumentPage = ({
onToggleBookmark={handleToggleBookmark}
onArchive={() => handleUpdate({ archived: true })}
onShowHistory={handleShowHistory}
- hasComments={hasComments}
/>
<Editor
onEditorReady={setEditorInstance}
diff --git a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx
index fe95142e698..6d9f281135b 100644
--- a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx
+++ b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx
@@ -1,5 +1,5 @@
import cx from "classnames";
-import { type CSSProperties, forwardRef, useMemo } from "react";
+import { type CSSProperties, forwardRef } from "react";
import { createPortal } from "react-dom";
import type { CommentThread } from "metabase/comments/types";
@@ -15,7 +15,7 @@ interface Props {
href: string;
show: boolean;
style: CSSProperties;
- threads: CommentThread[];
+ unresolvedCommentsCount: number;
}
export const getUnresolvedComments = (
@@ -29,11 +29,10 @@ export const getUnresolvedComments = (
};
export const CommentsMenu = forwardRef<HTMLDivElement, Props>(
- function CommentsMenu({ active, href, show, style, threads }: Props, ref) {
- const unresolvedCommentsCount = useMemo(
- () => getUnresolvedComments(threads).length,
- [threads],
- );
+ function CommentsMenu(
+ { active, href, show, style, unresolvedCommentsCount }: Props,
+ ref,
+ ) {
const hasUnresolvedComments = unresolvedCommentsCount > 0;
return createPortal(
diff --git a/frontend/src/metabase/documents/components/Editor/Editor.tsx b/frontend/src/metabase/documents/components/Editor/Editor.tsx
index c0f27cdb552..2cc863bd773 100644
--- a/frontend/src/metabase/documents/components/Editor/Editor.tsx
+++ b/frontend/src/metabase/documents/components/Editor/Editor.tsx
@@ -3,8 +3,7 @@ import { Placeholder } from "@tiptap/extension-placeholder";
import type { JSONContent, Editor as TiptapEditor } from "@tiptap/react";
import { EditorContent, useEditor } from "@tiptap/react";
import cx from "classnames";
-import type React from "react";
-import { useEffect, useMemo } from "react";
+import React, { useEffect, useMemo } from "react";
import { useLatest, usePrevious } from "react-use";
import { t } from "ttag";
@@ -94,190 +93,198 @@ export interface EditorProps {
editorContainerRef?: React.RefObject<HTMLDivElement>;
}
-export const Editor: React.FC<EditorProps> = ({
- onEditorReady,
- onCardEmbedsChange,
- initialContent,
- onChange,
- editable = true,
- onQuestionSelect,
- isLoading = false,
- editorContainerRef,
-}) => {
- const siteUrl = useSelector((state) => getSetting(state, "site-url"));
- const { getState } = useStore();
+export const Editor: React.FC<EditorProps> = React.memo(
+ ({
+ onEditorReady,
+ onCardEmbedsChange,
+ initialContent,
+ onChange,
+ editable = true,
+ onQuestionSelect,
+ isLoading = false,
+ editorContainerRef,
+ }) => {
+ const siteUrl = useSelector((state) => getSetting(state, "site-url"));
+ const { getState } = useStore();
- const extensions = useMemo(
- () => [
- CustomStarterKit.configure({
- dropcursor: {
- color: DROP_ZONE_COLOR,
- width: 2,
- class: DropCursorS.dropCursor,
- },
- }),
- Image.configure({
- inline: false,
- HTMLAttributes: {
- class: S.img,
- },
- }),
- SmartLink.configure({
- HTMLAttributes: {
- class: "smart-link",
- },
- siteUrl,
- }),
- PlainLink.configure({
- defaultProtocol: "https",
- }),
- Placeholder.configure({
- placeholder: t`Start writing, type "/" to list commands, or "@" to mention an item...`,
- }),
- CardEmbed,
- FlexContainer,
- SupportingText,
- MentionExtension.configure({
- suggestion: {
- allow: ({ state }) => !isMetabotBlock(state),
- render: createSuggestionRenderer(MentionSuggestion),
- },
- }),
- CommandExtension.configure({
- suggestion: {
- allow: ({ state }) => !isMetabotBlock(state),
- render: createSuggestionRenderer(CommandSuggestion),
- },
- }),
- MetabotNode.configure({
- serializePrompt: getMetabotPromptSerializer(getState),
- }),
- DisableMetabotSidebar,
- MetabotMentionExtension.configure({
- suggestion: {
- allow: ({ state }) => isMetabotBlock(state),
- render: createSuggestionRenderer(MetabotMentionSuggestion),
- },
- }),
- ResizeNode,
- HandleEditorDrop,
- ],
- [siteUrl, getState],
- );
+ const extensions = useMemo(
+ () => [
+ CustomStarterKit.configure({
+ dropcursor: {
+ color: DROP_ZONE_COLOR,
+ width: 2,
+ class: DropCursorS.dropCursor,
+ },
+ }),
+ Image.configure({
+ inline: false,
+ HTMLAttributes: {
+ class: S.img,
+ },
+ }),
+ SmartLink.configure({
+ HTMLAttributes: {
+ class: "smart-link",
+ },
+ siteUrl,
+ }),
+ PlainLink.configure({
+ defaultProtocol: "https",
+ }),
+ Placeholder.configure({
+ placeholder: t`Start writing, type "/" to list commands, or "@" to mention an item...`,
+ }),
+ CardEmbed,
+ FlexContainer,
+ SupportingText,
+ MentionExtension.configure({
+ suggestion: {
+ allow: ({ state }) => !isMetabotBlock(state),
+ render: createSuggestionRenderer(MentionSuggestion),
+ },
+ }),
+ CommandExtension.configure({
+ suggestion: {
+ allow: ({ state }) => !isMetabotBlock(state),
+ render: createSuggestionRenderer(CommandSuggestion),
+ },
+ }),
+ MetabotNode.configure({
+ serializePrompt: getMetabotPromptSerializer(getState),
+ }),
+ DisableMetabotSidebar,
+ MetabotMentionExtension.configure({
+ suggestion: {
+ allow: ({ state }) => isMetabotBlock(state),
+ render: createSuggestionRenderer(MetabotMentionSuggestion),
+ },
+ }),
+ ResizeNode,
+ HandleEditorDrop,
+ ],
+ [siteUrl, getState],
+ );
- const editor = useEditor(
- {
- extensions,
- content: initialContent || "",
- autofocus: false,
- editable,
- immediatelyRender: false,
- onUpdate: ({ editor }) => {
- if (onChange) {
- const currentContent = editor.getJSON();
- onChange(currentContent);
- }
+ const editor = useEditor(
+ {
+ extensions,
+ content: initialContent || "",
+ autofocus: false,
+ editable,
+ immediatelyRender: false,
+ onUpdate: ({ editor }) => {
+ if (onChange) {
+ const currentContent = editor.getJSON();
+ onChange(currentContent);
+ }
+ },
},
- },
- [],
- );
+ [],
+ );
- // Handle content updates when initialContent changes
- const previousContentRef = useLatest(usePrevious(initialContent));
- useEffect(() => {
- const previousContent = previousContentRef.current;
- if (editor && initialContent !== undefined) {
- // Use Promise.resolve() to avoid flushSync warning
- Promise.resolve().then(() => {
- editor
- .chain()
- .setMeta("addToHistory", previousContent != null)
- .setContent(initialContent || "")
- .run();
- });
- }
- }, [editor, initialContent, previousContentRef]);
+ // Handle content updates when initialContent changes
+ const previousContentRef = useLatest(usePrevious(initialContent));
+ useEffect(() => {
+ const previousContent = previousContentRef.current;
+ if (editor && initialContent !== undefined) {
+ // Use Promise.resolve() to avoid flushSync warning
+ Promise.resolve().then(() => {
+ editor
+ .chain()
+ .setMeta("addToHistory", previousContent != null)
+ .setContent(initialContent || "")
+ .run();
+ });
+ }
+ }, [editor, initialContent, previousContentRef]);
- // Notify parent when editor is ready
- useEffect(() => {
- if (editor && onEditorReady) {
- onEditorReady(editor);
- }
- }, [editor, onEditorReady]);
+ // Notify parent when editor is ready
+ useEffect(() => {
+ if (editor && onEditorReady) {
+ onEditorReady(editor);
+ }
+ }, [editor, onEditorReady]);
- // Update editor editable state
- useEffect(() => {
- if (editor) {
- editor.setEditable(editable);
- }
- }, [editor, editable]);
+ // Update editor editable state
+ useEffect(() => {
+ if (editor) {
+ editor.setEditable(editable);
+ }
+ }, [editor, editable]);
- useCardEmbedsTracking(editor, onCardEmbedsChange);
- useQuestionSelection(editor, onQuestionSelect);
+ useCardEmbedsTracking(editor, onCardEmbedsChange);
+ useQuestionSelection(editor, onQuestionSelect);
- if (!editor) {
- return null;
- }
+ if (!editor) {
+ return null;
+ }
+
+ if (isLoading) {
+ return (
+ <Box className={cx(S.editor, DND_IGNORE_CLASS_NAME)}>
+ <Loader data-testid="editor-loader" />
+ </Box>
+ );
+ }
- if (isLoading) {
return (
<Box className={cx(S.editor, DND_IGNORE_CLASS_NAME)}>
- <Loader data-testid="editor-loader" />
- </Box>
- );
- }
+ <Box
+ className={S.editorContent}
+ ref={editorContainerRef}
+ onClick={(e) => {
+ // Focus editor when clicking on empty space
+ const target = e.target;
+ if (!(target instanceof HTMLElement)) {
+ return;
+ }
- return (
- <Box className={cx(S.editor, DND_IGNORE_CLASS_NAME)}>
- <Box
- className={S.editorContent}
- ref={editorContainerRef}
- onClick={(e) => {
- // Focus editor when clicking on empty space
- const target = e.target as HTMLElement;
- if (
- target.classList.contains(S.editorContent) ||
- target.classList.contains("ProseMirror")
- ) {
- const clickY = e.clientY;
- const proseMirrorElement = target.querySelector(".ProseMirror");
+ if (
+ target.classList.contains(S.editorContent) ||
+ target.classList.contains("ProseMirror")
+ ) {
+ const clickY = e.clientY;
+ const proseMirrorElement = target.querySelector(".ProseMirror");
- if (proseMirrorElement) {
- const proseMirrorRect =
- proseMirrorElement.getBoundingClientRect();
- const isClickBelowContent = clickY > proseMirrorRect.bottom;
+ if (proseMirrorElement) {
+ const proseMirrorRect =
+ proseMirrorElement.getBoundingClientRect();
+ const isClickBelowContent = clickY > proseMirrorRect.bottom;
- if (isClickBelowContent) {
- // Only move to end if clicking below the actual content
- editor.commands.focus("end");
+ if (isClickBelowContent) {
+ // Only move to end if clicking below the actual content
+ editor.commands.focus("end");
+ } else {
+ // Just focus without changing cursor position for clicks in padding areas
+ editor.commands.focus();
+ }
} else {
- // Just focus without changing cursor position for clicks in padding areas
+ // Fallback: just focus without position change
editor.commands.focus();
}
- } else {
- // Fallback: just focus without position change
- editor.commands.focus();
}
- }
- }}
- >
- <EditorContent data-testid="document-content" editor={editor} />
+ }}
+ >
+ <EditorContent data-testid="document-content" editor={editor} />
- {editable && (
- <EditorBubbleMenu
- editor={editor}
- disallowedNodes={BUBBLE_MENU_DISALLOWED_NODES}
- disallowedFullySelectedNodes={
- BUBBLE_MENU_DISALLOWED_FULLY_SELECTED_NODES
- }
- />
- )}
- <Box pos="absolute" top={0} left={0} w="100%">
- <Box className={S.editorContentInner} pos="relative">
- <LinkHoverMenu editor={editor} editable={editable} />
+ {editable && (
+ <EditorBubbleMenu
+ editor={editor}
+ disallowedNodes={BUBBLE_MENU_DISALLOWED_NODES}
+ disallowedFullySelectedNodes={
+ BUBBLE_MENU_DISALLOWED_FULLY_SELECTED_NODES
+ }
+ />
+ )}
+ <Box pos="absolute" top={0} left={0} w="100%">
+ <Box className={S.editorContentInner} pos="relative">
+ <LinkHoverMenu editor={editor} editable={editable} />
+ </Box>
</Box>
</Box>
</Box>
- </Box>
- );
-};
+ );
+ },
+);
+
+Editor.displayName = "Editor";
diff --git a/frontend/src/metabase/documents/hooks/use-block-menus.ts b/frontend/src/metabase/documents/hooks/use-block-menus.ts
index 5513af88d3f..3a8ec73f54e 100644
--- a/frontend/src/metabase/documents/hooks/use-block-menus.ts
+++ b/frontend/src/metabase/documents/hooks/use-block-menus.ts
@@ -1,15 +1,13 @@
import { autoUpdate, useFloating } from "@floating-ui/react";
import type { Editor, NodeViewProps } from "@tiptap/core";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
+import { useUnresolvedCommentsCount } from "metabase/documents/hooks/use-unresolved-comments-count";
import {
getChildTargetId,
getCurrentDocument,
getHoveredChildTargetId,
} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
import { isTopLevel } from "metabase/documents/utils/editorNodeUtils";
import { isWithinIframe } from "metabase/lib/dom";
import { useSelector } from "metabase/lib/redux";
@@ -38,22 +36,16 @@ export function useBlockMenus({
const childTargetId = useSelector(getChildTargetId);
const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
+ const { _id } = node.attrs;
+
+ const unresolvedCommentsCount = useUnresolvedCommentsCount(_id);
+
const [hovered, setHovered] = useState(false);
const [rendered, setRendered] = useState(false);
- const { _id } = node.attrs;
const isOpen = childTargetId === _id;
const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
-
const { refs: commentsRefs, floatingStyles: commentsFloatingStyles } =
useFloating({
placement: "right-start",
@@ -105,7 +97,7 @@ export function useBlockMenus({
isHovered,
hovered,
setHovered,
- threads,
+ unresolvedCommentsCount,
document,
shouldShowMenus,
anchorUrl,
diff --git a/frontend/src/metabase/documents/hooks/use-unresolved-comments-count.ts b/frontend/src/metabase/documents/hooks/use-unresolved-comments-count.ts
new file mode 100644
index 00000000000..8b9924de56b
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-unresolved-comments-count.ts
@@ -0,0 +1,27 @@
+import { useListCommentsQuery } from "metabase/api";
+import { getTargetChildCommentThreads } from "metabase/comments/utils";
+import { getUnresolvedComments } from "metabase/documents/components/Editor/CommentsMenu";
+import { getCurrentDocument } from "metabase/documents/selectors";
+import { getListCommentsQuery } from "metabase/documents/utils/api";
+import { useSelector } from "metabase/lib/redux";
+
+export function useUnresolvedCommentsCount(targetId: string) {
+ const document = useSelector(getCurrentDocument);
+
+ const { unresolvedCommentsCount } = useListCommentsQuery(
+ getListCommentsQuery(document),
+ {
+ selectFromResult: ({ data: commentsData }) => {
+ const threads = getTargetChildCommentThreads(
+ commentsData?.comments,
+ targetId,
+ );
+ return {
+ unresolvedCommentsCount: getUnresolvedComments(threads).length,
+ };
+ },
+ },
+ );
+
+ return unresolvedCommentsCount;
+}
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
index 265bd9957b2..a57039b2907 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Blockquote/Blockquote.tsx
@@ -40,7 +40,7 @@ export const BlockquoteNodeView = ({ node, editor, getPos }: NodeViewProps) => {
isHovered,
hovered,
setHovered,
- threads,
+ unresolvedCommentsCount,
document,
shouldShowMenus,
setReferenceElement,
@@ -70,7 +70,7 @@ export const BlockquoteNodeView = ({ node, editor, getPos }: NodeViewProps) => {
ref={commentsRefs.setFloating}
show={isOpen || hovered}
style={commentsFloatingStyles}
- threads={threads}
+ unresolvedCommentsCount={unresolvedCommentsCount}
/>
)}
</>
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx
index 2754673c12e..7d3812e91db 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/BulletList/BulletList.tsx
@@ -36,7 +36,7 @@ export const BulletListNodeView = ({ node, editor, getPos }: NodeViewProps) => {
isHovered,
hovered,
setHovered,
- threads,
+ unresolvedCommentsCount,
document,
shouldShowMenus,
setReferenceElement,
@@ -67,7 +67,7 @@ export const BulletListNodeView = ({ node, editor, getPos }: NodeViewProps) => {
ref={commentsRefs.setFloating}
show={isOpen || hovered}
style={commentsFloatingStyles}
- threads={threads}
+ unresolvedCommentsCount={unresolvedCommentsCount}
/>
)}
</>
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
index 78bd6713b7c..97a844b87ac 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
@@ -13,8 +13,6 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { push } from "react-router-redux";
import { t } from "ttag";
-import { useListCommentsQuery } from "metabase/api";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
import { Ellipsified } from "metabase/common/components/Ellipsified";
import { ExplicitSizeRefreshModeContext } from "metabase/common/components/ExplicitSize/ExplicitSize";
import { QuestionPickerModal } from "metabase/common/components/Pickers";
@@ -24,7 +22,6 @@ import {
trackDocumentAddSupportingText,
trackDocumentReplaceCard,
} from "metabase/documents/analytics";
-import { getUnresolvedComments } from "metabase/documents/components/Editor/CommentsMenu";
import { EDITOR_STYLE_BOUNDARY_CLASS } from "metabase/documents/components/Editor/constants";
import { MAX_GROUP_SIZE } from "metabase/documents/constants";
import {
@@ -32,13 +29,13 @@ import {
openVizSettingsSidebar,
} from "metabase/documents/documents.slice";
import { useCardData } from "metabase/documents/hooks/use-card-data";
+import { useUnresolvedCommentsCount } from "metabase/documents/hooks/use-unresolved-comments-count";
import {
getChildTargetId,
getCurrentDocument,
getHasUnsavedChanges,
getHoveredChildTargetId,
} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
import { useDispatch, useSelector } from "metabase/lib/redux";
import { usePublicDocumentContext } from "metabase/public/contexts/PublicDocumentContext";
import { usePublicDocumentCardData } from "metabase/public/hooks/use-public-document-card-data";
@@ -174,23 +171,12 @@ export const CardEmbedComponent = memo(
const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
const document = useSelector(getCurrentDocument);
const { publicDocumentUuid } = usePublicDocumentContext();
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
+ const { _id } = node.attrs;
+ const unresolvedCommentsCount = useUnresolvedCommentsCount(_id);
- const comments = commentsData?.comments;
const hasUnsavedChanges = useSelector(getHasUnsavedChanges);
- const { _id } = node.attrs;
const isOpen = childTargetId === _id;
const isHovered = hoveredChildTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const unresolvedCommentsCount = useMemo(
- () => getUnresolvedComments(threads).length,
- [threads],
- );
const commentsPath = document
? `/document/${document.id}/comments/${_id}`
: "";
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
index d8cb566e3c9..1c82eb3ba44 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CodeBlock/CodeBlock.tsx
@@ -117,7 +117,7 @@ export const CodeBlockNodeView = ({ node, editor, getPos }: NodeViewProps) => {
isHovered,
hovered,
setHovered,
- threads,
+ unresolvedCommentsCount,
document,
shouldShowMenus,
setReferenceElement,
@@ -156,7 +156,7 @@ export const CodeBlockNodeView = ({ node, editor, getPos }: NodeViewProps) => {
ref={commentsRefs.setFloating}
show={isOpen || hovered}
style={commentsFloatingStyles}
- threads={threads}
+ unresolvedCommentsCount={unresolvedCommentsCount}
/>
)}
</>
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
index ed33513ccf5..816f3285c1a 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Heading/Heading.tsx
@@ -56,7 +56,7 @@ export const HeadingNodeView = ({ node, editor, getPos }: NodeViewProps) => {
isHovered,
hovered,
setHovered,
- threads,
+ unresolvedCommentsCount,
document,
shouldShowMenus,
anchorUrl,
@@ -98,7 +98,7 @@ export const HeadingNodeView = ({ node, editor, getPos }: NodeViewProps) => {
ref={commentsRefs.setFloating}
show={isOpen || hovered}
style={commentsFloatingStyles}
- threads={threads}
+ unresolvedCommentsCount={unresolvedCommentsCount}
/>
</>
)}
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx
index 057d4a8f797..01f614ed6a5 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/OrderedList/OrderedList.tsx
@@ -52,7 +52,7 @@ export const OrderedListNodeView = ({
isHovered,
hovered,
setHovered,
- threads,
+ unresolvedCommentsCount,
document,
shouldShowMenus,
setReferenceElement,
@@ -83,7 +83,7 @@ export const OrderedListNodeView = ({
ref={commentsRefs.setFloating}
show={isOpen || hovered}
style={commentsFloatingStyles}
- threads={threads}
+ unresolvedCommentsCount={unresolvedCommentsCount}
/>
)}
</>
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx
index 218cc8309b0..7b6df342b84 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Paragraph/Paragraph.tsx
@@ -44,7 +44,7 @@ export const ParagraphNodeView = ({
isHovered,
hovered,
setHovered,
- threads,
+ unresolvedCommentsCount,
document,
shouldShowMenus,
setReferenceElement,
@@ -79,7 +79,7 @@ export const ParagraphNodeView = ({
ref={commentsRefs.setFloating}
show={isOpen || hovered}
style={commentsFloatingStyles}
- threads={threads}
+ unresolvedCommentsCount={unresolvedCommentsCount}
/>
)}
</>
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
index 559116e4eaf..f16251e6b1e 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
@@ -11,18 +11,14 @@ import {
ReactNodeViewRenderer,
} from "@tiptap/react";
import cx from "classnames";
-import { useMemo } from "react";
import { push } from "react-router-redux";
import { t } from "ttag";
-import { useListCommentsQuery } from "metabase/api/comment";
-import { getTargetChildCommentThreads } from "metabase/comments/utils";
-import { getUnresolvedComments } from "metabase/documents/components/Editor/CommentsMenu";
+import { useUnresolvedCommentsCount } from "metabase/documents/hooks/use-unresolved-comments-count";
import {
getChildTargetId,
getCurrentDocument,
} from "metabase/documents/selectors";
-import { getListCommentsQuery } from "metabase/documents/utils/api";
import { isWithinIframe } from "metabase/lib/dom";
import { useDispatch, useSelector } from "metabase/lib/redux/hooks";
import { DropZone } from "metabase/rich_text_editing/tiptap/extensions/shared/dnd/DropZone";
@@ -142,20 +138,9 @@ const SupportingTextComponent = ({
}: NodeViewProps) => {
const childTargetId = useSelector(getChildTargetId);
const document = useSelector(getCurrentDocument);
- const { data: commentsData } = useListCommentsQuery(
- getListCommentsQuery(document),
- );
- const comments = commentsData?.comments;
const { _id } = node.attrs;
+ const unresolvedCommentsCount = useUnresolvedCommentsCount(_id);
const isOpen = childTargetId === _id;
- const threads = useMemo(
- () => getTargetChildCommentThreads(comments, _id),
- [comments, _id],
- );
- const unresolvedCommentsCount = useMemo(
- () => getUnresolvedComments(threads).length,
- [threads],
- );
const commentsPath = document
? `/document/${document.id}/comments/${_id}`
: "";