diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift index c8ec3886974a9..0571d2c604f1c 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -134,6 +134,10 @@ public final class T3NativeControlsModule: Module { view.sources = self.presentationSources view.identifier = identifier } + Prop("fallbackIdentifier") { (view: T3PresentationSourceView, identifier: String?) in + view.sources = self.presentationSources + view.fallbackIdentifier = identifier ?? "" + } } View(T3FrostedCutoutView.self) { diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift index 382e92875f303..259d68c43531d 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift @@ -126,8 +126,10 @@ final class T3NativeImageViewer: NSObject { private func decode(_ index: Int) { guard !finished, let file = file(at: index), !decoded.contains(index), decodes[index] == nil else { return } - let source = sourceView(index) - let previous = decodeQueue + // ImageIO reads SVG poorly or not at all; the thumbnail is vector, so redraw it at full-screen size + // without blocking the serial raster decode queue while waiting for reveal. + let isSVG = file.pathExtension.lowercased() == "svg" + let previous = isSVG ? nil : decodeQueue let task = Task { @MainActor [self] in await previous?.value var settled = false @@ -137,8 +139,6 @@ final class T3NativeImageViewer: NSObject { if !settled, !finished, isNearCurrent(index), !decoded.contains(index) { decode(index) } } guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } - // ImageIO reads SVG poorly or not at all; the thumbnail is vector, so redraw it at full-screen size. - let isSVG = file.pathExtension.lowercased() == "svg" let image = isSVG ? nil : await Task.detached(priority: .userInitiated) { Self.decode(file) }.value guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } if isSVG { @@ -147,7 +147,7 @@ final class T3NativeImageViewer: NSObject { guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } } settled = true - if let image = image ?? (isSVG ? source.flatMap(Self.render(_:)) : nil) { + if let image = image ?? (isSVG ? sourceView(index).flatMap(Self.render(_:)) : nil) { decoded.insert(index) controller?.setImage(image, at: index, full: true) } else { @@ -161,7 +161,7 @@ final class T3NativeImageViewer: NSObject { } } decodes[index] = task - decodeQueue = task + if !isSVG { decodeQueue = task } } private func finish() { @@ -184,9 +184,8 @@ final class T3NativeImageViewer: NSObject { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) } - /// The decoded image a thumbnail already shows, uncropped, or a snapshot of a view that draws one. - /// The largest image view wins, so an overlaid icon is never mistaken for the picture. - private static func thumbnail(of view: UIView) -> UIImage? { + /// The largest decoded image already shown in `view`, uncropped at its native aspect ratio. + private static func decodedImage(in view: UIView) -> UIImage? { var queue = [view] var best: (image: UIImage, area: CGFloat)? while let candidate = queue.popLast() { @@ -196,10 +195,19 @@ final class T3NativeImageViewer: NSObject { if area > best?.area ?? 0 { best = (image, area) } } if let best, best.area >= view.bounds.width * view.bounds.height / 2 { return best.image } + return nil + } + + /// The decoded image a thumbnail already shows, uncropped, or a snapshot of a view that draws one. + /// The largest image view wins, so an overlaid icon is never mistaken for the picture. + private static func thumbnail(of view: UIView) -> UIImage? { + if let image = decodedImage(in: view) { return image } return snapshot(view, scale: view.window?.screen.scale ?? 2) } private static func render(_ view: UIView) -> UIImage? { + // Strip cards decode SVGs into an image view inside a fixed landscape box; keep the image's own aspect ratio. + if let image = decodedImage(in: view) { return image } let screen = view.window?.screen.bounds.size ?? CGSize(width: 1024, height: 1024) let fit = min(screen.width / max(view.bounds.width, 1), screen.height / max(view.bounds.height, 1)) // The thumbnail was shown again after the open transition, in a frame not yet on screen. @@ -211,9 +219,11 @@ final class T3NativeImageViewer: NSObject { let format = UIGraphicsImageRendererFormat() format.scale = scale format.opaque = false - return UIGraphicsImageRenderer(bounds: view.bounds, format: format).image { _ in - view.drawHierarchy(in: view.bounds, afterScreenUpdates: afterScreenUpdates) + var drew = false + let image = UIGraphicsImageRenderer(bounds: view.bounds, format: format).image { _ in + drew = view.drawHierarchy(in: view.bounds, afterScreenUpdates: afterScreenUpdates) } + return drew ? image : nil } /// Decodes off the main thread at no more than zooming needs, and keeps GIFs animated. @@ -644,9 +654,9 @@ final class T3ImageViewerController: UIViewController, UIScrollViewDelegate, UIG private var reduceMotion: Bool { UIAccessibility.isReduceMotionEnabled } private func visibleSource(_ index: Int) -> UIView? { - guard !reduceMotion, let source = sourceView(index), source.window === view.window, !source.isHidden else { return nil } - let frame = source.convert(source.bounds, to: view) - guard frame.width > 1, frame.height > 1, view.bounds.intersects(frame) else { return nil } + guard !reduceMotion, let source = sourceView(index), source.window === view.window, + isVisiblePresentationTarget(source, in: view) + else { return nil } return source } diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift index 3b43334b1262d..8d62177f18992 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift @@ -1,6 +1,34 @@ import ExpoModulesCore import UIKit +/// Visible portion of `view` inside `container`, clipped by every `clipsToBounds` ancestor. +func clippedVisibleRect(of view: UIView, in container: UIView) -> CGRect { + guard let window = view.window, !view.isHidden, view.alpha > 0.01 else { return .null } + var rect = view.bounds + guard !rect.isEmpty else { return .null } + var current: UIView = view + while let parent = current.superview { + if parent.isHidden || parent.alpha <= 0.01 { return .null } + rect = current.convert(rect, to: parent) + if parent.clipsToBounds { + rect = rect.intersection(parent.bounds) + if rect.isNull || rect.isEmpty { return .null } + } + current = parent + if parent === window { break } + } + let inContainer = current.convert(rect, to: container) + return inContainer.intersection(container.bounds) +} + +/// Whether enough of `view` is visible inside `container` to serve as a zoom transition target. +func isVisiblePresentationTarget(_ view: UIView, in container: UIView) -> Bool { + let fullArea = view.bounds.width * view.bounds.height + guard fullArea > 1 else { return false } + let visible = clippedVisibleRect(of: view, in: container) + return visible.width > 1 && visible.height > 1 && visible.width * visible.height >= fullArea * 0.25 +} + final class T3PresentationSources { private class Entry { weak var view: UIView? @@ -23,11 +51,12 @@ final class T3PresentationSources { func view(for identifier: String) -> UIView? { let views = (entries[identifier] ?? []).compactMap(\.view) - // Prefer an on-screen copy, the latest first; use the child bounds, not the wrapper's stretched ones. + // Prefer a visible copy, the latest first; use the child bounds, not the wrapper's stretched ones. let source = views.last(where: { view in - guard let window = view.window else { return false } - return window.bounds.intersects(view.convert(view.bounds, to: window)) - }) ?? views.last + guard let window = view.window, let target = view.subviews.first else { return false } + return isVisiblePresentationTarget(target, in: window) + }) ?? views.last(where: { $0.window != nil && !$0.subviews.isEmpty }) + ?? views.last(where: { !$0.subviews.isEmpty }) return source?.subviews.first } } @@ -35,14 +64,23 @@ final class T3PresentationSources { final class T3PresentationSourceView: ExpoView { weak var sources: T3PresentationSources? var identifier = "" { - didSet { - sources?.remove(self, identifier: oldValue) - if !identifier.isEmpty { sources?.register(self, identifier: identifier) } + didSet { updateRegistration(old: oldValue, new: identifier) } + } + var fallbackIdentifier = "" { + didSet { updateRegistration(old: oldValue, new: fallbackIdentifier) } + } + + private func updateRegistration(old: String, new: String) { + guard old != new else { return } + if !old.isEmpty, old != identifier, old != fallbackIdentifier { + sources?.remove(self, identifier: old) } + if !new.isEmpty { sources?.register(self, identifier: new) } } deinit { - sources?.remove(self, identifier: identifier) + if !identifier.isEmpty { sources?.remove(self, identifier: identifier) } + if !fallbackIdentifier.isEmpty { sources?.remove(self, identifier: fallbackIdentifier) } } } diff --git a/apps/mobile/src/components/ui/NativePresentation.android.tsx b/apps/mobile/src/components/ui/NativePresentation.android.tsx index e342c6decc77a..8194c59e8dfd3 100644 --- a/apps/mobile/src/components/ui/NativePresentation.android.tsx +++ b/apps/mobile/src/components/ui/NativePresentation.android.tsx @@ -2,6 +2,10 @@ import { View } from "react-native"; import type { PresentationSourceProps } from "./NativePresentation"; -export function PresentationSource({ identifier: _identifier, ...props }: PresentationSourceProps) { +export function PresentationSource({ + identifier: _identifier, + fallbackIdentifier: _fallbackIdentifier, + ...props +}: PresentationSourceProps) { return ; } diff --git a/apps/mobile/src/components/ui/NativePresentation.tsx b/apps/mobile/src/components/ui/NativePresentation.tsx index 61ff2b2b226af..e05d1091fd1c2 100644 --- a/apps/mobile/src/components/ui/NativePresentation.tsx +++ b/apps/mobile/src/components/ui/NativePresentation.tsx @@ -5,6 +5,7 @@ import type { ViewProps } from "react-native"; export interface PresentationSourceProps extends ViewProps { readonly children: ReactElement; readonly identifier: string; + readonly fallbackIdentifier?: string; } const NativeSource: ComponentType = requireNativeView( diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx index f0604d6b4ceb6..abd35f0037d88 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx @@ -6,10 +6,14 @@ import { } from "./PullRequestMedia"; import { PullRequestSectionHeading } from "./PullRequestSectionHeading"; import { T, useGT, useMessages } from "gt-react-native"; -import { useContext, useMemo, useState, type ComponentProps, type ReactNode } from "react"; +import { useContext, useId, useMemo, useState, type ComponentProps, type ReactNode } from "react"; import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; -import { pullRequestImageSource } from "./pullRequestMediaSource"; +import { + pullRequestImageSource, + pullRequestScopedSourceIdentifier, +} from "./pullRequestMediaSource"; +import { filePreviewKey, imagePreviewName } from "../../lib/filePreviewGallery"; import { markdownReferenceDefinitions, parseMarkdownDocument } from "../../lib/markdownDocument"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; @@ -35,7 +39,9 @@ export function PullRequestDescription(props: { const { collapse } = props; const expanded = collapse?.expanded ?? true; const gt = useGT(); + const imageFallback = gt("Image"); const messages = useMessages(); + const stripScope = `pr-attachment:${useId()}`; const [bodyHeight, setBodyHeight] = useState(0); const mediaContext = useContext(PullRequestMediaContext); const { themeVariables: colors } = useAppearancePreferences(); @@ -52,14 +58,30 @@ export function PullRequestDescription(props: { attachments: content.attachments.filter((attachment) => !isBotBadgeImage(attachment.uri)), }; }, [props.markdown, messages]); - const gallery: FilePreviewItem[] = content.attachments - .filter((attachment) => attachment.kind === "image") - .map((attachment) => { - return { - ...pullRequestImageSource(attachment.uri, mediaContext), - name: new URL(attachment.uri).pathname.split("/").pop() || gt("Image"), + const { gallery, galleryByUri } = useMemo(() => { + const byUri = new Map(); + const byKey = new Map(); + const items: FilePreviewItem[] = []; + for (const attachment of content.attachments) { + if (attachment.kind !== "image") continue; + const name = imagePreviewName(attachment.uri, attachment.caption, imageFallback); + const source = pullRequestImageSource(attachment.uri, mediaContext, name); + const key = filePreviewKey(source); + const existing = byKey.get(key); + if (existing) { + byUri.set(attachment.uri, existing); + continue; + } + const item: FilePreviewItem = { + ...source, + sourceIdentifier: pullRequestScopedSourceIdentifier(stripScope, source), }; - }); + items.push(item); + byKey.set(key, item); + byUri.set(attachment.uri, item); + } + return { gallery: items, galleryByUri: byUri }; + }, [content.attachments, mediaContext, imageFallback, stripScope]); const canCollapse = collapse !== undefined && bodyHeight > COLLAPSED_HEIGHT; const collapsed = canCollapse && !expanded; return ( @@ -183,13 +205,7 @@ export function PullRequestDescription(props: { key={attachment.uri} url={attachment.uri} caption={attachment.caption} - source={ - gallery[ - content.attachments - .filter((item) => item.kind === "image") - .indexOf(attachment) - ]! - } + source={galleryByUri.get(attachment.uri)!} gallery={gallery} /> ), diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx index c1852a6ee2601..581c08f095f08 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx @@ -3,17 +3,18 @@ import { type PullRequestBodySegment, } from "@t3tools/client-runtime/pull-request-markdown"; import { markdownTaskMarkerOffset } from "@t3tools/shared/markdownTaskList"; +import { useGT } from "gt-react-native"; import type { ReactNode } from "react"; import { View } from "react-native"; import { useProject } from "../../state/entities"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { + PullRequestGalleryScopeContext, PullRequestMedia, PullRequestMediaContext, usePullRequestMediaUrl, } from "./PullRequestMedia"; -import { videoMimeType } from "@t3tools/shared/video"; -import { createContext, useContext, useMemo, useState } from "react"; +import { createContext, useContext, useId, useMemo, useState } from "react"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, @@ -27,15 +28,28 @@ import { nativePullRequestMarkdown } from "./pullRequestAutolinks"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; -import { markdownImageSources } from "../../lib/markdownImageSources"; import { markdownReferenceDefinitions } from "../../lib/markdownDocument"; import { FilePreviewGallery, useFilePreviewGallery } from "../../components/ui/FilePreviewGallery"; -import { pullRequestImageSource } from "./pullRequestMediaSource"; +import { + filePreviewKey, + filePreviewSourceIdentifier, + imagePreviewName, +} from "../../lib/filePreviewGallery"; +import { + isPullRequestVideoUrl, + isPullRequestWebUrl, + pullRequestImageSource, + pullRequestMarkdownImages, + pullRequestMediaSource, + pullRequestScopedSourceIdentifier, + pullRequestVideoMimeType, +} from "./pullRequestMediaSource"; import { FilePreviewModal, type FilePreviewSource, type FilePreviewItem, } from "../../components/ui/FilePreviewModal"; +import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal"; import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage"; import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText"; import type { SelectableMarkdownTextProps } from "../../native/SelectableMarkdownText.types"; @@ -85,23 +99,33 @@ export function PullRequestMarkdownRepository(props: { function MarkdownImage(props: { readonly href: string; readonly alt: string | null; + readonly title: string | null; readonly onPreview: (source: FilePreviewSource) => void; }) { + const gt = useGT(); const media = usePullRequestMediaUrl(props.href); const context = useContext(PullRequestMediaContext); + const galleryScope = useContext(PullRequestGalleryScopeContext); const withGallery = useFilePreviewGallery(); + const label = props.alt?.trim() || props.title?.trim() || null; + const name = imagePreviewName(props.href, label, gt("Image")); + const previewSource = pullRequestImageSource(props.href, context, name); + const sourceIdentifier = galleryScope + ? pullRequestScopedSourceIdentifier(galleryScope, previewSource) + : filePreviewSourceIdentifier(previewSource); return ( props.onPreview( withGallery({ - ...pullRequestImageSource(props.href, context), - name: source.name, + ...previewSource, sourceIdentifier: source.sourceIdentifier, }), ) @@ -123,42 +147,58 @@ export function PullRequestMarkdown(props: { readonly checked: boolean; }) => boolean; }) { + const gt = useGT(); + const imageFallback = gt("Image"); + const galleryScope = `pr-markdown:${useId()}`; const mediaContext = useContext(PullRequestMediaContext); const changeRequestUrl = useContext(ChangeRequestUrlContext); const segments = useMemo( () => splitPullRequestBody(props.markdown, markdownReferenceDefinitions), [props.markdown], ); + const groupSegments = useMemo( + () => + props.imageGroupMarkdown === undefined || props.imageGroupMarkdown === props.markdown + ? segments + : splitPullRequestBody(props.imageGroupMarkdown, markdownReferenceDefinitions), + [props.imageGroupMarkdown, props.markdown, segments], + ); const [undoneTicks, setUndoneTicks] = useState(0); - const gallery: FilePreviewItem[] = markdownImageSources( - props.imageGroupMarkdown ?? props.markdown, - ) - .map((href) => (changeRequestUrl ? resolveChangeRequestMediaUrl(href, changeRequestUrl) : href)) - .filter( - (uri) => - /^https?:\/\//i.test(uri) && - videoMimeType({ name: uri.split(/[?#]/)[0] ?? uri, mimeType: "" }) === null, - ) - .map((uri) => pullRequestImageSource(uri, mediaContext)); + const gallery = useMemo( + () => + pullRequestMarkdownImages(groupSegments, (href) => + changeRequestUrl ? resolveChangeRequestMediaUrl(href, changeRequestUrl) : href, + ).map(({ uri, alt }) => { + const name = imagePreviewName(uri, alt, imageFallback); + const source = pullRequestImageSource(uri, mediaContext, name); + return { + ...source, + sourceIdentifier: pullRequestScopedSourceIdentifier(galleryScope, source), + }; + }), + [groupSegments, changeRequestUrl, mediaContext, imageFallback, galleryScope], + ); const segmentProps = { - gallery, lineBreaks: props.lineBreaks, undoneTicks, onTaskListChange: props.onTaskListChange, onTaskListUndone: () => setUndoneTicks((count) => count + 1), }; return ( - - {segments.map((segment) => ( - - ))} - + + + + {segments.map((segment) => ( + + ))} + + + ); } function PullRequestBodySegmentView(props: { readonly segment: PullRequestBodySegment; - readonly gallery: FilePreviewItem[]; readonly lineBreaks: boolean | undefined; readonly undoneTicks: number; readonly onTaskListChange: @@ -175,7 +215,6 @@ function PullRequestBodySegmentView(props: { (null); - const renderImage: MarkdownImageRenderer = (image) => ( - - ); + const [video, setVideo] = useState(null); + const renderImage: MarkdownImageRenderer = (image) => { + const resolvedHref = resolveMediaUrl(image.href); + if (isPullRequestWebUrl(resolvedHref) && isPullRequestVideoUrl(resolvedHref)) { + return ( + + ); + } + return ( + + ); + }; const styles = useMarkdownPreviewStyles(); return ( - + <> - setPreview(pullRequestImageSource(resolveMediaUrl(href), mediaContext)) - } + onImagePress={(href) => { + const uri = resolveMediaUrl(href); + if (!isPullRequestWebUrl(uri)) return; + if (isPullRequestVideoUrl(uri)) { + setVideo({ + type: "media", + ...pullRequestMediaSource(uri, mediaContext), + name: uri.split(/[?#]/)[0]?.split("/").pop() || gt("Video"), + mimeType: pullRequestVideoMimeType(uri) ?? "video/mp4", + }); + return; + } + const source = pullRequestImageSource( + uri, + mediaContext, + imagePreviewName(uri, null, gt("Image")), + ); + const key = filePreviewKey(source); + const match = gallery.find((item) => filePreviewKey(item) === key); + setPreview({ ...(match ?? source), sourceIdentifier: "" }); + }} onTaskListItemPress={props.onTaskListItemPress} /> setPreview(null)} /> - + setVideo(null)} /> + ); } diff --git a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx index 6ca0b68e0bf3b..1cac9deacc8e6 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx @@ -1,20 +1,23 @@ import { useGT } from "gt-react-native"; -import { createContext, useContext, useState } from "react"; +import { createContext, useContext, useId, useState } from "react"; import { pullRequestMediaSource, pullRequestImageSource, + pullRequestScopedSourceIdentifier, + pullRequestVideoMimeType, type PullRequestMediaLocation, } from "./pullRequestMediaSource"; import { useFilePreviewGallery } from "../../components/ui/FilePreviewGallery"; -import { videoMimeType } from "@t3tools/shared/video"; import { Pressable, View } from "react-native"; import { Image } from "expo-image"; import { AppText } from "../../components/ui/AppText"; import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets"; import { assetImageCacheKey } from "../../lib/assetImageSource"; +import { filePreviewSourceIdentifier, imagePreviewName } from "../../lib/filePreviewGallery"; import { MediaVideoPlayer } from "../../components/MediaVideoPlayer"; import { VideoAttachmentTile } from "../../components/VideoAttachmentTile"; import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal"; +import { PresentationSource } from "../../components/ui/NativePresentation"; import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage"; import { FilePreviewModal, @@ -26,6 +29,8 @@ export const PullRequestMediaVisibleContext = createContext(true); export const PullRequestMediaContext = createContext(null); +export const PullRequestGalleryScopeContext = createContext(null); + export function usePullRequestMediaUrl(url: string) { const context = useContext(PullRequestMediaContext); const source = pullRequestMediaSource(url, context); @@ -51,24 +56,31 @@ export function PullRequestMedia(props: { const gt = useGT(); const visible = useContext(PullRequestMediaVisibleContext); const context = useContext(PullRequestMediaContext); + const galleryScope = useContext(PullRequestGalleryScopeContext); const withGallery = useFilePreviewGallery(); const [image, setImage] = useState(null); const [video, setVideo] = useState(null); - const name = props.caption || new URL(props.url).pathname.split("/").pop() || gt("Attachment"); - if (props.kind === "image") + const name = props.caption || props.url.split(/[?#]/)[0]?.split("/").pop() || gt("Attachment"); + if (props.kind === "image") { + const imageName = imagePreviewName(props.url, props.caption, gt("Image")); + const previewSource = pullRequestImageSource(props.url, context, imageName); + const sourceIdentifier = galleryScope + ? pullRequestScopedSourceIdentifier(galleryScope, previewSource) + : filePreviewSourceIdentifier(previewSource); return ( <> setImage( withGallery({ - ...pullRequestImageSource(props.url, context), - name, + ...previewSource, sourceIdentifier: source.sourceIdentifier, }), ) @@ -77,6 +89,7 @@ export function PullRequestMedia(props: { setImage(null)} /> ); + } return ( {props.compact ? ( @@ -90,9 +103,7 @@ export function PullRequestMedia(props: { type: "media", ...media.source, name, - mimeType: - videoMimeType({ name: props.url.split(/[?#]/)[0] ?? props.url, mimeType: "" }) ?? - "video/mp4", + mimeType: pullRequestVideoMimeType(props.url) ?? "video/mp4", }) } /> @@ -120,24 +131,41 @@ export function PullRequestImageAttachment(props: { }) { const media = usePullRequestMediaUrl(props.url); const gt = useGT(); + const localSourceIdentifier = useId(); const [preview, setPreview] = useState(null); + const imageKey = media.uri ? (media.cacheKey ?? media.uri) : null; + const [loadedKey, setLoadedKey] = useState(null); + const loaded = imageKey !== null && loadedKey === imageKey; return ( <> setPreview({ ...props.source, gallery: props.gallery })} + onPress={() => + setPreview({ + ...props.source, + sourceIdentifier: localSourceIdentifier, + gallery: props.gallery, + }) + } className="gap-2 active:opacity-70" style={{ width: 176 }} > - - - + + + setLoadedKey(imageKey)} + onError={() => setLoadedKey(null)} + /> + + {props.caption} diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts index 74e21d39018ee..397124d5b915f 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; -import { markdownReferenceDefinitions, type MarkdownNode } from "../../lib/markdownDocument"; +import { + markdownReferenceDefinitions, + parseMarkdownDocument, + type MarkdownNode, +} from "../../lib/markdownDocument"; import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown"; import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent"; @@ -40,4 +44,66 @@ describe("PR attachments", () => { { uri: "https://drop.example.com/after.mp4", caption: "Video", kind: "video" }, ]); }); + + it("classifies markdown-embedded video URLs as videos instead of images", () => { + const document = { + type: "root", + children: [ + { type: "image", url: "https://drop.example.com/shot.png", alt: "Screenshot" }, + { + type: "image", + url: "https://drop.example.com/recording.mp4?download=1", + alt: "Recording, 36s", + }, + { type: "image", url: "https://drop.example.com/clip.webm" }, + ], + } as MarkdownNode; + expect(pullRequestDescriptionContent(document).attachments).toEqual([ + { uri: "https://drop.example.com/shot.png", caption: "Screenshot", kind: "image" }, + { + uri: "https://drop.example.com/recording.mp4?download=1", + caption: "Recording, 36s", + kind: "video", + }, + { uri: "https://drop.example.com/clip.webm", caption: "Video", kind: "video" }, + ]); + }); + + it("collects reference-style markdown images with their definitions", () => { + const document = { + type: "root", + children: [ + { type: "imageReference", identifier: "before", alt: "Before" }, + { type: "imageReference", identifier: "after", alt: "" }, + { type: "definition", identifier: "before", url: "https://drop.example.com/before.png" }, + { + type: "definition", + identifier: "after", + url: "https://drop.example.com/after.png", + title: "After", + }, + ], + } as MarkdownNode; + expect(pullRequestDescriptionContent(document).attachments).toEqual([ + { uri: "https://drop.example.com/before.png", caption: "Before", kind: "image" }, + { uri: "https://drop.example.com/after.png", caption: "After", kind: "image" }, + ]); + }); + + it("preserves document order across bare attachments and inline markdown images", () => { + const markdown = [ + "https://drop.example.com/before.png", + "", + "![Diagram](https://drop.example.com/diagram.svg)", + "", + "https://drop.example.com/after.png", + ].join("\n"); + const document = parseMarkdownDocument(markdown); + const media = splitPullRequestBody(markdown, markdownReferenceDefinitions); + expect(pullRequestDescriptionContent(document, media).attachments).toEqual([ + { uri: "https://drop.example.com/before.png", caption: "before.png", kind: "image" }, + { uri: "https://drop.example.com/diagram.svg", caption: "Diagram", kind: "image" }, + { uri: "https://drop.example.com/after.png", caption: "after.png", kind: "image" }, + ]); + }); }); diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts index 61836c1a97a96..1018d7d8afe1d 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.ts @@ -1,15 +1,15 @@ import type { PullRequestBodySegment } from "@t3tools/client-runtime/pull-request-markdown"; import { msg } from "gt-react-native"; -import type { MarkdownNode } from "../../lib/markdownDocument"; +import { parseMarkdownDocument, type MarkdownNode } from "../../lib/markdownDocument"; import { m, type MessageResolver } from "../../i18n/messages"; +import { imagePreviewName } from "../../lib/filePreviewGallery"; +import { markdownDocumentImages } from "../../lib/markdownImageSources"; +import { isPullRequestVideoUrl, isPullRequestWebUrl } from "./pullRequestMediaSource"; -function isWebUrl(url: string): boolean { - try { - const parsed = new URL(url); - return parsed.protocol === "https:" || parsed.protocol === "http:"; - } catch { - return false; - } +interface PullRequestAttachment { + readonly uri: string; + readonly caption: string; + readonly kind: "image" | "video" | "unknown"; } export function pullRequestDescriptionContent( @@ -17,43 +17,63 @@ export function pullRequestDescriptionContent( media: readonly PullRequestBodySegment[] = [], resolve: MessageResolver = m, ) { - const attachments = new Map< - string, - { readonly uri: string; readonly caption: string; readonly kind: "image" | "video" | "unknown" } - >(); + const recordImages = (target: Map, root: MarkdownNode) => { + for (const { url, alt, title } of markdownDocumentImages(root, document)) { + if (!url || !isPullRequestWebUrl(url) || target.has(url)) continue; + const isVideo = isPullRequestVideoUrl(url); + target.set(url, { + uri: url, + caption: alt || title || resolve(isVideo ? msg("Video") : msg("Image")), + kind: isVideo ? "video" : "image", + }); + } + }; + const documentImages = new Map(); const text: string[] = []; + recordImages(documentImages, document); const visit = (node: MarkdownNode) => { - if (node.type === "image") { - if (node.url && isWebUrl(node.url) && !attachments.has(node.url)) { - attachments.set(node.url, { - uri: node.url, - caption: node.alt || node.title || resolve(msg("Image")), - kind: "image", - }); - } - return; - } - if (node.type === "html") return; + if (node.type === "image" || node.type === "imageReference" || node.type === "html") return; if ("value" in node) text.push(node.value); if ("children" in node) node.children.forEach(visit); if (["paragraph", "heading", "listItem", "code"].includes(node.type)) text.push("\n"); if (node.type === "break") text.push(" "); }; visit(document); + + if (media.length === 0) { + return { preview: text.join("").trim(), attachments: [...documentImages.values()] }; + } + + const attachments = new Map(); const collect = (segment: PullRequestBodySegment) => { if (segment.kind === "table") { segment.rows.flat().forEach((cell) => cell.segments.forEach(collect)); return; } + if (segment.kind === "markdown") { + if (segment.text.includes("![") || /]/i.test(segment.text)) { + recordImages(attachments, parseMarkdownDocument(segment.text)); + } + return; + } if (segment.kind === "attachment" && !attachments.has(segment.url)) { - const name = new URL(segment.url).pathname.split("/").pop(); - attachments.set(segment.url, { - uri: segment.url, - caption: segment.media === "video" ? resolve(msg("Video")) : name || resolve(msg("Image")), - kind: segment.media, - }); + const fromDocument = documentImages.get(segment.url); + attachments.set( + segment.url, + fromDocument ?? { + uri: segment.url, + caption: + segment.media === "video" + ? resolve(msg("Video")) + : imagePreviewName(segment.url, null, resolve(msg("Image"))), + kind: segment.media, + }, + ); } }; media.forEach(collect); + for (const [uri, item] of documentImages) { + if (!attachments.has(uri)) attachments.set(uri, item); + } return { preview: text.join("").trim(), attachments: [...attachments.values()] }; } diff --git a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts index 52ee08d3a6091..7def2e1984c19 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId } from "@t3tools/contracts"; +import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown"; import { filePreviewGallery } from "../../lib/filePreviewGallery"; -import { pullRequestImageSource } from "./pullRequestMediaSource"; +import { markdownReferenceDefinitions } from "../../lib/markdownDocument"; +import { pullRequestImageSource, pullRequestMarkdownImages } from "./pullRequestMediaSource"; const location = { environmentId: EnvironmentId.make("test"), @@ -22,4 +24,64 @@ describe("PR media previews", () => { { resource: { url: `${url}-second`, repository: location.repository } }, ]); }); + + it("populates mimeType and actionsSource for PR images", () => { + expect( + pullRequestImageSource("https://drop.example.com/shot.png?sig=1", null, "Before"), + ).toEqual({ + kind: "image", + uri: "https://drop.example.com/shot.png?sig=1", + name: "Before", + mimeType: "image/png", + actionsSource: { + uri: "https://drop.example.com/shot.png?sig=1", + name: "Before", + mimeType: "image/png", + }, + }); + expect( + pullRequestImageSource("https://drop.example.com/diagram.svg", location, "Diagram"), + ).toMatchObject({ + mimeType: "image/svg+xml", + actionsSource: { + name: "Diagram", + mimeType: "image/svg+xml", + }, + }); + expect( + pullRequestImageSource("file:///etc/hosts", null, "Hosts").actionsSource, + ).toBeUndefined(); + }); + + it("collects markdown images and bare image attachments in document order while skipping videos and non-HTTP URLs", () => { + const body = [ + "![Before](https://github.com/user-attachments/assets/111)", + "", + "https://drop.example.com/middle.png", + "", + "![Middle caption](https://drop.example.com/middle.png)", + "", + "![Relative](/api/attachments/shot.png)", + "", + "![Local](screenshots/local.png)", + "", + "
\n\nhttps://drop.example.com/table.png\n\n\n\nhttps://drop.example.com/demo.mp4\n\n
", + "", + "![Recording](https://drop.example.com/clip.mp4)", + "", + `After`, + ].join("\n"); + const segments = splitPullRequestBody(body, markdownReferenceDefinitions); + expect( + pullRequestMarkdownImages(segments, (href) => + href.startsWith("/") ? `https://forge.example.com${href}` : href, + ), + ).toEqual([ + { uri: "https://github.com/user-attachments/assets/111", alt: "Before" }, + { uri: "https://drop.example.com/middle.png", alt: "Middle caption" }, + { uri: "https://forge.example.com/api/attachments/shot.png", alt: "Relative" }, + { uri: "https://drop.example.com/table.png", alt: null }, + { uri: url, alt: "After" }, + ]); + }); }); diff --git a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts index dfcf8ad8a39a0..c4422373186e0 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts @@ -1,6 +1,28 @@ +import type { PullRequestBodySegment } from "@t3tools/client-runtime/pull-request-markdown"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { SOURCE_CONTROL_MEDIA_ASSET, type EnvironmentId } from "@t3tools/contracts"; +import { mediaMimeTypeFromExtension } from "@t3tools/shared/mediaPreview"; +import { videoMimeType } from "@t3tools/shared/video"; import type { FilePreviewItem } from "../../components/ui/FilePreviewModal.types"; +import { filePreviewKey, imagePreviewName } from "../../lib/filePreviewGallery"; +import { markdownImages } from "../../lib/markdownImageSources"; + +export function isPullRequestWebUrl(url: string): boolean { + try { + const parsed = new URL(url); + return parsed.protocol === "https:" || parsed.protocol === "http:"; + } catch { + return false; + } +} + +export function pullRequestVideoMimeType(url: string): string | null { + return videoMimeType({ name: url.split(/[?#]/)[0] ?? url, mimeType: "" }); +} + +export function isPullRequestVideoUrl(url: string): boolean { + return pullRequestVideoMimeType(url) !== null; +} export interface PullRequestMediaLocation { readonly environmentId: EnvironmentId; @@ -24,9 +46,66 @@ export function pullRequestMediaSource(url: string, location: PullRequestMediaLo : { uri: url }; } +export function pullRequestImageMimeType(url: string): string { + const path = url.split(/[?#]/)[0] ?? url; + const basename = path.split("/").pop() ?? ""; + const dot = basename.lastIndexOf("."); + const mime = dot > 0 ? mediaMimeTypeFromExtension(basename.slice(dot)) : null; + return mime?.startsWith("image/") ? mime : "image/*"; +} + export function pullRequestImageSource( url: string, location: PullRequestMediaLocation | null, + name?: string, ): FilePreviewItem { - return { kind: "image", ...pullRequestMediaSource(url, location) }; + const media = pullRequestMediaSource(url, location); + const mimeType = pullRequestImageMimeType(url); + const resolvedName = name ?? imagePreviewName(url, null, "Image"); + return { + kind: "image", + ...media, + ...(name !== undefined ? { name } : {}), + mimeType, + ...(isPullRequestWebUrl(url) + ? { actionsSource: { ...media, name: resolvedName, mimeType } } + : {}), + }; +} + +/** Scopes zoom targets per gallery surface so strips, descriptions, and comments never collide. */ +export function pullRequestScopedSourceIdentifier(scope: string, source: FilePreviewItem): string { + return `${scope}:${filePreviewKey(source)}`; +} + +export function pullRequestMarkdownImages( + segments: readonly PullRequestBodySegment[], + resolveUrl: (href: string) => string = (href) => href, +): { readonly uri: string; readonly alt: string | null }[] { + const images = new Map(); + const add = (href: string, alt: string | null) => { + const uri = resolveUrl(href); + if (!isPullRequestWebUrl(uri) || isPullRequestVideoUrl(uri)) return; + const existing = images.get(uri); + if (existing === undefined || (existing === null && alt !== null)) { + images.set(uri, alt); + } + }; + const visit = (segment: PullRequestBodySegment) => { + if (segment.kind === "markdown") { + for (const image of markdownImages(segment.text)) add(image.url, image.alt); + return; + } + if (segment.kind === "attachment") { + if (segment.media === "image") add(segment.url, null); + return; + } + for (const row of segment.rows) { + for (const cell of row) { + for (const inner of cell.segments) visit(inner); + } + } + }; + for (const segment of segments) visit(segment); + return [...images.entries()].map(([uri, alt]) => ({ uri, alt })); } diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx index 2f2bffa336402..848db371e408c 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx @@ -11,6 +11,7 @@ const harness = vi.hoisted(() => ({ failImage: () => {}, loadImage: (_event: { source: { width: number; height: number } }) => {}, Passthrough: ({ children }: { children?: unknown }) => children, + presentationSources: [] as { identifier: string; fallbackIdentifier?: string }[], pressable: {} as HandlerProps, gestures: {} as Record, contentStyle: () => ({}) as { transform?: Transform }, @@ -87,7 +88,19 @@ vi.mock("../../components/ui/AppText", () => ({ })); vi.mock("../../components/MediaActionsMenu", () => ({ MediaActionsMenu: harness.Passthrough })); vi.mock("../../components/ui/NativePresentation", () => ({ - PresentationSource: harness.Passthrough, + PresentationSource: (props: { + identifier: string; + fallbackIdentifier?: string; + children?: ReactNode; + }) => { + harness.presentationSources.push({ + identifier: props.identifier, + ...(props.fallbackIdentifier !== undefined + ? { fallbackIdentifier: props.fallbackIdentifier } + : {}), + }); + return props.children; + }, })); vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) })); vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() })); @@ -448,3 +461,43 @@ it("zooms the inline image around the pinch and keeps it until the source or fra await act(async () => root.unmount()); } }); + +it("registers its presentation source only after the image finishes decoding", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + harness.presentationSources.length = 0; + const root = createRoot(document.createElement("div")); + const openPreview = vi.fn<(source: FilePreviewSource) => void>(); + try { + await act(async () => + root.render( + , + ), + ); + expect(harness.presentationSources.at(-1)).toEqual({ + identifier: "", + fallbackIdentifier: "", + }); + + await act(async () => harness.loadImage({ source: { width: 400, height: 200 } })); + const registered = harness.presentationSources.at(-1)!; + expect(registered.identifier).not.toBe(""); + expect(registered.fallbackIdentifier).toBe("shared:shot"); + + await act(async () => harness.pressable.onPress?.({ nativeEvent: {} })); + expect(openPreview).toHaveBeenCalledWith( + expect.objectContaining({ + name: "Before", + sourceIdentifier: registered.identifier, + }), + ); + } finally { + await act(async () => root.unmount()); + } +}); diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx index 8e18d8445c85a..ab22ebd100928 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx @@ -22,7 +22,7 @@ import { useAssetUrlState } from "../../state/assets"; import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext"; import { ZoomableImagePressable } from "./ZoomableImagePressable"; import { assetImageCacheKey } from "../../lib/assetImageSource"; -import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery"; +import { filePreviewSourceIdentifier, imagePreviewName } from "../../lib/filePreviewGallery"; import { MARKDOWN_IMAGE_MAX_WIDTH, type MarkdownImageDisplaySize, @@ -105,7 +105,6 @@ export function ThreadMarkdownImageView(props: { const gt = useGT(); const withGallery = useFilePreviewGallery(); const localSourceIdentifier = useId(); - const sourceIdentifier = props.sourceIdentifier ?? localSourceIdentifier; const mediaActions = useMediaActions(props.actionsSource); const contextWidth = useContext(MarkdownImageAvailableWidthContext); const [measuredWidth, setMeasuredWidth] = useState(0); @@ -117,6 +116,12 @@ export function ThreadMarkdownImageView(props: { props.format === "svg" && props.uri !== null ? svgDocumentAtom(props.uri) : noSvgDocumentAtom, ); const svgDocument = AsyncResult.isSuccess(svg) ? svg.value : null; + const imageKey = props.uri ? (props.cacheKey ?? props.uri) : null; + const [loadedImageKey, setLoadedImageKey] = useState(null); + const ready = + props.format === "svg" + ? svgDocument !== null + : imageKey !== null && loadedImageKey === imageKey; // Keyed by source so a new source drops the previous image's decoded dimensions. const [decoded, setDecoded] = useState<{ sourceKey: string; size: ImageSize } | null>(null); const decodedSize = @@ -141,6 +146,7 @@ export function ThreadMarkdownImageView(props: { const placeholderWidth: ViewStyle["width"] = availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%"; const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 }; + const previewName = props.actionsSource?.name ?? props.alt; return ( ) : ( - + + onLoad={(size) => { + setLoadedImageKey(imageKey); // Only the first decode counts: later loads report the bitmap // downsampled for the current frame (969 vs 970 wide), so keeping // them resizes the frame, which reloads the image, and so on. @@ -207,9 +218,12 @@ export function ThreadMarkdownImageView(props: { current?.sourceKey === props.sourceKey ? current : { sourceKey: props.sourceKey, size }, - ) - } - onError={() => setFailure({ uri: props.uri, failed: true })} + ); + }} + onError={() => { + setLoadedImageKey(null); + setFailure({ uri: props.uri, failed: true }); + }} /> )} diff --git a/apps/mobile/src/lib/filePreviewGallery.test.ts b/apps/mobile/src/lib/filePreviewGallery.test.ts index d8def9cc125d8..04a8c747e9248 100644 --- a/apps/mobile/src/lib/filePreviewGallery.test.ts +++ b/apps/mobile/src/lib/filePreviewGallery.test.ts @@ -5,7 +5,12 @@ import type { DraftComposerAttachment } from "./composerImages"; import { composerImageGallery } from "./composerImageGallery"; import { contextImageGallery } from "./contextImageGallery"; import { messageImageGallery } from "../features/threads/messageImageGallery"; -import { filePreviewGallery, filePreviewKey } from "./filePreviewGallery"; +import { + filePreviewGallery, + filePreviewKey, + filePreviewName, + imagePreviewName, +} from "./filePreviewGallery"; vi.mock("./uuid", () => ({})); @@ -148,4 +153,36 @@ describe("image preview groups", () => { expect(filePreviewKey(a)).toBe(filePreviewKey(b)); expect(filePreviewGallery(b, [a])).toEqual([b]); }); + + it("keeps explicit image titles instead of replacing them with direct-URI filenames", () => { + expect( + filePreviewName({ + kind: "image", + uri: "https://user-images.githubusercontent.com/123/106598434-9e719e00.png", + name: "Before", + }), + ).toBe("Before"); + expect( + filePreviewName({ + kind: "image", + uri: "https://drop.example.com/shot.png?sig=1", + }), + ).toBe("shot.png"); + expect( + filePreviewName({ + kind: "image", + uri: "https://github.com/user-attachments/assets/8c809121-7a99-412e-ad09-c3c7615226a9", + }), + ).toBe("Preview"); + expect(imagePreviewName("https://drop.example.com/shot.png?sig=1", "image", "Bild")).toBe( + "shot.png", + ); + expect( + imagePreviewName( + "https://github.com/user-attachments/assets/8c809121-7a99-412e-ad09-c3c7615226a9", + null, + "Image", + ), + ).toBe("Image"); + }); }); diff --git a/apps/mobile/src/lib/filePreviewGallery.ts b/apps/mobile/src/lib/filePreviewGallery.ts index 26f16ec03cdc0..c5b5ef496c1e3 100644 --- a/apps/mobile/src/lib/filePreviewGallery.ts +++ b/apps/mobile/src/lib/filePreviewGallery.ts @@ -54,15 +54,44 @@ export function filePreviewGallery(source: FilePreviewSource, group: readonly Fi return items; } +const IMAGE_FILENAME_EXTENSION = /\.(png|jpe?g|gif|webp|heic|heif|avif|svg)$/i; +const PREVIEW_FILENAME_EXTENSION = + /\.(png|jpe?g|gif|webp|heic|heif|avif|svg|pdf|docx?|xlsx?|pptx?|txt|rtf)$/i; + +export function imagePreviewName( + url: string, + label: string | null | undefined, + fallback: string, +): string { + const trimmed = label?.trim(); + const isDefaultImageLabel = + trimmed !== undefined && (trimmed === fallback || trimmed.toLowerCase() === "image"); + if (trimmed && !isDefaultImageLabel) return trimmed; + if (!/^data:/i.test(url)) { + const basename = url.split(/[?#]/)[0]?.split("/").pop(); + if (basename && IMAGE_FILENAME_EXTENSION.test(basename)) return basename; + } + return fallback; +} + export function filePreviewName(source: FilePreviewItem): string { - const uriName = "uri" in source ? source.uri.split(/[?#]/)[0]?.split("/").pop() : undefined; + const rawUriName = + "uri" in source && !/^data:/i.test(source.uri) + ? source.uri.split(/[?#]/)[0]?.split("/").pop() + : undefined; + const uriName = rawUriName || undefined; + const fallbackUriName = + source.kind === "image" + ? uriName && IMAGE_FILENAME_EXTENSION.test(uriName) + ? uriName + : undefined + : uriName; const name = - source.name ?? ("attachment" in source ? source.attachment.name : uriName) ?? "Preview"; - const extension = /\.(png|jpe?g|gif|webp|heic|heif|avif|svg|pdf|docx?|xlsx?|pptx?|txt|rtf)$/i; + source.name ?? ("attachment" in source ? source.attachment.name : fallbackUriName) ?? "Preview"; const filename = - source.kind !== "image" || extension.test(name) + source.kind !== "image" || PREVIEW_FILENAME_EXTENSION.test(name) ? name - : uriName && extension.test(uriName) + : uriName && /\.svg$/i.test(uriName) ? uriName : name.replace(/\./g, "_"); return Array.from(filename, (character) => diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 6cce7f84b475c..c68a2577cd3f9 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -8,7 +8,7 @@ import { parseMarkdownDocument, type MarkdownNode, } from "./markdownDocument"; -import { markdownImageSources } from "./markdownImageSources"; +import { markdownImages, markdownImageSources } from "./markdownImageSources"; import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "./markdownMedia"; import { resolveMarkdownLinkPresentation } from "./markdownLinks"; import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation"; @@ -71,6 +71,21 @@ describe("HTML in native Markdown", () => { const markdown = '```html\n\n```\n\nUse `` here.\n\n\n\n![Two](two.png)\n\n'; expect(markdownImageSources(markdown)).toEqual(["one.png", "two.png"]); + expect(markdownImages(markdown)).toEqual([ + { url: "one.png", alt: null }, + { url: "two.png", alt: "Two" }, + ]); + expect(markdownImages('![](same.png)\n\n![Captured](same.png "Ignored")')).toEqual([ + { url: "same.png", alt: "Captured" }, + ]); + expect( + markdownImages( + '![Before][shot-1]\n\n![][shot-2]\n\n[shot-1]: https://example.com/1.png\n[shot-2]: https://example.com/2.png "After"', + ), + ).toEqual([ + { url: "https://example.com/1.png", alt: "Before" }, + { url: "https://example.com/2.png", alt: "After" }, + ]); const result = markdownWithHtml(markdown); expect(result).toContain('```html\n\n```'); expect(result).toContain('``'); diff --git a/apps/mobile/src/lib/markdownImageSources.ts b/apps/mobile/src/lib/markdownImageSources.ts index d3ccaa8de793d..1529ee5cadc00 100644 --- a/apps/mobile/src/lib/markdownImageSources.ts +++ b/apps/mobile/src/lib/markdownImageSources.ts @@ -1,12 +1,53 @@ import { parseMarkdownDocument, type MarkdownNode } from "./markdownDocument"; -export function markdownImageSources(markdown: string): string[] { - if (!markdown.includes("![") && !/]/i.test(markdown)) return []; - const sources = new Set(); +export interface MarkdownImageNode { + readonly url: string; + readonly alt: string | null; + readonly title: string | null; +} + +/** Inline and reference-style images in document order; references resolve against `definitionsRoot`. */ +export function markdownDocumentImages( + document: MarkdownNode, + definitionsRoot: MarkdownNode = document, +): MarkdownImageNode[] { + const definitions = new Map(); + const collectDefinitions = (node: MarkdownNode) => { + if (node.type === "definition") { + const id = node.identifier.toLowerCase(); + if (!definitions.has(id)) definitions.set(id, { url: node.url, title: node.title ?? null }); + return; + } + if ("children" in node) node.children.forEach(collectDefinitions); + }; + collectDefinitions(definitionsRoot); + const images: MarkdownImageNode[] = []; const visit = (node: MarkdownNode) => { - if (node.type === "image") sources.add(node.url); + if (node.type === "image") { + images.push({ url: node.url, alt: node.alt ?? null, title: node.title ?? null }); + } else if (node.type === "imageReference") { + const definition = definitions.get(node.identifier.toLowerCase()); + if (definition) images.push({ ...definition, alt: node.alt ?? null }); + } if ("children" in node) node.children.forEach(visit); }; - visit(parseMarkdownDocument(markdown)); - return [...sources]; + visit(document); + return images; +} + +/** Unique image URLs, each with the first non-empty alt or title it was given. */ +export function markdownImages( + markdown: string, +): { readonly url: string; readonly alt: string | null }[] { + if (!markdown.includes("![") && !/]/i.test(markdown)) return []; + const images = new Map(); + for (const image of markdownDocumentImages(parseMarkdownDocument(markdown))) { + const label = image.alt?.trim() || image.title?.trim() || null; + if ((images.get(image.url) ?? null) === null) images.set(image.url, label); + } + return [...images.entries()].map(([url, alt]) => ({ url, alt })); +} + +export function markdownImageSources(markdown: string): string[] { + return markdownImages(markdown).map((image) => image.url); }