Files
open-webui/src/lib/components/chat/Placeholder/FolderOverview.svelte
T
2026-12-05 07:23:18 +04:00

610 lines
22 KiB
Svelte

<script lang="ts">
import { getContext } from 'svelte';
import { goto } from '$app/navigation';
import { config, folders, models, teams } from '$lib/stores';
import { loadFolderChatPage, type FolderDetails } from '$lib/stores/folderStates';
import type { FolderAutomation } from '$lib/apis/automations';
import { getTasks, type Task } from '$lib/apis/tasks';
import { taskStatusDef } from '$lib/utils/tasks';
import StatusIcon from './FolderStatusIcon.svelte';
import type { AppLayoutContext } from '$lib/types';
import type { WorkspaceChat } from '$lib/utils/folders';
import { openFolderChat } from './folderChat';
import FolderChatLink from './FolderChatLink.svelte';
import NotesIcon from '$lib/components/layout/Sidebar/icons/Notes.svelte';
import Emoji from '$lib/components/common/Emoji.svelte';
import Textarea from '$lib/components/common/Textarea.svelte';
import EmojiPicker from '$lib/components/common/EmojiPicker.svelte';
import ChevronRight from '$lib/components/layout/Sidebar/icons/ChevronRight.svelte';
import SettingsAlt from '$lib/components/icons/SettingsAlt.svelte';
import Icon from '$lib/components/chat/FileNav/Icon.svelte';
import TeamIcon from '$lib/components/teams/TeamIcon.svelte';
import TeamItemIcon from '$lib/components/teams/TeamItemIcon.svelte';
import { getUserInfoById } from '$lib/apis/users';
import { getGroupInfoById } from '$lib/apis/groups';
import UserGroup from '$lib/components/icons/UserGroup.svelte';
import { WEBUI_API_BASE_URL } from '$lib/constants';
const i18n = getContext<any>('i18n');
const appLayout = getContext<AppLayoutContext | undefined>('appLayout');
export let folder: FolderDetails;
export let readOnly = false;
export let iconSaving = false;
export let onIcon: (icon: string | null) => void = () => {};
// Saves fields of the folder's data, such as its summary and description.
export let onSave: (data: Record<string, string>) => void = () => {};
export let onEdit: () => void = () => {};
export let onChats: () => void = () => {};
export let onKnowledge: () => void = () => {};
// Set when the folder's directory can be opened; null otherwise.
export let onFiles: (() => void) | null = null;
// The folder page's loaded notes and automations; null when the feature is off.
export let notes: { id: string; title: string }[] | null = null;
export let automations: FolderAutomation[] | null = null;
// As many as the sidebar's first page of a folder's chats (folderStates).
const RECENT = 10;
// The sidebar's order: unread first, then most recently updated. Its cached page is reused.
let chats: WorkspaceChat[] = [];
let chatsFor = '';
$: if (folder.id !== chatsFor) {
chatsFor = folder.id;
chats = [];
const folderId = folder.id;
loadFolderChatPage(localStorage.token, folderId)
.then((page) => {
if (folder.id === folderId) chats = (page.chats as WorkspaceChat[]).slice(0, RECENT);
})
.catch(() => {});
}
// Open tasks, newest first, when tasks are on.
let tasks: Task[] = [];
let tasksFor = '';
$: if ($config?.features?.enable_tasks && folder.id !== tasksFor) {
tasksFor = folder.id;
tasks = [];
const folderId = folder.id;
getTasks(localStorage.token, {
folder_id: folderId,
category: ['backlog', 'todo', 'in_progress', 'waiting', 'none'],
sort_by: 'updated_at'
})
.then((page) => {
if (folder.id === folderId) tasks = page.tasks.slice(0, RECENT);
})
.catch(() => {});
}
// Notes and automations open in a page tab, as their own tabs open them.
const openPage = (event: MouseEvent, href: string, label: string) => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
return;
event.preventDefault();
if (appLayout?.openPageTab) appLayout.openPageTab({ href, label });
else void goto(href);
};
// A one-line summary under the name and a longer description, as on a Linear project.
$: summary = (folder.data?.summary ?? '').trim();
$: description = (folder.data?.description ?? '').trim();
// Edited in place; the saved text comes back in when another folder opens or a save lands.
let summaryDraft = '';
let draft = '';
let draftFor = '';
$: if (`${folder.id}:${summary}:${description}` !== draftFor) {
draftFor = `${folder.id}:${summary}:${description}`;
summaryDraft = summary;
draft = description;
}
const saveSummary = () => {
if (summaryDraft.trim() !== summary) onSave({ summary: summaryDraft.trim() });
};
const saveDraft = () => {
if (draft.trim() !== description) onSave({ description: draft.trim() });
};
$: subfolders = ($folders as FolderDetails[]).filter((child) => child.parent_id === folder.id);
$: folderModels = (folder.data?.model_ids ?? []).map((id: string) => ({
id,
name: ($models ?? []).find((model) => model.id === id)?.name ?? id
}));
$: knowledge = (folder.data?.files ?? []) as { id: string; name?: string; type?: string }[];
$: directory = folder.data?.machine_id ? (folder.data?.working_directory ?? '') : '';
// Everyone the folder reaches: its owner, then everyone, teams, groups and people it's shared with.
type SharedEntry = {
key: string;
kind: 'user' | 'group' | 'team' | 'anyone';
id: string;
name: string;
edit: boolean;
owner?: boolean;
href?: string;
team?: (typeof $teams)[number];
};
let names: Record<string, string> = {};
const resolving = new Set<string>();
const resolveNames = async (grants: { principal_type: string; principal_id: string }[]) => {
const pending = grants.filter(
(grant) =>
(grant.principal_type === 'user' || grant.principal_type === 'group') &&
grant.principal_id !== '*' &&
!(grant.principal_id in names) &&
!resolving.has(grant.principal_id)
);
pending.forEach((grant) => resolving.add(grant.principal_id));
const found = await Promise.all(
pending.map(async (grant) => {
const info = await (grant.principal_type === 'user' ? getUserInfoById : getGroupInfoById)(
localStorage.token,
grant.principal_id
).catch(() => null);
return [grant.principal_id, info?.name ?? ''] as const;
})
);
names = { ...names, ...Object.fromEntries(found) };
};
$: grants = (folder.access_grants ?? []) as {
principal_type: string;
principal_id: string;
permission: string;
}[];
$: void resolveNames([...grants, { principal_type: 'user', principal_id: owner }]);
$: owner = folder.user_id ?? '';
$: people = sharedWith.filter((entry) => entry.kind === 'user');
$: sharedWith = ((): SharedEntry[] => {
const byPrincipal = new Map<string, SharedEntry>();
for (const grant of grants) {
const kind =
grant.principal_type === 'user' && grant.principal_id === '*'
? 'anyone'
: (grant.principal_type as SharedEntry['kind']);
const key = `${kind}:${grant.principal_id}`;
const team =
kind === 'team' ? $teams.find((item) => item.id === grant.principal_id) : undefined;
if (kind === 'team' && !team) continue;
const entry = byPrincipal.get(key) ?? {
key,
kind,
id: grant.principal_id,
name:
kind === 'anyone' ? $i18n.t('Everyone') : (team?.name ?? names[grant.principal_id] ?? ''),
edit: false,
team,
href: team ? `/teams/${team.id}` : undefined
};
entry.edit ||= grant.permission === 'write';
byPrincipal.set(key, entry);
}
const order = { anyone: 0, team: 1, group: 2, user: 3 };
return [
{
key: `owner:${owner}`,
kind: 'user',
id: owner,
name: names[owner] ?? '',
edit: true,
owner: true
},
...[...byPrincipal.values()]
.filter((entry) => !(entry.kind === 'user' && entry.id === owner))
.sort((a, b) => order[a.kind] - order[b.kind] || a.name.localeCompare(b.name))
];
})();
// Folded groups are remembered per folder, as the team Overview remembers its own.
const COLLAPSED = 'folder-overview-collapsed';
let collapsed: Record<string, Record<string, boolean>> = (() => {
try {
return JSON.parse(localStorage.getItem(COLLAPSED) ?? '{}') ?? {};
} catch {
return {};
}
})();
$: folded = collapsed[folder.id] ?? {};
const toggleCollapsed = (group: string) => {
const { [group]: wasFolded, ...rest } = collapsed[folder.id] ?? {};
const next = wasFolded ? rest : { ...rest, [group]: true };
const { [folder.id]: _, ...others } = collapsed;
collapsed = Object.keys(next).length ? { ...others, [folder.id]: next } : others;
try {
localStorage.setItem(COLLAPSED, JSON.stringify(collapsed));
} catch {
/* Storage is optional. */
}
};
// The team Overview's rows and rail.
const overviewRow =
'group -mx-2 flex min-h-8 items-center gap-2 rounded-xl px-2 py-[0.375rem] text-left text-[0.8125rem] leading-5 text-base-800 transition-colors hover:text-base-1000 dark:text-base-200 dark:hover:text-base-0';
const groupRow =
'group flex min-h-8 items-center gap-2 py-[0.375rem] text-left text-[0.8125rem] leading-5 text-base-800 transition-colors hover:text-base-1000 dark:text-base-200 dark:hover:text-base-0';
// Models aren't links, so their rows don't darken.
const plainRow =
'flex min-h-8 items-center gap-2 py-[0.375rem] text-[0.8125rem] leading-5 text-base-800 dark:text-base-200';
// The rail's rows sit closer than the main column's, as in the team Overview's sidebar.
const railRow =
'group -mx-2 flex h-7 items-center gap-2 rounded-xl px-2 text-left text-[0.8125rem] text-base-800 transition-colors hover:text-base-1000 dark:text-base-200 dark:hover:text-base-0';
const railPlain = 'flex h-7 items-center gap-2 text-[0.8125rem] text-base-800 dark:text-base-200';
const railLabel = 'mb-1 text-[0.6875rem] text-base-400 dark:text-base-500';
const railIcon =
'flex size-4 shrink-0 items-center justify-center text-base-400 dark:text-base-500';
</script>
{#snippet folderIcon(className: string)}
{#if folder.meta?.icon}
<Emoji shortCode={folder.meta.icon} {className} />
{:else}
<Icon name="folder" size={15} />
{/if}
{/snippet}
<!-- The team Overview's group heading: the sidebar's Section heading, whose chevron shows on hover. -->
{#snippet groupHeader(group: string, label: string)}
<div class="flex h-6 items-center">
<h3 class="flex h-full">
<button
type="button"
class="group flex h-full items-center gap-1 text-xs text-base-400 transition-colors duration-100 hover:text-base-500 dark:text-base-500 dark:hover:text-base-400"
aria-expanded={!folded[group]}
on:click={() => toggleCollapsed(group)}
>
<span>{label}</span>
<span
class="flex opacity-0 transition-all duration-100 group-hover:opacity-100 group-focus-visible:opacity-100"
style="transform: rotate({folded[group] ? '0deg' : '90deg'})"
>
<ChevronRight className="size-[0.6875rem]" />
</span>
</button>
</h3>
</div>
{/snippet}
{#snippet sharedEntry(entry: SharedEntry)}
<span class={railIcon}>
{#if entry.team}
<TeamIcon team={entry.team} className="size-3.5" />
{:else if entry.kind === 'user'}
<img
class="size-3.5 rounded-full object-cover"
src={`${WEBUI_API_BASE_URL}/users/${entry.id}/profile/image`}
alt=""
/>
{:else if entry.kind === 'group'}
<UserGroup className="size-3.5" strokeWidth="1.5" />
{:else}
<Icon name="globe" size={14} />
{/if}
</span>
<span class="min-w-0 flex-1 truncate">{entry.name}</span>
<span class="shrink-0 text-[0.6875rem] text-base-400 dark:text-base-500"
>{entry.owner ? $i18n.t('Owner') : entry.edit ? $i18n.t('Can edit') : $i18n.t('Can view')}</span
>
{/snippet}
<!-- The team Overview for a folder, as a Linear project opens on its Overview. -->
<div class="h-full overflow-y-auto scrollbar-hover">
<div
class="w-full px-2.5 pt-1 text-sm md:px-3.5"
style="padding-bottom: calc(var(--folder-composer-space, 0px) + 3rem)"
>
<div class="grid w-full gap-7 pt-1 @2xl:grid-cols-[minmax(0,1fr)_13rem]">
<div class="min-w-0">
<div class="flex items-center gap-3">
{#if readOnly}
<span
class="flex size-[1.875rem] shrink-0 items-center justify-center rounded-lg bg-base-1000/[0.035] text-base-500 dark:bg-base-0/[0.06] dark:text-base-400"
>{@render folderIcon('size-[0.9375rem]')}</span
>
{:else}
<EmojiPicker side="bottom" selected={folder.meta?.icon || null} onSubmit={onIcon}>
<button
type="button"
class="flex size-[1.875rem] shrink-0 items-center justify-center rounded-lg bg-base-1000/[0.035] text-base-500 transition-colors hover:text-base-700 disabled:opacity-50 dark:bg-base-0/[0.06] dark:text-base-400 dark:hover:text-base-200"
aria-label={$i18n.t('Change folder icon')}
title={$i18n.t('Change folder icon')}
disabled={iconSaving}
>
{@render folderIcon('size-[0.9375rem]')}
</button>
</EmojiPicker>
{/if}
<h2 class="min-w-0 truncate text-xl font-medium text-base-900 dark:text-base-0">
{folder.name}
</h2>
</div>
{#if readOnly}
{#if summary}
<p
class="mt-3 truncate text-[0.8125rem] leading-relaxed text-base-600 dark:text-base-300"
>
{summary}
</p>
{/if}
{:else}
<input
class="mt-3 block w-full bg-transparent text-[0.8125rem] leading-relaxed text-base-600 outline-hidden placeholder:text-base-400 dark:text-base-300 dark:placeholder:text-base-500"
aria-label={$i18n.t('Summary')}
placeholder={$i18n.t('Add a short summary…')}
bind:value={summaryDraft}
on:blur={saveSummary}
on:keydown={(event) => {
if (event.key === 'Enter' && !event.isComposing) event.currentTarget.blur();
}}
/>
{/if}
<div class="mt-5 flex flex-col gap-4">
<!-- Always there for editors, like the team's Pinned; a placeholder until it's written. -->
{#if description || !readOnly}
<section>
{@render groupHeader('description', $i18n.t('Description'))}
{#if !folded.description}
{#if readOnly}
<p
class="py-1.5 text-[0.8125rem] leading-relaxed whitespace-pre-line text-base-600 dark:text-base-300"
>
{description}
</p>
{:else}
<Textarea
bind:value={draft}
ariaLabel={$i18n.t('Description')}
placeholder={$i18n.t('Add description')}
className="block w-full resize-none bg-transparent py-1.5 text-[0.8125rem] leading-relaxed text-base-600 outline-hidden placeholder:text-base-400 dark:text-base-300 dark:placeholder:text-base-500"
onBlur={saveDraft}
/>
{/if}
{/if}
</section>
{/if}
{#if chats.length}
<section>
{@render groupHeader('chats', $i18n.t('Chats'))}
{#if !folded.chats}
<ul class="py-0.5">
{#each chats as chat (chat.id)}
<li class={groupRow}>
<span class={railIcon}><Icon name="chat-bubble" size={14} /></span>
<FolderChatLink
chatId={chat.id}
title={chat.title}
className="min-w-0 truncate"
onclick={(event) => openFolderChat(chat, appLayout, event)}
/>
</li>
{/each}
</ul>
{/if}
</section>
{/if}
{#if tasks.length}
<section>
{@render groupHeader('tasks', $i18n.t('Tasks'))}
{#if !folded.tasks}
<ul class="py-0.5">
{#each tasks as task (task.id)}
<li>
<a
href="/tasks/{task.id}"
class={groupRow}
on:click={(event) =>
openPage(event, `/tasks/${task.id}`, `#${task.number} ${task.title}`)}
>
<span class={railIcon}
><StatusIcon
glyph={taskStatusDef(task, (key) => $i18n.t(key)).glyph}
color={taskStatusDef(task, (key) => $i18n.t(key)).color}
emoji={taskStatusDef(task, (key) => $i18n.t(key)).icon}
dot={!taskStatusDef(task, (key) => $i18n.t(key)).glyph}
/></span
>
<span class="shrink-0 text-base-400 tabular-nums dark:text-base-500"
>#{task.number}</span
>
<span class="min-w-0 truncate">{task.title}</span>
</a>
</li>
{/each}
</ul>
{/if}
</section>
{/if}
{#if notes?.length}
<section>
{@render groupHeader('notes', $i18n.t('Notes'))}
{#if !folded.notes}
<ul class="py-0.5">
{#each notes.slice(0, RECENT) as note (note.id)}
<li>
<a
href="/notes/{note.id}"
class={groupRow}
on:click={(event) => openPage(event, `/notes/${note.id}`, note.title)}
>
<span class={railIcon}
><NotesIcon className="size-3.5" strokeWidth="1.5" /></span
>
<span class="min-w-0 truncate">{note.title}</span>
</a>
</li>
{/each}
</ul>
{/if}
</section>
{/if}
{#if automations?.length}
<section>
{@render groupHeader('automations', $i18n.t('Automations'))}
{#if !folded.automations}
<ul class="py-0.5">
{#each automations.slice(0, RECENT) as automation (automation.id)}
<li>
<a
href="/automations/{automation.id}"
class={groupRow}
on:click={(event) =>
openPage(event, `/automations/${automation.id}`, automation.name)}
>
<span class={railIcon}><Icon name="clock" size={14} /></span>
<span class="min-w-0 truncate">{automation.name}</span>
</a>
</li>
{/each}
</ul>
{/if}
</section>
{/if}
{#if folderModels.length}
<section>
{@render groupHeader('models', $i18n.t('Models'))}
{#if !folded.models}
<!-- The models new chats here start with. -->
<ul class="py-0.5">
{#each folderModels as model (model.id)}
<li class={plainRow}>
<TeamItemIcon type="model" item={model} />
<span class="min-w-0 truncate">{model.name}</span>
</li>
{/each}
</ul>
{/if}
</section>
{/if}
{#if knowledge.length}
<section>
{@render groupHeader('knowledge', $i18n.t('Knowledge'))}
{#if !folded.knowledge}
<ul class="py-0.5">
{#each knowledge as item, index (`${item.type ?? 'file'}:${item.id ?? index}`)}
<li>
<button type="button" class="{groupRow} w-full" on:click={onKnowledge}>
{#if item.type === 'collection'}
<TeamItemIcon
type="knowledge"
item={{ id: item.id, name: item.name ?? '' }}
/>
{:else}
<span class={railIcon}><Icon name="page" size={14} /></span>
{/if}
<span class="min-w-0 truncate">{item.name}</span>
</button>
</li>
{/each}
</ul>
{/if}
</section>
{/if}
</div>
</div>
<!-- Borderless rail, as on the team Overview. -->
<aside class="flex flex-col gap-4">
<!-- Who can open the folder: like the team Overview's members, but a folder is shared
with people, groups, teams or everyone, each able to view or edit. -->
<div>
<div class={railLabel}>{$i18n.t('Shared with')}</div>
<!-- People as one avatar stack with a count, as the team Overview shows members. -->
<div
class="{railPlain} -mx-2 px-2"
title={people.map((entry) => (entry.owner ? `${entry.name} (${$i18n.t('Owner')})` : entry.name)).join(', ')}
>
<span class="flex -space-x-1.5">
{#each people.slice(0, 5) as entry (entry.key)}
<img
class="size-5 rounded-full object-cover ring-2 ring-base-0 dark:ring-base-900"
src={`${WEBUI_API_BASE_URL}/users/${entry.id}/profile/image`}
alt=""
/>
{/each}
</span>
<span class="text-base-500 dark:text-base-400"
>{$i18n.t('{{COUNT}} people', { COUNT: people.length })}</span
>
</div>
{#each sharedWith.filter((entry) => entry.kind !== 'user') as entry (entry.key)}
{#if entry.href}
<a
href={entry.href}
class={railRow}
title={entry.edit ? $i18n.t('Can edit') : $i18n.t('Can view')}
>
{@render sharedEntry(entry)}
</a>
{:else}
<div
class="{railPlain} -mx-2 px-2"
title={entry.owner
? $i18n.t('Owner')
: entry.edit
? $i18n.t('Can edit')
: $i18n.t('Can view')}
>
{@render sharedEntry(entry)}
</div>
{/if}
{/each}
</div>
{#if directory}
<div>
<div class={railLabel}>{$i18n.t('Working Directory')}</div>
{#if onFiles}
<button type="button" class="{railRow} w-full" title={directory} on:click={onFiles}>
<span class={railIcon}><Icon name="folder" size={14} /></span>
<span class="min-w-0 truncate">{directory}</span>
</button>
{:else}
<div class="{railPlain} -mx-2 px-2" title={directory}>
<span class={railIcon}><Icon name="folder" size={14} /></span>
<span class="min-w-0 truncate">{directory}</span>
</div>
{/if}
</div>
{/if}
<div>
<div class={railLabel}>{$i18n.t('Go to')}</div>
<button type="button" class="{railRow} w-full" on:click={onChats}>
<span class={railIcon}><Icon name="chat-bubble" size={14} /></span>
{$i18n.t('Chats')}
</button>
{#if !readOnly}
<button type="button" class="{railRow} w-full" on:click={onEdit}>
<span class={railIcon}><SettingsAlt className="size-3.5" /></span>
{$i18n.t('Edit Folder')}
</button>
{/if}
</div>
{#if subfolders.length}
<div>
<div class={railLabel}>{$i18n.t('Folders')}</div>
{#each subfolders as child (child.id)}
<a href="/folders/{child.id}" class={railRow}>
<span class={railIcon}
><TeamItemIcon
type="folder"
item={{ id: child.id, name: child.name, icon: child.meta?.icon }}
/></span
>
<span class="min-w-0 truncate">{child.name}</span>
</a>
{/each}
</div>
{/if}
</aside>
</div>
</div>
</div>