Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: a better lightbox (#1638)
Peter Chinman3836897cef84
diff --git a/js/app/bun.lock b/js/app/bun.lockindex 4622694603..ff2a462527 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -38,7 +38,6 @@"@lexical/utils": "^0.32.1","@lukemorales/query-key-factory": "^1.3.4","@normy/query-core": "^0.21.0",- "@panzoom/panzoom": "^4.6.0","@phosphor-icons/core": "^2.1.1","@solid-primitives/audio": "^1.4.2","@solid-primitives/broadcast-channel": "^0.1.1",@@ -70,6 +69,7 @@"@tauri-apps/plugin-websocket": "~2","@thisbeyond/solid-dnd": "^0.7.5","@vitest/ui": "^4.0.17",+ "@zoompinch/core": "^0.0.38","async-lock": "^1.4.1","async-mutex": "^0.5.0","brace-expansion": "^4.0.1",@@ -878,8 +878,6 @@"@orval/zod": ["@orval/[email protected]", "", { "dependencies": { "@orval/core": "7.13.0", "lodash.uniq": "^4.5.0", "openapi3-ts": "4.5.0" } }, "sha512-jEEj0uRO5D5D1CHKQdth5Atl5Ap4/P21SMiOFmVpiArlXr4LQtMpbkiPVM2tsQXIhtC38c9oMt8+rOx1rYSjcw=="],- "@panzoom/panzoom": ["@panzoom/[email protected]", "", {}, "sha512-3KxkY1lNKFn98fW5ZFR6vV0YzsXj3I4EQDyFWSXME6/cic86eSS7VjuqIjrA3PEpySo0r5fFtlX8eYCt4JPUFQ=="],-"@paralleldrive/cuid2": ["@paralleldrive/[email protected]", "", { "dependencies": { "@noble/hashes": "^1.1.5" } }, "sha512-ZOBkgDwEdoYVlSeRbYYXs0S9MejQofiVYoTbKzy/6GQa39/q5tQU2IX46+shYnUkpEl3wc+J6wRlar7r2EK2xA=="],"@phosphor-icons/core": ["@phosphor-icons/[email protected]", "", {}, "sha512-v4ARvrip4qBCImOE5rmPUylOEK4iiED9ZyKjcvzuezqMaiRASCHKcRIuvvxL/twvLpkfnEODCOJp5dM4eZilxQ=="],@@ -1448,6 +1446,8 @@"@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-s9Kuh0nE/2+nKrvmKNMB2fE5Zlr3DL2t3OFKM55v5jRcfCOxbkOHhQoshoFum5mmXIfEtRXtLCWmkeTJsVjE9w=="],+ "@zoompinch/core": ["@zoompinch/[email protected]", "", {}, "sha512-lsFy8S1XG6NJTFmgCtpXzS1tfxheA7UeZuy6ahd6ENlxNh4Rn1BvJN5pD9wStZmN7a064D8FAT9WvmsZDFt9Mw=="],+"abort-controller": ["[email protected]", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],"acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="],diff --git a/js/app/package.json b/js/app/package.jsonindex ede3af508c..e3ac76747e 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -54,7 +54,6 @@"@lexical/utils": "^0.32.1","@lukemorales/query-key-factory": "^1.3.4","@normy/query-core": "^0.21.0",- "@panzoom/panzoom": "^4.6.0","@phosphor-icons/core": "^2.1.1","@solid-primitives/audio": "^1.4.2","@solid-primitives/broadcast-channel": "^0.1.1",@@ -86,6 +85,7 @@"@tauri-apps/plugin-websocket": "~2","@thisbeyond/solid-dnd": "^0.7.5","@vitest/ui": "^4.0.17",+ "@zoompinch/core": "^0.0.38","async-lock": "^1.4.1","async-mutex": "^0.5.0","brace-expansion": "^4.0.1",diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsxindex 6050978089..1c759937b5 100644--- a/js/app/packages/app/component/Layout.tsx+++ b/js/app/packages/app/component/Layout.tsx@@ -84,20 +84,11 @@ export function Layout(props: RouteSectionProps) {return (<divclass={cn(- 'relative flex flex-col justify-between w-dvw h-[calc(var(--dvh,1dvh)*100)]',+ 'relative flex flex-col justify-between w-dvw h-[calc(var(--dvh,1dvh)*100)] pt-[var(--safe-top)] pl-[var(--safe-left)] pr-[var(--safe-right)]',{- 'pb-[max(env(safe-area-inset-bottom,0px),var(--tauri-inset-bottom,0px))]':- !virtualKeyboardVisible(),+ 'pb-[var(--safe-bottom)]': !virtualKeyboardVisible(),})}- style={{- 'padding-top':- 'max(env(safe-area-inset-top, 0px), var(--tauri-inset-top, 0px))',- 'padding-left':- 'max(env(safe-area-inset-left, 0px), var(--tauri-inset-left, 0px))',- 'padding-right':- 'max(env(safe-area-inset-right, 0px), var(--tauri-inset-right, 0px))',- }}><Suspense><Show when={isAuthenticated()}>diff --git a/js/app/packages/app/index.css b/js/app/packages/app/index.cssindex cf1785a9a1..15406b0cc1 100644--- a/js/app/packages/app/index.css+++ b/js/app/packages/app/index.css@@ -495,6 +495,10 @@:root {--viewport-padding: 16px;--keyboard-height: 0px;+ --safe-top: max(env(safe-area-inset-top, 0px), var(--tauri-inset-top, 0px));+ --safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--tauri-inset-bottom, 0px));+ --safe-left: max(env(safe-area-inset-left, 0px), var(--tauri-inset-left, 0px));+ --safe-right: max(env(safe-area-inset-right, 0px), var(--tauri-inset-right, 0px));}/** isolate the app-root stacking context from the kobalte dialog and modal stacking context */@@ -741,6 +745,15 @@ html[data-modality="keyboard"] [contenteditable="true"]:focus-visible::after {--documentation: "Set this element as a bounding scope for the ScopedPortal component";}+/* Apply to the content wrapper div inside any Dialog.Portal (not the overlay).+ Keeps UI elements within device safe areas (notch, home indicator, etc.). */+@utility safe-insets {+ padding-top: var(--safe-top);+ padding-bottom: var(--safe-bottom);+ padding-left: var(--safe-left);+ padding-right: var(--safe-right);+}+:root {--thread-shift: 32px;--user-icon-width: 36px;diff --git a/js/app/packages/core/component/ImageGalleryPreview.tsx b/js/app/packages/core/component/ImageGalleryPreview.tsxindex 39427c5ddc..b9811adae6 100644--- a/js/app/packages/core/component/ImageGalleryPreview.tsx+++ b/js/app/packages/core/component/ImageGalleryPreview.tsx@@ -1,30 +1,18 @@import { SERVER_HOSTS } from '@core/constant/servers';-import * as stackingContext from '@core/constant/stackingContext';-import { isMobile } from '@core/mobile/isMobile';import { isTouchDevice } from '@core/mobile/isTouchDevice';import ExpandIcon from '@icon/regular/arrows-out-simple.svg';-import ChevronLeftIcon from '@icon/regular/caret-left.svg';-import ChevronRightIcon from '@icon/regular/caret-right.svg';import ClipboardIcon from '@icon/regular/clipboard.svg';import ThreeDotsIcon from '@icon/regular/dots-three-vertical.svg';import DownloadIcon from '@icon/regular/download-simple.svg';import TrashIcon from '@icon/regular/trash.svg';-import XIcon from '@icon/regular/x.svg';import { Dialog } from '@kobalte/core/dialog';import { DropdownMenu } from '@kobalte/core/dropdown-menu';-import Panzoom, { type PanzoomObject } from '@panzoom/panzoom';-import {- type Component,- createEffect,- createSignal,- For,- onCleanup,- Show,-} from 'solid-js';+import { type Component, createSignal, For, Show } from 'solid-js';+import { copyImageToClipboard, downloadImage } from '../util/imageActions';import { platformFetch } from '../util/platformFetch';import { DeprecatedIconButton } from './DeprecatedIconButton';+import { Lightbox } from './Lightbox';import { DropdownMenuContent, MenuItem, MenuSeparator } from './Menu';-import { toast } from './Toast/Toast';type ImageData = {id: string;@@ -48,398 +36,53 @@ const THEMES = {'size-23 object-cover rounded-2xl border border-edge hover:opacity-80 select-none',dynamic:'min-w-[100px] max-h-[200px] object-contain w-full rounded-2xl select-none border border-edge hover:border-accent hover-transition-border',- expanded:- 'max-w-full w-full h-full sm:min-w-[200px] sm:max-h-[80vh] object-contain rounded-2xl select-none',};export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (props) => {const [currentIndex, setCurrentIndex] = createSignal(props.initialIndex ?? 0);- const [imageRef, setImageRef] = createSignal<HTMLImageElement | undefined>();const [clickedIndex, setClickedIndex] = createSignal(0);- const [isDialogOpen, setIsDialogOpen] = createSignal(false);- const [panzoomInstance, setPanzoomInstance] =- createSignal<PanzoomObject | null>(null);- const [isToolbarVisible, setIsToolbarVisible] = createSignal(false);- let hideToolbarTimeout: number | undefined;- // Touch gesture state for swipe detection- const [touchStartX, setTouchStartX] = createSignal(0);- const [touchEndX, setTouchEndX] = createSignal(0);- const [isSwiping, setIsSwiping] = createSignal(false);+ const getImageUrl = (id: string) =>+ `${SERVER_HOSTS['static-file']}/file/${id}`;const currentImageUrl = () => {const id = props.images[currentIndex()]?.id;-- if (!id) return;-- return `${SERVER_HOSTS['static-file']}/file/${id}`;+ return id ? getImageUrl(id) : undefined;};- const getImageUrl = (id: string): string => {- return `${SERVER_HOSTS['static-file']}/file/${id}`;- };-- const hasNext = () => currentIndex() < props.images.length - 1;const hasPrevious = () => currentIndex() > 0;-- const navigateNext = () => {- if (hasNext()) {- setCurrentIndex((prev) => prev + 1);- }- };+ const hasNext = () => currentIndex() < props.images.length - 1;const navigatePrevious = () => {- if (hasPrevious()) {- setCurrentIndex((prev) => prev - 1);- }- };-- const handleTouchStart = (e: TouchEvent) => {- if (!isMobile()) return;- setTouchStartX(e.touches[0].clientX);- setIsSwiping(false);- };-- const handleTouchMove = (e: TouchEvent) => {- if (!isMobile()) return;- setTouchEndX(e.touches[0].clientX);-- const diffX = Math.abs(touchStartX() - e.touches[0].clientX);- if (diffX > 30) {- setIsSwiping(true);- }- };-- const handleTouchEnd = () => {- if (!isMobile() || !isSwiping()) return;-- const swipeThreshold = 50;- const diff = touchStartX() - touchEndX();-- if (Math.abs(diff) > swipeThreshold) {- if (diff > 0) {- navigateNext();- } else {- navigatePrevious();- }- }-- setIsSwiping(false);- setTouchStartX(0);- setTouchEndX(0);+ if (hasPrevious()) setCurrentIndex((i) => i - 1);};-- const downloadImage = async () => {- const imageUrl = currentImageUrl();- if (!imageUrl) return;- try {- const response = await platformFetch(imageUrl);- const blob = await response.blob();- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = `image-${props.images[currentIndex()]?.id}.png`;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(url);- toast.success('Downloaded image');- } catch (err) {- console.error('Download failed:', err);- toast.failure('Failed to download image');- }- };-- const downloadImageById = async (id: string) => {- try {- const response = await platformFetch(getImageUrl(id));- const blob = await response.blob();- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = `image-${id}.png`;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(url);- toast.success('Downloaded image');- } catch (err) {- console.error('Download failed:', err);- toast.failure('Failed to download image');- }- };-- const handleMouseMove = () => {- if (isTouchDevice()) return;-- setIsToolbarVisible(true);-- if (hideToolbarTimeout) {- clearTimeout(hideToolbarTimeout);- }-- hideToolbarTimeout = setTimeout(() => {- setIsToolbarVisible(false);- }, 1000) as unknown as number;- };-- const copyToClipboard = async () => {- const imageUrl = currentImageUrl();- if (!imageUrl) return;- if (isTouchDevice()) {- try {- const blob = await platformFetch(imageUrl).then((res) => res.blob());- const file = new File([blob], 'image.png', { type: blob.type });-- if (navigator.share) {- await navigator.share({- files: [file],- title: 'Share Image',- });- } else {- // Fallback to clipboard methods when share is not available- const isSupported = ClipboardItem.supports(blob.type);- if (isSupported) {- await navigator.clipboard.write([- new ClipboardItem({- [blob.type]: blob,- }),- ]);- toast.success('Copied to clipboard');- } else {- await navigator.clipboard.writeText(imageUrl);- toast.success('Copied image URL to clipboard');- }- }- } catch (err) {- console.error('Share/clipboard operation failed:', err);- try {- await navigator.clipboard.writeText(imageUrl);- toast.success('Copied image URL to clipboard');- } catch {- toast.failure('Failed to copy image');- }- }- } else {- try {- const response = await platformFetch(imageUrl);- const blob = await response.blob();-- const isSupported = ClipboardItem.supports(blob.type);-- if (isSupported) {- await navigator.clipboard.write([- new ClipboardItem({- [blob.type]: blob,- }),- ]);- toast.success('Copied to clipboard');- } else {- await navigator.clipboard.writeText(imageUrl);- toast.success('Copied image URL to clipboard');- }- } catch (err) {- console.error('Clipboard operation failed:', err);- try {- await navigator.clipboard.writeText(imageUrl);- toast.success('Copied image URL to clipboard');- } catch {- toast.failure('Failed to copy image');- }- }- }+ const navigateNext = () => {+ if (hasNext()) setCurrentIndex((i) => i + 1);};- const copyToClipboardById = async (id: string) => {- if (isTouchDevice()) {- try {- const blob = await platformFetch(getImageUrl(id)).then((res) =>- res.blob()- );- const file = new File([blob], 'image.png', { type: blob.type });- if (navigator.share) {- await navigator.share({ files: [file], title: 'Share Image' });- } else {- const isSupported = ClipboardItem.supports(blob.type);- if (isSupported) {- await navigator.clipboard.write([- new ClipboardItem({ [blob.type]: blob }),- ]);- toast.success('Copied to clipboard');- } else {- await navigator.clipboard.writeText(getImageUrl(id));- toast.success('Copied image URL to clipboard');- }- }- } catch (err) {- console.error('Share/clipboard operation failed:', err);- try {- await navigator.clipboard.writeText(getImageUrl(id));- toast.success('Copied image URL to clipboard');- } catch {- toast.failure('Failed to copy image');- }- }- } else {- try {- const response = await platformFetch(getImageUrl(id));- const blob = await response.blob();- const isSupported = ClipboardItem.supports(blob.type);- if (isSupported) {- await navigator.clipboard.write([- new ClipboardItem({ [blob.type]: blob }),- ]);- toast.success('Copied to clipboard');- } else {- await navigator.clipboard.writeText(getImageUrl(id));- toast.success('Copied image URL to clipboard');- }- } catch (err) {- console.error('Clipboard operation failed:', err);- try {- await navigator.clipboard.writeText(getImageUrl(id));- toast.success('Copied image URL to clipboard');- } catch {- toast.failure('Failed to copy image');- }- }- }+ // Thumbnail menu actions (operate on a specific image by ID)+ const copyToClipboardById = (id: string) => {+ const url = getImageUrl(id);+ return copyImageToClipboard(+ () => platformFetch(url).then((r) => r.blob()),+ url+ );};- // let panzoomCleanup: (() => void) | null = null;-- createEffect(() => {- const image = imageRef();- const dialogOpen = isDialogOpen();-- if (!image || !dialogOpen) {- return;- }-- setIsToolbarVisible(false);-- const panzoom = Panzoom(image, {- maxScale: 5,- contain: 'outside',- startScale: 1,- cursor: 'var(--cursor-default)',- });-- setPanzoomInstance(panzoom);-- const updateCursor = () => {- const scale = panzoom.getScale();- if (scale <= 1.01) {- image.style.cursor = 'var(--cursor-default)';- } else {- image.style.cursor = 'var(--cursor-grab)';- }- };-- const handleWheel = (e: WheelEvent) => {- panzoom.zoomWithWheel(e);- };-- image.addEventListener('panzoomchange', updateCursor);- image.addEventListener('wheel', handleWheel);-- // Navigation with keyboard- const handleKeyDown = (e: KeyboardEvent) => {- if (e.key === 'ArrowLeft') {- e.preventDefault();- navigatePrevious();- } else if (e.key === 'ArrowRight') {- e.preventDefault();- navigateNext();- }- };-- window.addEventListener('keydown', handleKeyDown);-- if (!isMobile()) {- setTimeout(() => {- window.addEventListener('mousemove', handleMouseMove);- }, 500);- }-- const handleTouchStartWrapper = (e: TouchEvent) => {- const scale = panzoom.getScale();- if (scale <= 1.01) {- handleTouchStart(e);- }- };-- const handleTouchMoveWrapper = (e: TouchEvent) => {- const scale = panzoom.getScale();- if (scale <= 1.01) {- handleTouchMove(e);- if (isSwiping()) {- e.preventDefault();- }- }- };-- const handleTouchEndWrapper = () => {- const scale = panzoom.getScale();- if (scale <= 1.01) {- handleTouchEnd();- }- };-- if (isMobile()) {- image.addEventListener('touchstart', handleTouchStartWrapper, {- passive: true,- });- image.addEventListener('touchmove', handleTouchMoveWrapper, {- passive: false,- });- image.addEventListener('touchend', handleTouchEndWrapper, {- passive: true,- });- }-- onCleanup(() => {- panzoom.destroy();- image.removeEventListener('panzoomchange', updateCursor);- image.removeEventListener('wheel', handleWheel);- window.removeEventListener('keydown', handleKeyDown);- window.removeEventListener('mousemove', handleMouseMove);-- if (hideToolbarTimeout) {- clearTimeout(hideToolbarTimeout);- }-- if (isMobile()) {- image.removeEventListener('touchstart', handleTouchStartWrapper);- image.removeEventListener('touchmove', handleTouchMoveWrapper);- image.removeEventListener('touchend', handleTouchEndWrapper);- }- });- });-- createEffect(() => {- if (!isDialogOpen()) return;- currentIndex(); //force re-render-- panzoomInstance()?.reset({ animate: false });- });-- const handleDelete = (attachmentId: string) => {- props.onDelete?.(attachmentId);- };+ const downloadImageById = (id: string) =>+ downloadImage(+ () => platformFetch(getImageUrl(id)).then((r) => r.blob()),+ id+ );return (<Dialogmodal={true}onOpenChange={(isOpen) => {- setIsDialogOpen(isOpen);- if (isOpen) {- setCurrentIndex(clickedIndex());- } else {- setClickedIndex(0);- }+ if (isOpen) setCurrentIndex(clickedIndex());+ else setClickedIndex(0);}}><div class={props.wrapperClass ?? 'flex flex-row flex-wrap gap-2'}>@@ -483,7 +126,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (text="Delete image"icon={TrashIcon}onClick={() =>- handleDelete(props.attachmentIds[index()])+ props.onDelete?.(props.attachmentIds[index()])}/></Show>@@ -519,104 +162,17 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (</div><Dialog.Portal><Dialog.Overlay class="fixed inset-0 z-modal bg-modal-overlay pattern-edge-muted pattern-diagonal-4" />- <div class="fixed inset-0 z-modal w-screen h-screen flex items-center justify-center p-2 pb-6 sm:p-12">- <Dialog.Content class="relative flex items-center justify-center w-full h-full sm:w-auto sm:h-auto bg-panel">- {/* Top toolbar */}- <div- class="absolute top-4 right-4 bg-dialog backdrop-blur-sm rounded-lg border border-edge p-1 flex flex-row items-center gap-1 shadow-md transition-opacity duration-300"- classList={{- 'opacity-100': isMobile() || isToolbarVisible(),- 'opacity-0 pointer-events-none':- !isMobile() && !isToolbarVisible(),- }}- style={{ 'z-index': stackingContext.zModal + 1 }}- >- <DeprecatedIconButton- icon={ClipboardIcon}- theme="clear"- onClick={copyToClipboard}- onTouchEnd={copyToClipboard}- tooltip={{ label: 'Copy image' }}- />- <DeprecatedIconButton- icon={DownloadIcon}- theme="clear"- onClick={downloadImage}- tooltip={{ label: 'Download image' }}- />- <Dialog.CloseButton>- <DeprecatedIconButton- icon={XIcon}- theme="clear"- tooltip={{ label: 'Close' }}- />- </Dialog.CloseButton>- </div>-- {/* Navigation arrows */}- <Show when={!isMobile()}>- <Show when={props.images.length > 1}>- <button- class="absolute left-4 top-1/2 -translate-y-1/2 bg-dialog backdrop-blur-sm rounded-lg border border-edge p-2 shadow-md hover:bg-button transition-opacity duration-300"- classList={{- hidden: !hasPrevious(),- 'opacity-100': isTouchDevice() || isToolbarVisible(),- 'opacity-0 pointer-events-none':- !isTouchDevice() && !isToolbarVisible(),- }}- style={{ 'z-index': stackingContext.zModal + 1 }}- onClick={navigatePrevious}- aria-label="Previous image"- >- <ChevronLeftIcon class="w-5 h-5 text-ink" />- </button>- <button- class="absolute right-4 top-1/2 -translate-y-1/2 bg-dialog backdrop-blur-sm rounded-lg border border-edge p-2 shadow-md hover:bg-button transition-opacity duration-300"- classList={{- hidden: !hasNext(),- 'opacity-100': isTouchDevice() || isToolbarVisible(),- 'opacity-0 pointer-events-none':- !isTouchDevice() && !isToolbarVisible(),- }}- style={{ 'z-index': stackingContext.zModal + 1 }}- onClick={navigateNext}- aria-label="Next image"- >- <ChevronRightIcon class="w-5 h-5 text-ink" />- </button>- </Show>- </Show>-- {/* Navigation indicator */}- <Show when={props.images.length > 1}>- <div- class="absolute top-4 left-4 bg-dialog backdrop-blur-sm rounded-lg border border-edge px-3 py-1.5 shadow-md transition-opacity duration-300"- classList={{- 'opacity-100': isTouchDevice() || isToolbarVisible(),- 'opacity-0 pointer-events-none':- !isTouchDevice() && !isToolbarVisible(),- }}- style={{ 'z-index': stackingContext.zModal + 1 }}- >- <span class="text-sm text-ink font-medium">- {currentIndex() + 1}/{props.images.length}- </span>- </div>- </Show>-- {/* Image container */}- <div class="w-full h-full flex items-center justify-center rounded-2xl overflow-visible">- <img- ref={(el) => {- setImageRef(el);- }}- class={`${THEMES['expanded']} transition-opacity duration-150`}- src={currentImageUrl()}- alt="preview"- />- </div>- </Dialog.Content>- </div>+ <Lightbox+ src={currentImageUrl}+ imageId={() => props.images[currentIndex()]?.id ?? ''}+ onPrevious={hasPrevious() ? navigatePrevious : undefined}+ onNext={hasNext() ? navigateNext : undefined}+ indexLabel={+ props.images.length > 1+ ? () => `${currentIndex() + 1}/${props.images.length}`+ : undefined+ }+ /></Dialog.Portal></Dialog>);diff --git a/js/app/packages/core/component/ImagePreview.tsx b/js/app/packages/core/component/ImagePreview.tsxindex 23f99a5103..99ab65a253 100644--- a/js/app/packages/core/component/ImagePreview.tsx+++ b/js/app/packages/core/component/ImagePreview.tsx@@ -1,5 +1,4 @@import { SERVER_HOSTS } from '@core/constant/servers';-import * as stackingContext from '@core/constant/stackingContext';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { maybeThrow } from '@core/util/maybeResult';import ExpandIcon from '@icon/regular/arrows-out-simple.svg';@@ -7,18 +6,20 @@ import ClipboardIcon from '@icon/regular/clipboard.svg';import ThreeDotsIcon from '@icon/regular/dots-three-vertical.svg';import DownloadIcon from '@icon/regular/download-simple.svg';import TrashIcon from '@icon/regular/trash.svg';-import XIcon from '@icon/regular/x.svg';import { Dialog } from '@kobalte/core/dialog';import { DropdownMenu } from '@kobalte/core/dropdown-menu';-import Panzoom from '@panzoom/panzoom';import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';import { storageServiceClient } from '@service-storage/client';import { fetchBinary } from '@service-storage/util/fetchBinary';import { createEffect, createSignal, onCleanup, Show } from 'solid-js';+import {+ copyImageToClipboard,+ downloadImage as downloadImageAction,+} from '../util/imageActions';import { platformFetch } from '../util/platformFetch';import { DeprecatedIconButton } from './DeprecatedIconButton';+import { Lightbox } from './Lightbox';import { DropdownMenuContent, MenuItem, MenuSeparator } from './Menu';-import { toast } from './Toast/Toast';type ImageData = {id: string;@@ -41,8 +42,6 @@ const THEMES = {'size-15 object-cover rounded-2xl border border-edge hover:opacity-80 select-none',dynamic:'min-w-[100px] max-h-[80vh] object-contain w-full rounded-2xl select-none border border-edge hover:border-accent hover-transition-border',- expanded:- 'max-w-full w-full h-full sm:min-w-[200px] sm:max-h-[80vh] object-contain rounded-2xl select-none',};// NOTE: copied logic from block-image@@ -59,10 +58,6 @@ const getDssImageBlob = async (documentId: string) => {};export function ImagePreview(props: ImagePreviewProps) {- const [imageRef, setImageRef] = createSignal<HTMLImageElement | undefined>();- const [isToolbarVisible, setIsToolbarVisible] = createSignal(false);- let hideToolbarTimeout: number | undefined;-const [imageBlob, setImageBlob] = createSignal<Blob>();const [objectUrl, setObjectUrl] = createSignal<string>();@@ -75,24 +70,19 @@ export function ImagePreview(props: ImagePreviewProps) {};const imageSrc = () => {- if (props.isDss) {- return objectUrl();- }+ if (props.isDss) return objectUrl();return sfsImageUrl();};- // download DSS image+ // Load DSS image blobcreateEffect(() => {if (!props.isDss) return;getDssImageBlob(props.image.id).then((blob) => {- if (!blob) {- throw new Error('Failed to download DSS image');- }+ if (!blob) throw new Error('Failed to download DSS image');setImageBlob(blob);- const url = URL.createObjectURL(blob);- setObjectUrl(url);+ setObjectUrl(URL.createObjectURL(blob));}).catch((err) => {props.onError?.(err);@@ -101,158 +91,17 @@ export function ImagePreview(props: ImagePreviewProps) {onCleanup(() => {const url = objectUrl();- if (!url) return;- URL.revokeObjectURL(url);+ if (url) URL.revokeObjectURL(url);});- const downloadImage = async () => {- const blobUrl = async () => {- if (props.isDss) {- return objectUrl();- }- const response = await platformFetch(sfsImageUrl());- const blob = await response.blob();- const url = URL.createObjectURL(blob);- return url;- };-- try {- const url = await blobUrl();- if (!url) throw new Error('No blob url');- const a = document.createElement('a');- a.href = url;- a.download = `image-${props.image.id}.png`;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(url);- toast.success('Downloaded image');- } catch (err) {- console.error('Download failed:', err);- toast.failure('Failed to download image');- }+ // Thumbnail menu actions+ const getBlob = (): Promise<Blob | undefined> => {+ if (props.isDss) return Promise.resolve(imageBlob());+ return platformFetch(sfsImageUrl()).then((r) => r.blob());};- const handleDelete = () => {- props.onDelete?.();- };-- const handleMouseMove = () => {- setIsToolbarVisible(true);-- if (hideToolbarTimeout) {- clearTimeout(hideToolbarTimeout);- }-- hideToolbarTimeout = setTimeout(() => {- setIsToolbarVisible(false);- }, 1000) as unknown as number;- };-- const copyToClipboard = async () => {- const getBlob = async () => {- if (props.isDss) {- return imageBlob();- }-- const response = await platformFetch(sfsImageUrl());- const blob = await response.blob();- return blob;- };-- const copyUrlFallback = async () => {- try {- await navigator.clipboard.writeText(sfsImageUrl());- toast.success('Copied image URL to clipboard');- } catch {- toast.failure('Failed to copy image');- }- };-- const copyBlobToClipboard = async (blob: Blob) => {- const isSupported = ClipboardItem.supports(blob.type);- if (isSupported) {- await navigator.clipboard.write([- new ClipboardItem({- [blob.type]: blob,- }),- ]);- toast.success('Copied to clipboard');- } else {- await navigator.clipboard.writeText(sfsImageUrl());- toast.success('Copied image URL to clipboard');- }- };-- try {- const blob = await getBlob();- if (!blob) throw new Error('No blob');-- if (isTouchDevice() && navigator.share) {- const file = new File([blob], 'image.png', { type: blob.type });- await navigator.share({- files: [file],- title: 'Share Image',- });- } else {- await copyBlobToClipboard(blob);- }- } catch (err) {- console.error('Share/clipboard operation failed:', err);- await copyUrlFallback();- }- };-- let removePanzoomEventListener: () => void = () => {};- createEffect(() => {- const image = imageRef();- if (!image) {- removePanzoomEventListener();- return;- }-- setIsToolbarVisible(false);-- const panzoom = Panzoom(image, {- maxScale: 5,- contain: 'outside',- startScale: 1,- cursor: 'var(--cursor-default)',- });-- const updateCursor = () => {- const scale = panzoom.getScale();- if (scale <= 1.01) {- image.style.cursor = 'var(--cursor-default)';- } else {- image.style.cursor = 'var(--cursor-grab)';- }- };-- removePanzoomEventListener = () => {- panzoom.destroy();- image.removeEventListener('wheel', panzoom.zoomWithWheel);- image.removeEventListener('panzoomchange', updateCursor);- };-- image.addEventListener('panzoomchange', updateCursor);- image.addEventListener('wheel', panzoom.zoomWithWheel);-- if (!isTouchDevice()) {- setTimeout(() => {- window.addEventListener('mousemove', handleMouseMove);- }, 500);- }-- onCleanup(() => {- removePanzoomEventListener();- window.removeEventListener('mousemove', handleMouseMove);-- if (hideToolbarTimeout) {- clearTimeout(hideToolbarTimeout);- }- });- });+ const copyToClipboard = () => copyImageToClipboard(getBlob, sfsImageUrl());+ const downloadImage = () => downloadImageAction(getBlob, props.image.id);return (<Dialog modal={true}>@@ -284,7 +133,7 @@ export function ImagePreview(props: ImagePreviewProps) {<MenuItemtext="Delete image"icon={TrashIcon}- onClick={handleDelete}+ onClick={() => props.onDelete?.()}/></Show></DropdownMenuContent>@@ -307,7 +156,6 @@ export function ImagePreview(props: ImagePreviewProps) {alt="preview"width={props.image.width}height={props.image.height}- // Prevent long press on image ios behaviorstyle={{'-webkit-touch-callout': 'none','-webkit-user-select': 'none',@@ -323,61 +171,11 @@ export function ImagePreview(props: ImagePreviewProps) {</div><Dialog.Portal><Dialog.Overlay class="fixed inset-0 z-modal bg-modal-overlay pattern-edge-muted pattern-diagonal-4" />- <div class="fixed inset-0 z-modal w-screen h-screen flex items-center justify-center p-2 pb-6 sm:p-12">- <Dialog.Content class="relative flex items-center justify-center w-full h-full sm:w-auto sm:h-auto bg-panel">- <div- class="absolute top-4 right-4 bg-dialog rounded-lg border border-edge p-1 flex flex-row items-center gap-1 shadow-md transition-opacity duration-300"- classList={{- 'opacity-100': isTouchDevice() || isToolbarVisible(),- 'opacity-0 pointer-events-none':- !isTouchDevice() && !isToolbarVisible(),- }}- style={{ 'z-index': stackingContext.zModal + 1 }}- >- <DeprecatedIconButton- icon={ClipboardIcon}- theme="clear"- onClick={copyToClipboard}- onTouchEnd={copyToClipboard}- tooltip={{ label: 'Copy image' }}- />- <DeprecatedIconButton- icon={DownloadIcon}- theme="clear"- onClick={downloadImage}- tooltip={{ label: 'Download image' }}- />- <Dialog.CloseButton>- <DeprecatedIconButton- icon={XIcon}- theme="clear"- tooltip={{ label: 'Close' }}- />- </Dialog.CloseButton>- </div>- <div class="w-full h-full flex items-center justify-center rounded-2xl overflow-visible">- <Show- when={imageSrc()}- fallback={- <div class="flex flex-col items-center justify-center gap-2 w-[60px] h-[60px] border border-edge rounded-md bg-menu">- <Spinner class="w-4 h-4 animate-spin" />- </div>- }- >- <img- ref={(el) => {- setImageRef(el);- }}- class={THEMES['expanded']}- src={imageSrc()}- alt="preview"- width={props.image.width}- height={props.image.height}- />- </Show>- </div>- </Dialog.Content>- </div>+ <Lightbox+ src={imageSrc}+ imageId={() => props.image.id}+ getBlob={props.isDss ? () => Promise.resolve(imageBlob()) : undefined}+ /></Dialog.Portal></Dialog>);diff --git a/js/app/packages/core/component/Lightbox.tsx b/js/app/packages/core/component/Lightbox.tsxnew file mode 100644index 0000000000..5278a99e3f--- /dev/null+++ b/js/app/packages/core/component/Lightbox.tsx@@ -0,0 +1,425 @@+import * as stackingContext from '@core/constant/stackingContext';+import { cn } from '@ui/utils/classname';+import { isMobile } from '@core/mobile/isMobile';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import ChevronLeftIcon from '@icon/regular/caret-left.svg';+import ChevronRightIcon from '@icon/regular/caret-right.svg';+import ClipboardIcon from '@icon/regular/clipboard.svg';+import DownloadIcon from '@icon/regular/download-simple.svg';+import XIcon from '@icon/regular/x.svg';+import { Dialog } from '@kobalte/core/dialog';+import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';+import {+ type Accessor,+ type Component,+ createEffect,+ createMemo,+ createSignal,+ type JSX,+ onCleanup,+ Show,+ untrack,+} from 'solid-js';+import {+ copyImageToClipboard,+ downloadImage as downloadImageAction,+} from '../util/imageActions';+import { platformFetch } from '../util/platformFetch';+import { DeprecatedIconButton } from './DeprecatedIconButton';+import { Zoompinch, type ZoompinchHandle } from './Zoompinch';+import { isIOS } from '@solid-primitives/platform';++const SpinnerIcon: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (p) => (+ <Spinner {...p} class="animate-spin" />+);++type LightboxProps = {+ // Current image to display+ src: Accessor<string | undefined>;+ // Used for the download filename+ imageId: Accessor<string>;+ // Optional pre-fetched blob override (e.g. DSS images). Falls back to fetching `src`.+ getBlob?: () => Promise<Blob | undefined>;+ // Gallery navigation. Passing either enables swipe (mobile) + arrow key (desktop) support.+ // Pass undefined for a direction when that navigation is unavailable (first/last image).+ onPrevious?: () => void;+ onNext?: () => void;+ // "2/5" style indicator — rendered when provided+ indexLabel?: Accessor<string>;+};++export function Lightbox(props: LightboxProps) {+ const [zoompinchHandle, setZoompinchHandle] = createSignal<+ ZoompinchHandle | undefined+ >();+ const [isToolbarVisible, setIsToolbarVisible] = createSignal(false);+ let hideToolbarTimeout: ReturnType<typeof setTimeout> | undefined;++ const handleMouseMove = () => {+ if (isTouchDevice()) return;+ setIsToolbarVisible(true);+ if (hideToolbarTimeout) clearTimeout(hideToolbarTimeout);+ hideToolbarTimeout = setTimeout(() => setIsToolbarVisible(false), 1000);+ };++ const fetchBlob = async (): Promise<Blob | undefined> => {+ if (props.getBlob) return props.getBlob();+ const url = props.src();+ if (!url) return undefined;+ return (await platformFetch(url)).blob();+ };++ // Pre-fetch the blob on iOS so it is already in memory when the user taps+ // copy/download. This keeps navigator.share() close to synchronous with the+ // gesture — the user-activation window expires if a network round-trip is+ // needed. Desktop clipboard doesn't have this constraint.+ const [cachedBlob, setCachedBlob] = createSignal<Blob | undefined>();+ if (isIOS) {+ createEffect(() => {+ props.src(); // re-fetch when navigating to a new image+ setCachedBlob(undefined);+ untrack(() => fetchBlob())+ .then((blob) => {+ if (blob) setCachedBlob(blob);+ })+ .catch(() => {});+ });+ }+ const fetchBlobCached = (): Promise<Blob | undefined> => {+ const cached = cachedBlob();+ return cached ? Promise.resolve(cached) : fetchBlob();+ };++ const [isCopying, setIsCopying] = createSignal(false);+ const [isDownloading, setIsDownloading] = createSignal(false);++ const copyToClipboard = async () => {+ if (isCopying()) return;+ setIsCopying(true);+ try {+ await copyImageToClipboard(fetchBlobCached, props.src() ?? '');+ } finally {+ setIsCopying(false);+ }+ };++ const downloadImage = async () => {+ if (isDownloading()) return;+ setIsDownloading(true);+ try {+ await downloadImageAction(fetchBlobCached, props.imageId());+ } finally {+ setIsDownloading(false);+ }+ };++ // Reactive cursor state — drives the cursor style on the Zoompinch wrapper.+ const [isDragging, setIsDragging] = createSignal(false);+ const [currentScale, setCurrentScale] = createSignal(1);+ const cursor = createMemo(() => {+ if (isDragging() && currentScale() > 1.01) return 'grab';+ if (currentScale() > 1.01) return 'zoom-out';+ return 'zoom-in';+ });++ // Swipe-to-navigate state (used inside the touch override callbacks below)+ let swipeTouchStartX = 0;+ let swipeTouchEndX = 0;+ let isSwiping = false;+ let zoompinchHandlingTouch = false;++ // Touch override handlers for swipe-to-navigate+ const touchOnStart = (e: TouchEvent, engine: ZoompinchHandle['engine']) => {+ const hasNav = props.onPrevious != null || props.onNext != null;+ const doSwipeDetection =+ isMobile() && hasNav && e.touches.length === 1 && engine.scale <= 1.01;+ if (doSwipeDetection) {+ swipeTouchStartX = e.touches[0].clientX;+ isSwiping = false;+ zoompinchHandlingTouch = false;+ } else {+ engine.handleTouchstart(e);+ zoompinchHandlingTouch = true;+ }+ };++ const touchOnWindowMove = (+ e: TouchEvent,+ engine: ZoompinchHandle['engine']+ ) => {+ if (zoompinchHandlingTouch) {+ engine.handleTouchmove(e);+ return;+ }+ // Second finger appeared mid-gesture: switch to zoompinch+ if (e.touches.length > 1) {+ engine.handleTouchstart(e);+ zoompinchHandlingTouch = true;+ isSwiping = false;+ return;+ }+ swipeTouchEndX = e.touches[0].clientX;+ if (Math.abs(swipeTouchStartX - e.touches[0].clientX) > 30)+ isSwiping = true;+ if (isSwiping) e.preventDefault();+ };++ const touchOnWindowEnd = (+ e: TouchEvent,+ engine: ZoompinchHandle['engine']+ ) => {+ if (zoompinchHandlingTouch) {+ engine.handleTouchend(e);+ zoompinchHandlingTouch = false;+ return;+ }+ if (isSwiping && engine.scale <= 1.01) {+ const diff = swipeTouchStartX - swipeTouchEndX;+ if (Math.abs(diff) > 50) {+ if (diff > 0) props.onNext?.();+ else props.onPrevious?.();+ }+ }+ isSwiping = false;+ swipeTouchStartX = 0;+ swipeTouchEndX = 0;+ zoompinchHandlingTouch = false;+ };++ // Keyboard nav + toolbar fade — active while the Zoompinch handle is set+ createEffect(() => {+ const handle = zoompinchHandle();+ if (!handle) return;+ const { engine, wrapperElement: wrapper } = handle;++ const hasNav = props.onPrevious != null || props.onNext != null;++ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'ArrowLeft') {+ e.preventDefault();+ props.onPrevious?.();+ } else if (e.key === 'ArrowRight') {+ e.preventDefault();+ props.onNext?.();+ }+ };+ if (hasNav) window.addEventListener('keydown', handleKeyDown);++ let mouseMoveListenerTimeoutId: number | undefined;+ if (!isMobile()) {+ mouseMoveListenerTimeoutId = window.setTimeout(+ () => window.addEventListener('mousemove', handleMouseMove),+ 500+ );++ // Track dragging so click-to-zoom and cursor stay in sync+ let isMouseDown = false;+ let mouseDownX = 0;+ let mouseDownY = 0;++ const handleMouseDown = (e: MouseEvent) => {+ isMouseDown = true;+ mouseDownX = e.clientX;+ mouseDownY = e.clientY;+ setIsDragging(false);+ };+ const handleWindowMouseMove = (e: MouseEvent) => {+ if (!isMouseDown) return;+ if (Math.hypot(e.clientX - mouseDownX, e.clientY - mouseDownY) > 5) {+ setIsDragging(true);+ }+ };+ const handleWindowMouseUp = () => {+ isMouseDown = false;+ // Delay reset so the click event (which fires after mouseup) can still+ // read isDragging=true and suppress the zoom-out action.+ setTimeout(() => setIsDragging(false), 0);+ };++ // Click-to-zoom: zoom in at cursor position, or reset if already zoomed+ const handleClick = (e: MouseEvent) => {+ if (isDragging()) return;+ const b = engine.wrapperBounds;+ const relX = (e.clientX - b.x) / b.width;+ const relY = (e.clientY - b.y) / b.height;+ if (engine.scale <= 1.01) {+ engine.applyTransform(2.5, [relX, relY], [relX, relY]);+ } else {+ engine.applyTransform(1, [0.5, 0.5], [0.5, 0.5]);+ }+ };++ wrapper.addEventListener('mousedown', handleMouseDown);+ window.addEventListener('mousemove', handleWindowMouseMove);+ window.addEventListener('mouseup', handleWindowMouseUp);+ wrapper.addEventListener('click', handleClick);++ onCleanup(() => {+ wrapper.removeEventListener('mousedown', handleMouseDown);+ window.removeEventListener('mousemove', handleWindowMouseMove);+ window.removeEventListener('mouseup', handleWindowMouseUp);+ wrapper.removeEventListener('click', handleClick);+ });+ }++ onCleanup(() => {+ if (hasNav) window.removeEventListener('keydown', handleKeyDown);+ window.clearTimeout(mouseMoveListenerTimeoutId);+ window.removeEventListener('mousemove', handleMouseMove);+ if (hideToolbarTimeout) clearTimeout(hideToolbarTimeout);+ });+ });++ // Reset zoom when navigating to a different image.+ createEffect(() => {+ props.src();+ untrack(() => zoompinchHandle())?.engine.applyTransform(+ 1,+ [0.5, 0.5],+ [0.5, 0.5]+ );+ });++ const navButtonClass =+ 'absolute top-1/2 -translate-y-1/2 bg-dialog backdrop-blur-sm rounded-lg border border-edge p-2 shadow-md hover:bg-button transition-opacity duration-300';++ const navVisible = () => isTouchDevice() || isToolbarVisible();++ return (+ <div+ class="fixed inset-0 z-modal flex items-center justify-center"+ style={{+ 'padding-top': 'max(var(--safe-top), 0.5rem)',+ 'padding-bottom': 'max(var(--safe-bottom), 1.5rem)',+ 'padding-left': 'max(var(--safe-left), 0.5rem)',+ 'padding-right': 'max(var(--safe-right), 0.5rem)',+ }}+ >+ <Dialog.Content class="relative flex items-center justify-center w-full h-full sm:w-auto sm:h-auto bg-panel">+ {/* Toolbar */}+ <LightboxToolbar isVisible={isToolbarVisible()}>+ <DeprecatedIconButton+ icon={isCopying() ? SpinnerIcon : ClipboardIcon}+ theme="clear"+ onClick={copyToClipboard}+ disabled={isCopying()}+ tooltip={{ label: 'Copy image' }}+ />+ <DeprecatedIconButton+ icon={isDownloading() ? SpinnerIcon : DownloadIcon}+ theme="clear"+ onClick={downloadImage}+ disabled={isDownloading()}+ tooltip={{ label: 'Download image' }}+ />+ <Dialog.CloseButton>+ <DeprecatedIconButton+ icon={XIcon}+ theme="clear"+ tooltip={{ label: 'Close' }}+ />+ </Dialog.CloseButton>+ </LightboxToolbar>++ {/* Nav arrows — desktop only */}+ <Show when={!isMobile()}>+ <Show when={props.onPrevious}>+ <button+ class={cn(+ navButtonClass,+ 'left-4',+ navVisible() ? 'opacity-100' : 'opacity-0 pointer-events-none'+ )}+ style={{ 'z-index': stackingContext.zModal + 1 }}+ onClick={props.onPrevious}+ aria-label="Previous image"+ >+ <ChevronLeftIcon class="w-5 h-5 text-ink" />+ </button>+ </Show>+ <Show when={props.onNext}>+ <button+ class={cn(+ navButtonClass,+ 'right-4',+ navVisible() ? 'opacity-100' : 'opacity-0 pointer-events-none'+ )}+ style={{ 'z-index': stackingContext.zModal + 1 }}+ onClick={props.onNext}+ aria-label="Next image"+ >+ <ChevronRightIcon class="w-5 h-5 text-ink" />+ </button>+ </Show>+ </Show>++ {/* Index indicator */}+ <Show when={props.indexLabel}>+ <div+ class={cn(+ 'absolute top-4 left-4 bg-dialog backdrop-blur-sm rounded-lg border border-edge px-3 py-1.5 shadow-md transition-opacity duration-300',+ navVisible() ? 'opacity-100' : 'opacity-0 pointer-events-none'+ )}+ style={{ 'z-index': stackingContext.zModal + 1 }}+ >+ <span class="text-sm text-ink font-medium">+ {props.indexLabel?.()}+ </span>+ </div>+ </Show>++ {/* Image */}+ <div class="w-full h-full flex items-center justify-center">+ <Show+ when={props.src()}+ fallback={+ <div class="flex flex-col items-center justify-center gap-2 w-[60px] h-[60px] border border-edge rounded-md bg-menu">+ <Spinner class="w-4 h-4 animate-spin" />+ </div>+ }+ >+ <Zoompinch+ handleRef={setZoompinchHandle}+ clampBounds+ onUpdate={(engine) => setCurrentScale(engine.scale)}+ touch={{+ onStart: touchOnStart,+ onWindowMove: touchOnWindowMove,+ onWindowEnd: touchOnWindowEnd,+ }}+ class="w-full h-full relative overflow-hidden rounded-2xl"+ style={{ cursor: cursor() }}+ >+ <img+ class="w-full h-full sm:min-w-[200px] sm:max-h-[80vh] object-contain select-none"+ style={{ '-webkit-touch-callout': 'none' }}+ src={props.src()}+ alt="preview"+ />+ </Zoompinch>+ </Show>+ </div>+ </Dialog.Content>+ </div>+ );+}++type LightboxToolbarProps = {+ isVisible: boolean;+ children: JSX.Element;+};++export function LightboxToolbar(props: LightboxToolbarProps) {+ return (+ <div+ class="absolute top-4 right-4 bg-dialog backdrop-blur-sm rounded-lg border border-edge p-1 flex flex-row items-center gap-1 shadow-md transition-opacity duration-300"+ classList={{+ 'opacity-100': isMobile() || props.isVisible,+ 'opacity-0 pointer-events-none': !isMobile() && !props.isVisible,+ }}+ style={{ 'z-index': stackingContext.zModal + 1 }}+ >+ {props.children}+ </div>+ );+}diff --git a/js/app/packages/core/component/Zoompinch.tsx b/js/app/packages/core/component/Zoompinch.tsxnew file mode 100644index 0000000000..33b03a41fb--- /dev/null+++ b/js/app/packages/core/component/Zoompinch.tsx@@ -0,0 +1,159 @@+import { Zoompinch as ZoompinchEngine } from '@zoompinch/core';+import { createEffect, createSignal, type JSX, onCleanup } from 'solid-js';++export type ZoompinchHandle = {+ engine: ZoompinchEngine;+ wrapperElement: HTMLDivElement;+};++export type ZoompinchProps = {+ handleRef?: (handle: ZoompinchHandle | undefined) => void;+ minScale?: number;+ maxScale?: number;+ clampBounds?: boolean;+ rotation?: boolean;+ /** Called on every transform update. */+ onUpdate?: (engine: ZoompinchEngine) => void;+ /**+ * Override the wheel handler. Defaults to forwarding to the engine, which+ * zooms when ctrlKey is held and pans otherwise (trackpad-friendly).+ */+ onWheel?: (e: WheelEvent, engine: ZoompinchEngine) => void;+ /**+ * Override individual touch handlers. Each defaults to forwarding directly+ * to the engine. Useful for intercepting swipes for gallery navigation.+ */+ touch?: {+ onStart?: (e: TouchEvent, engine: ZoompinchEngine) => void;+ onWindowMove?: (e: TouchEvent, engine: ZoompinchEngine) => void;+ onWindowEnd?: (e: TouchEvent, engine: ZoompinchEngine) => void;+ };+ class?: string;+ style?: JSX.CSSProperties;+ children?: JSX.Element;+};++/**+ * SolidJS component that wraps a Zoompinch engine. Renders a wrapper div with+ * a .canvas child and wires all mouse, wheel, touch, and gesture event handlers.+ *+ * Exposes an imperative handle via `ref` for calling `applyTransform` etc.+ * The handle is set when the engine initialises and cleared on unmount.+ */+export function Zoompinch(props: ZoompinchProps) {+ const [wrapperRef, setWrapperRef] = createSignal<+ HTMLDivElement | undefined+ >();++ // Snapshot stable config at component init — not reactive.+ // The engine doesn't support hot-reloading options, so this is intentional.+ const minScale = props.minScale ?? 1;+ const maxScale = props.maxScale ?? 5;+ const clampBounds = props.clampBounds ?? false;+ const rotation = props.rotation ?? false;+ const onUpdate = props.onUpdate;+ const onWheelOverride = props.onWheel;+ const touch = props.touch ?? {};+ const ref = props.handleRef;++ createEffect(() => {+ const wrapper = wrapperRef();+ if (!wrapper) return;++ const e = new ZoompinchEngine(+ wrapper,+ { top: 0, right: 0, bottom: 0, left: 0 },+ 0, // translateX+ 0, // translateY+ 1, // scale+ 0, // rotate+ minScale,+ maxScale,+ clampBounds,+ rotation+ );++ // Zoompinch initializes canvasBounds/wrapperBounds in a rAF callback, but+ // its ResizeObserver callbacks fire before rAF and access canvasBounds —+ // crashing if uninitialized. Pre-populate synchronously as a workaround.+ const canvasEl = wrapper.querySelector('.canvas') as HTMLElement | null;+ if (canvasEl) {+ e.canvasBounds = canvasEl.getBoundingClientRect();+ e.wrapperBounds = wrapper.getBoundingClientRect();+ }++ e.addEventListener('init', () =>+ e.applyTransform(1, [0.5, 0.5], [0.5, 0.5])+ );+ if (onUpdate) e.addEventListener('update', () => onUpdate(e));++ // Mouse pan (mousedown on wrapper, move/up on window)+ const handleMouseDown = (ev: MouseEvent) => e.handleMousedown(ev);+ const handleWindowMouseMove = (ev: MouseEvent) => e.handleMousemove(ev);+ const handleWindowMouseUp = (ev: MouseEvent) => e.handleMouseup(ev);+ wrapper.addEventListener('mousedown', handleMouseDown);+ window.addEventListener('mousemove', handleWindowMouseMove);+ window.addEventListener('mouseup', handleWindowMouseUp);++ // Scroll wheel zoom+ const handleWheel = (ev: WheelEvent) =>+ onWheelOverride ? onWheelOverride(ev, e) : e.handleWheel(ev);+ wrapper.addEventListener('wheel', handleWheel);++ // Safari desktop pinch-to-zoom via gesture events+ const handleGestureStart = (ev: Event) =>+ e.handleGesturestart(ev as UIEvent);+ const handleGestureChange = (ev: Event) =>+ e.handleGesturechange(ev as UIEvent);+ const handleGestureEnd = (ev: Event) => e.handleGestureend(ev as UIEvent);+ wrapper.addEventListener('gesturestart', handleGestureStart);+ window.addEventListener('gesturechange', handleGestureChange);+ window.addEventListener('gestureend', handleGestureEnd);++ // Touch — overrideable for swipe navigation etc.+ const onTouchStart = touch.onStart ?? ((ev) => e.handleTouchstart(ev));+ const onWindowTouchMove =+ touch.onWindowMove ?? ((ev) => e.handleTouchmove(ev));+ const onWindowTouchEnd =+ touch.onWindowEnd ?? ((ev) => e.handleTouchend(ev));+ const handleTouchStart = (ev: TouchEvent) => onTouchStart(ev, e);+ const handleWindowTouchMove = (ev: TouchEvent) => onWindowTouchMove(ev, e);+ const handleWindowTouchEnd = (ev: TouchEvent) => onWindowTouchEnd(ev, e);+ wrapper.addEventListener('touchstart', handleTouchStart, { passive: true });+ window.addEventListener('touchmove', handleWindowTouchMove, {+ passive: false,+ });+ window.addEventListener('touchend', handleWindowTouchEnd, {+ passive: true,+ });++ ref?.({ engine: e, wrapperElement: wrapper });++ onCleanup(() => {+ ref?.(undefined);+ e.destroy();+ wrapper.removeEventListener('mousedown', handleMouseDown);+ window.removeEventListener('mousemove', handleWindowMouseMove);+ window.removeEventListener('mouseup', handleWindowMouseUp);+ wrapper.removeEventListener('wheel', handleWheel);+ wrapper.removeEventListener('gesturestart', handleGestureStart);+ window.removeEventListener('gesturechange', handleGestureChange);+ window.removeEventListener('gestureend', handleGestureEnd);+ wrapper.removeEventListener('touchstart', handleTouchStart);+ window.removeEventListener('touchmove', handleWindowTouchMove);+ window.removeEventListener('touchend', handleWindowTouchEnd);+ });+ });++ return (+ <div+ ref={setWrapperRef}+ class={props.class}+ style={{ ...props.style, 'touch-action': 'none' }}+ >+ <div class="canvas w-full h-full will-change-transform">+ {props.children}+ </div>+ </div>+ );+}diff --git a/js/app/packages/core/util/imageActions.ts b/js/app/packages/core/util/imageActions.tsnew file mode 100644index 0000000000..0a165ed868--- /dev/null+++ b/js/app/packages/core/util/imageActions.ts@@ -0,0 +1,113 @@+import { toast } from '@core/component/Toast/Toast';+import { isTouchDevice } from '@core/mobile/isTouchDevice';++async function toPng(blob: Blob): Promise<Blob> {+ const bitmap = await createImageBitmap(blob);+ const canvas = document.createElement('canvas');+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;+ const ctx = canvas.getContext('2d');+ if (!ctx) throw new Error('Canvas 2D context unavailable');+ ctx.drawImage(bitmap, 0, 0);+ return new Promise<Blob>((resolve, reject) =>+ canvas.toBlob(+ (b) => (b ? resolve(b) : reject(new Error('Canvas toBlob failed'))),+ 'image/png'+ )+ );+}++export async function copyImageToClipboard(+ getBlob: () => Promise<Blob | undefined>,+ fallbackUrl: string+): Promise<void> {+ try {+ const blob = await getBlob();+ if (!blob) throw new Error('No blob');++ if (isTouchDevice() && navigator.share) {+ try {+ await navigator.share({+ files: [+ new File([blob], 'image.png', {+ type: blob.type || 'image/png',+ }),+ ],+ });+ return;+ } catch (err) {+ if (err instanceof Error && err.name === 'AbortError') return;+ // navigator.share failed (e.g. gesture context expired in dev) —+ // fall back to copying the URL.+ try {+ if (fallbackUrl) await navigator.clipboard.writeText(fallbackUrl);+ toast.success('Copied image URL to clipboard');+ } catch {+ toast.failure('Failed to copy image');+ }+ return;+ }+ }++ // Desktop: normalise to PNG (the only type clipboard reliably supports),+ // then write. Falls back to URL if the clipboard write fails.+ const pngBlob = blob.type === 'image/png' ? blob : await toPng(blob);+ try {+ await navigator.clipboard.write([+ new ClipboardItem({ 'image/png': pngBlob }),+ ]);+ toast.success('Copied to clipboard');+ } catch {+ await navigator.clipboard.writeText(fallbackUrl);+ toast.success('Copied image URL to clipboard');+ }+ } catch (err) {+ console.error('Share/clipboard operation failed:', err);+ try {+ if (fallbackUrl) await navigator.clipboard.writeText(fallbackUrl);+ toast.success('Copied image URL to clipboard');+ } catch {+ toast.failure('Failed to copy image');+ }+ }+}++export async function downloadImage(+ getBlob: () => Promise<Blob | undefined>,+ imageId: string+): Promise<void> {+ try {+ const blob = await getBlob();+ if (!blob) throw new Error('No blob');++ // iOS: Use the native share sheet instead — the user can save to Photos, AirDrop, etc.+ if (isTouchDevice() && navigator.share) {+ try {+ await navigator.share({+ files: [+ new File([blob], `image-${imageId}.png`, {+ type: blob.type || 'image/png',+ }),+ ],+ });+ return;+ } catch (err) {+ if (err instanceof Error && err.name === 'AbortError') return;+ throw err;+ }+ }++ const blobUrl = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = blobUrl;+ a.download = `image-${imageId}.png`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(blobUrl);+ toast.success('Downloaded image');+ } catch (err) {+ console.error('Download failed:', err);+ toast.failure('Failed to download image');+ }+}