diff --git a/apps/mobile/modules/t3-markdown-text/index.ts b/apps/mobile/modules/t3-markdown-text/index.ts index 89bce5395c..17fb433655 100644 --- a/apps/mobile/modules/t3-markdown-text/index.ts +++ b/apps/mobile/modules/t3-markdown-text/index.ts @@ -21,6 +21,8 @@ export { type MarkdownHighlightedToken, } from "./src/SelectableMarkdownText"; export type { + MarkdownImagePresentation, + MarkdownImageRenderer, NativeMarkdownTextStyle, SelectableMarkdownSkill, SelectableMarkdownTextProps, diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx index e6a045b3cd..8e9b4b2787 100644 --- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx +++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { createContext, useContext, useEffect, useState } from "react"; import { Image, ScrollView, Text, useColorScheme, View } from "react-native"; import type { MarkdownNode } from "react-native-nitro-markdown/headless"; @@ -13,9 +13,14 @@ import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios import type { MarkdownCodeHighlighter, MarkdownHighlightedToken, + MarkdownImageRenderer, NativeMarkdownTextStyle, } from "./SelectableMarkdownText.types"; +export const MarkdownImageRendererContext = createContext( + undefined, +); + type HighlightedCode = ReadonlyArray>; const highlightedCodeCache = new Map(); @@ -379,6 +384,7 @@ function NativeMarkdownImage(props: { readonly textStyle: NativeMarkdownTextStyle; readonly onLinkPress?: (href: string) => void; }) { + const renderImage = useContext(MarkdownImageRendererContext); const href = props.node.href; if (!href) { return ( @@ -390,6 +396,18 @@ function NativeMarkdownImage(props: { ); } + if (renderImage) { + return ( + <> + {renderImage({ + href, + ...(props.node.alt ? { alt: props.node.alt } : {}), + ...(props.node.title ? { title: props.node.title } : {}), + })} + + ); + } + return ( - {chunks.map((chunk, index) => { - const content = - chunk.kind === "rich" ? ( - - ) : ( - - ); + + {/* A percentage width here creates a cyclic intrinsic measurement inside + shrink-to-fit containers such as user-message bubbles. Yoga then gives + the native text node an unbounded second pass and the parent only clips + the resulting single-line width instead of reflowing it. */} + + {chunks.map((chunk, index) => { + const content = + chunk.kind === "rich" ? ( + + ) : ( + + ); - return ( - - {content} - - ); - })} - + return ( + + {content} + + ); + })} + + ); } diff --git a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts index 42cc3cd6fb..defebde68f 100644 --- a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts +++ b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts @@ -1,3 +1,5 @@ +import type { ReactNode } from "react"; + export interface NativeMarkdownTextStyle { readonly color: string; readonly strongColor: string; @@ -36,6 +38,14 @@ export interface SelectableMarkdownSkill { readonly displayName?: string | null; } +export interface MarkdownImagePresentation { + readonly href: string; + readonly alt?: string; + readonly title?: string; +} + +export type MarkdownImageRenderer = (image: MarkdownImagePresentation) => ReactNode; + export interface SelectableMarkdownTextProps { readonly markdown: string; readonly textStyle: NativeMarkdownTextStyle; @@ -43,6 +53,7 @@ export interface SelectableMarkdownTextProps { readonly skills?: ReadonlyArray; readonly preserveSoftBreaks?: boolean; readonly onLinkPress?: (href: string) => void; + readonly renderImage?: MarkdownImageRenderer; readonly marginTop?: number; readonly marginBottom?: number; } diff --git a/apps/mobile/src/features/threads/MarkdownMedia.tsx b/apps/mobile/src/features/threads/MarkdownMedia.tsx new file mode 100644 index 0000000000..619d98d27f --- /dev/null +++ b/apps/mobile/src/features/threads/MarkdownMedia.tsx @@ -0,0 +1,233 @@ +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + isWorkspaceVideoPreviewPath, + markdownMediaFileName, + resolveMarkdownMediaSource, +} from "@t3tools/shared/filePreview"; +import { useMemo, useState } from "react"; +import { ActivityIndicator, Image, Pressable, Text, type ColorValue, View } from "react-native"; +import { WebView } from "react-native-webview"; + +import { useAssetUrlState } from "../../state/assets"; + +interface MarkdownMediaProps { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly src: string; + readonly alt?: string; + readonly title?: string; + readonly backgroundColor: ColorValue; + readonly mutedColor: ColorValue; + readonly onPressImage: (uri: string) => void; +} + +function normalizeDirectUrl(url: string): string { + return url.startsWith("//") ? `https:${url}` : url; +} + +function escapeHtmlAttribute(value: string): string { + return value + .replaceAll("&", "&") + .replaceAll('"', """) + .replaceAll("<", "<") + .replaceAll(">", ">"); +} + +function MediaUnavailable(props: { readonly name: string; readonly color: ColorValue }) { + return ( + + + Media unavailable: {props.name} + + + ); +} + +function LoadingMedia(props: { + readonly name: string; + readonly backgroundColor: ColorValue; + readonly color: ColorValue; +}) { + return ( + + + + {props.name} + + + ); +} + +function MarkdownVideo(props: { + readonly url: string; + readonly name: string; + readonly backgroundColor: ColorValue; + readonly color: ColorValue; + readonly onError: () => void; +}) { + const html = useMemo(() => { + const url = escapeHtmlAttribute(props.url); + const name = escapeHtmlAttribute(props.name); + return ` + + + + + + + + + +`; + }, [props.name, props.url]); + + return ( + + + { + if (event.nativeEvent.data === "media-error") { + props.onError(); + } + }} + originWhitelist={["*"]} + scrollEnabled={false} + source={{ html }} + style={{ flex: 1, backgroundColor: "#000000" }} + /> + + + {props.name} + + + ); +} + +function ResolvedMedia(props: { + readonly url: string; + readonly name: string; + readonly isVideo: boolean; + readonly backgroundColor: ColorValue; + readonly color: ColorValue; + readonly onPressImage: (uri: string) => void; +}) { + const [failedUrl, setFailedUrl] = useState(null); + const [measuredImage, setMeasuredImage] = useState<{ + readonly url: string; + readonly aspectRatio: number; + } | null>(null); + const aspectRatio = measuredImage?.url === props.url ? measuredImage.aspectRatio : 16 / 9; + + if (failedUrl === props.url) { + return ; + } + + if (props.isVideo) { + return ( + setFailedUrl(props.url)} + /> + ); + } + + return ( + + props.onPressImage(props.url)} + style={{ aspectRatio, backgroundColor: props.backgroundColor }} + > + setFailedUrl(props.url)} + onLoad={(event) => { + const { width, height } = event.nativeEvent.source; + if (width > 0 && height > 0) { + setMeasuredImage({ + url: props.url, + aspectRatio: Math.min(2, Math.max(0.75, width / height)), + }); + } + }} + resizeMode="contain" + source={{ uri: props.url }} + style={{ height: "100%", width: "100%" }} + /> + + + {props.name} + + + ); +} + +export function MarkdownMedia(props: MarkdownMediaProps) { + const source = useMemo( + () => resolveMarkdownMediaSource(props.src, props.threadId), + [props.src, props.threadId], + ); + const assetUrl = useAssetUrlState( + source._tag === "Asset" ? props.environmentId : null, + source._tag === "Asset" ? source.resource : null, + ); + const name = + props.alt?.trim() || props.title?.trim() || markdownMediaFileName(props.src) || "Media"; + const isVideo = isWorkspaceVideoPreviewPath(props.src); + + if (source._tag === "Direct") { + return ( + + ); + } + if (assetUrl._tag === "Failure") { + return ; + } + if (assetUrl._tag === "Loading") { + return ( + + ); + } + return ( + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 8ad117c863..2b4aeee22f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -59,6 +59,7 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { hasNativeSelectableMarkdownText, SelectableMarkdownText, + type MarkdownImageRenderer, type NativeMarkdownTextStyle, type SelectableMarkdownSkill, } from "../../native/SelectableMarkdownText"; @@ -101,6 +102,7 @@ import { ThreadWorkLog, WORK_GROUP_TOGGLE_HEIGHT, } from "./thread-work-log"; +import { MarkdownMedia } from "./MarkdownMedia"; import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState"; import { useAssetUrl } from "../../state/assets"; import { resolveWorkspaceRelativeFilePath } from "../files/filePath"; @@ -244,6 +246,7 @@ interface MarkdownStyleSet { readonly theme: PartialMarkdownTheme; readonly styles: NodeStyleOverrides; readonly renderers: CustomRenderers; + readonly renderImage: MarkdownImageRenderer; readonly nativeTextStyle: NativeMarkdownTextStyle; } @@ -446,7 +449,12 @@ function useReviewCommentColors(): ReviewCommentColors { ); } -function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets { +function useMarkdownStyles( + onLinkPress: (href: string) => void, + environmentId: EnvironmentId, + threadId: ThreadId, + onPressImage: (uri: string) => void, +): MarkdownStyleSets { const colorScheme = useColorScheme(); const { appearance } = useAppearancePreferences(); const markdownFontSizes = useMemo( @@ -575,7 +583,14 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe copyTintColor: ColorValue, preserveSoftBreaks: boolean, highlightCode: boolean, + renderImage: MarkdownImageRenderer, ): CustomRenderers => ({ + image: ({ url = "", alt, title }) => + renderImage({ + href: url, + ...(alt ? { alt } : {}), + ...(title ? { title } : {}), + }), link: ({ children, href = "" }) => { const presentation = resolveMarkdownLinkPresentation(href); if (presentation.kind === "file") { @@ -689,6 +704,22 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe /> ), }); + const createMediaRenderer = + (backgroundColor: ColorValue, mutedColor: ColorValue): MarkdownImageRenderer => + ({ href, alt, title }) => ( + + ); + const userMediaRenderer = createMediaRenderer(markdownUserCodeBg, markdownUserBodyColor); + const assistantMediaRenderer = createMediaRenderer(markdownCodeBg, iconSubtleColor); const userTheme: PartialMarkdownTheme = { ...baseTheme, @@ -747,7 +778,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe userBubbleForegroundMuted, true, false, + userMediaRenderer, ), + renderImage: userMediaRenderer, nativeTextStyle: { color: markdownUserBodyColor, strongColor: markdownUserBodyColor, @@ -780,7 +813,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe iconSubtleColor, false, true, + assistantMediaRenderer, ), + renderImage: assistantMediaRenderer, nativeTextStyle: { color: markdownBodyColor, strongColor: markdownStrongColor, @@ -810,9 +845,12 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe inlineSkillForeground, markdownFontSizes, nativeMarkdownTypography, + environmentId, onLinkPress, + onPressImage, regularFontFamily, themeMode, + threadId, userBubbleForegroundMuted, ]); } @@ -969,6 +1007,7 @@ function renderFeedEntry( skills={props.skills} textStyle={styles.nativeTextStyle} onLinkPress={props.onMarkdownLinkPress} + renderImage={styles.renderImage} /> ) : ( ); } @@ -1107,6 +1147,7 @@ function UserMessageContent(props: { textStyle={props.markdownStyles.nativeTextStyle} preserveSoftBreaks onLinkPress={props.onLinkPress} + renderImage={props.markdownStyles.renderImage} /> ) : ( ; } | null>(null); + const onPressImage = useCallback((uri: string, headers?: Record) => { + setExpandedImage({ uri, headers }); + }, []); const horizontalPadding = props.layoutVariant === "split" ? 20 : 16; const contentHorizontalPadding = deriveCenteredContentHorizontalPadding({ viewportWidth, @@ -1400,7 +1444,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }, [props.environmentId, props.threadId, props.workspaceRoot, navigation], ); - const markdownStyles = useMarkdownStyles(onMarkdownLinkPress); + const markdownStyles = useMarkdownStyles( + onMarkdownLinkPress, + props.environmentId, + props.threadId, + onPressImage, + ); const reviewCommentColors = useReviewCommentColors(); // LegendList does not invalidate visible rows when only the renderItem closure changes. // Keep row-local interaction props in extraData so disclosures and copy feedback repaint. @@ -1692,10 +1741,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { [suspendEndScrollMaintenanceForDisclosure], ); - const onPressImage = useCallback((uri: string, headers?: Record) => { - setExpandedImage({ uri, headers }); - }, []); - // Rows whose height is known before they ever render. Without this, every // row above the viewport is assumed to be estimatedItemSize tall, and // scrolling up through unmeasured content corrects each row's height as it diff --git a/apps/mobile/src/native/SelectableMarkdownText.ios.tsx b/apps/mobile/src/native/SelectableMarkdownText.ios.tsx index 488766f369..6ecb361c98 100644 --- a/apps/mobile/src/native/SelectableMarkdownText.ios.tsx +++ b/apps/mobile/src/native/SelectableMarkdownText.ios.tsx @@ -8,6 +8,7 @@ import { highlightCodeSnippet } from "../features/review/shikiReviewHighlighter" type MobileSelectableMarkdownTextProps = Omit; export type { + MarkdownImageRenderer, NativeMarkdownTextStyle, SelectableMarkdownSkill, } from "@t3tools/mobile-markdown-text/types"; diff --git a/apps/mobile/src/native/SelectableMarkdownText.tsx b/apps/mobile/src/native/SelectableMarkdownText.tsx index 403f32a1de..db9a0b091e 100644 --- a/apps/mobile/src/native/SelectableMarkdownText.tsx +++ b/apps/mobile/src/native/SelectableMarkdownText.tsx @@ -3,6 +3,7 @@ import type { SelectableMarkdownTextProps } from "@t3tools/mobile-markdown-text/ type MobileSelectableMarkdownTextProps = Omit; export type { + MarkdownImageRenderer, NativeMarkdownTextStyle, SelectableMarkdownSkill, } from "@t3tools/mobile-markdown-text/types"; diff --git a/apps/mobile/src/state/assets.ts b/apps/mobile/src/state/assets.ts index b8b827585e..480b3aa234 100644 --- a/apps/mobile/src/state/assets.ts +++ b/apps/mobile/src/state/assets.ts @@ -12,18 +12,35 @@ const EMPTY_ASSET_URL_ATOM = Atom.make(AsyncResult.initial(false)) Atom.withLabel("mobile-asset-url:empty"), ); -export function useAssetUrl( +export type AssetUrlState = + | { readonly _tag: "Loading" } + | { readonly _tag: "Failure" } + | { readonly _tag: "Success"; readonly url: string }; + +export function useAssetUrlState( environmentId: EnvironmentId | null, resource: AssetResource | null, -): string | null { +): AssetUrlState { const preparedConnection = usePreparedConnection(environmentId); const result = useAtomValue( environmentId === null || resource === null ? EMPTY_ASSET_URL_ATOM : assetEnvironment.createUrl({ environmentId, input: { resource } }), ); - if (preparedConnection._tag === "None" || result._tag !== "Success") { - return null; + if (result._tag === "Failure") { + return { _tag: "Failure" }; } - return resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl); + if (preparedConnection._tag === "None" || result._tag !== "Success") { + return { _tag: "Loading" }; + } + const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl); + return url === null ? { _tag: "Failure" } : { _tag: "Success", url }; +} + +export function useAssetUrl( + environmentId: EnvironmentId | null, + resource: AssetResource | null, +): string | null { + const result = useAssetUrlState(environmentId, resource); + return result._tag === "Success" ? result.url : null; } diff --git a/apps/web/src/components/chat/MarkdownMedia.tsx b/apps/web/src/components/chat/MarkdownMedia.tsx index f9aba64ac7..50b6fe2e12 100644 --- a/apps/web/src/components/chat/MarkdownMedia.tsx +++ b/apps/web/src/components/chat/MarkdownMedia.tsx @@ -1,20 +1,16 @@ import { memo, useState } from "react"; import { createPortal } from "react-dom"; import type { AssetResource, ScopedThreadRef } from "@t3tools/contracts"; -import { isWorkspaceVideoPreviewPath } from "@t3tools/shared/filePreview"; +import { + isDirectMarkdownMediaSource, + isWorkspaceVideoPreviewPath, + markdownMediaFileName, + resolveMarkdownMediaSource, +} from "@t3tools/shared/filePreview"; import { useAssetUrlState } from "../../assets/assetUrls"; import { ExpandedImageDialog } from "./ExpandedImageDialog"; -/** Sources the browser can load directly without a signed workspace asset URL. */ -const DIRECT_MEDIA_SRC_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i; - -/** `markdownUrlTransform` escapes Windows drive paths as `/C:/…` so they survive sanitization. */ -const ESCAPED_WINDOWS_DRIVE_PATH_PATTERN = /^\/[A-Za-z]:[\\/]/; - -/** Paths that are absolute on either platform (after Windows-drive unescaping). */ -const ABSOLUTE_PATH_PATTERN = /^(?:[/\\]|[A-Za-z]:[\\/])/; - const MEDIA_FRAME_CLASS_NAME = "my-2 block max-h-96 max-w-full rounded-lg border border-border/60 bg-background object-contain"; @@ -26,48 +22,6 @@ interface MarkdownMediaProps { kind?: "image" | "video" | undefined; } -function safeDecode(value: string): string { - try { - return decodeURIComponent(value); - } catch { - return value; - } -} - -function mediaFileName(src: string): string { - const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; - const basename = withoutQuery.slice(withoutQuery.lastIndexOf("/") + 1); - return basename.length > 0 ? safeDecode(basename) : safeDecode(withoutQuery); -} - -/** - * Normalize a non-direct markdown src into a filesystem-style path: strip - * query/fragment, decode percent escapes, and unescape the `/C:/…` form the - * markdown URL transform uses to carry Windows drive paths through - * sanitization. - */ -function mediaPathFromSrc(src: string): string { - const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; - const decoded = safeDecode(withoutQuery); - return ESCAPED_WINDOWS_DRIVE_PATH_PATTERN.test(decoded) ? decoded.slice(1) : decoded; -} - -/** - * Browser evidence artifacts (screenshots/recordings from the embedded - * browser) are referenced by the absolute path the preview tools return, - * e.g. `/…/userdata/browser-artifacts/browser-recording-x.webm`. They are - * served by file name from the server's browser-artifacts directory. Only - * absolute paths qualify — a workspace-relative path like - * `docs/browser-artifacts/x.png` is an ordinary repo file. - */ -function browserArtifactFileName(path: string): string | null { - if (!ABSOLUTE_PATH_PATTERN.test(path)) { - return null; - } - const match = /[/\\]browser-artifacts[/\\]([^/\\]+)$/.exec(path); - return match?.[1] ?? null; -} - function MediaUnavailable({ name }: { name: string }) { return ( @@ -171,22 +125,18 @@ export const MarkdownMedia = memo(function MarkdownMedia({ if (!src) { return null; } - const name = alt && alt.trim().length > 0 ? alt.trim() : mediaFileName(src); + const name = alt && alt.trim().length > 0 ? alt.trim() : markdownMediaFileName(src); const isVideo = kind === "video" || (kind === undefined && isWorkspaceVideoPreviewPath(src)); - if (DIRECT_MEDIA_SRC_PATTERN.test(src)) { + if (isDirectMarkdownMediaSource(src)) { return ; } if (!threadRef) { return ; } - const path = mediaPathFromSrc(src); - const artifactFileName = browserArtifactFileName(path); - const resource: AssetResource = artifactFileName - ? { _tag: "browser-artifact", fileName: artifactFileName } - : { - _tag: "workspace-file", - threadId: threadRef.threadId, - path: path.startsWith("./") ? path.slice(2) : path, - }; - return ; + const source = resolveMarkdownMediaSource(src, threadRef.threadId); + return source._tag === "Asset" ? ( + + ) : ( + + ); }); diff --git a/packages/shared/src/filePreview.test.ts b/packages/shared/src/filePreview.test.ts index eb8b7d1e89..117b3726a6 100644 --- a/packages/shared/src/filePreview.test.ts +++ b/packages/shared/src/filePreview.test.ts @@ -1,9 +1,12 @@ +import { ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { isWorkspaceBrowserPreviewPath, isWorkspaceImagePreviewPath, isWorkspacePreviewEntryPath, + markdownMediaFileName, + resolveMarkdownMediaSource, } from "./filePreview.ts"; describe("workspace file previews", () => { @@ -33,4 +36,63 @@ describe("workspace file previews", () => { expect(isWorkspacePreviewEntryPath(path)).toBe(false); }, ); + + it("classifies direct markdown media without asset resolution", () => { + expect( + resolveMarkdownMediaSource("https://cdn.example/preview.png", ThreadId.make("thread-1")), + ).toEqual({ + _tag: "Direct", + url: "https://cdn.example/preview.png", + }); + }); + + it("scopes relative markdown media to the thread worktree", () => { + expect( + resolveMarkdownMediaSource("./tmp/evidence%20capture.png?cache=1", ThreadId.make("thread-1")), + ).toEqual({ + _tag: "Asset", + resource: { + _tag: "workspace-file", + threadId: "thread-1", + path: "tmp/evidence capture.png", + }, + }); + }); + + it.each([ + "/tmp/userdata/browser-artifacts/browser-recording-1.webm", + "C:\\t3\\userdata\\browser-artifacts\\browser-recording-1.webm", + "/C:/t3/userdata/browser-artifacts/browser-recording-1.webm", + ])("resolves absolute browser artifact path %s", (path) => { + expect(resolveMarkdownMediaSource(path, ThreadId.make("thread-1"))).toEqual({ + _tag: "Asset", + resource: { + _tag: "browser-artifact", + fileName: "browser-recording-1.webm", + }, + }); + }); + + it("does not treat a relative browser-artifacts directory as the artifact store", () => { + expect( + resolveMarkdownMediaSource( + "docs/browser-artifacts/browser-recording-1.webm", + ThreadId.make("thread-1"), + ), + ).toEqual({ + _tag: "Asset", + resource: { + _tag: "workspace-file", + threadId: "thread-1", + path: "docs/browser-artifacts/browser-recording-1.webm", + }, + }); + }); + + it("derives a decoded media file name without query or fragment", () => { + expect(markdownMediaFileName("tmp/evidence%20capture.png?cache=1#preview")).toBe( + "evidence capture.png", + ); + expect(markdownMediaFileName("C:\\tmp\\evidence%20capture.png")).toBe("evidence capture.png"); + }); }); diff --git a/packages/shared/src/filePreview.ts b/packages/shared/src/filePreview.ts index 040f95dd6f..f59a788e42 100644 --- a/packages/shared/src/filePreview.ts +++ b/packages/shared/src/filePreview.ts @@ -1,3 +1,5 @@ +import type { AssetResource, ThreadId } from "@t3tools/contracts"; + export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const; export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [ @@ -13,6 +15,19 @@ export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [ export const WORKSPACE_VIDEO_PREVIEW_EXTENSIONS = [".m4v", ".mov", ".mp4", ".webm"] as const; +/** Sources a client can load directly without a signed workspace asset URL. */ +const DIRECT_MARKDOWN_MEDIA_SRC_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i; + +/** Web markdown URL normalization carries Windows drive paths as `/C:/…`. */ +const ESCAPED_WINDOWS_DRIVE_PATH_PATTERN = /^\/[A-Za-z]:[\\/]/; + +/** Paths that are absolute on either platform after Windows-drive unescaping. */ +const ABSOLUTE_PATH_PATTERN = /^(?:[/\\]|[A-Za-z]:[\\/])/; + +export type MarkdownMediaSource = + | { readonly _tag: "Direct"; readonly url: string } + | { readonly _tag: "Asset"; readonly resource: AssetResource }; + function hasPreviewExtension(path: string, extensions: ReadonlyArray): boolean { const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? ""; return extensions.some((extension) => pathWithoutQuery.endsWith(extension)); @@ -37,3 +52,52 @@ export function isWorkspacePreviewEntryPath(path: string): boolean { isWorkspaceVideoPreviewPath(path) ); } + +export function isDirectMarkdownMediaSource(src: string): boolean { + return DIRECT_MARKDOWN_MEDIA_SRC_PATTERN.test(src); +} + +function safeDecode(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +export function markdownMediaFileName(src: string): string { + const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; + const basename = withoutQuery.slice( + Math.max(withoutQuery.lastIndexOf("/"), withoutQuery.lastIndexOf("\\")) + 1, + ); + return basename.length > 0 ? safeDecode(basename) : safeDecode(withoutQuery); +} + +/** + * Normalize markdown media into either a directly loadable URL or an asset RPC + * resource. Absolute preview-tool artifact paths are served from the dedicated + * artifact store; every other non-direct path is scoped to the thread worktree. + */ +export function resolveMarkdownMediaSource(src: string, threadId: ThreadId): MarkdownMediaSource { + if (isDirectMarkdownMediaSource(src)) { + return { _tag: "Direct", url: src }; + } + + const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; + const decoded = safeDecode(withoutQuery); + const path = ESCAPED_WINDOWS_DRIVE_PATH_PATTERN.test(decoded) ? decoded.slice(1) : decoded; + const artifactMatch = ABSOLUTE_PATH_PATTERN.test(path) + ? /[/\\]browser-artifacts[/\\]([^/\\]+)$/.exec(path) + : null; + + return { + _tag: "Asset", + resource: artifactMatch?.[1] + ? { _tag: "browser-artifact", fileName: artifactMatch[1] } + : { + _tag: "workspace-file", + threadId, + path: path.startsWith("./") ? path.slice(2) : path, + }, + }; +}