asset-viewer.svelte 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <script lang="ts">
  2. import { goto } from '$app/navigation';
  3. import { downloadAssets } from '$lib/stores/download';
  4. import {
  5. AlbumResponseDto,
  6. api,
  7. AssetResponseDto,
  8. AssetTypeEnum,
  9. SharedLinkResponseDto
  10. } from '@api';
  11. import { createEventDispatcher, onDestroy, onMount } from 'svelte';
  12. import ChevronLeft from 'svelte-material-icons/ChevronLeft.svelte';
  13. import ChevronRight from 'svelte-material-icons/ChevronRight.svelte';
  14. import { fly } from 'svelte/transition';
  15. import AlbumSelectionModal from '../shared-components/album-selection-modal.svelte';
  16. import {
  17. notificationController,
  18. NotificationType
  19. } from '../shared-components/notification/notification';
  20. import AssetViewerNavBar from './asset-viewer-nav-bar.svelte';
  21. import DetailPanel from './detail-panel.svelte';
  22. import PhotoViewer from './photo-viewer.svelte';
  23. import VideoViewer from './video-viewer.svelte';
  24. import { assetStore } from '$lib/stores/assets.store';
  25. import { addAssetsToAlbum } from '$lib/utils/asset-utils';
  26. import { browser } from '$app/environment';
  27. export let asset: AssetResponseDto;
  28. export let publicSharedKey = '';
  29. export let showNavigation = true;
  30. export let sharedLink: SharedLinkResponseDto | undefined = undefined;
  31. const dispatch = createEventDispatcher();
  32. let halfLeftHover = false;
  33. let halfRightHover = false;
  34. let isShowDetail = false;
  35. let appearsInAlbums: AlbumResponseDto[] = [];
  36. let isShowAlbumPicker = false;
  37. let addToSharedAlbum = true;
  38. let shouldPlayMotionPhoto = false;
  39. let shouldShowDownloadButton = sharedLink ? sharedLink.allowDownload : true;
  40. let canCopyImagesToClipboard: boolean;
  41. const onKeyboardPress = (keyInfo: KeyboardEvent) => handleKeyboardPress(keyInfo.key);
  42. onMount(async () => {
  43. document.addEventListener('keydown', onKeyboardPress);
  44. getAllAlbums();
  45. // Import hack :( see https://github.com/vadimkorr/svelte-carousel/issues/27#issuecomment-851022295
  46. // TODO: Move to regular import once the package correctly supports ESM.
  47. const module = await import('copy-image-clipboard');
  48. canCopyImagesToClipboard = module.canCopyImagesToClipboard();
  49. });
  50. onDestroy(() => {
  51. if (browser) {
  52. document.removeEventListener('keydown', onKeyboardPress);
  53. }
  54. });
  55. $: asset.id && getAllAlbums(); // Update the album information when the asset ID changes
  56. const getAllAlbums = async () => {
  57. try {
  58. const { data } = await api.albumApi.getAllAlbums(undefined, asset.id);
  59. appearsInAlbums = data;
  60. } catch (e) {
  61. console.error('Error getting album that asset belong to', e);
  62. }
  63. };
  64. const handleKeyboardPress = (key: string) => {
  65. switch (key) {
  66. case 'Escape':
  67. closeViewer();
  68. return;
  69. case 'Delete':
  70. deleteAsset();
  71. return;
  72. case 'i':
  73. isShowDetail = !isShowDetail;
  74. return;
  75. case 'ArrowLeft':
  76. navigateAssetBackward();
  77. return;
  78. case 'ArrowRight':
  79. navigateAssetForward();
  80. return;
  81. }
  82. };
  83. const handleCloseViewer = () => {
  84. isShowDetail = false;
  85. closeViewer();
  86. };
  87. const closeViewer = () => {
  88. dispatch('close');
  89. };
  90. const navigateAssetForward = (e?: Event) => {
  91. e?.stopPropagation();
  92. dispatch('navigate-next');
  93. };
  94. const navigateAssetBackward = (e?: Event) => {
  95. e?.stopPropagation();
  96. dispatch('navigate-previous');
  97. };
  98. const showDetailInfoHandler = () => {
  99. isShowDetail = !isShowDetail;
  100. };
  101. const handleDownload = () => {
  102. if (asset.livePhotoVideoId) {
  103. downloadFile(asset.livePhotoVideoId, true, publicSharedKey);
  104. downloadFile(asset.id, false, publicSharedKey);
  105. return;
  106. }
  107. downloadFile(asset.id, false, publicSharedKey);
  108. };
  109. /**
  110. * Get the filename of the asset based on the user defined template
  111. */
  112. const getTemplateFilename = () => {
  113. const filenameWithExtension = asset.originalPath.split('/').pop() as string;
  114. const filenameWithoutExtension = filenameWithExtension.split('.')[0];
  115. return {
  116. filenameWithExtension,
  117. filenameWithoutExtension
  118. };
  119. };
  120. const downloadFile = async (assetId: string, isLivePhoto: boolean, key: string) => {
  121. try {
  122. const { filenameWithoutExtension } = getTemplateFilename();
  123. const imageExtension = isLivePhoto ? 'mov' : asset.originalPath.split('.')[1];
  124. const imageFileName = filenameWithoutExtension + '.' + imageExtension;
  125. // If assets is already download -> return;
  126. if ($downloadAssets[imageFileName]) {
  127. return;
  128. }
  129. $downloadAssets[imageFileName] = 0;
  130. const { data, status } = await api.assetApi.downloadFile(assetId, key, {
  131. responseType: 'blob',
  132. onDownloadProgress: (progressEvent) => {
  133. if (progressEvent.lengthComputable) {
  134. const total = progressEvent.total;
  135. const current = progressEvent.loaded;
  136. $downloadAssets[imageFileName] = Math.floor((current / total) * 100);
  137. }
  138. }
  139. });
  140. if (!(data instanceof Blob)) {
  141. return;
  142. }
  143. if (status === 200) {
  144. const fileUrl = URL.createObjectURL(data);
  145. const anchor = document.createElement('a');
  146. anchor.href = fileUrl;
  147. anchor.download = imageFileName;
  148. document.body.appendChild(anchor);
  149. anchor.click();
  150. document.body.removeChild(anchor);
  151. URL.revokeObjectURL(fileUrl);
  152. // Remove item from download list
  153. setTimeout(() => {
  154. const copy = $downloadAssets;
  155. delete copy[imageFileName];
  156. $downloadAssets = copy;
  157. }, 2000);
  158. }
  159. } catch (e) {
  160. $downloadAssets = {};
  161. console.error('Error downloading file ', e);
  162. notificationController.show({
  163. type: NotificationType.Error,
  164. message: 'Error downloading file, check console for more details.'
  165. });
  166. }
  167. };
  168. const deleteAsset = async () => {
  169. try {
  170. if (
  171. window.confirm(
  172. `Caution! Are you sure you want to delete this asset? This step also deletes this asset in the album(s) to which it belongs. You can not undo this action!`
  173. )
  174. ) {
  175. const { data: deletedAssets } = await api.assetApi.deleteAsset({
  176. ids: [asset.id]
  177. });
  178. navigateAssetForward();
  179. for (const asset of deletedAssets) {
  180. if (asset.status == 'SUCCESS') {
  181. assetStore.removeAsset(asset.id);
  182. }
  183. }
  184. }
  185. } catch (e) {
  186. notificationController.show({
  187. type: NotificationType.Error,
  188. message: 'Error deleting this asset, check console for more details'
  189. });
  190. console.error('Error deleteSelectedAssetHandler', e);
  191. }
  192. };
  193. const toggleFavorite = async () => {
  194. const { data } = await api.assetApi.updateAsset(asset.id, {
  195. isFavorite: !asset.isFavorite
  196. });
  197. asset.isFavorite = data.isFavorite;
  198. assetStore.updateAsset(asset.id, data.isFavorite);
  199. };
  200. const openAlbumPicker = (shared: boolean) => {
  201. isShowAlbumPicker = true;
  202. addToSharedAlbum = shared;
  203. };
  204. const handleAddToNewAlbum = (event: CustomEvent) => {
  205. isShowAlbumPicker = false;
  206. const { albumName }: { albumName: string } = event.detail;
  207. api.albumApi.createAlbum({ albumName, assetIds: [asset.id] }).then((response) => {
  208. const album = response.data;
  209. goto('/albums/' + album.id);
  210. });
  211. };
  212. const handleAddToAlbum = async (event: CustomEvent<{ album: AlbumResponseDto }>) => {
  213. isShowAlbumPicker = false;
  214. const album = event.detail.album;
  215. addAssetsToAlbum(album.id, [asset.id]).then((dto) => {
  216. if (dto.successfullyAdded === 1 && dto.album) {
  217. appearsInAlbums = [...appearsInAlbums, dto.album];
  218. }
  219. });
  220. };
  221. const disableKeyDownEvent = () => {
  222. if (browser) {
  223. document.removeEventListener('keydown', onKeyboardPress);
  224. }
  225. };
  226. const enableKeyDownEvent = () => {
  227. if (browser) {
  228. document.addEventListener('keydown', onKeyboardPress);
  229. }
  230. };
  231. const toggleArchive = async () => {
  232. try {
  233. const { data } = await api.assetApi.updateAsset(asset.id, {
  234. isArchived: !asset.isArchived
  235. });
  236. asset.isArchived = data.isArchived;
  237. if (data.isArchived) {
  238. dispatch('archived', data);
  239. } else {
  240. dispatch('unarchived', data);
  241. }
  242. notificationController.show({
  243. type: NotificationType.Info,
  244. message: asset.isArchived ? `Added to archive` : `Removed from archive`
  245. });
  246. } catch (error) {
  247. console.error(error);
  248. notificationController.show({
  249. type: NotificationType.Error,
  250. message: `Error ${
  251. asset.isArchived ? 'archiving' : 'unarchiving'
  252. } asset, check console for more details`
  253. });
  254. }
  255. };
  256. </script>
  257. <section
  258. id="immich-asset-viewer"
  259. class="fixed h-screen w-screen left-0 top-0 overflow-y-hidden bg-black z-[1001] grid grid-rows-[64px_1fr] grid-cols-4"
  260. >
  261. <div class="col-start-1 col-span-4 row-start-1 row-span-1 z-[1000] transition-transform">
  262. <AssetViewerNavBar
  263. {asset}
  264. isMotionPhotoPlaying={shouldPlayMotionPhoto}
  265. showCopyButton={canCopyImagesToClipboard && asset.type === AssetTypeEnum.Image}
  266. showMotionPlayButton={!!asset.livePhotoVideoId}
  267. showDownloadButton={shouldShowDownloadButton}
  268. on:goBack={closeViewer}
  269. on:showDetail={showDetailInfoHandler}
  270. on:download={handleDownload}
  271. on:delete={deleteAsset}
  272. on:favorite={toggleFavorite}
  273. on:addToAlbum={() => openAlbumPicker(false)}
  274. on:addToSharedAlbum={() => openAlbumPicker(true)}
  275. on:playMotionPhoto={() => (shouldPlayMotionPhoto = true)}
  276. on:stopMotionPhoto={() => (shouldPlayMotionPhoto = false)}
  277. on:toggleArchive={toggleArchive}
  278. />
  279. </div>
  280. {#if showNavigation}
  281. <div
  282. class={`row-start-2 row-span-end col-start-1 col-span-2 flex place-items-center hover:cursor-pointer w-3/4 mb-[60px] ${
  283. asset.type === AssetTypeEnum.Video ? '' : 'z-[999]'
  284. }`}
  285. on:mouseenter={() => {
  286. halfLeftHover = true;
  287. halfRightHover = false;
  288. }}
  289. on:mouseleave={() => {
  290. halfLeftHover = false;
  291. }}
  292. on:click={navigateAssetBackward}
  293. on:keydown={navigateAssetBackward}
  294. >
  295. <button
  296. class="rounded-full p-3 hover:bg-gray-500 hover:text-gray-700 z-[1000] text-gray-500 mx-4"
  297. class:navigation-button-hover={halfLeftHover}
  298. on:click={navigateAssetBackward}
  299. >
  300. <ChevronLeft size="36" />
  301. </button>
  302. </div>
  303. {/if}
  304. <div class="row-start-1 row-span-full col-start-1 col-span-4">
  305. {#key asset.id}
  306. {#if asset.type === AssetTypeEnum.Image}
  307. {#if shouldPlayMotionPhoto && asset.livePhotoVideoId}
  308. <VideoViewer
  309. {publicSharedKey}
  310. assetId={asset.livePhotoVideoId}
  311. on:close={closeViewer}
  312. on:onVideoEnded={() => (shouldPlayMotionPhoto = false)}
  313. />
  314. {:else}
  315. <PhotoViewer {publicSharedKey} {asset} on:close={closeViewer} />
  316. {/if}
  317. {:else}
  318. <VideoViewer {publicSharedKey} assetId={asset.id} on:close={closeViewer} />
  319. {/if}
  320. {/key}
  321. </div>
  322. {#if showNavigation}
  323. <div
  324. class={`row-start-2 row-span-full col-start-3 col-span-2 flex justify-end place-items-center hover:cursor-pointer w-3/4 justify-self-end mb-[60px] ${
  325. asset.type === AssetTypeEnum.Video ? '' : 'z-[500]'
  326. }`}
  327. on:click={navigateAssetForward}
  328. on:keydown={navigateAssetForward}
  329. on:mouseenter={() => {
  330. halfLeftHover = false;
  331. halfRightHover = true;
  332. }}
  333. on:mouseleave={() => {
  334. halfRightHover = false;
  335. }}
  336. >
  337. <button
  338. class="rounded-full p-3 hover:bg-gray-500 hover:text-white text-gray-500 mx-4"
  339. class:navigation-button-hover={halfRightHover}
  340. on:click={navigateAssetForward}
  341. >
  342. <ChevronRight size="36" />
  343. </button>
  344. </div>
  345. {/if}
  346. {#if isShowDetail}
  347. <div
  348. transition:fly={{ duration: 150 }}
  349. id="detail-panel"
  350. class="bg-immich-bg w-[360px] z-[1002] row-span-full transition-all overflow-y-auto dark:bg-immich-dark-bg dark:border-l dark:border-l-immich-dark-gray"
  351. translate="yes"
  352. >
  353. <DetailPanel
  354. {asset}
  355. albums={appearsInAlbums}
  356. on:close={() => (isShowDetail = false)}
  357. on:close-viewer={handleCloseViewer}
  358. on:description-focus-in={disableKeyDownEvent}
  359. on:description-focus-out={enableKeyDownEvent}
  360. />
  361. </div>
  362. {/if}
  363. {#if isShowAlbumPicker}
  364. <AlbumSelectionModal
  365. shared={addToSharedAlbum}
  366. on:newAlbum={handleAddToNewAlbum}
  367. on:newSharedAlbum={handleAddToNewAlbum}
  368. on:album={handleAddToAlbum}
  369. on:close={() => (isShowAlbumPicker = false)}
  370. />
  371. {/if}
  372. </section>
  373. <style>
  374. #immich-asset-viewer {
  375. contain: layout;
  376. }
  377. .navigation-button-hover {
  378. background-color: rgb(107 114 128 / var(--tw-bg-opacity));
  379. color: rgb(255 255 255 / var(--tw-text-opacity));
  380. transition: all 150ms;
  381. }
  382. </style>