Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -161,7 +161,7 @@ final class T3NativeImageViewer: NSObject {
}
}
decodes[index] = task
decodeQueue = task
if !isSVG { decodeQueue = task }
}

private func finish() {
Expand All @@ -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() {
Expand All @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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?
Expand All @@ -23,26 +51,36 @@ 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
}
}

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) }
}
}

Expand Down
6 changes: 5 additions & 1 deletion apps/mobile/src/components/ui/NativePresentation.android.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <View {...props} />;
}
1 change: 1 addition & 0 deletions apps/mobile/src/components/ui/NativePresentation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<PresentationSourceProps> = requireNativeView(
Expand Down
48 changes: 32 additions & 16 deletions apps/mobile/src/features/pull-requests/PullRequestDescription.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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();
Expand All @@ -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<string, FilePreviewItem>();
const byKey = new Map<string, FilePreviewItem>();
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 (
Expand Down Expand Up @@ -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}
/>
),
Expand Down
Loading
Loading