From 87171d0e7ad60e9b7b30821048ab22548316cff1 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Sun, 15 Nov 2026 21:41:57 +0000 Subject: [PATCH] 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'); });