asset-viewer.svelte 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 closeViewer = () => {
  84. dispatch('close');
  85. };
  86. const navigateAssetForward = (e?: Event) => {
  87. e?.stopPropagation();
  88. dispatch('navigate-next');
  89. };
  90. const navigateAssetBackward = (e?: Event) => {
  91. e?.stopPropagation();
  92. dispatch('navigate-previous');
  93. };
  94. const showDetailInfoHandler = () => {
  95. isShowDetail = !isShowDetail;
  96. };
  97. const handleDownload = () => {
  98. if (asset.livePhotoVideoId) {
  99. downloadFile(asset.livePhotoVideoId, true, publicSharedKey);
  100. downloadFile(asset.id, false, publicSharedKey);
  101. return;
  102. }
  103. downloadFile(asset.id, false, publicSharedKey);
  104. };
  105. /**
  106. * Get the filename of the asset based on the user defined template
  107. */
  108. const getTemplateFilename = () => {
  109. const filenameWithExtension = asset.originalPath.split('/').pop() as string;
  110. const filenameWithoutExtension = filenameWithExtension.split('.')[0];
  111. return {
  112. filenameWithExtension,
  113. filenameWithoutExtension
  114. };
  115. };
  116. const downloadFile = async (assetId: string, isLivePhoto: boolean, key: string) => {
  117. try {
  118. const { filenameWithoutExtension } = getTemplateFilename();
  119. const imageExtension = isLivePhoto ? 'mov' : asset.originalPath.split('.')[1];
  120. const imageFileName = filenameWithoutExtension + '.' + imageExtension;
  121. // If assets is already download -> return;
  122. if ($downloadAssets[imageFileName]) {
  123. return;
  124. }
  125. $downloadAssets[imageFileName] = 0;
  126. const { data, status } = await api.assetApi.downloadFile(assetId, key, {
  127. responseType: 'blob',
  128. onDownloadProgress: (progressEvent) => {
  129. if (progressEvent.lengthComputable) {
  130. const total = progressEvent.total;
  131. const current = progressEvent.loaded;
  132. $downloadAssets[imageFileName] = Math.floor((current / total) * 100);
  133. }
  134. }
  135. });
  136. if (!(data instanceof Blob)) {
  137. return;
  138. }
  139. if (status === 200) {
  140. const fileUrl = URL.createObjectURL(data);
  141. const anchor = document.createElement('a');
  142. anchor.href = fileUrl;
  143. anchor.download = imageFileName;
  144. document.body.appendChild(anchor);
  145. anchor.click();
  146. document.body.removeChild(anchor);
  147. URL.revokeObjectURL(fileUrl);
  148. // Remove item from download list
  149. setTimeout(() => {
  150. const copy = $downloadAssets;
  151. delete copy[imageFileName];
  152. $downloadAssets = copy;
  153. }, 2000);
  154. }
  155. } catch (e) {
  156. $downloadAssets = {};
  157. console.error('Error downloading file ', e);
  158. notificationController.show({
  159. type: NotificationType.Error,
  160. message: 'Error downloading file, check console for more details.'
  161. });
  162. }
  163. };
  164. const deleteAsset = async () => {
  165. try {
  166. if (
  167. window.confirm(
  168. `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!`
  169. )
  170. ) {
  171. const { data: deletedAssets } = await api.assetApi.deleteAsset({
  172. ids: [asset.id]
  173. });
  174. navigateAssetForward();
  175. for (const asset of deletedAssets) {
  176. if (asset.status == 'SUCCESS') {
  177. assetStore.removeAsset(asset.id);
  178. }
  179. }
  180. }
  181. } catch (e) {
  182. notificationController.show({
  183. type: NotificationType.Error,
  184. message: 'Error deleting this asset, check console for more details'
  185. });
  186. console.error('Error deleteSelectedAssetHandler', e);
  187. }
  188. };
  189. const toggleFavorite = async () => {
  190. const { data } = await api.assetApi.updateAsset(asset.id, {
  191. isFavorite: !asset.isFavorite
  192. });
  193. asset.isFavorite = data.isFavorite;
  194. assetStore.updateAsset(asset.id, data.isFavorite);
  195. };
  196. const openAlbumPicker = (shared: boolean) => {
  197. isShowAlbumPicker = true;
  198. addToSharedAlbum = shared;
  199. };
  200. const handleAddToNewAlbum = (event: CustomEvent) => {
  201. isShowAlbumPicker = false;
  202. const { albumName }: { albumName: string } = event.detail;
  203. api.albumApi.createAlbum({ albumName, assetIds: [asset.id] }).then((response) => {
  204. const album = response.data;
  205. goto('/albums/' + album.id);
  206. });
  207. };
  208. const handleAddToAlbum = async (event: CustomEvent<{ album: AlbumResponseDto }>) => {
  209. isShowAlbumPicker = false;
  210. const album = event.detail.album;
  211. addAssetsToAlbum(album.id, [asset.id]).then((dto) => {
  212. if (dto.successfullyAdded === 1 && dto.album) {
  213. appearsInAlbums = [...appearsInAlbums, dto.album];
  214. }
  215. });
  216. };
  217. const disableKeyDownEvent = () => {
  218. if (browser) {
  219. document.removeEventListener('keydown', onKeyboardPress);
  220. }
  221. };
  222. const enableKeyDownEvent = () => {
  223. if (browser) {
  224. document.addEventListener('keydown', onKeyboardPress);
  225. }
  226. };
  227. const toggleArchive = async () => {
  228. try {
  229. const { data } = await api.assetApi.updateAsset(asset.id, {
  230. isArchived: !asset.isArchived
  231. });
  232. asset.isArchived = data.isArchived;
  233. if (data.isArchived) {
  234. dispatch('archived', data);
  235. } else {
  236. dispatch('unarchived', data);
  237. }
  238. notificationController.show({
  239. type: NotificationType.Info,
  240. message: asset.isArchived ? `Added to archive` : `Removed from archive`
  241. });
  242. } catch (error) {
  243. console.error(error);
  244. notificationController.show({
  245. type: NotificationType.Error,
  246. message: `Error ${
  247. asset.isArchived ? 'archiving' : 'unarchiving'
  248. } asset, check console for more details`
  249. });
  250. }
  251. };
  252. </script>
  253. <section
  254. id="immich-asset-viewer"
  255. 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"
  256. >
  257. <div class="col-start-1 col-span-4 row-start-1 row-span-1 z-[1000] transition-transform">
  258. <AssetViewerNavBar
  259. {asset}
  260. isMotionPhotoPlaying={shouldPlayMotionPhoto}
  261. showCopyButton={canCopyImagesToClipboard && asset.type === AssetTypeEnum.Image}
  262. showMotionPlayButton={!!asset.livePhotoVideoId}
  263. showDownloadButton={shouldShowDownloadButton}
  264. on:goBack={closeViewer}
  265. on:showDetail={showDetailInfoHandler}
  266. on:download={handleDownload}
  267. on:delete={deleteAsset}
  268. on:favorite={toggleFavorite}
  269. on:addToAlbum={() => openAlbumPicker(false)}
  270. on:addToSharedAlbum={() => openAlbumPicker(true)}
  271. on:playMotionPhoto={() => (shouldPlayMotionPhoto = true)}
  272. on:stopMotionPhoto={() => (shouldPlayMotionPhoto = false)}
  273. on:toggleArchive={toggleArchive}
  274. />
  275. </div>
  276. {#if showNavigation}
  277. <div
  278. 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] ${
  279. asset.type === AssetTypeEnum.Video ? '' : 'z-[999]'
  280. }`}
  281. on:mouseenter={() => {
  282. halfLeftHover = true;
  283. halfRightHover = false;
  284. }}
  285. on:mouseleave={() => {
  286. halfLeftHover = false;
  287. }}
  288. on:click={navigateAssetBackward}
  289. on:keydown={navigateAssetBackward}
  290. >
  291. <button
  292. class="rounded-full p-3 hover:bg-gray-500 hover:text-gray-700 z-[1000] text-gray-500 mx-4"
  293. class:navigation-button-hover={halfLeftHover}
  294. on:click={navigateAssetBackward}
  295. >
  296. <ChevronLeft size="36" />
  297. </button>
  298. </div>
  299. {/if}
  300. <div class="row-start-1 row-span-full col-start-1 col-span-4">
  301. {#key asset.id}
  302. {#if asset.type === AssetTypeEnum.Image}
  303. {#if shouldPlayMotionPhoto && asset.livePhotoVideoId}
  304. <VideoViewer
  305. {publicSharedKey}
  306. assetId={asset.livePhotoVideoId}
  307. on:close={closeViewer}
  308. on:onVideoEnded={() => (shouldPlayMotionPhoto = false)}
  309. />
  310. {:else}
  311. <PhotoViewer {publicSharedKey} {asset} on:close={closeViewer} />
  312. {/if}
  313. {:else}
  314. <VideoViewer {publicSharedKey} assetId={asset.id} on:close={closeViewer} />
  315. {/if}
  316. {/key}
  317. </div>
  318. {#if showNavigation}
  319. <div
  320. 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] ${
  321. asset.type === AssetTypeEnum.Video ? '' : 'z-[500]'
  322. }`}
  323. on:click={navigateAssetForward}
  324. on:keydown={navigateAssetForward}
  325. on:mouseenter={() => {
  326. halfLeftHover = false;
  327. halfRightHover = true;
  328. }}
  329. on:mouseleave={() => {
  330. halfRightHover = false;
  331. }}
  332. >
  333. <button
  334. class="rounded-full p-3 hover:bg-gray-500 hover:text-gray-700 text-gray-500 mx-4"
  335. class:navigation-button-hover={halfRightHover}
  336. on:click={navigateAssetForward}
  337. >
  338. <ChevronRight size="36" />
  339. </button>
  340. </div>
  341. {/if}
  342. {#if isShowDetail}
  343. <div
  344. transition:fly={{ duration: 150 }}
  345. id="detail-panel"
  346. 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"
  347. translate="yes"
  348. >
  349. <DetailPanel
  350. {asset}
  351. albums={appearsInAlbums}
  352. on:close={() => (isShowDetail = false)}
  353. on:description-focus-in={disableKeyDownEvent}
  354. on:description-focus-out={enableKeyDownEvent}
  355. />
  356. </div>
  357. {/if}
  358. {#if isShowAlbumPicker}
  359. <AlbumSelectionModal
  360. shared={addToSharedAlbum}
  361. on:newAlbum={handleAddToNewAlbum}
  362. on:newSharedAlbum={handleAddToNewAlbum}
  363. on:album={handleAddToAlbum}
  364. on:close={() => (isShowAlbumPicker = false)}
  365. />
  366. {/if}
  367. </section>
  368. <style>
  369. #immich-asset-viewer {
  370. contain: layout;
  371. }
  372. .navigation-button-hover {
  373. background-color: rgb(107 114 128 / var(--tw-bg-opacity));
  374. color: rgb(55 65 81 / var(--tw-text-opacity));
  375. transition: all 150ms;
  376. }
  377. </style>