Skip to content

High performance self-hosted photo and video management solution.

13.0 KB
Raw Blame
<script lang="ts">
  import { shortcut } from '#lib/actions/shortcut.ts';
  import OnEvents from '#lib/components/OnEvents.svelte';
  import { timeBeforeShowLoadingSpinner } from '#lib/constants.ts';
  import { assetViewerManager } from '#lib/managers/asset-viewer-manager.svelte.ts';
  import { eventManager } from '#lib/managers/event-manager.svelte.ts';
  import { languageManager } from '#lib/managers/language-manager.svelte.ts';
  import { executeMutation } from '#lib/queries/client.ts';
  import { deleteFaceMutation, getFacesQuery, reassignFacesByIdMutation } from '#lib/queries/face.query.ts';
  import { getPeopleThumbnailUrl } from '#lib/utils.ts';
  import { handleError } from '#lib/utils/handle-error.ts';
  import { zoomImageToBase64 } from '#lib/utils/people-utils.ts';
  import { getPersonNameWithHiddenValue } from '#lib/utils/person.ts';
  import { AssetTypeEnum, createPerson, type AssetFaceResponseDto, type PersonResponseDto } from '@immich/sdk';
  import { Icon, IconButton, LoadingSpinner, modalManager, toastManager } from '@immich/ui';
  import { mdiAccountOff, mdiArrowLeftThin, mdiArrowRightThin, mdiPencil, mdiRestart, mdiTrashCan } from '@mdi/js';
  import { createQuery } from '@tanstack/svelte-query';
  import { t } from 'svelte-i18n';
  import { linear } from 'svelte/easing';
  import { fly } from 'svelte/transition';
  import ImageThumbnail from '../assets/thumbnail/ImageThumbnail.svelte';
  import AssignFaceSidePanel from './AssignFaceSidePanel.svelte';

  interface Props {
    assetId: string;
    assetType: AssetTypeEnum;
    onClose: () => void;
    onRefresh: () => void;
  }

  let { assetId, assetType, onClose, onRefresh }: Props = $props();

  // keep track of the changes
  let peopleToCreate: string[] = [];
  let assetFaceGenerated: string[] = [];

  const query = createQuery(() => getFacesQuery(assetId));
  const peopleWithFaces = $derived(query.data ?? []);
  let selectedPersonToReassign: Record<string, PersonResponseDto> = $state({});
  let selectedPersonToCreate: Record<string, string> = $state({});
  let editedFace: AssetFaceResponseDto | undefined = $state();

  // loading spinners
  let isShowLoadingDone = $state(false);

  // search people
  let showSelectedFaces = $state(false);

  // timers
  let loaderLoadingDoneTimeout: ReturnType<typeof setTimeout>;
  let automaticRefreshTimeout: ReturnType<typeof setTimeout>;

  const thumbnailWidth = '90px';

  const onPersonThumbnailReady = ({ id }: { id: string }) => {
    assetFaceGenerated.push(id);
    if (
      isEqual(assetFaceGenerated, peopleToCreate) &&
      loaderLoadingDoneTimeout &&
      automaticRefreshTimeout &&
      Object.keys(selectedPersonToCreate).length === peopleToCreate.length
    ) {
      clearTimeout(loaderLoadingDoneTimeout);
      clearTimeout(automaticRefreshTimeout);
      onRefresh();
    }
  };

  const isEqual = (a: string[], b: string[]): boolean => {
    return b.every((valueB) => a.includes(valueB));
  };

  const handleReset = (id: string) => {
    if (Object.hasOwn(selectedPersonToReassign, id)) {
      delete selectedPersonToReassign[id];
    }
    if (Object.hasOwn(selectedPersonToCreate, id)) {
      delete selectedPersonToCreate[id];
    }
  };

  const handleEditFaces = async () => {
    loaderLoadingDoneTimeout = setTimeout(() => (isShowLoadingDone = true), timeBeforeShowLoadingSpinner);
    const numberOfChanges = Object.keys(selectedPersonToCreate).length + Object.keys(selectedPersonToReassign).length;

    if (numberOfChanges > 0) {
      let failed = false;
      try {
        for (const personWithFace of peopleWithFaces) {
          let personId = selectedPersonToReassign[personWithFace.id]?.id;

          if (!personId && Object.hasOwn(selectedPersonToCreate, personWithFace.id)) {
            const data = await createPerson({ personCreateDto: {} });
            peopleToCreate.push(data.id);
            personId = data.id;
          }

          if (!personId) {
            continue;
          }

          await executeMutation(reassignFacesByIdMutation, [{ id: personId, faceDto: { id: personWithFace.id } }], {
            onError: () => (failed = true),
          });

          if (failed) {
            break;
          }
        }
      } catch (error) {
        handleError(error, $t('errors.cant_apply_changes'));
        failed = true;
      }

      if (!failed) {
        toastManager.primary($t('people_edits_count', { values: { count: numberOfChanges } }));
      }
    }

    isShowLoadingDone = false;
    if (peopleToCreate.length === 0) {
      clearTimeout(loaderLoadingDoneTimeout);
      onRefresh();
    } else {
      automaticRefreshTimeout = setTimeout(onRefresh, 15_000);
    }
  };

  const handleCreatePerson = (newFeaturePhoto: string | null) => {
    if (newFeaturePhoto && editedFace) {
      selectedPersonToCreate[editedFace.id] = newFeaturePhoto;
    }
    showSelectedFaces = false;
  };

  const handleReassignFace = (person: PersonResponseDto | null) => {
    if (person && editedFace) {
      selectedPersonToReassign[editedFace.id] = person;
    }
    showSelectedFaces = false;
  };

  const handleFacePicker = (face: AssetFaceResponseDto) => {
    editedFace = face;
    showSelectedFaces = true;
  };

  const deleteAssetFace = async (face: AssetFaceResponseDto) => {
    const person = face.person;
    if (!person) {
      return;
    }

    const isConfirmed = await modalManager.showDialog({
      prompt: $t('confirm_delete_face', { values: { name: person.name } }),
    });
    if (!isConfirmed) {
      return;
    }

    await executeMutation(deleteFaceMutation, [{ id: face.id, assetFaceDeleteDto: { force: false } }], {
      onSuccess: () => {
        eventManager.emit('PersonAssetDelete', { id: person.id, assetId });
        void assetViewerManager.setAssetId(assetId);
      },
    });
  };
</script>

<OnEvents {onPersonThumbnailReady} />

<svelte:document
  use:shortcut={{
    shortcut: { key: 'Escape' },
    onShortcut: () => {
      if (showSelectedFaces) {
        showSelectedFaces = false;
      } else {
        onClose();
      }
    },
  }}
/>

<section
  transition:fly={{ x: 360, duration: 100, easing: linear }}
  class="absolute top-0 h-full w-90 overflow-x-hidden bg-light p-2 dark:text-immich-dark-fg"
>
  <div class="flex place-items-center justify-between gap-2">
    <div class="flex items-center gap-2">
      <IconButton
        shape="round"
        color="secondary"
        variant="ghost"
        icon={languageManager.rtl ? mdiArrowRightThin : mdiArrowLeftThin}
        aria-label={$t('back')}
        onclick={onClose}
      />
      <p class="flex text-lg text-immich-fg dark:text-immich-dark-fg">{$t('edit_faces')}</p>
    </div>
    {#if !isShowLoadingDone}
      <button
        type="button"
        class="justify-self-end rounded-lg p-2 hover:bg-immich-dark-primary hover:dark:bg-immich-dark-primary/50"
        onclick={() => handleEditFaces()}
      >
        {$t('done')}
      </button>
    {:else}
      <LoadingSpinner />
    {/if}
  </div>

  <div class="p-4 text-sm">
    <div class="mt-4 flex flex-wrap gap-2">
      {#if query.isPending}
        <div class="flex w-full justify-center">
          <LoadingSpinner />
        </div>
      {:else}
        {#each peopleWithFaces as face, index (face.id)}
          {const personName = face.person ? face.person.name : $t('face_unassigned')}
          {const isHighlighted = $derived(assetViewerManager.highlightedFaces.some((b) => b.id === face.id))}
          <div class="relative h-29 w-24">
            <div
              role="button"
              tabindex={index}
              class="absolute inset-s-0 top-0 size-22.5 cursor-default"
              onfocus={() => assetViewerManager.setHighlightedFaces([peopleWithFaces[index]])}
              onpointerenter={() => assetViewerManager.setHighlightedFaces([peopleWithFaces[index]])}
              onpointerleave={() => assetViewerManager.clearHighlightedFaces()}
            >
              <div class="relative">
                {#if selectedPersonToCreate[face.id]}
                  <ImageThumbnail
                    curve
                    shadow
                    highlighted={isHighlighted}
                    url={selectedPersonToCreate[face.id]}
                    altText={$t('new_person')}
                    title={$t('new_person')}
                    widthStyle={thumbnailWidth}
                    heightStyle={thumbnailWidth}
                  />
                {:else if selectedPersonToReassign[face.id]}
                  <ImageThumbnail
                    curve
                    shadow
                    highlighted={isHighlighted}
                    url={getPeopleThumbnailUrl(selectedPersonToReassign[face.id])}
                    altText={selectedPersonToReassign[face.id].name}
                    title={$getPersonNameWithHiddenValue(
                      selectedPersonToReassign[face.id].name,
                      selectedPersonToReassign[face.id]?.isHidden,
                    )}
                    widthStyle={thumbnailWidth}
                    heightStyle={thumbnailWidth}
                    hidden={selectedPersonToReassign[face.id].isHidden}
                  />
                {:else if face.person}
                  <ImageThumbnail
                    curve
                    shadow
                    highlighted={isHighlighted}
                    url={getPeopleThumbnailUrl(face.person)}
                    altText={face.person.name}
                    title={$getPersonNameWithHiddenValue(face.person.name, face.person.isHidden)}
                    widthStyle={thumbnailWidth}
                    heightStyle={thumbnailWidth}
                    hidden={face.person.isHidden}
                  />
                {:else}
                  {#await zoomImageToBase64(face, assetId, assetType, assetViewerManager.imgRef)}
                    <ImageThumbnail
                      curve
                      shadow
                      highlighted={isHighlighted}
                      url="/src/lib/assets/no-thumbnail.png"
                      altText={$t('face_unassigned')}
                      title={$t('face_unassigned')}
                      widthStyle="90px"
                      heightStyle="90px"
                    />
                  {:then data}
                    <ImageThumbnail
                      curve
                      shadow
                      highlighted={isHighlighted}
                      url={data === null ? '/src/lib/assets/no-thumbnail.png' : data}
                      altText={$t('face_unassigned')}
                      title={$t('face_unassigned')}
                      widthStyle="90px"
                      heightStyle="90px"
                    />
                  {/await}
                {/if}
              </div>

              {#if !Object.hasOwn(selectedPersonToCreate, face.id)}
                <p class="relative mt-1 truncate font-medium" title={personName}>
                  {#if selectedPersonToReassign[face.id]?.id}
                    {selectedPersonToReassign[face.id]?.name}
                  {:else}
                    <span class={personName === $t('face_unassigned') ? 'dark:text-gray-500' : ''}>{personName}</span>
                  {/if}
                </p>
              {/if}

              <div class="absolute -inset-e-2.25 -top-2.25 flex flex-col gap-1 rounded-full">
                {#if selectedPersonToCreate[face.id] || selectedPersonToReassign[face.id]}
                  <IconButton
                    shape="round"
                    variant="ghost"
                    color="primary"
                    icon={mdiRestart}
                    aria-label={$t('reset')}
                    size="small"
                    onclick={() => handleReset(face.id)}
                  />
                {:else}
                  <IconButton
                    shape="round"
                    color="primary"
                    icon={mdiPencil}
                    aria-label={$t('select_new_face')}
                    size="small"
                    onclick={() => handleFacePicker(face)}
                  />
                {/if}
                {#if face.person !== null}
                  <IconButton
                    shape="round"
                    color="danger"
                    icon={mdiTrashCan}
                    aria-label={$t('delete_face')}
                    size="small"
                    onclick={() => deleteAssetFace(face)}
                  />
                {/if}
              </div>
              {#if !Object.hasOwn(selectedPersonToCreate, face.id) && !Object.hasOwn(selectedPersonToReassign, face.id) && !face.person}
                <div class="absolute inset-e-7 -top-2.25 rounded-full bg-muted p-1">
                  <Icon color="primary" icon={mdiAccountOff} aria-hidden size="24" />
                </div>
              {/if}
            </div>
          </div>
        {/each}
      {/if}
    </div>
  </div>
</section>

{#if showSelectedFaces && editedFace}
  <AssignFaceSidePanel
    {editedFace}
    {assetId}
    {assetType}
    onClose={() => (showSelectedFaces = false)}
    onCreatePerson={handleCreatePerson}
    onReassign={handleReassignFace}
  />
{/if}