From 87171d0e7ad60e9b7b30821048ab22548316cff1 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Sun, 15 Nov 2026 21:41:57 +0000 Subject: [PATCH 1/8] Swipe through, drag away and save images in the full-screen viewer The viewer drew a band across the top just to hold the modal's close button, and moved between images with chevrons. Now the image sits on black that reaches the edges, with the app's round sheet buttons floating over it: close on the left, save on the right. Swiping sideways pages through a commit's images, with dashes at the bottom that slide to the current one. At its whole size an image can be dragged up or down: it follows the finger, the black fades, and letting go far enough (or flicking) closes the viewer. A short drag springs back. Once zoomed, a drag pans instead, until a pinch brings the image back to its whole size. Save puts the image in the phone's photo library through a small local plugin (packages/photos), since no NativePHP plugin does this. iOS asks for add-only photo access with a new usage string. Android 10 and up needs no permission. A toast says how it went. The viewer's state moved out of ShowsCommits into its own ShowsImageViewer trait, so other screens (Remotes next) can use it. Android keeps the modal's own close row for now: mobile-ui's modal only closes on Android's back while it's dismissible, and dismissible draws the row. Co-Authored-By: Claude Opus 5.5 --- app/Devnull/ImageViewer.php | 25 ++ app/Icons/Lucide.php | 2 + .../Concerns/ShowsCommits.php | 119 +------- .../Concerns/ShowsImageViewer.php | 243 ++++++++++++++++ app/Providers/NativeServiceProvider.php | 2 + composer.json | 6 + composer.lock | 38 ++- config/nativephp.php | 1 + packages/photos/composer.json | 26 ++ packages/photos/nativephp.json | 32 ++ .../resources/android/PhotosFunctions.kt | 96 ++++++ .../resources/ios/PhotosFunctions.swift | 93 ++++++ packages/photos/src/Events/SaveFailed.php | 20 ++ packages/photos/src/Events/Saved.php | 15 + packages/photos/src/Facades/Photos.php | 18 ++ packages/photos/src/Photos.php | 25 ++ packages/photos/src/PhotosServiceProvider.php | 13 + resources/icons/download.svg | 1 + .../partials/image-viewer-pages.blade.php | 44 +++ .../native/partials/image-viewer.blade.php | 107 +++---- tests/Feature/Screens/ImageViewerTest.php | 273 +++++++++++++----- tests/Feature/Screens/LogTest.php | 4 +- 22 files changed, 969 insertions(+), 234 deletions(-) create mode 100644 app/Devnull/ImageViewer.php create mode 100644 app/NativeComponents/Concerns/ShowsImageViewer.php create mode 100644 packages/photos/composer.json create mode 100644 packages/photos/nativephp.json create mode 100644 packages/photos/resources/android/PhotosFunctions.kt create mode 100644 packages/photos/resources/ios/PhotosFunctions.swift create mode 100644 packages/photos/src/Events/SaveFailed.php create mode 100644 packages/photos/src/Events/Saved.php create mode 100644 packages/photos/src/Facades/Photos.php create mode 100644 packages/photos/src/Photos.php create mode 100644 packages/photos/src/PhotosServiceProvider.php create mode 100644 resources/icons/download.svg create mode 100644 resources/views/native/partials/image-viewer-pages.blade.php diff --git a/app/Devnull/ImageViewer.php b/app/Devnull/ImageViewer.php new file mode 100644 index 00000000..c6c94631 --- /dev/null +++ b/app/Devnull/ImageViewer.php @@ -0,0 +1,25 @@ + 'bug', self::ImagePlus => 'image-plus', self::Image => 'image', + self::Download => 'download', self::Camera => 'camera', self::ChartBar => 'chart-bar', self::Eye => 'eye', diff --git a/app/NativeComponents/Concerns/ShowsCommits.php b/app/NativeComponents/Concerns/ShowsCommits.php index 05407927..2fc900e2 100644 --- a/app/NativeComponents/Concerns/ShowsCommits.php +++ b/app/NativeComponents/Concerns/ShowsCommits.php @@ -5,7 +5,6 @@ use App\Devnull\Account; use App\Devnull\Client; use App\Devnull\Data\Commit; -use App\Devnull\Data\CommitImage; use App\Devnull\Data\Pasteis; use App\Devnull\Data\User; use App\Devnull\Display; @@ -18,7 +17,6 @@ use App\Devnull\Toasts; use Closure; use Native\Mobile\Attributes\On; -use Native\Mobile\Edge\SharedValue; use Native\Mobile\Events\Alert\ButtonPressed; use Native\Mobile\Facades\Browser; use Native\Mobile\Facades\Dialog; @@ -45,6 +43,7 @@ trait ShowsCommits use OpensCommitSheet; use OpensHashtags; use OpensStargazers; + use ShowsImageViewer; use VotesOnPolls; use WritesInBackground; @@ -62,37 +61,6 @@ trait ShowsCommits */ public ?string $deleting = null; - /** - * Whether the image viewer is up, over everything else on the screen, - * sheet included. - */ - public bool $viewerOpen = false; - - /** - * The images of the commit being viewed, as they were when it opened, so - * the viewer keeps what it shows while it slides away even if the commit - * leaves the screen. - * - * @var list - */ - public array $viewerImages = []; - - /** - * Which of the viewer's images is showing. - */ - public int $viewerIndex = 0; - - /** - * The zoom and pan of the image being viewed, driven on the phone by the - * viewer's gesture area. Fresh ones on every open and every move between - * images, so each starts at rest; nulled on close. - */ - public ?SharedValue $viewerZoom = null; - - public ?SharedValue $viewerPanX = null; - - public ?SharedValue $viewerPanY = null; - /** * Every commit the screen is showing. * @@ -308,61 +276,13 @@ public function playNataNullers(): void } /** - * Opens a commit's image full-screen in the app (see partials/image-viewer), - * from the one the row tapped: the image whole rather than cropped, pinch - * zoom between its whole self and four times, a drag to pan, and the - * chevrons under it to move between the commit's other images. An image the - * screen isn't showing, or one at no web address, opens nothing, as it did - * in the browser. + * Opens a commit's image full-screen in the app (see ShowsImageViewer), from + * the one the row tapped. An image the screen isn't showing, or one at no + * web address, opens nothing, as it did in the browser. */ public function openImage(string $id, int $index = 0): void { - $images = $this->shownCommit($id)?->images ?? []; - $image = $images[$index] ?? null; - - if ($image === null || ! SiteLink::isWebUrl($image->url)) { - return; - } - - $this->viewerImages = $images; - $this->viewerIndex = $index; - $this->restViewerImage(); - $this->viewerOpen = true; - } - - /** - * The chevron under the viewer: the commit's next image, at rest again. At - * the last image there's no chevron to press, and a next at no web address - * goes nowhere, as an image at one never opens. - */ - public function viewNextImage(): void - { - $this->showInViewedImage($this->viewerIndex + 1); - } - - /** - * The chevron under the viewer: the commit's previous image, at rest - * again. At the first image there's no chevron to press, and a previous at - * no web address goes nowhere either. - */ - public function viewPreviousImage(): void - { - $this->showInViewedImage($this->viewerIndex - 1); - } - - /** - * The viewer's close, back or outside tap, however the phone reports it: - * the viewer goes and forgets the image and what its gestures left behind, - * so the next one opens as this one did. - */ - public function closeImageViewer(): void - { - $this->viewerOpen = false; - $this->viewerImages = []; - $this->viewerIndex = 0; - $this->viewerZoom = null; - $this->viewerPanX = null; - $this->viewerPanY = null; + $this->showImagesInViewer($this->shownCommit($id)?->images ?? [], $index); } /** @@ -632,33 +552,4 @@ private function openInBrowser(?string $url): void Browser::inApp($url); } } - - /** - * Puts the viewer's image back at rest: fresh shared values, which the - * phone seeds at one and none, so what the last image's gestures left - * behind can't carry over to it. - */ - private function restViewerImage(): void - { - $this->viewerZoom = SharedValue::make(1.0); - $this->viewerPanX = SharedValue::make(); - $this->viewerPanY = SharedValue::make(); - } - - /** - * Moves the viewer to one of its commit's images by its place among them, - * or nowhere when there's no image there or it's at no web address, so the - * viewer never comes to show one the phone shouldn't be asked for. - */ - private function showInViewedImage(int $index): void - { - $image = $this->viewerImages[$index] ?? null; - - if (! $this->viewerOpen || $image === null || ! SiteLink::isWebUrl($image->url)) { - return; - } - - $this->viewerIndex = $index; - $this->restViewerImage(); - } } diff --git a/app/NativeComponents/Concerns/ShowsImageViewer.php b/app/NativeComponents/Concerns/ShowsImageViewer.php new file mode 100644 index 00000000..7f68a42c --- /dev/null +++ b/app/NativeComponents/Concerns/ShowsImageViewer.php @@ -0,0 +1,243 @@ + + */ + public array $viewerImages = []; + + /** + * Which of the viewer's images is showing. + */ + public int $viewerIndex = 0; + + /** + * The zoom and pan of each image, by its place, driven on the phone by its page's gesture area. Fresh ones when + * the viewer opens and when a page is left, so each image starts at rest; emptied on close. + * + * @var array + */ + public array $viewerZooms = []; + + /** + * @var array + */ + public array $viewerPansX = []; + + /** + * @var array + */ + public array $viewerPansY = []; + + /** + * Whether the showing image is zoomed in, as its last pinch left it. Zoomed, a drag pans it; at its whole self a + * drag sideways pages and a drag up or down closes. + */ + public bool $viewerZoomed = false; + + /** + * How far the image has been dragged up or down to close the viewer, on the phone. + */ + public ?SharedValue $viewerDrag = null; + + /** + * Whether a save to the phone's photos is under way, so a second tap doesn't save it twice. + */ + public bool $savingViewedImage = false; + + /** + * Opens the viewer on $images, from the one at $index. An image at no web address opens nothing, and the viewer + * never pages to one. + * + * @param list $images + */ + public function showImagesInViewer(array $images, int $index = 0): void + { + $images = array_values($images); + $image = $images[$index] ?? null; + + if ($image === null || ! SiteLink::isWebUrl($image->url)) { + return; + } + + $this->viewerImages = $images; + $this->viewerIndex = $index; + $this->viewerZooms = $this->viewerPansX = $this->viewerPansY = []; + + foreach (array_keys($images) as $place) { + $this->restViewerImage($place); + } + + $this->viewerZoomed = false; + $this->viewerDrag = SharedValue::make(); + $this->savingViewedImage = false; + $this->viewerOpen = true; + } + + /** + * The pager settled on another image. The one left goes back to rest, as Photos puts it, and the one arrived at + * starts unzoomed. An image at no web address can't be paged to: the viewer stays where it was. + */ + public function viewerPaged(int $index): void + { + $image = $this->viewerImages[$index] ?? null; + + if (! $this->viewerOpen || $index === $this->viewerIndex || $image === null || ! SiteLink::isWebUrl($image->url)) { + return; + } + + $this->restViewerImage($this->viewerIndex); + $this->viewerIndex = $index; + $this->viewerZoomed = false; + } + + /** + * A pinch on the showing image ended, at $scale. + */ + public function viewerZoomEnded(float $scale): void + { + $this->viewerZoomed = $this->viewerOpen && $scale > ImageViewer::ZoomedPast; + } + + /** + * The image was let go after a drag up or down, settled at $y: at rest, or off to one side, which closes the + * viewer. + */ + public function viewerDragged(float $x, float $y): void + { + if (abs($y) >= ImageViewer::DismissDistance / 2) { + $this->closeImageViewer(); + } + } + + /** + * The viewer's close, a drag away, or Android's back: it goes and forgets the images and what their gestures + * left behind, so the next one opens as this one did. + */ + public function closeImageViewer(): void + { + $this->viewerOpen = false; + $this->viewerImages = []; + $this->viewerIndex = 0; + $this->viewerZooms = $this->viewerPansX = $this->viewerPansY = []; + $this->viewerZoomed = false; + $this->viewerDrag = null; + $this->savingViewedImage = false; + } + + /** + * Saves the showing image to the phone's photos, from the copy the app already has where there is one. The phone + * may ask first, and says how it went (see viewedImageSaved()). + */ + public function saveViewedImage(): void + { + $image = $this->viewerImages[$this->viewerIndex] ?? null; + + if (! $this->viewerOpen || $this->savingViewedImage || $image === null || ! SiteLink::isWebUrl($image->url)) { + return; + } + + $path = $this->viewedImageFile($image->url); + + if ($path === null || ! Photos::save($path)) { + Toasts::failed('Could not save the image. Try again.'); + + return; + } + + $this->savingViewedImage = true; + } + + #[On(Saved::class)] + public function viewedImageSaved(): void + { + $this->savingViewedImage = false; + + Toasts::say('Saved to Photos', short: true); + } + + #[On(SaveFailed::class)] + public function viewedImageNotSaved(string $reason = 'error'): void + { + $this->savingViewedImage = false; + + Toasts::failed($reason === 'denied' + ? 'devnull isn\'t allowed to add to your photos. You can allow it in Settings.' + : 'Could not save the image. Try again.'); + } + + /** + * The image's file on the phone: the one the image cache keeps, or a fresh download into it. + */ + private function viewedImageFile(string $url): ?string + { + $path = ImageCache::path($url); + + if (is_file($path)) { + return $path; + } + + try { + $response = Http::timeout(20)->get($url); + } catch (Throwable) { + return null; + } + + if (! $response instanceof Response || ! $response->successful() || ! str_starts_with((string) $response->header('Content-Type'), 'image/')) { + return null; + } + + File::ensureDirectoryExists(ImageCache::directory()); + File::put($path.'.part', $response->body()); + File::move($path.'.part', $path); + + return $path; + } + + /** + * Puts an image back at rest: fresh shared values, which the phone seeds at one and none, so what its last + * gestures left behind can't carry over. + */ + private function restViewerImage(int $place): void + { + $this->viewerZooms[$place] = SharedValue::make(1.0); + $this->viewerPansX[$place] = SharedValue::make(); + $this->viewerPansY[$place] = SharedValue::make(); + } +} diff --git a/app/Providers/NativeServiceProvider.php b/app/Providers/NativeServiceProvider.php index b8dceea4..b78aa287 100644 --- a/app/Providers/NativeServiceProvider.php +++ b/app/Providers/NativeServiceProvider.php @@ -4,6 +4,7 @@ use Codingwithrk\NativephpSocialAuth\NativephpSocialAuthServiceProvider; use Devnull\Calls\CallsServiceProvider; +use Devnull\Photos\PhotosServiceProvider; use Illuminate\Support\ServiceProvider; use Native\Mobile\Providers\BrowserServiceProvider; use Native\Mobile\Providers\CameraServiceProvider; @@ -63,6 +64,7 @@ public function plugins(): array ToastKitServiceProvider::class, ClipboardServiceProvider::class, CallsServiceProvider::class, + PhotosServiceProvider::class, SkiaServiceProvider::class, ...(config('devnull.apple_sign_in') ? [NativephpSocialAuthServiceProvider::class] : []), ]; diff --git a/composer.json b/composer.json index 122d0d56..69430f68 100644 --- a/composer.json +++ b/composer.json @@ -16,6 +16,11 @@ "type": "path", "url": "packages/calls" }, + { + "name": "photos", + "type": "path", + "url": "packages/photos" + }, { "type": "vcs", "url": "https://github.com/simonhamp/toastkit" @@ -34,6 +39,7 @@ "php": "^8.3", "codingwithrk/nativephp-social-auth": "^1.0", "devnull/nativephp-calls": "^1.0", + "devnull/nativephp-photos": "^1.0", "laravel/boost": "^2.0", "laravel/framework": "^13.0", "laravel/tinker": "^3.0", diff --git a/composer.lock b/composer.lock index eefe7986..d76c4bb3 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4564a3ffac02898824b683cfa1aedddd", + "content-hash": "8da614573009c041da1206198f293c72", "packages": [ { "name": "bacon/bacon-qr-code", @@ -427,6 +427,42 @@ "relative": true } }, + { + "name": "devnull/nativephp-photos", + "version": "1.0.0", + "dist": { + "type": "path", + "url": "packages/photos", + "reference": "bfb784d83f6154ce2b97592ad994951e69cfebaf" + }, + "require": { + "nativephp/mobile": "^4.6.1", + "php": "^8.3" + }, + "type": "nativephp-plugin", + "extra": { + "laravel": { + "providers": [ + "Devnull\\Photos\\PhotosServiceProvider" + ] + }, + "nativephp": { + "manifest": "nativephp.json" + } + }, + "autoload": { + "psr-4": { + "Devnull\\Photos\\": "src/" + } + }, + "license": [ + "MIT" + ], + "description": "Saves an image to the phone's photo library for the devnull app", + "transport-options": { + "relative": true + } + }, { "name": "dflydev/dot-access-data", "version": "v3.0.3", diff --git a/config/nativephp.php b/config/nativephp.php index 2e38a8c5..9d9c18b3 100644 --- a/config/nativephp.php +++ b/config/nativephp.php @@ -112,6 +112,7 @@ 'permissions' => [ 'NSCameraUsageDescription' => 'devnull uses the camera when you take a photo to attach to a commit.', 'NSPhotoLibraryUsageDescription' => 'devnull opens your photos when you pick some to attach to a commit.', + 'NSPhotoLibraryAddUsageDescription' => 'devnull saves an image to your photos when you ask it to from the image viewer.', 'NSMicrophoneUsageDescription' => 'devnull uses the microphone when you record a voice note or make a call in Remotes.', ], diff --git a/packages/photos/composer.json b/packages/photos/composer.json new file mode 100644 index 00000000..b9041560 --- /dev/null +++ b/packages/photos/composer.json @@ -0,0 +1,26 @@ +{ + "name": "devnull/nativephp-photos", + "description": "Saves an image to the phone's photo library for the devnull app", + "type": "nativephp-plugin", + "version": "1.0.0", + "license": "MIT", + "require": { + "php": "^8.3", + "nativephp/mobile": "^4.6.1" + }, + "autoload": { + "psr-4": { + "Devnull\\Photos\\": "src/" + } + }, + "extra": { + "laravel": { + "providers": [ + "Devnull\\Photos\\PhotosServiceProvider" + ] + }, + "nativephp": { + "manifest": "nativephp.json" + } + } +} diff --git a/packages/photos/nativephp.json b/packages/photos/nativephp.json new file mode 100644 index 00000000..b670b818 --- /dev/null +++ b/packages/photos/nativephp.json @@ -0,0 +1,32 @@ +{ + "namespace": "Photos", + "bridge_functions": [ + { + "name": "Photos.Save", + "android": "com.devnull.plugins.photos.PhotosFunctions.Save", + "ios": "PhotosFunctions.Save", + "description": "Save an image file to the phone's photo library, asking to add to it first where the phone needs that" + } + ], + "events": [ + "Devnull\\Photos\\Events\\Saved", + "Devnull\\Photos\\Events\\SaveFailed" + ], + "android": { + "min_version": 29, + "permissions": [], + "dependencies": { + "implementation": [] + } + }, + "ios": { + "min_version": "18.0", + "info_plist": { + "NSPhotoLibraryAddUsageDescription": "Saves the images you choose to your photo library." + }, + "dependencies": { + "swift_packages": [], + "pods": [] + } + } +} diff --git a/packages/photos/resources/android/PhotosFunctions.kt b/packages/photos/resources/android/PhotosFunctions.kt new file mode 100644 index 00000000..9d51f3c9 --- /dev/null +++ b/packages/photos/resources/android/PhotosFunctions.kt @@ -0,0 +1,96 @@ +package com.devnull.plugins.photos + +import android.content.ContentValues +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.os.Environment +import android.os.Handler +import android.os.Looper +import android.provider.MediaStore +import androidx.fragment.app.FragmentActivity +import com.nativephp.mobile.bridge.BridgeFunction +import com.nativephp.mobile.utils.NativeActionCoordinator +import org.json.JSONObject +import java.io.ByteArrayOutputStream +import java.io.File +import kotlin.concurrent.thread + +/** + * The phone's photo library. + * Namespace: "Photos.*" + * + * Saving returns at once and works off the main thread; what comes of it arrives as an event (Saved or SaveFailed). + * From Android 10 an app adds its own pictures to the shared collection without asking. + */ +object PhotosFunctions { + + private const val EVENTS = "Devnull\\Photos\\Events\\" + + /** Formats the gallery keeps as they are. Anything else Android can read goes in as a JPEG. */ + private val kept = setOf("image/jpeg", "image/png", "image/gif", "image/webp", "image/heif", "image/heic") + + /** + * Saves an image file to Pictures/devnull. + * Parameters: + * - path: string - The image file. Its name needn't say what kind of image it is. + */ + class Save(private val activity: FragmentActivity) : BridgeFunction { + override fun execute(parameters: Map): Map { + val file = (parameters["path"] as? String)?.let(::File)?.takeIf { it.isFile } ?: return mapOf("success" to false) + + thread(name = "devnull-photos-save") { save(activity, file) } + + return mapOf("success" to true) + } + } + + private fun save(activity: FragmentActivity, file: File) { + val (bytes, mime) = photo(file.readBytes()) ?: return dispatch(activity, "SaveFailed", JSONObject().put("reason", "unreadable")) + val extension = mime.substringAfter('/').replace("jpeg", "jpg") + val resolver = activity.contentResolver + val values = ContentValues().apply { + put(MediaStore.Images.Media.DISPLAY_NAME, "devnull-${System.currentTimeMillis()}.$extension") + put(MediaStore.Images.Media.MIME_TYPE, mime) + put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/devnull") + put(MediaStore.Images.Media.IS_PENDING, 1) + } + + val uri = try { + resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) + } catch (e: Exception) { + null + } ?: return dispatch(activity, "SaveFailed", JSONObject().put("reason", "error")) + + try { + resolver.openOutputStream(uri)?.use { it.write(bytes) } ?: throw IllegalStateException("No stream") + values.clear() + values.put(MediaStore.Images.Media.IS_PENDING, 0) + resolver.update(uri, values, null, null) + dispatch(activity, "Saved", JSONObject()) + } catch (e: Exception) { + resolver.delete(uri, null, null) + dispatch(activity, "SaveFailed", JSONObject().put("reason", "error")) + } + } + + /** The bytes to store and their type: the file as it is when the gallery keeps that format, a JPEG of it otherwise, or null when it isn't an image. */ + private fun photo(bytes: ByteArray): Pair? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + val mime = bounds.outMimeType ?: return null + + if (mime in kept) { + return bytes to mime + } + + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return null + val jpeg = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.JPEG, 95, it) }.toByteArray() + + return jpeg to "image/jpeg" + } + + private fun dispatch(activity: FragmentActivity, event: String, payload: JSONObject) { + // Events only reach PHP from the main thread. + Handler(Looper.getMainLooper()).post { NativeActionCoordinator.dispatchEvent(activity, EVENTS + event, payload.toString()) } + } +} diff --git a/packages/photos/resources/ios/PhotosFunctions.swift b/packages/photos/resources/ios/PhotosFunctions.swift new file mode 100644 index 00000000..50caf6c0 --- /dev/null +++ b/packages/photos/resources/ios/PhotosFunctions.swift @@ -0,0 +1,93 @@ +import Foundation +import ImageIO +import Photos +import UIKit +import UniformTypeIdentifiers + +// MARK: - Photos Function Namespace + +/// The phone's photo library. +/// Namespace: "Photos.*" +/// +/// Saving returns at once: the phone may ask the person first, and what comes of it arrives as an event (Saved or +/// SaveFailed). +enum PhotosFunctions { + + private static let events = "Devnull\\Photos\\Events\\" + + /// Formats the photo library keeps as they are. Anything else the phone can read goes in as a JPEG. + private static let kept: Set = [ + UTType.jpeg.identifier, + UTType.png.identifier, + UTType.heic.identifier, + UTType.gif.identifier, + ] + + // MARK: - Photos.Save + + /// Saves an image file to the photo library, asking to add to it first if the person hasn't been asked. + /// Parameters: + /// - path: string - The image file. Its name needn't say what kind of image it is. + class Save: BridgeFunction { + func execute(parameters: [String: Any]) throws -> [String: Any] { + guard let path = parameters["path"] as? String, + let data = FileManager.default.contents(atPath: path) else { + return ["success": false] + } + + DispatchQueue.global(qos: .userInitiated).async { + PhotosFunctions.save(data) + } + + return ["success": true] + } + } + + private static func save(_ data: Data) { + guard let (image, type) = photo(from: data) else { + dispatch("SaveFailed", ["reason": "unreadable"]) + return + } + + PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in + guard status == .authorized || status == .limited else { + dispatch("SaveFailed", ["reason": "denied"]) + return + } + + PHPhotoLibrary.shared().performChanges({ + let options = PHAssetResourceCreationOptions() + options.uniformTypeIdentifier = type + PHAssetCreationRequest.forAsset().addResource(with: .photo, data: image, options: options) + }) { saved, _ in + dispatch(saved ? "Saved" : "SaveFailed", saved ? [:] : ["reason": "error"]) + } + } + } + + /// The bytes to give the library and their type: the file as it is when the library keeps that format, a JPEG of + /// it otherwise (WebP, say), or nil when it isn't an image. + private static func photo(from data: Data) -> (Data, String)? { + guard let source = CGImageSourceCreateWithData(data as CFData, nil), + let type = CGImageSourceGetType(source) as String? else { + return nil + } + + if kept.contains(type) { + return (data, type) + } + + guard let jpeg = UIImage(data: data)?.jpegData(compressionQuality: 0.95) else { + return nil + } + + return (jpeg, UTType.jpeg.identifier) + } + + private static func dispatch(_ event: String, _ payload: [String: Any]) { + // Events only reach PHP from the main thread. + DispatchQueue.main.async { + LaravelBridge.shared.send?(events + event, payload) + } + } +} diff --git a/packages/photos/src/Events/SaveFailed.php b/packages/photos/src/Events/SaveFailed.php new file mode 100644 index 00000000..a9b9d611 --- /dev/null +++ b/packages/photos/src/Events/SaveFailed.php @@ -0,0 +1,20 @@ + $path], JSON_THROW_ON_ERROR)); + + return (bool) (json_decode((string) $result, true)['success'] ?? false); + } +} diff --git a/packages/photos/src/PhotosServiceProvider.php b/packages/photos/src/PhotosServiceProvider.php new file mode 100644 index 00000000..a1c8d928 --- /dev/null +++ b/packages/photos/src/PhotosServiceProvider.php @@ -0,0 +1,13 @@ +app->singleton(Photos::class); + } +} diff --git a/resources/icons/download.svg b/resources/icons/download.svg new file mode 100644 index 00000000..f7f42237 --- /dev/null +++ b/resources/icons/download.svg @@ -0,0 +1 @@ + diff --git a/resources/views/native/partials/image-viewer-pages.blade.php b/resources/views/native/partials/image-viewer-pages.blade.php new file mode 100644 index 00000000..de5647cd --- /dev/null +++ b/resources/views/native/partials/image-viewer-pages.blade.php @@ -0,0 +1,44 @@ +{{-- + The image viewer's pages, one image each, moved up and down together by the drag to close (see image-viewer). + + Each image pinches on its own gesture area. Only the showing image, once zoomed, binds a pan: an area with a pan + claims every touch, which would stop the pager paging and the drag to close. So the first pinch on an image zooms + around its middle, and later ones around the fingers. An image at no web address gets an empty page, never asked + for (the pager can't skip a page, and the viewer never moves to it). +--}} + + + @foreach ($viewerImages as $place => $image) + @php($pans = $place === $viewerIndex && $viewerZoomed) + + @if (\App\Devnull\SiteLink::isWebUrl($image->url)) + + + + + + @endif + + @endforeach + + diff --git a/resources/views/native/partials/image-viewer.blade.php b/resources/views/native/partials/image-viewer.blade.php index 96c78fa3..d30a0ca8 100644 --- a/resources/views/native/partials/image-viewer.blade.php +++ b/resources/views/native/partials/image-viewer.blade.php @@ -1,57 +1,66 @@ {{-- - A commit's images full-screen, over everything else on the screen, sheet included (see ShowsCommits): the image - the row tapped, whole rather than cropped as it is in the row, on black. A pinch zooms between the image's whole - self and four times, around the fingers, and a drag pans it; both run on the phone with no frame trip, so the - picture follows a finger. Bounded by the picture's own shape, it can't be lost off screen: zoomed, its edges stop at - the screen's, and it stays centred on a side it fits; dragged past that it resists and springs back on release, so - at its whole self it always comes back to the middle. The modal's own close, and Android's back, close it. + Images full-screen, over everything else on the screen, sheet included (see Concerns\ShowsImageViewer), on black + that reaches every edge. Any screen can hang it: use the trait and include this once. - Several images in a commit move with the chevrons under the picture, which say their place among them, and each - move puts the picture back at rest, as closing and opening another image does. An image still loading, or one that - fails, shows whatever its platform's loader shows meanwhile — iOS its spinner, Android nothing — since the image - element tells the app nothing about either, there's nothing of the app's to draw here. + A swipe sideways pages through the images, one per page, and the dashes at the bottom say which is showing, the + bright one sliding along as the page changes. A pinch zooms an image between its whole self and four times, + around the fingers once it's zoomed, and a zoomed image pans; both run on the phone with no frame trip. Bounded by + the picture's own shape, it can't be lost off screen. Zoomed, a drag pans rather than pages or closes, so the + pager and the drag to close only take over again once a pinch brings it back to its whole self. - Always in the tree, shown or not, like the sheet, so the phone can animate it away and say when it's gone. - Included beside the sheet, so every screen that shows commits has it once. Keyed so its picture coming and going - doesn't shift the ids of whatever the screen draws after it, which would draw it anew, back at its top. + At its whole self, a drag up or down takes the image with the finger and fades the black and the buttons with it. + Let go short of halfway to ImageViewer::DismissDistance and it springs back; past that, or with a flick, it carries on + and the viewer closes. The round buttons over the top close it and save the image to the phone's photos, drawn as a + sheet's bar buttons are (see sheet-bar-button). + + On iOS the modal's own close row is turned off, since the round close floats over the picture instead. Android + keeps it, because the modal only closes on Android's back while it's dismissible, and dismissible draws the row. + + Always in the tree, shown or not, like the sheet, so the phone can animate it away and say when it's gone. Keyed + so its pages coming and going don't shift the ids of whatever the screen draws after it. --}} - +@php($viewerOwnRow = \Native\Mobile\Platform::isAndroid()) + @if ($viewerImages !== []) - @php($image = $viewerImages[$viewerIndex]) - - - - - - - @if (count($viewerImages) > 1) - - @if ($viewerIndex > 0) - - - - - - @endif - {{ $viewerIndex + 1 }} of {{ count($viewerImages) }} - @if ($viewerIndex < count($viewerImages) - 1) - - - - - - @endif - + @php($far = \App\Devnull\ImageViewer::DismissDistance) + @php($count = count($viewerImages)) + {{-- Faded by the drag either way: the outer layer as it goes up, the inner as it goes down. --}} + @php($fadeUp = $viewerDrag->interpolate([-$far, 0], [0, 1])) + @php($fadeDown = $viewerDrag->interpolate([0, $far], [1, 0])) + + + + + @if ($viewerZoomed) + + @include('native.partials.image-viewer-pages') + + @else + + @include('native.partials.image-viewer-pages') + @endif - + + + + @unless ($viewerOwnRow) + @include('native.partials.sheet-bar-button', ['ref' => 'viewer-close', 'icon' => \App\Icons\Lucide::X, 'label' => 'Close', 'press' => 'closeImageViewer']) + @endunless + @include('native.partials.sheet-bar-button', ['ref' => 'viewer-save', 'icon' => \App\Icons\Lucide::Download, 'label' => 'Save to Photos', 'loading' => $savingViewedImage, 'press' => $savingViewedImage ? null : 'saveViewedImage']) + + @if ($count > 1) + @php($step = 22) + + + @foreach ($viewerImages as $place => $image) + + @endforeach + + + + @endif + + + @endif diff --git a/tests/Feature/Screens/ImageViewerTest.php b/tests/Feature/Screens/ImageViewerTest.php index 7b2056b3..29b5b9dd 100644 --- a/tests/Feature/Screens/ImageViewerTest.php +++ b/tests/Feature/Screens/ImageViewerTest.php @@ -1,5 +1,8 @@ 'http://devnull.test']); - signIn(); + $this->bridge = signIn(); }); afterEach(function () { @@ -60,29 +63,46 @@ function imagedCommitImages(): array $screen->tap('image-i1'); $viewer = nodeByRef($screen, 'image-viewer'); - $gestures = nodeByRef($screen, 'viewer-gestures'); - $image = nodeByRef($screen, 'viewed-image'); + $gestures = nodeByRef($screen, 'viewer-gestures-0'); + $image = nodeByRef($screen, 'viewed-image-0'); $viewing = $screen->instance(); expect($viewer['props'])->toMatchArray(['visible' => true, 'a11y_label' => 'Image viewer']) ->and($viewer['props']['on_dismiss'])->not->toBeEmpty() // The image whole, not cropped as it is in the row, read out by the description its author gave it. ->and($image['props'])->toMatchArray(['src' => 'https://img.test/1', 'fit' => 1, 'alt' => 'A cat on a keyboard']) - // Pinch bounded one to four, and both pans, settled on the phone against the shared values this open made, - // kept on screen by the image's own shape. + // Pinch bounded one to four, settled on the phone against the shared values this open made, kept on screen + // by the image's own shape. At its whole self it doesn't pan, so the pager and the drag to close get the drag. ->and($gestures['props'])->toMatchArray(['pinch-min' => 1.0, 'pinch-max' => 4.0, 'bounded' => true, 'content-ratio' => 1.0]) - ->and($gestures['props']['pinch-id'])->toBe($viewing->viewerZoom->id) - ->and($gestures['props']['pan-x-id'])->toBe($viewing->viewerPanX->id) - ->and($gestures['props']['pan-y-id'])->toBe($viewing->viewerPanY->id) - ->and($image['props']['scale_sv'])->toBe((string) $viewing->viewerZoom) - ->and($image['props']['translate-x_sv'])->toBe((string) $viewing->viewerPanX) - ->and($image['props']['translate-y_sv'])->toBe((string) $viewing->viewerPanY) - // One image alone has no chevrons and no place among others. - ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewer-count'))->toBeNull(); + ->and($gestures['props']['pinch-id'])->toBe($viewing->viewerZooms[0]->id) + ->and($gestures['props'])->not->toHaveKey('pan-x-id') + ->and($gestures['props'])->not->toHaveKey('pan-y-id') + ->and($image['props']['scale_sv'])->toBe((string) $viewing->viewerZooms[0]) + ->and($image['props']['translate-x_sv'])->toBe((string) $viewing->viewerPansX[0]) + ->and($image['props']['translate-y_sv'])->toBe((string) $viewing->viewerPansY[0]) + // One image alone has no dashes to say its place. + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewer-dots'))->toBeNull(); $screen->assertNativeNotCalled('Browser.OpenInApp'); })->with(['ios', 'android']); +it('floats a sheet\'s round close over the picture on iOS, with no band for the modal\'s own', function () { + $screen = logWithImages(platform: 'ios')->tap('image-i1'); + + expect(nodeByRef($screen, 'image-viewer')['props']['dismissible'])->toBeFalse() + ->and(nodeByRef($screen, 'viewer-close')['props']['a11y_label'])->toBe('Close'); + + $screen->tap('viewer-close')->assertSet('viewerOpen', false); +}); + +it('keeps the modal\'s own close row on Android, so Android\'s back still closes it', function () { + $screen = logWithImages(platform: 'android')->tap('image-i1'); + + expect(nodeByRef($screen, 'image-viewer')['props']['dismissible'])->toBeTrue() + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewer-close'))->toBeNull() + ->and(nodeByRef($screen, 'viewer-save')['props']['a11y_label'])->toBe('Save to Photos'); +}); + it('keeps an image of no known size on screen by the screen\'s own shape', function () { Http::fake(['devnull.test/*' => Http::response(pageJson([commitJson(['id' => 'c1', 'images' => [ ['id' => 'i1', 'url' => 'https://img.test/1'], @@ -90,7 +110,7 @@ function imagedCommitImages(): array $screen = Native::visit('/log')->tap('image-i1'); - expect(nodeByRef($screen, 'viewer-gestures')['props'])->toHaveKey('bounded') + expect(nodeByRef($screen, 'viewer-gestures-0')['props'])->toHaveKey('bounded') ->not->toHaveKey('content-ratio'); }); @@ -101,53 +121,95 @@ function imagedCommitImages(): array $screen = Native::visit('/log')->tap('image-i1'); - expect(nodeByRef($screen, 'viewer-gestures')['props']['content-ratio'])->toBe(0.25); + expect(nodeByRef($screen, 'viewer-gestures-0')['props']['content-ratio'])->toBe(0.25); }); -it('starts from the image the row tapped, with the chevrons under it for the commit\'s others', function () { +it('pages through the commit\'s images from the one the row tapped, with dashes for its place', function () { $screen = logWithImages(3)->tap('image-i3'); - expect(nodeByRef($screen, 'viewed-image')['props'])->toMatchArray(['src' => 'https://img.test/3', 'alt' => 'Attached image 3 of 3']) + $pager = nodeByRef($screen, 'viewer-pager'); + + expect($pager['props'])->toMatchArray(['horizontal' => true, 'page' => 2, 'count' => 3]) + ->and($pager['props']['on_page_change'])->not->toBeEmpty() + ->and(nodeByRef($screen, 'viewed-image-2')['props'])->toMatchArray(['src' => 'https://img.test/3', 'alt' => 'Attached image 3 of 3']) + ->and(nodeByRef($screen, 'viewed-image-0')['props']['alt'])->toBe('A cat on a keyboard, image 1 of 3') ->and($screen->instance()->viewerIndex)->toBe(2) - ->and(shownText($screen))->toContain('3 of 3') - // The first image has nothing before it, the last nothing after it, so only the chevron that goes somewhere is drawn. - ->and(nodeByRef($screen, 'viewed-previous')['props']['a11y_label'])->toBe('Previous image') - ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-next'))->toBeNull(); - - $screen->tap('viewed-previous')->tap('viewed-previous'); - - expect(nodeByRef($screen, 'viewed-image')['props'])->toMatchArray(['src' => 'https://img.test/1', 'alt' => 'A cat on a keyboard, image 1 of 3']) - ->and($screen->instance()->viewerIndex)->toBe(0) - ->and(shownText($screen))->toContain('1 of 3') - ->and(nodeByRef($screen, 'viewed-next')['props']['a11y_label'])->toBe('Next image') - ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-previous'))->toBeNull(); + ->and(nodeByRef($screen, 'viewer-dots')['props']['a11y_label'])->toBe('Image 3 of 3') + // The bright dash sits over the third of three, and slides rather than jumps. + ->and(nodeByRef($screen, 'viewer-dot')['props'])->toMatchArray(['translate-x' => 22.0, 'animate-duration' => 250.0]) + // No chevrons any more: a swipe pages. + ->and(findNode($screen->tree(), fn (array $node): bool => in_array($node['ref'] ?? null, ['viewed-next', 'viewed-previous'], true)))->toBeNull(); + + $screen->changeTab('viewerPaged', 0); + + expect($screen->instance()->viewerIndex)->toBe(0) + ->and(nodeByRef($screen, 'viewer-dots')['props']['a11y_label'])->toBe('Image 1 of 3') + ->and(nodeByRef($screen, 'viewer-dot')['props']['translate-x'])->toBe(-22.0); }); -it('moves between the commit\'s images with the chevrons, each image starting at rest', function () { +it('puts an image back at rest once the pager leaves it, as Photos does', function () { $screen = logWithImages(3)->tap('image-i1'); - $atRest = nodeByRef($screen, 'viewer-gestures')['props']; + $first = nodeByRef($screen, 'viewer-gestures-0')['props']['pinch-id']; + $second = nodeByRef($screen, 'viewer-gestures-1')['props']['pinch-id']; + + $screen->pinch('viewer-gestures-0', 2.5); + + expect($screen->instance()->viewerZoomed)->toBeTrue(); - $screen->tap('viewed-next'); + $screen->changeTab('viewerPaged', 1); - $image = nodeByRef($screen, 'viewed-image'); - $moved = nodeByRef($screen, 'viewer-gestures')['props']; + expect($screen->instance()->viewerZoomed)->toBeFalse() + // Fresh zoom for the one left, so it's whole again when the pager comes back to it; the one arrived at keeps its own. + ->and(nodeByRef($screen, 'viewer-gestures-0')['props']['pinch-id'])->not->toBe($first) + ->and(nodeByRef($screen, 'viewer-gestures-1')['props']['pinch-id'])->toBe($second) + ->and(nodeByRef($screen, 'viewed-image-0')['props']['scale'])->toBe(1.0); +}); + +it('pans a zoomed image instead of paging or closing, until a pinch brings it back to its whole self', function () { + $screen = logWithImages(2)->tap('image-i1'); - expect($image['props']['src'])->toBe('https://img.test/2') - ->and($screen->instance()->viewerIndex)->toBe(1) - // Fresh zoom and pans, so what the last image's pinch or drag left behind can't carry over to it. - ->and($moved['pinch-id'])->not->toBe($atRest['pinch-id']) - ->and($moved['pan-x-id'])->not->toBe($atRest['pan-x-id']) - ->and($moved['pan-y-id'])->not->toBe($atRest['pan-y-id']) - ->and($image['props']['scale'])->toBe(1.0); + expect(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-id') + ->toHaveKey('pan-y-snap'); - // Past the last image, the chevron is gone and the call goes nowhere. - $screen->tap('viewed-next')->call('viewNextImage'); + $screen->pinch('viewer-gestures-0', 3.0); + + $viewing = $screen->instance(); + $gestures = nodeByRef($screen, 'viewer-gestures-0')['props']; - expect($screen->instance()->viewerIndex)->toBe(2) - ->and(nodeByRef($screen, 'viewed-image')['props']['src'])->toBe('https://img.test/3'); + expect($gestures['pan-x-id'])->toBe($viewing->viewerPansX[0]->id) + ->and($gestures['pan-y-id'])->toBe($viewing->viewerPansY[0]->id) + // The page that isn't showing doesn't pan, and the drag to close lets go of the drag. + ->and(nodeByRef($screen, 'viewer-gestures-1')['props'])->not->toHaveKey('pan-x-id') + ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->not->toHaveKey('pan-y-id') + ->not->toHaveKey('on_drag_end'); + + $screen->pinch('viewer-gestures-0', 1.0); + + expect($screen->instance()->viewerZoomed)->toBeFalse() + ->and(nodeByRef($screen, 'viewer-gestures-0')['props'])->not->toHaveKey('pan-x-id') + ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-id'); }); +it('closes when the image is dragged far enough up or down, and springs back from a short drag', function (float $settled, bool $closes) { + $screen = logWithImages(2)->tap('image-i1'); + + $dismiss = nodeByRef($screen, 'viewer-dismiss')['props']; + + expect($dismiss['pan-y-id'])->toBe($screen->instance()->viewerDrag->id) + ->and($dismiss['pan-y-snap'])->toBe('-240,0,240') + // The black and the buttons fade with the drag either way. + ->and(nodeByRef($screen, 'viewer-backdrop')['props']['opacity_sv'])->toContain('interp:0,240:1,0'); + + $screen->dragEnd('viewer-dismiss', 0, $settled); + + expect($screen->instance()->viewerOpen)->toBe(! $closes); +})->with([ + 'let go short' => [0.0, false], + 'dragged down' => [240.0, true], + 'flicked up' => [-240.0, true], +]); + it('opens nothing for an image the screen isn\'t showing, a place with no image, or no web address', function () { Http::fake(['devnull.test/*' => Http::response(pageJson([ imagedCommitJson(1), @@ -169,7 +231,8 @@ function imagedCommitImages(): array $screen = logWithImages(2, platform: $platform); $screen->tap('image-i2'); - $firstPinch = nodeByRef($screen, 'viewer-gestures')['props']['pinch-id']; + $firstPinch = nodeByRef($screen, 'viewer-gestures-1')['props']['pinch-id']; + $firstDrag = $screen->instance()->viewerDrag->id; $screen->dismissSheet('image-viewer'); @@ -178,48 +241,122 @@ function imagedCommitImages(): array expect($viewing->viewerOpen)->toBeFalse() ->and($viewing->viewerImages)->toBe([]) ->and($viewing->viewerIndex)->toBe(0) - ->and($viewing->viewerZoom)->toBeNull() - ->and($viewing->viewerPanX)->toBeNull() - ->and($viewing->viewerPanY)->toBeNull() + ->and($viewing->viewerZooms)->toBe([]) + ->and($viewing->viewerPansX)->toBe([]) + ->and($viewing->viewerPansY)->toBe([]) + ->and($viewing->viewerDrag)->toBeNull() // The modal itself stays in the tree, hidden, so the phone can animate it away and say when it's gone. ->and(nodeByRef($screen, 'image-viewer')['props']['visible'])->toBeFalse() - ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-image'))->toBeNull(); + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewer-pager'))->toBeNull(); - $screen->tap('image-i1'); + $screen->tap('image-i2'); - expect(nodeByRef($screen, 'viewed-image')['props']['src'])->toBe('https://img.test/1') - // A fresh pinch, seeded at one again, not the one the closed image was using. - ->and(nodeByRef($screen, 'viewer-gestures')['props']['pinch-id'])->not->toBe($firstPinch); + // A fresh pinch and drag, seeded at rest again, not the ones the closed viewer was using. + expect(nodeByRef($screen, 'viewer-gestures-1')['props']['pinch-id'])->not->toBe($firstPinch) + ->and($screen->instance()->viewerDrag->id)->not->toBe($firstDrag); })->with(['ios', 'android']); -it('goes nowhere when the next or previous image is at no web address, so the viewer never shows one', function () { +it('never shows or pages to an image at no web address', function () { Http::fake(['devnull.test/*' => Http::response(pageJson([commitJson(['id' => 'c1', 'images' => [ ['id' => 'i1', 'url' => 'https://img.test/1', 'width' => 10, 'height' => 10], ['id' => 'i2', 'url' => 'file:///etc/passwd', 'width' => 10, 'height' => 10], ['id' => 'i3', 'url' => 'https://img.test/3', 'width' => 10, 'height' => 10], ]])]))]); - $screen = Native::visit('/log'); - - // From the first, next is the unsafe image: the chevron goes nowhere. - $screen->tap('image-i1')->tap('viewed-next'); + $screen = Native::visit('/log')->tap('image-i1'); - expect($screen->instance()->viewerIndex)->toBe(0) - ->and(nodeByRef($screen, 'viewed-image')['props']['src'])->toBe('https://img.test/1'); + // Its page is empty, and settling on it leaves the viewer on the image it was showing. + expect(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-image-1'))->toBeNull(); - // From the last, previous is the unsafe image: the chevron goes nowhere either. - $screen->tap('image-i3')->tap('viewed-previous'); + $screen->changeTab('viewerPaged', 1); - expect($screen->instance()->viewerIndex)->toBe(2) - ->and(nodeByRef($screen, 'viewed-image')['props']['src'])->toBe('https://img.test/3'); + expect($screen->instance()->viewerIndex)->toBe(0); - // Nothing the viewer shows is at any but a web address. $shown = findNodes(nodeByRef($screen, 'image-viewer'), fn (array $node): bool => ($node['type'] ?? null) === 'image'); - expect($shown)->not->toBeEmpty() + expect($shown)->toHaveCount(2) ->and(array_map(fn (array $node): string => $node['props']['src'] ?? '', $shown))->each->toStartWith('https://'); }); +it('saves the showing image to the phone\'s photos from the copy the app keeps, and says so', function () { + $screen = logWithImages(2)->tap('image-i1'); + $screen->changeTab('viewerPaged', 1); + + $kept = ImageCache::path('https://img.test/2'); + File::ensureDirectoryExists(dirname($kept)); + File::put($kept, 'jpeg bytes'); + + try { + $this->bridge->respondTo('Photos.Save', ['success' => true]); + + $screen->tap('viewer-save') + ->assertNativeCalled('Photos.Save', fn (array $params): bool => $params['path'] === $kept) + ->assertSet('savingViewedImage', true); + + // A second tap while it's saving does nothing: the button is a spinner, not a button. + expect(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'viewer-save' && isset($node['props']['on_press'])))->toBeNull(); + + $screen->emitNative(Saved::class) + ->assertSet('savingViewedImage', false) + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === 'Saved to Photos'); + } finally { + File::delete($kept); + } +}); + +it('downloads an image the app hasn\'t kept before saving it', function () { + Http::fake([ + 'devnull.test/*' => Http::response(pageJson([imagedCommitJson(1)])), + 'img.test/*' => Http::response('png bytes', 200, ['Content-Type' => 'image/png']), + ]); + $this->bridge->respondTo('Photos.Save', ['success' => true]); + + $kept = ImageCache::path('https://img.test/1'); + File::delete($kept); + + try { + Native::visit('/log')->tap('image-i1')->tap('viewer-save') + ->assertNativeCalled('Photos.Save', fn (array $params): bool => $params['path'] === $kept); + + expect(File::get($kept))->toBe('png bytes'); + } finally { + File::delete($kept); + } +}); + +it('says why an image couldn\'t be saved', function (string $reason, string $message) { + $this->bridge->respondTo('Photos.Save', ['success' => true]); + + $kept = ImageCache::path('https://img.test/1'); + File::ensureDirectoryExists(dirname($kept)); + File::put($kept, 'jpeg bytes'); + + try { + logWithImages()->tap('image-i1')->tap('viewer-save') + ->emitNative(SaveFailed::class, ['reason' => $reason]) + ->assertSet('savingViewedImage', false) + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === $message); + } finally { + File::delete($kept); + } +})->with([ + 'not allowed' => ['denied', 'devnull isn\'t allowed to add to your photos. You can allow it in Settings.'], + 'anything else' => ['error', 'Could not save the image. Try again.'], +]); + +it('says it couldn\'t save when the image can\'t be fetched', function () { + Http::fake([ + 'devnull.test/*' => Http::response(pageJson([imagedCommitJson(1)])), + 'img.test/*' => Http::response('nope', 404), + ]); + File::delete(ImageCache::path('https://img.test/1')); + + Native::visit('/log')->tap('image-i1')->tap('viewer-save') + ->assertNativeNotCalled('Photos.Save') + ->assertSet('savingViewedImage', false) + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === 'Could not save the image. Try again.'); +}); + it('keeps the browser for a commit\'s link preview, as before', function () { Http::fake(['devnull.test/*' => Http::response(pageJson([commitJson([ 'id' => 'c1', @@ -242,7 +379,7 @@ function imagedCommitImages(): array $screen->tap('image-i1'); expect(nodeByRef($screen, 'image-viewer')['props']['visible'])->toBeTrue() - ->and(nodeByRef($screen, 'viewed-image')['props']['src'])->toBe('https://img.test/1'); + ->and(nodeByRef($screen, 'viewed-image-0')['props']['src'])->toBe('https://img.test/1'); $screen->assertNativeNotCalled('Browser.OpenInApp'); })->with([ diff --git a/tests/Feature/Screens/LogTest.php b/tests/Feature/Screens/LogTest.php index c0222442..41e99820 100644 --- a/tests/Feature/Screens/LogTest.php +++ b/tests/Feature/Screens/LogTest.php @@ -384,7 +384,7 @@ ->assertElement('image', fn (array $node): bool => ($node['props']['src'] ?? null) === 'http://devnull.test/commit-images/i1') ->tap('image-i1') ->assertSet('viewerOpen', true) - ->assertElement('image', fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-image' + ->assertElement('image', fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-image-0' && ($node['props']['src'] ?? null) === 'http://devnull.test/commit-images/i1') ->assertNativeNotCalled('Browser.OpenInApp'); }); @@ -403,7 +403,7 @@ ->assertElement('pressable', fn (array $node): bool => ($node['ref'] ?? null) === 'image-i3' && ($node['a11y']['label'] ?? $node['props']['a11y_label'] ?? null) !== null) ->tap('image-i3') ->assertSet('viewerIndex', 2) - ->assertElement('image', fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-image' + ->assertElement('image', fn (array $node): bool => ($node['ref'] ?? null) === 'viewed-image-2' && ($node['props']['src'] ?? null) === 'https://img.test/3') ->assertNativeNotCalled('Browser.OpenInApp'); }); From 698940a3c4071416a71989053efa14c59169600b Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Mon, 16 Nov 2026 02:54:02 +0000 Subject: [PATCH 2/8] Polish the profile screens: picture viewer, bio tags, share and follow Tapping the avatar on a person's profile now opens their picture in the full-screen image viewer from #175, where it can be zoomed and saved. It asks GitHub for the 1024 pixel version, as the web does. A live avatar still opens the stream. Accounts tagged in a bio or company (like @laravel) are drawn as the web draws them: the account's square GitHub icon and its handle in a small tag. EDGE can't put an image inside a run of text, so a bio with tags is laid out as a wrapping row of words and tags. A tag opens the account in the app when devnull has a page for it (the API's bio_profiles), and GitHub otherwise. devnull doesn't say whether that page is a user or an organization, so it opens as a user and the profile hands over to the organization screen on a 404, as it already did. If the API starts sending bio_profile_types, the app uses it. An organization's Share moves out of the header into its own nav bar button. Follow, Unfollow and Remote are now 40pt pills on Liquid Glass on iOS. Follow is tinted with your colour through the glass. Android keeps a solid pill. Co-Authored-By: Claude Opus 5.5 --- app/Devnull/BioText.php | 79 +++++++++++++++++++ app/Devnull/Data/Profile.php | 55 ++++++++++++- app/Devnull/Data/User.php | 19 +++++ app/NativeComponents/Organization.php | 25 +++++- app/NativeComponents/Profile.php | 49 ++++++++++-- .../native/partials/bio-mention.blade.php | 15 ++++ .../views/native/partials/bio-text.blade.php | 31 ++++++++ .../native/partials/github-text.blade.php | 13 --- .../partials/glass-pill-button.blade.php | 22 ++++++ .../partials/organization-header.blade.php | 21 +++-- .../native/partials/profile-fact.blade.php | 7 +- .../native/partials/profile-header.blade.php | 21 +++-- tests/Feature/Screens/LaneButtonsTest.php | 32 ++++++-- tests/Feature/Screens/OrganizationTest.php | 12 ++- tests/Feature/Screens/ProfileCacheTest.php | 4 +- tests/Feature/Screens/ProfileStandingTest.php | 51 +++++++++--- tests/Feature/Screens/ProfileTest.php | 58 ++++++++++++++ 17 files changed, 448 insertions(+), 66 deletions(-) create mode 100644 app/Devnull/BioText.php create mode 100644 resources/views/native/partials/bio-mention.blade.php create mode 100644 resources/views/native/partials/bio-text.blade.php delete mode 100644 resources/views/native/partials/github-text.blade.php create mode 100644 resources/views/native/partials/glass-pill-button.blade.php diff --git a/app/Devnull/BioText.php b/app/Devnull/BioText.php new file mode 100644 index 00000000..e3895c8a --- /dev/null +++ b/app/Devnull/BioText.php @@ -0,0 +1,79 @@ +> + */ + public static function paragraphs(string $text): array + { + return array_map(self::pieces(...), preg_split('/\R/u', trim($text)) ?: []); + } + + /** + * Whether the text tags anyone, and so needs badges rather than one run of text. + */ + public static function hasMentions(string $text): bool + { + return Mention::inText($text) !== []; + } + + /** + * @return list + */ + private static function pieces(string $paragraph): array + { + $pieces = []; + $position = 0; + + foreach (Mention::inText($paragraph) as $mention) { + self::words(mb_substr($paragraph, $position, $mention->offset - $position), $pieces); + $pieces[] = ['text' => $mention->username, 'mention' => $mention->username, 'spaceAfter' => false]; + $position = $mention->offset + $mention->length; + } + + self::words(mb_substr($paragraph, $position), $pieces); + + if ($pieces !== []) { + $pieces[array_key_last($pieces)]['spaceAfter'] = false; + } + + return $pieces; + } + + /** + * Adds the words of $text to $pieces. Whitespace marks the piece before it as followed by a space. + * + * @param list $pieces + */ + private static function words(string $text, array &$pieces): void + { + preg_match_all('/\S+|\s+/u', $text, $matches); + + foreach ($matches[0] as $token) { + if (trim($token) === '') { + if ($pieces !== []) { + $pieces[array_key_last($pieces)]['spaceAfter'] = true; + } + + continue; + } + + $pieces[] = ['text' => $token, 'mention' => null, 'spaceAfter' => false]; + } + } +} diff --git a/app/Devnull/Data/Profile.php b/app/Devnull/Data/Profile.php index 946ccde7..4c989d6d 100644 --- a/app/Devnull/Data/Profile.php +++ b/app/Devnull/Data/Profile.php @@ -4,6 +4,10 @@ final readonly class Profile { + /** + * @param array $bioProfiles the handles their bio and company tag that have a page on devnull, by lowercase handle + * @param array $bioProfileTypes what each of those is, by lowercase handle, when devnull says: user, organization or unclaimed + */ public function __construct( public User $user, public int $commitsCount = 0, @@ -17,13 +21,16 @@ public function __construct( public bool $isMuting = false, public ?Achievements $achievements = null, public ?int $pasteisReceived = null, + public array $bioProfiles = [], + public array $bioProfileTypes = [], ) {} /** * Reads a `GET /users/{username}` response: the user and counts in `data`, * and alongside it whether you follow or mute them, their pinned commit, * their streaks, their activity, their achievements and how many pastéis - * they have been given (null when devnull doesn't say). + * they have been given (null when devnull doesn't say), and which handles + * their bio and company tag have a page on devnull. * * @param array $json */ @@ -47,9 +54,55 @@ public static function fromArray(array $json): self isMuting: ($json['is_muting'] ?? $data['is_muting'] ?? false) === true, achievements: Achievements::fromArray($json['achievements'] ?? $data['achievements'] ?? null), pasteisReceived: is_int($received) ? max(0, $received) : null, + bioProfiles: self::handles($json['bio_profiles'] ?? $data['bio_profiles'] ?? null), + bioProfileTypes: self::handles($json['bio_profile_types'] ?? $data['bio_profile_types'] ?? null), ); } + /** + * Where a handle tagged in their bio or company opens: 'organization' or 'user' for a page on devnull the app has a + * screen for, or null for GitHub. devnull sends which handles have a page (bio_profiles) but not yet what each is, + * so a page of unknown kind opens as a user, whose screen hands over to the organization's when devnull has no + * such user (see Profile::refused()). An unclaimed developer's page has no screen in the app, so that goes to + * GitHub, as do handles with no page at all, as on the web. + */ + public function bioMentionScreen(string $handle): ?string + { + $key = mb_strtolower($handle); + + if (! isset($this->bioProfiles[$key])) { + return null; + } + + return match ($this->bioProfileTypes[$key] ?? 'user') { + 'organization' => 'organization', + 'user' => 'user', + default => null, + }; + } + + /** + * A JSON object of strings by lowercase handle. PHP sends an empty one as [] and Laravel's (object) cast as {}. + * + * @return array + */ + private static function handles(mixed $value): array + { + if (! is_array($value)) { + return []; + } + + $handles = []; + + foreach ($value as $key => $handle) { + if (is_string($key) && is_string($handle) && $handle !== '') { + $handles[mb_strtolower($key)] = $handle; + } + } + + return $handles; + } + public function withFollowing(bool $isFollowing): self { $change = $isFollowing === $this->isFollowing ? 0 : ($isFollowing ? 1 : -1); diff --git a/app/Devnull/Data/User.php b/app/Devnull/Data/User.php index 7a928363..5912abd2 100644 --- a/app/Devnull/Data/User.php +++ b/app/Devnull/Data/User.php @@ -108,6 +108,25 @@ public function handle(): string return '@'.$this->username; } + /** + * Their avatar at $pixels across, as the web's sizedAvatarUrl() asks for it. GitHub sends 460 pixels unless asked + * otherwise, and as large as the picture was uploaded when asked for more. An avatar from anywhere else is left + * as it is. + */ + public function avatarUrlAt(int $pixels): ?string + { + $parts = $this->avatarUrl === null ? false : parse_url($this->avatarUrl); + + if ($parts === false || ($parts['host'] ?? null) !== 'avatars.githubusercontent.com') { + return $this->avatarUrl; + } + + parse_str($parts['query'] ?? '', $query); + $query['s'] = (string) $pixels; + + return ($parts['scheme'] ?? 'https').'://'.$parts['host'].($parts['path'] ?? '').'?'.http_build_query($query); + } + /** * Their GitHub profile. Everyone on devnull signed in with GitHub, so it can be * worked out when the API leaves it out. diff --git a/app/NativeComponents/Organization.php b/app/NativeComponents/Organization.php index c2f3718c..eaeb77f1 100644 --- a/app/NativeComponents/Organization.php +++ b/app/NativeComponents/Organization.php @@ -12,6 +12,7 @@ use App\Devnull\SiteLink; use App\Devnull\Stash; use App\Devnull\Timeline; +use App\Icons\Lucide; use App\NativeComponents\Concerns\DrawsSkeletonFirst; use App\NativeComponents\Concerns\ExpandsThreads; use App\NativeComponents\Concerns\HoldsNewCommits; @@ -22,16 +23,18 @@ use App\NativeComponents\Concerns\TalksToDevnull; use Closure; use Illuminate\View\View; +use Native\Mobile\Edge\Layouts\Builders\NavAction; +use Native\Mobile\Edge\Layouts\Builders\NavBarOptions; use Native\Mobile\Edge\NativeComponent; use Native\Mobile\Facades\Browser; use Native\Mobile\Facades\Share; /** * A GitHub organization's page, as the web shows it at its "@handle": its - * avatar as a rounded square in its lane, Follow and Share, what GitHub says - * about it, how many follow it and its admins, then its Commits and the + * avatar as a rounded square in its lane, Follow, what GitHub says about it, + * how many follow it and its admins, then its Commits and the * commits that mention it, as pages you swipe between, as on a profile (see - * Profile). + * Profile). Share is a button of its own in the nav bar. * * It opens from a commit the organization posted, or a mention of it, beneath * the tab it was tapped in, on the page as it was kept last time, then asks @@ -115,6 +118,20 @@ public function navTitle(): string return $this->organization->organization->name ?? $this->handle(); } + /** + * Share in the nav bar, as its own button, under the share shape each phone uses (Lucide's share on iOS, share-2 + * on Android), as a profile's Share profile has it. It's always there, as the link needs nothing but the handle. + */ + public function navigationOptions(): ?NavBarOptions + { + return NavBarOptions::make()->action( + NavAction::make('share') + ->icon(ios: Lucide::Share->ios(), android: Lucide::Share2->android()) + ->a11yLabel('Share '.($this->organization?->organization->handle() ?? '@'.$this->handle())) + ->press('share'), + ); + } + /** * Pull to refresh. You're at the top, so new commits go straight in. */ @@ -185,7 +202,7 @@ public function toggleFollow(): void } /** - * The web's Share beside Follow: the system share sheet, with the organization's page on the web. + * The web's Share, from the nav bar: the system share sheet, with the organization's page on the web. */ public function share(): void { diff --git a/app/NativeComponents/Profile.php b/app/NativeComponents/Profile.php index d4c1e690..b800b854 100644 --- a/app/NativeComponents/Profile.php +++ b/app/NativeComponents/Profile.php @@ -4,6 +4,7 @@ use App\Devnull\Account; use App\Devnull\Data\Commit; +use App\Devnull\Data\CommitImage; use App\Devnull\Data\Mention; use App\Devnull\Data\Page; use App\Devnull\Data\Profile as ProfileData; @@ -103,6 +104,11 @@ class Profile extends NativeComponent */ public const int PreviewCommits = 3; + /** + * How large the profile picture is fetched for the image viewer, as the web's ProfilePicture asks for it. + */ + public const int ProfilePicturePixels = 1024; + /** * The alerts the safety menu confirms with, as the web words them. Each one's id names the profile too, so an * answer only reaches the profile that asked. @@ -604,19 +610,52 @@ public function openSafety(): void $this->openInTab('/safety'); } - public function openGitHubMention(string $username): void + /** + * An account their bio or company tags, from its badge, as the web links it: its screen here in the app when it + * has a page on devnull, an organization's included, otherwise GitHub (see ProfileData::bioMentionScreen()). Only + * a handle the bio or company does tag opens. + */ + public function openBioMention(string $username): void { $user = $this->profile?->user; foreach (Mention::inText(($user?->bio ?? '')."\n".($user?->company ?? '')) as $mention) { - if ($mention->username === $username) { - Browser::inApp('https://github.com/'.rawurlencode($username)); - - return; + if ($mention->username !== $username) { + continue; } + + match ($this->profile?->bioMentionScreen($username)) { + 'organization' => $this->openOrganization($username), + 'user' => $this->openInTab('/users/'.rawurlencode($username)), + default => Browser::inApp('https://github.com/'.rawurlencode($username)), + }; + + return; } } + /** + * Their profile picture full-screen, as the web opens it from the avatar, at the 1024 pixels the web asks GitHub + * for, in the image viewer commits use (see ShowsImageViewer), where it can be zoomed and saved. + */ + public function viewProfilePicture(): void + { + $user = $this->profile?->user; + $url = $user?->avatarUrlAt(self::ProfilePicturePixels); + + if ($user === null || $url === null) { + return; + } + + $this->showImagesInViewer([new CommitImage( + id: 'avatar-'.$user->id, + url: $url, + width: self::ProfilePicturePixels, + height: self::ProfilePicturePixels, + description: "{$user->name}'s profile picture", + )]); + } + public function openGitHubProfile(): void { $url = $this->profile?->user->gitHubProfileUrl(); diff --git a/resources/views/native/partials/bio-mention.blade.php b/resources/views/native/partials/bio-mention.blade.php new file mode 100644 index 00000000..443e17e8 --- /dev/null +++ b/resources/views/native/partials/bio-mention.blade.php @@ -0,0 +1,15 @@ +{{-- + An account tagged in a bio, as the web's bio badge: its square GitHub icon on the hairline colour (a handle GitHub + doesn't know keeps just the square), then the handle without its "@", in a rounded tag edged with a hairline on + the wash. A tap calls $press with the handle. Scaled to $size, the size of the text around it. +--}} +@php($height = round($size * 1.5)) +@php($icon = round($size * 1.15)) + + + + + + {{ $handle }} + + diff --git a/resources/views/native/partials/bio-text.blade.php b/resources/views/native/partials/bio-text.blade.php new file mode 100644 index 00000000..bbe0e9b7 --- /dev/null +++ b/resources/views/native/partials/bio-text.blade.php @@ -0,0 +1,31 @@ +{{-- + A bio or company synced from GitHub, with each account it tags as a badge, as the web's BioText draws them: the + account's square GitHub icon, then its handle, in a small tag on the wash (see bio-mention). $press names the + screen's method a badge calls with the handle. Text that tags nobody is one run of text, as before. + + EDGE can't put an image in a run of text, so text with tags is a wrapping row of words and badges per paragraph + (see App\Devnull\BioText). $size is the text's size in points, which the badges are scaled to. +--}} +@php($size ??= 15) +@php($press ??= 'openGitHubMention') +@php($maxLines ??= null) +@if (\App\Devnull\BioText::hasMentions($text)) + @php($mentionIndex = 0) + + @foreach (\App\Devnull\BioText::paragraphs($text) as $paragraph) + + @foreach ($paragraph as $piece) + @php($space = $piece['spaceAfter'] ? 'mr-['.round($size * 0.27).']' : '') + @if ($piece['mention'] !== null) + @include('native.partials.bio-mention', ['handle' => $piece['mention'], 'ref' => $ref.'-mention-'.$mentionIndex, 'size' => $size, 'press' => $press, 'space' => $space]) + @php($mentionIndex++) + @else + + @endif + @endforeach + + @endforeach + +@else + {{ $text }} +@endif diff --git a/resources/views/native/partials/github-text.blade.php b/resources/views/native/partials/github-text.blade.php deleted file mode 100644 index 54a224a6..00000000 --- a/resources/views/native/partials/github-text.blade.php +++ /dev/null @@ -1,13 +0,0 @@ -@php($position = 0) - -@foreach (\App\Devnull\Data\Mention::inText($text) as $mention) -@if ($mention->offset > $position) - -@endif - -@php($position = $mention->offset + $mention->length) -@endforeach -@if ($position < mb_strlen($text)) - -@endif - diff --git a/resources/views/native/partials/glass-pill-button.blade.php b/resources/views/native/partials/glass-pill-button.blade.php new file mode 100644 index 00000000..713ed7a8 --- /dev/null +++ b/resources/views/native/partials/glass-pill-button.blade.php @@ -0,0 +1,22 @@ +{{-- + A header's main buttons on a profile or an organization's page: Follow, Unfollow and Remote. A 40pt pill, a step up + from the small theme button they were, on Liquid Glass on iOS as the app's other floating buttons are (see + sheet-bar-button). $filled draws it in your colour, tinted through the glass on iOS, for the one thing to do next, + like Follow; otherwise it's clear glass on iOS and a tonal pill on Android. + + It's a pressable rather than a theme button, which takes no glass or per-button fill. +--}} +@php($filled ??= false) +@php($icon ??= null) +@php($hint ??= null) +@php($a11yLabel ??= $label) +@php($pill = 'rounded-full ios:glass:interactive '.($filled ? 'bg-theme-'.$myColour : 'android:bg-theme-surface-variant')) +@php($ink = $filled ? 'text-theme-on-'.$myColour : 'text-theme-ink') + + + @if ($icon) + + @endif + {{ $label }} + + diff --git a/resources/views/native/partials/organization-header.blade.php b/resources/views/native/partials/organization-header.blade.php index 295a56b4..e2de8a30 100644 --- a/resources/views/native/partials/organization-header.blade.php +++ b/resources/views/native/partials/organization-header.blade.php @@ -1,8 +1,8 @@ {{-- The organization's header, which the pager draws above its tabs (see organization.blade.php), laid out like the - web's: the avatar as a rounded square ringed in its lane, Share and Follow, the name, the handle marked - Organization, what GitHub says about it, how many follow it and its admins. It scrolls up with the tab you're on - until the tabs pin under the nav bar. + web's: the avatar as a rounded square ringed in its lane, Follow, the name, the handle marked Organization, what + GitHub says about it, how many follow it and its admins. Share is in the nav bar. It scrolls up with the tab you're + on until the tabs pin under the nav bar. --}} @php($lane = \App\Devnull\Lane::token($user->lane())) @@ -19,14 +19,11 @@ - - - @if ($organization->isFollowing) - Unfollow - @else - Follow - @endif - + @if ($organization->isFollowing) + @include('native.partials.glass-pill-button', ['ref' => 'follow', 'label' => 'Unfollow', 'press' => 'toggleFollow', 'hint' => 'Unfollows '.$user->handle()]) + @else + @include('native.partials.glass-pill-button', ['ref' => 'follow', 'label' => 'Follow', 'press' => 'toggleFollow', 'filled' => true]) + @endif @@ -41,7 +38,7 @@ @if ($user->bio) - @include('native.partials.github-text', ['text' => $user->bio, 'ref' => 'organization-bio', 'classes' => 'w-full text-[15px] leading-relaxed text-theme-ink', 'maxLines' => null]) + @include('native.partials.bio-text', ['text' => $user->bio, 'ref' => 'organization-bio', 'classes' => 'w-full text-[15px] leading-relaxed text-theme-ink']) @endif {{-- What GitHub says about it, links in Commit Blue, each on its own line, as on a profile. --}} diff --git a/resources/views/native/partials/profile-fact.blade.php b/resources/views/native/partials/profile-fact.blade.php index a012659f..71b4a7f6 100644 --- a/resources/views/native/partials/profile-fact.blade.php +++ b/resources/views/native/partials/profile-fact.blade.php @@ -1,4 +1,7 @@ -{{-- One thing GitHub says about someone, under their bio: a muted icon and text, or a link in Commit Blue when $press is set. --}} +{{-- + One thing GitHub says about someone, under their bio: a muted icon and text, or a link in Commit Blue when $press is + set. With $gitHubMentions, the accounts it tags are badges, as in the bio, which call $mentionPress (see bio-text). +--}} @php($press ??= null) @if ($press) @@ -15,7 +18,7 @@ @if ($gitHubMentions ?? false) - @include('native.partials.github-text', ['text' => $label, 'ref' => 'profile-'.$key.'-text', 'classes' => 'flex-1 text-sm text-theme-ink-muted', 'maxLines' => 1]) + @include('native.partials.bio-text', ['text' => $label, 'ref' => 'profile-'.$key.'-text', 'classes' => 'flex-1 text-sm text-theme-ink-muted', 'maxLines' => 1, 'size' => 14, 'flowClasses' => 'flex-1', 'wordClasses' => 'text-theme-ink-muted', 'press' => $mentionPress ?? 'openGitHubMention']) @else {{ $label }} @endif diff --git a/resources/views/native/partials/profile-header.blade.php b/resources/views/native/partials/profile-header.blade.php index 78c88ffc..abeac50f 100644 --- a/resources/views/native/partials/profile-header.blade.php +++ b/resources/views/native/partials/profile-header.blade.php @@ -1,6 +1,6 @@ {{-- The profile's header, which the pager draws above its tabs (see profile.blade.php): the avatar ringed in their - lane, Follow (or, on your own, Edit on GitHub), who they are, what GitHub says about them, their counts and, in + lane, which opens full-screen, Follow (or, on your own, Edit on GitHub), who they are, what GitHub says about them, their counts and, in pastéis mode, the pastéis they've been given, then their activity, streaks and achievements. It scrolls up with the tab you're on until the tabs pin under the nav bar. --}} @@ -22,6 +22,15 @@ @include('native.partials.live-badge', ['size' => 'lg']) + @elseif ($user->avatarUrl) + {{-- A tap shows the picture full-screen, as the web's does, where it can be zoomed and saved. --}} + + + + @include('native.partials.avatar', ['user' => $user, 'size' => 80]) + + + @else @@ -39,12 +48,12 @@ {{-- The web's Remote, beside Follow, when you can push to them. --}} @if ($canRemote) - Remote + @include('native.partials.glass-pill-button', ['ref' => 'remote', 'label' => 'Remote', 'icon' => \App\Icons\Lucide::MessagesSquare, 'press' => 'openRemote', 'a11yLabel' => 'Remote '.$user->handle()]) @endif @if ($profile->isFollowing) - Unfollow + @include('native.partials.glass-pill-button', ['ref' => 'follow', 'label' => 'Unfollow', 'press' => 'toggleFollow', 'hint' => 'Unfollows '.$user->handle()]) @else - Follow + @include('native.partials.glass-pill-button', ['ref' => 'follow', 'label' => 'Follow', 'press' => 'toggleFollow', 'filled' => true]) @endif @endif @@ -78,7 +87,7 @@ @if ($user->bio) - @include('native.partials.github-text', ['text' => $user->bio, 'ref' => 'profile-bio', 'classes' => 'w-full text-[15px] leading-relaxed text-theme-ink', 'maxLines' => null]) + @include('native.partials.bio-text', ['text' => $user->bio, 'ref' => 'profile-bio', 'classes' => 'w-full text-[15px] leading-relaxed text-theme-ink', 'press' => 'openBioMention']) @endif {{-- @@ -87,7 +96,7 @@ --}} @if ($user->company) - @include('native.partials.profile-fact', ['key' => 'company', 'icon' => \App\Icons\Lucide::Building2, 'label' => $user->company, 'gitHubMentions' => true]) + @include('native.partials.profile-fact', ['key' => 'company', 'icon' => \App\Icons\Lucide::Building2, 'label' => $user->company, 'gitHubMentions' => true, 'mentionPress' => 'openBioMention']) @endif @if ($user->location) @include('native.partials.profile-fact', ['key' => 'location', 'icon' => \App\Icons\Lucide::MapPin, 'label' => $user->location]) diff --git a/tests/Feature/Screens/LaneButtonsTest.php b/tests/Feature/Screens/LaneButtonsTest.php index 3e966d04..29fa415b 100644 --- a/tests/Feature/Screens/LaneButtonsTest.php +++ b/tests/Feature/Screens/LaneButtonsTest.php @@ -59,14 +59,6 @@ function laneLog(): TestableComponent return Native::visit('/log'); }, 'follow-ada'], - 'Follow, on a profile' => [function (): TestableComponent { - serveApi([ - 'GET /api/v1/users/ada' => [['data' => userWithCountsJson(['id' => 'u2', 'handle' => 'ada', 'name' => 'Ada']), 'is_following' => false]], - 'GET /api/v1/users/ada/commits' => [pageJson([])], - ]); - - return Native::visit('/log/users/ada'); - }, 'follow'], 'Follow, in a profile\'s followers' => [function (): TestableComponent { serveApi(['GET /api/v1/users/ada/followers' => [pageJson([userJson(['id' => 'u3', 'handle' => 'grace', 'name' => 'Grace', 'is_followed' => false, 'follows_you' => false])])]]); @@ -193,3 +185,27 @@ function laneLog(): TestableComponent expect(buttonProps(Native::visit('/profile/device', platform: 'ios'), 'unlink-apple')['size'] ?? null)->toBe('lg'); }); + +it('fills Follow on a profile and an organization with your lane, with a label that reads on it', function (string $path, array $api, int $lane) { + signIn(['lane' => $lane]); + serveApi($api); + + $screen = finishRefreshes(Native::visit($path)); + $pill = nodeByRef($screen, 'follow-pill'); + $label = findNode($pill, fn (array $node): bool => ($node['type'] ?? null) === 'text'); + + expect(strtolower($pill['style']['bg_color']))->toBe(strtolower(config("native-ui.theme.light.lane-{$lane}"))) + ->and(strtolower($label['props']['color']))->toBe(strtolower(config("native-ui.theme.light.on-lane-{$lane}"))); +})->with([ + 'a profile' => ['/log/users/ada', [ + 'GET /api/v1/users/ada' => [['data' => userWithCountsJson(['id' => 'u2', 'handle' => 'ada', 'name' => 'Ada']), 'is_following' => false]], + 'GET /api/v1/users/ada/commits' => [pageJson([])], + ]], + 'an organization' => ['/log/organizations/laravel', [ + 'GET /api/v1/organizations/laravel' => [['data' => ['handle' => 'laravel', 'name' => 'Laravel', 'type' => 'organization', 'followers_count' => 1], 'is_following' => false]], + 'GET /api/v1/organizations/laravel/commits' => [pageJson([])], + ]], +])->with([ + 'green, labelled in ink' => 1, + 'rose, labelled in white' => 4, +]); diff --git a/tests/Feature/Screens/OrganizationTest.php b/tests/Feature/Screens/OrganizationTest.php index 2a8fc540..f118bd1f 100644 --- a/tests/Feature/Screens/OrganizationTest.php +++ b/tests/Feature/Screens/OrganizationTest.php @@ -141,14 +141,20 @@ function tapOrganizationTab(TestableComponent $screen, string $tab): TestableCom ->and($screen->instance()->organization->followersCount)->toBe(45); }); -it('shares the organization page and opens its admins', function () { +it('shares the organization page from its own button in the nav bar, and opens its admins', function () { fakeApi([ 'GET /api/v1/organizations/laravel' => [organizationJson()], 'GET /api/v1/organizations/laravel/commits' => [pageJson([])], ]); - finishRefreshes(Native::visit('/log/organizations/laravel')) - ->tap('share') + $screen = finishRefreshes(Native::visit('/log/organizations/laravel', platform: 'ios')); + $actions = findNodes($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'top_bar_action'); + + expect(array_map(fn (array $node): string => $node['props']['id'], $actions))->toBe(['share']) + ->and($actions[0]['props'])->toMatchArray(['icon' => 'custom:share', 'a11y_label' => 'Share @laravel']) + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'share'))->toBeNull(); + + $screen->press('share') ->assertNativeCalled('Share.Url', fn (array $params): bool => $params['url'] === 'http://devnull.test/@laravel') ->tap('admin-nunomaduro') ->assertNavigatedTo('/log/users/nunomaduro'); diff --git a/tests/Feature/Screens/ProfileCacheTest.php b/tests/Feature/Screens/ProfileCacheTest.php index 9820272e..9f1bed47 100644 --- a/tests/Feature/Screens/ProfileCacheTest.php +++ b/tests/Feature/Screens/ProfileCacheTest.php @@ -76,7 +76,7 @@ function serveAda(array $commits, int $followers = 5): void ->assertSee('@ada') ->assertSee('Wrote the first program.') ->assertMissingElement('row', fn (array $node): bool => ($node['ref'] ?? null) === 'counts') - ->assertMissingElement('button', fn (array $node): bool => ($node['ref'] ?? null) === 'follow') + ->assertMissingElement('pressable', fn (array $node): bool => ($node['ref'] ?? null) === 'follow') ->assertElement('row', fn (array $node): bool => ($node['ref'] ?? null) === 'loading-1') ->assertMissingElement('column', fn (array $node): bool => ($node['ref'] ?? null) === 'loading-profile'); @@ -84,7 +84,7 @@ function serveAda(array $commits, int $followers = 5): void finishRefreshes($profile) ->assertElement('row', fn (array $node): bool => ($node['ref'] ?? null) === 'counts') - ->assertElement('button', fn (array $node): bool => ($node['ref'] ?? null) === 'follow') + ->assertElement('pressable', fn (array $node): bool => ($node['ref'] ?? null) === 'follow') ->assertSee('Analytical engine notes'); expect(showsLoading(showingProfile($profile)))->toBeFalse(); diff --git a/tests/Feature/Screens/ProfileStandingTest.php b/tests/Feature/Screens/ProfileStandingTest.php index f09af3f0..ed0312af 100644 --- a/tests/Feature/Screens/ProfileStandingTest.php +++ b/tests/Feature/Screens/ProfileStandingTest.php @@ -98,23 +98,54 @@ function standingJson(array $extra = []): array expect(childRefs($screen, 'sheet-badges'))->toBe(['sheet-badge-init', 'sheet-badge-stdout', 'sheet-badge-max_payload']); })->with(['earned' => [true, '+1 more'], 'none earned' => [false, 'View achievements']]); -it('opens tagged bio and company accounts on GitHub rather than as devnull users', function (string $ref, string $url) { +it('draws the accounts a bio and company tag as badges with their GitHub icon, words between them', function () { $json = standingJson(); - $json['data']['bio'] = 'Builds @laravel with @nunomaduro.'; + $json['data']['bio'] = "Builds @laravel, with @nunomaduro.\nTea first."; $json['data']['company'] = '@nativephp'; fakeApi(['GET /api/v1/users/ada' => [$json], 'GET /api/v1/users/ada/commits' => [pageJson([])]]); - Native::visit('/log/users/ada')->tap($ref) - ->assertNativeCalled('Browser.OpenInApp', fn (array $params): bool => $params['url'] === $url) - ->assertNoNavigation(); + $screen = Native::visit('/log/users/ada'); + $badge = nodeByRef($screen, 'profile-bio-mention-0'); + $icon = findNode($badge, fn (array $node): bool => ($node['type'] ?? null) === 'image'); + $texts = fn (string $ref): array => array_values(array_filter(array_map( + fn (array $node): ?string => $node['props']['text'] ?? null, + findNodes(nodeByRef($screen, $ref), fn (array $node): bool => ($node['type'] ?? null) === 'text'), + ))); + + expect($icon['props']['src'] ?? $icon['props']['url'] ?? null)->toContain('https://github.com/laravel.png') + ->and($texts('profile-bio'))->toBe(['Builds', 'laravel', ',', 'with', 'nunomaduro', '.', 'Tea', 'first.']) + ->and(nodeByRef($screen, 'profile-company-text-mention-0'))->not->toBeNull(); +}); + +it('opens a tagged account that has a page on devnull here in the app, and anything else on GitHub, as the web links them', function (array $types, string $ref, ?string $screenPath, ?string $url) { + $json = standingJson([ + 'bio_profiles' => ['laravel' => 'laravel', 'nunomaduro' => 'nunomaduro', 'taylor' => 'taylor'], + ...($types === [] ? [] : ['bio_profile_types' => $types]), + ]); + $json['data']['bio'] = 'Builds @Laravel with @nunomaduro, @taylor and @nativephp.'; + fakeApi(['GET /api/v1/users/ada' => [$json], 'GET /api/v1/users/ada/commits' => [pageJson([])]]); + + $screen = Native::visit('/log/users/ada')->tap($ref); + + if ($screenPath !== null) { + $screen->assertNavigatedTo($screenPath)->assertNativeNotCalled('Browser.OpenInApp'); + } else { + $screen->assertNoNavigation()->assertNativeCalled('Browser.OpenInApp', fn (array $params): bool => $params['url'] === $url); + } })->with([ - 'bio' => ['profile-bio-mention-7', 'https://github.com/laravel'], - 'company' => ['profile-company-text-mention-0', 'https://github.com/nativephp'], + 'a page of unknown kind opens as a user' => [[], 'profile-bio-mention-0', '/log/users/Laravel', null], + 'an organization' => [['laravel' => 'organization'], 'profile-bio-mention-0', '/log/organizations/Laravel', null], + 'a user' => [['nunomaduro' => 'user'], 'profile-bio-mention-1', '/log/users/nunomaduro', null], + 'an unclaimed developer' => [['taylor' => 'unclaimed'], 'profile-bio-mention-2', null, 'https://github.com/taylor'], + 'no page on devnull' => [[], 'profile-bio-mention-3', null, 'https://github.com/nativephp'], ]); -it('ignores profile mention actions for accounts that are not in the bio or company', function () { - fakeApi(['GET /api/v1/users/ada' => [standingJson()], 'GET /api/v1/users/ada/commits' => [pageJson([])]]); - Native::visit('/log/users/ada')->call('openGitHubMention', 'nobody')->assertNativeNotCalled('Browser.OpenInApp'); +it('ignores tag taps for accounts that are not in the bio or company', function () { + fakeApi(['GET /api/v1/users/ada' => [standingJson(['bio_profiles' => ['nobody' => 'nobody']])], 'GET /api/v1/users/ada/commits' => [pageJson([])]]); + + Native::visit('/log/users/ada')->call('openBioMention', 'nobody') + ->assertNativeNotCalled('Browser.OpenInApp') + ->assertNoNavigation(); }); it('marks a profile you mute, as the web does', function () { diff --git a/tests/Feature/Screens/ProfileTest.php b/tests/Feature/Screens/ProfileTest.php index eea451e5..87f8ab45 100644 --- a/tests/Feature/Screens/ProfileTest.php +++ b/tests/Feature/Screens/ProfileTest.php @@ -1,6 +1,8 @@ [fn (): array => [profileJson()], fn (): array => []], "devnull couldn't send it yet" => [fn (): array => [['message' => 'Server Error'], 500], fn (): array => ['user' => User::fromArray(userJson(['handle' => 'ada', 'name' => 'Ada Lovelace']))]], ]); + +it('opens the profile picture full-screen from the avatar, at the 1024 pixels the web asks GitHub for', function () { + fakeApi([ + 'GET /api/v1/users/ada' => [profileJson(user: ['avatar_url' => 'https://avatars.githubusercontent.com/u/42?v=4'])], + 'GET /api/v1/users/ada/commits' => [pageJson([])], + ]); + + $screen = Native::visit('/log/users/ada')->tap('profile-picture'); + + expect(nodeByRef($screen, 'image-viewer')['props']['visible'])->toBeTrue() + ->and(nodeByRef($screen, 'viewed-image-0')['props'])->toMatchArray([ + 'src' => 'https://avatars.githubusercontent.com/u/42?v=4&s=1024', + 'alt' => "Ada Lovelace's profile picture", + ]); + + $screen->assertNativeNotCalled('Browser.OpenInApp'); +}); + +it('leaves an avatar that is not on GitHub as it is, and a profile with none has nothing to open', function () { + fakeApi([ + 'GET /api/v1/users/ada' => [profileJson(user: ['avatar_url' => 'https://img.test/ada.png'])], + 'GET /api/v1/users/ada/commits' => [pageJson([])], + 'GET /api/v1/users/bob' => [profileJson(user: ['id' => 'u3', 'handle' => 'bob', 'avatar_url' => null])], + 'GET /api/v1/users/bob/commits' => [pageJson([])], + ]); + + $screen = Native::visit('/log/users/ada')->tap('profile-picture'); + + expect(nodeByRef($screen, 'viewed-image-0')['props']['src'])->toBe('https://img.test/ada.png'); + + $bob = Native::visit('/log/users/bob'); + + expect(findNode($bob->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'profile-picture'))->toBeNull(); + expect($bob->call('viewProfilePicture')->instance()->viewerOpen)->toBeFalse(); +}); + +it('draws Follow in your colour on glass on iOS, and Unfollow on clear glass, both 40pt pills', function (string $platform, bool $glass) { + fakeApi([ + 'GET /api/v1/users/ada' => [profileJson()], + 'GET /api/v1/users/ada/commits' => [pageJson([])], + 'POST /api/v1/users/ada/follow' => [null, 204], + ]); + + $screen = Native::visit('/log/users/ada', platform: $platform); + $pill = nodeByRef($screen, 'follow-pill'); + $mine = config('native-ui.theme.light.'.Lane::token(app(Account::class)->user()?->lane())); + + expect((float) $pill['layout']['height'])->toBe(40.0) + ->and($pill['style']['bg_color'] ?? null)->toBe($mine) + ->and(($pill['props']['glass'] ?? 0) !== 0)->toBe($glass); + + $pill = nodeByRef($screen->tap('follow'), 'follow-pill'); + + expect(($pill['props']['glass'] ?? 0) !== 0)->toBe($glass) + ->and($pill['style']['bg_color'] ?? null)->toBe($glass ? null : config('native-ui.theme.light.surface-variant')); +})->with(['iOS' => ['ios', true], 'Android' => ['android', false]]); From a6a75e9dc246d152cbf96da11814890088e19acb Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Wed, 18 Nov 2026 19:51:20 +0000 Subject: [PATCH 3/8] Double tap to zoom in the image viewer, and grow it out of the thumbnail A double tap on an image at its whole size zooms to half the most it zooms (twice), with the tapped point brought to the middle as far as the picture's bounds allow. A double tap on a zoomed image goes back to its whole size. Both animate on the phone and report through the same @pinchEnd as a pinch, so the pans bind and let go as before. The viewer no longer slides up. The black fades in over the screen while the tapped picture grows out of its thumbnail into place, and closing runs that backwards. After paging, it shrinks into the thumbnail of the image it's showing. With no thumbnail on screen it only fades. Each commit image now has a ref of its own (thumb-{id}) for this, beside the pressable's, and showImagesInViewer() takes those refs. Every page also hands its pans to the zoom as zoom-pan, which takes no drags. That's what lets a double tap at whole size aim, and it means the first pinch now zooms around the fingers rather than the middle. This needs NativePHP/mobile-ui#220 and #221 and NativePHP/mobile-air#716. Until they're in, mobile-ui ignores the new attributes: the viewer slides up as before and a double tap does nothing. Co-Authored-By: Claude Opus 5.5 --- app/Devnull/Data/CommitImage.php | 8 ++++ app/Devnull/ImageViewer.php | 5 +++ .../Concerns/ShowsCommits.php | 9 ++-- .../Concerns/ShowsImageViewer.php | 30 +++++++++---- .../native/partials/commit-media.blade.php | 7 +-- .../partials/image-viewer-pages.blade.php | 13 ++++-- .../native/partials/image-viewer.blade.php | 20 ++++++--- tests/Feature/Screens/ImageViewerTest.php | 43 +++++++++++++++++++ 8 files changed, 112 insertions(+), 23 deletions(-) diff --git a/app/Devnull/Data/CommitImage.php b/app/Devnull/Data/CommitImage.php index c758f783..d79e8482 100644 --- a/app/Devnull/Data/CommitImage.php +++ b/app/Devnull/Data/CommitImage.php @@ -50,6 +50,14 @@ public function label(int $index = 0, int $count = 1): string }; } + /** + * The ref of the image as a commit row draws it, which the image viewer grows out of and shrinks back into. + */ + public function thumbRef(): string + { + return 'thumb-'.$this->id; + } + /** * Width over height, so the space is held before the image loads, or if it never does. */ diff --git a/app/Devnull/ImageViewer.php b/app/Devnull/ImageViewer.php index c6c94631..05e1968e 100644 --- a/app/Devnull/ImageViewer.php +++ b/app/Devnull/ImageViewer.php @@ -22,4 +22,9 @@ final class ImageViewer * The most an image zooms, as many times its whole self. */ public const float MaxZoom = 4; + + /** + * How far a double tap zooms an image at its whole self: half the most it zooms. + */ + public const float DoubleTapZoom = self::MaxZoom / 2; } diff --git a/app/NativeComponents/Concerns/ShowsCommits.php b/app/NativeComponents/Concerns/ShowsCommits.php index 2fc900e2..3553e05e 100644 --- a/app/NativeComponents/Concerns/ShowsCommits.php +++ b/app/NativeComponents/Concerns/ShowsCommits.php @@ -5,6 +5,7 @@ use App\Devnull\Account; use App\Devnull\Client; use App\Devnull\Data\Commit; +use App\Devnull\Data\CommitImage; use App\Devnull\Data\Pasteis; use App\Devnull\Data\User; use App\Devnull\Display; @@ -277,12 +278,14 @@ public function playNataNullers(): void /** * Opens a commit's image full-screen in the app (see ShowsImageViewer), from - * the one the row tapped. An image the screen isn't showing, or one at no - * web address, opens nothing, as it did in the browser. + * the one the row tapped, which it grows out of. An image the screen isn't + * showing, or one at no web address, opens nothing, as it did in the browser. */ public function openImage(string $id, int $index = 0): void { - $this->showImagesInViewer($this->shownCommit($id)?->images ?? [], $index); + $images = $this->shownCommit($id)?->images ?? []; + + $this->showImagesInViewer($images, $index, array_map(fn (CommitImage $image): string => $image->thumbRef(), $images)); } /** diff --git a/app/NativeComponents/Concerns/ShowsImageViewer.php b/app/NativeComponents/Concerns/ShowsImageViewer.php index 7f68a42c..e22a5fe9 100644 --- a/app/NativeComponents/Concerns/ShowsImageViewer.php +++ b/app/NativeComponents/Concerns/ShowsImageViewer.php @@ -20,12 +20,13 @@ /** * Images full-screen, over everything else on the screen, sheet included (see partials/image-viewer): a commit's, * or a message's, from the one tapped. Any screen can show it: use this trait, include the partial once, and call - * showImagesInViewer() with the images and the one to start from. + * showImagesInViewer() with the images, the one to start from, and the refs of the images on the screen they were + * opened from, which the viewer grows out of as it opens and shrinks back into as it closes. * * Swiping sideways pages through the images, which the dashes under them follow. A pinch zooms one between its whole - * self and four times, and a zoomed one pans. Dragging one up or down at its whole self takes the viewer with it, and - * letting go far enough, or flicking it, closes the viewer. The round buttons over the top close it and save the - * image to the phone's photos. + * self and four times, a double tap zooms to twice and back, and a zoomed one pans. Dragging one up or down at its + * whole self takes the viewer with it, and letting go far enough, or flicking it, closes the viewer. The round buttons + * over the top close it and save the image to the phone's photos. */ trait ShowsImageViewer { @@ -47,6 +48,15 @@ trait ShowsImageViewer */ public int $viewerIndex = 0; + /** + * The ref of the image on the screen each of the viewer's images was opened from, by place: the picture grows + * out of the showing one's as the viewer opens, and shrinks back into it as it closes. An image with none, or + * whose one is off screen, fades in and out instead. + * + * @var array + */ + public array $viewerSources = []; + /** * The zoom and pan of each image, by its place, driven on the phone by its page's gesture area. Fresh ones when * the viewer opens and when a page is left, so each image starts at rest; emptied on close. @@ -82,12 +92,14 @@ trait ShowsImageViewer public bool $savingViewedImage = false; /** - * Opens the viewer on $images, from the one at $index. An image at no web address opens nothing, and the viewer - * never pages to one. + * Opens the viewer on $images, from the one at $index. $sources are the refs of the `native:image`s on the screen + * they were tapped in, in the same order. An image at no web address opens nothing, and the viewer never pages + * to one. * * @param list $images + * @param list $sources */ - public function showImagesInViewer(array $images, int $index = 0): void + public function showImagesInViewer(array $images, int $index = 0, array $sources = []): void { $images = array_values($images); $image = $images[$index] ?? null; @@ -98,6 +110,7 @@ public function showImagesInViewer(array $images, int $index = 0): void $this->viewerImages = $images; $this->viewerIndex = $index; + $this->viewerSources = array_slice(array_values($sources), 0, count($images)); $this->viewerZooms = $this->viewerPansX = $this->viewerPansY = []; foreach (array_keys($images) as $place) { @@ -128,7 +141,7 @@ public function viewerPaged(int $index): void } /** - * A pinch on the showing image ended, at $scale. + * A pinch or a double tap on the showing image ended, at $scale. */ public function viewerZoomEnded(float $scale): void { @@ -155,6 +168,7 @@ public function closeImageViewer(): void $this->viewerOpen = false; $this->viewerImages = []; $this->viewerIndex = 0; + $this->viewerSources = []; $this->viewerZooms = $this->viewerPansX = $this->viewerPansY = []; $this->viewerZoomed = false; $this->viewerDrag = null; diff --git a/resources/views/native/partials/commit-media.blade.php b/resources/views/native/partials/commit-media.blade.php index 0637bfad..cb3b42ca 100644 --- a/resources/views/native/partials/commit-media.blade.php +++ b/resources/views/native/partials/commit-media.blade.php @@ -4,7 +4,8 @@ A reply in a thread shows only its images and link preview ($withEmbeds false), as the web's thread does. Images hold their space at their aspect ratio on a wash, so one that fails to load leaves the row as it was. Each is read out by the description its author gave it, as the web's alt text. Images come from the device once ImageCache has - them, so they don't load again each time they scroll into view. + them, so they don't load again each time they scroll into view. Each image has a ref of its own for the image viewer + to grow out of and shrink back into (see Concerns\ShowsImageViewer). --}} @if ($commit->scoreCard) @include('native.partials.score-card') @@ -14,7 +15,7 @@ @if (count($images) === 1) - + @elseif (count($images) > 1) @@ -25,7 +26,7 @@ @foreach ($column as $image) @php($index = array_search($image, $images, true)) - + @endforeach diff --git a/resources/views/native/partials/image-viewer-pages.blade.php b/resources/views/native/partials/image-viewer-pages.blade.php index de5647cd..ec83934b 100644 --- a/resources/views/native/partials/image-viewer-pages.blade.php +++ b/resources/views/native/partials/image-viewer-pages.blade.php @@ -1,10 +1,12 @@ {{-- The image viewer's pages, one image each, moved up and down together by the drag to close (see image-viewer). - Each image pinches on its own gesture area. Only the showing image, once zoomed, binds a pan: an area with a pan - claims every touch, which would stop the pager paging and the drag to close. So the first pinch on an image zooms - around its middle, and later ones around the fingers. An image at no web address gets an empty page, never asked - for (the pager can't skip a page, and the viewer never moves to it). + Each image pinches, and zooms on a double tap, on its own gesture area. Only the showing image, once zoomed, binds a + pan: an area with a pan claims every touch, which would stop the pager paging and the drag to close. The zoom gets + the same pans as zoom-pan, which takes no drags, so a pinch zooms around the fingers and a double tap aims at the + tapped point from the first. Either one reports where it left the zoom through @pinchEnd, which binds the pans or + lets them go. An image at no web address gets an empty page, never asked for (the pager can't skip a page, and the + viewer never moves to it). --}} @@ -17,9 +19,12 @@ :pinch="$viewerZooms[$place]" pinch-min="1" :pinch-max="\App\Devnull\ImageViewer::MaxZoom" + :double-tap-zoom="\App\Devnull\ImageViewer::DoubleTapZoom" @pinchEnd="viewerZoomEnded" :pan-x="$pans ? $viewerPansX[$place] : null" :pan-y="$pans ? $viewerPansY[$place] : null" + :zoom-pan-x="$viewerPansX[$place]" + :zoom-pan-y="$viewerPansY[$place]" bounded :content-ratio="$image->naturalRatio()" class="w-full h-full" diff --git a/resources/views/native/partials/image-viewer.blade.php b/resources/views/native/partials/image-viewer.blade.php index d30a0ca8..72c15064 100644 --- a/resources/views/native/partials/image-viewer.blade.php +++ b/resources/views/native/partials/image-viewer.blade.php @@ -2,11 +2,21 @@ Images full-screen, over everything else on the screen, sheet included (see Concerns\ShowsImageViewer), on black that reaches every edge. Any screen can hang it: use the trait and include this once. + It doesn't slide up. The black fades in over the screen while the tapped picture grows out of the image it was + tapped in (morph-from, the source's ref) into its place here (morph-to), and closing runs that backwards: the black + fades out while the picture shrinks back into the image on the screen. Paged to another image, it shrinks into + that one's. With no source, or one that has gone off screen, it only fades. + + The fade, the morph, the double tap and the zoom's own pan need NativePHP/mobile-ui#221, mobile-ui#220 and + NativePHP/mobile-air#716. Without them the modal ignores transition and morph-*, and the gesture area ignores + double-tap-zoom and zoom-pan-*, so the viewer slides up as before and a double tap does nothing. + A swipe sideways pages through the images, one per page, and the dashes at the bottom say which is showing, the - bright one sliding along as the page changes. A pinch zooms an image between its whole self and four times, - around the fingers once it's zoomed, and a zoomed image pans; both run on the phone with no frame trip. Bounded by - the picture's own shape, it can't be lost off screen. Zoomed, a drag pans rather than pages or closes, so the - pager and the drag to close only take over again once a pinch brings it back to its whole self. + bright one sliding along as the page changes. A pinch zooms an image between its whole self and four times, and a + double tap at its whole self zooms to twice, aimed at the tapped point; a double tap on a zoomed image takes it + back to its whole self. A zoomed image pans. All of it runs on the phone with no frame trip. Bounded by the + picture's own shape, it can't be lost off screen. Zoomed, a drag pans rather than pages or closes, so the pager and + the drag to close only take over again once a pinch or a double tap brings it back to its whole self. At its whole self, a drag up or down takes the image with the finger and fades the black and the buttons with it. Let go short of halfway to ImageViewer::DismissDistance and it springs back; past that, or with a flick, it carries on @@ -20,7 +30,7 @@ so its pages coming and going don't shift the ids of whatever the screen draws after it. --}} @php($viewerOwnRow = \Native\Mobile\Platform::isAndroid()) - + @if ($viewerImages !== []) @php($far = \App\Devnull\ImageViewer::DismissDistance) @php($count = count($viewerImages)) diff --git a/tests/Feature/Screens/ImageViewerTest.php b/tests/Feature/Screens/ImageViewerTest.php index 29b5b9dd..ba2972f5 100644 --- a/tests/Feature/Screens/ImageViewerTest.php +++ b/tests/Feature/Screens/ImageViewerTest.php @@ -1,6 +1,7 @@ and(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-id'); }); +it('takes a double tap\'s zoom as it takes a pinch\'s, to twice and back to its whole self', function () { + $screen = logWithImages(2)->tap('image-i1'); + + // A double tap zooms to half the most an image zooms, and says so through the pinch's end. + expect(ImageViewer::DoubleTapZoom)->toBe(ImageViewer::MaxZoom / 2); + + $screen->pinch('viewer-gestures-0', ImageViewer::DoubleTapZoom); + + expect($screen->instance()->viewerZoomed)->toBeTrue() + ->and(nodeByRef($screen, 'viewer-gestures-0')['props']['pan-x-id'])->toBe($screen->instance()->viewerPansX[0]->id) + ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->not->toHaveKey('pan-y-id'); + + $screen->pinch('viewer-gestures-0', 1.0); + + expect($screen->instance()->viewerZoomed)->toBeFalse() + ->and(nodeByRef($screen, 'viewer-gestures-0')['props'])->not->toHaveKey('pan-x-id') + ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-id'); +}); + +it('grows out of the image the row was tapped in, and shrinks back into whichever image it has paged to', function () { + $screen = logWithImages(3); + + // Each of the row's images has a ref of its own, beside the pressable's, for the viewer to grow out of. + expect(nodeByRef($screen, 'thumb-i1')['props'])->toMatchArray(['src' => 'https://img.test/1', 'fit' => 2]) + ->and(nodeByRef($screen, 'thumb-i3')['props']['src'])->toBe('https://img.test/3'); + + $screen->tap('image-i2'); + + $viewing = $screen->instance(); + + expect($viewing->viewerSources)->toBe(['thumb-i1', 'thumb-i2', 'thumb-i3']) + ->and($viewing->viewerSources[$viewing->viewerIndex])->toBe('thumb-i2'); + + $screen->changeTab('viewerPaged', 2); + + expect($screen->instance()->viewerSources[$screen->instance()->viewerIndex])->toBe('thumb-i3'); + + $screen->dismissSheet('image-viewer'); + + expect($screen->instance()->viewerSources)->toBe([]); +}); + it('closes when the image is dragged far enough up or down, and springs back from a short drag', function (float $settled, bool $closes) { $screen = logWithImages(2)->tap('image-i1'); From 6b2b7518fdfb0a01a56f235182c423bfc7b9df65 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Wed, 18 Nov 2026 19:56:16 +0000 Subject: [PATCH 4/8] Grow the profile picture out of the header's avatar in the viewer The viewer now fades in and grows the picture out of the image it was opened from, and shrinks back into it on close (from feat/picture-viewer). Name the header's avatar so the profile picture does that too. Other avatars stay unnamed. Co-Authored-By: Claude Opus 5.5 --- app/NativeComponents/Profile.php | 7 ++++++- resources/views/native/partials/avatar.blade.php | 5 +++-- .../views/native/partials/profile-header.blade.php | 2 +- tests/Feature/Screens/ProfileTest.php | 11 +++++++++-- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/app/NativeComponents/Profile.php b/app/NativeComponents/Profile.php index b800b854..cd18a7bf 100644 --- a/app/NativeComponents/Profile.php +++ b/app/NativeComponents/Profile.php @@ -109,6 +109,11 @@ class Profile extends NativeComponent */ public const int ProfilePicturePixels = 1024; + /** + * The ref of the avatar in the profile's header, which the image viewer grows the profile picture out of. + */ + public const string ProfilePictureRef = 'profile-picture-image'; + /** * The alerts the safety menu confirms with, as the web words them. Each one's id names the profile too, so an * answer only reaches the profile that asked. @@ -653,7 +658,7 @@ public function viewProfilePicture(): void width: self::ProfilePicturePixels, height: self::ProfilePicturePixels, description: "{$user->name}'s profile picture", - )]); + )], sources: [self::ProfilePictureRef]); } public function openGitHubProfile(): void diff --git a/resources/views/native/partials/avatar.blade.php b/resources/views/native/partials/avatar.blade.php index b156675f..b41454a6 100644 --- a/resources/views/native/partials/avatar.blade.php +++ b/resources/views/native/partials/avatar.blade.php @@ -1,7 +1,8 @@ {{-- A person as a circle: their GitHub avatar on the wash, kept on the device for a day (see ImageCache), or their initial while it loads. An organization is a rounded square edged with a hairline instead, as the web draws it, so - it never passes for a person. The image sits inside the hairline, as the web's does. + it never passes for a person. The image sits inside the hairline, as the web's does. $imageRef names the image, for + the image viewer to grow out of (see Profile::viewProfilePicture). --}} @php($size ??= 40) @php($organization = $user->isOrganization) @@ -9,6 +10,6 @@ {{ mb_strtoupper(mb_substr($user->name, 0, 1)) }} @if ($user->avatarUrl) - + @endif diff --git a/resources/views/native/partials/profile-header.blade.php b/resources/views/native/partials/profile-header.blade.php index abeac50f..1f97c19a 100644 --- a/resources/views/native/partials/profile-header.blade.php +++ b/resources/views/native/partials/profile-header.blade.php @@ -27,7 +27,7 @@ - @include('native.partials.avatar', ['user' => $user, 'size' => 80]) + @include('native.partials.avatar', ['user' => $user, 'size' => 80, 'imageRef' => \App\NativeComponents\Profile::ProfilePictureRef]) diff --git a/tests/Feature/Screens/ProfileTest.php b/tests/Feature/Screens/ProfileTest.php index 87f8ab45..bcdefd8e 100644 --- a/tests/Feature/Screens/ProfileTest.php +++ b/tests/Feature/Screens/ProfileTest.php @@ -3,6 +3,7 @@ use App\Devnull\Account; use App\Devnull\Data\User; use App\Devnull\Lane; +use App\NativeComponents\Profile; use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; use Native\Mobile\Testing\Native; @@ -512,13 +513,19 @@ function adaCommitJson(array $overrides = []): array 'GET /api/v1/users/ada/commits' => [pageJson([])], ]); - $screen = Native::visit('/log/users/ada')->tap('profile-picture'); + $screen = Native::visit('/log/users/ada'); + + // The header's avatar is named, so the viewer grows the picture out of it. + expect(nodeByRef($screen, Profile::ProfilePictureRef)['type'])->toBe('image'); + + $screen->tap('profile-picture'); expect(nodeByRef($screen, 'image-viewer')['props']['visible'])->toBeTrue() ->and(nodeByRef($screen, 'viewed-image-0')['props'])->toMatchArray([ 'src' => 'https://avatars.githubusercontent.com/u/42?v=4&s=1024', 'alt' => "Ada Lovelace's profile picture", - ]); + ]) + ->and($screen->instance()->viewerSources)->toBe([Profile::ProfilePictureRef]); $screen->assertNativeNotCalled('Browser.OpenInApp'); }); From 621d53a9a56cd4ec478f07bdf15a1c753accd4f6 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Thu, 19 Nov 2026 22:23:02 +0000 Subject: [PATCH 5/8] Spell the viewer's double tap zoom @doubleTap.zoom mobile-air#716 renamed `double-tap-zoom` to `@doubleTap.zoom`. The pinch names stay, since they work with and without that PR. Co-Authored-By: Claude Opus 5.5 --- resources/views/native/partials/image-viewer-pages.blade.php | 2 +- resources/views/native/partials/image-viewer.blade.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/views/native/partials/image-viewer-pages.blade.php b/resources/views/native/partials/image-viewer-pages.blade.php index ec83934b..62dee886 100644 --- a/resources/views/native/partials/image-viewer-pages.blade.php +++ b/resources/views/native/partials/image-viewer-pages.blade.php @@ -19,7 +19,7 @@ :pinch="$viewerZooms[$place]" pinch-min="1" :pinch-max="\App\Devnull\ImageViewer::MaxZoom" - :double-tap-zoom="\App\Devnull\ImageViewer::DoubleTapZoom" + @doubleTap.zoom="{{ \App\Devnull\ImageViewer::DoubleTapZoom }}" @pinchEnd="viewerZoomEnded" :pan-x="$pans ? $viewerPansX[$place] : null" :pan-y="$pans ? $viewerPansY[$place] : null" diff --git a/resources/views/native/partials/image-viewer.blade.php b/resources/views/native/partials/image-viewer.blade.php index 72c15064..8fbc9529 100644 --- a/resources/views/native/partials/image-viewer.blade.php +++ b/resources/views/native/partials/image-viewer.blade.php @@ -9,7 +9,7 @@ The fade, the morph, the double tap and the zoom's own pan need NativePHP/mobile-ui#221, mobile-ui#220 and NativePHP/mobile-air#716. Without them the modal ignores transition and morph-*, and the gesture area ignores - double-tap-zoom and zoom-pan-*, so the viewer slides up as before and a double tap does nothing. + @doubleTap.zoom and zoom-pan-*, so the viewer slides up as before and a double tap does nothing. A swipe sideways pages through the images, one per page, and the dashes at the bottom say which is showing, the bright one sliding along as the page changes. A pinch zooms an image between its whole self and four times, and a From b25a039ec60315826a1047da4301ff4334f361e7 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Fri, 20 Nov 2026 01:46:16 +0000 Subject: [PATCH 6/8] Keep the viewer's pans bound and let the phone decide who gets a drag With NativePHP/mobile-ui#220 and NativePHP/mobile-air#716, a bounded gesture area only takes a one-finger drag while its zoomed image has room to move, so at whole size the pager pages and the drag to close closes with the pans bound. Each page now binds its pans all the time. $viewerZoomed, viewerZoomEnded(), ImageViewer::ZoomedPast, @pinchEnd, zoom-pan and the swapped close area are gone. This needs those two PRs: without them a bound pan takes every drag, so the pager wouldn't page and the drag to close wouldn't close. Co-Authored-By: Claude Opus 5.5 --- app/Devnull/ImageViewer.php | 5 -- .../Concerns/ShowsImageViewer.php | 26 ++---- .../partials/image-viewer-pages.blade.php | 20 ++--- .../native/partials/image-viewer.blade.php | 25 +++--- tests/Feature/Screens/ImageViewerTest.php | 84 ++++++++----------- 5 files changed, 58 insertions(+), 102 deletions(-) diff --git a/app/Devnull/ImageViewer.php b/app/Devnull/ImageViewer.php index 05e1968e..9996de56 100644 --- a/app/Devnull/ImageViewer.php +++ b/app/Devnull/ImageViewer.php @@ -13,11 +13,6 @@ final class ImageViewer */ public const float DismissDistance = 240; - /** - * The zoom past which an image counts as zoomed in, so a pinch that ends a hair over its whole self still pages. - */ - public const float ZoomedPast = 1.01; - /** * The most an image zooms, as many times its whole self. */ diff --git a/app/NativeComponents/Concerns/ShowsImageViewer.php b/app/NativeComponents/Concerns/ShowsImageViewer.php index e22a5fe9..1e555b19 100644 --- a/app/NativeComponents/Concerns/ShowsImageViewer.php +++ b/app/NativeComponents/Concerns/ShowsImageViewer.php @@ -25,8 +25,9 @@ * * Swiping sideways pages through the images, which the dashes under them follow. A pinch zooms one between its whole * self and four times, a double tap zooms to twice and back, and a zoomed one pans. Dragging one up or down at its - * whole self takes the viewer with it, and letting go far enough, or flicking it, closes the viewer. The round buttons - * over the top close it and save the image to the phone's photos. + * whole self takes the viewer with it, and letting go far enough, or flicking it, closes the viewer. Whether a drag + * pans, pages or closes is the phone's call, made from how far the image is zoomed, so PHP never hears about a zoom. + * The round buttons over the top close it and save the image to the phone's photos. */ trait ShowsImageViewer { @@ -75,12 +76,6 @@ trait ShowsImageViewer */ public array $viewerPansY = []; - /** - * Whether the showing image is zoomed in, as its last pinch left it. Zoomed, a drag pans it; at its whole self a - * drag sideways pages and a drag up or down closes. - */ - public bool $viewerZoomed = false; - /** * How far the image has been dragged up or down to close the viewer, on the phone. */ @@ -117,15 +112,14 @@ public function showImagesInViewer(array $images, int $index = 0, array $sources $this->restViewerImage($place); } - $this->viewerZoomed = false; $this->viewerDrag = SharedValue::make(); $this->savingViewedImage = false; $this->viewerOpen = true; } /** - * The pager settled on another image. The one left goes back to rest, as Photos puts it, and the one arrived at - * starts unzoomed. An image at no web address can't be paged to: the viewer stays where it was. + * The pager settled on another image. The one left goes back to rest, as Photos puts it, so it's whole again when + * the pager comes back to it. An image at no web address can't be paged to: the viewer stays where it was. */ public function viewerPaged(int $index): void { @@ -137,15 +131,6 @@ public function viewerPaged(int $index): void $this->restViewerImage($this->viewerIndex); $this->viewerIndex = $index; - $this->viewerZoomed = false; - } - - /** - * A pinch or a double tap on the showing image ended, at $scale. - */ - public function viewerZoomEnded(float $scale): void - { - $this->viewerZoomed = $this->viewerOpen && $scale > ImageViewer::ZoomedPast; } /** @@ -170,7 +155,6 @@ public function closeImageViewer(): void $this->viewerIndex = 0; $this->viewerSources = []; $this->viewerZooms = $this->viewerPansX = $this->viewerPansY = []; - $this->viewerZoomed = false; $this->viewerDrag = null; $this->savingViewedImage = false; } diff --git a/resources/views/native/partials/image-viewer-pages.blade.php b/resources/views/native/partials/image-viewer-pages.blade.php index 62dee886..84b5121e 100644 --- a/resources/views/native/partials/image-viewer-pages.blade.php +++ b/resources/views/native/partials/image-viewer-pages.blade.php @@ -1,17 +1,16 @@ {{-- The image viewer's pages, one image each, moved up and down together by the drag to close (see image-viewer). - Each image pinches, and zooms on a double tap, on its own gesture area. Only the showing image, once zoomed, binds a - pan: an area with a pan claims every touch, which would stop the pager paging and the drag to close. The zoom gets - the same pans as zoom-pan, which takes no drags, so a pinch zooms around the fingers and a double tap aims at the - tapped point from the first. Either one reports where it left the zoom through @pinchEnd, which binds the pans or - lets them go. An image at no web address gets an empty page, never asked for (the pager can't skip a page, and the - viewer never moves to it). + Each image pinches, zooms on a double tap and pans on its own gesture area, with its pans bound all the time. + Bounded, the area only takes a one-finger drag while its zoomed image has room to move, so at its whole self a drag + goes to the pager or the drag to close, and zoomed in the same drag pans it. The pinch and the double tap aim with + those same pans: a pinch zooms around the fingers and a double tap aims at the tapped point. The phone does all of + it, so PHP isn't told when a zoom ends. An image at no web address gets an empty page, never asked for (the pager + can't skip a page, and the viewer never moves to it). --}} @foreach ($viewerImages as $place => $image) - @php($pans = $place === $viewerIndex && $viewerZoomed) @if (\App\Devnull\SiteLink::isWebUrl($image->url)) - @if ($viewerZoomed) - - @include('native.partials.image-viewer-pages') - - @else - - @include('native.partials.image-viewer-pages') - - @endif + + @include('native.partials.image-viewer-pages') + diff --git a/tests/Feature/Screens/ImageViewerTest.php b/tests/Feature/Screens/ImageViewerTest.php index ba2972f5..f39e1cec 100644 --- a/tests/Feature/Screens/ImageViewerTest.php +++ b/tests/Feature/Screens/ImageViewerTest.php @@ -1,7 +1,6 @@ and($image['props'])->toMatchArray(['src' => 'https://img.test/1', 'fit' => 1, 'alt' => 'A cat on a keyboard']) // Pinch bounded one to four, settled on the phone against the shared values this open made, kept on screen - // by the image's own shape. At its whole self it doesn't pan, so the pager and the drag to close get the drag. + // by the image's own shape. Its pans are bound from the start: bounded, the phone only lets it take a drag + // once it's zoomed in, so at its whole self the pager and the drag to close get the drag. ->and($gestures['props'])->toMatchArray(['pinch-min' => 1.0, 'pinch-max' => 4.0, 'bounded' => true, 'content-ratio' => 1.0]) ->and($gestures['props']['pinch-id'])->toBe($viewing->viewerZooms[0]->id) - ->and($gestures['props'])->not->toHaveKey('pan-x-id') - ->and($gestures['props'])->not->toHaveKey('pan-y-id') + ->and($gestures['props']['pan-x-id'])->toBe($viewing->viewerPansX[0]->id) + ->and($gestures['props']['pan-y-id'])->toBe($viewing->viewerPansY[0]->id) ->and($image['props']['scale_sv'])->toBe((string) $viewing->viewerZooms[0]) ->and($image['props']['translate-x_sv'])->toBe((string) $viewing->viewerPansX[0]) ->and($image['props']['translate-y_sv'])->toBe((string) $viewing->viewerPansY[0]) @@ -151,64 +151,48 @@ function imagedCommitImages(): array it('puts an image back at rest once the pager leaves it, as Photos does', function () { $screen = logWithImages(3)->tap('image-i1'); - $first = nodeByRef($screen, 'viewer-gestures-0')['props']['pinch-id']; - $second = nodeByRef($screen, 'viewer-gestures-1')['props']['pinch-id']; - - $screen->pinch('viewer-gestures-0', 2.5); - - expect($screen->instance()->viewerZoomed)->toBeTrue(); + $left = nodeByRef($screen, 'viewer-gestures-0')['props']; + $arrived = nodeByRef($screen, 'viewer-gestures-1')['props']; $screen->changeTab('viewerPaged', 1); - expect($screen->instance()->viewerZoomed)->toBeFalse() - // Fresh zoom for the one left, so it's whole again when the pager comes back to it; the one arrived at keeps its own. - ->and(nodeByRef($screen, 'viewer-gestures-0')['props']['pinch-id'])->not->toBe($first) - ->and(nodeByRef($screen, 'viewer-gestures-1')['props']['pinch-id'])->toBe($second) + $viewing = $screen->instance(); + $leftNow = nodeByRef($screen, 'viewer-gestures-0')['props']; + + // Fresh zoom and pans for the one left, so it's whole again when the pager comes back to it, bound to its page as + // before; the one arrived at keeps its own. + expect($leftNow['pinch-id'])->not->toBe($left['pinch-id']) + ->and($leftNow['pan-x-id'])->not->toBe($left['pan-x-id']) + ->and($leftNow['pan-y-id'])->not->toBe($left['pan-y-id']) + ->and($leftNow['pan-x-id'])->toBe($viewing->viewerPansX[0]->id) + ->and($leftNow['pan-y-id'])->toBe($viewing->viewerPansY[0]->id) + ->and(nodeByRef($screen, 'viewer-gestures-1')['props'])->toMatchArray([ + 'pinch-id' => $arrived['pinch-id'], + 'pan-x-id' => $arrived['pan-x-id'], + 'pan-y-id' => $arrived['pan-y-id'], + ]) ->and(nodeByRef($screen, 'viewed-image-0')['props']['scale'])->toBe(1.0); }); -it('pans a zoomed image instead of paging or closing, until a pinch brings it back to its whole self', function () { +it('leaves it to the phone whether a drag pans, pages or closes, with every pan bound all the time', function () { $screen = logWithImages(2)->tap('image-i1'); - expect(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-id') - ->toHaveKey('pan-y-snap'); - - $screen->pinch('viewer-gestures-0', 3.0); - $viewing = $screen->instance(); - $gestures = nodeByRef($screen, 'viewer-gestures-0')['props']; - - expect($gestures['pan-x-id'])->toBe($viewing->viewerPansX[0]->id) - ->and($gestures['pan-y-id'])->toBe($viewing->viewerPansY[0]->id) - // The page that isn't showing doesn't pan, and the drag to close lets go of the drag. - ->and(nodeByRef($screen, 'viewer-gestures-1')['props'])->not->toHaveKey('pan-x-id') - ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->not->toHaveKey('pan-y-id') - ->not->toHaveKey('on_drag_end'); - - $screen->pinch('viewer-gestures-0', 1.0); - expect($screen->instance()->viewerZoomed)->toBeFalse() - ->and(nodeByRef($screen, 'viewer-gestures-0')['props'])->not->toHaveKey('pan-x-id') - ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-id'); -}); - -it('takes a double tap\'s zoom as it takes a pinch\'s, to twice and back to its whole self', function () { - $screen = logWithImages(2)->tap('image-i1'); - - // A double tap zooms to half the most an image zooms, and says so through the pinch's end. - expect(ImageViewer::DoubleTapZoom)->toBe(ImageViewer::MaxZoom / 2); + // Every page binds its own pans, not only the showing one, and none waits to hear how a zoom ended. + foreach ([0, 1] as $place) { + $gestures = nodeByRef($screen, 'viewer-gestures-'.$place)['props']; - $screen->pinch('viewer-gestures-0', ImageViewer::DoubleTapZoom); - - expect($screen->instance()->viewerZoomed)->toBeTrue() - ->and(nodeByRef($screen, 'viewer-gestures-0')['props']['pan-x-id'])->toBe($screen->instance()->viewerPansX[0]->id) - ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->not->toHaveKey('pan-y-id'); - - $screen->pinch('viewer-gestures-0', 1.0); + expect($gestures['bounded'])->toBeTrue() + ->and($gestures['pan-x-id'])->toBe($viewing->viewerPansX[$place]->id) + ->and($gestures['pan-y-id'])->toBe($viewing->viewerPansY[$place]->id) + ->and($gestures)->not->toHaveKey('on_pinch_end'); + } - expect($screen->instance()->viewerZoomed)->toBeFalse() - ->and(nodeByRef($screen, 'viewer-gestures-0')['props'])->not->toHaveKey('pan-x-id') - ->and(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-id'); + // And the drag to close stays bound around them. + expect(nodeByRef($screen, 'viewer-dismiss')['props'])->toHaveKey('pan-y-snap') + ->toHaveKey('on_drag_end') + ->and(nodeByRef($screen, 'viewer-dismiss')['props']['pan-y-id'])->toBe($viewing->viewerDrag->id); }); it('grows out of the image the row was tapped in, and shrinks back into whichever image it has paged to', function () { From b49a4fb25bcc4a74de419cd0a843c2c3566044f0 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Fri, 20 Nov 2026 12:12:31 +0000 Subject: [PATCH 7/8] Say in the viewer's comments that a zoomed image hands its edge to the pager With NativePHP/mobile-ui#220's latest commit, a drag past a zoomed image's edge pulls the pager on to the next image, a drag that way at the edge pages, and a drag let go glides on. The drag to close still only gets drags at whole size. Co-Authored-By: Claude Opus 5.5 --- resources/views/native/partials/image-viewer-pages.blade.php | 5 +++-- resources/views/native/partials/image-viewer.blade.php | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/resources/views/native/partials/image-viewer-pages.blade.php b/resources/views/native/partials/image-viewer-pages.blade.php index 84b5121e..7ebc48d6 100644 --- a/resources/views/native/partials/image-viewer-pages.blade.php +++ b/resources/views/native/partials/image-viewer-pages.blade.php @@ -2,8 +2,9 @@ The image viewer's pages, one image each, moved up and down together by the drag to close (see image-viewer). Each image pinches, zooms on a double tap and pans on its own gesture area, with its pans bound all the time. - Bounded, the area only takes a one-finger drag while its zoomed image has room to move, so at its whole self a drag - goes to the pager or the drag to close, and zoomed in the same drag pans it. The pinch and the double tap aim with + Bounded, the area only takes a one-finger drag while its zoomed image has room to move that way, so at its whole self + a drag goes to the pager or the drag to close, and zoomed in the same drag pans it. At a zoomed image's edge a drag + that way goes to the pager, never the drag to close. The pinch and the double tap aim with those same pans: a pinch zooms around the fingers and a double tap aims at the tapped point. The phone does all of it, so PHP isn't told when a zoom ends. An image at no web address gets an empty page, never asked for (the pager can't skip a page, and the viewer never moves to it). diff --git a/resources/views/native/partials/image-viewer.blade.php b/resources/views/native/partials/image-viewer.blade.php index 4c8564b4..4ad3c366 100644 --- a/resources/views/native/partials/image-viewer.blade.php +++ b/resources/views/native/partials/image-viewer.blade.php @@ -19,7 +19,8 @@ double tap at its whole self zooms to twice, aimed at the tapped point; a double tap on a zoomed image takes it back to its whole self. A zoomed image pans. All of it runs on the phone with no frame trip. Bounded by the picture's own shape, it can't be lost off screen. The phone decides who gets a drag: a zoomed image takes it while - it has room to move, and at its whole self the image leaves it to the pager and the drag to close. + it has room to move that way, and at its whole self the image leaves it to the pager and the drag to close. Dragged + on past its edge, a zoomed image pulls the pager along to the next one, and let go it glides on with the finger. At its whole self, a drag up or down takes the image with the finger and fades the black and the buttons with it. Let go short of halfway to ImageViewer::DismissDistance and it springs back; past that, or with a flick, it carries on From b98dd8c0dd9de0bae6a83c63ee2e70341dcfeda9 Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 23 Nov 2026 17:19:57 +0000 Subject: [PATCH 8/8] Open a Remotes message's images in the full-screen viewer (#176) * Open a Remotes message's images in the full-screen viewer Tapping an image in a direct-message or org thread now opens the image viewer from #175 at that image. It pages through that message's images only, as a commit's do. Drag to close and Save to Photos come with it. Images of a message still being pushed stay untappable, since they only exist on the phone until devnull has them. The long-press menu on a message's images is unchanged. Co-Authored-By: Claude Opus 5.5 * Grow a Remotes image out of its bubble in the viewer The viewer now fades in and grows the picture out of the image it was opened from, and shrinks back into it on close (from feat/picture-viewer). Pass the refs the thread already gives a message's images, so a Remotes image does that too rather than only fading. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- app/NativeComponents/Conversation.php | 19 +++- resources/views/native/conversation.blade.php | 3 + .../native/partials/message-images.blade.php | 10 +- tests/Feature/Screens/ConversationTest.php | 97 +++++++++++++++++++ tests/Feature/Screens/RemotesComposerTest.php | 6 +- 5 files changed, 130 insertions(+), 5 deletions(-) diff --git a/app/NativeComponents/Conversation.php b/app/NativeComponents/Conversation.php index ef23ac67..6dc5d653 100644 --- a/app/NativeComponents/Conversation.php +++ b/app/NativeComponents/Conversation.php @@ -29,6 +29,7 @@ use App\NativeComponents\Concerns\PlaysVoiceNotes; use App\NativeComponents\Concerns\RecordsVoiceNotes; use App\NativeComponents\Concerns\RefreshesInBackground; +use App\NativeComponents\Concerns\ShowsImageViewer; use App\NativeComponents\Concerns\SuggestsMentions; use App\NativeComponents\Concerns\SyncsOutbox; use App\NativeComponents\Concerns\TalksToDevnull; @@ -77,7 +78,8 @@ * and letting go there sets the composer replying to it; it springs back * either way. A double tap toggles a heart. A long press opens its menu (see * MessageMenu), whose React shows the web's quick reactions in a bubble - * above it, with More for the phone's own emoji picker. + * above it, with More for the phone's own emoji picker. A tap on one of its + * images opens them full-screen (see ShowsImageViewer). * * An org's pinned messages show as the web shows them: the latest in a bar * over the top of the thread, which opens them all in a sheet, and a pin @@ -109,6 +111,7 @@ class Conversation extends NativeComponent use PlaysVoiceNotes; use RecordsVoiceNotes; use RefreshesInBackground; + use ShowsImageViewer; use SuggestsMentions; use SyncsOutbox; use TalksToDevnull; @@ -1109,6 +1112,20 @@ public function openLink(int $id): void } } + /** + * Opens a message's images full-screen (see ShowsImageViewer), from the one + * tapped, which it grows out of, paging through that message's images only, + * as a commit's do. A message the thread isn't showing opens nothing, nor + * does one still being pushed, whose images are only on the phone. + */ + public function openMessageImage(int $id, int $index = 0): void + { + $images = $this->findMessage($id)?->images ?? []; + + // The refs partials/message-images gives them, keyed by the message's id. + $this->showImagesInViewer($images, $index, array_map(fn (int $place): string => "image-{$id}-{$place}", array_keys($images))); + } + /** * Opens a link in a message's body, by its place among the body's links: a * commit or another page on dev/null the app has a screen for here in the diff --git a/resources/views/native/conversation.blade.php b/resources/views/native/conversation.blade.php index c01b14b7..56343314 100644 --- a/resources/views/native/conversation.blade.php +++ b/resources/views/native/conversation.blade.php @@ -168,4 +168,7 @@ {{-- More reactions, from the bubble or anywhere else: the emoji keyboard on iOS, Jetpack's emoji picker on Android. --}} + + {{-- A message's images full-screen, over everything else. --}} + @include('native.partials.image-viewer') diff --git a/resources/views/native/partials/message-images.blade.php b/resources/views/native/partials/message-images.blade.php index e6c0bc12..94557fed 100644 --- a/resources/views/native/partials/message-images.blade.php +++ b/resources/views/native/partials/message-images.blade.php @@ -1,10 +1,16 @@ {{-- - A message's images. A long press on them opens the message's menu, as on its bubble ($photosMenu). + A message's images. A long press on them opens the message's menu, as on its bubble ($photosMenu). A tap on one + opens the message's images full-screen from that one (see Conversation::openMessageImage), once devnull has the + message: a message still being pushed has its images only on the phone. --}} @if ($message->images !== []) @foreach ($message->images as $index => $image) - + @if ($message->isPending()) + + @else + + @endif @endforeach @endif diff --git a/tests/Feature/Screens/ConversationTest.php b/tests/Feature/Screens/ConversationTest.php index 5e0634ef..29330a47 100644 --- a/tests/Feature/Screens/ConversationTest.php +++ b/tests/Feature/Screens/ConversationTest.php @@ -2,8 +2,12 @@ use App\Devnull\Account; use App\Devnull\Data\Remotes; +use App\Devnull\ImageCache; +use App\Devnull\ImageViewer; use App\NativeComponents\Conversation; +use Devnull\Photos\Events\Saved; use Illuminate\Http\Client\Request; +use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Http; use Native\Mobile\Events\Alert\ButtonPressed; use Native\Mobile\Testing\Native; @@ -1389,3 +1393,96 @@ function orgWithMembers(array $people): array ->tap('mention-ada') ->assertSet('draft', 'hi'); }); + +/** + * A message's photos as devnull sends them: $count of them, numbered from $first, the first described. + * + * @return list> + */ +function remotePhotos(int $count, int $first = 1): array +{ + return array_map(fn (int $n): array => [ + 'id' => $n, + 'width' => 400, + 'height' => 300, + 'description' => $n === $first ? 'The new logo' : null, + 'url' => 'https://img.test/'.$n, + ], range($first, $first + $count - 1)); +} + +it("opens a message's image full-screen from the one tapped, and pages through that message's images only", function (string $platform) { + serveRemoteThread(threadJson([ + remoteMessageJson(['id' => 1, 'body' => '', 'images' => remotePhotos(3)]), + remoteMessageJson(['id' => 2, 'body' => 'and the dark one', 'images' => remotePhotos(2, first: 4)]), + ], ['read_through_id' => 2])); + + $screen = finishRefreshes(Native::visit('/remotes/conversations/ada', platform: $platform)); + + // Hidden until a tap, always in the tree. + expect(nodeByRef($screen, 'image-viewer')['props']['visible'])->toBeFalse() + ->and(nodeByRef($screen, 'image-1-1')['on_press'] ?? null)->not->toBeNull(); + + $screen->tap('image-1-1')->assertSet('viewerOpen', true)->assertSet('viewerIndex', 1) + // It grows out of the message's own images, by their refs, and shrinks back into whichever it pages to. + ->assertSet('viewerSources', ['image-1-0', 'image-1-1', 'image-1-2']); + + $shown = findNodes(nodeByRef($screen, 'image-viewer'), fn (array $node): bool => ($node['type'] ?? null) === 'image'); + + expect(nodeByRef($screen, 'image-viewer')['props']['visible'])->toBeTrue() + ->and(array_map(fn (array $node): string => $node['props']['src'], $shown))->toBe(['https://img.test/1', 'https://img.test/2', 'https://img.test/3']) + ->and(nodeByRef($screen, 'viewed-image-0')['props']['alt'])->toBe('The new logo, image 1 of 3') + ->and(nodeByRef($screen, 'viewer-dots')['props']['a11y_label'])->toBe('Image 2 of 3') + ->and(nodeByRef($screen, 'viewer-save')['props']['a11y_label'])->toBe('Save to Photos'); + + $screen->changeTab('viewerPaged', 2)->assertSet('viewerIndex', 2); + $screen->dismissSheet('image-viewer')->assertSet('viewerOpen', false)->assertSet('viewerImages', []); + + // A message with text keeps its images tappable too, and opens on its own. + $screen->tap('image-2-1')->assertSet('viewerIndex', 1); + + expect(array_map(fn ($image): string => $image->url, $screen->instance()->viewerImages))->toBe(['https://img.test/4', 'https://img.test/5']) + ->and(nodeByRef($screen, 'viewer-dots')['props']['a11y_label'])->toBe('Image 2 of 2'); + + $screen->assertNativeNotCalled('Browser.OpenInApp'); +})->with(['ios', 'android']); + +it("keeps a message's long-press menu on its images while a tap opens them", function () { + serveRemoteThread(threadJson([remoteMessageJson(['id' => 1, 'body' => '', 'images' => remotePhotos(2)])], ['read_through_id' => 1])); + + $screen = finishRefreshes(Native::visit('/remotes/conversations/ada', platform: 'ios')); + + expect(array_column(menuItems($screen, 'photos-1'), 1))->toBe(['Reply', 'React']); + + $screen->tap('image-1-0')->assertSet('viewerOpen', true); +}); + +it("drags a message's image away and saves it to the phone's photos", function () { + serveRemoteThread(threadJson([remoteMessageJson(['id' => 1, 'body' => '', 'images' => remotePhotos(2)])], ['read_through_id' => 1])); + $this->bridge->respondTo('Photos.Save', ['success' => true]); + + $kept = ImageCache::path('https://img.test/2'); + File::ensureDirectoryExists(dirname($kept)); + File::put($kept, 'jpeg bytes'); + + try { + $screen = finishRefreshes(Native::visit('/remotes/conversations/ada', platform: 'ios'))->tap('image-1-1'); + + $screen->tap('viewer-save') + ->assertNativeCalled('Photos.Save', fn (array $params): bool => $params['path'] === $kept) + ->emitNative(Saved::class) + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === 'Saved to Photos'); + + $screen->dragEnd('viewer-dismiss', 0, ImageViewer::DismissDistance)->assertSet('viewerOpen', false); + } finally { + File::delete($kept); + } +}); + +it("opens nothing for a message the thread isn't showing, or a place with no image", function () { + serveRemoteThread(threadJson([remoteMessageJson(['id' => 1, 'body' => '', 'images' => remotePhotos(1)])], ['read_through_id' => 1])); + + $screen = finishRefreshes(Native::visit('/remotes/conversations/ada', platform: 'ios')); + + $screen->call('openMessageImage', 42, 0)->assertSet('viewerOpen', false); + $screen->call('openMessageImage', 1, 3)->assertSet('viewerOpen', false); +}); diff --git a/tests/Feature/Screens/RemotesComposerTest.php b/tests/Feature/Screens/RemotesComposerTest.php index b06a389a..f86f3e61 100644 --- a/tests/Feature/Screens/RemotesComposerTest.php +++ b/tests/Feature/Screens/RemotesComposerTest.php @@ -109,9 +109,10 @@ function threadWithAda(string $platform = 'ios'): TestableComponent $screen->tap('push')->assertSee('the new logo')->assertSee('staged')->assertSet('photos', []); $clientId = $screen->instance()->pending[0]->clientId; - // Drawn from the phone while they go. + // Drawn from the phone while they go, and not opened full-screen until devnull has them. expect(nodeByRef($screen, 'image-'.$clientId.'-0')['props']['src'])->toBe($kept[0]) - ->and(nodeByRef($screen, 'image-'.$clientId.'-1')['props']['src'])->toBe($kept[1]); + ->and(nodeByRef($screen, 'image-'.$clientId.'-1')['props']['src'])->toBe($kept[1]) + ->and(nodeByRef($screen, 'image-'.$clientId.'-0'))->not->toHaveKey('on_press'); finishRefreshes($screen)->assertSee('pushed')->assertSet('pending', []); @@ -121,6 +122,7 @@ function threadWithAda(string $platform = 'ios'): TestableComponent ['name' => 'images[]', 'type' => 'image/png', 'contents' => $contents[1]], ]]) ->and(nodeByRef($screen, 'image-99-0')['props']['src'])->toBe('http://devnull.test/message-images/1?signature=abc') + ->and(nodeByRef($screen, 'image-99-0')['on_press'] ?? null)->not->toBeNull() ->and(array_filter($kept, file_exists(...)))->toBe([]); });