refactor(web): tree data structure for folder and tag views (#18980)

* refactor folder view

inline link

* improved tree collapsing

* handle tags

* linting

* formatting

* simplify

* .from is faster

* simplify

* add key
This commit is contained in:
Mert 2025-06-09 11:02:16 -04:00 committed by GitHub
parent ac0e94c003
commit 74f79cae69
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 249 additions and 191 deletions

View File

@ -19,6 +19,7 @@
import { handleError } from '$lib/utils/handle-error'; import { handleError } from '$lib/utils/handle-error';
import { getMetadataSearchQuery } from '$lib/utils/metadata-search'; import { getMetadataSearchQuery } from '$lib/utils/metadata-search';
import { fromISODateTime, fromISODateTimeUTC } from '$lib/utils/timeline-util'; import { fromISODateTime, fromISODateTimeUTC } from '$lib/utils/timeline-util';
import { getParentPath } from '$lib/utils/tree-utils';
import { import {
AssetMediaSize, AssetMediaSize,
getAssetInfo, getAssetInfo,
@ -137,7 +138,7 @@
const getAssetFolderHref = (asset: AssetResponseDto) => { const getAssetFolderHref = (asset: AssetResponseDto) => {
const folderUrl = new URL(AppRoute.FOLDERS, globalThis.location.href); const folderUrl = new URL(AppRoute.FOLDERS, globalThis.location.href);
// Remove the last part of the path to get the parent path // Remove the last part of the path to get the parent path
const assetParentPath = asset.originalPath.split('/').slice(0, -1).join('/'); const assetParentPath = getParentPath(asset.originalPath);
folderUrl.searchParams.set(QueryParameter.PATH, assetParentPath); folderUrl.searchParams.set(QueryParameter.PATH, assetParentPath);
return folderUrl.href; return folderUrl.href;
}; };

View File

@ -1,23 +1,27 @@
<script lang="ts"> <script lang="ts">
import Icon from '$lib/components/elements/icon.svelte'; import Icon from '$lib/components/elements/icon.svelte';
import { TreeNode } from '$lib/utils/tree-utils';
import { IconButton } from '@immich/ui'; import { IconButton } from '@immich/ui';
import { mdiArrowUpLeft, mdiChevronRight } from '@mdi/js'; import { mdiArrowUpLeft, mdiChevronRight } from '@mdi/js';
import { t } from 'svelte-i18n'; import { t } from 'svelte-i18n';
interface Props { interface Props {
pathSegments?: string[]; node: TreeNode;
getLink: (path: string) => string; getLink: (path: string) => string;
title: string; title: string;
icon: string; icon: string;
} }
let { pathSegments = [], getLink, title, icon }: Props = $props(); const { node, getLink, title, icon }: Props = $props();
let isRoot = $derived(pathSegments.length === 0); const rootLink = getLink('');
const isRoot = $derived(node.parent === null);
const parentLink = $derived(getLink(node.parent ? node.parent.path : ''));
const parents = $derived(node.parents);
</script> </script>
<nav class="flex items-center py-2"> <nav class="flex items-center py-2">
{#if !isRoot} {#if parentLink}
<div> <div>
<IconButton <IconButton
shape="round" shape="round"
@ -25,9 +29,8 @@
variant="ghost" variant="ghost"
icon={mdiArrowUpLeft} icon={mdiArrowUpLeft}
aria-label={$t('to_parent')} aria-label={$t('to_parent')}
href={getLink(pathSegments.slice(0, -1).join('/'))} href={parentLink}
class="me-2" class="me-2"
onclick={() => {}}
/> />
</div> </div>
{/if} {/if}
@ -42,31 +45,29 @@
color="secondary" color="secondary"
variant="ghost" variant="ghost"
{icon} {icon}
href={getLink('')} href={rootLink}
aria-label={title} aria-label={title}
size="medium" size="medium"
aria-current={isRoot ? 'page' : undefined} aria-current={isRoot ? 'page' : undefined}
onclick={() => {}}
/> />
</li> </li>
{#each pathSegments as segment, index (index)} {#each parents as parent (parent)}
{@const isLastSegment = index === pathSegments.length - 1}
<li <li
class="flex gap-2 items-center font-mono text-sm text-nowrap text-immich-primary dark:text-immich-dark-primary" class="flex gap-2 items-center font-mono text-sm text-nowrap text-immich-primary dark:text-immich-dark-primary"
> >
<Icon path={mdiChevronRight} class="text-gray-500 dark:text-gray-300" size={16} ariaHidden /> <Icon path={mdiChevronRight} class="text-gray-500 dark:text-gray-300" size={16} ariaHidden />
{#if isLastSegment} <a class="underline hover:font-semibold whitespace-pre-wrap" href={getLink(parent.path)}>
<p class="cursor-default whitespace-pre-wrap">{segment}</p> {parent.value}
{:else}
<a
class="underline hover:font-semibold whitespace-pre-wrap"
href={getLink(pathSegments.slice(0, index + 1).join('/'))}
>
{segment}
</a> </a>
{/if}
</li> </li>
{/each} {/each}
<li
class="flex gap-2 items-center font-mono text-sm text-nowrap text-immich-primary dark:text-immich-dark-primary"
>
<Icon path={mdiChevronRight} class="text-gray-500 dark:text-gray-300" size={16} ariaHidden />
<p class="cursor-default whitespace-pre-wrap">{node.value}</p>
</li>
</ol> </ol>
</div> </div>
</nav> </nav>

View File

@ -1,29 +1,31 @@
<script lang="ts"> <script lang="ts">
import Icon from '$lib/components/elements/icon.svelte'; import Icon from '$lib/components/elements/icon.svelte';
import type { TreeNode } from '$lib/utils/tree-utils';
interface Props { interface Props {
items?: string[]; items: TreeNode[];
icon: string; icon: string;
onClick: (path: string) => void; onClick: (path: string) => void;
} }
let { items = [], icon, onClick }: Props = $props(); let { items, icon, onClick }: Props = $props();
</script> </script>
{#if items.length > 0} {#if items.length > 0}
<div <div
class="w-full grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 2xl:grid-cols-8 gap-2 bg-gray-50 dark:bg-immich-dark-gray/50 rounded-2xl border border-gray-100 dark:border-gray-900" class="w-full grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 2xl:grid-cols-8 gap-2 bg-gray-50 dark:bg-immich-dark-gray/50 rounded-2xl border border-gray-100 dark:border-gray-900"
> >
{#each items as item (item)} <!-- eslint-disable-next-line svelte/require-each-key -->
{#each items as item}
<button <button
class="flex flex-col place-items-center gap-2 py-2 px-4 hover:bg-immich-primary/10 dark:hover:bg-immich-primary/40 rounded-xl" class="flex flex-col place-items-center gap-2 py-2 px-4 hover:bg-immich-primary/10 dark:hover:bg-immich-primary/40 rounded-xl"
onclick={() => onClick(item)} onclick={() => onClick(item.value)}
title={item} title={item.value}
type="button" type="button"
> >
<Icon path={icon} class="text-immich-primary dark:text-immich-dark-primary" size={64} /> <Icon path={icon} class="text-immich-primary dark:text-immich-dark-primary" size={64} />
<p class="text-sm dark:text-gray-200 text-nowrap text-ellipsis overflow-clip w-full whitespace-pre-wrap"> <p class="text-sm dark:text-gray-200 text-nowrap text-ellipsis overflow-clip w-full whitespace-pre-wrap">
{item} {item.value}
</p> </p>
</button> </button>
{/each} {/each}

View File

@ -1,28 +1,21 @@
<script lang="ts"> <script lang="ts">
import Tree from '$lib/components/shared-components/tree/tree.svelte'; import Tree from '$lib/components/shared-components/tree/tree.svelte';
import { normalizeTreePath, type RecursiveObject } from '$lib/utils/tree-utils'; import { type TreeNode } from '$lib/utils/tree-utils';
interface Props { interface Props {
items: RecursiveObject; tree: TreeNode;
parent?: string; active: string;
active?: string;
icons: { default: string; active: string }; icons: { default: string; active: string };
getLink: (path: string) => string; getLink: (path: string) => string;
getColor?: (path: string) => string | undefined;
} }
let { items, parent = '', active = '', icons, getLink, getColor = () => undefined }: Props = $props(); let { tree, active, icons, getLink }: Props = $props();
</script> </script>
<ul class="list-none ms-2"> <ul class="list-none ms-2">
<!-- eslint-disable-next-line svelte/require-each-key --> {#each tree.children as node (node.color ? node.path + node.color : node.path)}
{#each Object.entries(items).sort() as [path, tree]}
{@const value = normalizeTreePath(`${parent}/${path}`)}
{@const key = value + getColor(value)}
{#key key}
<li> <li>
<Tree {parent} value={path} {tree} {icons} {active} {getLink} {getColor} /> <Tree {node} {icons} {active} {getLink} />
</li> </li>
{/key}
{/each} {/each}
</ul> </ul>

View File

@ -1,25 +1,20 @@
<script lang="ts"> <script lang="ts">
import Icon from '$lib/components/elements/icon.svelte'; import Icon from '$lib/components/elements/icon.svelte';
import TreeItems from '$lib/components/shared-components/tree/tree-items.svelte'; import TreeItems from '$lib/components/shared-components/tree/tree-items.svelte';
import { normalizeTreePath, type RecursiveObject } from '$lib/utils/tree-utils'; import { TreeNode } from '$lib/utils/tree-utils';
import { mdiChevronDown, mdiChevronRight } from '@mdi/js'; import { mdiChevronDown, mdiChevronRight } from '@mdi/js';
interface Props { interface Props {
tree: RecursiveObject; node: TreeNode;
parent: string; active: string;
value: string;
active?: string;
icons: { default: string; active: string }; icons: { default: string; active: string };
getLink: (path: string) => string; getLink: (path: string) => string;
getColor: (path: string) => string | undefined;
} }
let { tree, parent, value, active = '', icons, getLink, getColor }: Props = $props(); let { node, active, icons, getLink }: Props = $props();
const path = $derived(normalizeTreePath(`${parent}/${value}`)); const isTarget = $derived(active === node.path);
const isActive = $derived(active === path || active.startsWith(`${path}/`)); const isActive = $derived(active === node.path || active.startsWith(node.value === '/' ? '/' : `${node.path}/`));
const isTarget = $derived(active === path);
const color = $derived(getColor(path));
let isOpen = $derived(isActive); let isOpen = $derived(isActive);
const onclick = (event: MouseEvent) => { const onclick = (event: MouseEvent) => {
@ -29,25 +24,27 @@
</script> </script>
<a <a
href={getLink(path)} href={getLink(node.path)}
title={value} title={node.value}
class={`flex grow place-items-center ps-2 py-1 text-sm rounded-lg hover:bg-slate-200 dark:hover:bg-slate-800 hover:font-semibold ${isTarget ? 'bg-slate-100 dark:bg-slate-700 font-semibold text-immich-primary dark:text-immich-dark-primary' : 'dark:text-gray-200'}`} class={`flex grow place-items-center ps-2 py-1 text-sm rounded-lg hover:bg-slate-200 dark:hover:bg-slate-800 hover:font-semibold ${isTarget ? 'bg-slate-100 dark:bg-slate-700 font-semibold text-immich-primary dark:text-immich-dark-primary' : 'dark:text-gray-200'}`}
data-sveltekit-keepfocus data-sveltekit-keepfocus
> >
<button type="button" {onclick} class={Object.values(tree).length === 0 ? 'invisible' : ''}> {#if node.size > 0}
<button type="button" {onclick}>
<Icon path={isOpen ? mdiChevronDown : mdiChevronRight} class="text-gray-400" size={20} /> <Icon path={isOpen ? mdiChevronDown : mdiChevronRight} class="text-gray-400" size={20} />
</button> </button>
<div> {/if}
<div class={node.size === 0 ? 'ml-[1.5em] ' : ''}>
<Icon <Icon
path={isActive ? icons.active : icons.default} path={isActive ? icons.active : icons.default}
class={isActive ? 'text-immich-primary dark:text-immich-dark-primary' : 'text-gray-400'} class={isActive ? 'text-immich-primary dark:text-immich-dark-primary' : 'text-gray-400'}
{color} color={node.color}
size={20} size={20}
/> />
</div> </div>
<span class="text-nowrap overflow-hidden text-ellipsis font-mono ps-1 pt-1 whitespace-pre-wrap">{value}</span> <span class="text-nowrap overflow-hidden text-ellipsis font-mono ps-1 pt-1 whitespace-pre-wrap">{node.value}</span>
</a> </a>
{#if isOpen} {#if isOpen}
<TreeItems parent={path} items={tree} {icons} {active} {getLink} {getColor} /> <TreeItems tree={node} {icons} {active} {getLink} />
{/if} {/if}

View File

@ -1,4 +1,5 @@
import { eventManager } from '$lib/managers/event-manager.svelte'; import { eventManager } from '$lib/managers/event-manager.svelte';
import { TreeNode } from '$lib/utils/tree-utils';
import { import {
getAssetsByOriginalPath, getAssetsByOriginalPath,
getUniqueOriginalPaths, getUniqueOriginalPaths,
@ -13,47 +14,41 @@ type AssetCache = {
}; };
class FoldersStore { class FoldersStore {
folders = $state.raw<TreeNode | null>(null);
private initialized = false; private initialized = false;
uniquePaths = $state<string[]>([]); private assets = $state<AssetCache>({});
assets = $state<AssetCache>({});
constructor() { constructor() {
eventManager.on('auth.logout', () => this.clearCache()); eventManager.on('auth.logout', () => this.clearCache());
} }
async fetchUniquePaths() { async fetchTree(): Promise<TreeNode> {
if (this.initialized) { if (this.initialized) {
return; return this.folders!;
} }
this.initialized = true; this.initialized = true;
const uniquePaths = await getUniqueOriginalPaths(); this.folders = TreeNode.fromPaths(await getUniqueOriginalPaths());
this.uniquePaths.push(...uniquePaths); this.folders.collapse();
return this.folders;
} }
bustAssetCache() { bustAssetCache() {
this.assets = {}; this.assets = {};
} }
async refreshAssetsByPath(path: string | null) { async refreshAssetsByPath(path: string) {
if (!path) { return (this.assets[path] = await getAssetsByOriginalPath({ path }));
return;
}
this.assets[path] = await getAssetsByOriginalPath({ path });
} }
async fetchAssetsByPath(path: string) { async fetchAssetsByPath(path: string) {
if (this.assets[path]) { return (this.assets[path] ??= await getAssetsByOriginalPath({ path }));
return;
}
this.assets[path] = await getAssetsByOriginalPath({ path });
} }
clearCache() { clearCache() {
this.initialized = false; this.initialized = false;
this.uniquePaths = [];
this.assets = {}; this.assets = {};
this.folders = null;
} }
} }

View File

@ -23,7 +23,7 @@ export const isAssetViewerRoute = (target?: NavigationTarget | null) =>
!!(target?.route.id?.endsWith('/[[assetId=id]]') && 'assetId' in (target?.params || {})); !!(target?.route.id?.endsWith('/[[assetId=id]]') && 'assetId' in (target?.params || {}));
export function getAssetInfoFromParam({ assetId, key }: { assetId?: string; key?: string }) { export function getAssetInfoFromParam({ assetId, key }: { assetId?: string; key?: string }) {
return assetId && getAssetInfo({ id: assetId, key }); return assetId ? getAssetInfo({ id: assetId, key }) : undefined;
} }
function currentUrlWithoutAsset() { function currentUrlWithoutAsset() {

View File

@ -1,21 +1,144 @@
export interface RecursiveObject { /* eslint-disable @typescript-eslint/no-this-alias */
[key: string]: RecursiveObject; /* eslint-disable unicorn/no-this-assignment */
/* eslint-disable unicorn/prefer-at */
import type { TagResponseDto } from '@immich/sdk';
export class TreeNode extends Map<string, TreeNode> {
value: string;
path: string;
parent: TreeNode | null;
hasAssets: boolean;
id: string | undefined;
color: string | undefined;
private _parents: TreeNode[] | undefined;
private _children: TreeNode[] | undefined;
private constructor(value: string, path: string, parent: TreeNode | null) {
super();
this.value = value;
this.parent = parent;
this.path = path;
this.hasAssets = false;
} }
export const normalizeTreePath = (path: string) => path.replace(/^\//, '').replace(/\/$/, ''); static fromPaths(paths: string[]) {
const root = new TreeNode('', '', null);
export function buildTree(paths: string[]) {
const root: RecursiveObject = {};
for (const path of paths) { for (const path of paths) {
const parts = path.split('/'); const current = root.add(path);
let current = root; current.hasAssets = true;
for (const part of parts) {
if (!current[part]) {
current[part] = {};
}
current = current[part];
}
} }
return root; return root;
} }
static fromTags(tags: TagResponseDto[]) {
const root = new TreeNode('', '', null);
for (const tag of tags) {
const current = root.add(tag.value);
current.hasAssets = true;
current.id = tag.id;
current.color = tag.color;
}
return root;
}
traverse(path: string) {
const parts = getPathParts(path);
let current: TreeNode = this;
let curPart = null;
for (const part of parts) {
// segments common to all subtrees can be collapsed together
curPart = curPart === null ? part : joinPaths(curPart, part);
const next = current.get(curPart);
if (next) {
current = next;
curPart = null;
}
}
return current;
}
collapse() {
if (this.size === 1 && !this.hasAssets && this.parent !== null) {
const child = this.values().next().value!;
child.value = joinPaths(this.value, child.value);
child.parent = this.parent;
this.parent.delete(this.value);
this.parent.set(child.value, child);
}
for (const child of this.values()) {
child.collapse();
}
}
private add(path: string) {
let current: TreeNode = this;
for (const part of getPathParts(path)) {
let next = current.get(part);
if (next === undefined) {
next = new TreeNode(part, joinPaths(current.path, part), current);
current.set(part, next);
}
current = next;
}
return current;
}
get parents(): TreeNode[] {
if (this._parents) {
return this._parents;
}
const parents: TreeNode[] = [];
let current: TreeNode | null = this.parent;
while (current !== null && current.parent !== null) {
parents.push(current);
current = current.parent;
}
return (this._parents = parents.reverse());
}
get children(): TreeNode[] {
return (this._children ??= Array.from(this.values()));
}
}
export const normalizeTreePath = (path: string) =>
path.length > 1 && path[path.length - 1] === '/' ? path.slice(0, -1) : path;
export function getPathParts(path: string) {
const parts = path.split('/');
if (path[0] === '/') {
parts[0] = '/';
}
if (path[path.length - 1] === '/') {
parts.pop();
}
return parts;
}
export function joinPaths(path1: string, path2: string) {
if (!path1) {
return path2;
}
if (!path2) {
return path1;
}
if (path1[path1.length - 1] === '/') {
return path1 + path2;
}
return path1 + '/' + path2;
}
export function getParentPath(path: string) {
const normalized = normalizeTreePath(path);
const last = normalized.lastIndexOf('/');
if (last > 0) {
return normalized.slice(0, last);
}
return last === 0 ? '/' : normalized;
}

View File

@ -1,6 +1,5 @@
<script lang="ts"> <script lang="ts">
import { afterNavigate, goto, invalidateAll } from '$app/navigation'; import { afterNavigate, goto, invalidateAll } from '$app/navigation';
import { page } from '$app/stores';
import SkipLink from '$lib/components/elements/buttons/skip-link.svelte'; import SkipLink from '$lib/components/elements/buttons/skip-link.svelte';
import UserPageLayout, { headerId } from '$lib/components/layouts/user-page-layout.svelte'; import UserPageLayout, { headerId } from '$lib/components/layouts/user-page-layout.svelte';
import AddToAlbum from '$lib/components/photos-page/actions/add-to-album.svelte'; import AddToAlbum from '$lib/components/photos-page/actions/add-to-album.svelte';
@ -28,10 +27,9 @@
import { preferences } from '$lib/stores/user.store'; import { preferences } from '$lib/stores/user.store';
import { cancelMultiselect } from '$lib/utils/asset-utils'; import { cancelMultiselect } from '$lib/utils/asset-utils';
import { toTimelineAsset } from '$lib/utils/timeline-util'; import { toTimelineAsset } from '$lib/utils/timeline-util';
import { buildTree, normalizeTreePath } from '$lib/utils/tree-utils'; import { joinPaths } from '$lib/utils/tree-utils';
import { IconButton } from '@immich/ui'; import { IconButton } from '@immich/ui';
import { mdiDotsVertical, mdiFolder, mdiFolderHome, mdiFolderOutline, mdiPlus, mdiSelectAll } from '@mdi/js'; import { mdiDotsVertical, mdiFolder, mdiFolderHome, mdiFolderOutline, mdiPlus, mdiSelectAll } from '@mdi/js';
import { onMount } from 'svelte';
import { t } from 'svelte-i18n'; import { t } from 'svelte-i18n';
import type { PageData } from './$types'; import type { PageData } from './$types';
@ -43,51 +41,40 @@
const viewport: Viewport = $state({ width: 0, height: 0 }); const viewport: Viewport = $state({ width: 0, height: 0 });
let pathSegments = $derived(data.path ? data.path.split('/') : []);
let tree = $derived(buildTree(foldersStore.uniquePaths));
let currentPath = $derived($page.url.searchParams.get(QueryParameter.PATH) || '');
let currentTreeItems = $derived(currentPath ? data.currentFolders : Object.keys(tree).sort());
const assetInteraction = new AssetInteraction(); const assetInteraction = new AssetInteraction();
onMount(async function initializeFolders() { const handleNavigateToFolder = (folderName: string) => navigateToView(joinPaths(data.tree.path, folderName));
await foldersStore.fetchUniquePaths();
});
const handleNavigateToFolder = async function handleNavigateToFolder(folderName: string) { function getLinkForPath(path: string) {
await navigateToView(normalizeTreePath(`${data.path || ''}/${folderName}`));
};
const getLinkForPath = function getLinkForPath(path: string) {
const url = new URL(AppRoute.FOLDERS, globalThis.location.href); const url = new URL(AppRoute.FOLDERS, globalThis.location.href);
if (path) {
url.searchParams.set(QueryParameter.PATH, path); url.searchParams.set(QueryParameter.PATH, path);
}
return url.href; return url.href;
}; }
afterNavigate(function clearAssetSelection() { afterNavigate(function clearAssetSelection() {
// Clear the asset selection when we navigate (like going to another folder) // Clear the asset selection when we navigate (like going to another folder)
cancelMultiselect(assetInteraction); cancelMultiselect(assetInteraction);
}); });
const navigateToView = function navigateToView(path: string) { function navigateToView(path: string) {
return goto(getLinkForPath(path)); return goto(getLinkForPath(path), { keepFocus: true, noScroll: true });
}; }
const triggerAssetUpdate = async function updateAssets() { async function triggerAssetUpdate() {
cancelMultiselect(assetInteraction); cancelMultiselect(assetInteraction);
await foldersStore.refreshAssetsByPath(data.path); if (data.tree.path) {
await foldersStore.refreshAssetsByPath(data.tree.path);
}
await invalidateAll(); await invalidateAll();
}; }
const handleSelectAllAssets = function handleSelectAllAssets() { function handleSelectAllAssets() {
if (!data.pathAssets) { if (!data.pathAssets) {
return; return;
} }
assetInteraction.selectAssets(data.pathAssets.map((asset) => toTimelineAsset(asset))); assetInteraction.selectAssets(data.pathAssets.map((asset) => toTimelineAsset(asset)));
}; }
</script> </script>
<UserPageLayout title={data.meta.title}> <UserPageLayout title={data.meta.title}>
@ -99,8 +86,8 @@
<div class="h-full"> <div class="h-full">
<TreeItems <TreeItems
icons={{ default: mdiFolderOutline, active: mdiFolder }} icons={{ default: mdiFolderOutline, active: mdiFolder }}
items={tree} tree={foldersStore.folders!}
active={currentPath} active={data.tree.path}
getLink={getLinkForPath} getLink={getLinkForPath}
/> />
</div> </div>
@ -108,10 +95,10 @@
</Sidebar> </Sidebar>
{/snippet} {/snippet}
<Breadcrumbs {pathSegments} icon={mdiFolderHome} title={$t('folders')} getLink={getLinkForPath} /> <Breadcrumbs node={data.tree} icon={mdiFolderHome} title={$t('folders')} getLink={getLinkForPath} />
<section class="mt-2 h-[calc(100%-(--spacing(20)))] overflow-auto immich-scrollbar"> <section class="mt-2 h-[calc(100%-(--spacing(20)))] overflow-auto immich-scrollbar">
<TreeItemThumbnails items={currentTreeItems} icon={mdiFolder} onClick={handleNavigateToFolder} /> <TreeItemThumbnails items={data.tree.children} icon={mdiFolder} onClick={handleNavigateToFolder} />
<!-- Assets --> <!-- Assets -->
{#if data.pathAssets && data.pathAssets.length > 0} {#if data.pathAssets && data.pathAssets.length > 0}

View File

@ -3,38 +3,28 @@ import { foldersStore } from '$lib/stores/folders.svelte';
import { authenticate } from '$lib/utils/auth'; import { authenticate } from '$lib/utils/auth';
import { getFormatter } from '$lib/utils/i18n'; import { getFormatter } from '$lib/utils/i18n';
import { getAssetInfoFromParam } from '$lib/utils/navigation'; import { getAssetInfoFromParam } from '$lib/utils/navigation';
import { buildTree, normalizeTreePath } from '$lib/utils/tree-utils';
import type { PageLoad } from './$types'; import type { PageLoad } from './$types';
export const load = (async ({ params, url }) => { export const load = (async ({ params, url }) => {
await authenticate(url); await authenticate(url);
const asset = await getAssetInfoFromParam(params); const [, asset, $t] = await Promise.all([foldersStore.fetchTree(), getAssetInfoFromParam(params), getFormatter()]);
const $t = await getFormatter();
await foldersStore.fetchUniquePaths();
let pathAssets = null;
let tree = foldersStore.folders!;
const path = url.searchParams.get(QueryParameter.PATH); const path = url.searchParams.get(QueryParameter.PATH);
if (path) { if (path) {
await foldersStore.fetchAssetsByPath(path); tree = tree.traverse(path);
pathAssets = foldersStore.assets[path] || null; } else if (path === null) {
} else { // If no path is provided, we've just navigated to the folders page.
// If no path is provided, we we're at the root level
// We should bust the asset cache of the folder store, to make sure we don't show stale data // We should bust the asset cache of the folder store, to make sure we don't show stale data
foldersStore.bustAssetCache(); foldersStore.bustAssetCache();
} }
let tree = buildTree(foldersStore.uniquePaths); // only fetch assets if the folder has assets
const parts = normalizeTreePath(path || '').split('/'); const pathAssets = tree.hasAssets ? await foldersStore.fetchAssetsByPath(tree.path) : null;
for (const part of parts) {
tree = tree?.[part];
}
return { return {
asset, asset,
path, tree,
currentFolders: Object.keys(tree || {}).sort(),
pathAssets, pathAssets,
meta: { meta: {
title: $t('folders'), title: $t('folders'),

View File

@ -1,6 +1,5 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { page } from '$app/stores';
import SkipLink from '$lib/components/elements/buttons/skip-link.svelte'; import SkipLink from '$lib/components/elements/buttons/skip-link.svelte';
import UserPageLayout, { headerId } from '$lib/components/layouts/user-page-layout.svelte'; import UserPageLayout, { headerId } from '$lib/components/layouts/user-page-layout.svelte';
import AssetGrid from '$lib/components/photos-page/asset-grid.svelte'; import AssetGrid from '$lib/components/photos-page/asset-grid.svelte';
@ -15,9 +14,9 @@
import Sidebar from '$lib/components/sidebar/sidebar.svelte'; import Sidebar from '$lib/components/sidebar/sidebar.svelte';
import { AppRoute, AssetAction, QueryParameter, SettingInputFieldType } from '$lib/constants'; import { AppRoute, AssetAction, QueryParameter, SettingInputFieldType } from '$lib/constants';
import { modalManager } from '$lib/managers/modal-manager.svelte'; import { modalManager } from '$lib/managers/modal-manager.svelte';
import { AssetInteraction } from '$lib/stores/asset-interaction.svelte';
import { AssetStore } from '$lib/managers/timeline-manager/asset-store.svelte'; import { AssetStore } from '$lib/managers/timeline-manager/asset-store.svelte';
import { buildTree, normalizeTreePath } from '$lib/utils/tree-utils'; import { AssetInteraction } from '$lib/stores/asset-interaction.svelte';
import { joinPaths, TreeNode } from '$lib/utils/tree-utils';
import { deleteTag, getAllTags, updateTag, upsertTags, type TagResponseDto } from '@immich/sdk'; import { deleteTag, getAllTags, updateTag, upsertTags, type TagResponseDto } from '@immich/sdk';
import { Button, HStack, Modal, ModalBody, ModalFooter, Text } from '@immich/ui'; import { Button, HStack, Modal, ModalBody, ModalFooter, Text } from '@immich/ui';
import { mdiPencil, mdiPlus, mdiTag, mdiTagMultiple, mdiTrashCanOutline } from '@mdi/js'; import { mdiPencil, mdiPlus, mdiTag, mdiTagMultiple, mdiTrashCanOutline } from '@mdi/js';
@ -31,38 +30,24 @@
let { data }: Props = $props(); let { data }: Props = $props();
let pathSegments = $derived(data.path ? data.path.split('/') : []);
let currentPath = $derived($page.url.searchParams.get(QueryParameter.PATH) || '');
const assetInteraction = new AssetInteraction(); const assetInteraction = new AssetInteraction();
const buildMap = (tags: TagResponseDto[]) => {
return Object.fromEntries(tags.map((tag) => [tag.value, tag]));
};
const assetStore = new AssetStore(); const assetStore = new AssetStore();
$effect(() => void assetStore.updateOptions({ deferInit: !tag, tagId })); $effect(() => void assetStore.updateOptions({ deferInit: !tag, tagId: tag.id }));
onDestroy(() => assetStore.destroy()); onDestroy(() => assetStore.destroy());
let tags = $derived<TagResponseDto[]>(data.tags); let tags = $derived<TagResponseDto[]>(data.tags);
let tagsMap = $derived(buildMap(tags)); const tree = $derived(TreeNode.fromTags(tags));
let tag = $derived(currentPath ? tagsMap[currentPath] : null); const tag = $derived(tree.traverse(data.path));
let tagId = $derived(tag?.id);
let tree = $derived(buildTree(tags.map((tag) => tag.value)));
const handleNavigation = async (tag: string) => { const handleNavigation = (tag: string) => navigateToView(joinPaths(data.path, tag));
await navigateToView(normalizeTreePath(`${data.path || ''}/${tag}`));
};
const getLink = (path: string) => { const getLink = (path: string) => {
const url = new URL(AppRoute.TAGS, globalThis.location.href); const url = new URL(AppRoute.TAGS, globalThis.location.href);
if (path) {
url.searchParams.set(QueryParameter.PATH, path); url.searchParams.set(QueryParameter.PATH, path);
}
return url.href; return url.href;
}; };
const getColor = (path: string) => tagsMap[path]?.color;
const navigateToView = (path: string) => goto(getLink(path)); const navigateToView = (path: string) => goto(getLink(path));
let isNewOpen = $state(false); let isNewOpen = $state(false);
@ -86,7 +71,7 @@
const handleSubmit = async () => { const handleSubmit = async () => {
if (tag && isEditOpen && newTagColor) { if (tag && isEditOpen && newTagColor) {
await updateTag({ id: tag.id, tagUpdateDto: { color: newTagColor } }); await updateTag({ id: tag.id!, tagUpdateDto: { color: newTagColor } });
notificationController.show({ notificationController.show({
message: $t('tag_updated', { values: { tag: tag.value } }), message: $t('tag_updated', { values: { tag: tag.value } }),
@ -125,12 +110,11 @@
return; return;
} }
await deleteTag({ id: tag.id }); await deleteTag({ id: tag.id! });
tags = await getAllTags(); tags = await getAllTags();
// navigate to parent // navigate to parent
const parentPath = pathSegments.slice(0, -1).join('/'); await navigateToView(tag.parent ? tag.parent.path : '');
await navigateToView(parentPath);
}; };
const onsubmit = async (event: Event) => { const onsubmit = async (event: Event) => {
@ -146,13 +130,7 @@
<section> <section>
<div class="text-xs ps-4 mb-2 dark:text-white">{$t('explorer').toUpperCase()}</div> <div class="text-xs ps-4 mb-2 dark:text-white">{$t('explorer').toUpperCase()}</div>
<div class="h-full"> <div class="h-full">
<TreeItems <TreeItems icons={{ default: mdiTag, active: mdiTag }} {tree} active={tag.path} {getLink} />
icons={{ default: mdiTag, active: mdiTag }}
items={tree}
active={currentPath}
{getLink}
{getColor}
/>
</div> </div>
</section> </section>
</Sidebar> </Sidebar>
@ -164,7 +142,7 @@
<Text class="hidden md:block">{$t('create_tag')}</Text> <Text class="hidden md:block">{$t('create_tag')}</Text>
</Button> </Button>
{#if pathSegments.length > 0 && tag} {#if tag.path.length > 0}
<Button leadingIcon={mdiPencil} onclick={handleEdit} size="small" variant="ghost" color="secondary"> <Button leadingIcon={mdiPencil} onclick={handleEdit} size="small" variant="ghost" color="secondary">
<Text class="hidden md:block">{$t('edit_tag')}</Text> <Text class="hidden md:block">{$t('edit_tag')}</Text>
</Button> </Button>
@ -175,17 +153,17 @@
</HStack> </HStack>
{/snippet} {/snippet}
<Breadcrumbs {pathSegments} icon={mdiTagMultiple} title={$t('tags')} {getLink} /> <Breadcrumbs node={tag} icon={mdiTagMultiple} title={$t('tags')} {getLink} />
<section class="mt-2 h-[calc(100%-(--spacing(20)))] overflow-auto immich-scrollbar"> <section class="mt-2 h-[calc(100%-(--spacing(20)))] overflow-auto immich-scrollbar">
{#if tag} {#if tag.hasAssets}
<AssetGrid enableRouting={true} {assetStore} {assetInteraction} removeAction={AssetAction.UNARCHIVE}> <AssetGrid enableRouting={true} {assetStore} {assetInteraction} removeAction={AssetAction.UNARCHIVE}>
{#snippet empty()} {#snippet empty()}
<TreeItemThumbnails items={data.children} icon={mdiTag} onClick={handleNavigation} /> <TreeItemThumbnails items={tag.children} icon={mdiTag} onClick={handleNavigation} />
{/snippet} {/snippet}
</AssetGrid> </AssetGrid>
{:else} {:else}
<TreeItemThumbnails items={Object.keys(tree)} icon={mdiTag} onClick={handleNavigation} /> <TreeItemThumbnails items={tag.children} icon={mdiTag} onClick={handleNavigation} />
{/if} {/if}
</section> </section>
</UserPageLayout> </UserPageLayout>

View File

@ -2,7 +2,6 @@ import { QueryParameter } from '$lib/constants';
import { authenticate } from '$lib/utils/auth'; import { authenticate } from '$lib/utils/auth';
import { getFormatter } from '$lib/utils/i18n'; import { getFormatter } from '$lib/utils/i18n';
import { getAssetInfoFromParam } from '$lib/utils/navigation'; import { getAssetInfoFromParam } from '$lib/utils/navigation';
import { buildTree, normalizeTreePath } from '$lib/utils/tree-utils';
import { getAllTags } from '@immich/sdk'; import { getAllTags } from '@immich/sdk';
import type { PageLoad } from './$types'; import type { PageLoad } from './$types';
@ -11,20 +10,12 @@ export const load = (async ({ params, url }) => {
const asset = await getAssetInfoFromParam(params); const asset = await getAssetInfoFromParam(params);
const $t = await getFormatter(); const $t = await getFormatter();
const path = url.searchParams.get(QueryParameter.PATH);
const tags = await getAllTags(); const tags = await getAllTags();
const tree = buildTree(tags.map((tag) => tag.value));
let currentTree = tree;
const parts = normalizeTreePath(path || '').split('/');
for (const part of parts) {
currentTree = currentTree?.[part];
}
return { return {
path: url.searchParams.get(QueryParameter.PATH) ?? '',
tags, tags,
asset, asset,
path,
children: Object.keys(currentTree || {}),
meta: { meta: {
title: $t('tags'), title: $t('tags'),
}, },