mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-22 21:50:42 -05:00
refac
This commit is contained in:
1 parent
e4b969f606
commit
06491f0132
38 files changed
+4032
-725
No files matched your search
@@ -21,7 +21,9 @@ from open_webui.models.automations import AutomationRun
|
||||
from open_webui.models.chat_messages import ChatMessage, ChatMessages
|
||||
from open_webui.models.folders import Folders
|
||||
from open_webui.models.tags import Tag, TagModel, Tags
|
||||
from open_webui.tasks import has_active_tasks
|
||||
from open_webui.utils.misc import get_output_text, sanitize_data_for_db, sanitize_text_for_db
|
||||
from open_webui.utils.session_records import has_pending_tool_approval
|
||||
from pydantic import BaseModel, ConfigDict, field_validator
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
@@ -49,6 +51,28 @@ from sqlalchemy.sql.expression import bindparam
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
ACTIVE_CHAT_GAP_SECONDS = 30 * 60
|
||||
# Filter token for chats without a folder status. The status itself is stored and returned as null;
|
||||
# only query strings, which can't carry null, need a name for it.
|
||||
NO_FOLDER_STATUS = 'none'
|
||||
|
||||
|
||||
def _as_seconds(value):
|
||||
# Older rows may hold numbers as strings; chats set before tracking have none.
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def folder_status_since(meta: dict, status: str | None):
|
||||
"""When the chat would have entered `status` had all its time there been one stretch.
|
||||
|
||||
Earlier stretches in the same status count, so moving away and back doesn't reset it.
|
||||
"""
|
||||
started = _as_seconds(meta.get('folder_status_at'))
|
||||
if status is None or started is None:
|
||||
return None
|
||||
return started - (_as_seconds((meta.get('folder_status_durations') or {}).get(status)) or 0)
|
||||
CHAT_SEARCH_FILTER_PREFIXES = ('tag:', 'folder:', 'pinned:', 'archived:', 'shared:')
|
||||
|
||||
|
||||
@@ -2106,6 +2130,7 @@ class ChatTable:
|
||||
folder_ids: list[str],
|
||||
db: AsyncSession | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Count unread or approval-pending chats for folder notification badges."""
|
||||
if not folder_ids:
|
||||
return {}
|
||||
|
||||
@@ -2129,7 +2154,27 @@ class ChatTable:
|
||||
)
|
||||
.group_by(Chat.folder_id)
|
||||
)
|
||||
return {folder_id: count for folder_id, count in result.all() if folder_id}
|
||||
counts = {folder_id: count for folder_id, count in result.all() if folder_id}
|
||||
result = await session.execute(
|
||||
select(Chat.folder_id, Chat.id, ChatMessage.output)
|
||||
.join(ChatMessage, ChatMessage.chat_id == Chat.id)
|
||||
.where(
|
||||
Chat.user_id == user_id,
|
||||
Chat.folder_id.in_(folder_ids),
|
||||
Chat.archived == False,
|
||||
ChatMessage.role == 'assistant',
|
||||
ChatMessage.done.is_(False),
|
||||
)
|
||||
)
|
||||
# Unfinished chats are excluded above; count each approval-pending chat once.
|
||||
pending_chats = {
|
||||
(folder_id, chat_id)
|
||||
for folder_id, chat_id, output in result.all()
|
||||
if has_pending_tool_approval(output)
|
||||
}
|
||||
for folder_id, _ in pending_chats:
|
||||
counts[folder_id] = counts.get(folder_id, 0) + 1
|
||||
return counts
|
||||
|
||||
async def get_chats(self, skip: int = 0, limit: int = 50, db: AsyncSession | None = None) -> list[ChatModel]:
|
||||
async with get_async_db_context(db) as session:
|
||||
@@ -2604,6 +2649,324 @@ class ChatTable:
|
||||
participants[chat_id].append(author_id)
|
||||
return participants
|
||||
|
||||
def _folder_chat_conditions(
|
||||
self,
|
||||
folder_id: str,
|
||||
dialect_name: str,
|
||||
search: str = '',
|
||||
tag_ids: list[str] | None = None,
|
||||
status_ids: list[str] | None = None,
|
||||
valid_status_ids: tuple[str, ...] = (),
|
||||
) -> list:
|
||||
conditions = [
|
||||
Chat.folder_id == folder_id,
|
||||
Chat.archived.is_(False),
|
||||
Chat.meta['internal'].as_boolean().is_not(True),
|
||||
]
|
||||
|
||||
# Same matching as the sidebar search: the phrase, or every term.
|
||||
phrase = chat_search_content_query(search)
|
||||
if phrase:
|
||||
|
||||
def match(key: str, value: str):
|
||||
return or_(
|
||||
Chat.title.ilike(f'%{value}%'),
|
||||
text(chat_search_message_content_match_sql(dialect_name, key)).bindparams(**{key: value}),
|
||||
)
|
||||
|
||||
terms = [term for term in chat_search_terms(phrase) if term != phrase]
|
||||
phrase_match = match('folder_phrase', phrase)
|
||||
conditions.append(
|
||||
or_(phrase_match, and_(*[match(f'folder_term_{i}', term) for i, term in enumerate(terms)]))
|
||||
if terms
|
||||
else phrase_match
|
||||
)
|
||||
|
||||
# 'none' means untagged, as in the sidebar search's tag:none.
|
||||
tag_ids = set(tag_ids or [])
|
||||
if tag_ids:
|
||||
if dialect_name == 'sqlite':
|
||||
tags = "json_each(CASE WHEN json_type(chat.meta, '$.tags') = 'array' THEN json_extract(chat.meta, '$.tags') ELSE '[]' END)"
|
||||
else:
|
||||
tags = "json_array_elements_text(CASE WHEN json_typeof(chat.meta->'tags') = 'array' THEN chat.meta->'tags' ELSE '[]'::json END)"
|
||||
named = sorted(tag_ids - {'none'})
|
||||
matches = [text(f'NOT EXISTS (SELECT 1 FROM {tags} tag)')] if 'none' in tag_ids else []
|
||||
if named:
|
||||
matches.append(
|
||||
text(f'EXISTS (SELECT 1 FROM {tags} tag WHERE tag.value IN :folder_tag_ids)').bindparams(
|
||||
bindparam('folder_tag_ids', named, expanding=True)
|
||||
)
|
||||
)
|
||||
conditions.append(or_(*matches))
|
||||
|
||||
# 'not_started' was the default status's earlier name.
|
||||
status_ids = {NO_FOLDER_STATUS if value == 'not_started' else value for value in status_ids or []}
|
||||
if status_ids:
|
||||
stored = Chat.meta['folder_status'].as_string()
|
||||
named = sorted(status_ids - {NO_FOLDER_STATUS})
|
||||
matches = [stored.in_(named)] if named else []
|
||||
if NO_FOLDER_STATUS in status_ids:
|
||||
# Unknown or deleted statuses read as no status.
|
||||
matches.append(
|
||||
or_(stored.is_(None), stored.not_in(list(valid_status_ids)))
|
||||
)
|
||||
conditions.append(or_(*matches))
|
||||
return conditions
|
||||
|
||||
async def get_folder_chat_page(
|
||||
self,
|
||||
folder_id: str,
|
||||
user_id: str,
|
||||
skip: int = 0,
|
||||
limit: int = 50,
|
||||
search: str = '',
|
||||
tag_ids: list[str] | None = None,
|
||||
status_ids: list[str] | None = None,
|
||||
valid_status_ids: tuple[str, ...] = (),
|
||||
user_ids: list[str] | None = None,
|
||||
activity: str | None = None,
|
||||
updated_at_gte: int | None = None,
|
||||
sort_by: str = 'updated_at',
|
||||
sort_dir: str = 'desc',
|
||||
redis=None,
|
||||
db: AsyncSession | None = None,
|
||||
) -> tuple[list[dict], int]:
|
||||
"""A page of a folder's chats for the list and board views, filtered before paging."""
|
||||
async with get_async_db_context(db) as session:
|
||||
dialect_name = (await session.connection()).dialect.name
|
||||
conditions = self._folder_chat_conditions(
|
||||
folder_id, dialect_name, search, tag_ids, status_ids, valid_status_ids
|
||||
)
|
||||
|
||||
if user_ids:
|
||||
# Participants come from message history, so match them over this folder's chats.
|
||||
wanted = set(user_ids)
|
||||
rows = (await session.execute(select(Chat.id, Chat.user_id).where(*conditions))).all()
|
||||
authors = await self.get_participant_ids_by_chat_ids([row[0] for row in rows], db=session)
|
||||
conditions.append(
|
||||
Chat.id.in_(
|
||||
[
|
||||
chat_id
|
||||
for chat_id, owner in rows
|
||||
if owner in wanted or wanted.intersection(authors.get(chat_id, ()))
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
if updated_at_gte is not None:
|
||||
conditions.append(Chat.updated_at >= updated_at_gte)
|
||||
|
||||
if activity:
|
||||
# Same precedence as the sidebar markers: approval > generating > unread.
|
||||
unfinished = (
|
||||
await session.execute(
|
||||
select(ChatMessage.chat_id, ChatMessage.output)
|
||||
.join(Chat, Chat.id == ChatMessage.chat_id)
|
||||
.where(*conditions, ChatMessage.role == 'assistant', ChatMessage.done.is_(False))
|
||||
)
|
||||
).all()
|
||||
pending_ids = {chat_id for chat_id, output in unfinished if has_pending_tool_approval(output)}
|
||||
if activity == 'waiting_for_approval':
|
||||
conditions.append(Chat.id.in_(pending_ids))
|
||||
else:
|
||||
active_ids = {
|
||||
chat_id for chat_id in {row[0] for row in unfinished} if await has_active_tasks(redis, chat_id)
|
||||
}
|
||||
if activity == 'generating':
|
||||
conditions.append(Chat.id.in_(active_ids - pending_ids))
|
||||
elif activity == 'unread':
|
||||
conditions.extend(
|
||||
[
|
||||
Chat.user_id == user_id,
|
||||
or_(
|
||||
Chat.last_read_at.is_(None),
|
||||
Chat.last_read_at == 0,
|
||||
Chat.updated_at > Chat.last_read_at,
|
||||
),
|
||||
Chat.id.not_in(active_ids | pending_ids),
|
||||
]
|
||||
)
|
||||
elif activity == 'idle':
|
||||
# Everything the other three leave out.
|
||||
conditions.extend(
|
||||
[
|
||||
Chat.id.not_in(active_ids | pending_ids),
|
||||
or_(
|
||||
Chat.user_id != user_id,
|
||||
and_(
|
||||
Chat.last_read_at.is_not(None),
|
||||
Chat.last_read_at != 0,
|
||||
Chat.updated_at <= Chat.last_read_at,
|
||||
),
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
total = (await session.execute(select(func.count(Chat.id)).where(*conditions))).scalar_one()
|
||||
rows = (
|
||||
(
|
||||
await session.execute(
|
||||
select(
|
||||
Chat.id,
|
||||
Chat.title,
|
||||
Chat.user_id,
|
||||
Chat.updated_at,
|
||||
Chat.created_at,
|
||||
Chat.last_read_at,
|
||||
Chat.meta,
|
||||
)
|
||||
.where(*conditions)
|
||||
.order_by(*chat_list_order(sort_by, sort_dir, user_id))
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.all()
|
||||
)
|
||||
|
||||
tag_ids = {tag_id for row in rows for tag_id in (row['meta'] or {}).get('tags', [])}
|
||||
owners = {row['user_id'] for row in rows}
|
||||
labels = (
|
||||
{
|
||||
(tag.user_id, tag.id): tag
|
||||
for tag in (
|
||||
await session.execute(select(Tag).where(Tag.user_id.in_(owners), Tag.id.in_(tag_ids)))
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
}
|
||||
if tag_ids
|
||||
else {}
|
||||
)
|
||||
|
||||
bodies = {}
|
||||
if chat_search_content_query(search) and rows:
|
||||
bodies = dict(
|
||||
(
|
||||
await session.execute(
|
||||
select(Chat.id, Chat.chat).where(Chat.id.in_([row['id'] for row in rows]))
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
terms = chat_search_content_query(search).split()
|
||||
chats = []
|
||||
for row in rows:
|
||||
chat = dict(row)
|
||||
meta = chat.pop('meta') or {}
|
||||
chat['tags'] = []
|
||||
for tag_id in dict.fromkeys(meta.get('tags', [])):
|
||||
tag = labels.get((chat['user_id'], tag_id))
|
||||
chat['tags'].append(
|
||||
{
|
||||
'id': tag_id,
|
||||
'name': tag.name if tag else tag_id.replace('_', ' '),
|
||||
# The palette and default color live in the frontend.
|
||||
'color': (tag.meta or {}).get('color') if tag else None,
|
||||
}
|
||||
)
|
||||
status = meta.get('folder_status')
|
||||
chat['status'] = status if status in valid_status_ids else None
|
||||
chat['status_since'] = folder_status_since(meta, chat['status'])
|
||||
# For the time-in-status tooltip: when the current stretch began, and earlier
|
||||
# time per status (statuses the folder no longer has are left out).
|
||||
chat['status_entered_at'] = (
|
||||
_as_seconds(meta.get('folder_status_at')) if chat['status'] else None
|
||||
)
|
||||
chat['status_durations'] = {
|
||||
key: seconds
|
||||
for key, value in (meta.get('folder_status_durations') or {}).items()
|
||||
if key in valid_status_ids and (seconds := _as_seconds(value))
|
||||
}
|
||||
chat['can_edit_tags'] = chat['can_edit_status'] = chat['user_id'] == user_id
|
||||
# Only explain matches the title doesn't already show.
|
||||
chat['search_snippet'] = (
|
||||
chat_search_snippet(bodies.get(chat['id']) or {}, search)
|
||||
if terms and not all(term in chat['title'].lower() for term in terms)
|
||||
else None
|
||||
)
|
||||
chats.append(chat)
|
||||
return chats, total
|
||||
|
||||
async def get_participant_counts_by_folder_id(
|
||||
self, folder_id: str, db: AsyncSession | None = None
|
||||
) -> dict[str, int]:
|
||||
"""How many of a folder's chats each person owns or wrote in."""
|
||||
async with get_async_db_context(db) as session:
|
||||
dialect_name = (await session.connection()).dialect.name
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(Chat.id, Chat.user_id).where(*self._folder_chat_conditions(folder_id, dialect_name))
|
||||
)
|
||||
).all()
|
||||
authors = await self.get_participant_ids_by_chat_ids([row[0] for row in rows], db=session)
|
||||
counts: dict[str, int] = {}
|
||||
for chat_id, owner in rows:
|
||||
for participant_id in {owner, *authors.get(chat_id, ())}:
|
||||
counts[participant_id] = counts.get(participant_id, 0) + 1
|
||||
return counts
|
||||
|
||||
async def get_tag_counts_by_folder_id(self, folder_id: str, db: AsyncSession | None = None) -> list[dict]:
|
||||
"""Tags used in a folder with chat counts, aggregated in SQL without loading chats."""
|
||||
async with get_async_db_context(db) as session:
|
||||
dialect_name = (await session.connection()).dialect.name
|
||||
if dialect_name == 'sqlite':
|
||||
source = "json_each(chat.meta, '$.tags')"
|
||||
internal = "COALESCE(json_extract(chat.meta, '$.internal'), 0) != 1"
|
||||
else:
|
||||
source = "json_array_elements_text(chat.meta->'tags')"
|
||||
internal = "COALESCE((chat.meta->>'internal')::boolean, false) = false"
|
||||
query = text(f"""
|
||||
SELECT tag.value AS id, MIN(COALESCE(label.name, tag.value)) AS name,
|
||||
COUNT(DISTINCT chat.id) AS count
|
||||
FROM chat CROSS JOIN {source} tag
|
||||
LEFT JOIN tag label ON label.id = tag.value AND label.user_id = chat.user_id
|
||||
WHERE chat.folder_id = :folder_id AND chat.archived = false AND {internal}
|
||||
GROUP BY tag.value ORDER BY name
|
||||
""")
|
||||
result = await session.execute(query, {'folder_id': folder_id})
|
||||
return [dict(row) for row in result.mappings()]
|
||||
|
||||
async def update_chat_folder_status_by_id_and_user_id(
|
||||
self, id: str, folder_id: str, user_id: str, status: str | None, db: AsyncSession | None = None
|
||||
) -> bool:
|
||||
"""Set (or with None, clear) a chat's folder status, banking the time spent in its previous one.
|
||||
|
||||
Time adds up per status, so moving away and coming back doesn't reset it.
|
||||
"""
|
||||
async with get_async_db_context(db) as session:
|
||||
row = (
|
||||
await session.execute(
|
||||
select(Chat.meta).filter_by(id=id, folder_id=folder_id, user_id=user_id)
|
||||
)
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
return False
|
||||
meta = dict(row[0] or {})
|
||||
previous = meta.get('folder_status')
|
||||
if previous == status:
|
||||
return True # Same status: keep its clock running.
|
||||
now = int(time.time())
|
||||
started = _as_seconds(meta.get('folder_status_at'))
|
||||
durations = dict(meta.get('folder_status_durations') or {})
|
||||
if previous and previous != 'none' and started is not None: # 'none' was stored by older builds
|
||||
durations[previous] = (_as_seconds(durations.get(previous)) or 0) + max(0, now - started)
|
||||
await session.execute(
|
||||
update(Chat)
|
||||
.filter_by(id=id)
|
||||
.values(
|
||||
meta={
|
||||
# No status means no stored status, like chats that never had one.
|
||||
**{key: value for key, value in meta.items() if key not in ('folder_status', 'folder_status_at')},
|
||||
**({'folder_status': status, 'folder_status_at': now} if status is not None else {}),
|
||||
'folder_status_durations': durations,
|
||||
}
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
async def count_all_chats_by_folder_id(
|
||||
self,
|
||||
folder_id: str,
|
||||
|
||||
@@ -79,6 +79,21 @@ class SharedFolderResponse(BaseModel):
|
||||
# Forms
|
||||
|
||||
|
||||
def folder_status_ids(meta: dict | None) -> tuple[str, ...]:
|
||||
"""The statuses this folder defines in meta.statuses, in order. Chats may also have none (null)."""
|
||||
ids: list[str] = []
|
||||
for item in (meta or {}).get('statuses') or []:
|
||||
if (
|
||||
isinstance(item, dict)
|
||||
and isinstance(item.get('id'), str)
|
||||
and 0 < len(item['id']) <= 64
|
||||
and item['id'] != 'none'
|
||||
and item['id'] not in ids
|
||||
):
|
||||
ids.append(item['id'])
|
||||
return tuple(ids)
|
||||
|
||||
|
||||
class FolderForm(BaseModel):
|
||||
name: str
|
||||
data: Optional[dict] = None
|
||||
|
||||
@@ -9,12 +9,11 @@ import uuid
|
||||
# local imports
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import JSON, BigInteger, Column, Index, PrimaryKeyConstraint, String, delete, select
|
||||
from sqlalchemy import JSON, BigInteger, Column, Index, PrimaryKeyConstraint, String, delete, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Tag(Base): # database table mapping for tag entity
|
||||
__tablename__ = 'tag'
|
||||
id = Column(String)
|
||||
@@ -91,6 +90,18 @@ class TagTable:
|
||||
result = await db.execute(select(Tag).filter(Tag.id.in_(ids), Tag.user_id == user_id))
|
||||
return [TagModel.model_validate(tag) for tag in result.scalars().all()]
|
||||
|
||||
async def update_tag_color_by_name_and_user_id(
|
||||
self, name: str, user_id: str, color: str, db: AsyncSession | None = None
|
||||
) -> bool:
|
||||
async with get_async_db_context(db) as db:
|
||||
id = name.replace(' ', '_').lower()
|
||||
meta = (await db.execute(select(Tag.meta).filter_by(id=id, user_id=user_id))).one_or_none()
|
||||
if meta is None:
|
||||
return False
|
||||
await db.execute(update(Tag).filter_by(id=id, user_id=user_id).values(meta={**(meta[0] or {}), 'color': color}))
|
||||
await db.commit()
|
||||
return True
|
||||
|
||||
async def delete_tag_by_name_and_user_id(self, name: str, user_id: str, db: AsyncSession | None = None) -> bool:
|
||||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
|
||||
@@ -2454,3 +2454,22 @@ async def delete_tag_by_id_and_tag_name(
|
||||
return await Tags.get_tags_by_ids_and_user_id(tags, user.id, db=db)
|
||||
else:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
|
||||
class TagColorForm(BaseModel):
|
||||
name: str
|
||||
# A palette name chosen by the frontend, e.g. 'blue'; the server only stores it.
|
||||
color: str = Field(min_length=1, max_length=32, pattern=r'^[a-z][a-z0-9-]*$')
|
||||
|
||||
|
||||
@router.patch('/{id}/tags', response_model=list[TagModel])
|
||||
async def update_chat_tag_color(request: Request, id: str, form_data: TagColorForm,
|
||||
user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
tag_id = form_data.name.replace(' ', '_').lower()
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db)
|
||||
if not chat or tag_id not in (chat.meta or {}).get('tags', []):
|
||||
raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
if not await Tags.update_tag_color_by_name_and_user_id(form_data.name, user.id, form_data.color, db=db):
|
||||
raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
await publish_event(request, EVENTS.CHAT_UPDATED, actor=user, subject_id=id, data={'tag': form_data.name})
|
||||
return await Tags.get_tags_by_ids_and_user_id((chat.meta or {}).get('tags', []), user.id, db=db)
|
||||
@@ -4,7 +4,7 @@ import os
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
@@ -23,6 +23,7 @@ from open_webui.models.folders import (
|
||||
FolderNameIdResponse,
|
||||
Folders,
|
||||
FolderUpdateForm,
|
||||
folder_status_ids,
|
||||
)
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.shared_chats import ChatShareMode
|
||||
@@ -34,7 +35,7 @@ from open_webui.utils.access_control import (
|
||||
)
|
||||
from open_webui.utils.access_control.files import can_read_all_folder_files, get_accessible_folder_files
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -42,6 +43,10 @@ log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Folder list and board views page through a folder's chats this many at a time.
|
||||
FOLDER_PAGE_SIZE = 50
|
||||
FolderActivity = Literal['unread', 'generating', 'waiting_for_approval', 'idle']
|
||||
|
||||
|
||||
from open_webui.utils.access_control.folders import has_folder_access as _has_folder_access
|
||||
|
||||
@@ -578,6 +583,14 @@ async def get_shared_folder_chats(
|
||||
page: int | None = Query(None, ge=1),
|
||||
sort_by: str = Query('unread_updated_at'),
|
||||
sort_dir: str = Query('desc'),
|
||||
workspace: bool = False,
|
||||
search: str = Query('', max_length=256),
|
||||
tag_ids: list[str] = Query(default=[]),
|
||||
user_ids: list[str] = Query(default=[]),
|
||||
# `status` is taken by fastapi's status module here, hence the alias.
|
||||
status_filter: list[str] = Query(default=[], alias='status'),
|
||||
activity: FolderActivity | None = None,
|
||||
updated_at_gte: int | None = Query(None, ge=0),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
@@ -601,19 +614,45 @@ async def get_shared_folder_chats(
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
limit = 10
|
||||
limit = FOLDER_PAGE_SIZE if workspace else 10
|
||||
skip = (page - 1) * limit if page is not None else 0
|
||||
chats = await Chats.get_all_chats_by_folder_id(
|
||||
id,
|
||||
skip=skip,
|
||||
limit=limit if page is not None else 60,
|
||||
sort_by=sort_by,
|
||||
sort_dir=sort_dir,
|
||||
unread_for_user_id=user.id,
|
||||
db=db,
|
||||
)
|
||||
total = await Chats.count_all_chats_by_folder_id(id, db=db) if page is not None else len(chats)
|
||||
|
||||
if workspace:
|
||||
if sort_by not in ('title', 'updated_at', 'unread_updated_at') or sort_dir not in ('asc', 'desc'):
|
||||
raise HTTPException(status_code=422, detail='Invalid sort')
|
||||
if len(tag_ids) > 50 or len(user_ids) > 50:
|
||||
raise HTTPException(status_code=422, detail='Too many filters')
|
||||
statuses = folder_status_ids(folder.meta)
|
||||
# 'none' (or the older 'not_started') filters for chats without a status.
|
||||
if any(value not in (*statuses, 'none', 'not_started') for value in status_filter):
|
||||
raise HTTPException(status_code=422, detail='Invalid status')
|
||||
chats, total = await Chats.get_folder_chat_page(
|
||||
id,
|
||||
user.id,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
search=search.strip(),
|
||||
tag_ids=tag_ids,
|
||||
status_ids=status_filter,
|
||||
valid_status_ids=statuses,
|
||||
user_ids=user_ids,
|
||||
activity=activity,
|
||||
updated_at_gte=updated_at_gte,
|
||||
sort_by=sort_by,
|
||||
sort_dir=sort_dir,
|
||||
redis=request.app.state.redis,
|
||||
db=db,
|
||||
)
|
||||
else:
|
||||
chats = await Chats.get_all_chats_by_folder_id(
|
||||
id,
|
||||
skip=skip,
|
||||
limit=limit if page is not None else 60,
|
||||
sort_by=sort_by,
|
||||
sort_dir=sort_dir,
|
||||
unread_for_user_id=user.id,
|
||||
db=db,
|
||||
)
|
||||
total = await Chats.count_all_chats_by_folder_id(id, db=db) if page is not None else len(chats)
|
||||
participant_ids = await Chats.get_participant_ids_by_chat_ids([chat['id'] for chat in chats], db=db)
|
||||
user_ids = {chat['user_id'] for chat in chats}
|
||||
user_ids.update(uid for ids in participant_ids.values() for uid in ids)
|
||||
@@ -686,6 +725,59 @@ async def mark_folder_chats_read_by_id(
|
||||
}
|
||||
|
||||
|
||||
async def check_folder_read_access(request: Request, id: str, user, db: AsyncSession) -> FolderModel:
|
||||
"""Return the folder if the user may read it (owner, admin or shared), else raise."""
|
||||
await check_folders_permission(request, user, db=db)
|
||||
folder = await Folders.get_folder_by_id(id, db=db)
|
||||
if not folder:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
if user.role != 'admin' and folder.user_id != user.id and not await _has_folder_access(user.id, folder, 'read', db):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
return folder
|
||||
|
||||
|
||||
@router.get('/{id}/users')
|
||||
async def get_folder_users(request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
await check_folder_read_access(request, id, user, db)
|
||||
counts = await Chats.get_participant_counts_by_folder_id(id, db=db)
|
||||
users = await Users.get_users_by_user_ids(list(counts), db=db) if counts else []
|
||||
names = {u.id: u.name for u in users}
|
||||
return sorted(
|
||||
[{'id': user_id, 'name': names.get(user_id) or 'Unknown', 'count': count} for user_id, count in counts.items()],
|
||||
key=lambda entry: (entry['id'] != user.id, entry['name'].casefold()),
|
||||
)
|
||||
|
||||
|
||||
@router.get('/{id}/tags')
|
||||
async def get_folder_tags(request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
await check_folder_read_access(request, id, user, db)
|
||||
return await Chats.get_tag_counts_by_folder_id(id, db=db)
|
||||
|
||||
|
||||
class FolderChatStatusForm(BaseModel):
|
||||
# null clears the status.
|
||||
status: str | None = Field(default=None, min_length=1, max_length=64)
|
||||
|
||||
|
||||
@router.patch('/{id}/chats/{chat_id}/status')
|
||||
async def update_folder_chat_status(request: Request, id: str, chat_id: str, form_data: FolderChatStatusForm,
|
||||
user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
folder = await check_folder_read_access(request, id, user, db)
|
||||
if form_data.status is not None and form_data.status not in folder_status_ids(folder.meta):
|
||||
raise HTTPException(status_code=422, detail='Invalid status')
|
||||
if not await Chats.update_chat_folder_status_by_id_and_user_id(chat_id, id, user.id, form_data.status, db=db):
|
||||
raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
await publish_event(request, EVENTS.CHAT_UPDATED, actor=user, subject_id=chat_id,
|
||||
data={'folder_id': id, 'folder_status': form_data.status})
|
||||
return {'id': chat_id, 'status': form_data.status}
|
||||
|
||||
|
||||
# Delete Folder By Id
|
||||
|
||||
|
||||
|
||||
@@ -1591,7 +1591,11 @@ async def get_event_emitter(request_info, update_db=True):
|
||||
pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat_id])
|
||||
event_data = {
|
||||
**event_data,
|
||||
'data': {**(event_data.get('data') or {}), 'pending_approval': chat_id in pending_approval_ids},
|
||||
'data': {
|
||||
**(event_data.get('data') or {}),
|
||||
'pending_approval': chat_id in pending_approval_ids,
|
||||
**({'folder_unread_counts': await get_folder_unread_counts(user_id)} if not internal else {}),
|
||||
},
|
||||
}
|
||||
|
||||
room = f'user:{user_id}'
|
||||
|
||||
@@ -1561,6 +1561,44 @@ export const addTagById = async (token: string, id: string, tagName: string) =>
|
||||
return res;
|
||||
};
|
||||
|
||||
export const updateTagColorById = async (
|
||||
token: string,
|
||||
id: string,
|
||||
tagName: string,
|
||||
color: string
|
||||
) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/tags`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { authorization: `Bearer ${token}` })
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: tagName,
|
||||
color
|
||||
})
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
error = getErrorDetail(err);
|
||||
|
||||
console.error(err);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const deleteTagById = async (token: string, id: string, tagName: string) => {
|
||||
let error = null;
|
||||
|
||||
|
||||
@@ -334,10 +334,8 @@ export type ChatParticipant = {
|
||||
export const getSharedFolderChats = async (
|
||||
token: string,
|
||||
folderId: string,
|
||||
params: {
|
||||
params: Omit<import('$lib/stores/folderStates').FolderChatQuery, 'page'> & {
|
||||
page?: number | null;
|
||||
sortBy?: 'title' | 'updated_at' | 'unread_updated_at';
|
||||
sortDir?: 'asc' | 'desc';
|
||||
} = {}
|
||||
) => {
|
||||
let error = null;
|
||||
@@ -352,6 +350,14 @@ export const getSharedFolderChats = async (
|
||||
if (params.sortDir) {
|
||||
searchParams.append('sort_dir', params.sortDir);
|
||||
}
|
||||
if (params.workspace) searchParams.set('workspace', 'true');
|
||||
if (params.search?.trim()) searchParams.set('search', params.search.trim());
|
||||
for (const tag of params.tagIds ?? []) searchParams.append('tag_ids', tag);
|
||||
for (const id of params.userIds ?? []) searchParams.append('user_ids', id);
|
||||
for (const status of [params.status ?? []].flat()) searchParams.append('status', status);
|
||||
if (params.activity) searchParams.set('activity', params.activity);
|
||||
if (params.updatedAtGte !== undefined)
|
||||
searchParams.set('updated_at_gte', String(params.updatedAtGte));
|
||||
const query = searchParams.toString();
|
||||
|
||||
const res = await fetch(
|
||||
@@ -383,3 +389,100 @@ export const getSharedFolderChats = async (
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const getFolderUsers = async (token: string, id: string, signal?: AbortSignal) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/folders/${encodeURIComponent(id)}/users`, {
|
||||
signal,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
authorization: `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
if (signal?.aborted) return null;
|
||||
error = err.detail;
|
||||
console.error(err);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const getFolderTags = async (token: string, id: string, signal?: AbortSignal) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/folders/${encodeURIComponent(id)}/tags`, {
|
||||
signal,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
authorization: `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
if (signal?.aborted) return null;
|
||||
error = err.detail;
|
||||
console.error(err);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const updateFolderChatStatus = async (
|
||||
token: string,
|
||||
folderId: string,
|
||||
chatId: string,
|
||||
status: string | null
|
||||
) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(
|
||||
`${WEBUI_API_BASE_URL}/folders/${encodeURIComponent(folderId)}/chats/${encodeURIComponent(chatId)}/status`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ status })
|
||||
}
|
||||
)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
error = err.detail;
|
||||
console.error(err);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
@@ -4218,6 +4218,8 @@
|
||||
let mainChatGroupId = '';
|
||||
let tabTitleEditor: import('svelte').Snippet | undefined;
|
||||
let tabActions: import('svelte').Snippet | undefined;
|
||||
let folderTabActions: import('svelte').Snippet | undefined;
|
||||
|
||||
let tabBarActions: import('svelte').Snippet | undefined;
|
||||
|
||||
let initializedTerminalChatId: string | null = null;
|
||||
@@ -5786,7 +5788,7 @@
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
<div id="chat-pane" class="flex flex-col flex-auto z-10 w-full @container overflow-auto">
|
||||
<div id="chat-pane" class="flex min-h-0 flex-col flex-auto z-10 w-full @container overflow-auto">
|
||||
<div class="sr-only" aria-live="polite" aria-atomic="true">{liveStatus}</div>
|
||||
{#if (!side && $settings?.landingPageMode === 'chat' && !$selectedFolder) || (!contextOnly && createMessagesList(history, history.currentId).length > 0)}
|
||||
<div
|
||||
@@ -6059,8 +6061,9 @@
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex items-center h-full">
|
||||
<div class="flex h-full {$selectedFolder ? 'min-h-0 flex-1 overflow-hidden' : 'items-center'}">
|
||||
<Placeholder
|
||||
bind:folderTabActions
|
||||
{selectedTerminalId}
|
||||
{terminalSkills}
|
||||
chatId={$chatId}
|
||||
@@ -6134,8 +6137,9 @@
|
||||
bind:mainChatStyle
|
||||
bind:mainChatGroupId
|
||||
title={$chatTitle || $i18n.t('New Chat')}
|
||||
mainTabFolder={!$chatId && $selectedFolder ? { id: $selectedFolder.id, name: $selectedFolder.name, icon: $selectedFolder.meta?.icon } : null}
|
||||
tabTitleEditor={loading ? undefined : tabTitleEditor}
|
||||
tabActions={loading ? undefined : tabActions}
|
||||
tabActions={loading ? undefined : !$chatId && $selectedFolder ? folderTabActions : tabActions}
|
||||
tabBarActions={loading ? undefined : tabBarActions}
|
||||
{terminalContext}
|
||||
bind:history
|
||||
|
||||
@@ -1987,7 +1987,7 @@
|
||||
<div class="w-full">
|
||||
<div class=" mx-auto inset-x-0 bg-transparent flex justify-center">
|
||||
<div
|
||||
class="flex flex-col px-3 {($settings?.widescreenMode ?? null)
|
||||
class="flex flex-col px-3 {$settings?.widescreenMode ?? null
|
||||
? 'max-w-full'
|
||||
: 'max-w-[58rem]'} w-full"
|
||||
>
|
||||
@@ -2040,7 +2040,7 @@
|
||||
|
||||
<div class="bg-transparent">
|
||||
<div
|
||||
class="{($settings?.widescreenMode ?? null)
|
||||
class="{$settings?.widescreenMode ?? null
|
||||
? 'max-w-full'
|
||||
: 'max-w-[58rem]'} px-2 mx-auto inset-x-0"
|
||||
>
|
||||
@@ -2235,8 +2235,8 @@
|
||||
id={inputId === 'chat-input' ? 'message-input-container' : `${inputId}-wrapper`}
|
||||
data-composer-id={inputId}
|
||||
class="flex-1 flex flex-col relative w-full shadow-[0_6px_24px_-4px_rgba(0,0,0,0.1)] rounded-3xl border {isTemporary
|
||||
? 'border-dashed border-gray-200 dark:border-gray-800'
|
||||
: ' border-gray-200 dark:border-gray-800'} {($settings?.highContrastMode ??
|
||||
? 'border-dashed border-gray-200 dark:border-gray-850'
|
||||
: ' border-gray-200 dark:border-gray-850'} {($settings?.highContrastMode ??
|
||||
false)
|
||||
? 'focus-within:outline focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-blue-500 [&_.ProseMirror:focus-visible]:outline-none!'
|
||||
: ''} transition px-0.5 bg-white/5 dark:bg-gray-500/5 backdrop-blur-sm dark:text-gray-100"
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
import Markdown from './Markdown.svelte';
|
||||
import StructuredOutputRenderer from './StructuredOutputRenderer.svelte';
|
||||
import { getOutputText } from './structuredOutput';
|
||||
import FloatingButtons from '../ContentRenderer/FloatingButtons.svelte';
|
||||
import { createMessagesList, replaceOutsideCode } from '$lib/utils';
|
||||
|
||||
@@ -146,7 +147,12 @@
|
||||
)
|
||||
: messageContent;
|
||||
|
||||
let autoOpenedArtifactIds = new Set();
|
||||
const initialContent = content;
|
||||
const initialOutputText = getOutputText(output);
|
||||
// The final code fence can render after the response is marked done.
|
||||
let hasStreamed = !done;
|
||||
$: if (!done) hasStreamed = true;
|
||||
const seenArtifactIds = new Set();
|
||||
/** @type {ReturnType<typeof selectedComment>} */
|
||||
let commentSelection = null;
|
||||
|
||||
@@ -163,17 +169,18 @@
|
||||
['html', 'svg'].includes(normalizedLang) ||
|
||||
(normalizedLang === 'xml' && code.toLowerCase().includes('<svg'));
|
||||
const artifactId = codeBlockId || `${normalizedLang}:${raw}`;
|
||||
if (!isArtifact || !hasClosingCodeFence(raw) || seenArtifactIds.has(artifactId)) return;
|
||||
// Restored blocks are seen too, so continuing a response cannot reopen them.
|
||||
seenArtifactIds.add(artifactId);
|
||||
|
||||
if (
|
||||
onOpenArtifacts &&
|
||||
hasStreamed &&
|
||||
(content !== initialContent || getOutputText(output) !== initialOutputText) &&
|
||||
($settings?.detectArtifacts ?? true) &&
|
||||
!compactPreview &&
|
||||
isArtifact &&
|
||||
hasClosingCodeFence(raw) &&
|
||||
!autoOpenedArtifactIds.has(artifactId) &&
|
||||
!$mobile
|
||||
) {
|
||||
autoOpenedArtifactIds.add(artifactId);
|
||||
await tick();
|
||||
onOpenArtifacts();
|
||||
}
|
||||
|
||||
@@ -888,7 +888,8 @@
|
||||
class="w-full flex flex-col relative {edit ? 'hidden' : ''}"
|
||||
id="response-content-container"
|
||||
>
|
||||
{#if hasResponseContent && message.error !== true}
|
||||
{#if message.error !== true}
|
||||
<!-- Mount before the first chunk so artifact detection can recognize new content. -->
|
||||
<!-- always show message contents even if there's an error -->
|
||||
<!-- unless message.error === true which is legacy error handling, where the error message is stored in message.content -->
|
||||
<ContentRenderer
|
||||
@@ -896,7 +897,7 @@
|
||||
{chatId}
|
||||
{onOpenArtifacts}
|
||||
messageId={message.id}
|
||||
content={message.content}
|
||||
content={message.content ?? ''}
|
||||
output={message.output}
|
||||
sources={message.sources}
|
||||
floatingButtons={message?.done &&
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
chatTitle as _chatTitle,
|
||||
config,
|
||||
mobile,
|
||||
selectedFolder,
|
||||
selectedTerminalId,
|
||||
settings,
|
||||
showSidebar,
|
||||
@@ -327,7 +328,9 @@
|
||||
<nav
|
||||
class="sticky top-0 z-30 w-full {$mobile ? 'pt-1.5' : ''} {tabbed
|
||||
? 'pb-0.5'
|
||||
: 'pb-1 -mb-12'} flex flex-col items-center drag-region"
|
||||
: $selectedFolder && !history.currentId
|
||||
? 'shrink-0 pb-1'
|
||||
: 'pb-1 -mb-12'} flex flex-col items-center drag-region"
|
||||
>
|
||||
<div class:hidden={tabbed} class="flex items-center w-full {$mobile ? 'px-1.5' : 'pl-1.5 pr-1'}">
|
||||
<div
|
||||
@@ -429,7 +432,7 @@
|
||||
{/if}
|
||||
|
||||
<div class="absolute top-full left-0 right-0 h-fit">
|
||||
{#if !history.currentId && !$chatId && ($banners.length > 0 || ($config?.license_metadata?.type ?? null) === 'trial' || (($config?.license_metadata?.seats ?? null) !== null && $config?.user_count > $config?.license_metadata?.seats))}
|
||||
{#if !$selectedFolder && !history.currentId && !$chatId && ($banners.length > 0 || ($config?.license_metadata?.type ?? null) === 'trial' || (($config?.license_metadata?.seats ?? null) !== null && $config?.user_count > $config?.license_metadata?.seats))}
|
||||
<div class=" w-full z-30">
|
||||
<div
|
||||
class=" flex flex-col gap-1 w-full max-h-28 overflow-y-auto overscroll-contain md:max-h-none md:overflow-visible"
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
temporaryChatEnabled,
|
||||
selectedFolder
|
||||
} from '$lib/stores';
|
||||
import { refreshChatList, refreshFolderChatLists } from '$lib/stores/chatList';
|
||||
import { sanitizeResponseContent, extractCurlyBraceWords } from '$lib/utils';
|
||||
import {
|
||||
resolveLocalizedModelDescription,
|
||||
@@ -34,7 +33,6 @@
|
||||
import EyeSlash from '$lib/components/icons/EyeSlash.svelte';
|
||||
import MessageInput from './MessageInput.svelte';
|
||||
import FolderPlaceholder from './Placeholder/FolderPlaceholder.svelte';
|
||||
import FolderTitle from './Placeholder/FolderTitle.svelte';
|
||||
|
||||
const i18n: any = getContext('i18n');
|
||||
|
||||
@@ -54,6 +52,7 @@
|
||||
|
||||
export let history;
|
||||
export let chatId = '';
|
||||
export let folderTabActions: import('svelte').Snippet | undefined = undefined;
|
||||
|
||||
export let prompt = '';
|
||||
export let files = [];
|
||||
@@ -96,6 +95,9 @@
|
||||
|
||||
export let dragged = false;
|
||||
|
||||
// Height of the floating folder composer, so lists can scroll clear of it.
|
||||
let composerHeight = 0;
|
||||
|
||||
let models = [];
|
||||
export let selectedModelIdx = 0;
|
||||
let selectedModel;
|
||||
@@ -122,11 +124,66 @@
|
||||
// True when viewing a shared folder the current user doesn't own AND lacks write access
|
||||
$: folderReadOnly =
|
||||
$selectedFolder != null &&
|
||||
$user?.role !== 'admin' &&
|
||||
$selectedFolder.user_id !== $user?.id &&
|
||||
!$selectedFolder.write_access;
|
||||
</script>
|
||||
|
||||
<div class="m-auto w-full max-w-[58rem] px-1 md:@3xl:px-20 translate-y-6 py-24 text-center">
|
||||
{#snippet composer(placeholder = '')}
|
||||
<MessageInput
|
||||
{selectedTerminalId}
|
||||
{terminalSkills}
|
||||
{chatId}
|
||||
bind:terminalContext
|
||||
{callActive}
|
||||
{callEnabled}
|
||||
bind:this={messageInput}
|
||||
{history}
|
||||
bind:selectedModels
|
||||
{onModelSelect}
|
||||
bind:chatFiles
|
||||
bind:params
|
||||
{onParamChange}
|
||||
bind:files
|
||||
bind:prompt
|
||||
bind:autoScroll
|
||||
bind:selectedToolIds
|
||||
bind:selectedSkillIds
|
||||
bind:selectedFilterIds
|
||||
bind:imageGenerationEnabled
|
||||
bind:codeInterpreterEnabled
|
||||
bind:webSearchEnabled
|
||||
bind:atSelectedModel
|
||||
bind:showCommands
|
||||
bind:dragged
|
||||
{pendingOAuthTools}
|
||||
{oauthRedirectHandler}
|
||||
{toolApprovalMode}
|
||||
{onToolApprovalModeChange}
|
||||
{stopResponse}
|
||||
{createMessagePair}
|
||||
{placeholder}
|
||||
{onChange}
|
||||
{onUpload}
|
||||
{onUpdate}
|
||||
{messageQueue}
|
||||
{onQueueSendNow}
|
||||
{onQueueEdit}
|
||||
{onQueueDelete}
|
||||
{askUser}
|
||||
{onWebSearchToggle}
|
||||
on:chatVariables
|
||||
on:submit={(e) => {
|
||||
dispatch('submit', e.detail);
|
||||
}}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
<div
|
||||
class="w-full {$selectedFolder
|
||||
? 'flex h-full min-h-0 flex-col overflow-hidden'
|
||||
: 'm-auto max-w-[58rem] px-1 md:@3xl:px-20 translate-y-6 py-24'} text-center"
|
||||
>
|
||||
{#if $temporaryChatEnabled}
|
||||
<Tooltip
|
||||
content={$i18n.t("This chat won't appear in history and your messages will not be saved.")}
|
||||
@@ -139,22 +196,37 @@
|
||||
</Tooltip>
|
||||
{/if}
|
||||
|
||||
<div class="w-full text-3xl text-gray-800 dark:text-gray-100 text-center flex items-center gap-4">
|
||||
<div class="w-full flex flex-col justify-center items-center">
|
||||
{#if $selectedFolder}
|
||||
<FolderTitle
|
||||
folder={$selectedFolder}
|
||||
readOnly={folderReadOnly}
|
||||
onUpdate={async () => {
|
||||
await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]);
|
||||
}}
|
||||
onDelete={async (deletedFolder: { id: string }) => {
|
||||
await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]);
|
||||
{#if $selectedFolder}
|
||||
<div
|
||||
class="relative min-h-0 w-full flex-1"
|
||||
style="--folder-composer-space: {folderReadOnly ? 0 : composerHeight}px"
|
||||
>
|
||||
<FolderPlaceholder
|
||||
folder={$selectedFolder}
|
||||
readOnly={folderReadOnly}
|
||||
bind:folderTabActions
|
||||
onNewChat={() => messageInput?.focus()}
|
||||
/>
|
||||
|
||||
if ($selectedFolder?.id === deletedFolder.id) selectedFolder.set(null);
|
||||
}}
|
||||
/>
|
||||
{:else}
|
||||
{#if !folderReadOnly}
|
||||
<!-- Same mount as the in-chat composer, floating over the list and board. -->
|
||||
<div
|
||||
class="pointer-events-none absolute inset-x-0 bottom-0 bg-linear-to-t from-white from-40% to-transparent pt-8 pb-2 text-left dark:from-gray-900 {dragged
|
||||
? 'z-0'
|
||||
: 'z-10'}"
|
||||
bind:clientHeight={composerHeight}
|
||||
>
|
||||
<div class="pointer-events-auto">
|
||||
{@render composer()}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div
|
||||
class="w-full shrink-0 text-3xl text-gray-800 dark:text-gray-100 text-center flex items-center gap-4"
|
||||
>
|
||||
<div class="w-full flex flex-col justify-center items-center">
|
||||
<div class="flex flex-row justify-center gap-2.5 @sm:gap-3 w-fit px-5 max-w-xl">
|
||||
<div class="flex shrink-0 justify-center">
|
||||
<div class="flex -space-x-4 mb-0.5" in:fade={{ duration: 100 }}>
|
||||
@@ -257,67 +329,17 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="text-base font-normal @md:max-w-3xl w-full py-3 {atSelectedModel ? 'mt-2' : ''}">
|
||||
{#if !($selectedFolder && folderReadOnly)}
|
||||
<MessageInput
|
||||
{selectedTerminalId}
|
||||
{terminalSkills}
|
||||
{chatId}
|
||||
bind:terminalContext
|
||||
{callActive}
|
||||
{callEnabled}
|
||||
bind:this={messageInput}
|
||||
{history}
|
||||
bind:selectedModels
|
||||
{onModelSelect}
|
||||
bind:chatFiles
|
||||
bind:params
|
||||
{onParamChange}
|
||||
bind:files
|
||||
bind:prompt
|
||||
bind:autoScroll
|
||||
bind:selectedToolIds
|
||||
bind:selectedSkillIds
|
||||
bind:selectedFilterIds
|
||||
bind:imageGenerationEnabled
|
||||
bind:codeInterpreterEnabled
|
||||
bind:webSearchEnabled
|
||||
bind:atSelectedModel
|
||||
bind:showCommands
|
||||
bind:dragged
|
||||
{pendingOAuthTools}
|
||||
{oauthRedirectHandler}
|
||||
{toolApprovalMode}
|
||||
{onToolApprovalModeChange}
|
||||
{stopResponse}
|
||||
{createMessagePair}
|
||||
placeholder={$i18n.t('How can I help you today?')}
|
||||
{onChange}
|
||||
{onUpload}
|
||||
{onUpdate}
|
||||
{messageQueue}
|
||||
{onQueueSendNow}
|
||||
{onQueueEdit}
|
||||
{onQueueDelete}
|
||||
{askUser}
|
||||
{onWebSearchToggle}
|
||||
on:chatVariables
|
||||
on:submit={(e) => {
|
||||
dispatch('submit', e.detail);
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if $selectedFolder}
|
||||
<div class="mx-auto px-4 md:max-w-3xl md:px-6 min-h-62" in:fade={{ duration: 200, delay: 200 }}>
|
||||
<FolderPlaceholder folder={$selectedFolder} />
|
||||
<div
|
||||
class="text-base font-normal mx-auto @md:max-w-3xl py-3 w-full {atSelectedModel
|
||||
? 'mt-2'
|
||||
: ''}"
|
||||
>
|
||||
{@render composer($i18n.t('How can I help you today?'))}
|
||||
</div>
|
||||
{:else}
|
||||
|
||||
<div class="mx-auto max-w-2xl mt-2" in:fade={{ duration: 200, delay: 200 }}>
|
||||
<div class="mx-5">
|
||||
<Suggestions suggestionPrompts={selectedSuggestionPrompts} inputValue={prompt} {onSelect} />
|
||||
|
||||
@@ -1,307 +1,352 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import type { Writable } from 'svelte/store';
|
||||
|
||||
type ChatListI18n = {
|
||||
language: string;
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
};
|
||||
|
||||
const i18n: Writable<ChatListI18n> = getContext('i18n');
|
||||
|
||||
import dayjs from 'dayjs';
|
||||
import calendar from 'dayjs/plugin/calendar';
|
||||
import localizedFormat from 'dayjs/plugin/localizedFormat';
|
||||
import { getTimeRange } from '$lib/utils';
|
||||
import type { ChatParticipant } from '$lib/apis/folders';
|
||||
import ChevronUp from '$lib/components/icons/ChevronUp.svelte';
|
||||
import ChevronDown from '$lib/components/icons/ChevronDown.svelte';
|
||||
import ChevronLeft from '$lib/components/icons/ChevronLeft.svelte';
|
||||
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
|
||||
import { getContext, tick } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { chatId, chatTitle } from '$lib/stores';
|
||||
import { updateChatById } from '$lib/apis/chats';
|
||||
import { refreshChatList } from '$lib/stores/chatList';
|
||||
import { updateFolderChatLists } from '$lib/stores/folderStates';
|
||||
import type { AppLayoutContext } from '$lib/types';
|
||||
import { openFolderChat } from './folderChat';
|
||||
import {
|
||||
type FolderStatus,
|
||||
type WorkspaceChat,
|
||||
type WorkspacePage,
|
||||
isChatUnread
|
||||
} from '$lib/utils/folders';
|
||||
import ChatParticipants from '$lib/components/common/ChatParticipants.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { chatId, socket } from '$lib/stores';
|
||||
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
|
||||
import FolderTags from './FolderTags.svelte';
|
||||
import FolderChatMenu from './FolderChatMenu.svelte';
|
||||
import FolderStatusControl from './FolderStatus.svelte';
|
||||
import StatusIcon from './FolderStatusIcon.svelte';
|
||||
import FolderStatusTime from './FolderStatusTime.svelte';
|
||||
import { formatDateDetails, formatShortDate } from '$lib/utils';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
|
||||
dayjs.extend(calendar);
|
||||
dayjs.extend(localizedFormat);
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
|
||||
type ChatListItem = {
|
||||
export let groups: {
|
||||
id: string;
|
||||
title?: string;
|
||||
updated_at?: number | null;
|
||||
created_at?: number | null;
|
||||
last_read_at?: number | null;
|
||||
active?: boolean;
|
||||
time_range?: string;
|
||||
user_id?: string;
|
||||
owner_name?: string;
|
||||
participants?: ChatParticipant[];
|
||||
[key: string]: unknown;
|
||||
};
|
||||
label: string;
|
||||
status?: FolderStatus;
|
||||
dot?: string;
|
||||
spinner?: boolean;
|
||||
page?: WorkspacePage;
|
||||
}[] = [];
|
||||
export let saving = '';
|
||||
export let loading = false;
|
||||
export let loadingGroup = '';
|
||||
export let onMore: (id: string) => Promise<void>;
|
||||
export let onMove: (chat: WorkspaceChat, status: FolderStatus) => Promise<void>;
|
||||
export let onTagsChange: () => Promise<void>;
|
||||
|
||||
export let chats: ChatListItem[] = [];
|
||||
let collapsed: Record<string, boolean> = {};
|
||||
let menuOpen: Record<string, boolean> = {};
|
||||
|
||||
export let chatListLoading = false;
|
||||
export let showOwnerInfo = false;
|
||||
export let page = 1;
|
||||
export let total = 0;
|
||||
export let perPage = 10;
|
||||
export let orderBy: 'title' | 'updated_at' = 'updated_at';
|
||||
export let direction: 'asc' | 'desc' = 'desc';
|
||||
export let onPageChange: (page: number) => void | Promise<void> = () => {};
|
||||
export let onSort: (key: 'title' | 'updated_at') => void | Promise<void> = () => {};
|
||||
|
||||
let chatList: ChatListItem[] | null = null;
|
||||
let totalPages = 1;
|
||||
let pages: (number | 'ellipsis')[] = [];
|
||||
|
||||
const init = async () => {
|
||||
if (chats.length === 0) {
|
||||
chatList = [];
|
||||
} else {
|
||||
chatList = chats.map((chat) => ({
|
||||
...chat,
|
||||
time_range: getTimeRange(chat.updated_at)
|
||||
}));
|
||||
// Inline rename, like the sidebar chat item.
|
||||
let renaming = '';
|
||||
let renameValue = '';
|
||||
async function startRename(chat: WorkspaceChat) {
|
||||
renaming = chat.id;
|
||||
renameValue = chat.title;
|
||||
await tick();
|
||||
const input = container?.querySelector<HTMLInputElement>('[data-rename-input]');
|
||||
input?.focus();
|
||||
input?.select();
|
||||
}
|
||||
async function saveRename(chat: WorkspaceChat) {
|
||||
if (renaming !== chat.id) return;
|
||||
const title = renameValue.trim();
|
||||
renaming = '';
|
||||
if (!title || title === chat.title) return;
|
||||
try {
|
||||
await updateChatById(localStorage.token, chat.id, { title });
|
||||
updateFolderChatLists({ id: chat.id, title });
|
||||
if (chat.id === $chatId) chatTitle.set(title);
|
||||
await Promise.all([
|
||||
refreshChatList(localStorage.token, { refreshPinned: true }),
|
||||
onTagsChange()
|
||||
]);
|
||||
} catch (error) {
|
||||
toast.error(`${error}`);
|
||||
}
|
||||
};
|
||||
}
|
||||
let container: HTMLDivElement;
|
||||
|
||||
const setSortKey = (key: 'title' | 'updated_at') => {
|
||||
onSort(key);
|
||||
};
|
||||
const appLayout = getContext<AppLayoutContext | undefined>('appLayout');
|
||||
$: showStatusTime = groups.some((group) =>
|
||||
group.page?.chats.some((chat) => chat.status_since && chat.status)
|
||||
);
|
||||
|
||||
const markChatRead = (chat: ChatListItem, unread: boolean) => {
|
||||
if (!unread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastReadAt = Date.now() / 1000;
|
||||
chatList = (chatList ?? []).map((item) =>
|
||||
item.id === chat.id ? { ...item, last_read_at: lastReadAt } : item
|
||||
);
|
||||
|
||||
$socket?.emit('events:chat', {
|
||||
chat_id: chat.id,
|
||||
data: { type: 'last_read_at' }
|
||||
});
|
||||
};
|
||||
|
||||
const buildPages = (currentPage: number, pageCount: number): (number | 'ellipsis')[] => {
|
||||
if (pageCount <= 7) {
|
||||
return Array.from({ length: pageCount }, (_, i) => i + 1);
|
||||
}
|
||||
|
||||
const items: (number | 'ellipsis')[] = [1];
|
||||
if (currentPage > 3) {
|
||||
items.push('ellipsis');
|
||||
}
|
||||
|
||||
const start = Math.max(2, currentPage - 1);
|
||||
const end = Math.min(pageCount - 1, currentPage + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
items.push(i);
|
||||
}
|
||||
|
||||
if (currentPage < pageCount - 2) {
|
||||
items.push('ellipsis');
|
||||
}
|
||||
items.push(pageCount);
|
||||
|
||||
return items;
|
||||
};
|
||||
|
||||
$: if (chats) {
|
||||
init();
|
||||
function open(event: MouseEvent, chat: WorkspaceChat) {
|
||||
if ((event.target as Element).closest('a, button, input, [role="menu"]')) return;
|
||||
if (window.getSelection()?.toString()) return;
|
||||
openFolderChat(chat, appLayout, event);
|
||||
}
|
||||
|
||||
$: totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
$: pages = buildPages(page, totalPages);
|
||||
// j/k and arrow keys move between rows, like Linear.
|
||||
function navigate(event: KeyboardEvent) {
|
||||
const keys: Record<string, number> = { ArrowDown: 1, j: 1, ArrowUp: -1, k: -1 };
|
||||
const step = keys[event.key];
|
||||
if (!step || event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const target = event.target as HTMLElement;
|
||||
if (!target.matches('[data-row-link]')) return;
|
||||
const links = [...container.querySelectorAll<HTMLElement>('[data-row-link]')];
|
||||
const next = links[links.indexOf(target) + step];
|
||||
if (!next) return;
|
||||
event.preventDefault();
|
||||
next.focus();
|
||||
next.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
|
||||
// Ungrouped lists page in as the end of the list scrolls into view.
|
||||
function sentinel(node: HTMLElement, id: string) {
|
||||
let current = id;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting) && !loading && !loadingGroup)
|
||||
void onMore(current);
|
||||
},
|
||||
{ root: container, rootMargin: '240px' }
|
||||
);
|
||||
observer.observe(node);
|
||||
return {
|
||||
update(next: string) {
|
||||
current = next;
|
||||
},
|
||||
destroy() {
|
||||
observer.disconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if chatList}
|
||||
{#if chatList.length > 0}
|
||||
<div class="flex text-xs font-normal mb-1 items-center -mr-0.5">
|
||||
<button
|
||||
class="px-1.5 py-1 cursor-pointer select-none basis-3/5"
|
||||
on:click={() => setSortKey('title')}
|
||||
>
|
||||
<div class="flex gap-1.5 items-center">
|
||||
{$i18n.t('Title')}
|
||||
|
||||
{#if orderBy === 'title'}
|
||||
<span class="font-normal"
|
||||
>{#if direction === 'asc'}
|
||||
<ChevronUp className="size-2" />
|
||||
{:else}
|
||||
<ChevronDown className="size-2" />
|
||||
{/if}
|
||||
</span>
|
||||
{:else}
|
||||
<span class="invisible">
|
||||
<ChevronUp className="size-2" />
|
||||
</span>
|
||||
<!-- svelte-ignore a11y-no-static-element-interactions -->
|
||||
<div
|
||||
bind:this={container}
|
||||
class="folder-list scrollbar-hidden h-full min-h-0 min-w-0 overflow-y-auto px-3 @container"
|
||||
style="padding-bottom: calc(var(--folder-composer-space, 0px) + 1.5rem)"
|
||||
on:keydown={navigate}
|
||||
>
|
||||
{#each groups as group (group.id)}
|
||||
{@const chats = group.page?.chats ?? []}
|
||||
{#if group.label}
|
||||
<!-- An opaque strip behind the header hides rows above it and behind its rounded corners. -->
|
||||
<div class="sticky top-0 z-[1] mt-1 bg-white pt-0.5 first:mt-0 dark:bg-gray-900">
|
||||
<div class="group-header flex h-8 items-center gap-2 rounded-xl pl-2 pr-3">
|
||||
<button
|
||||
type="button"
|
||||
class="flex size-5 items-center justify-center rounded-md text-gray-400 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"
|
||||
aria-expanded={!collapsed[group.id]}
|
||||
aria-label={collapsed[group.id]
|
||||
? $i18n.t('Expand {{name}}', { name: group.label })
|
||||
: $i18n.t('Collapse {{name}}', { name: group.label })}
|
||||
on:click={() => (collapsed = { ...collapsed, [group.id]: !collapsed[group.id] })}
|
||||
>
|
||||
<ChevronRight
|
||||
className="size-3 transition-transform {collapsed[group.id] ? '' : 'rotate-90'}"
|
||||
strokeWidth="2"
|
||||
/>
|
||||
</button>
|
||||
{#if group.status}
|
||||
<StatusIcon status={group.status} />
|
||||
{:else if group.spinner}
|
||||
<span class="flex size-3.5 shrink-0 items-center justify-center"
|
||||
><Spinner className="size-3" /></span
|
||||
>
|
||||
{:else if group.dot}
|
||||
<span class="flex size-3.5 shrink-0 items-center justify-center"
|
||||
><span class="size-2 rounded-full {group.dot}"></span></span
|
||||
>
|
||||
{/if}
|
||||
<h3 class="text-xs text-gray-700 dark:text-gray-200">
|
||||
{group.label}
|
||||
</h3>
|
||||
<span class="text-xs tabular-nums text-gray-400 dark:text-gray-500"
|
||||
>{group.page?.total ?? ''}</span
|
||||
>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
class="px-1.5 py-1 cursor-pointer select-none hidden sm:flex sm:basis-2/5 justify-end"
|
||||
on:click={() => setSortKey('updated_at')}
|
||||
>
|
||||
<div class="flex gap-1.5 items-center">
|
||||
{$i18n.t('Updated at')}
|
||||
|
||||
{#if orderBy === 'updated_at'}
|
||||
<span class="font-normal"
|
||||
>{#if direction === 'asc'}
|
||||
<ChevronUp className="size-2" />
|
||||
{:else}
|
||||
<ChevronDown className="size-2" />
|
||||
{/if}
|
||||
</span>
|
||||
{:else}
|
||||
<span class="invisible">
|
||||
<ChevronUp className="size-2" />
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="text-left text-sm w-full mb-3">
|
||||
{#if chatList.length === 0}
|
||||
<div
|
||||
class="text-xs text-gray-500 dark:text-gray-400 text-center px-5 min-h-20 w-full h-full flex justify-center items-center"
|
||||
>
|
||||
{$i18n.t('No chats found')}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#each chatList as chat, idx (chat.id)}
|
||||
{@const unread =
|
||||
chat.id !== $chatId &&
|
||||
!chat.active &&
|
||||
(chat.last_read_at == null ||
|
||||
(chat.updated_at != null && chat.updated_at > chat.last_read_at))}
|
||||
{#if (idx === 0 || (idx > 0 && chat.time_range !== chatList[idx - 1].time_range)) && chat?.time_range}
|
||||
<div
|
||||
class="w-full text-xs text-gray-500 dark:text-gray-500 font-normal {idx === 0
|
||||
? ''
|
||||
: 'pt-5'} pb-2 px-2"
|
||||
>
|
||||
{$i18n.t(chat.time_range)}
|
||||
<!-- localisation keys for time_range to be recognized from the i18next parser (so they don't get automatically removed):
|
||||
{$i18n.t('Today')}
|
||||
{$i18n.t('Yesterday')}
|
||||
{$i18n.t('Previous 7 days')}
|
||||
{$i18n.t('Previous 30 days')}
|
||||
{$i18n.t('January')}
|
||||
{$i18n.t('February')}
|
||||
{$i18n.t('March')}
|
||||
{$i18n.t('April')}
|
||||
{$i18n.t('May')}
|
||||
{$i18n.t('June')}
|
||||
{$i18n.t('July')}
|
||||
{$i18n.t('August')}
|
||||
{$i18n.t('September')}
|
||||
{$i18n.t('October')}
|
||||
{$i18n.t('November')}
|
||||
{$i18n.t('December')}
|
||||
-->
|
||||
</div>
|
||||
{/if}
|
||||
{#if !collapsed[group.id]}
|
||||
<ul class="py-0.5" aria-label={group.label || undefined}>
|
||||
{#each chats as chat (chat.id)}
|
||||
{@const unread = chat.id !== $chatId && !chat.active && isChatUnread(chat)}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
|
||||
<li
|
||||
data-folder-item
|
||||
class="group flex cursor-pointer items-center gap-1.5 rounded-xl px-3 py-1.5 transition-colors hover:bg-gray-50 focus-within:bg-gray-50 dark:hover:bg-gray-850/50 dark:focus-within:bg-gray-850/50 {saving ===
|
||||
chat.id
|
||||
? 'opacity-60'
|
||||
: ''}"
|
||||
on:click={(event) => open(event, chat)}
|
||||
>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<FolderStatusControl {chat} disabled={!!saving || loading} onChange={onMove} />
|
||||
{#if showStatusTime}
|
||||
<!-- Time in status; fixed width keeps titles aligned across rows. -->
|
||||
<span class="-ml-1 flex w-6 shrink-0"><FolderStatusTime {chat} /></span>
|
||||
{/if}
|
||||
<!-- Same marker as the sidebar chat item; takes no space when absent. -->
|
||||
{#if chat.pending_approval || chat.active || unread}
|
||||
<span class="flex size-3 shrink-0 items-center justify-center">
|
||||
{#if chat.pending_approval}
|
||||
<span
|
||||
class="size-1.5 rounded-full bg-yellow-500"
|
||||
role="status"
|
||||
aria-label={$i18n.t('Waiting for approval')}
|
||||
title={$i18n.t('Waiting for approval')}
|
||||
></span>
|
||||
{:else if chat.active}
|
||||
<span role="status" aria-label={$i18n.t('Generating…')}
|
||||
><Spinner className="size-3" /></span
|
||||
>
|
||||
{:else if unread}
|
||||
<span
|
||||
class="size-1.5 rounded-full bg-sky-500"
|
||||
role="status"
|
||||
aria-label={$i18n.t('Unread')}
|
||||
title={$i18n.t('Unread')}
|
||||
></span>
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div
|
||||
class=" w-full flex justify-between items-center rounded-lg text-sm py-2 px-3 hover:bg-gray-50 dark:hover:bg-gray-850"
|
||||
>
|
||||
{#if (showOwnerInfo && chat.user_id) || (chat.participants?.length ?? 0) > 1}
|
||||
<div class="flex shrink-0 me-2">
|
||||
<ChatParticipants
|
||||
participants={chat.participants ?? []}
|
||||
owner={chat.user_id ? { id: chat.user_id, name: chat.owner_name ?? null } : null}
|
||||
/>
|
||||
<div class="flex min-w-0 flex-1 items-center gap-2">
|
||||
{#if renaming === chat.id}
|
||||
<input
|
||||
data-rename-input
|
||||
class="min-w-0 flex-1 bg-transparent text-[0.8125rem] leading-5 text-gray-900 outline-none dark:text-white"
|
||||
aria-label={$i18n.t('Rename')}
|
||||
bind:value={renameValue}
|
||||
on:blur={() => saveRename(chat)}
|
||||
on:keydown={(event) => {
|
||||
if (event.isComposing || event.keyCode === 229) return;
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void saveRename(chat);
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
renaming = '';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{:else}
|
||||
<a
|
||||
data-row-link
|
||||
class="min-w-0 shrink truncate rounded text-[0.8125rem] leading-5 outline-none focus-visible:underline {unread
|
||||
? 'text-gray-900 dark:text-white'
|
||||
: 'text-gray-700 dark:text-gray-200'}"
|
||||
href={`/c/${chat.id}`}
|
||||
title={chat.title}
|
||||
on:click={(event) => openFolderChat(chat, appLayout, event)}>{chat.title}</a
|
||||
>
|
||||
{/if}
|
||||
{#if chat.search_snippet}
|
||||
<span
|
||||
class="hidden min-w-0 flex-1 truncate text-xs text-gray-400 @lg:block dark:text-gray-500"
|
||||
>{chat.search_snippet}</span
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="ml-2 flex shrink-0 items-center gap-3">
|
||||
<div class="hidden @md:flex">
|
||||
<FolderTags {chat} onChange={onTagsChange} />
|
||||
</div>
|
||||
<div class="hidden @sm:flex">
|
||||
<ChatParticipants
|
||||
participants={chat.participants ?? []}
|
||||
owner={{ id: chat.user_id, name: chat.owner_name ?? null }}
|
||||
/>
|
||||
</div>
|
||||
<!-- The menu takes the date's place on hover, so nothing shifts. -->
|
||||
<div
|
||||
class="date-slot relative flex w-14 shrink-0 items-center justify-end"
|
||||
class:open={menuOpen[chat.id]}
|
||||
>
|
||||
<Tooltip
|
||||
as="span"
|
||||
className="row-date flex shrink-0"
|
||||
placement="top-end"
|
||||
content={formatDateDetails(chat.updated_at, $i18n.language)}
|
||||
>
|
||||
<time
|
||||
class="w-14 text-right text-[0.6875rem] tabular-nums text-gray-400 dark:text-gray-500"
|
||||
datetime={new Date(chat.updated_at * 1000).toISOString()}
|
||||
>{formatShortDate(chat.updated_at, $i18n.language)}</time
|
||||
>
|
||||
</Tooltip>
|
||||
<div class="chat-menu absolute inset-y-0 right-0 flex items-center">
|
||||
<FolderChatMenu
|
||||
{chat}
|
||||
bind:open={menuOpen[chat.id]}
|
||||
onRename={() => startRename(chat)}
|
||||
onChange={onTagsChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
{#if group.page?.has_more}
|
||||
{#if group.label}
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center rounded-xl py-1.5 pl-9.5 text-xs text-gray-400 transition-colors hover:bg-gray-50 hover:text-gray-700 disabled:pointer-events-none dark:text-gray-500 dark:hover:bg-gray-850/50 dark:hover:text-gray-300"
|
||||
disabled={loading || !!loadingGroup}
|
||||
on:click={() => onMore(group.id)}
|
||||
>
|
||||
{loadingGroup === group.id
|
||||
? $i18n.t('Loading…')
|
||||
: $i18n.t('Show {{count}} more', {
|
||||
count: Math.max(0, (group.page?.total ?? 0) - chats.length)
|
||||
})}
|
||||
</button>
|
||||
{:else}
|
||||
<div use:sentinel={group.id} class="flex h-10 items-center justify-center">
|
||||
{#if loadingGroup === group.id}<Spinner className="size-3.5" />{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<a
|
||||
class="flex min-w-0 flex-1 justify-between items-center"
|
||||
draggable="false"
|
||||
href={`/c/${chat.id}`}
|
||||
on:click={() => markChatRead(chat, unread)}
|
||||
>
|
||||
<div class="flex min-w-0 items-center w-full sm:basis-3/5">
|
||||
{#if chat.active}
|
||||
<div class="shrink-0 self-center pr-2">
|
||||
<Spinner className="size-3" />
|
||||
</div>
|
||||
{:else if unread}
|
||||
<div class="shrink-0 self-center pr-2.5 flex transition-opacity duration-300">
|
||||
<div class="size-1.5 bg-sky-500 rounded-full"></div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class="text-ellipsis line-clamp-1 min-w-0 {unread
|
||||
? 'font-normal text-gray-800 dark:text-gray-200'
|
||||
: ''}"
|
||||
>
|
||||
{chat?.title}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hidden sm:flex sm:basis-2/5 items-center justify-end gap-2">
|
||||
<div class=" text-gray-500 dark:text-gray-400 text-xs">
|
||||
{dayjs((chat.updated_at ?? chat.created_at ?? 0) * 1000)
|
||||
.locale($i18n.language)
|
||||
.calendar()}
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if totalPages > 1}
|
||||
<div class="flex items-center justify-center gap-1.5 pt-2">
|
||||
<button
|
||||
class="inline-flex size-7 items-center justify-center rounded-lg text-xs font-medium text-gray-500 transition hover:bg-gray-50 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-25 dark:text-gray-500 dark:hover:bg-gray-850 dark:hover:text-gray-300"
|
||||
disabled={chatListLoading || page <= 1}
|
||||
aria-label={$i18n.t('Previous page')}
|
||||
on:click={() => onPageChange(page - 1)}
|
||||
>
|
||||
<ChevronLeft className="size-3.5" strokeWidth="2" />
|
||||
</button>
|
||||
|
||||
{#each pages as item, index (item === 'ellipsis' ? `ellipsis-${index}` : item)}
|
||||
{#if item === 'ellipsis'}
|
||||
<span
|
||||
class="inline-flex size-7 items-center justify-center text-xs text-gray-400 select-none dark:text-gray-600"
|
||||
>
|
||||
...
|
||||
</span>
|
||||
{:else}
|
||||
<button
|
||||
class="inline-flex size-7 items-center justify-center rounded-lg text-xs font-medium transition hover:bg-gray-50 hover:text-gray-700 dark:hover:bg-gray-850 dark:hover:text-gray-300 {item ===
|
||||
page
|
||||
? 'bg-gray-50 text-gray-800 dark:bg-gray-850 dark:text-gray-100'
|
||||
: 'text-gray-500 dark:text-gray-500'}"
|
||||
aria-label={`Page ${item}`}
|
||||
aria-current={item === page ? 'page' : undefined}
|
||||
on:click={() => onPageChange(item)}
|
||||
>
|
||||
{item}
|
||||
</button>
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
<button
|
||||
class="inline-flex size-7 items-center justify-center rounded-lg text-xs font-medium text-gray-500 transition hover:bg-gray-50 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-25 dark:text-gray-500 dark:hover:bg-gray-850 dark:hover:text-gray-300"
|
||||
disabled={chatListLoading || page >= totalPages}
|
||||
aria-label={$i18n.t('Next page')}
|
||||
on:click={() => onPageChange(page + 1)}
|
||||
>
|
||||
<ChevronRight className="size-3.5" strokeWidth="2" />
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* A soft, opaque band: the old tint mixed into the page background, so rows never show through. */
|
||||
.group-header {
|
||||
background: color-mix(in oklab, var(--color-gray-50) 60%, var(--color-white));
|
||||
}
|
||||
:global(.dark) .group-header {
|
||||
background: color-mix(in oklab, var(--color-gray-850) 30%, var(--color-gray-900));
|
||||
}
|
||||
|
||||
/* The menu replaces the date on hover, focus, or while open; touch shows the menu. */
|
||||
@media (hover: hover) {
|
||||
.date-slot:not(.open) .chat-menu {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
:global([data-folder-item]:hover) .date-slot .chat-menu,
|
||||
:global([data-folder-item]:focus-within) .date-slot .chat-menu {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.date-slot.open :global(.row-date),
|
||||
:global([data-folder-item]:hover) .date-slot :global(.row-date),
|
||||
:global([data-folder-item]:focus-within) .date-slot :global(.row-date) {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@media (hover: none) {
|
||||
.date-slot :global(.row-date) {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,371 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import { chatId } from '$lib/stores';
|
||||
import type { AppLayoutContext } from '$lib/types';
|
||||
import { openFolderChat } from './folderChat';
|
||||
import {
|
||||
type FolderStatus,
|
||||
type WorkspaceChat,
|
||||
type WorkspacePage,
|
||||
isChatUnread,
|
||||
statusKey
|
||||
} from '$lib/utils/folders';
|
||||
import ChatParticipants from '$lib/components/common/ChatParticipants.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
|
||||
import FolderTags from './FolderTags.svelte';
|
||||
import FolderStatusControl from './FolderStatus.svelte';
|
||||
import StatusIcon from './FolderStatusIcon.svelte';
|
||||
import FolderStatusTime from './FolderStatusTime.svelte';
|
||||
import { formatDateDetails, formatShortDate } from '$lib/utils';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
|
||||
type BoardGroup = {
|
||||
id: string;
|
||||
label: string;
|
||||
status?: FolderStatus;
|
||||
dot?: string;
|
||||
spinner?: boolean;
|
||||
page?: WorkspacePage;
|
||||
};
|
||||
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
|
||||
export let columns: BoardGroup[] = [];
|
||||
/** Optional swimlanes; cards are placed by `rowOf`. */
|
||||
export let rows: BoardGroup[] | null = null;
|
||||
export let rowOf: (chat: WorkspaceChat) => string[] = () => [];
|
||||
/** The status a drop into this cell sets, or null when the cell isn't a status. */
|
||||
export let dropStatus: (column: string, row: string | null) => FolderStatus | null = (column) =>
|
||||
column;
|
||||
export let onMore: (id: string) => Promise<void>;
|
||||
export let onMove: (chat: WorkspaceChat, status: FolderStatus) => Promise<void>;
|
||||
export let onTagsChange: () => Promise<void>;
|
||||
export let onAddStatus: (() => void) | null = null;
|
||||
export let saving = '';
|
||||
export let loading = false;
|
||||
export let loadingGroup = '';
|
||||
|
||||
let dragged: WorkspaceChat | null = null;
|
||||
let over = '';
|
||||
let collapsed: Record<string, boolean> = {};
|
||||
|
||||
const cellKey = (column: string, row: string | null) => `${column}\u0000${row ?? ''}`;
|
||||
$: canDrop = (column: string, row: string | null) => dropStatus(column, row) != null;
|
||||
$: draggableBoard = columns.some((column) => canDrop(column.id, rows?.[0]?.id ?? null));
|
||||
|
||||
function drop(column: string, row: string | null) {
|
||||
const status = dropStatus(column, row);
|
||||
if (dragged && status && dragged.can_edit_status && statusKey(dragged.status) !== status)
|
||||
void onMove(dragged, status);
|
||||
dragged = null;
|
||||
over = '';
|
||||
}
|
||||
|
||||
const dropzone = (column: string, row: string | null) => ({
|
||||
dragover: (event: DragEvent) => {
|
||||
if (!dragged || !canDrop(column, row)) return;
|
||||
event.preventDefault();
|
||||
over = cellKey(column, row);
|
||||
if (event.dataTransfer)
|
||||
event.dataTransfer.dropEffect =
|
||||
statusKey(dragged.status) === dropStatus(column, row) ? 'none' : 'move';
|
||||
},
|
||||
dragleave: (event: DragEvent) => {
|
||||
const target = event.currentTarget as HTMLElement;
|
||||
if (!target.contains(event.relatedTarget as Node | null)) over = '';
|
||||
},
|
||||
drop: (event: DragEvent) => {
|
||||
event.preventDefault();
|
||||
drop(column, row);
|
||||
}
|
||||
});
|
||||
|
||||
const cellChats = (column: BoardGroup, row: BoardGroup) =>
|
||||
(column.page?.chats ?? []).filter((chat) => rowOf(chat).includes(row.id));
|
||||
const rowCount = (row: BoardGroup) =>
|
||||
new Set(columns.flatMap((column) => cellChats(column, row).map((chat) => chat.id))).size;
|
||||
|
||||
const appLayout = getContext<AppLayoutContext | undefined>('appLayout');
|
||||
|
||||
function open(event: MouseEvent, chat: WorkspaceChat) {
|
||||
if ((event.target as Element).closest('a, button, input, [role="menu"]')) return;
|
||||
if (window.getSelection()?.toString()) return;
|
||||
openFolderChat(chat, appLayout, event);
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet groupIcon(group: BoardGroup)}
|
||||
{#if group.status}
|
||||
<StatusIcon status={group.status} />
|
||||
{:else if group.spinner}
|
||||
<span class="flex size-3.5 shrink-0 items-center justify-center"
|
||||
><Spinner className="size-3" /></span
|
||||
>
|
||||
{:else if group.dot}
|
||||
<span class="flex size-3.5 shrink-0 items-center justify-center"
|
||||
><span class="size-2 rounded-full {group.dot}"></span></span
|
||||
>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet columnHeader(column: BoardGroup)}
|
||||
<header class="flex h-9 shrink-0 items-center gap-2 px-3">
|
||||
{@render groupIcon(column)}
|
||||
<h3 class="min-w-0 truncate text-xs text-gray-700 dark:text-gray-200">
|
||||
{column.label}
|
||||
</h3>
|
||||
<span class="text-xs tabular-nums text-gray-400 dark:text-gray-500"
|
||||
>{column.page?.total ?? ''}</span
|
||||
>
|
||||
</header>
|
||||
{/snippet}
|
||||
|
||||
{#snippet more(column: BoardGroup)}
|
||||
{#if column.page?.has_more}
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-7 w-full items-center justify-center rounded-lg text-xs text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800/60 dark:hover:text-gray-300"
|
||||
disabled={loading || !!loadingGroup}
|
||||
on:click={() => onMore(column.id)}
|
||||
>
|
||||
{loadingGroup === column.id
|
||||
? $i18n.t('Loading…')
|
||||
: $i18n.t('Show {{count}} more', {
|
||||
count: Math.max(0, (column.page?.total ?? 0) - (column.page?.chats.length ?? 0))
|
||||
})}
|
||||
</button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet card(chat: WorkspaceChat)}
|
||||
{@const unread = chat.id !== $chatId && !chat.active && isChatUnread(chat)}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
|
||||
<article
|
||||
data-folder-item
|
||||
class="group cursor-pointer rounded-xl border border-black/[0.06] bg-white px-3 py-2 shadow-[0_1px_2px_rgba(0,0,0,0.03)] transition hover:border-black/[0.09] dark:border-white/[0.06] dark:bg-gray-900 dark:hover:border-white/[0.09] {saving ===
|
||||
chat.id || dragged?.id === chat.id
|
||||
? 'opacity-40'
|
||||
: ''}"
|
||||
draggable={draggableBoard && chat.can_edit_status && !saving && !loading}
|
||||
on:click={(event) => open(event, chat)}
|
||||
on:dragstart={(event) => {
|
||||
dragged = chat;
|
||||
event.dataTransfer?.setData('text/plain', chat.id);
|
||||
if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move';
|
||||
}}
|
||||
on:dragend={() => {
|
||||
dragged = null;
|
||||
over = '';
|
||||
}}
|
||||
>
|
||||
<div class="flex items-start gap-1.5">
|
||||
<div class="-ml-0.5 shrink-0">
|
||||
<FolderStatusControl {chat} disabled={!!saving || loading} onChange={onMove} />
|
||||
</div>
|
||||
<!-- Time in status, on the title's first line. -->
|
||||
{#if chat.status_since && chat.status}
|
||||
<span class="-ml-1 flex h-5 shrink-0 items-center"><FolderStatusTime {chat} /></span>
|
||||
{/if}
|
||||
{#if chat.pending_approval || chat.active || unread}
|
||||
<!-- Centered on the title's first line, like the list's marker slot. -->
|
||||
<span class="flex h-5 w-3 shrink-0 items-center justify-center">
|
||||
{#if chat.pending_approval}
|
||||
<span
|
||||
class="size-1.5 rounded-full bg-yellow-500"
|
||||
role="status"
|
||||
aria-label={$i18n.t('Waiting for approval')}
|
||||
title={$i18n.t('Waiting for approval')}
|
||||
></span>
|
||||
{:else if chat.active}
|
||||
<span role="status" aria-label={$i18n.t('Generating…')}
|
||||
><Spinner className="size-3" /></span
|
||||
>
|
||||
{:else}
|
||||
<span
|
||||
class="size-1.5 rounded-full bg-sky-500"
|
||||
role="status"
|
||||
aria-label={$i18n.t('Unread')}
|
||||
title={$i18n.t('Unread')}
|
||||
></span>
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
<a
|
||||
class="min-w-0 flex-1 line-clamp-2 text-[0.8125rem] leading-5 outline-none focus-visible:underline {unread
|
||||
? 'text-gray-900 dark:text-white'
|
||||
: 'text-gray-700 dark:text-gray-200'}"
|
||||
href={`/c/${chat.id}`}
|
||||
draggable="false"
|
||||
title={chat.title}
|
||||
on:click={(event) => openFolderChat(chat, appLayout, event)}>{chat.title}</a
|
||||
>
|
||||
</div>
|
||||
|
||||
{#if chat.search_snippet}
|
||||
<p class="mt-1 line-clamp-2 pl-6 text-xs leading-4 text-gray-500 dark:text-gray-400">
|
||||
{chat.search_snippet}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div class="mt-2 flex min-h-5 items-center gap-2 pl-6">
|
||||
<div class="flex min-w-0 flex-1">
|
||||
<FolderTags {chat} onChange={onTagsChange} />
|
||||
</div>
|
||||
<ChatParticipants
|
||||
participants={chat.participants ?? []}
|
||||
owner={{ id: chat.user_id, name: chat.owner_name ?? null }}
|
||||
/>
|
||||
<Tooltip
|
||||
as="span"
|
||||
className="flex shrink-0"
|
||||
placement="top-end"
|
||||
content={formatDateDetails(chat.updated_at, $i18n.language)}
|
||||
>
|
||||
<time
|
||||
class="shrink-0 text-[0.6875rem] tabular-nums text-gray-400 dark:text-gray-500"
|
||||
datetime={new Date(chat.updated_at * 1000).toISOString()}
|
||||
>{formatShortDate(chat.updated_at, $i18n.language)}</time
|
||||
>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</article>
|
||||
{/snippet}
|
||||
|
||||
{#snippet emptyCell(column: string, row: string | null)}
|
||||
<div
|
||||
class="flex h-20 items-center justify-center rounded-xl border border-dashed text-xs text-gray-400 transition-colors dark:text-gray-500 {over ===
|
||||
cellKey(column, row)
|
||||
? 'border-gray-300 dark:border-gray-700'
|
||||
: 'border-gray-200/70 dark:border-gray-800'}"
|
||||
>
|
||||
{$i18n.t('No conversations')}
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet addStatus()}
|
||||
{#if onAddStatus}
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 w-36 shrink-0 items-center gap-1.5 rounded-2xl px-3 text-xs text-gray-400 transition-colors hover:bg-gray-50 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-850/40 dark:hover:text-gray-200"
|
||||
on:click={onAddStatus}
|
||||
>
|
||||
<Plus className="size-3" strokeWidth="2" />{$i18n.t('Add status')}
|
||||
</button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#if !rows}
|
||||
<!-- Columns only: each column runs full height and scrolls on its own. -->
|
||||
<div
|
||||
class="scrollbar-hidden flex h-full min-h-0 gap-2 overflow-x-auto px-3 pt-1 pb-2"
|
||||
aria-label={$i18n.t('Conversation board')}
|
||||
>
|
||||
{#each columns as column (column.id)}
|
||||
{@const chats = column.page?.chats ?? []}
|
||||
{@const zone = dropzone(column.id, null)}
|
||||
<section
|
||||
class="flex min-h-0 w-72 min-w-64 flex-1 flex-col rounded-2xl transition-colors {over ===
|
||||
cellKey(column.id, null)
|
||||
? 'bg-gray-100 ring-1 ring-gray-200 dark:bg-gray-850 dark:ring-gray-800'
|
||||
: 'bg-gray-50/80 dark:bg-gray-850/40'}"
|
||||
aria-label={column.label}
|
||||
on:dragover={zone.dragover}
|
||||
on:dragleave={zone.dragleave}
|
||||
on:drop={zone.drop}
|
||||
>
|
||||
{@render columnHeader(column)}
|
||||
<div
|
||||
class="scrollbar-hidden min-h-0 flex-1 space-y-1.5 overflow-y-auto px-1.5"
|
||||
style="padding-bottom: calc(var(--folder-composer-space, 0px) + 0.375rem)"
|
||||
>
|
||||
{#each chats as chat (chat.id)}
|
||||
{@render card(chat)}
|
||||
{/each}
|
||||
{#if !loading && !chats.length}
|
||||
{@render emptyCell(column.id, null)}
|
||||
{/if}
|
||||
{@render more(column)}
|
||||
</div>
|
||||
</section>
|
||||
{/each}
|
||||
{@render addStatus()}
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Swimlanes: the board scrolls as one; column headers stick to the top. -->
|
||||
<div
|
||||
class="scrollbar-hidden h-full min-h-0 overflow-auto px-3 pt-1"
|
||||
style="padding-bottom: calc(var(--folder-composer-space, 0px) + 0.5rem)"
|
||||
aria-label={$i18n.t('Conversation board')}
|
||||
>
|
||||
<div class="inline-flex min-w-full flex-col">
|
||||
<div class="sticky top-0 z-[2] flex gap-2 bg-white pb-1 dark:bg-gray-900">
|
||||
{#each columns as column (column.id)}
|
||||
<div class="w-72 shrink-0 rounded-2xl bg-gray-50/80 dark:bg-gray-850/40">
|
||||
{@render columnHeader(column)}
|
||||
</div>
|
||||
{/each}
|
||||
{@render addStatus()}
|
||||
</div>
|
||||
|
||||
{#each rows as row (row.id)}
|
||||
{@const count = rowCount(row)}
|
||||
{#if count}
|
||||
<div class="sticky left-0 z-[1] flex h-8 w-fit items-center gap-2 pr-3">
|
||||
<button
|
||||
type="button"
|
||||
class="flex size-5 items-center justify-center rounded-md text-gray-400 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"
|
||||
aria-expanded={!collapsed[row.id]}
|
||||
aria-label={collapsed[row.id]
|
||||
? $i18n.t('Expand {{name}}', { name: row.label })
|
||||
: $i18n.t('Collapse {{name}}', { name: row.label })}
|
||||
on:click={() => (collapsed = { ...collapsed, [row.id]: !collapsed[row.id] })}
|
||||
>
|
||||
<ChevronRight
|
||||
className="size-3 transition-transform {collapsed[row.id] ? '' : 'rotate-90'}"
|
||||
strokeWidth="2"
|
||||
/>
|
||||
</button>
|
||||
{@render groupIcon(row)}
|
||||
<span class="text-xs text-gray-700 dark:text-gray-200">{row.label}</span>
|
||||
<span class="text-xs tabular-nums text-gray-400 dark:text-gray-500">{count}</span>
|
||||
</div>
|
||||
|
||||
{#if !collapsed[row.id]}
|
||||
<div class="flex gap-2 pb-2">
|
||||
{#each columns as column (column.id)}
|
||||
{@const chats = cellChats(column, row)}
|
||||
{@const zone = dropzone(column.id, row.id)}
|
||||
<div
|
||||
role="group"
|
||||
aria-label={`${column.label} · ${row.label}`}
|
||||
class="w-72 shrink-0 space-y-1.5 rounded-2xl p-1.5 transition-colors {over ===
|
||||
cellKey(column.id, row.id)
|
||||
? 'bg-gray-100 ring-1 ring-gray-200 dark:bg-gray-850 dark:ring-gray-800'
|
||||
: 'bg-gray-50/80 dark:bg-gray-850/40'}"
|
||||
on:dragover={zone.dragover}
|
||||
on:dragleave={zone.dragleave}
|
||||
on:drop={zone.drop}
|
||||
>
|
||||
{#each chats as chat (chat.id)}
|
||||
{@render card(chat)}
|
||||
{/each}
|
||||
{#if !chats.length}
|
||||
<div class="h-10"></div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
<div class="flex gap-2">
|
||||
{#each columns as column (column.id)}
|
||||
<div class="w-72 shrink-0">{@render more(column)}</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,133 @@
|
||||
<script lang="ts">
|
||||
import { getContext, tick } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { chatId, user, tags } from '$lib/stores';
|
||||
import {
|
||||
archiveChatById,
|
||||
cloneChatById,
|
||||
deleteChatById,
|
||||
getAllTags,
|
||||
markChatUnreadById,
|
||||
updateChatFolderIdById
|
||||
} from '$lib/apis/chats';
|
||||
import { refreshSidebar } from '$lib/stores/chatList';
|
||||
import { updateFolderChatLists } from '$lib/stores/folderStates';
|
||||
import type { WorkspaceChat } from '$lib/utils/folders';
|
||||
import ChatMenu from '$lib/components/layout/Sidebar/ChatMenu.svelte';
|
||||
import MoreHorizontalIcon from '$lib/components/layout/Sidebar/icons/MoreHorizontal.svelte';
|
||||
import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
||||
import ShareChatModal from '$lib/components/chat/ShareChatModal.svelte';
|
||||
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
|
||||
export let chat: WorkspaceChat;
|
||||
/** Start renaming the chat inline in its row. */
|
||||
export let onRename: () => void = () => {};
|
||||
/** Reload the folder view after a change. */
|
||||
export let onChange: () => Promise<void> = async () => {};
|
||||
export let open = false;
|
||||
|
||||
let showShare = false;
|
||||
let showDelete = false;
|
||||
let busy = false;
|
||||
|
||||
// Same actions as the sidebar chat item, refreshing this view and the sidebar after each.
|
||||
async function run(action: () => Promise<unknown>, removed = false) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
const result = await action();
|
||||
if (result === null) return;
|
||||
if (removed) {
|
||||
updateFolderChatLists({ id: chat.id }, undefined, true);
|
||||
if ($chatId === chat.id) {
|
||||
await goto('/');
|
||||
chatId.set('');
|
||||
await tick();
|
||||
}
|
||||
}
|
||||
await Promise.all([
|
||||
refreshSidebar(localStorage.token),
|
||||
getAllTags(localStorage.token).then((value) => tags.set(value)),
|
||||
onChange()
|
||||
]);
|
||||
} catch (error) {
|
||||
toast.error(`${error}`);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
const clone = () =>
|
||||
run(async () => {
|
||||
if (!($user?.role === 'admin' || ($user?.permissions?.chat?.import ?? true))) {
|
||||
toast.error($i18n.t('Access prohibited'));
|
||||
return null;
|
||||
}
|
||||
const res = await cloneChatById(
|
||||
localStorage.token,
|
||||
chat.id,
|
||||
$i18n.t('Clone of {{TITLE}}', { TITLE: chat.title })
|
||||
);
|
||||
if (res) void goto(`/c/${res.id}`);
|
||||
return res;
|
||||
});
|
||||
|
||||
const archive = () =>
|
||||
run(async () => {
|
||||
await archiveChatById(localStorage.token, chat.id);
|
||||
toast.success($i18n.t('Chat archived.'));
|
||||
}, true);
|
||||
|
||||
const remove = () => run(() => deleteChatById(localStorage.token, chat.id), true);
|
||||
|
||||
const move = (id: string, folderId: string) =>
|
||||
run(async () => {
|
||||
const res = await updateChatFolderIdById(localStorage.token, id, folderId);
|
||||
if (res) {
|
||||
updateFolderChatLists(res, folderId);
|
||||
toast.success($i18n.t('Chat moved successfully'));
|
||||
}
|
||||
return res;
|
||||
});
|
||||
|
||||
const markUnread = () =>
|
||||
run(async () => {
|
||||
const res = await markChatUnreadById(localStorage.token, chat.id);
|
||||
if (res) updateFolderChatLists({ id: chat.id, last_read_at: res.last_read_at ?? 0 });
|
||||
return res;
|
||||
});
|
||||
</script>
|
||||
|
||||
<ShareChatModal bind:show={showShare} chatId={chat.id} />
|
||||
|
||||
<DeleteConfirmDialog bind:show={showDelete} title={$i18n.t('Delete chat?')} on:confirm={remove}>
|
||||
<div class="flex-1 line-clamp-3 text-sm text-gray-500">
|
||||
{$i18n.t('This will delete')} <span class="font-normal">{chat.title}</span>.
|
||||
</div>
|
||||
</DeleteConfirmDialog>
|
||||
|
||||
<ChatMenu
|
||||
readonly={!chat.can_edit_tags}
|
||||
chatId={chat.id}
|
||||
cloneChatHandler={clone}
|
||||
shareHandler={() => (showShare = true)}
|
||||
moveChatHandler={move}
|
||||
archiveChatHandler={archive}
|
||||
renameHandler={onRename}
|
||||
deleteHandler={() => (showDelete = true)}
|
||||
markUnreadHandler={markUnread}
|
||||
onOpen={() => (open = true)}
|
||||
onClose={() => (open = false)}
|
||||
onPinChange={() => onChange()}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={$i18n.t('Chat Menu')}
|
||||
class="flex size-5 items-center justify-center rounded-md text-gray-400 transition hover:text-gray-700 dark:text-gray-500 dark:hover:text-white"
|
||||
disabled={busy}
|
||||
>
|
||||
<MoreHorizontalIcon className="size-3.5" strokeWidth="2" />
|
||||
</button>
|
||||
</ChatMenu>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,70 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import type { Readable } from 'svelte/store';
|
||||
import type { FolderStatus, StatusDef, WorkspaceChat } from '$lib/utils/folders';
|
||||
import { statusKey } from '$lib/utils/folders';
|
||||
import Dropdown from '$lib/components/common/Dropdown.svelte';
|
||||
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
|
||||
import Check from '$lib/components/icons/Check.svelte';
|
||||
import Icon from '$lib/components/chat/FileNav/Icon.svelte';
|
||||
import StatusIcon from './FolderStatusIcon.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import { formatElapsed } from '$lib/utils';
|
||||
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
const defs = getContext<Readable<StatusDef[]> | undefined>('folder-statuses');
|
||||
const manage = getContext<Readable<(() => void) | null> | undefined>('folder-statuses-manage');
|
||||
|
||||
export let chat: WorkspaceChat;
|
||||
export let disabled = false;
|
||||
export let onChange: (chat: WorkspaceChat, status: FolderStatus) => Promise<void>;
|
||||
|
||||
$: current = statusKey(chat.status);
|
||||
$: label = $defs?.find((item) => item.id === current)?.name ?? $i18n.t('No status');
|
||||
// "In progress · 3 days": how long this chat has been in its status.
|
||||
$: tip = chat.status_since
|
||||
? `${label} · ${formatElapsed(chat.status_since, $i18n.language)}`
|
||||
: label;
|
||||
</script>
|
||||
|
||||
<Tooltip content={tip} placement="top-start" as="span" className="flex shrink-0">
|
||||
{#if chat.can_edit_status}
|
||||
<Dropdown align="start" closeOnSelect>
|
||||
<button
|
||||
type="button"
|
||||
class="flex size-5 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-gray-100 disabled:opacity-50 dark:hover:bg-gray-800"
|
||||
{disabled}
|
||||
aria-label={$i18n.t('Status for {{title}}: {{status}}', { title: chat.title, status: tip })}
|
||||
>
|
||||
<StatusIcon status={current} />
|
||||
</button>
|
||||
<DropdownMenu slot="content" className="w-44">
|
||||
{#each $defs ?? [] as status (status.id)}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitemradio"
|
||||
aria-checked={current === status.id}
|
||||
{disabled}
|
||||
on:click={() => {
|
||||
if (current !== status.id) void onChange(chat, status.id);
|
||||
}}
|
||||
>
|
||||
<StatusIcon status={status.id} />
|
||||
<span class="min-w-0 flex-1 truncate text-left">{status.name}</span>
|
||||
{#if current === status.id}<Check className="size-3! shrink-0" />{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{#if $manage}
|
||||
<hr class="border-gray-50/30 dark:border-gray-800/30" />
|
||||
<button type="button" on:click={() => $manage?.()}>
|
||||
<Icon name="pencil" size={14} />{$i18n.t('Edit statuses…')}
|
||||
</button>
|
||||
{/if}
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
{:else}
|
||||
<span class="flex size-5 shrink-0 items-center justify-center">
|
||||
<StatusIcon status={current} />
|
||||
</span>
|
||||
{/if}
|
||||
</Tooltip>
|
||||
@@ -0,0 +1,68 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import type { Readable } from 'svelte/store';
|
||||
import {
|
||||
glyphColor,
|
||||
NO_STATUS,
|
||||
type FolderStatus,
|
||||
type StatusDef,
|
||||
type StatusGlyph
|
||||
} from '$lib/utils/folders';
|
||||
import type { TagColor } from '$lib/utils/tags';
|
||||
import Emoji from '$lib/components/common/Emoji.svelte';
|
||||
|
||||
/** A folder status id, looked up in the folder's statuses. */
|
||||
export let status: FolderStatus = NO_STATUS;
|
||||
/** Explicit look, e.g. for previews; overrides the lookup. */
|
||||
export let glyph: StatusGlyph | undefined = undefined;
|
||||
export let color: TagColor | undefined = undefined;
|
||||
export let emoji: string | undefined = undefined;
|
||||
export let className = 'size-3.5';
|
||||
|
||||
const defs = getContext<Readable<StatusDef[]> | undefined>('folder-statuses');
|
||||
$: def = glyph || emoji ? undefined : $defs?.find((item) => item.id === status);
|
||||
$: shownEmoji = emoji ?? def?.icon;
|
||||
$: shape = glyph ?? def?.glyph ?? (status === NO_STATUS || !def ? null : 'todo');
|
||||
$: tone = glyphColor[color ?? def?.color ?? 'gray'];
|
||||
</script>
|
||||
|
||||
{#if shownEmoji}
|
||||
<Emoji shortCode={shownEmoji} className="shrink-0 {className}" />
|
||||
{:else if !shape}
|
||||
<!-- No status -->
|
||||
<svg
|
||||
class="shrink-0 text-gray-300 dark:text-gray-600 {className}"
|
||||
viewBox="0 0 14 14"
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M4.25 7h5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
|
||||
</svg>
|
||||
{:else}
|
||||
<svg class="shrink-0 {tone} {className}" viewBox="0 0 14 14" fill="none" aria-hidden="true">
|
||||
{#if shape === 'done'}
|
||||
<circle cx="7" cy="7" r="6.25" fill="currentColor" />
|
||||
<path
|
||||
d="M4.4 7.2 6.1 8.9 9.6 5.4"
|
||||
stroke="var(--color-white)"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
{:else}
|
||||
<circle
|
||||
cx="7"
|
||||
cy="7"
|
||||
r="5.75"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
stroke-dasharray={shape === 'backlog' ? '1.6 1.8' : undefined}
|
||||
/>
|
||||
{#if shape === 'in_progress'}
|
||||
<path d="M7 4a3 3 0 0 1 0 6z" fill="currentColor" />
|
||||
{:else if shape === 'waiting'}
|
||||
<path d="M7 4a3 3 0 1 1-3 3h3z" fill="currentColor" />
|
||||
{/if}
|
||||
{/if}
|
||||
</svg>
|
||||
{/if}
|
||||
@@ -0,0 +1,69 @@
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import type { Readable } from 'svelte/store';
|
||||
import dayjs from 'dayjs';
|
||||
import { statusKey, type StatusDef, type WorkspaceChat } from '$lib/utils/folders';
|
||||
import { formatElapsed, formatElapsedShort } from '$lib/utils';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
const defs = getContext<Readable<StatusDef[]> | undefined>('folder-statuses');
|
||||
|
||||
export let chat: WorkspaceChat;
|
||||
export let className = '';
|
||||
|
||||
const escape = (value: string) => value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
|
||||
const nameOf = (id: string) => $defs?.find((item) => item.id === id)?.name ?? id;
|
||||
// A plain length of time, e.g. "2 hours", from a number of seconds.
|
||||
const span = (seconds: number) => formatElapsed(Date.now() / 1000 - seconds, $i18n.language);
|
||||
|
||||
$: current = statusKey(chat.status);
|
||||
$: earlier = chat.status_durations?.[current] ?? 0;
|
||||
$: others = Object.entries(chat.status_durations ?? {}).filter(
|
||||
([id, seconds]) => id !== current && seconds > 0
|
||||
);
|
||||
|
||||
// What the "3d" label can't say: when this stretch began, whether earlier time is
|
||||
// included, and how long the chat spent in its other statuses.
|
||||
$: tip = !chat.status_since
|
||||
? ''
|
||||
: [
|
||||
`${escape(nameOf(current))} · ${escape(
|
||||
earlier
|
||||
? $i18n.t('{{duration}} in total', {
|
||||
duration: formatElapsed(chat.status_since, $i18n.language)
|
||||
})
|
||||
: formatElapsed(chat.status_since, $i18n.language)
|
||||
)}`,
|
||||
...(chat.status_entered_at
|
||||
? [
|
||||
`<span class="opacity-60">${escape(
|
||||
$i18n.t(earlier ? 'This time since {{date}}' : 'Since {{date}}', {
|
||||
date: dayjs(chat.status_entered_at * 1000)
|
||||
.locale($i18n.language)
|
||||
.format('llll')
|
||||
})
|
||||
)}</span>`
|
||||
]
|
||||
: []),
|
||||
...(others.length
|
||||
? [
|
||||
`<span class="opacity-60">${escape(
|
||||
$i18n.t('Before: {{statuses}}', {
|
||||
statuses: others
|
||||
.map(([id, seconds]) => `${nameOf(id)} ${span(seconds)}`)
|
||||
.join(' · ')
|
||||
})
|
||||
)}</span>`
|
||||
]
|
||||
: [])
|
||||
].join('<br>');
|
||||
</script>
|
||||
|
||||
{#if chat.status_since && chat.status}
|
||||
<Tooltip content={tip} placement="top" allowHTML as="span" className="flex shrink-0">
|
||||
<span class="text-[0.6875rem] tabular-nums text-gray-400 dark:text-gray-500 {className}"
|
||||
>{formatElapsedShort(chat.status_since)}</span
|
||||
>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
@@ -0,0 +1,261 @@
|
||||
<script lang="ts">
|
||||
import { getContext, tick } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { newStatusId, statusGlyphs, type CustomStatus, type StatusDef } from '$lib/utils/folders';
|
||||
import { colorDot, tagColors } from '$lib/utils/tags';
|
||||
import Modal from '$lib/components/common/Modal.svelte';
|
||||
import Dropdown from '$lib/components/common/Dropdown.svelte';
|
||||
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
|
||||
import EmojiPicker from '$lib/components/common/EmojiPicker.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import Check from '$lib/components/icons/Check.svelte';
|
||||
import StatusIcon from './FolderStatusIcon.svelte';
|
||||
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
|
||||
export let show = false;
|
||||
export let statuses: StatusDef[] = [];
|
||||
export let onSave: (statuses: CustomStatus[]) => Promise<void>;
|
||||
|
||||
let draft: CustomStatus[] = [];
|
||||
let saving = false;
|
||||
let list: HTMLDivElement;
|
||||
let wasOpen = false;
|
||||
let dragId = '';
|
||||
|
||||
const glyphLabels: Record<string, string> = {
|
||||
backlog: 'Dashed',
|
||||
todo: 'Ring',
|
||||
in_progress: 'Half',
|
||||
waiting: 'Three quarters',
|
||||
done: 'Done'
|
||||
};
|
||||
|
||||
// Start a fresh draft each time the modal opens.
|
||||
$: {
|
||||
if (show && !wasOpen)
|
||||
draft = statuses
|
||||
.filter((item) => item.custom)
|
||||
.map(({ id, name, glyph, color, icon }) => ({ id, name, glyph, color, icon }));
|
||||
wasOpen = show;
|
||||
}
|
||||
|
||||
const update = (id: string, patch: Partial<CustomStatus>) =>
|
||||
(draft = draft.map((item) => (item.id === id ? { ...item, ...patch } : item)));
|
||||
|
||||
async function add() {
|
||||
draft = [...draft, { id: newStatusId(), name: '', glyph: 'todo', color: 'gray' }];
|
||||
await tick();
|
||||
[...(list?.querySelectorAll<HTMLInputElement>('input[data-status-name]') ?? [])]
|
||||
.at(-1)
|
||||
?.focus();
|
||||
}
|
||||
|
||||
function reorder(overId: string) {
|
||||
if (!dragId || dragId === overId) return;
|
||||
const from = draft.findIndex((item) => item.id === dragId);
|
||||
const to = draft.findIndex((item) => item.id === overId);
|
||||
if (from < 0 || to < 0) return;
|
||||
const next = [...draft];
|
||||
next.splice(to, 0, ...next.splice(from, 1));
|
||||
draft = next;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const cleaned = draft
|
||||
.map((item) => ({ ...item, name: item.name.trim() }))
|
||||
.filter((item) => item.name);
|
||||
const names = cleaned.map((item) => item.name.toLowerCase());
|
||||
if (
|
||||
new Set(names).size !== names.length ||
|
||||
names.includes($i18n.t('No status').toLowerCase())
|
||||
) {
|
||||
toast.error($i18n.t('Status names must be unique.'));
|
||||
return;
|
||||
}
|
||||
saving = true;
|
||||
try {
|
||||
await onSave(cleaned);
|
||||
show = false;
|
||||
} catch (error) {
|
||||
toast.error(String(error));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal size="sm" bind:show ariaLabel={$i18n.t('Statuses')}>
|
||||
<div class="px-4 pt-3 pb-4 dark:text-gray-200">
|
||||
<div class="flex items-center justify-between pb-2 dark:text-gray-300">
|
||||
<div class="text-sm">{$i18n.t('Statuses')}</div>
|
||||
<button
|
||||
aria-label={$i18n.t('Close')}
|
||||
class="rounded-lg py-1 text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
|
||||
on:click={() => (show = false)}><XMark className="size-4" /></button
|
||||
>
|
||||
</div>
|
||||
|
||||
<form on:submit|preventDefault={save}>
|
||||
<div bind:this={list} class="max-h-[60vh] overflow-y-auto">
|
||||
<div class="flex h-8 items-center gap-2 px-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
<span class="w-3 shrink-0"></span>
|
||||
<span class="flex size-6 items-center justify-center"><StatusIcon /></span>
|
||||
<span class="flex-1">{$i18n.t('No status')}</span>
|
||||
<span class="text-xs text-gray-400 dark:text-gray-500">{$i18n.t('Default')}</span>
|
||||
</div>
|
||||
|
||||
{#each draft as item (item.id)}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="group flex h-8 items-center gap-2 rounded-lg px-1 transition-opacity {dragId ===
|
||||
item.id
|
||||
? 'opacity-40'
|
||||
: ''}"
|
||||
draggable={dragId === item.id}
|
||||
on:dragstart={(event) => {
|
||||
if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move';
|
||||
}}
|
||||
on:dragover|preventDefault={() => reorder(item.id)}
|
||||
on:dragend={() => (dragId = '')}
|
||||
>
|
||||
<span
|
||||
class="flex w-3 shrink-0 cursor-grab justify-center text-gray-300 opacity-0 transition group-hover:opacity-100 dark:text-gray-600"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
aria-label={$i18n.t('Reorder')}
|
||||
on:pointerdown={() => (dragId = item.id)}
|
||||
on:pointerup={() => (dragId = '')}
|
||||
>
|
||||
<svg class="size-3" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true"
|
||||
><circle cx="4" cy="3" r="1" /><circle cx="8" cy="3" r="1" /><circle
|
||||
cx="4"
|
||||
cy="6"
|
||||
r="1"
|
||||
/><circle cx="8" cy="6" r="1" /><circle cx="4" cy="9" r="1" /><circle
|
||||
cx="8"
|
||||
cy="9"
|
||||
r="1"
|
||||
/></svg
|
||||
>
|
||||
</span>
|
||||
|
||||
<Dropdown align="start">
|
||||
<button
|
||||
type="button"
|
||||
class="flex size-6 shrink-0 items-center justify-center rounded-lg transition hover:bg-gray-50 dark:hover:bg-gray-850"
|
||||
aria-label={$i18n.t('Change status icon')}
|
||||
title={$i18n.t('Change status icon')}
|
||||
>
|
||||
<StatusIcon glyph={item.glyph} color={item.color} emoji={item.icon} />
|
||||
</button>
|
||||
<DropdownMenu slot="content" className="w-48">
|
||||
<div class="px-2 pt-1.5 pb-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('Icon')}
|
||||
</div>
|
||||
<div class="flex gap-0.5 px-1 pb-1">
|
||||
{#each statusGlyphs as glyph}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitemradio"
|
||||
aria-checked={!item.icon && item.glyph === glyph}
|
||||
aria-label={$i18n.t(glyphLabels[glyph])}
|
||||
title={$i18n.t(glyphLabels[glyph])}
|
||||
class="flex size-7 items-center justify-center rounded-lg transition hover:bg-gray-50 dark:hover:bg-gray-800 {!item.icon &&
|
||||
item.glyph === glyph
|
||||
? 'bg-gray-50 dark:bg-gray-800'
|
||||
: ''}"
|
||||
on:click={() => update(item.id, { glyph, icon: undefined })}
|
||||
>
|
||||
<StatusIcon {glyph} color={item.color} />
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="px-2 pt-0.5 pb-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('Color')}
|
||||
</div>
|
||||
<div class="grid grid-cols-8 gap-0.5 px-1 pb-1">
|
||||
{#each tagColors as color}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitemradio"
|
||||
aria-checked={item.color === color}
|
||||
aria-label={$i18n.t(color)}
|
||||
title={$i18n.t(color)}
|
||||
class="flex size-5 items-center justify-center rounded-md hover:bg-gray-50 dark:hover:bg-gray-800"
|
||||
on:click={() => update(item.id, { color, icon: undefined })}
|
||||
>
|
||||
<span
|
||||
class="size-2.5 rounded-full {colorDot(color)} {item.color === color &&
|
||||
!item.icon
|
||||
? 'ring-2 ring-gray-300 ring-offset-1 ring-offset-white dark:ring-gray-600 dark:ring-offset-gray-850'
|
||||
: ''}"
|
||||
></span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<hr class="border-gray-50/30 dark:border-gray-800/30" />
|
||||
<EmojiPicker
|
||||
side="bottom"
|
||||
selected={item.icon ?? null}
|
||||
onSubmit={(icon: string | null) => update(item.id, { icon: icon ?? undefined })}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-[1.6875rem] w-full items-center gap-2 rounded-xl px-2 text-[0.8125rem] hover:bg-gray-50/60 dark:hover:bg-gray-800/60"
|
||||
>
|
||||
<span class="flex-1 text-left">{$i18n.t('Use emoji…')}</span>
|
||||
{#if item.icon}<Check className="size-3! shrink-0" />{/if}
|
||||
</button>
|
||||
</EmojiPicker>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
|
||||
<input
|
||||
data-status-name
|
||||
class="min-w-0 flex-1 bg-transparent text-sm outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700"
|
||||
placeholder={$i18n.t('Status name')}
|
||||
maxlength="40"
|
||||
value={item.name}
|
||||
on:input={(event) => update(item.id, { name: event.currentTarget.value })}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg p-1 text-gray-400 opacity-0 transition group-hover:opacity-100 group-focus-within:opacity-100 hover:text-gray-700 dark:hover:text-gray-200"
|
||||
aria-label={$i18n.t('Delete status')}
|
||||
on:click={() => (draft = draft.filter((entry) => entry.id !== item.id))}
|
||||
><XMark className="size-3.5" /></button
|
||||
>
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-full items-center gap-2 rounded-lg px-1 text-sm text-gray-500 transition hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
|
||||
on:click={add}
|
||||
>
|
||||
<span class="w-3 shrink-0"></span>
|
||||
<span class="flex size-6 items-center justify-center"><Plus className="size-3.5" /></span>
|
||||
{$i18n.t('Add status')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="mt-2 text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('Chats in a deleted status go back to “No status”.')}
|
||||
</p>
|
||||
|
||||
<div class="mt-3 flex justify-end">
|
||||
<button
|
||||
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-gray-900 px-2.5 text-xs font-normal text-white transition hover:bg-black disabled:cursor-not-allowed disabled:opacity-60 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
>
|
||||
{$i18n.t('Save')}
|
||||
{#if saving}<Spinner className="size-3" />{/if}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,242 @@
|
||||
<script lang="ts">
|
||||
import { getContext, tick } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { tags as userTags } from '$lib/stores';
|
||||
import { addTagById, deleteTagById, getAllTags, updateTagColorById } from '$lib/apis/chats';
|
||||
import type { WorkspaceChat } from '$lib/utils/folders';
|
||||
import { colorDot, tagColor, tagColors, tagDot, type FolderTag } from '$lib/utils/tags';
|
||||
import Dropdown from '$lib/components/common/Dropdown.svelte';
|
||||
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
|
||||
import Check from '$lib/components/icons/Check.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
|
||||
export let chat: WorkspaceChat;
|
||||
export let max = 2;
|
||||
export let onChange: () => Promise<void> = async () => {};
|
||||
|
||||
let show = false;
|
||||
let query = '';
|
||||
let busy = false;
|
||||
let input: HTMLInputElement;
|
||||
let assigned: FolderTag[] = [];
|
||||
|
||||
$: assigned = chat.tags ?? [];
|
||||
$: needle = query.trim().toLowerCase();
|
||||
$: options = [
|
||||
...assigned,
|
||||
...(($userTags ?? []) as FolderTag[]).filter(
|
||||
(tag) => !assigned.some((item) => item.id === tag.id)
|
||||
)
|
||||
].filter((tag) => tag.name.toLowerCase().includes(needle));
|
||||
$: canCreate =
|
||||
needle &&
|
||||
needle !== 'none' &&
|
||||
![...assigned, ...(($userTags ?? []) as FolderTag[])].some(
|
||||
(tag) => tag.id === needle.replaceAll(' ', '_') || tag.name.toLowerCase() === needle
|
||||
);
|
||||
|
||||
const isAssigned = (tag: FolderTag) => assigned.some((item) => item.id === tag.id);
|
||||
|
||||
async function mutate(action: () => Promise<FolderTag[]>, reset = false) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
assigned = await action();
|
||||
if (reset) query = '';
|
||||
$userTags = await getAllTags(localStorage.token);
|
||||
await onChange();
|
||||
} catch (error) {
|
||||
toast.error(String(error));
|
||||
} finally {
|
||||
busy = false;
|
||||
input?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = (tag: FolderTag) =>
|
||||
mutate(() =>
|
||||
isAssigned(tag)
|
||||
? deleteTagById(localStorage.token, chat.id, tag.name)
|
||||
: addTagById(localStorage.token, chat.id, tag.name)
|
||||
);
|
||||
|
||||
async function opened(open: boolean) {
|
||||
if (!open) return;
|
||||
query = '';
|
||||
await tick();
|
||||
input?.focus();
|
||||
try {
|
||||
$userTags = await getAllTags(localStorage.token);
|
||||
} catch (error) {
|
||||
toast.error(String(error));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet pills()}
|
||||
{#each assigned.slice(0, max) as tag (tag.id)}
|
||||
<span
|
||||
class="inline-flex h-5 min-w-0 max-w-28 items-center gap-1.5 rounded-full border border-gray-100/60 pl-2 pr-1.25 text-[0.6875rem] text-gray-600 dark:border-gray-800/60 dark:text-gray-300"
|
||||
title={tag.name}
|
||||
>
|
||||
<span class="size-1.5 shrink-0 rounded-full {tagDot(tag)}"></span>
|
||||
<span class="truncate">{tag.name}</span>
|
||||
</span>
|
||||
{/each}
|
||||
{#if assigned.length > max}
|
||||
<span
|
||||
class="inline-flex h-5 shrink-0 items-center rounded-full border border-gray-100/60 px-1.5 text-[0.6875rem] text-gray-500 dark:border-gray-800/60 dark:text-gray-400"
|
||||
title={assigned
|
||||
.slice(max)
|
||||
.map((tag) => tag.name)
|
||||
.join(', ')}>+{assigned.length - max}</span
|
||||
>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#if chat.can_edit_tags}
|
||||
<Dropdown bind:show onOpenChange={opened} align="end">
|
||||
<button
|
||||
type="button"
|
||||
class="flex min-w-0 items-center gap-1 rounded-full"
|
||||
aria-label={$i18n.t('Edit tags for {{title}}', { title: chat.title })}
|
||||
title={assigned.length ? undefined : $i18n.t('Add tags')}
|
||||
>
|
||||
{@render pills()}
|
||||
{#if !assigned.length}
|
||||
<span
|
||||
class="tag-add flex h-5 items-center gap-1 rounded-full border border-dashed border-gray-200 px-1.5 text-[0.6875rem] text-gray-400 transition-colors hover:border-gray-300 hover:text-gray-600 dark:border-gray-700 dark:text-gray-500 dark:hover:text-gray-300"
|
||||
class:open={show}
|
||||
>
|
||||
<Plus className="size-2.5" strokeWidth="2" />{$i18n.t('Tag')}
|
||||
</span>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<DropdownMenu slot="content" className="w-52 text-gray-700 dark:text-gray-200">
|
||||
<form
|
||||
on:submit|preventDefault={() => {
|
||||
const exact = options.find((tag) => tag.name.toLowerCase() === needle);
|
||||
if (exact) void toggle(exact);
|
||||
else if (canCreate)
|
||||
void mutate(() => addTagById(localStorage.token, chat.id, query.trim()), true);
|
||||
}}
|
||||
>
|
||||
<input
|
||||
bind:this={input}
|
||||
class="h-7 w-full bg-transparent px-2 text-xs outline-none placeholder:text-gray-400 dark:placeholder:text-gray-500"
|
||||
aria-label={$i18n.t('Find or create a tag')}
|
||||
placeholder={$i18n.t('Add tags…')}
|
||||
maxlength="64"
|
||||
bind:value={query}
|
||||
disabled={busy}
|
||||
/>
|
||||
</form>
|
||||
|
||||
<div class="max-h-56 overflow-y-auto pt-0.5" role="group" aria-label={$i18n.t('Tags')}>
|
||||
{#each options as tag (tag.id)}
|
||||
{@const checked = isAssigned(tag)}
|
||||
<div
|
||||
class="group/tag flex h-[1.6875rem] items-center rounded-xl pr-1 hover:bg-gray-50/60 dark:hover:bg-gray-800/60"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitemcheckbox"
|
||||
aria-checked={checked}
|
||||
class="flex h-full min-w-0 flex-1 items-center gap-2 px-2 text-[0.8125rem]"
|
||||
disabled={busy}
|
||||
on:click={() => toggle(tag)}
|
||||
>
|
||||
<span
|
||||
class="flex size-3 shrink-0 items-center justify-center rounded-[0.25rem] border transition-colors {checked
|
||||
? 'border-gray-800 bg-gray-800 text-white dark:border-gray-100 dark:bg-gray-100 dark:text-gray-900'
|
||||
: 'border-gray-300 dark:border-gray-600'}"
|
||||
>
|
||||
{#if checked}<Check className="size-2" strokeWidth="3.5" />{/if}
|
||||
</span>
|
||||
<span class="size-1.5 shrink-0 rounded-full {tagDot(tag)}"></span>
|
||||
<span class="min-w-0 flex-1 truncate text-left">{tag.name}</span>
|
||||
</button>
|
||||
{#if checked}
|
||||
<Dropdown align="end" closeOnSelect>
|
||||
<button
|
||||
type="button"
|
||||
class="flex size-5 items-center justify-center rounded-md opacity-0 transition hover:bg-gray-100 focus-visible:opacity-100 group-hover/tag:opacity-100 dark:hover:bg-gray-800"
|
||||
aria-label={$i18n.t('Color for {{tag}}', { tag: tag.name })}
|
||||
title={$i18n.t('Applies wherever you use this tag')}
|
||||
disabled={busy}
|
||||
>
|
||||
<span
|
||||
class="size-2 rounded-full ring-2 ring-white dark:ring-gray-850 {tagDot(tag)}"
|
||||
></span>
|
||||
</button>
|
||||
<div
|
||||
slot="content"
|
||||
class="z-50 grid grid-cols-4 gap-0.5 rounded-xl border border-gray-100 bg-white p-1 shadow-lg dark:border-gray-800 dark:bg-gray-850"
|
||||
>
|
||||
{#each tagColors as color}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitemradio"
|
||||
aria-checked={tagColor(tag) === color}
|
||||
aria-label={$i18n.t(color)}
|
||||
title={$i18n.t(color)}
|
||||
class="flex size-5 items-center justify-center rounded-md hover:bg-gray-50 dark:hover:bg-gray-800"
|
||||
disabled={busy}
|
||||
on:click={() =>
|
||||
mutate(() =>
|
||||
updateTagColorById(localStorage.token, chat.id, tag.name, color)
|
||||
)}
|
||||
>
|
||||
<span
|
||||
class="size-2.5 rounded-full {colorDot(color)} {tagColor(tag) === color
|
||||
? 'ring-2 ring-gray-300 ring-offset-1 ring-offset-white dark:ring-gray-600 dark:ring-offset-gray-850'
|
||||
: ''}"
|
||||
></span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</Dropdown>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if canCreate}
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-[1.6875rem] w-full items-center gap-2 rounded-xl px-2 text-left text-[0.8125rem] hover:bg-gray-50/60 dark:hover:bg-gray-800/60"
|
||||
disabled={busy}
|
||||
on:click={() =>
|
||||
mutate(() => addTagById(localStorage.token, chat.id, query.trim()), true)}
|
||||
>
|
||||
<Plus className="size-3 text-gray-400" />
|
||||
<span class="min-w-0 truncate"
|
||||
>{$i18n.t('Create “{{name}}”', { name: query.trim() })}</span
|
||||
>
|
||||
</button>
|
||||
{:else if !options.length}
|
||||
<div class="px-2 py-1.5 text-xs text-gray-400 dark:text-gray-500">
|
||||
{$i18n.t('No tags yet. Type to create one.')}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
{:else if assigned.length}
|
||||
<div class="flex min-w-0 items-center gap-1">{@render pills()}</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@media (hover: hover) {
|
||||
.tag-add {
|
||||
opacity: 0;
|
||||
}
|
||||
.tag-add.open,
|
||||
:global([data-folder-item]:hover) .tag-add,
|
||||
:global([data-folder-item]:focus-within) .tag-add {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,8 +2,6 @@
|
||||
import { getContext } from 'svelte';
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
import fileSaver from 'file-saver';
|
||||
const { saveAs } = fileSaver;
|
||||
|
||||
@@ -14,33 +12,28 @@
|
||||
loadFolderDetails,
|
||||
updateFolderDetails,
|
||||
removeFolderState,
|
||||
type FolderDetails,
|
||||
type FolderDetails
|
||||
} from '$lib/stores/folderStates';
|
||||
|
||||
import {
|
||||
deleteFolderById,
|
||||
updateFolderById,
|
||||
createNewFolder
|
||||
} from '$lib/apis/folders';
|
||||
import { deleteFolderById, updateFolderById, createNewFolder } from '$lib/apis/folders';
|
||||
import { getChatsByFolderId } from '$lib/apis/chats';
|
||||
|
||||
import FolderModal from '$lib/components/layout/Sidebar/Folders/FolderModal.svelte';
|
||||
|
||||
import Folder from '$lib/components/icons/Folder.svelte';
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
import FolderMenu from '$lib/components/layout/Sidebar/Folders/FolderMenu.svelte';
|
||||
import EllipsisHorizontal from '$lib/components/icons/EllipsisHorizontal.svelte';
|
||||
import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
||||
import Emoji from '$lib/components/common/Emoji.svelte';
|
||||
import EmojiPicker from '$lib/components/common/EmojiPicker.svelte';
|
||||
|
||||
export let folder: FolderDetails | null = null;
|
||||
export let readOnly: boolean = false;
|
||||
export let onNewChat: () => void = () => {};
|
||||
export let folderTabActions: import('svelte').Snippet | undefined = undefined;
|
||||
$: folderTabActions = renderFolderActions;
|
||||
|
||||
export let onUpdate: Function = (folderId) => {};
|
||||
export let onDelete: Function = (folderId) => {};
|
||||
|
||||
let showFolderModal = false;
|
||||
export let showFolderModal = false;
|
||||
let showCreateSubFolderModal = false;
|
||||
let showDeleteConfirm = false;
|
||||
let deleteFolderContents = true;
|
||||
@@ -78,39 +71,12 @@
|
||||
|
||||
toast.success($i18n.t('Folder updated successfully'));
|
||||
|
||||
const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch((error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
});
|
||||
|
||||
const updatedFolder = { ...targetFolder, ..._folder };
|
||||
if ($selectedFolder?.id === targetFolder.id) selectedFolder.set(updatedFolder);
|
||||
onUpdate(updatedFolder);
|
||||
}
|
||||
};
|
||||
|
||||
const updateIconHandler = async (iconName) => {
|
||||
const targetFolder = folder;
|
||||
if (!targetFolder) return;
|
||||
const res = await updateFolderById(localStorage.token, targetFolder.id, {
|
||||
meta: {
|
||||
icon: iconName ?? ''
|
||||
}
|
||||
}).catch((error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (res) {
|
||||
updateFolderDetails(targetFolder.id, res);
|
||||
targetFolder.meta = { ...targetFolder.meta, icon: iconName ?? '' };
|
||||
|
||||
toast.success($i18n.t('Folder updated successfully'));
|
||||
|
||||
const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch((error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
});
|
||||
const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch(
|
||||
(error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
}
|
||||
);
|
||||
|
||||
const updatedFolder = { ...targetFolder, ..._folder };
|
||||
if ($selectedFolder?.id === targetFolder.id) selectedFolder.set(updatedFolder);
|
||||
@@ -121,12 +87,14 @@
|
||||
const deleteHandler = async () => {
|
||||
const targetFolder = folder;
|
||||
if (!targetFolder) return;
|
||||
const res = await deleteFolderById(localStorage.token, targetFolder.id, deleteFolderContents).catch(
|
||||
(error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
}
|
||||
);
|
||||
const res = await deleteFolderById(
|
||||
localStorage.token,
|
||||
targetFolder.id,
|
||||
deleteFolderContents
|
||||
).catch((error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (res) {
|
||||
removeFolderState(targetFolder.id);
|
||||
@@ -175,6 +143,35 @@
|
||||
};
|
||||
</script>
|
||||
|
||||
{#snippet renderFolderActions()}
|
||||
{#if folder && !readOnly}
|
||||
<div class="flex shrink-0 items-center">
|
||||
<FolderMenu
|
||||
align="end"
|
||||
{onNewChat}
|
||||
onEdit={() => {
|
||||
showFolderModal = true;
|
||||
}}
|
||||
onDelete={() => {
|
||||
showDeleteConfirm = true;
|
||||
}}
|
||||
onExport={() => {
|
||||
exportHandler();
|
||||
}}
|
||||
onCreateSubFolder={() => {
|
||||
showCreateSubFolderModal = true;
|
||||
}}
|
||||
>
|
||||
<div
|
||||
class="flex size-4 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-700 dark:hover:bg-white/10 dark:hover:text-white"
|
||||
>
|
||||
<EllipsisHorizontal className="size-3" strokeWidth="1.5" />
|
||||
</div>
|
||||
</FolderMenu>
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#if folder}
|
||||
<FolderModal
|
||||
bind:show={showFolderModal}
|
||||
@@ -218,81 +215,4 @@
|
||||
</div>
|
||||
</div>
|
||||
</DeleteConfirmDialog>
|
||||
|
||||
<div
|
||||
class="{folder.data?.description
|
||||
? 'mb-0.5'
|
||||
: 'mb-2'} px-5 @md:max-w-3xl justify-between w-full flex relative group items-center"
|
||||
>
|
||||
<div class="text-center flex gap-3.5 items-center">
|
||||
{#if readOnly}
|
||||
<div
|
||||
class="rounded-full bg-gray-50/50 dark:bg-gray-800/40 size-11 flex justify-center items-center"
|
||||
>
|
||||
{#if folder?.meta?.icon}
|
||||
<Emoji className="size-7" shortCode={folder.meta.icon} />
|
||||
{:else}
|
||||
<Folder className="size-6" strokeWidth="2" />
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<EmojiPicker
|
||||
onClose={() => {}}
|
||||
selected={folder?.meta?.icon ?? null}
|
||||
onSubmit={(name) => {
|
||||
console.log(name);
|
||||
updateIconHandler(name);
|
||||
}}
|
||||
>
|
||||
<button
|
||||
aria-label={$i18n.t('Change folder icon')}
|
||||
class="rounded-full bg-gray-50/50 dark:bg-gray-800/40 size-11 flex justify-center items-center outline-hidden focus:outline-hidden"
|
||||
>
|
||||
{#if folder?.meta?.icon}
|
||||
<Emoji className="size-7" shortCode={folder.meta.icon} />
|
||||
{:else}
|
||||
<Folder className="size-6" strokeWidth="2" />
|
||||
{/if}
|
||||
</button>
|
||||
</EmojiPicker>
|
||||
{/if}
|
||||
|
||||
<div class="text-3xl line-clamp-1">
|
||||
{folder.name}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if !readOnly}
|
||||
<div class="flex items-center translate-x-2.5">
|
||||
<FolderMenu
|
||||
align="end"
|
||||
onEdit={() => {
|
||||
showFolderModal = true;
|
||||
}}
|
||||
onDelete={() => {
|
||||
showDeleteConfirm = true;
|
||||
}}
|
||||
onExport={() => {
|
||||
exportHandler();
|
||||
}}
|
||||
onCreateSubFolder={() => {
|
||||
showCreateSubFolderModal = true;
|
||||
}}
|
||||
>
|
||||
<div class="inline-flex p-1.5 dark:hover:bg-gray-850 rounded-full touch-auto">
|
||||
<EllipsisHorizontal className="size-4" strokeWidth="2.5" />
|
||||
</div>
|
||||
</FolderMenu>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if folder.data?.description}
|
||||
<!-- Align with the title after the row padding, icon, and gap. -->
|
||||
<div
|
||||
class="mb-2 w-full pl-[4.875rem] pr-6 text-left text-sm text-gray-400 dark:text-gray-500 @md:max-w-3xl"
|
||||
>
|
||||
<p class="line-clamp-2 whitespace-pre-wrap break-words">{folder.data.description}</p>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { get } from 'svelte/store';
|
||||
import { socket, selectedFolder } from '$lib/stores';
|
||||
import { updateFolderChatLists } from '$lib/stores/folderStates';
|
||||
import type { AppLayoutContext } from '$lib/types';
|
||||
import type { WorkspaceChat } from '$lib/utils/folders';
|
||||
|
||||
const wantsBrowserTab = (event?: MouseEvent) =>
|
||||
!!event && (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0);
|
||||
|
||||
function markRead(chat: WorkspaceChat) {
|
||||
updateFolderChatLists({ id: chat.id, last_read_at: Date.now() / 1000 });
|
||||
get(socket)?.emit('events:chat', { chat_id: chat.id, data: { type: 'last_read_at' } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a chat from the folder view in an internal tab beside it, the same way mention
|
||||
* links open pages. Modifier clicks keep the browser's new-tab behaviour.
|
||||
*/
|
||||
export function openFolderChat(
|
||||
chat: WorkspaceChat,
|
||||
appLayout: AppLayoutContext | undefined,
|
||||
event?: MouseEvent
|
||||
) {
|
||||
markRead(chat);
|
||||
const href = `/c/${chat.id}`;
|
||||
if (wantsBrowserTab(event)) {
|
||||
// A link handles its own modifier click; anywhere else on the row needs a hand.
|
||||
if (!(event?.target as Element | null)?.closest('a')) window.open(href, '_blank', 'noopener');
|
||||
return;
|
||||
}
|
||||
event?.preventDefault();
|
||||
if (appLayout?.openPageTab) {
|
||||
appLayout.openPageTab({ href, label: chat.title });
|
||||
} else {
|
||||
selectedFolder.set(null);
|
||||
void goto(href);
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@
|
||||
import Dropdown from '../common/Dropdown.svelte';
|
||||
import DropdownMenu from '../common/DropdownMenu.svelte';
|
||||
import Icon from './FileNav/Icon.svelte';
|
||||
import Emoji from '$lib/components/common/Emoji.svelte';
|
||||
import Annotation from '$lib/components/icons/Annotation.svelte';
|
||||
import HomeIcon from '$lib/components/icons/Home.svelte';
|
||||
import HashtagIcon from '$lib/components/icons/Hashtag.svelte';
|
||||
@@ -159,6 +160,8 @@
|
||||
export let mainChatGroupId = '';
|
||||
let paneCanvas: HTMLDivElement;
|
||||
export let title = '';
|
||||
export let mainTabFolder: { id: string; name: string; icon?: string | null } | null = null;
|
||||
$: mainTabTitle = mainTabFolder?.name ?? title;
|
||||
export let mainChatHref = '/';
|
||||
export let tabTitleEditor: import('svelte').Snippet | undefined = undefined;
|
||||
export let tabActions: import('svelte').Snippet | undefined = undefined;
|
||||
@@ -293,7 +296,7 @@
|
||||
if (version !== switchVersion) return;
|
||||
// The chat restores its terminal and directory together; layouts must not override them.
|
||||
owner.state.selectedTerminalId = $selectedTerminalId;
|
||||
owner.state.panels = setMainChatTab(owner.state.panels, true, title);
|
||||
owner.state.panels = setMainChatTab(owner.state.panels, true, mainTabTitle);
|
||||
tabs = owner.state.panels;
|
||||
dirtyFiles = {};
|
||||
fileContexts = {};
|
||||
@@ -2184,10 +2187,11 @@
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if viewReady && !chatLoading && !viewError && !tabs.tabs.length && canOpenNewTab}<div
|
||||
class="flex h-full items-center justify-center p-4 text-center text-xs text-gray-400"
|
||||
<!-- The mobile drawer hides the main chat tab, so count what it actually shows. -->
|
||||
{#if viewReady && !chatLoading && !viewError && !displayTabs.tabs.length && (canOpenNewTab || !largeScreen)}<div
|
||||
class="flex h-full items-center justify-center p-3 text-center text-xs text-gray-500 dark:text-gray-400"
|
||||
>
|
||||
{$i18n.t('Open a tab using the + menu.')}
|
||||
{canOpenNewTab ? $i18n.t('Open a tab using the + menu.') : $i18n.t('No open tabs')}
|
||||
</div>{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -2246,13 +2250,19 @@
|
||||
aria-controls={`${domId(tab.id)}-view`}
|
||||
aria-selected={group.activeId === tab.id}
|
||||
tabindex={group.activeId === tab.id ? 0 : -1}
|
||||
title={tab.kind === 'chat' ? title : (tab.directory ?? tab.path ?? tabLabel(tab))}
|
||||
aria-label={tab.kind === 'chat' ? title : undefined}
|
||||
title={tab.kind === 'chat' ? mainTabTitle : (tab.directory ?? tab.path ?? tabLabel(tab))}
|
||||
aria-label={tab.kind === 'chat' ? mainTabTitle : undefined}
|
||||
class="flex h-full items-center gap-1.5 min-w-0"
|
||||
>
|
||||
{#if (tab.kind === 'chat' && chatStreaming) || (tab.kind === 'side' && sideChatStreaming[tab.id])}
|
||||
<Spinner className="size-3.5" />
|
||||
<span class="sr-only">{$i18n.t('Generating...')}</span>
|
||||
{:else if tab.kind === 'chat' && mainTabFolder}
|
||||
{#if mainTabFolder.icon}
|
||||
<Emoji shortCode={mainTabFolder.icon} className="size-3.5" />
|
||||
{:else}
|
||||
<Icon name="folder" size={14} />
|
||||
{/if}
|
||||
{:else if tab.kind === 'file'}
|
||||
<Icon name={fileIconName(tab.label)} size={14} strokeWidth={1.4} />
|
||||
{:else if tab.kind === 'comments'}
|
||||
@@ -2262,9 +2272,9 @@
|
||||
{:else}
|
||||
<Icon name={tabIcon(tab.kind)} size={14} />
|
||||
{/if}
|
||||
{#if tab.kind !== 'chat' || !tabTitleEditor}
|
||||
{#if tab.kind !== 'chat' || !tabTitleEditor || mainTabFolder}
|
||||
<span class="max-w-30 overflow-hidden text-ellipsis"
|
||||
>{tab.kind === 'chat' ? title : tabLabel(tab)}</span
|
||||
>{tab.kind === 'chat' ? mainTabTitle : tabLabel(tab)}</span
|
||||
>
|
||||
{/if}
|
||||
{#if tab.kind === 'comments' && commentCount}<span class="text-gray-400"
|
||||
@@ -2276,7 +2286,7 @@
|
||||
aria-label={$i18n.t('Unsaved changes')}
|
||||
></span>{/if}
|
||||
{#if tab.kind === 'chat'}
|
||||
{@render tabTitleEditor?.()}
|
||||
{#if !mainTabFolder}{@render tabTitleEditor?.()}{/if}
|
||||
{@render tabActions?.()}
|
||||
{:else}<button
|
||||
type="button"
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
export let side = 'top';
|
||||
export let align = 'start';
|
||||
export let user = null;
|
||||
export let selected = null;
|
||||
export let selected: string | null = null;
|
||||
|
||||
const MAX_RECENT = 30;
|
||||
|
||||
|
||||
@@ -948,6 +948,9 @@
|
||||
if (event.data?.type === 'chat:active') {
|
||||
updateFolderChatLists({ id: event.chat_id, active: event.data.data?.active ?? false, pending_approval: event.data.data?.pending_approval ?? false });
|
||||
const eventData = event.data.data ?? {};
|
||||
if (eventData.folder_unread_counts) {
|
||||
applyFolderUnreadCounts(eventData.folder_unread_counts);
|
||||
}
|
||||
const active = eventData.active ?? false;
|
||||
const pendingApproval = eventData.pending_approval ?? false;
|
||||
const found = setChatActive(event.chat_id, active, pendingApproval);
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
{/if}
|
||||
{#if !folder.shared && (folder.unread_count ?? 0) > 0}
|
||||
<span>·</span>
|
||||
<span>{folder.unread_count.toLocaleString()} {$i18n.t('Unread')}</span>
|
||||
<span>{folder.unread_count.toLocaleString()} {$i18n.t('Unread or waiting for approval')}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
import Modal from '$lib/components/common/Modal.svelte';
|
||||
import AccessButton from '$lib/components/common/AccessButton.svelte';
|
||||
import FolderShareModal from './FolderShareModal.svelte';
|
||||
import EmojiPicker from '$lib/components/common/EmojiPicker.svelte';
|
||||
import Emoji from '$lib/components/common/Emoji.svelte';
|
||||
import FolderIcon from '$lib/components/icons/Folder.svelte';
|
||||
import XMark from '../icons/XMark.svelte';
|
||||
|
||||
import { toast } from 'svelte-sonner';
|
||||
@@ -35,8 +38,9 @@
|
||||
|
||||
let folder = null;
|
||||
let name = '';
|
||||
let meta = {
|
||||
background_image_url: null
|
||||
let meta: { background_image_url: string | null; icon: string; [key: string]: unknown } = {
|
||||
background_image_url: null,
|
||||
icon: ''
|
||||
};
|
||||
let data = {
|
||||
description: '',
|
||||
@@ -135,8 +139,10 @@
|
||||
if (!folder) return;
|
||||
|
||||
name = folder.name;
|
||||
meta = folder.meta || {
|
||||
background_image_url: null
|
||||
meta = {
|
||||
background_image_url: null,
|
||||
icon: '',
|
||||
...folder.meta
|
||||
};
|
||||
data = {
|
||||
system_prompt: '',
|
||||
@@ -173,7 +179,8 @@
|
||||
$: if (!show && !edit) {
|
||||
name = '';
|
||||
meta = {
|
||||
background_image_url: null
|
||||
background_image_url: null,
|
||||
icon: ''
|
||||
};
|
||||
data = {
|
||||
description: '',
|
||||
@@ -225,10 +232,29 @@
|
||||
>{$i18n.t('Folder Name')}</label
|
||||
>
|
||||
|
||||
<div class="flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<EmojiPicker
|
||||
side="bottom"
|
||||
selected={meta.icon || null}
|
||||
onSubmit={(icon: string | null) => { meta = { ...meta, icon: icon ?? '' }; }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex size-7 shrink-0 items-center justify-center rounded-full text-gray-500 hover:bg-gray-50/40 dark:text-gray-400 dark:hover:bg-gray-800/40"
|
||||
aria-label={$i18n.t('Change folder icon')}
|
||||
title={$i18n.t('Change folder icon')}
|
||||
disabled={loading}
|
||||
>
|
||||
{#if meta.icon}
|
||||
<Emoji shortCode={meta.icon} className="size-4" />
|
||||
{:else}
|
||||
<FolderIcon className="size-4" />
|
||||
{/if}
|
||||
</button>
|
||||
</EmojiPicker>
|
||||
<input
|
||||
id="folder-name"
|
||||
class="w-full text-sm bg-transparent placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-hidden"
|
||||
class="min-w-0 flex-1 text-sm bg-transparent placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-hidden"
|
||||
type="text"
|
||||
bind:value={name}
|
||||
placeholder={$i18n.t('Enter folder name')}
|
||||
|
||||
@@ -829,7 +829,7 @@
|
||||
{#if !folders[folderId]?.shared && (folders[folderId]?.unread_count ?? 0) > 0}
|
||||
<div
|
||||
class="inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-md bg-sky-500/10 px-1 text-[0.625rem] font-semibold leading-4 text-sky-600 dark:bg-sky-400/10 dark:text-sky-300"
|
||||
title={$i18n.t('Unread')}
|
||||
title={$i18n.t('Unread or waiting for approval')}
|
||||
>
|
||||
{formatUnreadCount(folders[folderId].unread_count)}
|
||||
</div>
|
||||
|
||||
@@ -134,7 +134,7 @@
|
||||
: ''} max-w-full"
|
||||
>
|
||||
<div class="flex h-full min-w-0 flex-1 flex-col">
|
||||
<nav class="px-1.5 drag-region select-none">
|
||||
<nav class="px-1.5 md:px-2.5 drag-region select-none">
|
||||
<div class="flex items-center gap-0.5 md:gap-1">
|
||||
{#if $mobile && !pageTab}
|
||||
<div class="{$showSidebar ? 'md:hidden' : ''} self-center flex flex-none items-center">
|
||||
|
||||
@@ -4455,6 +4455,7 @@
|
||||
"Unpin from Sidebar": "",
|
||||
"Unpushed": "",
|
||||
"Unread": "",
|
||||
"Unread or waiting for approval": "",
|
||||
"Unsaved changes": "",
|
||||
"Unsaved changes to this version will be discarded.": "",
|
||||
"Unshare All": "",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { FOLDER_PAGE_SIZE, type FolderStatus, type FolderActivity } from '$lib/utils/folders';
|
||||
import { readonly, writable } from 'svelte/store';
|
||||
import { getFolderById, getSharedFolderChats } from '$lib/apis/folders';
|
||||
import { getChatListByFolderId } from '$lib/apis/chats';
|
||||
@@ -25,6 +26,13 @@ export type FolderChatQuery = {
|
||||
page?: number;
|
||||
sortBy?: 'title' | 'updated_at' | 'unread_updated_at';
|
||||
sortDir?: 'asc' | 'desc';
|
||||
workspace?: boolean;
|
||||
search?: string;
|
||||
tagIds?: string[];
|
||||
userIds?: string[];
|
||||
status?: FolderStatus | FolderStatus[];
|
||||
activity?: FolderActivity;
|
||||
updatedAtGte?: number;
|
||||
};
|
||||
export type FolderChatPage = {
|
||||
chats: FolderChat[];
|
||||
@@ -58,7 +66,22 @@ const revision = (key: string) => revisions.get(key) ?? 0;
|
||||
const changed = (key: string) => revisions.set(key, revision(key) + 1);
|
||||
|
||||
export const folderChatPageKey = (query: FolderChatQuery = {}) =>
|
||||
JSON.stringify([query.page ?? 1, query.sortBy ?? 'unread_updated_at', query.sortDir ?? 'desc']);
|
||||
JSON.stringify([
|
||||
query.page ?? 1,
|
||||
query.sortBy ?? 'unread_updated_at',
|
||||
query.sortDir ?? 'desc',
|
||||
...(query.workspace
|
||||
? [
|
||||
true,
|
||||
query.search?.trim() ?? '',
|
||||
[...new Set(query.tagIds ?? [])].sort(),
|
||||
query.status ?? null,
|
||||
query.activity ?? null,
|
||||
query.updatedAtGte ?? null,
|
||||
[...new Set(query.userIds ?? [])].sort()
|
||||
]
|
||||
: [])
|
||||
]);
|
||||
|
||||
export function getFolderState(id: string): FolderState {
|
||||
return (entries[id] ??= { details: null, chatPages: {}, sidebarPage: 1, agentModels: null });
|
||||
@@ -154,6 +177,7 @@ export function loadFolderChatPage(
|
||||
} catch (error) {
|
||||
// Keep the sidebar's legacy fallback, but never use it to bypass access failures.
|
||||
if (
|
||||
query.workspace ||
|
||||
(query.sortBy && query.sortBy !== 'unread_updated_at') ||
|
||||
[401, 403, 404].includes((error as any)?.status)
|
||||
)
|
||||
@@ -166,12 +190,16 @@ export function loadFolderChatPage(
|
||||
return {
|
||||
...result,
|
||||
total: result.total ?? result.chats.length,
|
||||
has_more: result.has_more ?? result.chats.length === 10,
|
||||
has_more:
|
||||
result.has_more ?? result.chats.length === (query.workspace ? FOLDER_PAGE_SIZE : 10),
|
||||
dirty: false
|
||||
};
|
||||
},
|
||||
(result) => {
|
||||
folder.chatPages[key] = result;
|
||||
const searches = Object.keys(folder.chatPages).filter((key) => JSON.parse(key)[3]);
|
||||
for (const expired of searches.slice(0, Math.max(0, searches.length - 20)))
|
||||
delete folder.chatPages[expired];
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -234,7 +262,14 @@ export function updateFolderChatLists(
|
||||
? 1
|
||||
: 0;
|
||||
for (const [key, page] of Object.entries(folder.chatPages)) {
|
||||
const [number, sortBy, sortDir] = JSON.parse(key);
|
||||
const [number, sortBy, sortDir, workspace] = JSON.parse(key);
|
||||
if (workspace) {
|
||||
// Filter membership and column totals must be reconciled by the server.
|
||||
page.chats = page.chats.map((item) => (item.id === chat.id ? { ...item, ...chat } : item));
|
||||
page.dirty = true;
|
||||
changed(resourceKey(id, key));
|
||||
continue;
|
||||
}
|
||||
page.total = Math.max(0, page.total + countChange);
|
||||
page.has_more = page.total > number * 10;
|
||||
const existing = page.chats.find((item) => item.id === chat.id);
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { ChatParticipant } from '$lib/apis/folders';
|
||||
import { tagColors, type FolderTag, type TagColor } from './tags';
|
||||
|
||||
// Folder list and board views page through a folder's chats this many at a time.
|
||||
export const FOLDER_PAGE_SIZE = 50;
|
||||
export type FolderActivity = 'unread' | 'generating' | 'waiting_for_approval' | 'idle';
|
||||
|
||||
// Chats only have "No status" built in; every other status is defined per folder.
|
||||
// A chat's status is null when it has none; 'none' is only the key for that group, column and filter.
|
||||
export const NO_STATUS = 'none';
|
||||
export const statusGlyphs = ['backlog', 'todo', 'in_progress', 'waiting', 'done'] as const;
|
||||
export type StatusGlyph = (typeof statusGlyphs)[number];
|
||||
export type FolderStatus = string;
|
||||
// A status shows an emoji when `icon` is set, otherwise its glyph in its color.
|
||||
export type CustomStatus = {
|
||||
id: string;
|
||||
name: string;
|
||||
glyph?: StatusGlyph;
|
||||
color?: TagColor;
|
||||
icon?: string;
|
||||
};
|
||||
export type StatusDef = CustomStatus & { custom: boolean };
|
||||
|
||||
export const customStatuses = (meta?: { statuses?: unknown } | null): CustomStatus[] => {
|
||||
const seen = new Set<string>([NO_STATUS]);
|
||||
return (Array.isArray(meta?.statuses) ? meta.statuses : [])
|
||||
.filter(
|
||||
(item) =>
|
||||
!!item &&
|
||||
typeof item.id === 'string' &&
|
||||
typeof item.name === 'string' &&
|
||||
!seen.has(item.id) &&
|
||||
!!seen.add(item.id)
|
||||
)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
glyph: statusGlyphs.includes(item.glyph) ? item.glyph : 'todo',
|
||||
color: tagColors.includes(item.color) ? item.color : 'gray',
|
||||
icon: typeof item.icon === 'string' && item.icon ? item.icon : undefined
|
||||
}));
|
||||
};
|
||||
|
||||
// "No status" first, then the folder's statuses in its own order (matches the server).
|
||||
export const statusDefs = (
|
||||
meta: { statuses?: unknown } | null | undefined,
|
||||
t: (key: string) => string
|
||||
): StatusDef[] => [
|
||||
{ id: NO_STATUS, name: t('No status'), custom: false },
|
||||
...customStatuses(meta).map((item) => ({ ...item, custom: true }))
|
||||
];
|
||||
|
||||
export const newStatusId = () => `s_${Math.random().toString(36).slice(2, 10)}`;
|
||||
|
||||
export const glyphColor: Record<TagColor, string> = {
|
||||
gray: 'text-gray-400 dark:text-gray-500',
|
||||
blue: 'text-blue-500',
|
||||
violet: 'text-violet-500',
|
||||
pink: 'text-pink-500',
|
||||
red: 'text-red-500',
|
||||
amber: 'text-amber-500',
|
||||
green: 'text-green-500',
|
||||
teal: 'text-teal-500'
|
||||
};
|
||||
|
||||
export type WorkspaceChat = {
|
||||
id: string;
|
||||
title: string;
|
||||
user_id: string;
|
||||
owner_name?: string;
|
||||
tags: FolderTag[];
|
||||
status: FolderStatus | null;
|
||||
/** When the chat would have entered its status if all its time there were one stretch (seconds); earlier stretches count, so going back doesn't reset it. Null for no status or older chats. */
|
||||
status_since?: number | null;
|
||||
/** When the current stretch in this status began (seconds). */
|
||||
status_entered_at?: number | null;
|
||||
/** Earlier time per status, in seconds, from before the current stretch. */
|
||||
status_durations?: Record<string, number>;
|
||||
can_edit_tags: boolean;
|
||||
can_edit_status: boolean;
|
||||
updated_at: number;
|
||||
created_at: number;
|
||||
last_read_at?: number | null;
|
||||
participants?: ChatParticipant[];
|
||||
active?: boolean;
|
||||
pending_approval?: boolean;
|
||||
search_snippet?: string | null;
|
||||
};
|
||||
export const statusKey = (status?: FolderStatus | null) => status ?? NO_STATUS;
|
||||
|
||||
export type WorkspacePage = { chats: WorkspaceChat[]; total: number; has_more: boolean };
|
||||
export type FolderUser = { id: string; name: string; count: number };
|
||||
|
||||
export const isChatUnread = (chat: WorkspaceChat) =>
|
||||
(chat.last_read_at ?? 0) === 0 || chat.updated_at > (chat.last_read_at ?? 0);
|
||||
@@ -524,6 +524,34 @@ export const formatMessageTimestamp = (inputDate, locale: string) =>
|
||||
minute: '2-digit'
|
||||
}) ?? '';
|
||||
|
||||
// Compact list date: the time today, "Nov 3" this year, "Nov 3, 2024" before.
|
||||
export const formatShortDate = (seconds: number, locale: string) => {
|
||||
const date = dayjs(seconds * 1000).locale(locale);
|
||||
if (date.isSame(dayjs(), 'day')) return date.format('LT');
|
||||
return date.format(date.isSame(dayjs(), 'year') ? 'MMM D' : 'll');
|
||||
};
|
||||
|
||||
// Hover detail for a short date: "3 days ago · Monday, November 3, 2025, 2:32 PM".
|
||||
export const formatDateDetails = (seconds: number, locale: string) =>
|
||||
`${dayjs(seconds * 1000)
|
||||
.locale(locale)
|
||||
.fromNow()} · ${formatMessageTimestampFull(seconds, locale)}`;
|
||||
|
||||
// Time since a moment without "ago", e.g. "3 days" for time in a status.
|
||||
export const formatElapsed = (seconds: number, locale: string) =>
|
||||
dayjs(seconds * 1000)
|
||||
.locale(locale)
|
||||
.fromNow(true);
|
||||
|
||||
// Compact time since a moment for tight spaces: "45s", "12m", "3h", "5d".
|
||||
export const formatElapsedShort = (seconds: number) => {
|
||||
const elapsed = Math.max(0, Math.floor(Date.now() / 1000 - seconds));
|
||||
if (elapsed < 60) return `${elapsed}s`;
|
||||
if (elapsed < 3600) return `${Math.floor(elapsed / 60)}m`;
|
||||
if (elapsed < 86400) return `${Math.floor(elapsed / 3600)}h`;
|
||||
return `${Math.floor(elapsed / 86400)}d`;
|
||||
};
|
||||
|
||||
export const formatMessageTimestampFull = (inputDate, locale: string) =>
|
||||
messageTimestampDate(inputDate)?.toLocaleString(locale, {
|
||||
weekday: 'long',
|
||||
|
||||
@@ -15,3 +15,45 @@ export const normalizeTags = (tags: unknown): Tag[] =>
|
||||
.map(getTagName)
|
||||
.filter((name): name is string => typeof name === 'string' && name.trim() !== '')
|
||||
.map((name) => ({ name: name.trim() }));
|
||||
|
||||
export const tagColors = [
|
||||
'gray',
|
||||
'blue',
|
||||
'violet',
|
||||
'pink',
|
||||
'red',
|
||||
'amber',
|
||||
'green',
|
||||
'teal'
|
||||
] as const;
|
||||
export type TagColor = (typeof tagColors)[number];
|
||||
|
||||
// A chat tag as folder views show it: with its color and, in filters, how many chats use it.
|
||||
export type FolderTag = {
|
||||
id: string;
|
||||
name: string;
|
||||
color?: TagColor;
|
||||
count?: number;
|
||||
meta?: { color?: TagColor } | null;
|
||||
};
|
||||
|
||||
// The tag's chosen color, or a stable default from its id. The palette lives only here.
|
||||
export const tagColor = (tag: FolderTag): TagColor => {
|
||||
const value = tag.color ?? tag.meta?.color;
|
||||
return value && tagColors.includes(value)
|
||||
? value
|
||||
: tagColors[new TextEncoder().encode(tag.id).reduce((a, b) => a + b, 0) % tagColors.length];
|
||||
};
|
||||
|
||||
const tagDots: Record<TagColor, string> = {
|
||||
gray: 'bg-gray-400 dark:bg-gray-500',
|
||||
blue: 'bg-blue-500',
|
||||
violet: 'bg-violet-500',
|
||||
pink: 'bg-pink-500',
|
||||
red: 'bg-red-500',
|
||||
amber: 'bg-amber-500',
|
||||
green: 'bg-green-500',
|
||||
teal: 'bg-teal-500'
|
||||
};
|
||||
export const colorDot = (color: TagColor) => tagDots[color];
|
||||
export const tagDot = (tag: FolderTag) => tagDots[tagColor(tag)];
|
||||
@@ -13,7 +13,7 @@
|
||||
isCurrentFolderOpening,
|
||||
isCancelledFolderRequest,
|
||||
} from '$lib/stores/folderStates';
|
||||
import { selectedFolder } from '$lib/stores';
|
||||
import { selectedFolder, showSidebar } from '$lib/stores';
|
||||
|
||||
let ready = false;
|
||||
let loadedFolderId = '';
|
||||
@@ -57,7 +57,7 @@
|
||||
{#if ready}
|
||||
<Chat />
|
||||
{:else}
|
||||
<div class="w-full h-screen flex items-center justify-center">
|
||||
<Spinner />
|
||||
<div class="w-full h-screen max-h-[100dvh] flex items-center justify-center {$showSidebar ? 'md:max-w-[calc(100%-var(--sidebar-width))]' : ''}">
|
||||
<Spinner className="size-5" />
|
||||
</div>
|
||||
{/if}
|
||||
Reference in new issue
Block a user