Skip to content

High performance self-hosted photo and video management solution.

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

Mert74f79cae69fe
diff --git a/web/src/lib/components/asset-viewer/detail-panel.svelte b/web/src/lib/components/asset-viewer/detail-panel.svelte
index c8adabd055..ef4ddc13ce 100644
--- a/web/src/lib/components/asset-viewer/detail-panel.svelte
+++ b/web/src/lib/components/asset-viewer/detail-panel.svelte
@@ -19,6 +19,7 @@
import { handleError } from '$lib/utils/handle-error';
import { getMetadataSearchQuery } from '$lib/utils/metadata-search';
import { fromISODateTime, fromISODateTimeUTC } from '$lib/utils/timeline-util';
+ import { getParentPath } from '$lib/utils/tree-utils';
import {
AssetMediaSize,
getAssetInfo,
@@ -137,7 +138,7 @@
const getAssetFolderHref = (asset: AssetResponseDto) => {
const folderUrl = new URL(AppRoute.FOLDERS, globalThis.location.href);
// 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);
return folderUrl.href;
};
diff --git a/web/src/lib/components/shared-components/tree/breadcrumbs.svelte b/web/src/lib/components/shared-components/tree/breadcrumbs.svelte
index 135dda0aca..01e442a928 100644
--- a/web/src/lib/components/shared-components/tree/breadcrumbs.svelte
+++ b/web/src/lib/components/shared-components/tree/breadcrumbs.svelte
@@ -1,23 +1,27 @@
<script lang="ts">
import Icon from '$lib/components/elements/icon.svelte';
+ import { TreeNode } from '$lib/utils/tree-utils';
import { IconButton } from '@immich/ui';
import { mdiArrowUpLeft, mdiChevronRight } from '@mdi/js';
import { t } from 'svelte-i18n';
interface Props {
- pathSegments?: string[];
+ node: TreeNode;
getLink: (path: string) => string;
title: 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>
<nav class="flex items-center py-2">
- {#if !isRoot}
+ {#if parentLink}
<div>
<IconButton
shape="round"
@@ -25,9 +29,8 @@
variant="ghost"
icon={mdiArrowUpLeft}
aria-label={$t('to_parent')}
- href={getLink(pathSegments.slice(0, -1).join('/'))}
+ href={parentLink}
class="me-2"
- onclick={() => {}}
/>
</div>
{/if}
@@ -42,31 +45,29 @@
color="secondary"
variant="ghost"
{icon}
- href={getLink('')}
+ href={rootLink}
aria-label={title}
size="medium"
aria-current={isRoot ? 'page' : undefined}
- onclick={() => {}}
/>
</li>
- {#each pathSegments as segment, index (index)}
- {@const isLastSegment = index === pathSegments.length - 1}
+ {#each parents as parent (parent)}
<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 />
- {#if isLastSegment}
- <p class="cursor-default whitespace-pre-wrap">{segment}</p>
- {:else}
- <a
- class="underline hover:font-semibold whitespace-pre-wrap"
- href={getLink(pathSegments.slice(0, index + 1).join('/'))}
- >
- {segment}
- </a>
- {/if}
+ <a class="underline hover:font-semibold whitespace-pre-wrap" href={getLink(parent.path)}>
+ {parent.value}
+ </a>
</li>
{/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>
</div>
</nav>
diff --git a/web/src/lib/components/shared-components/tree/tree-item-thumbnails.svelte b/web/src/lib/components/shared-components/tree/tree-item-thumbnails.svelte
index 71d87acb8d..da8c24697b 100644
--- a/web/src/lib/components/shared-components/tree/tree-item-thumbnails.svelte
+++ b/web/src/lib/components/shared-components/tree/tree-item-thumbnails.svelte
@@ -1,29 +1,31 @@
<script lang="ts">
import Icon from '$lib/components/elements/icon.svelte';
+ import type { TreeNode } from '$lib/utils/tree-utils';
interface Props {
- items?: string[];
+ items: TreeNode[];
icon: string;
onClick: (path: string) => void;
}
- let { items = [], icon, onClick }: Props = $props();
+ let { items, icon, onClick }: Props = $props();
</script>
{#if items.length > 0}
<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"
>
- {#each items as item (item)}
+ <!-- eslint-disable-next-line svelte/require-each-key -->
+ {#each items as item}
<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"
- onclick={() => onClick(item)}
- title={item}
+ onclick={() => onClick(item.value)}
+ title={item.value}
type="button"
>
<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">
- {item}
+ {item.value}
</p>
</button>
{/each}
diff --git a/web/src/lib/components/shared-components/tree/tree-items.svelte b/web/src/lib/components/shared-components/tree/tree-items.svelte
index 0df71ca605..9c2fb6638e 100644
--- a/web/src/lib/components/shared-components/tree/tree-items.svelte
+++ b/web/src/lib/components/shared-components/tree/tree-items.svelte
@@ -1,28 +1,21 @@
<script lang="ts">
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 {
- items: RecursiveObject;
- parent?: string;
- active?: string;
+ tree: TreeNode;
+ active: string;
icons: { default: string; active: 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>
<ul class="list-none ms-2">
- <!-- eslint-disable-next-line svelte/require-each-key -->
- {#each Object.entries(items).sort() as [path, tree]}
- {@const value = normalizeTreePath(`${parent}/${path}`)}
- {@const key = value + getColor(value)}
- {#key key}
- <li>
- <Tree {parent} value={path} {tree} {icons} {active} {getLink} {getColor} />
- </li>
- {/key}
+ {#each tree.children as node (node.color ? node.path + node.color : node.path)}
+ <li>
+ <Tree {node} {icons} {active} {getLink} />
+ </li>
{/each}
</ul>
diff --git a/web/src/lib/components/shared-components/tree/tree.svelte b/web/src/lib/components/shared-components/tree/tree.svelte
index 25c40f096e..6311b69831 100644
--- a/web/src/lib/components/shared-components/tree/tree.svelte
+++ b/web/src/lib/components/shared-components/tree/tree.svelte
@@ -1,25 +1,20 @@
<script lang="ts">
import Icon from '$lib/components/elements/icon.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';
interface Props {
- tree: RecursiveObject;
- parent: string;
- value: string;
- active?: string;
+ node: TreeNode;
+ active: string;
icons: { default: string; active: 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 isActive = $derived(active === path || active.startsWith(`${path}/`));
- const isTarget = $derived(active === path);
- const color = $derived(getColor(path));
+ const isTarget = $derived(active === node.path);
+ const isActive = $derived(active === node.path || active.startsWith(node.value === '/' ? '/' : `${node.path}/`));
let isOpen = $derived(isActive);
const onclick = (event: MouseEvent) => {
@@ -29,25 +24,27 @@
</script>
<a
- href={getLink(path)}
- title={value}
+ href={getLink(node.path)}
+ 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'}`}
data-sveltekit-keepfocus
>
- <button type="button" {onclick} class={Object.values(tree).length === 0 ? 'invisible' : ''}>
- <Icon path={isOpen ? mdiChevronDown : mdiChevronRight} class="text-gray-400" size={20} />
- </button>
- <div>
+ {#if node.size > 0}
+ <button type="button" {onclick}>
+ <Icon path={isOpen ? mdiChevronDown : mdiChevronRight} class="text-gray-400" size={20} />
+ </button>
+ {/if}
+ <div class={node.size === 0 ? 'ml-[1.5em] ' : ''}>
<Icon
path={isActive ? icons.active : icons.default}
class={isActive ? 'text-immich-primary dark:text-immich-dark-primary' : 'text-gray-400'}
- {color}
+ color={node.color}
size={20}
/>
</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>
{#if isOpen}
- <TreeItems parent={path} items={tree} {icons} {active} {getLink} {getColor} />
+ <TreeItems tree={node} {icons} {active} {getLink} />
{/if}
diff --git a/web/src/lib/stores/folders.svelte.ts b/web/src/lib/stores/folders.svelte.ts
index 6f3eb8b66a..f77b67bb7c 100644
--- a/web/src/lib/stores/folders.svelte.ts
+++ b/web/src/lib/stores/folders.svelte.ts
@@ -1,4 +1,5 @@
import { eventManager } from '$lib/managers/event-manager.svelte';
+import { TreeNode } from '$lib/utils/tree-utils';
import {
getAssetsByOriginalPath,
getUniqueOriginalPaths,
@@ -13,47 +14,41 @@ type AssetCache = {
};
class FoldersStore {
+ folders = $state.raw<TreeNode | null>(null);
private initialized = false;
- uniquePaths = $state<string[]>([]);
- assets = $state<AssetCache>({});
+ private assets = $state<AssetCache>({});
constructor() {
eventManager.on('auth.logout', () => this.clearCache());
}
- async fetchUniquePaths() {
+ async fetchTree(): Promise<TreeNode> {
if (this.initialized) {
- return;
+ return this.folders!;
}
this.initialized = true;
- const uniquePaths = await getUniqueOriginalPaths();
- this.uniquePaths.push(...uniquePaths);
+ this.folders = TreeNode.fromPaths(await getUniqueOriginalPaths());
+ this.folders.collapse();
+ return this.folders;
}
bustAssetCache() {
this.assets = {};
}
- async refreshAssetsByPath(path: string | null) {
- if (!path) {
- return;
- }
- this.assets[path] = await getAssetsByOriginalPath({ path });
+ async refreshAssetsByPath(path: string) {
+ return (this.assets[path] = await getAssetsByOriginalPath({ path }));
}
async fetchAssetsByPath(path: string) {
- if (this.assets[path]) {
- return;
- }
-
- this.assets[path] = await getAssetsByOriginalPath({ path });
+ return (this.assets[path] ??= await getAssetsByOriginalPath({ path }));
}
clearCache() {
this.initialized = false;
- this.uniquePaths = [];
this.assets = {};
+ this.folders = null;
}
}
diff --git a/web/src/lib/utils/navigation.ts b/web/src/lib/utils/navigation.ts
index c3b4d83f38..89e1f9f5f0 100644
--- a/web/src/lib/utils/navigation.ts
+++ b/web/src/lib/utils/navigation.ts
@@ -23,7 +23,7 @@ export const isAssetViewerRoute = (target?: NavigationTarget | null) =>
!!(target?.route.id?.endsWith('/[[assetId=id]]') && 'assetId' in (target?.params || {}));
export function getAssetInfoFromParam({ assetId, key }: { assetId?: string; key?: string }) {
- return assetId && getAssetInfo({ id: assetId, key });
+ return assetId ? getAssetInfo({ id: assetId, key }) : undefined;
}
function currentUrlWithoutAsset() {
diff --git a/web/src/lib/utils/tree-utils.ts b/web/src/lib/utils/tree-utils.ts
index 5a6e917079..267bb2eec7 100644
--- a/web/src/lib/utils/tree-utils.ts
+++ b/web/src/lib/utils/tree-utils.ts
@@ -1,21 +1,144 @@
-export interface RecursiveObject {
- [key: string]: RecursiveObject;
-}
+/* eslint-disable @typescript-eslint/no-this-alias */
+/* 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;
-export const normalizeTreePath = (path: string) => path.replace(/^\//, '').replace(/\/$/, '');
+ private constructor(value: string, path: string, parent: TreeNode | null) {
+ super();
+ this.value = value;
+ this.parent = parent;
+ this.path = path;
+ this.hasAssets = false;
+ }
-export function buildTree(paths: string[]) {
- const root: RecursiveObject = {};
+ static fromPaths(paths: string[]) {
+ const root = new TreeNode('', '', null);
+ for (const path of paths) {
+ const current = root.add(path);
+ current.hasAssets = true;
+ }
+ return root;
+ }
- for (const path of paths) {
- const parts = path.split('/');
- let current = 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) {
- if (!current[part]) {
- current[part] = {};
+ // 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;
}
- current = current[part];
}
+ 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 root;
+ return last === 0 ? '/' : normalized;
}
diff --git a/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.svelte b/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.svelte
index 89df31562e..84ae328ccc 100644
--- a/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.svelte
+++ b/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.svelte
@@ -1,6 +1,5 @@
<script lang="ts">
import { afterNavigate, goto, invalidateAll } from '$app/navigation';
- import { page } from '$app/stores';
import SkipLink from '$lib/components/elements/buttons/skip-link.svelte';
import UserPageLayout, { headerId } from '$lib/components/layouts/user-page-layout.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 { cancelMultiselect } from '$lib/utils/asset-utils';
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 { mdiDotsVertical, mdiFolder, mdiFolderHome, mdiFolderOutline, mdiPlus, mdiSelectAll } from '@mdi/js';
- import { onMount } from 'svelte';
import { t } from 'svelte-i18n';
import type { PageData } from './$types';
@@ -43,51 +41,40 @@
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();
- onMount(async function initializeFolders() {
- await foldersStore.fetchUniquePaths();
- });
-
- const handleNavigateToFolder = async function handleNavigateToFolder(folderName: string) {
- await navigateToView(normalizeTreePath(`${data.path || ''}/${folderName}`));
- };
+ const handleNavigateToFolder = (folderName: string) => navigateToView(joinPaths(data.tree.path, folderName));
- const getLinkForPath = function getLinkForPath(path: string) {
+ function getLinkForPath(path: string) {
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;
- };
+ }
afterNavigate(function clearAssetSelection() {
// Clear the asset selection when we navigate (like going to another folder)
cancelMultiselect(assetInteraction);
});
- const navigateToView = function navigateToView(path: string) {
- return goto(getLinkForPath(path));
- };
+ function navigateToView(path: string) {
+ return goto(getLinkForPath(path), { keepFocus: true, noScroll: true });
+ }
- const triggerAssetUpdate = async function updateAssets() {
+ async function triggerAssetUpdate() {
cancelMultiselect(assetInteraction);
- await foldersStore.refreshAssetsByPath(data.path);
+ if (data.tree.path) {
+ await foldersStore.refreshAssetsByPath(data.tree.path);
+ }
await invalidateAll();
- };
+ }
- const handleSelectAllAssets = function handleSelectAllAssets() {
+ function handleSelectAllAssets() {
if (!data.pathAssets) {
return;
}
assetInteraction.selectAssets(data.pathAssets.map((asset) => toTimelineAsset(asset)));
- };
+ }
</script>
<UserPageLayout title={data.meta.title}>
@@ -99,8 +86,8 @@
<div class="h-full">
<TreeItems
icons={{ default: mdiFolderOutline, active: mdiFolder }}
- items={tree}
- active={currentPath}
+ tree={foldersStore.folders!}
+ active={data.tree.path}
getLink={getLinkForPath}
/>
</div>
@@ -108,10 +95,10 @@
</Sidebar>
{/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">
- <TreeItemThumbnails items={currentTreeItems} icon={mdiFolder} onClick={handleNavigateToFolder} />
+ <TreeItemThumbnails items={data.tree.children} icon={mdiFolder} onClick={handleNavigateToFolder} />
<!-- Assets -->
{#if data.pathAssets && data.pathAssets.length > 0}
diff --git a/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.ts b/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.ts
index 7fd0a749c0..72fb102e53 100644
--- a/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.ts
+++ b/web/src/routes/(user)/folders/[[photos=photos]]/[[assetId=id]]/+page.ts
@@ -3,38 +3,28 @@ import { foldersStore } from '$lib/stores/folders.svelte';
import { authenticate } from '$lib/utils/auth';
import { getFormatter } from '$lib/utils/i18n';
import { getAssetInfoFromParam } from '$lib/utils/navigation';
-import { buildTree, normalizeTreePath } from '$lib/utils/tree-utils';
import type { PageLoad } from './$types';
export const load = (async ({ params, url }) => {
await authenticate(url);
- const asset = await getAssetInfoFromParam(params);
- const $t = await getFormatter();
-
- await foldersStore.fetchUniquePaths();
-
- let pathAssets = null;
+ const [, asset, $t] = await Promise.all([foldersStore.fetchTree(), getAssetInfoFromParam(params), getFormatter()]);
+ let tree = foldersStore.folders!;
const path = url.searchParams.get(QueryParameter.PATH);
if (path) {
- await foldersStore.fetchAssetsByPath(path);
- pathAssets = foldersStore.assets[path] || null;
- } else {
- // If no path is provided, we we're at the root level
+ tree = tree.traverse(path);
+ } else if (path === null) {
+ // If no path is provided, we've just navigated to the folders page.
// We should bust the asset cache of the folder store, to make sure we don't show stale data
foldersStore.bustAssetCache();
}
- let tree = buildTree(foldersStore.uniquePaths);
- const parts = normalizeTreePath(path || '').split('/');
- for (const part of parts) {
- tree = tree?.[part];
- }
+ // only fetch assets if the folder has assets
+ const pathAssets = tree.hasAssets ? await foldersStore.fetchAssetsByPath(tree.path) : null;
return {
asset,
- path,
- currentFolders: Object.keys(tree || {}).sort(),
+ tree,
pathAssets,
meta: {
title: $t('folders'),
diff --git a/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.svelte b/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.svelte
index a42c6534a7..e344c448b0 100644
--- a/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.svelte
+++ b/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.svelte
@@ -1,6 +1,5 @@
<script lang="ts">
import { goto } from '$app/navigation';
- import { page } from '$app/stores';
import SkipLink from '$lib/components/elements/buttons/skip-link.svelte';
import UserPageLayout, { headerId } from '$lib/components/layouts/user-page-layout.svelte';
import AssetGrid from '$lib/components/photos-page/asset-grid.svelte';
@@ -15,9 +14,9 @@
import Sidebar from '$lib/components/sidebar/sidebar.svelte';
import { AppRoute, AssetAction, QueryParameter, SettingInputFieldType } from '$lib/constants';
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 { 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 { Button, HStack, Modal, ModalBody, ModalFooter, Text } from '@immich/ui';
import { mdiPencil, mdiPlus, mdiTag, mdiTagMultiple, mdiTrashCanOutline } from '@mdi/js';
@@ -31,38 +30,24 @@
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 buildMap = (tags: TagResponseDto[]) => {
- return Object.fromEntries(tags.map((tag) => [tag.value, tag]));
- };
const assetStore = new AssetStore();
- $effect(() => void assetStore.updateOptions({ deferInit: !tag, tagId }));
+ $effect(() => void assetStore.updateOptions({ deferInit: !tag, tagId: tag.id }));
onDestroy(() => assetStore.destroy());
let tags = $derived<TagResponseDto[]>(data.tags);
- let tagsMap = $derived(buildMap(tags));
- let tag = $derived(currentPath ? tagsMap[currentPath] : null);
- let tagId = $derived(tag?.id);
- let tree = $derived(buildTree(tags.map((tag) => tag.value)));
+ const tree = $derived(TreeNode.fromTags(tags));
+ const tag = $derived(tree.traverse(data.path));
- const handleNavigation = async (tag: string) => {
- await navigateToView(normalizeTreePath(`${data.path || ''}/${tag}`));
- };
+ const handleNavigation = (tag: string) => navigateToView(joinPaths(data.path, tag));
const getLink = (path: string) => {
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;
};
- const getColor = (path: string) => tagsMap[path]?.color;
-
const navigateToView = (path: string) => goto(getLink(path));
let isNewOpen = $state(false);
@@ -86,7 +71,7 @@
const handleSubmit = async () => {
if (tag && isEditOpen && newTagColor) {
- await updateTag({ id: tag.id, tagUpdateDto: { color: newTagColor } });
+ await updateTag({ id: tag.id!, tagUpdateDto: { color: newTagColor } });
notificationController.show({
message: $t('tag_updated', { values: { tag: tag.value } }),
@@ -125,12 +110,11 @@
return;
}
- await deleteTag({ id: tag.id });
+ await deleteTag({ id: tag.id! });
tags = await getAllTags();
// navigate to parent
- const parentPath = pathSegments.slice(0, -1).join('/');
- await navigateToView(parentPath);
+ await navigateToView(tag.parent ? tag.parent.path : '');
};
const onsubmit = async (event: Event) => {
@@ -146,13 +130,7 @@
<section>
<div class="text-xs ps-4 mb-2 dark:text-white">{$t('explorer').toUpperCase()}</div>
<div class="h-full">
- <TreeItems
- icons={{ default: mdiTag, active: mdiTag }}
- items={tree}
- active={currentPath}
- {getLink}
- {getColor}
- />
+ <TreeItems icons={{ default: mdiTag, active: mdiTag }} {tree} active={tag.path} {getLink} />
</div>
</section>
</Sidebar>
@@ -164,7 +142,7 @@
<Text class="hidden md:block">{$t('create_tag')}</Text>
</Button>
- {#if pathSegments.length > 0 && tag}
+ {#if tag.path.length > 0}
<Button leadingIcon={mdiPencil} onclick={handleEdit} size="small" variant="ghost" color="secondary">
<Text class="hidden md:block">{$t('edit_tag')}</Text>
</Button>
@@ -175,17 +153,17 @@
</HStack>
{/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">
- {#if tag}
+ {#if tag.hasAssets}
<AssetGrid enableRouting={true} {assetStore} {assetInteraction} removeAction={AssetAction.UNARCHIVE}>
{#snippet empty()}
- <TreeItemThumbnails items={data.children} icon={mdiTag} onClick={handleNavigation} />
+ <TreeItemThumbnails items={tag.children} icon={mdiTag} onClick={handleNavigation} />
{/snippet}
</AssetGrid>
{:else}
- <TreeItemThumbnails items={Object.keys(tree)} icon={mdiTag} onClick={handleNavigation} />
+ <TreeItemThumbnails items={tag.children} icon={mdiTag} onClick={handleNavigation} />
{/if}
</section>
</UserPageLayout>
diff --git a/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.ts b/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.ts
index 6e92eda7d3..225d79a38d 100644
--- a/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.ts
+++ b/web/src/routes/(user)/tags/[[photos=photos]]/[[assetId=id]]/+page.ts
@@ -2,7 +2,6 @@ import { QueryParameter } from '$lib/constants';
import { authenticate } from '$lib/utils/auth';
import { getFormatter } from '$lib/utils/i18n';
import { getAssetInfoFromParam } from '$lib/utils/navigation';
-import { buildTree, normalizeTreePath } from '$lib/utils/tree-utils';
import { getAllTags } from '@immich/sdk';
import type { PageLoad } from './$types';
@@ -11,20 +10,12 @@ export const load = (async ({ params, url }) => {
const asset = await getAssetInfoFromParam(params);
const $t = await getFormatter();
- const path = url.searchParams.get(QueryParameter.PATH);
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 {
+ path: url.searchParams.get(QueryParameter.PATH) ?? '',
tags,
asset,
- path,
- children: Object.keys(currentTree || {}),
meta: {
title: $t('tags'),
},