mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-26 03:46:25 -08:00
fix(mobile): improve image saves and touch handling
This commit is contained in:
15 files changed
+798
-94
No files matched your search
Generated
+33
-18
@@ -168,7 +168,7 @@ version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -179,7 +179,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1011,7 +1011,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1553,7 +1553,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1585,7 +1585,7 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
|
||||
dependencies = [
|
||||
"libloading 0.7.4",
|
||||
"libloading 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1855,7 +1855,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3653,7 +3653,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.19",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3777,7 +3777,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4026,6 +4026,19 @@ dependencies = [
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-photos"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6ea9a706f18e32cf8a0723e99855af4f135282891e07259301bae9135ae3872"
|
||||
dependencies = [
|
||||
"bitflags 2.13.1",
|
||||
"block2",
|
||||
"dispatch2",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-quartz-core"
|
||||
version = "0.3.2"
|
||||
@@ -4181,7 +4194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4839,7 +4852,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2 0.6.5",
|
||||
"tracing",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5258,7 +5271,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5316,7 +5329,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5355,6 +5368,7 @@ dependencies = [
|
||||
"aes",
|
||||
"async-stream",
|
||||
"base64 0.22.1",
|
||||
"block2",
|
||||
"cef",
|
||||
"ctr",
|
||||
"enigo",
|
||||
@@ -5366,6 +5380,7 @@ dependencies = [
|
||||
"log",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
"objc2-photos",
|
||||
"percent-encoding",
|
||||
"regex",
|
||||
"reqwest 0.12.28",
|
||||
@@ -6011,7 +6026,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7030,7 +7045,7 @@ dependencies = [
|
||||
"serde_with",
|
||||
"swift-rs",
|
||||
"thiserror 2.0.19",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml 1.1.3+spec-1.1.0",
|
||||
"url",
|
||||
"urlpattern",
|
||||
"uuid",
|
||||
@@ -7069,7 +7084,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7694,7 +7709,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.19",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7768,7 +7783,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
|
||||
dependencies = [
|
||||
"memoffset",
|
||||
"tempfile",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8398,7 +8413,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+18
-1
@@ -127,7 +127,24 @@ tauri-plugin-sharekit = { git = "https://github.com/Choochmeque/tauri-plugin-sha
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
objc2 = "0.6"
|
||||
objc2-foundation = { version = "0.3", features = ["NSFileManager", "NSString", "NSURL"] }
|
||||
objc2-foundation = { version = "0.3", features = [
|
||||
"NSError",
|
||||
"NSFileManager",
|
||||
"NSString",
|
||||
"NSURL",
|
||||
] }
|
||||
objc2-photos = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"PHPhotoLibrary",
|
||||
"PHChangeRequest",
|
||||
"PHAssetChangeRequest",
|
||||
"PHAssetCreationRequest",
|
||||
"PhotosTypes",
|
||||
"bitflags",
|
||||
"block2",
|
||||
"dispatch2",
|
||||
] }
|
||||
block2 = "0.6"
|
||||
tauri-plugin-fs = "2"
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"permissions": [
|
||||
"android-fs:allow-check-public-files-permission",
|
||||
"android-fs:allow-create-new-public-file",
|
||||
"android-fs:allow-create-new-public-image-file",
|
||||
"android-fs:allow-request-public-files-permission",
|
||||
"android-fs:allow-write-file",
|
||||
"android-fs:allow-set-public-file-pending",
|
||||
|
||||
@@ -105,6 +105,7 @@ targets:
|
||||
CFBundleShortVersionString: {{apple.bundle-version-short}}
|
||||
CFBundleVersion: "{{apple.bundle-version}}"
|
||||
UIBackgroundModes: [audio]
|
||||
NSPhotoLibraryAddUsageDescription: Sable saves images you download to your photo library.
|
||||
# Mirrors plugins.deep-link in tauri.conf.json: the plugin only patches
|
||||
# these in when cargo reruns its build script, so a fresh `tauri ios
|
||||
# init` silently loses them unless they live here.
|
||||
|
||||
@@ -159,3 +159,139 @@ pub(crate) fn play_notification_sound(kind: String) -> Result<(), String> {
|
||||
unsafe { AudioServicesPlaySystemSound(sound_id) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// PhotoKit lane for saving images to the camera roll with add-only access;
|
||||
// the prompt text is NSPhotoLibraryAddUsageDescription in ios-project.yml.
|
||||
|
||||
// Empty block only to emit the linker directive, same role as AudioToolbox above.
|
||||
#[link(name = "Photos", kind = "framework")]
|
||||
extern "C" {}
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2_photos::{
|
||||
PHAccessLevel, PHAssetCreationRequest, PHAssetResourceType, PHAuthorizationStatus,
|
||||
PHPhotoLibrary,
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
fn photo_access_allowed(status: PHAuthorizationStatus) -> bool {
|
||||
// Add-only access: .limited still permits adds (it only restricts reads).
|
||||
status == PHAuthorizationStatus::Authorized || status == PHAuthorizationStatus::Limited
|
||||
}
|
||||
|
||||
fn photo_authorization_error(status: PHAuthorizationStatus) -> String {
|
||||
if status == PHAuthorizationStatus::Denied {
|
||||
"permission denied: allow photo access in Settings > Apps > Sable > Photos".to_string()
|
||||
} else if status == PHAuthorizationStatus::Restricted {
|
||||
"saving to Photos is blocked by device management or parental controls".to_string()
|
||||
} else {
|
||||
format!("unexpected photo authorization status: {status:?}")
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_photo_add_authorization() -> Result<(), String> {
|
||||
let status =
|
||||
unsafe { PHPhotoLibrary::authorizationStatusForAccessLevel(PHAccessLevel::AddOnly) };
|
||||
if photo_access_allowed(status) {
|
||||
return Ok(());
|
||||
}
|
||||
if status != PHAuthorizationStatus::NotDetermined {
|
||||
return Err(photo_authorization_error(status));
|
||||
}
|
||||
|
||||
let (tx, rx) = oneshot::channel::<PHAuthorizationStatus>();
|
||||
{
|
||||
let tx = Mutex::new(Some(tx));
|
||||
let handler: RcBlock<dyn Fn(PHAuthorizationStatus)> = RcBlock::new(move |status| {
|
||||
if let Ok(mut guard) = tx.lock() {
|
||||
if let Some(tx) = guard.take() {
|
||||
let _ = tx.send(status);
|
||||
}
|
||||
}
|
||||
});
|
||||
unsafe {
|
||||
PHPhotoLibrary::requestAuthorizationForAccessLevel_handler(
|
||||
PHAccessLevel::AddOnly,
|
||||
&handler,
|
||||
);
|
||||
}
|
||||
// PhotoKit copies the handler; keep the !Send RcBlock out of the await below.
|
||||
}
|
||||
|
||||
let granted = rx
|
||||
.await
|
||||
.map_err(|_| "photo authorization request was cancelled".to_string())?;
|
||||
if photo_access_allowed(granted) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(photo_authorization_error(granted))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_media_to_photo_library(bytes: &[u8], filename: &str) -> Result<(), String> {
|
||||
// PhotoKit infers the content type from the file URL, so the temp file
|
||||
// keeps the extension; `file_name` strips any directory components.
|
||||
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let leaf = std::path::Path::new(filename)
|
||||
.file_name()
|
||||
.unwrap_or_else(|| OsStr::new("download"));
|
||||
let mut path = std::env::temp_dir();
|
||||
path.push(format!(
|
||||
"sable-photos-{}-{}-{}",
|
||||
std::process::id(),
|
||||
TEMP_COUNTER.fetch_add(1, Ordering::Relaxed),
|
||||
leaf.to_string_lossy()
|
||||
));
|
||||
|
||||
if let Err(error) = std::fs::write(&path, bytes) {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return Err(format!("failed to write {}: {error}", path.display()));
|
||||
}
|
||||
|
||||
let result = unsafe {
|
||||
let path_str = NSString::from_str(&path.to_string_lossy());
|
||||
let url = NSURL::fileURLWithPath(&path_str);
|
||||
let library = PHPhotoLibrary::sharedPhotoLibrary();
|
||||
// PhotoKit rejects creation requests instantiated outside the change block.
|
||||
let change: RcBlock<dyn Fn()> = RcBlock::new(move || {
|
||||
let request = PHAssetCreationRequest::creationRequestForAsset();
|
||||
request.addResourceWithType_fileURL_options(PHAssetResourceType::Photo, &url, None);
|
||||
});
|
||||
library
|
||||
.performChangesAndWait_error(RcBlock::as_ptr(&change))
|
||||
.map_err(|error| {
|
||||
format!(
|
||||
"failed to save '{filename}' to Photos ({} error {}): {}",
|
||||
error.domain(),
|
||||
error.code(),
|
||||
error.localizedDescription()
|
||||
)
|
||||
})
|
||||
};
|
||||
let _ = std::fs::remove_file(&path);
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn save_media_to_photos(
|
||||
bytes: Vec<u8>,
|
||||
filename: String,
|
||||
mime_type: String,
|
||||
) -> Result<(), String> {
|
||||
if !mime_type.starts_with("image/") {
|
||||
return Err(format!(
|
||||
"unsupported media type '{mime_type}': only images can be saved to Photos"
|
||||
));
|
||||
}
|
||||
|
||||
request_photo_add_authorization().await?;
|
||||
|
||||
// performChangesAndWait blocks until commit; it must not run on the main thread.
|
||||
tauri::async_runtime::spawn_blocking(move || write_media_to_photo_library(&bytes, &filename))
|
||||
.await
|
||||
.map_err(|error| format!("failed to run photo save: {error}"))?
|
||||
}
|
||||
@@ -445,6 +445,8 @@ pub fn run() {
|
||||
mobile::stop_call_foreground_service,
|
||||
#[cfg(target_os = "ios")]
|
||||
ios::haptic_feedback,
|
||||
#[cfg(target_os = "ios")]
|
||||
ios::save_media_to_photos,
|
||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||
play_notification_sound,
|
||||
#[cfg(desktop)]
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
},
|
||||
"iOS": {
|
||||
"template": "src-tauri/ios-project.yml",
|
||||
"frameworks": ["AudioToolbox"]
|
||||
"frameworks": ["AudioToolbox", "Photos"]
|
||||
},
|
||||
"linux": {
|
||||
"deb": {
|
||||
|
||||
@@ -3,8 +3,26 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import FileSaver from 'file-saver';
|
||||
import { ImageViewer } from './ImageViewer';
|
||||
import { showToast } from '$state/toast';
|
||||
import type { IImageInfo } from '$types/matrix/common';
|
||||
|
||||
const downloadMedia = vi.fn<(src: string) => Promise<Blob>>();
|
||||
const saveMediaToGallery =
|
||||
vi.fn<(input: string, filename: string, mimeType: string) => Promise<void>>();
|
||||
const toastMocks = vi.hoisted(() => ({
|
||||
showToast: vi.fn<(text: string, durationMs?: number) => void>(),
|
||||
}));
|
||||
vi.mock('$state/toast', () => ({ showToast: toastMocks.showToast }));
|
||||
const platformMocks = vi.hoisted(() => ({
|
||||
isAndroidTauri: vi.fn<() => boolean>(() => false),
|
||||
iosApp: vi.fn<() => boolean>(() => false),
|
||||
}));
|
||||
const screenMocks = vi.hoisted(() => ({ isMobile: false }));
|
||||
vi.mock('$utils/platform', async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
isAndroidTauri: platformMocks.isAndroidTauri,
|
||||
iosApp: platformMocks.iosApp,
|
||||
}));
|
||||
const gestureMocks = vi.hoisted(() => ({
|
||||
onPointerDown: vi.fn<(event: React.PointerEvent) => void>(),
|
||||
}));
|
||||
@@ -30,6 +48,10 @@ vi.mock('$hooks/useImageGestures', () => ({
|
||||
vi.mock('$utils/matrix', () => ({
|
||||
downloadMedia: (...args: [string]) => downloadMedia(...args),
|
||||
}));
|
||||
vi.mock('$utils/download', async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
saveMediaToGallery: (...args: [string, string, string]) => saveMediaToGallery(...args),
|
||||
}));
|
||||
|
||||
vi.mock('file-saver', () => ({
|
||||
default: {
|
||||
@@ -39,21 +61,30 @@ vi.mock('file-saver', () => ({
|
||||
|
||||
vi.mock('$hooks/useScreenSize', () => ({
|
||||
ScreenSize: { Desktop: 'Desktop', Tablet: 'Tablet', Mobile: 'Mobile' },
|
||||
useScreenSizeContext: () => 'Desktop',
|
||||
useScreenSizeOptionally: () => 'Desktop',
|
||||
useScreenSizeContext: () => (screenMocks.isMobile ? 'Mobile' : 'Desktop'),
|
||||
useScreenSizeOptionally: () => (screenMocks.isMobile ? 'Mobile' : 'Desktop'),
|
||||
}));
|
||||
|
||||
const renderViewer = (props: { alt?: string; src?: string; info?: IImageInfo } = {}) =>
|
||||
render(
|
||||
<ImageViewer
|
||||
alt="kitten.png"
|
||||
src="https://example.org/kitten.png"
|
||||
requestClose={vi.fn<() => void>()}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
const mockPlatform = (platform: 'web' | 'android' | 'ios') => {
|
||||
platformMocks.isAndroidTauri.mockReturnValue(platform === 'android');
|
||||
platformMocks.iosApp.mockReturnValue(platform === 'ios');
|
||||
};
|
||||
|
||||
describe('ImageViewer', () => {
|
||||
it('downloads media without passing a media token argument', async () => {
|
||||
downloadMedia.mockResolvedValue(new Blob(['image']));
|
||||
|
||||
render(
|
||||
<ImageViewer
|
||||
alt="kitten.png"
|
||||
src="https://example.org/kitten.png"
|
||||
requestClose={vi.fn<() => void>()}
|
||||
/>
|
||||
);
|
||||
renderViewer();
|
||||
|
||||
fireEvent.click(screen.getByText('Download'));
|
||||
|
||||
@@ -62,6 +93,98 @@ describe('ImageViewer', () => {
|
||||
});
|
||||
expect(FileSaver.saveAs).toHaveBeenCalledWith(expect.any(Blob), 'kitten.png');
|
||||
});
|
||||
|
||||
it('activates the download control on the first touch sequence', async () => {
|
||||
screenMocks.isMobile = true;
|
||||
downloadMedia.mockClear();
|
||||
downloadMedia.mockResolvedValue(new Blob(['image']));
|
||||
|
||||
renderViewer();
|
||||
|
||||
const download = screen.getByText('Download');
|
||||
fireEvent.pointerDown(download, { pointerId: 1, pointerType: 'touch' });
|
||||
fireEvent.pointerUp(download, { pointerId: 1, pointerType: 'touch' });
|
||||
fireEvent.click(download);
|
||||
|
||||
await waitFor(() => expect(downloadMedia).toHaveBeenCalledOnce());
|
||||
screenMocks.isMobile = false;
|
||||
});
|
||||
|
||||
it('shows an error toast when downloading media fails', async () => {
|
||||
const error = new Error('network unavailable');
|
||||
downloadMedia.mockRejectedValue(error);
|
||||
vi.mocked(showToast).mockClear();
|
||||
|
||||
renderViewer();
|
||||
|
||||
fireEvent.click(screen.getByText('Download'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(showToast).toHaveBeenCalledWith('Failed to download file: network unavailable');
|
||||
});
|
||||
});
|
||||
|
||||
it('shows the Android gallery action for trusted image media', () => {
|
||||
mockPlatform('android');
|
||||
|
||||
renderViewer({ info: { mimetype: 'image/png' } });
|
||||
|
||||
fireEvent.contextMenu(screen.getByAltText('kitten.png'));
|
||||
|
||||
expect(screen.getByText('Save to Gallery')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('labels the primary action Save to Photos on iOS without duplicating it in the overflow menu', () => {
|
||||
mockPlatform('ios');
|
||||
|
||||
renderViewer({ info: { mimetype: 'image/png' } });
|
||||
|
||||
fireEvent.contextMenu(screen.getByAltText('kitten.png'));
|
||||
|
||||
expect(screen.getAllByText('Save to Photos')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('routes the primary iOS action for trusted images straight to Photos', async () => {
|
||||
mockPlatform('ios');
|
||||
saveMediaToGallery.mockClear();
|
||||
downloadMedia.mockClear();
|
||||
vi.mocked(FileSaver.saveAs).mockClear();
|
||||
|
||||
renderViewer({ info: { mimetype: 'image/png' } });
|
||||
|
||||
fireEvent.click(screen.getByText('Save to Photos'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(saveMediaToGallery).toHaveBeenCalledWith(
|
||||
'https://example.org/kitten.png',
|
||||
'kitten.png',
|
||||
'image/png'
|
||||
)
|
||||
);
|
||||
expect(downloadMedia).not.toHaveBeenCalled();
|
||||
expect(FileSaver.saveAs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the iOS primary action on the Files export for videos', async () => {
|
||||
mockPlatform('ios');
|
||||
saveMediaToGallery.mockClear();
|
||||
downloadMedia.mockClear();
|
||||
downloadMedia.mockResolvedValue(new Blob(['video']));
|
||||
|
||||
renderViewer({
|
||||
alt: 'clip.mp4',
|
||||
src: 'https://example.org/clip.mp4',
|
||||
info: { mimetype: 'video/mp4' },
|
||||
});
|
||||
|
||||
expect(screen.getByText('Download')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Save to Photos')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByText('Download'));
|
||||
|
||||
await waitFor(() => expect(downloadMedia).toHaveBeenCalledWith('https://example.org/clip.mp4'));
|
||||
expect(saveMediaToGallery).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
vi.mock('$components/media', async () => {
|
||||
@@ -86,25 +209,44 @@ vi.mock('$components/media', async () => {
|
||||
|
||||
describe('ImageViewer', () => {
|
||||
it('renders the fullscreen image without crashing', () => {
|
||||
render(<ImageViewer alt="demo" src="https://example.com/demo.png" requestClose={() => {}} />);
|
||||
renderViewer({ alt: 'demo', src: 'https://example.com/demo.png' });
|
||||
|
||||
expect(screen.getByAltText('demo')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download').closest('[data-gestures="ignore"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('starts viewer gestures from the rendered lottie canvas', () => {
|
||||
gestureMocks.onPointerDown.mockClear();
|
||||
render(
|
||||
<ImageViewer
|
||||
alt="animated sticker"
|
||||
src="https://example.com/sticker"
|
||||
info={{ mimetype: 'application/x-tgsticker' }}
|
||||
requestClose={() => {}}
|
||||
/>
|
||||
);
|
||||
renderViewer({
|
||||
alt: 'animated sticker',
|
||||
src: 'https://example.com/sticker',
|
||||
info: { mimetype: 'application/x-tgsticker' },
|
||||
});
|
||||
|
||||
const canvas = screen.getByLabelText('animated sticker');
|
||||
expect(canvas.tagName).toBe('CANVAS');
|
||||
fireEvent.pointerDown(canvas);
|
||||
expect(gestureMocks.onPointerDown).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('contains viewer touches from an enclosing message long-press handler', () => {
|
||||
const messageLongPress = vi.fn<() => void>();
|
||||
render(
|
||||
<div
|
||||
onTouchStart={(evt) => {
|
||||
const target = evt.target as Element;
|
||||
if (target.closest('[data-gestures="ignore"]')) return;
|
||||
messageLongPress();
|
||||
}}
|
||||
>
|
||||
<ImageViewer alt="demo" src="https://example.com/demo.png" requestClose={() => {}} />
|
||||
</div>
|
||||
);
|
||||
|
||||
fireEvent.touchStart(screen.getByText('Download'), {
|
||||
touches: [{ identifier: 1, clientX: 10, clientY: 10 }],
|
||||
});
|
||||
|
||||
expect(messageLongPress).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -19,13 +19,17 @@ import { useMenuAnchor } from '$hooks/useMenuAnchor';
|
||||
import { useDismissOnBack } from '$utils/androidBack';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { isPixelatedRendering, settingsAtom } from '$state/settings';
|
||||
import { showToast } from '$state/toast';
|
||||
import { downloadMedia } from '$utils/matrix';
|
||||
import * as css from './ImageViewer.css';
|
||||
import type { IImageInfo } from '$types/matrix/common';
|
||||
import { CheckerboardIcon, CopyIcon, DownloadIcon } from '@phosphor-icons/react';
|
||||
import { copyImageToClipboard } from '$utils/dom';
|
||||
import { getDownloadFilename, saveFileToDevice } from '$utils/download';
|
||||
import { getDownloadFilename, saveFileToDevice, saveMediaToGallery } from '$utils/download';
|
||||
import { ResponsiveMenu } from '$components/ResponsiveMenu';
|
||||
import { isAndroidTauri, iosApp } from '$utils/platform';
|
||||
import { ScreenSize, useScreenSizeOptionally } from '$hooks/useScreenSize';
|
||||
import { useMobileTapActivation } from '$hooks/useMobileTapActivation';
|
||||
|
||||
type ImageViewerProps = {
|
||||
alt: string;
|
||||
@@ -39,6 +43,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
({ className, alt, filename, src, requestClose, info, ...props }, ref) => {
|
||||
const zoomInputRef = useRef<HTMLInputElement>(null);
|
||||
const [pixelatedImageRendering] = useSetting(settingsAtom, 'pixelatedImageRendering');
|
||||
const isMobile = useScreenSizeOptionally() === ScreenSize.Mobile;
|
||||
|
||||
// Android back closes the viewer instead of navigating away.
|
||||
useDismissOnBack(requestClose);
|
||||
@@ -90,12 +95,61 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
}
|
||||
}, [isEditingZoom]);
|
||||
|
||||
const galleryMimeType = info?.mimetype?.toLowerCase();
|
||||
// On iOS the primary action saves trusted images straight to Photos (PhotoKit).
|
||||
const iosSaveToPhotos = iosApp() && (galleryMimeType?.startsWith('image/') ?? false);
|
||||
const downloadFilename = getDownloadFilename(filename, alt, 'image');
|
||||
|
||||
const handleDownload = async () => {
|
||||
const fileContent = await downloadMedia(src);
|
||||
await saveFileToDevice(fileContent, getDownloadFilename(filename, alt, 'image'));
|
||||
if (iosSaveToPhotos) {
|
||||
await saveMediaToGallery(src, downloadFilename, galleryMimeType!);
|
||||
return;
|
||||
}
|
||||
let fileContent: Blob;
|
||||
try {
|
||||
fileContent = await downloadMedia(src);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'unknown error';
|
||||
showToast(`Failed to download file: ${message}`);
|
||||
return;
|
||||
}
|
||||
await saveFileToDevice(fileContent, downloadFilename);
|
||||
};
|
||||
|
||||
const menu = useMenuAnchor<HTMLDivElement>();
|
||||
const canSaveToGallery = isAndroidTauri() && (galleryMimeType?.startsWith('image/') ?? false);
|
||||
|
||||
const closeActivation = useMobileTapActivation(isMobile, requestClose);
|
||||
const pixelatedActivation = useMobileTapActivation(isMobile, () =>
|
||||
setIsPixelated(!isPixelated)
|
||||
);
|
||||
const originalSizeActivation = useMobileTapActivation(isMobile, () => setZoom(1));
|
||||
const resetZoomActivation = useMobileTapActivation(isMobile, () => {
|
||||
resetTransforms();
|
||||
enableResizeWithWindow();
|
||||
setZoom(fitRatio);
|
||||
});
|
||||
const zoomOutActivation = useMobileTapActivation(isMobile, zoomOut);
|
||||
const zoomInputActivation = useMobileTapActivation(isMobile, () => {
|
||||
setZoomInput(Math.round(transforms.zoom * 100).toString());
|
||||
setIsEditingZoom(true);
|
||||
});
|
||||
const zoomInActivation = useMobileTapActivation(isMobile, zoomIn);
|
||||
const downloadActivation = useMobileTapActivation(isMobile, () => {
|
||||
void handleDownload();
|
||||
});
|
||||
const copyImageActivation = useMobileTapActivation(isMobile, () => {
|
||||
menu.close();
|
||||
void downloadMedia(src).then(copyImageToClipboard);
|
||||
});
|
||||
const saveImageActivation = useMobileTapActivation(isMobile, () => {
|
||||
menu.close();
|
||||
void handleDownload();
|
||||
});
|
||||
const galleryActivation = useMobileTapActivation(isMobile, () => {
|
||||
menu.close();
|
||||
void saveMediaToGallery(src, downloadFilename, galleryMimeType!);
|
||||
});
|
||||
|
||||
const handleContextMenu: MouseEventHandler<HTMLDivElement> = (evt) => {
|
||||
if (evt.altKey || !window.getSelection()?.isCollapsed) return;
|
||||
@@ -119,11 +173,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
radii="300"
|
||||
size="300"
|
||||
after={menuIcon(CopyIcon)}
|
||||
onClick={async () => {
|
||||
menu.close();
|
||||
const fileContent = await downloadMedia(src);
|
||||
await copyImageToClipboard(fileContent);
|
||||
}}
|
||||
{...copyImageActivation}
|
||||
>
|
||||
<Text size="T300" style={{ flexGrow: 1 }}>
|
||||
Copy image
|
||||
@@ -134,15 +184,25 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
radii="300"
|
||||
size="300"
|
||||
after={menuIcon(DownloadIcon)}
|
||||
onClick={() => {
|
||||
menu.close();
|
||||
handleDownload();
|
||||
}}
|
||||
{...saveImageActivation}
|
||||
>
|
||||
<Text size="T300" style={{ flexGrow: 1 }}>
|
||||
Save image
|
||||
</Text>
|
||||
</MenuItem>
|
||||
{canSaveToGallery && (
|
||||
<MenuItem
|
||||
as="button"
|
||||
radii="300"
|
||||
size="300"
|
||||
after={menuIcon(DownloadIcon)}
|
||||
{...galleryActivation}
|
||||
>
|
||||
<Text size="T300" style={{ flexGrow: 1 }}>
|
||||
Save to Gallery
|
||||
</Text>
|
||||
</MenuItem>
|
||||
)}
|
||||
</Box>
|
||||
</Menu>
|
||||
}
|
||||
@@ -150,12 +210,13 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
<Box
|
||||
className={classNames(css.ImageViewer, className)}
|
||||
direction="Column"
|
||||
data-gestures="ignore"
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<Header className={css.ImageViewerHeader} size="400">
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||
<IconButton size="300" radii="300" {...closeActivation}>
|
||||
{sizedIcon(ArrowLeft, '200')}
|
||||
</IconButton>
|
||||
<Text size="T300" truncate>
|
||||
@@ -167,7 +228,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
variant="Surface"
|
||||
size="300"
|
||||
radii="Pill"
|
||||
onClick={() => setIsPixelated(!isPixelated)}
|
||||
{...pixelatedActivation}
|
||||
aria-label="Toggle Pixelation"
|
||||
title={`Turn ${isPixelated ? 'Anti-aliasing' : 'Pixelation'} on`}
|
||||
>
|
||||
@@ -186,9 +247,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
}}
|
||||
size="300"
|
||||
radii="Pill"
|
||||
onClick={() => {
|
||||
setZoom(1);
|
||||
}}
|
||||
{...originalSizeActivation}
|
||||
aria-label="View Original Size"
|
||||
title="View Original Size"
|
||||
>
|
||||
@@ -205,11 +264,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
}}
|
||||
size="300"
|
||||
radii="Pill"
|
||||
onClick={() => {
|
||||
resetTransforms();
|
||||
enableResizeWithWindow();
|
||||
setZoom(fitRatio);
|
||||
}}
|
||||
{...resetZoomActivation}
|
||||
aria-label="Reset Zoom"
|
||||
title="Zoom to Fill Container"
|
||||
>
|
||||
@@ -220,7 +275,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
outlined={transforms.zoom < 1}
|
||||
size="300"
|
||||
radii="Pill"
|
||||
onClick={zoomOut}
|
||||
{...zoomOutActivation}
|
||||
aria-label="Zoom Out"
|
||||
title="Zoom Out"
|
||||
>
|
||||
@@ -235,10 +290,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
// 4em should be generous enough to fit without manually determining the width of the text.
|
||||
minWidth: '4em',
|
||||
}}
|
||||
onClick={() => {
|
||||
setZoomInput(Math.round(transforms.zoom * 100).toString());
|
||||
setIsEditingZoom(true);
|
||||
}}
|
||||
{...zoomInputActivation}
|
||||
title="Update Zoom"
|
||||
>
|
||||
<Text
|
||||
@@ -288,7 +340,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
outlined={transforms.zoom > 1}
|
||||
size="300"
|
||||
radii="Pill"
|
||||
onClick={zoomIn}
|
||||
{...zoomInActivation}
|
||||
aria-label="Zoom In"
|
||||
title="Zoom In"
|
||||
>
|
||||
@@ -296,12 +348,12 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
</IconButton>
|
||||
<Chip
|
||||
variant="Primary"
|
||||
onClick={handleDownload}
|
||||
{...downloadActivation}
|
||||
radii="300"
|
||||
before={sizedIcon(Download, '50')}
|
||||
outlined
|
||||
>
|
||||
<Text size="B300">Download</Text>
|
||||
<Text size="B300">{iosSaveToPhotos ? 'Save to Photos' : 'Download'}</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
</Header>
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { ImageContent } from './ImageContent';
|
||||
|
||||
const screenMocks = vi.hoisted(() => ({ isMobile: true }));
|
||||
vi.mock('$hooks/useScreenSize', () => ({
|
||||
ScreenSize: { Desktop: 'Desktop', Tablet: 'Tablet', Mobile: 'Mobile' },
|
||||
useScreenSizeOptionally: () => (screenMocks.isMobile ? 'Mobile' : 'Desktop'),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMatrixClient', () => ({
|
||||
useMatrixClient: () => ({}),
|
||||
}));
|
||||
vi.mock('$hooks/useMediaAuthentication', () => ({
|
||||
useMediaAuthentication: () => false,
|
||||
}));
|
||||
vi.mock('$hooks/useFavoriteGifs', () => ({
|
||||
useFavoriteGifs: () => ({ gifs: [] }),
|
||||
}));
|
||||
vi.mock('$hooks/useRenderableMediaUrl', () => ({
|
||||
useRenderableMediaUrl: (url: string | undefined) => url,
|
||||
}));
|
||||
vi.mock('$hooks/useObjectURL', () => ({
|
||||
useCreateObjectURL: () => (value: string) => value,
|
||||
}));
|
||||
|
||||
const imageContent = (
|
||||
<ImageContent
|
||||
url="https://example.com/image.png"
|
||||
renderImage={() => <img alt="preview" />}
|
||||
renderViewer={() => <div>viewer</div>}
|
||||
/>
|
||||
);
|
||||
|
||||
const touchTap = (target: Element) => {
|
||||
fireEvent.pointerDown(target, {
|
||||
pointerId: 1,
|
||||
pointerType: 'touch',
|
||||
isPrimary: true,
|
||||
clientX: 10,
|
||||
clientY: 10,
|
||||
});
|
||||
fireEvent.pointerUp(target, {
|
||||
pointerId: 1,
|
||||
pointerType: 'touch',
|
||||
isPrimary: true,
|
||||
clientX: 10,
|
||||
clientY: 10,
|
||||
});
|
||||
fireEvent.click(target);
|
||||
};
|
||||
|
||||
// Mirrors Message.tsx: an enclosing long-press timer that media gestures must
|
||||
// not trigger (media containers are marked `data-gestures="ignore"`).
|
||||
const renderWithLongPress = (children: ReactNode, onLongPress: () => void) =>
|
||||
render(
|
||||
<div
|
||||
onTouchStart={(evt) => {
|
||||
const target = evt.target as Element;
|
||||
if (target.closest('[data-gestures="ignore"]')) return;
|
||||
setTimeout(onLongPress, 500);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
describe('ImageContent', () => {
|
||||
it('opens the viewer after one tap on idle media', async () => {
|
||||
render(imageContent);
|
||||
|
||||
touchTap(screen.getByRole('button', { name: 'View' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('viewer')).toBeInTheDocument());
|
||||
expect(screen.getByAltText('preview').closest('[data-gestures="ignore"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('does not mount hover controls for touch pointer entry', () => {
|
||||
render(imageContent);
|
||||
|
||||
const media = screen.getByRole('button', { name: 'View' }).closest('[data-gestures="ignore"]');
|
||||
expect(media).not.toBeNull();
|
||||
fireEvent.pointerEnter(media!, { pointerType: 'touch' });
|
||||
expect(screen.queryByTitle('Hide Image')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.pointerEnter(media!, { pointerType: 'mouse' });
|
||||
expect(screen.getByTitle('Hide Image')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps media touches out of an enclosing message long-press timer', () => {
|
||||
vi.useFakeTimers();
|
||||
const messageLongPress = vi.fn<() => void>();
|
||||
try {
|
||||
renderWithLongPress(imageContent, messageLongPress);
|
||||
|
||||
const view = screen.getByRole('button', { name: 'View' });
|
||||
fireEvent.touchStart(view, {
|
||||
touches: [{ identifier: 1, clientX: 10, clientY: 10 }],
|
||||
});
|
||||
touchTap(view);
|
||||
vi.advanceTimersByTime(600);
|
||||
|
||||
expect(messageLongPress).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('still allows ordinary message touches to start long press', () => {
|
||||
vi.useFakeTimers();
|
||||
const messageLongPress = vi.fn<() => void>();
|
||||
try {
|
||||
renderWithLongPress(<span>ordinary message</span>, messageLongPress);
|
||||
|
||||
fireEvent.touchStart(screen.getByText('ordinary message'), {
|
||||
touches: [{ identifier: 1, clientX: 10, clientY: 10 }],
|
||||
});
|
||||
vi.advanceTimersByTime(600);
|
||||
|
||||
expect(messageLongPress).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -53,6 +53,8 @@ import {
|
||||
import { useFavoriteGifs } from '$hooks/useFavoriteGifs';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import { useCreateObjectURL } from '$hooks/useObjectURL';
|
||||
import { ScreenSize, useScreenSizeOptionally } from '$hooks/useScreenSize';
|
||||
import { useMobileTapActivation } from '$hooks/useMobileTapActivation';
|
||||
import { ModalOverlay } from '$components/modal-overlay/ModalOverlay';
|
||||
|
||||
export function checkIfGif(url: string, mimetype?: string, body?: string) {
|
||||
@@ -136,6 +138,7 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
) => {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const isMobile = useScreenSizeOptionally() === ScreenSize.Mobile;
|
||||
const blurHash = validBlurHash(info?.[MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]);
|
||||
|
||||
const [load, setLoad] = useState(false);
|
||||
@@ -216,6 +219,19 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
loadSrc().catch(() => undefined);
|
||||
};
|
||||
|
||||
const handleView = async () => {
|
||||
if (srcState.status !== AsyncStatus.Idle) return;
|
||||
try {
|
||||
const src = await loadSrc();
|
||||
if (src !== undefined) setViewer(true);
|
||||
} catch {
|
||||
// The existing error state is handled by the async callback.
|
||||
}
|
||||
};
|
||||
const viewActivation = useMobileTapActivation(isMobile, () => {
|
||||
void handleView();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (autoPlay) loadSrc().catch(() => undefined);
|
||||
}, [autoPlay, loadSrc]);
|
||||
@@ -250,6 +266,7 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
return (
|
||||
<Box
|
||||
className={classNames(rootClass, className)}
|
||||
data-gestures="ignore"
|
||||
style={{
|
||||
...fillPreviewSlotStyle,
|
||||
...intrinsicSizingStyle,
|
||||
@@ -257,8 +274,12 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
}}
|
||||
{...props}
|
||||
ref={ref}
|
||||
onPointerEnter={() => setIsHovered(true)}
|
||||
onPointerLeave={() => setIsHovered(false)}
|
||||
onPointerEnter={(evt) => {
|
||||
if (evt.pointerType === 'mouse' || evt.pointerType === 'pen') setIsHovered(true);
|
||||
}}
|
||||
onPointerLeave={(evt) => {
|
||||
if (evt.pointerType === 'mouse' || evt.pointerType === 'pen') setIsHovered(false);
|
||||
}}
|
||||
>
|
||||
{srcState.status === AsyncStatus.Success && (
|
||||
<ModalOverlay open={viewer} requestClose={() => setViewer(false)}>
|
||||
@@ -291,14 +312,13 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
onClick={loadSrc}
|
||||
{...viewActivation}
|
||||
>
|
||||
<Button
|
||||
variant="Secondary"
|
||||
fill="Solid"
|
||||
radii="300"
|
||||
size="300"
|
||||
onClick={loadSrc}
|
||||
before={sizedIcon(Image, 'Inherit', { filled: true })}
|
||||
>
|
||||
<Text size="B300">View</Text>
|
||||
|
||||
@@ -986,7 +986,14 @@ function MessageInternal(
|
||||
WebkitTapHighlightColor: 'transparent',
|
||||
}}
|
||||
onContextMenu={contextMenuHandler}
|
||||
onTouchStart={menu.triggerProps.onTouchStart}
|
||||
onTouchStart={(evt) => {
|
||||
const target = evt.target instanceof Element ? evt.target : undefined;
|
||||
if (target?.closest('[data-gestures="ignore"]')) {
|
||||
menu.triggerProps.onTouchCancel();
|
||||
return;
|
||||
}
|
||||
menu.triggerProps.onTouchStart(evt);
|
||||
}}
|
||||
onTouchEnd={menu.triggerProps.onTouchEnd}
|
||||
onTouchMove={menu.triggerProps.onTouchMove}
|
||||
onTouchCancel={menu.triggerProps.onTouchCancel}
|
||||
|
||||
@@ -119,7 +119,6 @@ export const useImageGestures = (active: boolean, step = 0.2, min = 0.1, max = 5
|
||||
prepareForTransform();
|
||||
e.stopPropagation();
|
||||
const target = e.target as HTMLElement;
|
||||
target.setPointerCapture(e.pointerId);
|
||||
|
||||
// Double click zoom
|
||||
const now = Date.now();
|
||||
|
||||
+142
-20
@@ -3,13 +3,14 @@ import FileSaver from 'file-saver';
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
import { showToast } from '$state/toast';
|
||||
import { saveFileToDevice } from './download';
|
||||
import { saveFileToDevice, saveMediaToGallery } from './download';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
androidFs: {
|
||||
checkPublicFilesPermission: vi.fn<() => Promise<boolean>>(),
|
||||
requestPublicFilesPermission: vi.fn<() => Promise<boolean>>(),
|
||||
createNewPublicFile: vi.fn<() => Promise<string>>(),
|
||||
createNewPublicImageFile: vi.fn<() => Promise<string>>(),
|
||||
writeFile: vi.fn<() => Promise<void>>(),
|
||||
setPublicFilePending: vi.fn<() => Promise<void>>(),
|
||||
scanPublicFile: vi.fn<() => Promise<void>>(),
|
||||
@@ -22,6 +23,7 @@ const mocks = vi.hoisted(() => ({
|
||||
isTauri: vi.fn<() => boolean>(),
|
||||
osType: vi.fn<() => string>(),
|
||||
showToast: vi.fn<(text: string, durationMs?: number) => void>(),
|
||||
fetch: vi.fn<(input: string) => Promise<Response>>(),
|
||||
}));
|
||||
const { androidFs, save, writeFile } = mocks;
|
||||
|
||||
@@ -32,33 +34,36 @@ vi.mock('@tauri-apps/api/core', () => ({
|
||||
}));
|
||||
vi.mock('@tauri-apps/plugin-os', () => ({ type: mocks.osType }));
|
||||
vi.mock('$state/toast', () => ({ showToast: mocks.showToast }));
|
||||
vi.mock('$utils/fetch', () => ({ fetch: mocks.fetch }));
|
||||
vi.mock('tauri-plugin-android-fs-api', () => ({
|
||||
AndroidFs: mocks.androidFs,
|
||||
AndroidPublicGeneralPurposeDir: { Download: 'Download' },
|
||||
AndroidPublicImageDir: { Pictures: 'Pictures' },
|
||||
}));
|
||||
vi.mock('@tauri-apps/plugin-dialog', () => ({ save: mocks.save }));
|
||||
vi.mock('@tauri-apps/plugin-fs', () => ({ writeFile: mocks.writeFile }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(isTauri).mockReturnValue(true);
|
||||
vi.mocked(osType).mockReturnValue('android');
|
||||
vi.mocked(invoke).mockResolvedValue(true);
|
||||
androidFs.checkPublicFilesPermission.mockResolvedValue(true);
|
||||
androidFs.requestPublicFilesPermission.mockResolvedValue(true);
|
||||
androidFs.createNewPublicFile.mockResolvedValue('content://download/file');
|
||||
androidFs.createNewPublicImageFile.mockResolvedValue('content://media/image');
|
||||
androidFs.writeFile.mockResolvedValue(undefined);
|
||||
androidFs.setPublicFilePending.mockResolvedValue(undefined);
|
||||
androidFs.scanPublicFile.mockResolvedValue(undefined);
|
||||
androidFs.removeFile.mockResolvedValue(undefined);
|
||||
save.mockResolvedValue(null);
|
||||
writeFile.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('saveFileToDevice', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(isTauri).mockReturnValue(true);
|
||||
vi.mocked(osType).mockReturnValue('android');
|
||||
vi.mocked(invoke).mockResolvedValue(true);
|
||||
androidFs.checkPublicFilesPermission.mockResolvedValue(true);
|
||||
androidFs.requestPublicFilesPermission.mockResolvedValue(true);
|
||||
androidFs.createNewPublicFile.mockResolvedValue('content://download/file');
|
||||
androidFs.writeFile.mockResolvedValue(undefined);
|
||||
androidFs.setPublicFilePending.mockResolvedValue(undefined);
|
||||
androidFs.scanPublicFile.mockResolvedValue(undefined);
|
||||
androidFs.removeFile.mockResolvedValue(undefined);
|
||||
save.mockResolvedValue(null);
|
||||
writeFile.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('scans an Android Downloads file after making it public', async () => {
|
||||
await saveFileToDevice(new Blob(['data'], { type: 'text/plain' }), 'file.txt');
|
||||
|
||||
@@ -112,3 +117,120 @@ describe('saveFileToDevice', () => {
|
||||
expect(FileSaver.saveAs).toHaveBeenCalledWith(expect.any(Blob), 'file.txt');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saveMediaToGallery', () => {
|
||||
it('saves Android images to Pictures through the public image API', async () => {
|
||||
await saveMediaToGallery(new Blob(['data']), 'photo.png', 'image/png');
|
||||
|
||||
expect(androidFs.createNewPublicImageFile).toHaveBeenCalledWith(
|
||||
'Pictures',
|
||||
'photo.png',
|
||||
'image/png',
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
expect(androidFs.writeFile).toHaveBeenCalledWith(
|
||||
'content://media/image',
|
||||
expect.any(Uint8Array)
|
||||
);
|
||||
expect(androidFs.setPublicFilePending).toHaveBeenCalledWith('content://media/image', false);
|
||||
expect(androidFs.scanPublicFile).toHaveBeenCalledWith('content://media/image');
|
||||
expect(showToast).toHaveBeenCalledWith('Saved to Gallery');
|
||||
});
|
||||
|
||||
it('rejects video media explicitly without touching any backend or falling back', async () => {
|
||||
await expect(
|
||||
saveMediaToGallery(new Blob(['data']), 'clip.mp4', 'video/mp4')
|
||||
).rejects.toThrow('Only image media can be saved to the gallery');
|
||||
|
||||
expect(androidFs.createNewPublicImageFile).not.toHaveBeenCalled();
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
expect(showToast).not.toHaveBeenCalled();
|
||||
expect(FileSaver.saveAs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cleans up the pending Android gallery file and does not fall back when writing fails', async () => {
|
||||
androidFs.writeFile.mockRejectedValue(new Error('write failed'));
|
||||
|
||||
await saveMediaToGallery(new Blob(['data']), 'photo.png', 'image/png');
|
||||
|
||||
expect(androidFs.removeFile).toHaveBeenCalledWith('content://media/image');
|
||||
expect(showToast).toHaveBeenCalledWith('Failed to save to gallery: write failed');
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
expect(FileSaver.saveAs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends media bytes to the native Photos command on iOS', async () => {
|
||||
vi.mocked(osType).mockReturnValue('ios');
|
||||
|
||||
await saveMediaToGallery(new Blob(['data']), 'photo.png', 'image/png');
|
||||
|
||||
expect(invoke).toHaveBeenCalledWith('save_media_to_photos', {
|
||||
filename: 'photo.png',
|
||||
mimeType: 'image/png',
|
||||
bytes: [100, 97, 116, 97],
|
||||
});
|
||||
expect(showToast).toHaveBeenCalledWith('Saved to Photos');
|
||||
expect(androidFs.createNewPublicImageFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a failure toast when the iOS Photos command rejects', async () => {
|
||||
vi.mocked(osType).mockReturnValue('ios');
|
||||
vi.mocked(invoke).mockRejectedValue(new Error('photos unavailable'));
|
||||
|
||||
await saveMediaToGallery(new Blob(['data']), 'photo.png', 'image/png');
|
||||
|
||||
expect(showToast).toHaveBeenCalledWith('Failed to save to photos: photos unavailable');
|
||||
});
|
||||
|
||||
it('rejects non-media types without touching any backend', async () => {
|
||||
await expect(
|
||||
saveMediaToGallery(new Blob(['data']), 'doc.pdf', 'application/pdf')
|
||||
).rejects.toThrow('Only image media can be saved to the gallery');
|
||||
|
||||
expect(androidFs.createNewPublicImageFile).not.toHaveBeenCalled();
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
expect(showToast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects on desktop platforms and in the browser instead of falling back', async () => {
|
||||
vi.mocked(osType).mockReturnValue('macos');
|
||||
await expect(saveMediaToGallery(new Blob(['data']), 'photo.png', 'image/png')).rejects.toThrow(
|
||||
/not supported/
|
||||
);
|
||||
|
||||
vi.mocked(isTauri).mockReturnValue(false);
|
||||
await expect(saveMediaToGallery(new Blob(['data']), 'photo.png', 'image/png')).rejects.toThrow(
|
||||
/only available/
|
||||
);
|
||||
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
expect(FileSaver.saveAs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows exactly one gallery failure toast when fetching the media fails on Android', async () => {
|
||||
mocks.fetch.mockRejectedValueOnce(new Error('network down'));
|
||||
|
||||
await saveMediaToGallery('mxc://example/photo.png', 'photo.png', 'image/png');
|
||||
|
||||
expect(showToast).toHaveBeenCalledTimes(1);
|
||||
expect(showToast).toHaveBeenCalledWith('Failed to save to gallery: network down');
|
||||
expect(androidFs.createNewPublicImageFile).not.toHaveBeenCalled();
|
||||
expect(androidFs.removeFile).not.toHaveBeenCalled();
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
expect(FileSaver.saveAs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows exactly one photos failure toast when blob conversion fails on iOS', async () => {
|
||||
vi.mocked(osType).mockReturnValue('ios');
|
||||
mocks.fetch.mockResolvedValueOnce({
|
||||
blob: () => Promise.reject(new Error('decode failed')),
|
||||
} as unknown as Response);
|
||||
|
||||
await saveMediaToGallery('mxc://example/photo.png', 'photo.png', 'image/png');
|
||||
|
||||
expect(showToast).toHaveBeenCalledTimes(1);
|
||||
expect(showToast).toHaveBeenCalledWith('Failed to save to photos: decode failed');
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
expect(FileSaver.saveAs).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -57,6 +57,70 @@ async function resolveBlob(input: Blob | string): Promise<Blob> {
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
export async function saveMediaToGallery(
|
||||
input: Blob | string,
|
||||
filename: string,
|
||||
mimeType: string
|
||||
): Promise<void> {
|
||||
const mediaMimeType = mimeType.trim().toLowerCase();
|
||||
if (!mediaMimeType.startsWith('image/')) {
|
||||
throw new Error(`Only image media can be saved to the gallery (received "${mimeType}")`);
|
||||
}
|
||||
if (!isTauri()) {
|
||||
throw new Error('Saving to the gallery is only available in the Android and iOS apps');
|
||||
}
|
||||
|
||||
const platform = osType();
|
||||
if (platform !== 'android' && platform !== 'ios') {
|
||||
throw new Error(`Saving to the gallery is not supported on ${platform}`);
|
||||
}
|
||||
|
||||
if (platform === 'android') {
|
||||
const { AndroidFs, AndroidPublicImageDir } = await import('tauri-plugin-android-fs-api');
|
||||
let uri: Awaited<ReturnType<typeof AndroidFs.createNewPublicImageFile>> | undefined;
|
||||
try {
|
||||
const blob = await resolveBlob(input);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
|
||||
if (!(await AndroidFs.checkPublicFilesPermission())) {
|
||||
const granted = await AndroidFs.requestPublicFilesPermission();
|
||||
if (!granted) throw new Error('Storage permission was denied');
|
||||
}
|
||||
|
||||
uri = await AndroidFs.createNewPublicImageFile(
|
||||
AndroidPublicImageDir.Pictures,
|
||||
filename,
|
||||
mediaMimeType,
|
||||
{ isPending: true, requestPermission: true }
|
||||
);
|
||||
await AndroidFs.writeFile(uri, bytes);
|
||||
await AndroidFs.setPublicFilePending(uri, false);
|
||||
await AndroidFs.scanPublicFile(uri);
|
||||
showToast('Saved to Gallery');
|
||||
} catch (error) {
|
||||
if (uri) await AndroidFs.removeFile(uri).catch(() => undefined);
|
||||
const message = error instanceof Error ? error.message : 'unknown error';
|
||||
showToast(`Failed to save to gallery: ${message}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const blob = await resolveBlob(input);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
|
||||
await invoke('save_media_to_photos', {
|
||||
filename,
|
||||
mimeType: mediaMimeType,
|
||||
bytes: Array.from(bytes),
|
||||
});
|
||||
showToast('Saved to Photos');
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'unknown error';
|
||||
showToast(`Failed to save to photos: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveFileToDevice(
|
||||
input: Blob | string,
|
||||
filename: string,
|
||||
|
||||
Reference in new issue
Block a user