: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(mobilehog): render markdown images (#109520)
Dylan Martin16ece54318f6
diff --git a/products/desktop/apps/mobilehog/src/components/Markdown.tsx b/products/desktop/apps/mobilehog/src/components/Markdown.tsxindex 3700243d4d4b..1216c1529283 100644--- a/products/desktop/apps/mobilehog/src/components/Markdown.tsx+++ b/products/desktop/apps/mobilehog/src/components/Markdown.tsx@@ -1,14 +1,17 @@import { isSafeExternalUrl } from "@posthog/shared";import { type MarkedToken, marked, type Token, type Tokens } from "marked";-import { type ReactNode, useMemo } from "react";+import { type ReactNode, useMemo, useState } from "react";import {type ColorValue,+ Image,Linking,+ Pressable,ScrollView,StyleSheet,Text,View,} from "react-native";+import { splitImageRuns } from "@/lib/markdown";import { colors, fonts } from "@/lib/theme";interface MarkdownProps {@@ -23,6 +26,7 @@ function openLink(href: string): void {function renderInline(tokens: Token[] | undefined,color: ColorValue,+ linked = false,): ReactNode[] {return (tokens ?? []).map((raw, index) => {const token = raw as MarkedToken;@@ -31,19 +35,19 @@ function renderInline(case "strong":return (<Text key={key} style={{ fontFamily: fonts.sansSemi, color }}>- {renderInline(token.tokens, color)}+ {renderInline(token.tokens, color, linked)}</Text>);case "em":return (<Text key={key} style={{ fontFamily: fonts.sansItalic, color }}>- {renderInline(token.tokens, color)}+ {renderInline(token.tokens, color, linked)}</Text>);case "del":return (<Text key={key} style={styles.strike}>- {renderInline(token.tokens, color)}+ {renderInline(token.tokens, color, linked)}</Text>);case "codespan":@@ -59,14 +63,26 @@ function renderInline(style={styles.link}onPress={() => openLink(token.href)}>- {renderInline(token.tokens, colors.accent)}+ {renderInline(token.tokens, colors.accent, true)}+ </Text>+ );+ case "image":+ return !linked && isSafeExternalUrl(token.href) ? (+ <Text+ key={key}+ style={styles.link}+ onPress={() => openLink(token.href)}+ >+ {token.text || token.href}</Text>+ ) : (+ token.text);case "br":return "\n";case "text":return token.tokens ? (- <Text key={key}>{renderInline(token.tokens, color)}</Text>+ <Text key={key}>{renderInline(token.tokens, color, linked)}</Text>) : (token.text);@@ -138,6 +154,72 @@ function List({ token, color }: { token: Tokens.List; color: ColorValue }) {);}+interface ImageSize {+ width: number;+ height: number;+}++function MarkdownImage({ token }: { token: Tokens.Image }) {+ const [size, setSize] = useState<ImageSize | null>(null);+ const [failed, setFailed] = useState(false);+ if (failed) {+ return (+ <Text+ style={[styles.body, styles.link]}+ onPress={() => openLink(token.href)}+ >+ {token.text || token.href}+ </Text>+ );+ }+ return (+ <Pressable+ onPress={() => openLink(token.href)}+ accessibilityRole="imagebutton"+ accessibilityLabel={token.text || undefined}+ >+ <Image+ source={{ uri: token.href }}+ onLoad={(event) => {+ const { width, height } = event.nativeEvent.source;+ if (width > 0 && height > 0) setSize({ width, height });+ }}+ onError={() => setFailed(true)}+ style={[+ styles.image,+ size+ ? { aspectRatio: size.width / size.height }+ : styles.imagePending,+ ]}+ />+ </Pressable>+ );+}++function Paragraph({ tokens, color }: { tokens: Token[]; color: ColorValue }) {+ const runs = splitImageRuns(tokens);+ if (!runs.some((run) => run.kind === "image")) {+ return (+ <Text style={[styles.body, { color }]} selectable>+ {renderInline(tokens, color)}+ </Text>+ );+ }+ return (+ <View style={styles.runs}>+ {runs.map((run, index) =>+ run.kind === "image" ? (+ <MarkdownImage key={`${index}-${run.token.href}`} token={run.token} />+ ) : (+ <Text key={String(index)} style={[styles.body, { color }]} selectable>+ {renderInline(run.tokens, color)}+ </Text>+ ),+ )}+ </View>+ );+}+function renderBlocks(tokens: Token[] | undefined,color: ColorValue,@@ -189,9 +271,7 @@ function renderBlocks(case "paragraph":case "text":return (- <Text key={key} style={[styles.body, { color }]} selectable>- {renderInline(token.tokens, color)}- </Text>+ <Paragraph key={key} tokens={token.tokens ?? []} color={color} />);default:return null;@@ -250,6 +330,13 @@ const styles = StyleSheet.create({color: colors.ink,},strike: { textDecorationLine: "line-through" },+ runs: { gap: 8 },+ image: {+ width: "100%",+ borderRadius: 16,+ backgroundColor: colors.fill,+ },+ imagePending: { aspectRatio: 16 / 9 },link: { color: colors.accent, textDecorationLine: "underline" },table: {borderWidth: StyleSheet.hairlineWidth,diff --git a/products/desktop/apps/mobilehog/src/lib/markdown.test.ts b/products/desktop/apps/mobilehog/src/lib/markdown.test.tsnew file mode 100644index 000000000000..21aae3cf5e4f--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/markdown.test.ts@@ -0,0 +1,113 @@+import { marked, type Token, type Tokens } from "marked";+import { describe, expect, it } from "vitest";+import { isLoadableImageUrl, splitImageRuns } from "./markdown";++function paragraphTokens(text: string): Token[] {+ const [paragraph] = marked.lexer(text) as Tokens.Paragraph[];+ return paragraph.tokens;+}++describe("splitImageRuns", () => {+ it("keeps a paragraph without images as one text run", () => {+ const runs = splitImageRuns(paragraphTokens("Just **text** here."));+ expect(runs).toHaveLength(1);+ expect(runs[0].kind).toBe("text");+ });++ it("lifts a lone image into an image run", () => {+ const runs = splitImageRuns(+ paragraphTokens(""),+ );+ expect(runs).toEqual([+ {+ kind: "image",+ token: expect.objectContaining({+ href: "https://example.com/chart.png",+ text: "A chart",+ }),+ },+ ]);+ });++ it("splits text around an inline image", () => {+ const runs = splitImageRuns(+ paragraphTokens("Before  after"),+ );+ expect(runs.map((run) => run.kind)).toEqual(["text", "image", "text"]);+ });++ it("drops whitespace between images", () => {+ const runs = splitImageRuns(+ paragraphTokens(+ " ",+ ),+ );+ expect(runs.map((run) => run.kind)).toEqual(["image", "image"]);+ });++ it("keeps images with unsafe URLs inline", () => {+ const runs = splitImageRuns(+ paragraphTokens("See  now"),+ );+ expect(runs).toHaveLength(1);+ expect(runs[0].kind).toBe("text");+ });++ it("leaves images nested in links inline", () => {+ const runs = splitImageRuns(+ paragraphTokens(+ "[](https://example.com)",+ ),+ );+ expect(runs).toHaveLength(1);+ expect(runs[0].kind).toBe("text");+ });++ it.each([+ ["bold", "****"],+ ["italic", "__"],+ ["struck", "~~~~"],+ ])("lifts an image out of %s text", (_name, text) => {+ const runs = splitImageRuns(paragraphTokens(text));+ expect(runs.map((run) => run.kind)).toEqual(["image"]);+ });++ it("keeps the formatting of text around a lifted image", () => {+ const runs = splitImageRuns(+ paragraphTokens("**Before  after**"),+ );+ expect(runs.map((run) => run.kind)).toEqual(["text", "image", "text"]);+ const [before, , after] = runs;+ for (const run of [before, after]) {+ expect(run.kind === "text" && run.tokens[0].type).toBe("strong");+ }+ });++ it("leaves formatted images nested in links inline", () => {+ const runs = splitImageRuns(+ paragraphTokens(+ "[****](https://example.com)",+ ),+ );+ expect(runs.map((run) => run.kind)).toEqual(["text"]);+ });++ it("keeps images with mailto URLs inline", () => {+ const runs = splitImageRuns(+ paragraphTokens("Write  today"),+ );+ expect(runs.map((run) => run.kind)).toEqual(["text"]);+ });+});++describe("isLoadableImageUrl", () => {+ it.each([+ ["https://example.com/a.png", true],+ ["HTTP://example.com/a.png", true],+ ["mailto:[email protected]", false],+ ["file:///etc/passwd", false],+ ["not a url", false],+ ])("%s -> %s", (href, expected) => {+ expect(isLoadableImageUrl(href)).toBe(expected);+ });+});diff --git a/products/desktop/apps/mobilehog/src/lib/markdown.ts b/products/desktop/apps/mobilehog/src/lib/markdown.tsnew file mode 100644index 000000000000..78bdd3eb8754--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/markdown.ts@@ -0,0 +1,82 @@+import { isSafeExternalUrl } from "@posthog/shared";+import type { Token, Tokens } from "marked";++export type InlineRun =+ | { kind: "text"; tokens: Token[] }+ | { kind: "image"; token: Tokens.Image };++type Piece =+ | { kind: "text"; token: Token }+ | { kind: "image"; token: Tokens.Image };++export function isImageToken(token: Token): token is Tokens.Image {+ return token.type === "image";+}++export function isLoadableImageUrl(href: string): boolean {+ return /^https?:/i.test(href) && isSafeExternalUrl(href);+}++function isFormatToken(+ token: Token,+): token is Tokens.Strong | Tokens.Em | Tokens.Del {+ return token.type === "strong" || token.type === "em" || token.type === "del";+}++// Links stay whole, so an image inside a link keeps its alt text inline.+function liftImages(token: Token): Piece[] {+ if (isImageToken(token) && isLoadableImageUrl(token.href)) {+ return [{ kind: "image", token }];+ }+ if (!isFormatToken(token)) return [{ kind: "text", token }];+ const inner = token.tokens.flatMap(liftImages);+ if (!inner.some((piece) => piece.kind === "image")) {+ return [{ kind: "text", token }];+ }+ // Split the wrapper around each image so the text keeps its formatting.+ const pieces: Piece[] = [];+ let text: Token[] = [];+ const flush = () => {+ if (text.length) {+ const raw = text.map((child) => child.raw).join("");+ pieces.push({+ kind: "text",+ token: { ...token, raw, text: raw, tokens: text },+ });+ }+ text = [];+ };+ for (const piece of inner) {+ if (piece.kind === "image") {+ flush();+ pieces.push(piece);+ } else {+ text.push(piece.token);+ }+ }+ flush();+ return pieces;+}++// Images that can load stand on their own row between the text around them;+// the rest stay inline and render their alt text.+export function splitImageRuns(tokens: Token[]): InlineRun[] {+ const runs: InlineRun[] = [];+ let text: Token[] = [];+ const flush = () => {+ if (text.some((token) => token.raw.trim())) {+ runs.push({ kind: "text", tokens: text });+ }+ text = [];+ };+ for (const piece of tokens.flatMap(liftImages)) {+ if (piece.kind === "image") {+ flush();+ runs.push(piece);+ } else {+ text.push(piece.token);+ }+ }+ flush();+ return runs;+}