feat(mobile): render chat media previews
This commit is contained in:
12 files changed
+515
-108
No files matched your search
@@ -21,6 +21,8 @@ export {
|
||||
type MarkdownHighlightedToken,
|
||||
} from "./src/SelectableMarkdownText";
|
||||
export type {
|
||||
MarkdownImagePresentation,
|
||||
MarkdownImageRenderer,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
SelectableMarkdownTextProps,
|
||||
|
||||
@@ -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<MarkdownImageRenderer | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
|
||||
|
||||
const highlightedCodeCache = new Map<string, HighlightedCode>();
|
||||
@@ -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 (
|
||||
<View style={{ gap: 6 }}>
|
||||
<Image
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownWithPreservedSoftBreaks,
|
||||
} from "./nativeMarkdownText";
|
||||
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { MarkdownImageRendererContext, NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
SelectableMarkdownSkill,
|
||||
@@ -36,6 +36,7 @@ export function SelectableMarkdownText({
|
||||
highlightCode,
|
||||
preserveSoftBreaks = false,
|
||||
onLinkPress,
|
||||
renderImage,
|
||||
marginTop = 0,
|
||||
marginBottom = 0,
|
||||
}: SelectableMarkdownTextProps) {
|
||||
@@ -59,37 +60,39 @@ export function SelectableMarkdownText({
|
||||
}, [markdown, preserveSoftBreaks, skills]);
|
||||
|
||||
return (
|
||||
// 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.
|
||||
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={chunk.runs}
|
||||
textStyle={textStyle}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
);
|
||||
<MarkdownImageRendererContext.Provider value={renderImage}>
|
||||
{/* 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. */}
|
||||
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={chunk.runs}
|
||||
textStyle={textStyle}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
key={chunk.key}
|
||||
style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
|
||||
>
|
||||
{content}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
return (
|
||||
<View
|
||||
key={chunk.key}
|
||||
style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
|
||||
>
|
||||
{content}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</MarkdownImageRendererContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -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<SelectableMarkdownSkill>;
|
||||
readonly preserveSoftBreaks?: boolean;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly renderImage?: MarkdownImageRenderer;
|
||||
readonly marginTop?: number;
|
||||
readonly marginBottom?: number;
|
||||
}
|
||||
@@ -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 (
|
||||
<View className="my-1 max-w-full self-start rounded-lg border border-border px-2.5 py-1.5">
|
||||
<Text className="font-mono text-xs" style={{ color: props.color }}>
|
||||
Media unavailable: {props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingMedia(props: {
|
||||
readonly name: string;
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly color: ColorValue;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
className="my-2 h-40 w-full items-center justify-center gap-2 rounded-xl"
|
||||
style={{ backgroundColor: props.backgroundColor }}
|
||||
>
|
||||
<ActivityIndicator color={props.color} />
|
||||
<Text className="font-mono text-xs" numberOfLines={1} style={{ color: props.color }}>
|
||||
{props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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 `<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
|
||||
<style>
|
||||
html, body { background: #000; height: 100%; margin: 0; overflow: hidden; width: 100%; }
|
||||
video { height: 100%; object-fit: contain; width: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<video id="media" controls playsinline preload="metadata" aria-label="${name}" src="${url}"></video>
|
||||
<script>
|
||||
document.getElementById("media").addEventListener("error", function () {
|
||||
window.ReactNativeWebView.postMessage("media-error");
|
||||
}, { once: true });
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}, [props.name, props.url]);
|
||||
|
||||
return (
|
||||
<View className="my-2 w-full gap-1.5">
|
||||
<View
|
||||
className="w-full overflow-hidden rounded-xl"
|
||||
style={{ aspectRatio: 16 / 9, backgroundColor: props.backgroundColor }}
|
||||
>
|
||||
<WebView
|
||||
accessibilityLabel={`Video ${props.name}`}
|
||||
allowsFullscreenVideo
|
||||
allowsInlineMediaPlayback
|
||||
bounces={false}
|
||||
javaScriptEnabled
|
||||
mediaPlaybackRequiresUserAction
|
||||
onError={props.onError}
|
||||
onMessage={(event) => {
|
||||
if (event.nativeEvent.data === "media-error") {
|
||||
props.onError();
|
||||
}
|
||||
}}
|
||||
originWhitelist={["*"]}
|
||||
scrollEnabled={false}
|
||||
source={{ html }}
|
||||
style={{ flex: 1, backgroundColor: "#000000" }}
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-sans text-xs" numberOfLines={1} style={{ color: props.color }}>
|
||||
{props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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<string | null>(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 <MediaUnavailable name={props.name} color={props.color} />;
|
||||
}
|
||||
|
||||
if (props.isVideo) {
|
||||
return (
|
||||
<MarkdownVideo
|
||||
url={props.url}
|
||||
name={props.name}
|
||||
backgroundColor={props.backgroundColor}
|
||||
color={props.color}
|
||||
onError={() => setFailedUrl(props.url)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="my-2 w-full gap-1.5">
|
||||
<Pressable
|
||||
accessibilityLabel={`Expand image ${props.name}`}
|
||||
accessibilityRole="button"
|
||||
className="w-full overflow-hidden rounded-xl active:opacity-80"
|
||||
onPress={() => props.onPressImage(props.url)}
|
||||
style={{ aspectRatio, backgroundColor: props.backgroundColor }}
|
||||
>
|
||||
<Image
|
||||
accessibilityLabel={props.name}
|
||||
onError={() => 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%" }}
|
||||
/>
|
||||
</Pressable>
|
||||
<Text className="font-sans text-xs" numberOfLines={1} style={{ color: props.color }}>
|
||||
{props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<ResolvedMedia
|
||||
url={normalizeDirectUrl(source.url)}
|
||||
name={name}
|
||||
isVideo={isVideo}
|
||||
backgroundColor={props.backgroundColor}
|
||||
color={props.mutedColor}
|
||||
onPressImage={props.onPressImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (assetUrl._tag === "Failure") {
|
||||
return <MediaUnavailable name={name} color={props.mutedColor} />;
|
||||
}
|
||||
if (assetUrl._tag === "Loading") {
|
||||
return (
|
||||
<LoadingMedia name={name} backgroundColor={props.backgroundColor} color={props.mutedColor} />
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ResolvedMedia
|
||||
url={assetUrl.url}
|
||||
name={name}
|
||||
isVideo={isVideo}
|
||||
backgroundColor={props.backgroundColor}
|
||||
color={props.mutedColor}
|
||||
onPressImage={props.onPressImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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 }) => (
|
||||
<MarkdownMedia
|
||||
environmentId={environmentId}
|
||||
threadId={threadId}
|
||||
src={href}
|
||||
{...(alt ? { alt } : {})}
|
||||
{...(title ? { title } : {})}
|
||||
backgroundColor={backgroundColor}
|
||||
mutedColor={mutedColor}
|
||||
onPressImage={onPressImage}
|
||||
/>
|
||||
);
|
||||
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}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -1066,6 +1105,7 @@ function UserMessageContent(props: {
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
renderImage={props.markdownStyles.renderImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1107,6 +1147,7 @@ function UserMessageContent(props: {
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
renderImage={props.markdownStyles.renderImage}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -1346,6 +1387,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
uri: string;
|
||||
headers?: Record<string, string>;
|
||||
} | null>(null);
|
||||
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
|
||||
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<string, string>) => {
|
||||
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
|
||||
|
||||
@@ -8,6 +8,7 @@ import { highlightCodeSnippet } from "../features/review/shikiReviewHighlighter"
|
||||
type MobileSelectableMarkdownTextProps = Omit<SelectableMarkdownTextProps, "highlightCode">;
|
||||
|
||||
export type {
|
||||
MarkdownImageRenderer,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "@t3tools/mobile-markdown-text/types";
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { SelectableMarkdownTextProps } from "@t3tools/mobile-markdown-text/
|
||||
type MobileSelectableMarkdownTextProps = Omit<SelectableMarkdownTextProps, "highlightCode">;
|
||||
|
||||
export type {
|
||||
MarkdownImageRenderer,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "@t3tools/mobile-markdown-text/types";
|
||||
|
||||
@@ -12,18 +12,35 @@ const EMPTY_ASSET_URL_ATOM = Atom.make(AsyncResult.initial<never, never>(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;
|
||||
}
|
||||
@@ -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 (
|
||||
<span className="my-1 inline-flex max-w-full items-baseline gap-1 rounded-md border border-border/60 bg-muted/40 px-2 py-1 text-xs text-muted-foreground">
|
||||
@@ -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 <ResolvedMedia url={src} name={name} isVideo={isVideo} />;
|
||||
}
|
||||
if (!threadRef) {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
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 <ResourceMedia threadRef={threadRef} resource={resource} name={name} isVideo={isVideo} />;
|
||||
const source = resolveMarkdownMediaSource(src, threadRef.threadId);
|
||||
return source._tag === "Asset" ? (
|
||||
<ResourceMedia threadRef={threadRef} resource={source.resource} name={name} isVideo={isVideo} />
|
||||
) : (
|
||||
<ResolvedMedia url={source.url} name={name} isVideo={isVideo} />
|
||||
);
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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<string>): 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,
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user