:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(frontend): load the rich text editor only where it renders (#127336)
Paul D'Ambra93ebb3f7c194
diff --git a/.semgrep/rules/devex/rich-text-editor-via-lazy-wrapper.yaml b/.semgrep/rules/devex/rich-text-editor-via-lazy-wrapper.yamlnew file mode 100644index 000000000000..6f12c8c22cfe--- /dev/null+++ b/.semgrep/rules/devex/rich-text-editor-via-lazy-wrapper.yaml@@ -0,0 +1,64 @@+rules:+ - id: rich-text-editor-via-lazy-wrapper+ message: |+ The rich text editor stack (`@tiptap/*` and `prosemirror-*`, about 450 KiB minified) is+ imported outside an editor implementation. A static import from a scene, a logic or a+ shared helper puts the whole stack on the eager path of every scene that reaches it.++ Render rich text through `lib/components/RichContentEditor/LazyRichContent`+ (`LazyTextContent`, `LazyRichContentPreview`, `LazyLemonRichContentEditor`), and call+ `preloadRichContent()` from a logic when its data shows that rich text renders on first paint.+ For text of a rich content document, use `richContentToText` from+ `lib/components/RichContentEditor/richContentText`.+ For types, write `import type { ... }`: esbuild drops a type-only import.++ A new editor implementation can import the stack directly. Add its directory to+ `paths.exclude` in this rule, and load it behind a lazy boundary.+ severity: ERROR+ languages: [typescript, javascript]+ paths:+ include:+ - /frontend/src+ - /products+ - /common+ exclude:+ - '*.test.ts'+ - '*.test.tsx'+ - '*.stories.tsx'+ - /products/desktop+ # Editor implementations. Code outside them reaches these modules only through a lazy import.+ - /frontend/src/lib/components/RichContentEditor+ - /frontend/src/lib/components/Cards/TextCard+ - /frontend/src/lib/components/MarkdownEditor+ - /frontend/src/lib/utils/markdown.ts+ - /frontend/src/lib/utils/parseMarkdownToTipTap.ts+ - /frontend/src/scenes/max/utils/markdownToTiptap.ts+ - /frontend/src/scenes/notebooks+ - /frontend/src/scenes/product-tours/editor+ - /products/conversations/frontend/components/Editor+ - /products/conversations/frontend/components/Macros/MacroSuggestionExtension.tsx+ - /products/dashboards/frontend/components/ImageTile/imageTileMarkdown.ts+ - /products/data_catalog/frontend/components/MetricMarkdownEditor.tsx+ - /products/data_catalog/frontend/components/metricMarkdown.ts+ - /products/data_catalog/frontend/components/metricMarkdownSlashCommands.tsx+ # Anchors the packages into a shared chunk. It is a build entry, not app code.+ - /frontend/src/sharedChunkAnchors.ts+ patterns:+ - pattern-either:+ - pattern: import $X from '$MOD'+ - pattern: import { ... } from '$MOD'+ - pattern: import * as $X from '$MOD'+ - pattern: import '$MOD'+ - pattern: import('$MOD')+ - pattern: require('$MOD')+ - pattern: export * from '$MOD'+ # Semgrep matches `import type` with the patterns above, so a regex lets type imports through.+ - pattern-not-regex: (?m)^import\s+type\s+ # JSONContent is only a type, so esbuild drops this import. Older code wrote it without `type`.+ - pattern-not-regex: (?m)^import \{ JSONContent \} from '@tiptap/core'+ - metavariable-regex:+ metavariable: $MOD+ regex: ^['"]?(@tiptap/|prosemirror-)+ metadata:+ category: performance+ confidence: HIGHdiff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex ca607b16349e..d5571e39ab0b 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -23,6 +23,12 @@ const reportOnly = process.argv.includes('--report-only')const assertReportIndex = process.argv.indexOf('--assert-report')const failForbiddenHits = process.argv.includes('--fail-forbidden-hits')+// The rich text stack loads with the first text tile, comment or editor, through+// lib/components/RichContentEditor/LazyRichContent. A hit means a static import of an editor module.+const RICH_TEXT_STACK = ['node_modules/@tiptap/', 'node_modules/prosemirror-', 'node_modules/marked/']+// The emoji picker loads with the editor that opens it.+const EMOJI_PICKER = 'node_modules/frimousse/'+// The eager graph is everything a root actually SHIPS on the critical path — the bytes a// browser downloads and parses before that surface is interactive. It is measured from the// esbuild OUTPUT chunks: the root's entry chunk plus every chunk reachable through static@@ -196,6 +202,8 @@ const ROOTS = [budgetBytes: 10_314_000,forbidden: [QUILL_UMBRELLA_DIST,+ ...RICH_TEXT_STACK,+ EMOJI_PICKER,// Neither scene plays recordings. A hit means a static import pulled the playlist and player onto it.'src/scenes/session-recordings/playlist/SessionRecordingsPlaylist.tsx',// Only web analytics insights render this tile. A hit means a static import put the web@@ -260,6 +268,8 @@ const ROOTS = [budgetBytes: 9_869_000,forbidden: [QUILL_UMBRELLA_DIST,+ ...RICH_TEXT_STACK,+ EMOJI_PICKER,// Neither scene plays recordings. A hit means a static import pulled the playlist and player onto it.'src/scenes/session-recordings/playlist/SessionRecordingsPlaylist.tsx',// Only web analytics insights render this tile. A hit means a static import put the web@@ -288,6 +298,8 @@ const ROOTS = [budgetBytes: 10_999_000,forbidden: [QUILL_UMBRELLA_DIST,+ ...RICH_TEXT_STACK,+ EMOJI_PICKER,// Only the live tab renders this dashboard. Its world map holds about 1 MiB of country shapes.'src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx','products/product_analytics/frontend/insights/trends/WorldMap/countryVectors.tsx',@@ -310,6 +322,7 @@ const ROOTS = [budgetBytes: 8_520_000,forbidden: [QUILL_UMBRELLA_DIST,+ ...RICH_TEXT_STACK,// The player shows a snapshot of a few settings. A hit means it imports settingsLogic again,// which holds every settings page.'src/scenes/settings/SettingsMap.tsx',diff --git a/frontend/bin/layer-baseline.txt b/frontend/bin/layer-baseline.txtindex ab6095d7831f..dc7f85178c63 100644--- a/frontend/bin/layer-baseline.txt+++ b/frontend/bin/layer-baseline.txt@@ -100,7 +100,6 @@ frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts -> frontendfrontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts -> frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsfrontend/src/lib/components/Alerting/AlertWizard/steps/DestinationStep.tsx -> frontend/src/scenes/hog-functions/configuration/HogFunctionIcon.tsxfrontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx -> frontend/src/scenes/insights/insightLogic.tsx-frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx -> products/annotations/frontend/components/AnnotationModal.tsxfrontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx -> products/annotations/frontend/logics/annotationModalLogic.tsfrontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts -> frontend/src/scenes/insights/insightLogic.tsxfrontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts -> frontend/src/scenes/insights/insightVizDataLogic.ts@@ -317,7 +316,6 @@ frontend/src/models/cohortsModel.ts -> frontend/src/scenes/cohorts/CohortFiltersfrontend/src/models/cohortsModel.ts -> products/persons/frontend/logics/personsLogic.tsxfrontend/src/models/insightsModel.tsx -> frontend/src/scenes/insights/utils/api.tsfrontend/src/models/notebooksModel.ts -> frontend/src/scenes/analytics/analyticsBackLink.ts-frontend/src/models/notebooksModel.ts -> frontend/src/scenes/notebooks/Notebook/notebookLogic.tsfrontend/src/models/notebooksModel.ts -> frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.tsfrontend/src/models/notebooksModel.ts -> frontend/src/scenes/notebooks/NotebookTemplates/notebookTemplates.tsfrontend/src/models/notebooksModel.ts -> frontend/src/scenes/notebooks/types.tsdiff --git a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsxindex c9ffb4ad5160..a236c104a762 100644--- a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx+++ b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx@@ -2,18 +2,20 @@ import './AnnotationsOverlay.scss'import { BindLogic, useActions, useValues } from 'kea'import posthog from 'posthog-js'-import React, { useEffect, useRef, useState } from 'react'+import React, { Suspense, useEffect, useRef, useState } from 'react'import { IconPencil, IconPlusSmall, IconTrash } from '@posthog/icons'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'+import { LazyTextContent } from 'lib/components/RichContentEditor/LazyRichContent'import { dayjs } from 'lib/dayjs'+import { useKeepMountedWhileOpen } from 'lib/hooks/useKeepMountedWhileOpen'import { LemonBadge } from 'lib/lemon-ui/LemonBadge/LemonBadge'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonModal } from 'lib/lemon-ui/LemonModal'import { Popover } from 'lib/lemon-ui/Popover/Popover'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { lazyWithRetry } from 'lib/utils/retryImport'import { pluralize } from 'lib/utils/strings'import { shortTimeZone } from 'lib/utils/timezones'import { insightLogic } from 'scenes/insights/insightLogic'@@ -21,13 +23,17 @@ import { insightLogic } from 'scenes/insights/insightLogic'import { annotationsModel } from '~/models/annotationsModel'import { AnnotationType, DatedAnnotationType, IntervalType } from '~/types'-import { AnnotationModal } from 'products/annotations/frontend/components/AnnotationModal'import { annotationModalLogic, annotationScopeToName } from 'products/annotations/frontend/logics/annotationModalLogic'import { AnnotationsOverlayLogicProps, annotationsOverlayLogic } from './annotationsOverlayLogic'import { useAnnotationPopoverHover } from './useAnnotationPopoverHover'import { AnnotationsChartGeometry, useAnnotationsPositioning } from './useAnnotationsPositioning'+// The modal carries a markdown editor, which a chart needs only once someone adds or edits an annotation.+const AnnotationModal = lazyWithRetry(() =>+ import('products/annotations/frontend/components/AnnotationModal').then((m) => ({ default: m.AnnotationModal }))+)+const MIN_BADGE_SPACING_PX = 24/** Clusters anchor on their starting badge (leftPx) so a chain of near-adjacent badges* can't keep absorbing each other into one oversized cluster spanning a wide date range. */@@ -122,6 +128,9 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({const { activeDate, tickDates, annotationBadgeDataIndices, groupedAnnotations, readOnly } = useValues(logic)const { closePopover, deactivateDate } = useActions(logic)const { closeModal } = useActions(annotationModalLogic)+ const { isModalOpen } = useValues(annotationModalLogic)+ // Grace-extended so the modal's exit animation finishes before its lazy subtree unmounts.+ const shouldRenderAnnotationModal = useKeepMountedWhileOpen(isModalOpen)const hover = useAnnotationPopoverHover(deactivateDate)useEffect(() => {@@ -240,10 +249,14 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({hover={hover}/>)}- <AnnotationModal- contentRef={(el) => (modalContentRef.current = el)}- overlayRef={(el) => (modalOverlayRef.current = el)}- />+ {shouldRenderAnnotationModal ? (+ <Suspense fallback={null}>+ <AnnotationModal+ contentRef={(el) => (modalContentRef.current = el)}+ overlayRef={(el) => (modalOverlayRef.current = el)}+ />+ </Suspense>+ ) : null}</div></BindLogic>)@@ -502,7 +515,7 @@ function AnnotationCard({ annotation }: { annotation: AnnotationType }): JSX.Ele{isSystemAnnotation && (<LemonBadge status="primary" size="small" className="flex-shrink-0" content="PostHog" />)}- <TextContent text={annotation.content ?? ''} data-attr="annotation-overlay-rendered-content" />+ <LazyTextContent text={annotation.content ?? ''} data-attr="annotation-overlay-rendered-content" /></div>{!isSystemAnnotation && (<div className="leading-6 mt-2 flex flex-row items-center justify-between">diff --git a/frontend/src/lib/components/Cards/TextCard/TextCard.test.tsx b/frontend/src/lib/components/Cards/TextCard/TextCard.test.tsxindex 54d19ecce627..19e361e245ce 100644--- a/frontend/src/lib/components/Cards/TextCard/TextCard.test.tsx+++ b/frontend/src/lib/components/Cards/TextCard/TextCard.test.tsx@@ -4,7 +4,8 @@ import { fireEvent, render } from '@testing-library/react'import { DashboardPlacement, DashboardTile } from '~/types'-import { TextCard, TextContent } from './TextCard'+import { TextCard } from './TextCard'+import { TextContent } from './TextContent'const makeTextTile = (overrides: Partial<DashboardTile> = {}): DashboardTile =>({diff --git a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx b/frontend/src/lib/components/Cards/TextCard/TextCard.tsxindex b1dd7446b413..1bcf8f2da1af 100644--- a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx+++ b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx@@ -1,22 +1,17 @@import './TextCard.scss'-import { EditorContent } from '@tiptap/react'import clsx from 'clsx'-import React, { memo, useEffect, useMemo } from 'react'+import React from 'react'import 'lib/components/Cards/CardMeta.scss'-import 'lib/components/MarkdownEditor/shared/RichMarkdownEditor.scss'import { Resizeable } from 'lib/components/Cards/CardMeta'import { DashboardResizeHandles } from 'lib/components/Cards/handles'import { EditModeEdge, EditModeEdgeOverlay } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'-import { useRichContentEditor } from 'lib/components/RichContentEditor'+import { LazyTextContent } from 'lib/components/RichContentEditor/LazyRichContent'import { More, MoreProps } from 'lib/lemon-ui/LemonButton/More'-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { DashboardPlacement, DashboardTile } from '~/types'-import { TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS, textCardConverter } from './textCardMarkdown'-interface TextCardProps extends React.HTMLAttributes<HTMLDivElement>, Resizeable {textTile: DashboardTileplacement: DashboardPlacement@@ -32,44 +27,6 @@ interface TextCardProps extends React.HTMLAttributes<HTMLDivElement>, ResizeableshowEditingControls?: boolean}-interface TextCardBodyProps extends Pick<React.HTMLAttributes<HTMLDivElement>, 'className'> {- text: string- closeDetails?: () => void-}--function TextContentImpl({ text, closeDetails, className }: TextCardBodyProps): JSX.Element {- const initialDoc = useMemo(() => textCardConverter.markdownToDoc(text), [text])-- const editor = useRichContentEditor({- extensions: TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS,- initialContent: initialDoc,- disabled: true,- })-- useEffect(() => {- if (!editor) {- return- }-- editor.commands.setContent(initialDoc, { emitUpdate: false })- }, [editor, initialDoc])-- return (- <div className={clsx('w-full', className)} onClick={() => closeDetails?.()}>- {editor ? (- <div className="RichMarkdownEditor overflow-auto">- <EditorContent editor={editor} className="RichMarkdownEditor__content px-0 py-0" />- </div>- ) : (- <LemonMarkdown className="overflow-auto">{text}</LemonMarkdown>- )}- </div>- )-}--export const TextContent = memo(TextContentImpl)-TextContent.displayName = 'TextContent'-function TextCardInternal({textTile,@@ -120,7 +77,7 @@ function TextCardInternal()}onMouseDown={onDragHandleMouseDown}>- <TextContent text={text.body} className={shouldHideMoreButton ? 'p-4' : 'p-4 pr-14'} />+ <LazyTextContent text={text.body} className={shouldHideMoreButton ? 'p-4' : 'p-4 pr-14'} /></div>{(canEnterEditModeFromEdge || showResizeHandles) && onEnterEditModeFromEdge && (diff --git a/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsx b/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsxindex a9d3915c6d72..998a18df4acb 100644--- a/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsx+++ b/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsx@@ -1,7 +1,7 @@import { Placeholder } from '@tiptap/extension-placeholder'import { Extensions } from '@tiptap/react'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'+import { TextContent } from 'lib/components/Cards/TextCard/TextContent'import { RichMarkdownEditor } from 'lib/components/MarkdownEditor/rich/RichMarkdownEditor'import { TEXT_CARD_MARKDOWN_EXTENSIONS, textCardConverter } from './textCardMarkdown'diff --git a/frontend/src/lib/components/Cards/TextCard/TextContent.tsx b/frontend/src/lib/components/Cards/TextCard/TextContent.tsxnew file mode 100644index 000000000000..fde82da71e5b--- /dev/null+++ b/frontend/src/lib/components/Cards/TextCard/TextContent.tsx@@ -0,0 +1,47 @@+import { EditorContent } from '@tiptap/react'+import clsx from 'clsx'+import { HTMLAttributes, memo, useEffect, useMemo } from 'react'++import 'lib/components/MarkdownEditor/shared/RichMarkdownEditor.scss'+import { useRichContentEditor } from 'lib/components/RichContentEditor'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'++import { TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS, textCardConverter } from './textCardMarkdown'++export interface TextContentProps extends Pick<HTMLAttributes<HTMLDivElement>, 'className'> {+ text: string+ closeDetails?: () => void+}++function TextContentImpl({ text, closeDetails, className }: TextContentProps): JSX.Element {+ const initialDoc = useMemo(() => textCardConverter.markdownToDoc(text), [text])++ const editor = useRichContentEditor({+ extensions: TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS,+ initialContent: initialDoc,+ disabled: true,+ })++ useEffect(() => {+ if (!editor) {+ return+ }++ editor.commands.setContent(initialDoc, { emitUpdate: false })+ }, [editor, initialDoc])++ return (+ <div className={clsx('w-full', className)} onClick={() => closeDetails?.()}>+ {editor ? (+ <div className="RichMarkdownEditor overflow-auto">+ <EditorContent editor={editor} className="RichMarkdownEditor__content px-0 py-0" />+ </div>+ ) : (+ <LemonMarkdown className="overflow-auto">{text}</LemonMarkdown>+ )}+ </div>+ )+}++export const TextContent = memo(TextContentImpl)+TextContent.displayName = 'TextContent'diff --git a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.tsindex 49649c211385..53d9caf89c20 100644--- a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts+++ b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts@@ -10,8 +10,6 @@ import { DashboardTile, DashboardTileIdOrNew, DashboardType } from '~/types'import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'-import { textCardConverter } from './textCardMarkdown'-export interface TextTileForm {body: stringagent_context: string@@ -161,7 +159,7 @@ export const textCardModalLogic = kea<textCardModalLogicType>([body_length: textTile.body.length,agent_context_length: textTile.agent_context.length,has_agent_context: textTile.agent_context.trim().length > 0,- content_type: getImageOnlyTextCardImage(textCardConverter, textTile.body) ? 'image' : 'text',+ content_type: getImageOnlyTextCardImage(textTile.body) ? 'image' : 'text',})},})),diff --git a/frontend/src/lib/components/Comments/commentUtils.test.ts b/frontend/src/lib/components/Comments/commentUtils.test.tsindex e7e3e3e09bf7..0e2c61a3457c 100644--- a/frontend/src/lib/components/Comments/commentUtils.test.ts+++ b/frontend/src/lib/components/Comments/commentUtils.test.ts@@ -1,3 +1,6 @@+import { generateText } from '@tiptap/core'++import { DEFAULT_EXTENSIONS, serializationOptions } from 'lib/components/RichContentEditor/LemonRichContentEditor'import { JSONContent } from 'lib/components/RichContentEditor/types'import { getCommentText } from './commentUtils'@@ -90,4 +93,22 @@ describe('getCommentText', () => {}expect(getCommentText({ rich_content: richContent })).toBe('hey @member:42')})++ const paragraph = (...content: JSONContent[]): JSONContent => ({ type: 'paragraph', content })+ const text = (value: string): JSONContent => ({ type: 'text', text: value })++ // Comments render their text without the editor, so text from the comment schema must match what the editor extracts.+ it.each<[string, JSONContent[]]>([+ ['one paragraph', [paragraph(text('hello'))]],+ ['two paragraphs', [paragraph(text('first')), paragraph(text('second'))]],+ ['an empty paragraph between two', [paragraph(text('first')), paragraph(), paragraph(text('second'))]],+ ['a mention', [paragraph(text('hey '), { type: 'ph-mention', attrs: { id: 42 } }, text(' look'))]],+ ['an empty document', [paragraph()]],+ ])('extracts the same text as the editor from %s', (_label, content) => {+ const richContent: JSONContent = { type: 'doc', content }++ expect(getCommentText({ rich_content: richContent })).toBe(+ generateText(richContent, DEFAULT_EXTENSIONS, serializationOptions)+ )+ })})diff --git a/frontend/src/lib/components/Comments/commentUtils.ts b/frontend/src/lib/components/Comments/commentUtils.tsindex 6d52e0a907ae..a24df56881d6 100644--- a/frontend/src/lib/components/Comments/commentUtils.ts+++ b/frontend/src/lib/components/Comments/commentUtils.ts@@ -1,7 +1,5 @@-import { generateText } from '@tiptap/core'--import { DEFAULT_EXTENSIONS, serializationOptions } from 'lib/components/RichContentEditor/LemonRichContentEditor'-import { JSONContent, RichContentNodeType } from 'lib/components/RichContentEditor/types'+import { richContentToText } from 'lib/components/RichContentEditor/richContentText'+import { JSONContent } from 'lib/components/RichContentEditor/types'import { dayjs } from 'lib/dayjs'import { urls } from 'scenes/urls'@@ -62,38 +60,7 @@ export function getCommentText(comment: { content?: string | null; rich_content?],}- try {- return generateText(content, DEFAULT_EXTENSIONS, serializationOptions)- } catch {- // Conversations authors comments with a richer schema than DEFAULT_EXTENSIONS, so a mark or- // node it lacks (italic, list, image, ...) makes generateText throw. Extract text schema-free.- return extractPlainText(content)- }-}--const INLINE_NODE_TYPES = new Set<string>(['text', 'hardBreak', RichContentNodeType.Mention])--/** Concatenate a rich-content doc's text with no ProseMirror schema, so no node or mark can throw. */-function extractPlainText(node: JSONContent): string {- if (node.type === RichContentNodeType.Mention) {- return node.attrs?.id != null ? `@member:${node.attrs.id}` : ''- }- if (node.type === 'hardBreak') {- return '\n'- }- if (node.type === 'image') {- return node.attrs?.src ? `` : ''- }- const children = node.content ?? []- const joined = children- .map(extractPlainText)- // Block children are separated by a blank line, inline runs concatenate directly.- .map((part, index) => {- const isBlock = index > 0 && !INLINE_NODE_TYPES.has(children[index].type ?? '')- return isBlock ? `\n\n${part}` : part- })- .join('')- return (node.text ?? '') + joined+ return richContentToText(content, (id) => `@member:${id}`)}export function isViewingRecording(recordingId: string): boolean {diff --git a/frontend/src/lib/components/Comments/utils.ts b/frontend/src/lib/components/Comments/utils.tsindex e3a17263d2f8..21d61f2b6e52 100644--- a/frontend/src/lib/components/Comments/utils.ts+++ b/frontend/src/lib/components/Comments/utils.ts@@ -1,7 +1,5 @@-import { generateText } from '@tiptap/core'--import { DEFAULT_EXTENSIONS } from 'lib/components/RichContentEditor/LemonRichContentEditor'-import { JSONContent, RichContentNodeType } from 'lib/components/RichContentEditor/types'+import { richContentToText } from 'lib/components/RichContentEditor/richContentText'+import { JSONContent } from 'lib/components/RichContentEditor/types'import { ActivityScope, OrganizationMemberType } from '~/types'@@ -22,16 +20,9 @@ export const discussionsSlug = (scope?: string, itemId?: string | null): stringexport const getTextContent = (content: JSONContent | undefined | null, members: OrganizationMemberType[]): string => {return content- ? generateText(content, DEFAULT_EXTENSIONS, {- textSerializers: {- [RichContentNodeType.Mention]: ({ node }) => {- const userId = node.attrs.id-- const member = members.find((member) => member.user.id === userId)-- return `@${member ? member.user.first_name : `user:${userId}`}`- },- },+ ? richContentToText(content, (userId) => {+ const member = members.find((member) => member.user.id === userId)+ return `@${member ? member.user.first_name : `user:${userId}`}`}): ''}diff --git a/frontend/src/lib/components/LemonTextAreaMarkdown/LemonTextAreaMarkdown.tsx b/frontend/src/lib/components/LemonTextAreaMarkdown/LemonTextAreaMarkdown.tsxindex dc9e871b6b6a..883df47d4edd 100644--- a/frontend/src/lib/components/LemonTextAreaMarkdown/LemonTextAreaMarkdown.tsx+++ b/frontend/src/lib/components/LemonTextAreaMarkdown/LemonTextAreaMarkdown.tsx@@ -4,7 +4,7 @@ import React, { useCallback, useRef, useState } from 'react'import { IconImage, IconMarkdownFilled } from '@posthog/icons'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'+import { TextContent } from 'lib/components/Cards/TextCard/TextContent'import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'import { useUploadFiles } from 'lib/hooks/useUploadFiles'import { LemonButton } from 'lib/lemon-ui/LemonButton'diff --git a/frontend/src/lib/components/RichContentEditor/LazyRichContent.test.tsx b/frontend/src/lib/components/RichContentEditor/LazyRichContent.test.tsxnew file mode 100644index 000000000000..2aca718b418c--- /dev/null+++ b/frontend/src/lib/components/RichContentEditor/LazyRichContent.test.tsx@@ -0,0 +1,57 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { LazyLemonRichContentEditor, LazyTextContent } from './LazyRichContent'++let mockFailImports = true+const mockChunkLoadError = (): Error => new Error('Failed to fetch dynamically imported module: /static/chunk.js')++jest.mock('lib/components/Cards/TextCard/TextContent', () => ({+ __esModule: true,+ get TextContent() {+ if (mockFailImports) {+ throw mockChunkLoadError()+ }+ return ({ text }: { text: string }) => <div>rich {text}</div>+ },+}))+jest.mock('./LemonRichContentEditor', () => ({+ __esModule: true,+ get LemonRichContentEditor() {+ if (mockFailImports) {+ throw mockChunkLoadError()+ }+ return () => <div>rich editor</div>+ },+ RichContentPreview: () => null,+}))++describe('LazyRichContent', () => {+ afterEach(cleanup)++ it('offers a page reload when a retry fails too', async () => {+ render(<LazyLemonRichContentEditor logicKey="test" onCreate={() => {}} />)++ fireEvent.click(await screen.findByText('Try again', undefined, { timeout: 5000 }))++ expect(await screen.findByText('Reload page', undefined, { timeout: 5000 })).toBeInTheDocument()+ })++ it('keeps a failed chunk local: text falls back to markdown, the editor offers a retry', async () => {+ render(+ <>+ <LazyTextContent text="Hello **there**" />+ <LazyLemonRichContentEditor logicKey="test" onCreate={() => {}} />+ </>+ )++ expect(await screen.findByText("Couldn't load the editor.", undefined, { timeout: 5000 })).toBeInTheDocument()+ expect(screen.getByText('Hello **there**')).toBeInTheDocument()++ mockFailImports = false+ fireEvent.click(screen.getByText('Try again'))++ expect(await screen.findByText('rich editor', undefined, { timeout: 5000 })).toBeInTheDocument()+ })+})diff --git a/frontend/src/lib/components/RichContentEditor/LazyRichContent.tsx b/frontend/src/lib/components/RichContentEditor/LazyRichContent.tsxnew file mode 100644index 000000000000..863a9cf8bcee--- /dev/null+++ b/frontend/src/lib/components/RichContentEditor/LazyRichContent.tsx@@ -0,0 +1,181 @@+import clsx from 'clsx'+import posthog from 'posthog-js'+import { Component, ComponentType, LazyExoticComponent, ReactNode, Suspense } from 'react'++import type { TextContentProps } from 'lib/components/Cards/TextCard/TextContent'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LazyLemonMarkdown } from 'lib/lemon-ui/LemonMarkdown/LazyLemonMarkdown'+import { isChunkLoadError } from 'lib/utils/isChunkLoadError'+import { lazyWithRetry, retryImport } from 'lib/utils/retryImport'+import { reloadAfterChunkLoadError } from 'lib/utils/stableChunks'++import type { LemonRichContentEditorProps } from './LemonRichContentEditor'+import { richContentToText } from './richContentText'+import type { JSONContent } from './types'++const importTextContent = (): Promise<typeof import('lib/components/Cards/TextCard/TextContent')> =>+ import('lib/components/Cards/TextCard/TextContent')+const importLemonRichContentEditor = (): Promise<typeof import('./LemonRichContentEditor')> =>+ import('./LemonRichContentEditor')++interface RetryableChunk<T extends ComponentType<any>> {+ get: () => LazyExoticComponent<T>+ reset: () => void+}++// React.lazy keeps a failed import forever, so a retry needs a new lazy component.+function retryableChunk<T extends ComponentType<any>>(factory: () => Promise<{ default: T }>): RetryableChunk<T> {+ let chunk = lazyWithRetry(factory)+ return {+ get: () => chunk,+ reset: () => {+ chunk = lazyWithRetry(factory)+ },+ }+}++const textContentChunk = retryableChunk(() => importTextContent().then((m) => ({ default: m.TextContent })))+const richContentPreviewChunk = retryableChunk(() =>+ importLemonRichContentEditor().then((m) => ({ default: m.RichContentPreview }))+)+const lemonRichContentEditorChunk = retryableChunk(() =>+ importLemonRichContentEditor().then((m) => ({ default: m.LemonRichContentEditor }))+)++interface LazyChunkProps<T extends ComponentType<any>> {+ chunk: RetryableChunk<T>+ render: (Chunk: LazyExoticComponent<T>) => ReactNode+ loading: ReactNode+ renderError: (recover: ChunkRecovery) => ReactNode+}++interface ChunkRecovery {+ label: string+ onClick: () => void+}++// Without this boundary a failed chunk reaches ChunkLoadErrorBoundary, which reloads the page unasked.+class LazyChunk<T extends ComponentType<any>> extends Component<+ LazyChunkProps<T>,+ { error: unknown; retried: boolean }+> {+ override state: { error: unknown; retried: boolean } = { error: null, retried: false }++ static getDerivedStateFromError(error: unknown): { error: unknown } {+ return { error }+ }++ override componentDidCatch(error: unknown): void {+ if (isChunkLoadError(error)) {+ posthog.captureException(error)+ }+ }++ retry = (): void => {+ this.props.chunk.reset()+ this.setState({ error: null, retried: true })+ }++ // A failed parse stays cached and a deploy deletes old chunks, so only a reload recovers those.+ recovery(error: unknown): ChunkRecovery {+ const needsReload = this.state.retried || (error as { name?: string }).name === 'SyntaxError'+ return needsReload+ ? { label: 'Reload page', onClick: () => reloadAfterChunkLoadError(error) }+ : { label: 'Try again', onClick: this.retry }+ }++ override render(): ReactNode {+ const { error } = this.state+ if (error && !isChunkLoadError(error)) {+ throw error+ }+ if (error) {+ return this.props.renderError(this.recovery(error))+ }+ return <Suspense fallback={this.props.loading}>{this.props.render(this.props.chunk.get())}</Suspense>+ }+}++/** Call from a logic once its data shows rich text will render, so the chunk loads alongside the scene. */+export function preloadRichContent(): void {+ void Promise.all([retryImport(importTextContent), retryImport(importLemonRichContentEditor)]).catch(() => {+ // The lazy component retries the import when it renders, and its error boundary handles a failure.+ })+}++function PlainTextContent({ text, className, busy }: TextContentProps & { busy?: boolean }): JSX.Element {+ return (+ <div className={clsx('w-full', className)} aria-busy={busy}>+ <LazyLemonMarkdown className="overflow-auto">{text}</LazyLemonMarkdown>+ </div>+ )+}++/** `TextContent` loaded on first render. The text renders as plain markdown while the chunk loads, or if it fails. */+export function LazyTextContent(props: TextContentProps): JSX.Element {+ return (+ <LazyChunk+ chunk={textContentChunk}+ render={(Chunk) => <Chunk {...props} />}+ loading={<PlainTextContent {...props} busy />}+ renderError={() => <PlainTextContent {...props} />}+ />+ )+}++function PlainRichContentPreview({+ content,+ className,+ busy,+}: {+ content: JSONContent | null+ className?: string+ busy?: boolean+}): JSX.Element {+ return (+ <div+ className={clsx('w-full p-2 whitespace-pre-line [overflow-wrap:anywhere]', busy && 'invisible', className)}+ aria-busy={busy}+ >+ {content ? richContentToText(content, (id) => `@member:${id}`) : null}+ </div>+ )+}++/** `RichContentPreview` loaded on first render. The plain text holds the height while the chunk loads, and shows if it fails. */+export function LazyRichContentPreview(props: { content: JSONContent | null; className?: string }): JSX.Element {+ return (+ <LazyChunk+ chunk={richContentPreviewChunk}+ render={(Chunk) => <Chunk {...props} />}+ loading={<PlainRichContentPreview {...props} busy />}+ renderError={() => <PlainRichContentPreview {...props} />}+ />+ )+}++/** `LemonRichContentEditor` loaded on first render. An empty input holds its place while the chunk loads. */+export function LazyLemonRichContentEditor(props: LemonRichContentEditorProps): JSX.Element {+ return (+ <LazyChunk+ chunk={lemonRichContentEditorChunk}+ render={(Chunk) => <Chunk {...props} />}+ loading={+ <div className="flex flex-col border rounded mt-4 input-like" aria-busy>+ <div className="p-2 min-h-16" />+ <div className="h-8 border-t" />+ </div>+ }+ renderError={(recover) => (+ <div className="flex flex-col border rounded mt-4 input-like">+ <div className="p-2 min-h-16 text-secondary">Couldn't load the editor.</div>+ <div className="flex justify-end border-t p-1">+ <LemonButton size="xsmall" type="secondary" onClick={recover.onClick}>+ {recover.label}+ </LemonButton>+ </div>+ </div>+ )}+ />+ )+}diff --git a/frontend/src/lib/components/RichContentEditor/LemonRichContentEditor.tsx b/frontend/src/lib/components/RichContentEditor/LemonRichContentEditor.tsxindex 357727666d18..4e66bfdaec24 100644--- a/frontend/src/lib/components/RichContentEditor/LemonRichContentEditor.tsx+++ b/frontend/src/lib/components/RichContentEditor/LemonRichContentEditor.tsx@@ -11,7 +11,7 @@ import { useRef, useState } from 'react'import { IconEye, IconImage, IconPencil } from '@posthog/icons'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'+import { TextContent } from 'lib/components/Cards/TextCard/TextContent'import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'import { useRichContentEditor } from 'lib/components/RichContentEditor'import { CommandEnterExtension } from 'lib/components/RichContentEditor/CommandEnterExtension'diff --git a/frontend/src/lib/components/RichContentEditor/richContentText.ts b/frontend/src/lib/components/RichContentEditor/richContentText.tsnew file mode 100644index 000000000000..ae08126e898c--- /dev/null+++ b/frontend/src/lib/components/RichContentEditor/richContentText.ts@@ -0,0 +1,28 @@+import { JSONContent, RichContentNodeType } from './types'++const INLINE_NODE_TYPES = new Set<string>(['text', 'hardBreak', RichContentNodeType.Mention])++/**+ * Concatenates the text of a rich content document without a ProseMirror schema, so it needs no+ * editor code and no node or mark can throw. Blocks are separated by a blank line, as in the editor.+ */+export function richContentToText(node: JSONContent, mentionText: (id: number) => string): string {+ if (node.type === RichContentNodeType.Mention) {+ return node.attrs?.id != null ? mentionText(node.attrs.id) : ''+ }+ if (node.type === 'hardBreak') {+ return '\n'+ }+ if (node.type === 'image') {+ return node.attrs?.src ? `` : ''+ }+ const children = node.content ?? []+ const joined = children+ .map((child) => richContentToText(child, mentionText))+ .map((part, index) => {+ const isBlock = index > 0 && !INLINE_NODE_TYPES.has(children[index].type ?? '')+ return isBlock ? `\n\n${part}` : part+ })+ .join('')+ return (node.text ?? '') + joined+}diff --git a/frontend/src/models/notebooksModel.ts b/frontend/src/models/notebooksModel.tsindex 05ae14c07479..903e54e6d808 100644--- a/frontend/src/models/notebooksModel.ts+++ b/frontend/src/models/notebooksModel.ts@@ -7,8 +7,8 @@ import api from 'lib/api'import { JSONContent } from 'lib/components/RichContentEditor/types'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { addProductIntent } from 'lib/utils/product-intents'+import { retryImport } from 'lib/utils/retryImport'import { withBackLink } from 'scenes/analytics/analyticsBackLink'-import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'import type { notebookLogicType } from 'scenes/notebooks/Notebook/notebookLogic'import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'import { LOCAL_NOTEBOOK_TEMPLATES } from 'scenes/notebooks/NotebookTemplates/notebookTemplates'@@ -27,17 +27,14 @@ import type { NotebookType } from '../scenes/notebooks/types'// kea logic. `openNotebook` pushes here; `notebookLogic.afterMount` drains.const pendingNotebookOperations = new Map<string, ((logic: BuiltLogic<notebookLogicType>) => void)[]>()-export function drainPendingNotebookOperations(shortId: string): void {+export function drainPendingNotebookOperations(shortId: string, logic: BuiltLogic<notebookLogicType>): void {const ops = pendingNotebookOperations.get(shortId)if (!ops?.length) {return}pendingNotebookOperations.delete(shortId)- const logic = notebookLogic.findMounted({ shortId })- if (logic) {- for (const op of ops) {- op(logic)- }+ for (const op of ops) {+ op(logic)}}@@ -67,13 +64,15 @@ export const openNotebook = async (}if (onOpen) {+ // Queued before the import, so a failed import still leaves the callback for the logic to drain on mount.+ const ops = pendingNotebookOperations.get(notebookId) || []+ ops.push(onOpen)+ pendingNotebookOperations.set(notebookId, ops)+ // A dynamic import keeps the notebook editor and its rich text stack out of every scene that can open a notebook.+ const { notebookLogic } = await retryImport(() => import('scenes/notebooks/Notebook/notebookLogic'))const mountedLogic = notebookLogic.findMounted({ shortId: notebookId })if (mountedLogic) {- onOpen(mountedLogic)- } else {- const ops = pendingNotebookOperations.get(notebookId) || []- ops.push(onOpen)- pendingNotebookOperations.set(notebookId, ops)+ drainPendingNotebookOperations(notebookId, mountedLogic)}}}diff --git a/frontend/src/scenes/dashboard/DashboardModals.test.tsx b/frontend/src/scenes/dashboard/DashboardModals.test.tsxindex 728cbeba652a..3b0419a84e42 100644--- a/frontend/src/scenes/dashboard/DashboardModals.test.tsx+++ b/frontend/src/scenes/dashboard/DashboardModals.test.tsx@@ -1,4 +1,4 @@-import { render } from '@testing-library/react'+import { render, waitFor } from '@testing-library/react'import { useActions, useValues } from 'kea'import { router } from 'kea-router'@@ -148,7 +148,7 @@ describe('DashboardModals', () => {it.each([['image', ImageTileModal, 'showImageTileModal'],['button', ButtonTileCardModal, 'showButtonTileModal'],- ] as const)('closes a new %s modal without navigating', (_type, modal, visibleKey) => {+ ] as const)('closes a new %s modal without navigating', async (_type, modal, visibleKey) => {mockedUseValues.mockImplementation((logic) =>logic === dashboardLogic? {@@ -170,6 +170,8 @@ describe('DashboardModals', () => {)render(<DashboardModals dashboard={{ id: 5, tiles: [] } as unknown as DashboardType} />)+ // The image modal loads lazily.+ await waitFor(() => expect(modal).toHaveBeenCalled())const modalProps = (modal as jest.Mock).mock.calls[0][0]modalProps.onClose()diff --git a/frontend/src/scenes/dashboard/DashboardModals.tsx b/frontend/src/scenes/dashboard/DashboardModals.tsxindex 3b09840230cf..25b7bfb18a0c 100644--- a/frontend/src/scenes/dashboard/DashboardModals.tsx+++ b/frontend/src/scenes/dashboard/DashboardModals.tsx@@ -3,8 +3,6 @@ import { router } from 'kea-router'import { Suspense, useEffect } from 'react'import { ButtonTileCardModal } from 'lib/components/Cards/ButtonTileCard/ButtonTileCardModal'-import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'-import { TextCardModal } from 'lib/components/Cards/TextCard/TextCardModal'import { useKeepMountedWhileOpen } from 'lib/hooks/useKeepMountedWhileOpen'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { lazyWithRetry } from 'lib/utils/retryImport'@@ -14,7 +12,6 @@ import { userLogic } from 'scenes/userLogic'import { dashboardsModel } from '~/models/dashboardsModel'import { DashboardMode, DashboardType } from '~/types'-import { ImageTileModal } from 'products/dashboards/frontend/components/ImageTile/ImageTileModal'import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'import { DashboardInsightColorsModal } from './DashboardInsightColorsModal'@@ -24,7 +21,7 @@ import { DashboardTemplateEditor } from './DashboardTemplateEditor'import { DeleteDashboardModal } from './DeleteDashboardModal'import { DuplicateDashboardModal } from './DuplicateDashboardModal'-// These modals carry their own editors and integration setup, which a dashboard needs only once one opens.+// These modals carry their own editors, the rich text stack included, and integration setup, which a dashboard needs only once one opens.const AddWidgetModal = lazyWithRetry(() =>import('@posthog/products-dashboards/frontend/widgets/AddWidgetModal').then((m) => ({ default: m.AddWidgetModal })))@@ -39,6 +36,14 @@ const SubscriptionsModal = lazyWithRetry(() =>const TerraformExportModal = lazyWithRetry(() =>import('lib/components/TerraformExporter/TerraformExportModal').then((m) => ({ default: m.TerraformExportModal })))+const TextCardModal = lazyWithRetry(() =>+ import('lib/components/Cards/TextCard/TextCardModal').then((m) => ({ default: m.TextCardModal }))+)+const ImageTileModal = lazyWithRetry(() =>+ import('products/dashboards/frontend/components/ImageTile/ImageTileModal').then((m) => ({+ default: m.ImageTileModal,+ }))+)export function DashboardModals({ dashboard }: { dashboard: DashboardType }): JSX.Element {const {@@ -68,13 +73,14 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType }): JSconst textRouteTile =textTileId !== null ? dashboard.tiles?.find((tile) => tile.id === Number(textTileId)) : undefinedconst isCreatingTextTile = textTileId === null- const textRouteHasImage =- !!textRouteTile?.text && !!getImageOnlyTextCardImage(textCardConverter, textRouteTile.text.body)+ const textRouteHasImage = !!textRouteTile?.text && !!getImageOnlyTextCardImage(textRouteTile.text.body)const buttonRouteTile =buttonTileId !== null ? dashboard.tiles?.find((tile) => tile.id === Number(buttonTileId)) : undefinedconst isCreatingButtonTile = buttonTileId === nullconst selectedImageTileId = textRouteHasImage ? (textRouteTile?.id ?? null) : nullconst shouldShowImageTileModal = showImageTileModal || selectedImageTileId !== null+ const isTextTileModalOpen = showTextTileModal && (isCreatingTextTile || !!textRouteTile?.text)+ const shouldRenderTextTile = useKeepMountedWhileOpen(isTextTileModalOpen)const hasMissingRouteTile = (textTileId !== null && !textRouteTile) || (buttonTileId !== null && !buttonRouteTile)const closeTile = (): void => {if (@@ -136,21 +142,25 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType }): JS{canEditDashboard && (<>{shouldShowImageTileModal ? (- <ImageTileModal- key={selectedImageTileId ?? 'new'}- isOpen={shouldShowImageTileModal}- onClose={closeTile}- dashboard={dashboard}- imageTileId={selectedImageTileId}- />- ) : (- <TextCardModal- isOpen={showTextTileModal && (isCreatingTextTile || !!textRouteTile?.text)}- onClose={closeTile}- dashboard={dashboard}- textTileId={textTileId}- />- )}+ <Suspense fallback={<DashboardModalLoading isOpen onClose={closeTile} />}>+ <ImageTileModal+ key={selectedImageTileId ?? 'new'}+ isOpen={shouldShowImageTileModal}+ onClose={closeTile}+ dashboard={dashboard}+ imageTileId={selectedImageTileId}+ />+ </Suspense>+ ) : shouldRenderTextTile ? (+ <Suspense fallback={<DashboardModalLoading isOpen={isTextTileModalOpen} onClose={closeTile} />}>+ <TextCardModal+ isOpen={isTextTileModalOpen}+ onClose={closeTile}+ dashboard={dashboard}+ textTileId={textTileId}+ />+ </Suspense>+ ) : null}<ButtonTileCardModalisOpen={showButtonTileModal && (isCreatingButtonTile || !!buttonRouteTile?.button_tile)}onClose={closeTile}diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 6baf485ec089..da1a0a4954a6 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -39,6 +39,7 @@ import api, { getJSONOrNull } from 'lib/api'import { ApiError, isAccessDeniedError } from 'lib/api-error'import { ApiRequestTiming, flattenRequestTiming } from 'lib/apiRequestTiming'import { DataColorTheme } from 'lib/colors'+import { preloadRichContent } from 'lib/components/RichContentEditor/LazyRichContent'import { OrganizationMembershipLevel } from 'lib/constants'import { FEATURE_FLAGS } from 'lib/constants'import { Dayjs, dayjs, now } from 'lib/dayjs'@@ -127,6 +128,7 @@ import {TileLayout,} from '~/types'+import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'import { DashboardGridCompaction, getDashboardGridCompactor } from 'products/dashboards/frontend/dashboardCustomization'import {dashboardFiltersEqual,@@ -1958,6 +1960,13 @@ function planTileMove(}}+/** Text tiles render rich text, so start loading it while the rest of the dashboard renders. */+function preloadTextTileRenderer(dashboard: DashboardType): void {+ if (dashboard.tiles?.some((tile) => !!tile.text && !getImageOnlyTextCardImage(tile.text.body))) {+ preloadRichContent()+ }+}+export const dashboardLogic = kea<dashboardLogicType>([path(['scenes', 'dashboard', 'dashboardLogic']),connect(() => ({@@ -6161,6 +6170,7 @@ export const dashboardLogic = kea<dashboardLogicType>([actions.dashboardNotFound()return // We hit a 404}+ preloadTextTileRenderer(values.dashboard)},sharedListeners.handleDashboardLoadComplete,],@@ -6171,6 +6181,7 @@ export const dashboardLogic = kea<dashboardLogicType>([actions.dashboardNotFound()return // We hit a 404}+ preloadTextTileRenderer(dashboard)},tileStreamingComplete: sharedListeners.handleDashboardLoadComplete,dashboardNotFound: () => {diff --git a/frontend/src/scenes/dashboard/tileLayouts.ts b/frontend/src/scenes/dashboard/tileLayouts.tsindex 878f198d84f2..9567bcf8aa94 100644--- a/frontend/src/scenes/dashboard/tileLayouts.ts+++ b/frontend/src/scenes/dashboard/tileLayouts.ts@@ -6,7 +6,6 @@ import {type DashboardWidgetCatalogEntry,} from '@posthog/products-dashboards/frontend/widget_types/catalog'-import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'import { BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'import {@@ -227,9 +226,7 @@ export const sortTilesByLayout = (tiles: Array<DashboardTile>, col: DashboardLayexport const calculateLayouts = (tiles: DashboardTile[]): Partial<Record<DashboardLayoutSize, Layout>> => {const allLayouts: Partial<Record<keyof typeof BREAKPOINT_COLUMN_COUNTS, Layout>> = {}const imageTileIds = new Set(- tiles- .filter((tile) => !!tile.text && !!getImageOnlyTextCardImage(textCardConverter, tile.text.body))- .map((tile) => tile.id)+ tiles.filter((tile) => !!tile.text && !!getImageOnlyTextCardImage(tile.text.body)).map((tile) => tile.id))// Always calculate sm layout first to establish reference orderdiff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.tsindex 8a9df24b42bf..3f6f9f6bc1fd 100644--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts@@ -11,12 +11,6 @@ import { LegacyRecordingFilters } from '~/types'import { convertMarkdownTablesInContent } from './convertMarkdownTablesInContent'-// NOTE: Increment this number when you add a new content migration-// It will bust the cache on the localContent in the notebookLogic-// so that the latest content will fall back to the remote content which-// is filtered through the migrate function below that ensures integrity-export const NOTEBOOKS_VERSION = '3'-export interface MigrateOptions {/*** Skips the query migrate step which issues a POST request to the backend which will resultdiff --git a/frontend/src/scenes/notebooks/Notebook/migrations/notebooksVersion.ts b/frontend/src/scenes/notebooks/Notebook/migrations/notebooksVersion.tsnew file mode 100644index 000000000000..21bc2b533378--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/migrations/notebooksVersion.ts@@ -0,0 +1,5 @@+// NOTE: Increment this number when you add a new content migration to migrate.ts+// It will bust the cache on the localContent in the notebookLogic+// so that the latest content will fall back to the remote content which+// is filtered through the migrate function that ensures integrity+export const NOTEBOOKS_VERSION = '3'diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 56f0cef99db4..82507e31fb09 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -42,6 +42,7 @@ import { downloadFile } from 'lib/utils/dom'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { objectsEqual } from 'lib/utils/objects'import { RetainedValues } from 'lib/utils/retainedValues'+import { retryImport } from 'lib/utils/retryImport'import { slugify } from 'lib/utils/strings'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -96,7 +97,7 @@ import {isMarkdownNotebookContent,notebookArtifactContentToMarkdown,} from './markdownNotebookV2'-import { NOTEBOOKS_VERSION, migrate } from './migrations/migrate'+import { NOTEBOOKS_VERSION } from './migrations/notebooksVersion'import { buildNotebookOpenedEvent } from './notebookAnalytics'import { shouldWarnBeforeLeavingNotebook } from './notebookBeforeUnload'import { notebookKernelInfoLogic } from './notebookKernelInfoLogic'@@ -1059,6 +1060,7 @@ export const notebookLogic = kea<notebookLogicType>([}}+ const { migrate } = await retryImport(() => import('./migrations/migrate'))return await migrate(response, { skipApiUpgrade: !!values.isShared })},@@ -2265,7 +2267,7 @@ export const notebookLogic = kea<notebookLogicType>([})),afterMount(({ props, values, actions }) => {- drainPendingNotebookOperations(props.shortId)+ drainPendingNotebookOperations(props.shortId, notebookLogic(props))// A retained copy renders at once, so check it against the server straight away.if (values.notebook && canRetainNotebook(props)) {actions.loadNotebook()diff --git a/frontend/src/scenes/session-recordings/player/commenting/CommentOnRecordingButton.tsx b/frontend/src/scenes/session-recordings/player/commenting/CommentOnRecordingButton.tsxindex 1b36379c5802..23e43b8aa5de 100644--- a/frontend/src/scenes/session-recordings/player/commenting/CommentOnRecordingButton.tsx+++ b/frontend/src/scenes/session-recordings/player/commenting/CommentOnRecordingButton.tsx@@ -6,6 +6,7 @@ import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'+import { preloadRichContent } from 'lib/components/RichContentEditor/LazyRichContent'import { KeyboardShortcut } from 'lib/lemon-ui/KeyboardShortcut/KeyboardShortcut'import { emojiUsageLogic } from 'lib/lemon-ui/LemonTextArea/emojiUsageLogic'import { cn } from 'lib/utils/css-classes'@@ -63,6 +64,7 @@ export function CommentOnRecordingButton({><LemonButtonsize="xsmall"+ onMouseEnter={preloadRichContent}onClick={(e) => {e.stopPropagation()setIsCommenting(!isCommenting)diff --git a/frontend/src/scenes/session-recordings/player/commenting/PlayerFrameCommentOverlay.tsx b/frontend/src/scenes/session-recordings/player/commenting/PlayerFrameCommentOverlay.tsxindex 5283e544f5d0..e7eee8242b67 100644--- a/frontend/src/scenes/session-recordings/player/commenting/PlayerFrameCommentOverlay.tsx+++ b/frontend/src/scenes/session-recordings/player/commenting/PlayerFrameCommentOverlay.tsx@@ -3,7 +3,7 @@ import { Form } from 'kea-forms'import { LemonButton, LemonInput } from '@posthog/lemon-ui'-import { LemonRichContentEditor } from 'lib/components/RichContentEditor/LemonRichContentEditor'+import { LazyLemonRichContentEditor } from 'lib/components/RichContentEditor/LazyRichContent'import { LemonField } from 'lib/lemon-ui/LemonField'import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'@@ -52,7 +52,7 @@ export const PlayerCommentModal = (): JSX.Element => {</div><div><LemonField name="content">- <LemonRichContentEditor+ <LazyLemonRichContentEditorplaceholder="Comment on this recording? Use @ to mention team members"data-attr="create-recording-comment-input"onPressCmdEnter={submitRecordingComment}diff --git a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsxindex 37e4dfb72115..695057ada401 100644--- a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx+++ b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx@@ -6,9 +6,8 @@ import useResizeObserver from 'use-resize-observer'import { IconComment } from '@posthog/icons'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'-import { RichContentPreview } from 'lib/components/RichContentEditor/LemonRichContentEditor'+import { LazyRichContentPreview, LazyTextContent } from 'lib/components/RichContentEditor/LazyRichContent'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { Tooltip } from 'lib/lemon-ui/Tooltip'@@ -147,9 +146,9 @@ function PlayerSeekbarTick({) : (<div className="flex flex-col px-4 py-2 gap-y-2">{item.data.rich_content ? (- <RichContentPreview content={item.data.rich_content} className="rounded-none" />+ <LazyRichContentPreview content={item.data.rich_content} className="rounded-none" />) : (- <TextContent+ <LazyTextContenttext={item.data.content ?? ''}data-attr="PlayerSeekbarTicks--text-content"/>diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemAnyComment.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemAnyComment.tsxindex f91d61383e1c..dbfe92829298 100644--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemAnyComment.tsx+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemAnyComment.tsx@@ -2,8 +2,7 @@ import { useActions, useValues } from 'kea'import { IconPencil, IconTrash } from '@posthog/icons'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'-import { RichContentPreview } from 'lib/components/RichContentEditor/LemonRichContentEditor'+import { LazyRichContentPreview, LazyTextContent } from 'lib/components/RichContentEditor/LazyRichContent'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { Tooltip } from 'lib/lemon-ui/Tooltip'@@ -46,11 +45,11 @@ function ItemComment({ item }: { item: InspectorListItemComment }): JSX.Elementconst hasMarkdownImage = (item.data.content ?? '').includes('![')let rowContent = item.data.rich_content ? (- <RichContentPreview content={item.data.rich_content} className="rounded-none" />+ <LazyRichContentPreview content={item.data.rich_content} className="rounded-none" />) : hasMarkdownImage ? (<>{item.data.content ?? ''}</>) : (- <TextContent text={item.data.content ?? ''} data-attr="item-annotation-comment-title-rendered-content" />+ <LazyTextContent text={item.data.content ?? ''} data-attr="item-annotation-comment-title-rendered-content" />)return (@@ -59,9 +58,9 @@ function ItemComment({ item }: { item: InspectorListItemComment }): JSX.Element<Tooltiptitle={item.data.rich_content ? (- <RichContentPreview content={item.data.rich_content} className="rounded-none" />+ <LazyRichContentPreview content={item.data.rich_content} className="rounded-none" />) : (- <TextContent+ <LazyTextContenttext={item.data.content ?? ''}data-attr="item-annotation-comment-title-rendered-content"/>@@ -151,7 +150,7 @@ function ItemCommentDetail({ item }: { item: InspectorListItemComment }): JSX.El</div><div className="p-2 text-xs border-t cursor-pointer text-wrap">- <TextContent+ <LazyTextContenttext={item.data.content ?? ''}data-attr="item-annotation-comment-detail-rendered-content"/>diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.tsindex 1f5403313cfd..1da766169b69 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.ts@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'import posthog from 'posthog-js'import api from 'lib/api'+import { preloadRichContent } from 'lib/components/RichContentEditor/LazyRichContent'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { playerCommentModel } from 'scenes/session-recordings/player/commenting/playerCommentModel'import { RecordingComment } from 'scenes/session-recordings/player/inspector/playerInspectorLogic'@@ -171,6 +172,13 @@ export const sessionRecordingCommentsLogic = kea<sessionRecordingCommentsLogicTyactions.loadRecordingNotebookComments()},+ loadRecordingCommentsSuccess: ({ sessionComments }) => {+ // Comments render as rich text on the seekbar, in the inspector and in the comments list.+ if (sessionComments.length > 0) {+ preloadRichContent()+ }+ },+deleteCommentSuccess: () => {lemonToast.success('Comment deleted')},diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex 322d7ef96777..73900817968a 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -34,6 +34,7 @@ import {import api from 'lib/api'import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'+import { preloadRichContent } from 'lib/components/RichContentEditor/LazyRichContent'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs, now } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -2687,6 +2688,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(},setIsCommenting: ({ isCommenting }) => {if (isCommenting) {+ preloadRichContent()actions.setPause()} else {actions.setPlay()diff --git a/frontend/src/scenes/session-recordings/player/watch/RecordingCommentsList.tsx b/frontend/src/scenes/session-recordings/player/watch/RecordingCommentsList.tsxindex 144639b94fc2..f55f222bb147 100644--- a/frontend/src/scenes/session-recordings/player/watch/RecordingCommentsList.tsx+++ b/frontend/src/scenes/session-recordings/player/watch/RecordingCommentsList.tsx@@ -2,8 +2,7 @@ import { useValues } from 'kea'import { Button, Skeleton } from '@posthog/quill'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'-import { RichContentPreview } from 'lib/components/RichContentEditor/LemonRichContentEditor'+import { LazyRichContentPreview, LazyTextContent } from 'lib/components/RichContentEditor/LazyRichContent'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'@@ -65,9 +64,9 @@ export function RecordingCommentsList({ sessionId }: { sessionId: string }): JSX)}</div>{comment.rich_content ? (- <RichContentPreview content={comment.rich_content} className="rounded-none" />+ <LazyRichContentPreview content={comment.rich_content} className="rounded-none" />) : (- <TextContent text={comment.content ?? ''} />+ <LazyTextContent text={comment.content ?? ''} />)}</div></div>diff --git a/products/annotations/frontend/pages/Annotations.tsx b/products/annotations/frontend/pages/Annotations.tsxindex dbe296ac421f..575eb1257530 100644--- a/products/annotations/frontend/pages/Annotations.tsx+++ b/products/annotations/frontend/pages/Annotations.tsx@@ -4,7 +4,7 @@ import { IconPencil } from '@posthog/icons'import { LemonSelect, Link } from '@posthog/lemon-ui'import { Button } from '@posthog/quill'-import { TextContent } from 'lib/components/Cards/TextCard/TextCard'+import { LazyTextContent } from 'lib/components/RichContentEditor/LazyRichContent'import { Shortcut } from 'lib/components/Shortcuts/Shortcut'import { keyBinds } from 'lib/components/Shortcuts/shortcuts'import { TZLabel } from 'lib/components/TZLabel'@@ -62,7 +62,7 @@ export function Annotations(): JSX.Element {return (<Tooltiptitle={- <TextContent+ <LazyTextContenttext={annotation.content ?? ''}data-attr="annotation-scene-comment-title-rendered-content"/>diff --git a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsxindex eebb4bf77f28..8e450fdfd594 100644--- a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx+++ b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx@@ -7,7 +7,6 @@ import {type DashboardWidgetPlacementMenusProps,} from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'import { TextCard } from 'lib/components/Cards/TextCard/TextCard'-import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'@@ -57,7 +56,7 @@ function DashboardTextItemInternal(}))- const image = tile.text ? getImageOnlyTextCardImage(textCardConverter, tile.text.body) : null+ const image = tile.text ? getImageOnlyTextCardImage(tile.text.body) : nullconst tileType = image ? 'image' : 'text'const moreButtonOverlay = (<>diff --git a/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx b/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsxindex aeb9deff68f3..c0a0c5c4cbfc 100644--- a/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx+++ b/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx@@ -87,7 +87,7 @@ export function ImageTileModal({const [isDragging, setIsDragging] = useState(false)const [previewPosition, setPreviewPosition] = useState<ImageTilePosition | null>(null)const [uploadComplete, setUploadComplete] = useState(false)- const image = getImageOnlyTextCardImage(textCardConverter, textTile.body)+ const image = getImageOnlyTextCardImage(textTile.body)const previewImage = image && previewPosition ? { ...image, position: previewPosition } : imageimageRef.current = imagediff --git a/products/dashboards/frontend/components/ImageTile/imageTileUtils.test.ts b/products/dashboards/frontend/components/ImageTile/imageTileUtils.test.tsindex 869b3ac48e2b..ca3ca4cb1e13 100644--- a/products/dashboards/frontend/components/ImageTile/imageTileUtils.test.ts+++ b/products/dashboards/frontend/components/ImageTile/imageTileUtils.test.ts@@ -1,13 +1,37 @@import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'-import { getImageOnlyTextCardImage, imageTileToMarkdown } from './imageTileUtils'+import { ImageTileImage, getImageOnlyTextCardImage, imageTileToMarkdown } from './imageTileUtils'describe('imageTileUtils', () => {it.each([['markdown image', '', 'A diagram', 'contain'],['HTML image', '<img src="https://example.com/diagram.png" alt="A diagram" />', 'A diagram', 'contain'],+ [+ 'markdown image with a bracketed source',+ '',+ 'A diagram',+ 'contain',+ ],+ [+ 'markdown image with an escaped source',+ '',+ 'A diagram',+ 'contain',+ ],+ [+ 'markdown image with blank lines',+ '\n\n\n',+ 'A diagram',+ 'contain',+ ],+ [+ 'HTML image in a paragraph',+ '<p><img src="https://example.com/diagram.png" alt="A diagram"></p>',+ 'A diagram',+ 'contain',+ ],])('detects an image-only text card from %s', (_name, markdown, alt, layout) => {- expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({+ expect(getImageOnlyTextCardImage(markdown)).toMatchObject({src: 'https://example.com/diagram.png',alt,layout,@@ -19,61 +43,89 @@ describe('imageTileUtils', () => {['image caption', '\n\nA caption'],['multiple images', '\n\n'],['malformed image markdown', ''],+ ['HTML image without a source', '<img alt="A diagram" />'],+ ['HTML image with a caption', '<img src="https://example.com/diagram.png" alt="A diagram" /> A caption'],+ ['empty body', ''],+ ['missing body', null],])('keeps %s as a text card', (_name, markdown) => {- expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toBeNull()+ expect(getImageOnlyTextCardImage(markdown)).toBeNull()})- it('creates image markdown through the text card converter', () => {- const markdown = imageTileToMarkdown(textCardConverter, {- src: 'https://example.com/diagram.png',- alt: 'A diagram',- })+ // The text card editor writes image markdown and the dashboard reads it back without the editor,+ // so every image the editor can write must parse to the same image.+ it.each<[string, Pick<ImageTileImage, 'src' | 'alt'> & Partial<ImageTileImage>, string]>([+ [+ 'contain layout',+ { src: 'https://example.com/diagram.png', alt: 'A diagram' },+ '',+ ],+ [+ 'title',+ { src: 'https://example.com/diagram.png', alt: 'A diagram', title: 'The title' },+ '',+ ],+ [+ 'cover layout',+ { src: 'https://example.com/diagram.png', alt: 'A diagram', layout: 'cover' },+ '<img src="https://example.com/diagram.png" alt="A diagram" data-layout="cover" />',+ ],+ [+ 'custom position',+ {+ src: 'https://example.com/diagram.png',+ alt: 'A diagram',+ layout: 'cover',+ position: { x: 25, y: 75 },+ },+ '<img src="https://example.com/diagram.png" alt="A diagram" data-layout="cover" data-position-x="25" data-position-y="75" />',+ ],+ [+ 'size',+ { src: 'https://example.com/diagram.png', alt: 'A diagram', width: '320', height: '240' },+ '<img src="https://example.com/diagram.png" alt="A diagram" width="320" height="240" />',+ ],+ [+ 'parentheses in the source',+ { src: 'https://example.com/diagram(1).png', alt: 'A diagram' },+ '.png)',+ ],+ [+ 'bracket in the description',+ { src: 'https://example.com/diagram.png', alt: 'A ] diagram' },+ '![A \\] diagram](https://example.com/diagram.png)',+ ],+ [+ 'backslash in the description',+ { src: 'https://example.com/diagram.png', alt: 'A \\ diagram' },+ '<img src="https://example.com/diagram.png" alt="A \\ diagram" />',+ ],+ [+ 'quote in the title',+ { src: 'https://example.com/diagram.png', alt: 'A diagram', title: 'A "quoted" title' },+ '<img src="https://example.com/diagram.png" alt="A diagram" title="A "quoted" title" />',+ ],+ ])('reads back an image the editor writes with %s', (_name, image, expectedMarkdown) => {+ const markdown = imageTileToMarkdown(textCardConverter, image)- expect(markdown).toBe('')- })-- it('preserves a cover layout through the text card converter', () => {- const markdown = imageTileToMarkdown(textCardConverter, {- src: 'https://example.com/diagram.png',- alt: 'A diagram',- layout: 'cover',- })-- expect(markdown).toBe('<img src="https://example.com/diagram.png" alt="A diagram" data-layout="cover" />')- expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({ layout: 'cover' })+ expect(markdown).toBe(expectedMarkdown)expect(textCardConverter.isRoundTripSafe(markdown)).toBe(true)- })-- it('preserves a custom image position through the text card converter', () => {- const markdown = imageTileToMarkdown(textCardConverter, {- src: 'https://example.com/diagram.png',- alt: 'A diagram',- layout: 'cover',- position: { x: 25, y: 75 },+ expect(getImageOnlyTextCardImage(markdown)).toEqual({+ src: image.src,+ alt: image.alt,+ title: image.title ?? '',+ layout: image.layout ?? 'contain',+ position: image.position ?? { x: 50, y: 50 },+ width: image.width ?? null,+ height: image.height ?? null,})-- expect(markdown).toBe(- '<img src="https://example.com/diagram.png" alt="A diagram" data-layout="cover" data-position-x="25" data-position-y="75" />'- )- expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({ position: { x: 25, y: 75 } })- expect(textCardConverter.isRoundTripSafe(markdown)).toBe(true)})it('clamps malformed image positions to the frame', () => {expect(getImageOnlyTextCardImage(- textCardConverter,'<img src="https://example.com/diagram.png" alt="A diagram" data-position-x="120" data-position-y="-20" />')).toMatchObject({ position: { x: 100, y: 0 } })})-- it.each(['A ] diagram', 'A \\ diagram'])('preserves punctuation in image descriptions: %s', (alt) => {- const markdown = imageTileToMarkdown(textCardConverter, {- src: 'https://example.com/diagram.png',- alt,- })-- expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({ alt })- })})diff --git a/products/dashboards/frontend/components/ImageTile/imageTileUtils.ts b/products/dashboards/frontend/components/ImageTile/imageTileUtils.tsindex 0ebf019e71b0..49d7bfa21256 100644--- a/products/dashboards/frontend/components/ImageTile/imageTileUtils.ts+++ b/products/dashboards/frontend/components/ImageTile/imageTileUtils.ts@@ -1,5 +1,3 @@-import type { JSONContent } from '@tiptap/core'-import type { TiptapMarkdownConverter } from 'lib/utils/markdown'export type ImageTileLayout = 'contain' | 'cover'@@ -56,60 +54,69 @@ export function imageTilePositionToCss(position: ImageTilePosition): string {return `${normalizedPosition.x}% ${normalizedPosition.y}%`}-export function getImageOnlyTextCardImage(- converter: TiptapMarkdownConverter,- markdown: string | null | undefined-): ImageTileImage | null {+// One markdown image: ``, ``, either with an optional `"title"`.+// A bare src may hold parentheses nested two deep, such as `diagram(1).png`.+const MARKDOWN_IMAGE =+ /^!\[((?:\\.|[^\\\]])*)\]\((?:<((?:\\.|[^\\<>\n])*)>|(?!<)((?:\\.|[^\s()\\]|\((?:\\.|[^\s()\\]|\((?:\\.|[^\s()\\])*\))*\))+))(?:\s+"((?:\\.|[^"\\])*)")?\)$/+const MARKDOWN_ESCAPE = /\\([!-/:-@[-`{-~])/g++/**+ * Reads the image of a text card whose body is a single image, without the rich text editor,+ * so dashboard layout code can tell image tiles from text tiles before the editor loads.+ */+export function getImageOnlyTextCardImage(markdown: string | null | undefined): ImageTileImage | null {const cacheKey = markdown ?? ''if (imageOnlyTextCardImageCache.has(cacheKey)) {return imageOnlyTextCardImageCache.get(cacheKey) ?? null}- let doc: JSONContent- try {- doc = converter.markdownToDoc(markdown)- } catch {- cacheImageOnlyTextCardImage(cacheKey, null)+ const result = parseImageOnlyMarkdown(cacheKey.trim())+ cacheImageOnlyTextCardImage(cacheKey, result)++ return result+}++function parseImageOnlyMarkdown(body: string): ImageTileImage | null {+ const markdownImage = MARKDOWN_IMAGE.exec(body)+ if (markdownImage) {+ return toImageTile({+ src: (markdownImage[2] ?? markdownImage[3]).replace(MARKDOWN_ESCAPE, '$1'),+ alt: markdownImage[1].replace(MARKDOWN_ESCAPE, '$1'),+ title: markdownImage[4]?.replace(MARKDOWN_ESCAPE, '$1') ?? null,+ })+ }+ if (!body.startsWith('<')) {return null}- let image: ImageTileImage | null = null- let imageCount = 0- let hasOtherContent = false-- const visit = (node: JSONContent): void => {- if (node.type === 'image') {- imageCount += 1- const parsedImage = getImageTile(node)- if (parsedImage) {- image = parsedImage- } else {- hasOtherContent = true- }- return+ const images: HTMLImageElement[] = []+ const isImageOnly = (node: Node): boolean => {+ if (node.nodeType === Node.TEXT_NODE) {+ return !node.textContent?.trim()}-- if (node.type === 'text') {- if (node.text?.trim()) {- hasOtherContent = true- }- return- }-- if (node.type === 'doc' || node.type === 'paragraph') {- node.content?.forEach(visit)- return+ if (node instanceof HTMLImageElement) {+ images.push(node)+ return true}-- hasOtherContent = true+ return node instanceof HTMLParagraphElement && Array.from(node.childNodes).every(isImageOnly)+ }+ const { body: htmlBody } = new DOMParser().parseFromString(body, 'text/html')+ if (!Array.from(htmlBody.childNodes).every(isImageOnly) || images.length !== 1) {+ return null}- visit(doc)-- const result = imageCount === 1 && !hasOtherContent ? image : null- cacheImageOnlyTextCardImage(cacheKey, result)-- return result+ const [image] = images+ const x = image.getAttribute('data-position-x')+ const y = image.getAttribute('data-position-y')+ return toImageTile({+ src: image.getAttribute('src'),+ alt: image.getAttribute('alt'),+ title: image.getAttribute('title'),+ layout: image.getAttribute('data-layout') === 'cover' ? 'cover' : null,+ position: x === null || y === null ? null : { x: Number(x), y: Number(y) },+ width: image.getAttribute('width'),+ height: image.getAttribute('height'),+ })}export function imageTileToMarkdown(@@ -143,20 +150,30 @@ export function imageTileToMarkdown(})}-function getImageTile(node: JSONContent): ImageTileImage | null {- const src = String(node.attrs?.src ?? '').trim()+interface ImageTileAttributes {+ src: string | null+ alt: string | null+ title: string | null+ layout?: ImageTileLayout | null+ position?: ImageTilePosition | null+ width?: string | null+ height?: string | null+}++function toImageTile(attrs: ImageTileAttributes): ImageTileImage | null {+ const src = (attrs.src ?? '').trim()if (!src) {return null}return {src,- alt: String(node.attrs?.alt ?? ''),- title: String(node.attrs?.title ?? ''),- layout: getImageTileLayout(node.attrs?.layout),- position: getImageTilePosition(node.attrs?.position),- width: node.attrs?.width,- height: node.attrs?.height,+ alt: attrs.alt ?? '',+ title: attrs.title ?? '',+ layout: getImageTileLayout(attrs.layout),+ position: getImageTilePosition(attrs.position),+ width: attrs.width ?? null,+ height: attrs.height ?? null,}}