TypeScript
fix(mobile): render workspace images in markdown file previews (#8769)
Dara Adedeji09b81a34954c
diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsxindex b7497debc52..c3118c1dfa7 100644--- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx+++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx@@ -1,3 +1,6 @@+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { resolveMediaSource } from "@t3tools/client-runtime/media-source";+import { getBrowseDirectoryPath } from "@t3tools/client-runtime/state/projects";import { useCallback, useMemo, useState } from "react";import {Markdown,@@ -14,12 +17,18 @@ import {resolveNativeMarkdownTypography,} from "../../lib/appearancePreferences";import { useUniwindTheme } from "../../lib/useUniwindTheme";+import {+ ThreadMarkdownImage,+ ThreadMarkdownImageUnavailable,+} from "../threads/ThreadMarkdownImage";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import {hasNativeSelectableMarkdownText,SelectableMarkdownText,+ type MarkdownImageRenderer,type NativeMarkdownTextStyle,} from "../../native/SelectableMarkdownText";+import { resolveWorkspaceFilePath } from "./filePath";interface MarkdownPreviewStyles {readonly theme: PartialMarkdownTheme;@@ -28,7 +37,7 @@ interface MarkdownPreviewStyles {readonly nativeTextStyle: NativeMarkdownTextStyle;}-function useMarkdownPreviewStyles(): MarkdownPreviewStyles {+function useMarkdownPreviewStyles(renderImage?: MarkdownImageRenderer): MarkdownPreviewStyles {const { appearance } = useAppearancePreferences();const markdownFontSizes = useMemo(() => resolveMarkdownFontSizes(appearance.baseFontSize),@@ -69,6 +78,14 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {{children}</NativeText>),+ image: ({ node }) =>+ node.href && renderImage+ ? (renderImage({+ href: node.href,+ alt: node.alt ?? null,+ title: node.title ?? null,+ }) ?? undefined)+ : undefined,};return {@@ -166,13 +183,18 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {mediumFontFamily,nativeMarkdownTypography,regularFontFamily,+ renderImage,strong,boldFontFamily,]);}export function FileMarkdownPreview(props: {+ readonly cwd: string;+ readonly environmentId: EnvironmentId;readonly markdown: string;+ readonly relativePath: string;+ readonly threadId: ThreadId;readonly onRefresh?: () => Promise<void> | void;}) {const [isPullRefreshing, setIsPullRefreshing] = useState(false);@@ -187,7 +209,36 @@ export function FileMarkdownPreview(props: {setIsPullRefreshing(false);}}, [props.onRefresh]);- const styles = useMarkdownPreviewStyles();+ const markdownDirectory = useMemo(+ () => getBrowseDirectoryPath(resolveWorkspaceFilePath(props.cwd, props.relativePath)),+ [props.cwd, props.relativePath],+ );+ const renderImage = useCallback<MarkdownImageRenderer>(+ (image) => {+ const media = resolveMediaSource(image.href, {+ threadId: props.threadId,+ workspaceRoot: markdownDirectory,+ imageEmbed: true,+ });+ if (media?.access === "direct") {+ return null;+ }+ if (media === null || media.kind !== "image" || media.access === "unavailable") {+ return <ThreadMarkdownImageUnavailable alt={image.alt} />;+ }+ return (+ <ThreadMarkdownImage+ environmentId={props.environmentId}+ resource={media.resource}+ alt={image.alt}+ srcFragment={media.srcFragment}+ onPressPreview={() => undefined}+ />+ );+ },+ [markdownDirectory, props.environmentId, props.threadId],+ );+ const styles = useMarkdownPreviewStyles(renderImage);const onLinkPress = useCallback((href: string) => {void tryOpenExternalUrl(href, "markdown-link");}, []);@@ -210,6 +261,7 @@ export function FileMarkdownPreview(props: {<SelectableMarkdownTextmarkdown={props.markdown}onLinkPress={onLinkPress}+ renderImage={renderImage}textStyle={styles.nativeTextStyle}/>) : (diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsxindex 91b832e68d1..2c3422673b0 100644--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx@@ -106,7 +106,8 @@ function defaultViewMode(path: string | null): FileViewMode {function FileContent(props: {readonly activeMode: FileViewMode;- readonly environmentId: EnvironmentId | null;+ readonly cwd: string;+ readonly environmentId: EnvironmentId;readonly previewUri: string | null;readonly previewFailure: AssetUrlFailureReason | null;readonly onRetryPreview: () => void;@@ -116,6 +117,7 @@ function FileContent(props: {readonly fileContents: string | null;readonly fileError: string | null;readonly relativePath: string;+ readonly threadId: ThreadId;readonly initialLine: number | null;readonly truncated: boolean;readonly onRefresh?: () => Promise<void> | void;@@ -199,7 +201,14 @@ function FileContent(props: {</View>) : null}{props.activeMode === "preview" && isMarkdown ? (- <FileMarkdownPreview markdown={props.fileContents} onRefresh={props.onRefresh} />+ <FileMarkdownPreview+ cwd={props.cwd}+ environmentId={props.environmentId}+ markdown={props.fileContents}+ relativePath={props.relativePath}+ threadId={props.threadId}+ onRefresh={props.onRefresh}+ />) : (<SourceFileSurfacecontents={props.fileContents}@@ -910,6 +919,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {<FileContentkey={previewKey}activeMode={resolvedActiveMode}+ cwd={cwd}environmentId={environmentId}previewUri={previewUri}previewFailure={assetPreview._tag === "Failure" ? assetPreview.reason : null}@@ -921,6 +931,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {fileError={fileQuery.error}initialLine={targetLine}relativePath={relativePath}+ threadId={threadId}truncated={fileData?.truncated ?? false}onRefresh={() => fileQuery.refresh()}/>diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex a25045c6011..ab48046fbd9 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -2,7 +2,6 @@ import * as Haptics from "expo-haptics";import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";import type {- AssetResource,ChatAttachment,ChatFileAttachment,ChatImageAttachment,@@ -68,7 +67,6 @@ import {type ColorValue,useWindowDimensions,View,- type ViewStyle,} from "react-native";import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";import { isPdfFile } from "../../lib/filePreview";@@ -102,8 +100,6 @@ import { VideoPreviewModal, type VideoPreviewSource } from "../../components/Vidimport { VideoAttachmentTile } from "../../components/VideoAttachmentTile";import { MediaVideoPlayer } from "../../components/MediaVideoPlayer";import { resolveMarkdownMediaPreview } from "../../lib/markdownMedia";-import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";-import { MediaActionsMenu } from "../../components/MediaActionsMenu";import {attachmentVideoPreviewSource,mediaVideoPreviewUri,@@ -178,8 +174,12 @@ import {isAbsolutePath,resolveWorkspaceRelativeFilePath,} from "../files/filePath";-import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";import { fileChipMenu, resolveFileChipTarget, type FileChipAction } from "./fileChipMenu";+import {+ ThreadMarkdownImage,+ ThreadMarkdownImageUnavailable,+ ThreadMarkdownImageView,+} from "./ThreadMarkdownImage";const WIDE_MARKDOWN_BLOCK_OPTIONS = {// Native iOS blockquotes and adjacent selectable text are separate layout@@ -505,171 +505,6 @@ function MessageAttachmentUnknown(props: { readonly name: string }) {);}-function ThreadMarkdownImageView(props: {- readonly uri: string | null;- readonly sourceKey: string;- readonly unavailable: boolean;- readonly alt: string | null;- readonly actionsSource?: MediaActionsSource;- readonly onPressPreview: (source: FilePreviewSource) => void;-}) {- const sourceIdentifier = useId();- const mediaActions = useMediaActions(props.actionsSource);- const [availableWidth, setAvailableWidth] = useState(0);- const [sourceSize, setSourceSize] = useState<{ width: number; height: number } | null>(null);- const [failedUri, setFailedUri] = useState<string | null>(null);-- useEffect(() => {- setSourceSize(null);- }, [props.sourceKey]);-- useEffect(() => {- setFailedUri(null);- }, [props.uri]);-- const displaySize =- sourceSize === null- ? null- : resolveMarkdownImageDisplaySize({- sourceWidth: sourceSize.width,- sourceHeight: sourceSize.height,- availableWidth,- });- const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);- const placeholderWidth: ViewStyle["width"] =- availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";- const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };-- return (- <View- onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}- style={{ alignSelf: "stretch", gap: 6 }}- >- {props.uri === null || failed ? (- <MediaActionsMenu media={mediaActions}>- <Pressable- accessibilityRole="imagebutton"- accessibilityLabel={props.alt ?? "Markdown image"}- accessibilityHint={- mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined- }- className="items-center justify-center rounded-[10px] bg-md-code-bg"- style={frameStyle}- >- {failed ? (- <Text className="text-xs text-foreground-muted">Image unavailable</Text>- ) : (- <ActivityIndicator />- )}- </Pressable>- </MediaActionsMenu>- ) : (- <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>- <MediaActionsMenu media={mediaActions}>- <Pressable- accessibilityRole="imagebutton"- accessibilityLabel={props.alt ?? "Markdown image"}- accessibilityHint={- mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined- }- onPress={() =>- // Quick Look picks the viewer from the name's extension, so it needs the- // file name rather than the alt text.- props.onPressPreview({- kind: "image",- uri: props.uri!,- name: props.actionsSource?.name ?? props.alt ?? "Image",- sourceIdentifier,- actionsSource: props.actionsSource,- })- }- style={{ alignSelf: "flex-start" }}- >- <View- className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"- style={{- ...frameStyle,- }}- >- <ThreadMarkdownImageRequest- key={props.uri}- uri={props.uri}- onLoad={setSourceSize}- onError={() => setFailedUri(props.uri)}- />- </View>- </Pressable>- </MediaActionsMenu>- </PresentationSource>- )}- {props.alt ? (- <Text selectable className="text-xs text-foreground-muted">- {props.alt}- </Text>- ) : null}- </View>- );-}--function ThreadMarkdownImageRequest(props: {- readonly uri: string;- readonly onLoad: (sourceSize: { width: number; height: number }) => void;- readonly onError: () => void;-}) {- const [loaded, setLoaded] = useState(false);-- return (- <>- <Image- source={{ uri: props.uri }}- resizeMode="contain"- accessible={false}- onLoad={(event) => {- setLoaded(true);- props.onLoad(event.nativeEvent.source);- }}- onError={props.onError}- style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}- />- {loaded ? null : (- <View- pointerEvents="none"- style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}- >- <Text className="text-xs text-foreground-muted">Loading image…</Text>- </View>- )}- </>- );-}--/** Environment-hosted image that loads through a signed asset URL. */-function ThreadMarkdownImage(props: {- readonly environmentId: EnvironmentId;- readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "media-file" }>;- readonly alt: string | null;- readonly srcFragment?: string;- readonly actionsSource?: MediaActionsSource;- readonly onPressPreview: (source: FilePreviewSource) => void;-}) {- const assetUrl = useAssetUrlState(props.environmentId, props.resource);-- return (- <ThreadMarkdownImageView- uri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}- sourceKey={- props.resource._tag === "attachment"- ? `attachment:${props.resource.attachmentId}`- : `workspace:${props.resource.path}`- }- unavailable={assetUrl._tag === "Failure"}- alt={props.alt}- actionsSource={props.actionsSource}- onPressPreview={props.onPressPreview}- />- );-}-const ThreadMediaVisibleContext = createContext(false);// LegendList only computes hook visibility when the list has a viewability config.const THREAD_MEDIA_VIEWABILITY_CONFIG = { itemVisiblePercentThreshold: 0 };@@ -713,18 +548,6 @@ function ThreadMarkdownVideo(props: { readonly source: MediaVideoPreviewSource });}-function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {- return (- <ThreadMarkdownImageView- uri={null}- sourceKey="unavailable"- unavailable- alt={props.alt}- onPressPreview={() => undefined}- />- );-}-const MARKDOWN_MONO_FONT = Platform.select({ios: "ui-monospace",android: "monospace",diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsxnew file mode 100644index 00000000000..c506bf1875e--- /dev/null+++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx@@ -0,0 +1,193 @@+import type { AssetResource, EnvironmentId } from "@t3tools/contracts";+import { useEffect, useId, useState } from "react";+import {+ ActivityIndicator,+ Image,+ Pressable,+ StyleSheet,+ View,+ type ViewStyle,+} from "react-native";++import { AppText as Text } from "../../components/AppText";+import type { FilePreviewSource } from "../../components/FilePreviewModal";+import { MediaActionsMenu } from "../../components/MediaActionsMenu";+import { PresentationSource } from "../../components/NativePresentation";+import { useMediaActions, type MediaActionsSource } from "../../lib/mediaActions";+import { useAssetUrlState } from "../../state/assets";+import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";++export function ThreadMarkdownImageView(props: {+ readonly uri: string | null;+ readonly sourceKey: string;+ readonly unavailable: boolean;+ readonly alt: string | null;+ readonly actionsSource?: MediaActionsSource;+ readonly onPressPreview: (source: FilePreviewSource) => void;+}) {+ const sourceIdentifier = useId();+ const mediaActions = useMediaActions(props.actionsSource);+ const [availableWidth, setAvailableWidth] = useState(0);+ const [sourceSize, setSourceSize] = useState<{ width: number; height: number } | null>(null);+ const [failedUri, setFailedUri] = useState<string | null>(null);++ useEffect(() => {+ setSourceSize(null);+ }, [props.sourceKey]);++ useEffect(() => {+ setFailedUri(null);+ }, [props.uri]);++ const displaySize =+ sourceSize === null+ ? null+ : resolveMarkdownImageDisplaySize({+ sourceWidth: sourceSize.width,+ sourceHeight: sourceSize.height,+ availableWidth,+ });+ const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);+ const placeholderWidth: ViewStyle["width"] =+ availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";+ const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };++ return (+ <View+ onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}+ style={{ alignSelf: "stretch", gap: 6 }}+ >+ {props.uri === null || failed ? (+ <MediaActionsMenu media={mediaActions}>+ <Pressable+ accessibilityRole="imagebutton"+ accessibilityLabel={props.alt ?? "Markdown image"}+ accessibilityHint={+ mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined+ }+ className="items-center justify-center rounded-[10px] bg-md-code-bg"+ style={frameStyle}+ >+ {failed ? (+ <Text className="text-xs text-foreground-muted">Image unavailable</Text>+ ) : (+ <ActivityIndicator />+ )}+ </Pressable>+ </MediaActionsMenu>+ ) : (+ <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>+ <MediaActionsMenu media={mediaActions}>+ <Pressable+ accessibilityRole="imagebutton"+ accessibilityLabel={props.alt ?? "Markdown image"}+ accessibilityHint={+ mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined+ }+ onPress={() =>+ props.onPressPreview({+ kind: "image",+ uri: props.uri!,+ name: props.actionsSource?.name ?? props.alt ?? "Image",+ sourceIdentifier,+ actionsSource: props.actionsSource,+ })+ }+ style={{ alignSelf: "flex-start" }}+ >+ <View+ className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"+ style={{+ ...frameStyle,+ }}+ >+ <ThreadMarkdownImageRequest+ key={props.uri}+ uri={props.uri}+ onLoad={setSourceSize}+ onError={() => setFailedUri(props.uri)}+ />+ </View>+ </Pressable>+ </MediaActionsMenu>+ </PresentationSource>+ )}+ {props.alt ? (+ <Text selectable className="text-xs text-foreground-muted">+ {props.alt}+ </Text>+ ) : null}+ </View>+ );+}++function ThreadMarkdownImageRequest(props: {+ readonly uri: string;+ readonly onLoad: (sourceSize: { width: number; height: number }) => void;+ readonly onError: () => void;+}) {+ const [loaded, setLoaded] = useState(false);++ return (+ <>+ <Image+ source={{ uri: props.uri }}+ resizeMode="contain"+ accessible={false}+ onLoad={(event) => {+ setLoaded(true);+ props.onLoad(event.nativeEvent.source);+ }}+ onError={props.onError}+ style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}+ />+ {loaded ? null : (+ <View+ pointerEvents="none"+ style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}+ >+ <Text className="text-xs text-foreground-muted">Loading image…</Text>+ </View>+ )}+ </>+ );+}++/** Environment-hosted image that loads through a signed asset URL. */+export function ThreadMarkdownImage(props: {+ readonly environmentId: EnvironmentId;+ readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "media-file" }>;+ readonly alt: string | null;+ readonly srcFragment?: string;+ readonly actionsSource?: MediaActionsSource;+ readonly onPressPreview: (source: FilePreviewSource) => void;+}) {+ const assetUrl = useAssetUrlState(props.environmentId, props.resource);++ return (+ <ThreadMarkdownImageView+ uri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}+ sourceKey={+ props.resource._tag === "attachment"+ ? `attachment:${props.resource.attachmentId}`+ : `workspace:${props.resource.path}`+ }+ unavailable={assetUrl._tag === "Failure"}+ alt={props.alt}+ actionsSource={props.actionsSource}+ onPressPreview={props.onPressPreview}+ />+ );+}++export function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {+ return (+ <ThreadMarkdownImageView+ uri={null}+ sourceKey="unavailable"+ unavailable+ alt={props.alt}+ onPressPreview={() => undefined}+ />+ );+}