From 87171d0e7ad60e9b7b30821048ab22548316cff1 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Sun, 15 Nov 2026 21:41:57 +0000 Subject: [PATCH 1/5] 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 a6a75e9dc246d152cbf96da11814890088e19acb Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Wed, 18 Nov 2026 19:51:20 +0000 Subject: [PATCH 2/5] 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 621d53a9a56cd4ec478f07bdf15a1c753accd4f6 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Thu, 19 Nov 2026 22:23:02 +0000 Subject: [PATCH 3/5] 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 4/5] 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 5/5] 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