mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-18 22:14:27 +00:00
🧷 style: Sidebar Row Controls, Pinned Unpin Badge and Drag Rules (#15870)
* 🔘 style: Seat Sidebar Row Actions One Radius Inside Their Row Every control that sits on a sidebar row took the base `rounded-lg`, the same radius as the row hosting it, so a hovered button filled corner to corner with its row. `row-action` and `section-action` now carry `rounded-md`, one step inside the rows, which stay as they were. Three controls also diverged from the recipe they were built on. `ConvoOptions` and the Projects heading action overrode the variant's hover fill with `surface-hover`; the rename form's save and cancel buttons answered the pointer with `hover:opacity-70` and no fill at all. All four now take the shared hover. The project row's two actions are the exception that earns its own recipe: they sit on a row that fills on hover, where the variant's hover surface reads as a second, weaker hover stacked on the first. They take `surface-active` instead, under the pointer and while the menu one of them owns is open, and sit 4px apart like a pinned chat's own pair. * 🧲 fix: Give Both Pinned Row Kinds One Unpin Badge, and Stop Its Flicker Pinned chats and pinned agents/models sit in one list and are dragged against each other, but their unpin badges were two controls: the chat's was `text-text-primary` and always visible, the favorite's was a hand-rolled copy of the shared row action, `text-text-secondary`, revealed on hover. `UnpinButton` is now the single badge both rows render. It keeps the favorites' reveal, holds open while the row's overflow menu is, and is inert while hidden so it cannot swallow a click meant for the row. The reveal is asked for in JS rather than through an `@media (hover: hover)` variant: the variant has to beat the `group-hover` rules that reveal the badge, and it loses that cascade for `opacity` while winning it for `pointer-events`, which left the badge visible and unclickable. Two things made a row's controls flicker under the pointer: - The overflow slot took its width from its content, and the menu mounts a tick after the row is hovered. The unpin badge beside it slid 28px left at that moment, out from under the pointer, mid-fill; whatever landed there started its own. The slot now reserves its width from the row's hover, and `shrink-0` keeps a growing sibling from squeezing it. - `hasInteracted` unmounted that menu on every leave, so each entry mounted a fresh button one frame late into an already-revealed slot, restarting its fill from transparent. A row that has been reached now keeps its control for as long as the row lives; virtualization still drops the whole row. * 🧺 feat: Unpin a Chat by Dropping It on Chats, and Keep Pinned Kinds Apart Dropping a chat on the Chats section filed it out of its project but left a pinned one pinned, so the section it landed in was not the section it went to. The drop now also unpins, and accepts a pinned chat that is already in the root list; a chat that is both filed and pinned comes out of both, each call a no-op for the half that already holds. Pinned chats and pinned agents/models could be dragged through each other, which the list cannot honour: the two are ordered independently and a row dropped into the other group snapped back. Each row now accepts only its own drag type, so the other kind never previews a displacement, and Alt+Arrow refuses the same step. An order saved while the two interleaved is read back grouped, or a row would be walled in by neighbours it is not allowed to swap with. * 🧹 fix: Unnest the Row Action Width Ternary and Correct the Pinned Doc The rebase onto `dev` left two things the branch's own checks catch: the width branch that reserves a chat row's action slot had grown a nested ternary, which the repository's ESLint forbids, and `dnd.ts` carried an import out of order. The section's own doc comment still promised that favorites and conversations "interleave freely", which this branch stopped being true: a row only reorders against its own kind, and a stored order is read back grouped. * 🪃 fix: Keep a Pinned Reorder That Was Released on a Row Reordering the Pinned section with the pointer never survived the release. The rows shifted under the drag, and the moment the button came up they snapped back to where they had started; nothing was written, so a reload showed the old order too. Only Alt+Arrow could actually reorder the list. A row is a drop target — that is what makes the hover that reorders the list arrive at all, since the HTML5 backend reports hover only for targets that could receive the drag. react-dnd then counts that target as having handled the drop whether or not it carries a `drop` handler, so `monitor.didDrop()` was true for every release on a row, and the drag's `end` reads that as "this chat was filed somewhere else" and discards the arrangement the drag built. The row now answers the release with a result that names it, and `end` treats a handled drop as a filing action only when the result is not that one. The same change stops a row swallowing the drop of an unpinned chat that lands on it: that drop reaches the section underneath, which is what pins the chat. Covered by `dropping-a-chat-on-a-pinned-row-pins-it` and the same-kind control inside `a-pinned-chat-cannot-be-dragged-through-a-pinned-model`, both in `e2e/specs/mock/scenarios/pinned-drag-rules.spec.ts`. * 🧪 test: Drive the Sidebar Row Rules in a Real Browser Twelve scenarios in the mock harness, one per behaviour this branch claims: the radius and fill every row control draws inside its row, the one unpin badge both pinned row kinds carry and when it shows, the controls holding still while the pointer crosses a row, the touch tap that reaches the badge directly, the drop on Chats that unpins, the drop on a pinned row that pins, the kind boundary a drag and Alt+Arrow both refuse, and the stored interleaved order that loads grouped. They seed pinned chats straight into Mongo and set favourites and the pinned order through the routes the star and the drag use, so the server's own cache invalidation runs. Pointer-only scenarios skip on a pointer that cannot hover and the touch scenario skips where it can, which is what lets the same file cover the desktop and mobile projects. `dragRowOnto` steps the pointer rather than jumping: the list reorders on `dragover` once the pointer has crossed the hovered row's midpoint, and a single move never delivers enough of them. * 🧭 fix: Sequence the Two Halves of a Drop on Chats, and Reach the Mobile Drawer Dropping a chat that is both pinned and filed in a project asked for the two writes at once. The pin route answers with the conversation as it stands after its own write, and the sidebar publishes that answer into every list, so a pin that overlapped the project write could put the old `chatProjectId` back over the lists the assignment had just corrected — and a failed assignment still left the chat unpinned, out of the section it had been dragged from and still in the project it was supposed to leave. The unpin now waits for the assignment and runs only if it took, so a failure leaves the chat exactly where it was and the published snapshot is the one taken after both writes. `useAssignDroppedConversation` reports that outcome through a named `AssignDroppedConversation` type, and the project row's drop keeps handing back nothing, since the pinned list reads the drop result to tell a reorder from a filing action. On a narrow viewport the sidebar is a drawer that slides out of view rather than unmounting, so its rows answer every query while nothing on them can be tapped. The scenario helpers open it through the chat header the way a person does, which is what lets the touch and keyboard scenarios run in the mobile project. * 📝 docs: Say What the Kept Overflow Control Actually Costs The comment beside `hasInteracted` claimed virtualization bounded the controls a hovered row leaves mounted. It does for the chats list, which drops a row as it scrolls out, but not for the Pinned section: that one mounts every pinned row at once, so a pointer crossing it leaves one `ConvoOptions` per row it touched, standing until the section unmounts. The bound there is the number of chats the user pinned, which is worth stating rather than implying it is zero. * ⏱️ test: Give the Sidebar Scenario Hooks the Time Their Seeding Takes `test.setTimeout` called inside a test body does not reach the hooks around it, and the slow part of these scenarios is in a hook: seeding a pinned list, then reloading and waiting for the section. On a loaded machine the `beforeEach` hit the default 30s and failed a scenario whose own budget was 60s. The timeout is configured once per file instead, and the per-test calls it duplicated are gone. * ⏳ test: Allow for the Cold Start the First Sidebar Scenario Pays The first test of a run loads the app for the first time against a database that\nmay be a network hop away, and under reviewctl verify that first load pushed the\nseeding hook past 60s. The file budget is 120s and the navigation waits are 30s,\nwhich is the cold start plus room, not a licence for a slow assertion: every\nassertion here still resolves in single-digit seconds once the app is warm. * 🧱 test: Tell an Unlaid Sidebar From a Closed One The helper that brings the sidebar on screen read a missing bounding box as "off\nscreen" and reached for the chat header's opener, which desktop widths do not\nrender: the click waited out the whole test budget while the panel it was waiting\nfor was already open beside it. Placement is now three states — on screen, slid\nout of view, not laid out yet — and only a drawer that is really closed, on a\nviewport that really has an opener, is clicked. * 🧮 fix: Keep Each Pinned Kind in Its Own Slots, and Never Report a Pending Write as Done Two ways the drop and order bookkeeping could still move a row nobody touched. A stored order written before the two kinds were kept apart can interleave them, and `mergeVisibleOrder` substituted visible keys across that interleaving. With part of the pinned list still draining, reordering two visible chats could carry an undelivered chat across the favorite between them, so the row moved within its own group once the rest of the list arrived. The stored order is now grouped the way the section reads it back, and each kind is substituted inside its own run. `useAssignDroppedConversation` treated a pending assignment's destination as an outcome: dropping the same chat on Chats again while its first write was still in flight matched `effectiveProjectId`, reported success, and unpinned the chat — and if that first write then failed, the chat stayed in its project with its pin gone. A write already heading where the drop asks now reports "not filed", so the drop that started it keeps ownership of what follows. Covered by `dnd.spec.ts` (`keeps each kind in its own slots when a legacy order interleaves them`), `unpinDropped.spec.tsx` (`does not unpin again while an assignment to the same place is in flight`) and the `PinnedSection` hidden-key test, which now states the normalized order it expects. The pinned scenarios also wait for the rows to advertise their reorder shortcut before dragging: a move is refused until the saved order has arrived, so a drag issued before that passed or failed on how fast the query answered. * 🔗 fix: Wait for the Write a Drop Asked For, Whoever Started It The pending-assignment guard assumed the write in flight belonged to another\ndrop, which would unpin the chat when it landed. The row menu populates the same\nmap and unfiles a chat without unpinning it, so a drop onto Chats made while that\nmenu action was in flight did nothing at all: an accepted drop left the chat in\nthe Pinned section.\n\nA pending entry now only stops this path from reading \ as\n"already there". The drop issues its own write and waits for that one; the\nmutation queues writes per conversation, so it lands after the one already out\nand repeats what it asked for, which the server takes as the no-op it is. The\nunpin still runs only on a write this drop saw succeed. * 🛰️ fix: Let the Server Say Whether a Dropped Chat Is Out of Its Project Three rounds of review found three ways the same guess went wrong, so the guess is gone. Deciding locally whether the filing half of a Chats drop "already holds" meant reading one of three things that are not the answer: a pending write, which is a request that can still fail; a cached project, which another tab may already have changed; or the drag item's own copy, older still. Each one could let the drop unpin a chat that stayed in its project, and a chat that is pinned nowhere and filed in a project is in neither list the sidebar shows. The drop now always sends the assignment and acts on what comes back. Repeating an assignment the chat already has is the no-op update it looks like, and the mutation queues writes per conversation, so this one lands after anything already out. The success notice reads the two project ids in the response rather than the fact that a request was sent, so a write that moved nothing stays quiet — which is what a pinned chat with no project gets when it is dropped on Chats. `unpinDropped.spec.tsx` covers the three: the unpin waits for the write, a failed write keeps the pin, and a chat already out of every project is still confirmed with the server and unpinned without announcing a move that did not happen. The scenario drag helper also steps its pointer more finely. The list shifts rows as it reorders and reads the pointer offset when the hover fires; a pointer that arrived in one jump got a single reading, sometimes taken mid-render, and the reorder it asked for did not always happen. * 🧷 test: Press Only a Row the List Has Connected for Dragging The pinned list disconnects its drag sources while the saved order reconciles,\nand a press on a disconnected row is not a refused drag — it is a click, so the\nrow opens instead of moving. Against the lab database, where that reconciliation\ntakes long enough to overlap the gesture, the Chats-drop scenario failed with the\ndragged row still pinned and now the active chat.\n\nreact-dnd marks a connected source \, so the helper waits for that\nbefore pressing.
This commit is contained in:
parent
e43fed2ed4
commit
9bf51fc302
19 changed files with 1633 additions and 212 deletions
|
|
@ -22,6 +22,7 @@ import {
|
|||
markExternalHover,
|
||||
useAssignDroppedConversation,
|
||||
useEffectiveProjectId,
|
||||
useUnpinDroppedConversation,
|
||||
} from './dnd';
|
||||
import { useLocalize, TranslationKeys, useElementSize } from '~/hooks';
|
||||
import { groupConversations, cn } from '~/utils';
|
||||
|
|
@ -195,9 +196,11 @@ const Conversations: FC<ConversationsProps> = ({
|
|||
const filterTags = useAtomValue(chatFilterTagsAtom);
|
||||
const resetFilters = useSetAtom(resetChatFiltersAtom);
|
||||
const isSmallScreen = useMediaQuery('(max-width: 768px)');
|
||||
/* Dropping a project conversation on the Chats section files it back out of
|
||||
* its project. Root-list chats already live here, so they are rejected. */
|
||||
/* Dropping a chat on the Chats section makes it an ordinary chat: out of its
|
||||
* project, and unpinned. A root-list chat that is not pinned already is one,
|
||||
* so it is rejected rather than given a drop that would do nothing. */
|
||||
const assignDropped = useAssignDroppedConversation();
|
||||
const unpinDropped = useUnpinDroppedConversation();
|
||||
const effectiveProjectId = useEffectiveProjectId();
|
||||
const chatsRegionRef = useRef<HTMLDivElement>(null);
|
||||
const [{ isDropOver, canDrop }, dropRef] = useDrop<
|
||||
|
|
@ -206,11 +209,25 @@ const Conversations: FC<ConversationsProps> = ({
|
|||
{ isDropOver: boolean; canDrop: boolean }
|
||||
>({
|
||||
accept: CONVERSATION_DRAG_TYPE,
|
||||
canDrop: (item) => effectiveProjectId(item) != null,
|
||||
canDrop: (item) => effectiveProjectId(item) != null || item.pinned === true,
|
||||
/* Reported even when refused, so a root chat dropped back on Chats does not
|
||||
* save the shift its pointer caused on the way out of the pinned list. */
|
||||
hover: () => markExternalHover(),
|
||||
drop: (item) => assignDropped(item, null),
|
||||
drop: (item) => {
|
||||
/* Sequenced rather than fired together, for a pinned chat that also sits
|
||||
* in a project. The pin write answers with the conversation as it stands
|
||||
* once it has run, so a pin that overlapped the project write would
|
||||
* publish a row still carrying its old `chatProjectId` into the lists the
|
||||
* assignment had just corrected. Waiting also gives a failure one shape:
|
||||
* an assignment that did not take leaves the chat pinned where it was,
|
||||
* instead of unpinning it out of a project it is still in. Each half is a
|
||||
* no-op when it already holds. */
|
||||
void assignDropped(item, null).then((filed) => {
|
||||
if (filed) {
|
||||
unpinDropped(item);
|
||||
}
|
||||
});
|
||||
},
|
||||
collect: (monitor) => ({ isDropOver: monitor.isOver(), canDrop: monitor.canDrop() }),
|
||||
});
|
||||
dropRef(chatsRegionRef);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import React, { memo, useState, useEffect, useRef, useMemo, useCallback } from 'react';
|
||||
import { useDrag } from 'react-dnd';
|
||||
import { Link2 } from 'lucide-react';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { Link2, PinOff } from 'lucide-react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Constants } from 'librechat-data-provider';
|
||||
import { Button, Spinner, TooltipAnchor, useToastContext, useMediaQuery } from '@librechat/client';
|
||||
import { Spinner, useToastContext, useMediaQuery } from '@librechat/client';
|
||||
import type { TConversation } from 'librechat-data-provider';
|
||||
import type { ConversationDragItem } from './dnd';
|
||||
import {
|
||||
|
|
@ -20,6 +20,7 @@ import { cn, logger, setDocumentTitle } from '~/utils';
|
|||
import { NotificationSeverity } from '~/common';
|
||||
import { CONVERSATION_DRAG_TYPE } from './dnd';
|
||||
import ConvoActions from './ConvoActions';
|
||||
import UnpinButton from './UnpinButton';
|
||||
import RenameForm from './RenameForm';
|
||||
import ConvoLink from './ConvoLink';
|
||||
import store from '~/store';
|
||||
|
|
@ -166,11 +167,22 @@ function Conversation({
|
|||
setRenaming(false);
|
||||
};
|
||||
|
||||
/* One-way: a row that has been reached keeps its overflow control mounted for
|
||||
* as long as the row itself lives. Resetting this on leave unmounted the
|
||||
* control and remounted it on the next entry, one frame after the row's hover
|
||||
* had already revealed its slot — so the button arrived a frame late and
|
||||
* restarted its hover fill from transparent every time the pointer crossed
|
||||
* the row's edge, which reads as a flicker.
|
||||
*
|
||||
* The cost is what the row's own lifetime is: the chats list unmounts a row
|
||||
* as it scrolls out, while the Pinned section mounts every pinned row at
|
||||
* once, so there a pointer crossing the list leaves one `ConvoOptions` per
|
||||
* row it touched, standing until the section unmounts. That is bounded by
|
||||
* the pin count the user chose, and a control that unmounts instead is what
|
||||
* this comment's first paragraph describes. */
|
||||
const handleMouseEnter = useCallback(() => {
|
||||
if (!hasInteracted) {
|
||||
setHasInteracted(true);
|
||||
}
|
||||
}, [hasInteracted]);
|
||||
setHasInteracted(true);
|
||||
}, []);
|
||||
|
||||
/* Matches the favorites' row-level unpin: one click on the pin badge, no
|
||||
* menu digging. The row unmounts once the pinned refetch lands, so focus is
|
||||
|
|
@ -213,35 +225,8 @@ function Conversation({
|
|||
);
|
||||
}, [conversationId, unpinMutation, showToast, localize]);
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
if (!isPopoverActive) {
|
||||
setHasInteracted(false);
|
||||
}
|
||||
}, [isPopoverActive]);
|
||||
|
||||
const handleBlur = useCallback(
|
||||
(e: React.FocusEvent<HTMLDivElement>) => {
|
||||
// Don't reset if focus is moving to a child element within this container
|
||||
if (e.currentTarget.contains(e.relatedTarget as Node)) {
|
||||
return;
|
||||
}
|
||||
if (!isPopoverActive) {
|
||||
setHasInteracted(false);
|
||||
}
|
||||
},
|
||||
[isPopoverActive],
|
||||
);
|
||||
|
||||
const handlePopoverOpenChange = useCallback((open: boolean) => {
|
||||
setIsPopoverActive(open);
|
||||
if (!open) {
|
||||
requestAnimationFrame(() => {
|
||||
const container = containerRef.current;
|
||||
if (container && !container.contains(document.activeElement)) {
|
||||
setHasInteracted(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleNavigation = (ctrlOrMetaKey: boolean) => {
|
||||
|
|
@ -291,20 +276,29 @@ function Conversation({
|
|||
</span>
|
||||
);
|
||||
|
||||
/* The slot takes its width from the row's hover, not from its content. The
|
||||
* overflow menu mounts a tick after the pointer arrives (see `ConvoActions`),
|
||||
* and a content-sized slot grew at that moment, pulling the unpin badge a
|
||||
* button's width leftwards out from under the pointer: the badge's fill,
|
||||
* already fading in, handed off to whichever control had slid into its place.
|
||||
* Reserving the width up front leaves every control where it was drawn. */
|
||||
let actionVisibilityClassName =
|
||||
'pointer-events-none max-w-0 scale-x-0 opacity-0 group-focus-within:pointer-events-auto group-focus-within:max-w-[60px] group-focus-within:scale-x-100 group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:max-w-[60px] group-hover:scale-x-100 group-hover:opacity-100';
|
||||
'pointer-events-none w-0 scale-x-0 opacity-0 group-focus-within:pointer-events-auto group-focus-within:scale-x-100 group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:scale-x-100 group-hover:opacity-100';
|
||||
let actionWidthClassName = isSmallScreen
|
||||
? 'group-focus-within:w-9 group-hover:w-9'
|
||||
: 'group-focus-within:w-7 group-hover:w-7';
|
||||
if (isGenerating) {
|
||||
actionVisibilityClassName = 'pointer-events-none w-5 scale-x-100 opacity-100';
|
||||
actionWidthClassName = '';
|
||||
} else if (isPopoverActive || isActiveConvo || isSmallScreen) {
|
||||
/** Touch has no hover, so a reveal-on-hover menu is unreachable there. */
|
||||
actionVisibilityClassName = 'pointer-events-auto scale-x-100 opacity-100';
|
||||
}
|
||||
|
||||
let actionWidthClassName = '';
|
||||
if (!isGenerating && !isPopoverActive && isActiveConvo && isShiftHeld) {
|
||||
actionWidthClassName = 'max-w-[60px]';
|
||||
} else if (!isGenerating) {
|
||||
actionWidthClassName = isSmallScreen ? 'max-w-[36px]' : 'max-w-[28px]';
|
||||
/** Shift over the active row swaps the menu for archive and delete. */
|
||||
if (!isPopoverActive && isActiveConvo && isShiftHeld) {
|
||||
actionWidthClassName = 'w-[60px]';
|
||||
} else {
|
||||
actionWidthClassName = isSmallScreen ? 'w-9' : 'w-7';
|
||||
}
|
||||
}
|
||||
|
||||
let actionContent: React.ReactNode = null;
|
||||
|
|
@ -331,9 +325,7 @@ function Conversation({
|
|||
onPointerLeave={() => setIsHovered(false)}
|
||||
onPointerCancel={() => setIsHovered(false)}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onFocus={handleMouseEnter}
|
||||
onBlur={handleBlur}
|
||||
onClick={(e) => {
|
||||
if (renaming) {
|
||||
return;
|
||||
|
|
@ -372,29 +364,19 @@ function Conversation({
|
|||
<Link2 className="icon-sm mr-1 shrink-0 text-text-secondary" aria-hidden="true" />
|
||||
)}
|
||||
{conversation.pinned === true && (
|
||||
<TooltipAnchor
|
||||
description={localize('com_ui_unpin')}
|
||||
side="top"
|
||||
render={
|
||||
<Button
|
||||
variant="row-action"
|
||||
size="icon-xs"
|
||||
aria-label={localize('com_ui_unpin')}
|
||||
data-testid="convo-unpin-button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
unpinConvo();
|
||||
}}
|
||||
className="mr-1 shrink-0 text-text-primary"
|
||||
>
|
||||
<PinOff className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
}
|
||||
<UnpinButton
|
||||
testId="convo-unpin-button"
|
||||
className="mr-1"
|
||||
keepVisible={isPopoverActive}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
unpinConvo();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
'mr-2 flex origin-left items-center justify-center',
|
||||
'mr-1 flex shrink-0 origin-left items-center justify-center',
|
||||
actionVisibilityClassName,
|
||||
actionWidthClassName,
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -416,7 +416,7 @@ function ConvoOptions({
|
|||
<div className="flex items-center gap-0.5">
|
||||
<button
|
||||
aria-label={localize(isArchived ? 'com_ui_unarchive' : 'com_ui_archive')}
|
||||
className={cn(buttonClassName, 'hover:bg-surface-hover')}
|
||||
className={buttonClassName}
|
||||
onClick={handleArchiveClick}
|
||||
disabled={isArchiveLoading}
|
||||
>
|
||||
|
|
@ -424,7 +424,7 @@ function ConvoOptions({
|
|||
</button>
|
||||
<button
|
||||
aria-label={localize('com_ui_delete')}
|
||||
className={cn(buttonClassName, 'hover:bg-surface-hover')}
|
||||
className={buttonClassName}
|
||||
onClick={handleInstantDelete}
|
||||
disabled={isDeleteLoading}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -38,10 +38,12 @@ const FAVORITE_ROW_DRAG_TYPE = 'favorite-item';
|
|||
* to a row would otherwise never meet the section's written hint, leaving the
|
||||
* only non-pointer way to reorder undiscoverable. */
|
||||
const REORDER_SHORTCUTS = 'Alt+ArrowUp Alt+ArrowDown';
|
||||
/** A pinned row accepts both: favorites reorder here only, while a dragged
|
||||
* conversation reorders here but can also be dropped on a project row or the
|
||||
* Chats section to be filed or unfiled. */
|
||||
/** The whole section accepts both kinds: a drop anywhere on it pins a chat that
|
||||
* is not pinned yet, whichever row it happened to land on. */
|
||||
const PINNED_ROW_ACCEPTS = [CONVERSATION_DRAG_TYPE, FAVORITE_ROW_DRAG_TYPE];
|
||||
/** What a row answers a release with, so the drag can tell a reorder inside
|
||||
* this list from a drop that filed the chat somewhere else. */
|
||||
const PINNED_ROW_DROP_RESULT = { pinnedRowReorder: true } as const;
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
|
|
@ -107,7 +109,18 @@ const DraggablePinnedRow = ({
|
|||
const ref = useRef<HTMLDivElement>(null);
|
||||
const hasHoverPointer = useMediaQuery('(hover: hover)');
|
||||
const [{ handlerId }, drop] = useDrop<PinnedRowDragItem, unknown, { handlerId: unknown }>({
|
||||
accept: PINNED_ROW_ACCEPTS,
|
||||
/* A row only takes a drag of its own kind, so a pinned chat never shifts a
|
||||
* pinned agent or model out of the way — not even as a preview. The two
|
||||
* groups are ordered independently, and the drag layer shows no
|
||||
* displacement for a target that cannot receive it. */
|
||||
accept: entry.kind === 'convo' ? CONVERSATION_DRAG_TYPE : FAVORITE_ROW_DRAG_TYPE,
|
||||
/* A release on a row ends a reorder; it files nothing. The row has to stay
|
||||
* droppable to get there — the HTML5 backend reports hover only for targets
|
||||
* that could receive the drag, and the hover is what reorders — so it names
|
||||
* itself in the drop result instead. Without that name, `end` below saw
|
||||
* `monitor.didDrop()` and read the release as a filing action, discarding
|
||||
* the arrangement: every pointer reorder snapped back on release. */
|
||||
drop: () => PINNED_ROW_DROP_RESULT,
|
||||
collect(monitor) {
|
||||
return { handlerId: monitor.getHandlerId() };
|
||||
},
|
||||
|
|
@ -153,11 +166,14 @@ const DraggablePinnedRow = ({
|
|||
: { key: entry.key, conversationId: '', chatProjectId: null, pinned: false };
|
||||
},
|
||||
collect: (monitor) => ({ isDragging: monitor.isDragging() }),
|
||||
/* Rows carry no drop handler of their own, so an unhandled drop usually
|
||||
* means a reorder. A refused external target also reports none, though, so
|
||||
* the last thing under the pointer settles it. */
|
||||
/* A drop the list itself answered is a reorder and keeps the arrangement.
|
||||
* Anything else that handled it filed the chat — into a project, or back
|
||||
* into Chats — and a refused external target reports no handler at all, so
|
||||
* the last thing under the pointer settles that case. */
|
||||
end: (_item, monitor) => {
|
||||
onDrop(monitor.didDrop() || endedOverExternalTarget());
|
||||
const result = monitor.getDropResult() as { pinnedRowReorder?: boolean } | null;
|
||||
const filedElsewhere = monitor.didDrop() && result?.pinnedRowReorder !== true;
|
||||
onDrop(filedElsewhere || endedOverExternalTarget());
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -286,9 +302,10 @@ interface PinnedSectionProps {
|
|||
}
|
||||
|
||||
/** Pinned chats and pinned agents/models/specs (favorites) render as ONE
|
||||
* reorderable list: favorites and conversations interleave freely, the order
|
||||
* persists per user, and the section opens with the same collapse motion as
|
||||
* the Projects section above it. */
|
||||
* reorderable list, kept in two groups — favorites first, then chats — because
|
||||
* a row only reorders against its own kind. The order persists per user, and
|
||||
* the section opens with the same collapse motion as the Projects section
|
||||
* above it. */
|
||||
const PinnedSection = ({
|
||||
conversations,
|
||||
toggleNav,
|
||||
|
|
@ -400,7 +417,11 @@ const PinnedSection = ({
|
|||
}, [favoritesData.favorites, conversations]);
|
||||
|
||||
/** Stored keys order the entries they still resolve to; the rest append in
|
||||
* natural order, so a stale order never hides an item. */
|
||||
* natural order, so a stale order never hides an item. Kinds stay grouped —
|
||||
* pinned agents and models first, then pinned chats — because neither kind
|
||||
* can be dragged through the other: an order saved before that rule, with
|
||||
* the two interleaved, would otherwise leave a row walled in by neighbours
|
||||
* it is not allowed to swap with. */
|
||||
const orderedEntries = useMemo<PinnedEntry[]>(() => {
|
||||
if (!storedOrder || storedOrder.length === 0) {
|
||||
return naturalEntries;
|
||||
|
|
@ -420,7 +441,10 @@ const PinnedSection = ({
|
|||
ordered.push(entry);
|
||||
}
|
||||
}
|
||||
return ordered;
|
||||
return [
|
||||
...ordered.filter((entry) => entry.kind === 'favorite'),
|
||||
...ordered.filter((entry) => entry.kind === 'convo'),
|
||||
];
|
||||
}, [storedOrder, naturalEntries]);
|
||||
|
||||
/* The live list the drag mutates; keyed ordering only, so a refetch under a
|
||||
|
|
@ -477,11 +501,14 @@ const PinnedSection = ({
|
|||
* still holds, and releasing would save something no longer on screen. */
|
||||
const arrangementRef = useRef(0);
|
||||
|
||||
/** A move only ever swaps two rows of the same kind. Chats and favorites are
|
||||
* two independently ordered groups, so the position announced for the
|
||||
* keyboard path counts within the moved row's own group. */
|
||||
const moveEntry = useCallback((dragKey: string, hoverKey: string) => {
|
||||
const list = [...dragEntriesRef.current];
|
||||
const from = list.findIndex((entry) => entry.key === dragKey);
|
||||
const to = list.findIndex((entry) => entry.key === hoverKey);
|
||||
if (from < 0 || to < 0 || from === to) {
|
||||
if (from < 0 || to < 0 || from === to || list[from].kind !== list[to].kind) {
|
||||
return;
|
||||
}
|
||||
const [moved] = list.splice(from, 1);
|
||||
|
|
@ -494,7 +521,8 @@ const PinnedSection = ({
|
|||
|
||||
/** Keyboard reorder: one step per keypress, persisted immediately, with the
|
||||
* new position announced because nothing visual conveys it to a screen
|
||||
* reader. */
|
||||
* reader. A step that would leave the row's own group does nothing, matching
|
||||
* what the pointer can do. */
|
||||
const moveEntryBy = useCallback(
|
||||
(key: string, delta: number) => {
|
||||
if (!orderLoadedRef.current) {
|
||||
|
|
@ -503,17 +531,20 @@ const PinnedSection = ({
|
|||
const list = [...dragEntriesRef.current];
|
||||
const from = list.findIndex((entry) => entry.key === key);
|
||||
const to = from + delta;
|
||||
if (from < 0 || to < 0 || to >= list.length) {
|
||||
if (from < 0 || to < 0 || to >= list.length || list[from].kind !== list[to].kind) {
|
||||
return;
|
||||
}
|
||||
const kind = list[from].kind;
|
||||
const [moved] = list.splice(from, 1);
|
||||
list.splice(to, 0, moved);
|
||||
dragEntriesRef.current = list;
|
||||
hasReorderedRef.current = true;
|
||||
arrangementRef.current += 1;
|
||||
setLiveEntries(list);
|
||||
const group = list.filter((entry) => entry.kind === kind);
|
||||
const position = group.findIndex((entry) => entry.key === key) + 1;
|
||||
setAnnouncement(
|
||||
localize('com_ui_moved_to_position', { 0: `${to + 1}`, 1: `${list.length}` }),
|
||||
localize('com_ui_moved_to_position', { 0: `${position}`, 1: `${group.length}` }),
|
||||
);
|
||||
commitOrderRef.current();
|
||||
},
|
||||
|
|
|
|||
|
|
@ -56,6 +56,17 @@ const iconButtonClassName = cn(
|
|||
'shrink-0',
|
||||
);
|
||||
|
||||
/** The same control on a project row rather than beside the heading. The row
|
||||
* itself already fills on hover, so the variant's hover surface would leave
|
||||
* the button reading as a second, weaker hover on top of it. These take the
|
||||
* active fill instead — the same one the row's own selected state uses — both
|
||||
* under the pointer and while the menu they own is open. */
|
||||
const rowActionClassName = cn(
|
||||
iconButtonClassName,
|
||||
'hover:bg-surface-active hover:text-text-primary',
|
||||
);
|
||||
const rowActionOpenClassName = 'bg-surface-active text-text-primary';
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
type ProjectChatsInlineProps = {
|
||||
|
|
@ -141,7 +152,7 @@ const ProjectChatsInline = memo(function ProjectChatsInline({
|
|||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onShowAll}
|
||||
className="ml-1 mt-0.5 h-auto rounded-md px-2 py-1 text-xs font-medium text-text-secondary transition-colors hover:bg-transparent hover:text-text-primary"
|
||||
className="ml-1 mt-0.5 h-auto rounded-md px-2 py-1 text-xs font-medium text-text-secondary transition-colors hover:text-text-primary"
|
||||
>
|
||||
{localize('com_ui_show_all')}
|
||||
</Button>
|
||||
|
|
@ -193,7 +204,12 @@ const ProjectItem = memo(
|
|||
* project it already belongs to still left the pinned list, and the rows
|
||||
* it crossed must not be saved in their shifted order. */
|
||||
hover: () => markExternalHover(),
|
||||
drop: (item) => assignDropped(item, project._id),
|
||||
/* The drop result is what the pinned list reads to tell a reorder from a
|
||||
* filing action, so this hands back nothing rather than the assignment's
|
||||
* promise. */
|
||||
drop: (item) => {
|
||||
void assignDropped(item, project._id);
|
||||
},
|
||||
collect: (monitor) => ({ isDropOver: monitor.isOver(), canDrop: monitor.canDrop() }),
|
||||
});
|
||||
dropRef(projectRowRef);
|
||||
|
|
@ -292,7 +308,10 @@ const ProjectItem = memo(
|
|||
</button>
|
||||
<div
|
||||
className={cn(
|
||||
'absolute right-1 top-1/2 flex -translate-y-1/2 items-center',
|
||||
/* The 4px between the two controls, and from the row's trailing
|
||||
edge, that a pinned chat keeps between its unpin badge and its
|
||||
overflow menu. */
|
||||
'absolute right-1 top-1/2 flex -translate-y-1/2 items-center gap-1',
|
||||
isMenuOpen
|
||||
? 'opacity-100'
|
||||
: [
|
||||
|
|
@ -308,7 +327,7 @@ const ProjectItem = memo(
|
|||
<a
|
||||
href={projectChatPath}
|
||||
aria-label={localize('com_ui_new_chat_in_project', { name: project.name })}
|
||||
className={iconButtonClassName}
|
||||
className={rowActionClassName}
|
||||
onClick={startChat}
|
||||
>
|
||||
<NewChatIcon className="h-4 w-4" />
|
||||
|
|
@ -327,7 +346,7 @@ const ProjectItem = memo(
|
|||
trigger={
|
||||
<Ariakit.MenuButton
|
||||
aria-label={localize('com_ui_more_options')}
|
||||
className={cn(iconButtonClassName, isMenuOpen && 'text-text-primary')}
|
||||
className={cn(rowActionClassName, isMenuOpen && rowActionOpenClassName)}
|
||||
>
|
||||
<Ellipsis className="h-4 w-4" aria-hidden="true" />
|
||||
</Ariakit.MenuButton>
|
||||
|
|
@ -486,7 +505,7 @@ const ProjectsSection = ({ toggleNav, isAuthenticated }: ProjectsSectionProps) =
|
|||
<button
|
||||
type="button"
|
||||
aria-label={localize('com_ui_all_projects')}
|
||||
className={cn(iconButtonClassName, 'hover:bg-surface-hover')}
|
||||
className={iconButtonClassName}
|
||||
onClick={openProjects}
|
||||
>
|
||||
<Folders className="h-4 w-4" aria-hidden="true" />
|
||||
|
|
|
|||
|
|
@ -61,24 +61,20 @@ const RenameForm: React.FC<RenameFormProps> = ({
|
|||
/>
|
||||
<div className="flex gap-1" role="toolbar">
|
||||
<Button
|
||||
variant="ghost"
|
||||
variant="row-action"
|
||||
size="icon"
|
||||
onClick={() => onCancel()}
|
||||
className={cn(
|
||||
'size-auto rounded-md p-1 hover:opacity-70 focus:outline-none focus:ring-2 focus:ring-text-primary',
|
||||
)}
|
||||
className={cn('size-auto p-1 focus:outline-none focus:ring-2 focus:ring-text-primary')}
|
||||
aria-label={localize('com_ui_cancel')}
|
||||
type="button"
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
variant="row-action"
|
||||
size="icon"
|
||||
onClick={() => onSubmit(titleInput)}
|
||||
className={cn(
|
||||
'size-auto rounded-md p-1 hover:opacity-70 focus:outline-none focus:ring-2 focus:ring-text-primary',
|
||||
)}
|
||||
className={cn('size-auto p-1 focus:outline-none focus:ring-2 focus:ring-text-primary')}
|
||||
aria-label={localize('com_ui_save')}
|
||||
type="button"
|
||||
>
|
||||
|
|
|
|||
70
client/src/components/Conversations/UnpinButton.tsx
Normal file
70
client/src/components/Conversations/UnpinButton.tsx
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { PinOff } from 'lucide-react';
|
||||
import { Button, TooltipAnchor, useMediaQuery } from '@librechat/client';
|
||||
import type { KeyboardEvent, MouseEvent } from 'react';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
interface UnpinButtonProps {
|
||||
onClick: (event: MouseEvent<HTMLButtonElement>) => void;
|
||||
onKeyDown?: (event: KeyboardEvent<HTMLButtonElement>) => void;
|
||||
/** Which row kind reports the click, for the tests that drive each one. */
|
||||
testId: string;
|
||||
/** Holds the badge open past the pointer leaving, for a row whose overflow
|
||||
* menu is open: the pointer is on the menu, not on the row, and a control
|
||||
* that vanished while its own row's menu stood open read as the row losing
|
||||
* half its actions. */
|
||||
keepVisible?: boolean;
|
||||
/** Row-local placement only; the badge owns its own appearance. */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The unpin badge a pinned row carries, shared by both kinds of row in the
|
||||
* Pinned section: conversations and agents/models/specs. They sit in one list
|
||||
* and are reordered against each other, so a badge that differed in colour,
|
||||
* size or in when it appears read as two different controls.
|
||||
*
|
||||
* Hidden until the row is hovered or holds focus, and inert while hidden so an
|
||||
* invisible badge cannot swallow a click meant for the row. The reveal is asked
|
||||
* for in JS rather than through an `@media (hover: hover)` variant, the way the
|
||||
* row's overflow trigger does it: a variant only ever loses or wins the cascade
|
||||
* against the `group-hover` rules it has to override, and which way it goes
|
||||
* differs per property. A pointer with no hover gets no gating at all, which is
|
||||
* the only thing that makes the badge reachable by touch.
|
||||
*/
|
||||
export default function UnpinButton({
|
||||
onClick,
|
||||
onKeyDown,
|
||||
testId,
|
||||
keepVisible = false,
|
||||
className,
|
||||
}: UnpinButtonProps) {
|
||||
const localize = useLocalize();
|
||||
const hasHoverPointer = useMediaQuery('(hover: hover)');
|
||||
|
||||
return (
|
||||
<TooltipAnchor
|
||||
description={localize('com_ui_unpin')}
|
||||
side="top"
|
||||
render={
|
||||
<Button
|
||||
variant="row-action"
|
||||
size="icon-xs"
|
||||
aria-label={localize('com_ui_unpin')}
|
||||
data-testid={testId}
|
||||
onClick={onClick}
|
||||
onKeyDown={onKeyDown}
|
||||
className={cn(
|
||||
'shrink-0 text-text-secondary',
|
||||
hasHoverPointer &&
|
||||
!keepVisible &&
|
||||
'pointer-events-none opacity-0 focus-visible:pointer-events-auto focus-visible:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<PinOff className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -76,6 +76,7 @@ jest.mock('@librechat/client', () => ({
|
|||
jest.mock('~/data-provider', () => ({
|
||||
useActiveJobs: () => ({ data: undefined }),
|
||||
useAssignConversationToProjectMutation: () => ({ mutate: jest.fn() }),
|
||||
usePinConversationMutation: () => ({ mutate: jest.fn() }),
|
||||
}));
|
||||
|
||||
jest.mock('~/utils', () => ({
|
||||
|
|
|
|||
|
|
@ -172,12 +172,14 @@ describe('PinnedSection unified list', () => {
|
|||
expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat', 'Another Pin']);
|
||||
});
|
||||
|
||||
it('interleaves favorites and conversations by the stored order', () => {
|
||||
/* Chats and favorites are two independently ordered groups: an order saved
|
||||
* before that rule, with the two interleaved, is read back grouped. */
|
||||
it('orders each kind by the stored order and keeps the kinds grouped', () => {
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }, { agentId: 'agent-1' }];
|
||||
mockFavoritesData.agentsMap = { 'agent-1': { id: 'agent-1' } };
|
||||
mockPinnedOrder = ['convo:c1', 'agent:agent-1', 'model:6:openAI:gpt-4o'];
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat')]);
|
||||
expect(itemLabels()).toEqual(['Pinned Chat', 'agent-1', 'gpt-4o']);
|
||||
mockPinnedOrder = ['convo:c2', 'agent:agent-1', 'model:6:openAI:gpt-4o', 'convo:c1'];
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Another Pin')]);
|
||||
expect(itemLabels()).toEqual(['agent-1', 'gpt-4o', 'Another Pin', 'Pinned Chat']);
|
||||
});
|
||||
|
||||
it('appends items missing from the stored order and ignores stale keys', () => {
|
||||
|
|
@ -214,26 +216,42 @@ describe('PinnedSection unified list', () => {
|
|||
fireEvent.keyDown(screen.getByText(label), { key, altKey: true });
|
||||
|
||||
it('moves a row down with Alt+ArrowDown and persists the new order', () => {
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
mockFavoritesData.favorites = [
|
||||
{ model: 'gpt-4o', endpoint: 'openAI' },
|
||||
{ model: 'gpt-4o-mini', endpoint: 'openAI' },
|
||||
];
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat')]);
|
||||
expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat']);
|
||||
expect(itemLabels()).toEqual(['gpt-4o', 'gpt-4o-mini', 'Pinned Chat']);
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
|
||||
expect(itemLabels()).toEqual(['Pinned Chat', 'gpt-4o']);
|
||||
expect(itemLabels()).toEqual(['gpt-4o-mini', 'gpt-4o', 'Pinned Chat']);
|
||||
expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
|
||||
['convo:c1', 'model:6:openAI:gpt-4o'],
|
||||
['model:6:openAI:gpt-4o-mini', 'model:6:openAI:gpt-4o', 'convo:c1'],
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('moves a row up with Alt+ArrowUp', () => {
|
||||
renderSection([pinnedConvo('c1', 'First'), pinnedConvo('c2', 'Second')]);
|
||||
|
||||
moveFocusedRow('Second', 'ArrowUp');
|
||||
|
||||
expect(itemLabels()).toEqual(['Second', 'First']);
|
||||
});
|
||||
|
||||
/* The pointer cannot drag a chat through a pinned agent or model, so the
|
||||
* keyboard must not either: a step that would leave the row's own group
|
||||
* does nothing rather than interleaving the two. */
|
||||
it('refuses a step that would cross into the other kind', () => {
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat')]);
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
moveFocusedRow('Pinned Chat', 'ArrowUp');
|
||||
|
||||
expect(itemLabels()).toEqual(['Pinned Chat', 'gpt-4o']);
|
||||
expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat']);
|
||||
expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/* Reordering against an order that has not arrived yet would merge into
|
||||
|
|
@ -242,13 +260,16 @@ describe('PinnedSection unified list', () => {
|
|||
/* A write that settles after the user has arranged the list again must not
|
||||
* clear the snapshot showing that newer arrangement. */
|
||||
it('keeps a newer arrangement when an older write settles', () => {
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
renderSection([pinnedConvo('c1', 'First'), pinnedConvo('c2', 'Second')]);
|
||||
renderSection([
|
||||
pinnedConvo('c1', 'First'),
|
||||
pinnedConvo('c2', 'Second'),
|
||||
pinnedConvo('c3', 'Third'),
|
||||
]);
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
moveFocusedRow('First', 'ArrowDown');
|
||||
const firstSettle = mockUpdatePinnedOrder.mock.calls[0][1].onSettled;
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
moveFocusedRow('First', 'ArrowDown');
|
||||
const arranged = itemLabels();
|
||||
|
||||
act(() => firstSettle());
|
||||
|
|
@ -307,12 +328,12 @@ describe('PinnedSection unified list', () => {
|
|||
});
|
||||
|
||||
it('prunes keys that are gone once the whole list is known', () => {
|
||||
mockPinnedOrder = ['convo:gone', 'model:6:openAI:gpt-4o', 'convo:c1'];
|
||||
mockPinnedOrder = ['convo:gone', 'model:6:openAI:gpt-4o', 'convo:c1', 'convo:c2'];
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
render(
|
||||
<DndProvider backend={HTML5Backend}>
|
||||
<PinnedSection
|
||||
conversations={[pinnedConvo('c1', 'Pinned Chat')]}
|
||||
conversations={[pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Second')]}
|
||||
toggleNav={jest.fn()}
|
||||
membershipComplete
|
||||
membershipUpdatedAt={MEMBERSHIP_FETCHED_AT}
|
||||
|
|
@ -320,12 +341,12 @@ describe('PinnedSection unified list', () => {
|
|||
</DndProvider>,
|
||||
);
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
moveFocusedRow('Pinned Chat', 'ArrowDown');
|
||||
|
||||
/* Merging forever would grow the array until the size guard rejected
|
||||
* every write, so a complete membership load compacts it. */
|
||||
expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
|
||||
['convo:c1', 'model:6:openAI:gpt-4o'],
|
||||
['model:6:openAI:gpt-4o', 'convo:c2', 'convo:c1'],
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
|
@ -351,10 +372,9 @@ describe('PinnedSection unified list', () => {
|
|||
});
|
||||
|
||||
it('announces the new position', () => {
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat')]);
|
||||
renderSection([pinnedConvo('c1', 'First'), pinnedConvo('c2', 'Second')]);
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
moveFocusedRow('First', 'ArrowDown');
|
||||
|
||||
expect(screen.getByRole('status')).toHaveTextContent('com_ui_moved_to_position');
|
||||
});
|
||||
|
|
@ -362,29 +382,36 @@ describe('PinnedSection unified list', () => {
|
|||
/* Rows can be missing from view for reasons the section cannot tell apart:
|
||||
* a bookmark filter hides them, or the pinned query is still draining its
|
||||
* cursor. Persisting only what is on screen would drop those keys and lose
|
||||
* their positions, so the order is always merged, never replaced. */
|
||||
* their positions, so the order is always merged, never replaced — and an
|
||||
* order saved while the two kinds interleaved is normalized on the way out,
|
||||
* so the hidden chat keeps its place among chats rather than being carried
|
||||
* across the favorite that used to sit above it. */
|
||||
it('keeps keys it cannot see in the stored order', () => {
|
||||
mockPinnedOrder = ['convo:hidden', 'model:6:openAI:gpt-4o', 'convo:c1'];
|
||||
mockPinnedOrder = ['convo:hidden', 'model:6:openAI:gpt-4o', 'convo:c1', 'convo:c2'];
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat')]);
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Second')]);
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
moveFocusedRow('Pinned Chat', 'ArrowDown');
|
||||
|
||||
expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
|
||||
['convo:hidden', 'convo:c1', 'model:6:openAI:gpt-4o'],
|
||||
['model:6:openAI:gpt-4o', 'convo:hidden', 'convo:c2', 'convo:c1'],
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not write the favorites array a second time', () => {
|
||||
mockPinnedOrder = ['model:6:openAI:gpt-4o', 'convo:c1'];
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
renderSection([pinnedConvo('c1', 'Pinned Chat')]);
|
||||
mockPinnedOrder = ['model:6:openAI:gpt-4o', 'model:6:openAI:gpt-4o-mini'];
|
||||
mockFavoritesData.favorites = [
|
||||
{ model: 'gpt-4o', endpoint: 'openAI' },
|
||||
{ model: 'gpt-4o-mini', endpoint: 'openAI' },
|
||||
];
|
||||
renderSection([]);
|
||||
|
||||
moveFocusedRow('gpt-4o', 'ArrowDown');
|
||||
|
||||
/* `pinnedOrder` is the only ordering the section reads, and a second
|
||||
* whole-array write would race the favorites membership mutations. */
|
||||
expect(mockUpdatePinnedOrder).toHaveBeenCalled();
|
||||
expect(mockReorderFavorites).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
@ -458,16 +485,16 @@ describe('PinnedSection unified list', () => {
|
|||
* has to stay quiet when there is nothing being held: reposting a committed
|
||||
* arrangement would undo whatever that reconciliation just brought in. */
|
||||
it('does not repost an arrangement that was already written', () => {
|
||||
mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
|
||||
const view = renderSection([pinnedConvo('c1', 'Pinned Chat')]);
|
||||
const rows = [pinnedConvo('c1', 'First'), pinnedConvo('c2', 'Second')];
|
||||
const view = renderSection(rows);
|
||||
|
||||
fireEvent.keyDown(screen.getByText('gpt-4o'), { key: 'ArrowDown', altKey: true });
|
||||
fireEvent.keyDown(screen.getByText('First'), { key: 'ArrowDown', altKey: true });
|
||||
expect(mockUpdatePinnedOrder).toHaveBeenCalledTimes(1);
|
||||
|
||||
mockOrderFetching = true;
|
||||
view.rerender(renderTree([pinnedConvo('c1', 'Pinned Chat')]));
|
||||
view.rerender(renderTree(rows));
|
||||
mockOrderFetching = false;
|
||||
view.rerender(renderTree([pinnedConvo('c1', 'Pinned Chat')]));
|
||||
view.rerender(renderTree(rows));
|
||||
|
||||
expect(mockUpdatePinnedOrder).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -85,6 +85,25 @@ describe('mergeVisibleOrder', () => {
|
|||
it('keeps every hidden key when only one row is visible', () => {
|
||||
expect(mergeVisibleOrder(['a', 'b', 'c'], ['c'])).toEqual(['a', 'b', 'c']);
|
||||
});
|
||||
|
||||
/* The section reads a stored order back grouped, so an order saved before the
|
||||
* kinds were kept apart is normalized here rather than merged across. Here
|
||||
* `convo:hidden` is a pinned chat the drained list has not delivered yet:
|
||||
* swapping the two visible chats must leave it where it was among chats,
|
||||
* second of three. */
|
||||
it('keeps each kind in its own slots when a legacy order interleaves them', () => {
|
||||
const stored = ['convo:c1', 'convo:hidden', 'model:1:A:m', 'convo:c2'];
|
||||
const visible = ['model:1:A:m', 'convo:c2', 'convo:c1'];
|
||||
|
||||
const merged = mergeVisibleOrder(stored, visible);
|
||||
|
||||
expect(merged).toEqual(['model:1:A:m', 'convo:c2', 'convo:hidden', 'convo:c1']);
|
||||
expect(merged.filter((key) => key.startsWith('convo:'))).toEqual([
|
||||
'convo:c2',
|
||||
'convo:hidden',
|
||||
'convo:c1',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
/* `didDrop()` is false both for a drop the pinned rows handled and for one an
|
||||
|
|
|
|||
|
|
@ -0,0 +1,222 @@
|
|||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import type {
|
||||
AssignDroppedConversation,
|
||||
ConversationDragItem,
|
||||
UnpinDroppedConversation,
|
||||
} from '../dnd';
|
||||
import { useAssignDroppedConversation, useUnpinDroppedConversation } from '../dnd';
|
||||
|
||||
const mockPin = jest.fn();
|
||||
const mockAssign = jest.fn();
|
||||
|
||||
const mockShowToast = jest.fn();
|
||||
|
||||
jest.mock('@librechat/client', () => ({
|
||||
useToastContext: () => ({ showToast: mockShowToast }),
|
||||
}));
|
||||
|
||||
let mockPendingAssignment: { token: number; projectId: string | null } | undefined;
|
||||
|
||||
jest.mock('~/data-provider/Projects/mutations', () => ({
|
||||
getPendingAssignment: () => mockPendingAssignment,
|
||||
}));
|
||||
|
||||
jest.mock('@tanstack/react-query', () => ({
|
||||
useQueryClient: () => ({ getQueryData: () => undefined }),
|
||||
}));
|
||||
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useAssignConversationToProjectMutation: () => ({ mutateAsync: mockAssign }),
|
||||
usePinConversationMutation: () => ({ mutate: mockPin }),
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
/** Only the two ids the drop reads; the response also carries the conversation. */
|
||||
type AssignResponse = { previousProjectId: string | null; projectId: string | null };
|
||||
|
||||
const item = (pinned: boolean, conversationId = 'c1'): ConversationDragItem => ({
|
||||
conversationId,
|
||||
chatProjectId: null,
|
||||
pinned,
|
||||
});
|
||||
|
||||
/* Dropping a chat on the Chats section asks for an ordinary chat, and a pinned
|
||||
* one is not that. */
|
||||
describe('useUnpinDroppedConversation', () => {
|
||||
beforeEach(() => {
|
||||
mockPin.mockReset();
|
||||
mockAssign.mockReset();
|
||||
});
|
||||
|
||||
it('unpins the dropped conversation', () => {
|
||||
const { result } = renderHook(() => useUnpinDroppedConversation());
|
||||
|
||||
result.current(item(true));
|
||||
|
||||
expect(mockPin).toHaveBeenCalledWith(
|
||||
{ conversationId: 'c1', pinned: false },
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves a chat that is not pinned alone', () => {
|
||||
const { result } = renderHook(() => useUnpinDroppedConversation());
|
||||
|
||||
result.current(item(false));
|
||||
|
||||
expect(mockPin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/* A favorite row's drag item carries no conversation at all. */
|
||||
it('ignores a drag item with no conversation', () => {
|
||||
const { result } = renderHook(() => useUnpinDroppedConversation());
|
||||
|
||||
result.current(item(true, ''));
|
||||
|
||||
expect(mockPin).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
/* What the Chats section does with a chat that is both pinned and filed in a
|
||||
* project: it asks for both halves, and the caller decides their order. */
|
||||
describe('a drop on Chats, filing and unpinning together', () => {
|
||||
beforeEach(() => {
|
||||
mockPin.mockReset();
|
||||
mockAssign.mockReset();
|
||||
mockShowToast.mockReset();
|
||||
mockPendingAssignment = undefined;
|
||||
});
|
||||
|
||||
/* The drop handler the Chats section installs, kept in one place so the two
|
||||
* cases below exercise the same sequence the component runs. */
|
||||
const drop = async (
|
||||
assign: AssignDroppedConversation,
|
||||
unpin: UnpinDroppedConversation,
|
||||
dragged: ConversationDragItem,
|
||||
) => {
|
||||
const filed = await assign(dragged, null);
|
||||
if (filed) {
|
||||
unpin(dragged);
|
||||
}
|
||||
};
|
||||
|
||||
it('unpins only once the project write has landed', async () => {
|
||||
let settle: ((result: AssignResponse) => void) | undefined;
|
||||
mockAssign.mockImplementation(
|
||||
() =>
|
||||
new Promise<AssignResponse>((resolve) => {
|
||||
settle = resolve;
|
||||
}),
|
||||
);
|
||||
const { result } = renderHook(() => ({
|
||||
assign: useAssignDroppedConversation(),
|
||||
unpin: useUnpinDroppedConversation(),
|
||||
}));
|
||||
|
||||
const dropped = { conversationId: 'c1', chatProjectId: 'p1', pinned: true };
|
||||
const running = drop(result.current.assign, result.current.unpin, dropped);
|
||||
|
||||
expect(mockAssign).toHaveBeenCalledWith({ conversationId: 'c1', projectId: null });
|
||||
expect(mockPin).not.toHaveBeenCalled();
|
||||
|
||||
settle?.({ previousProjectId: 'p1', projectId: null });
|
||||
await running;
|
||||
|
||||
expect(mockPin).toHaveBeenCalledWith(
|
||||
{ conversationId: 'c1', pinned: false },
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
/* A chat left in its project must not also leave the Pinned section: the row
|
||||
* would then be in neither place the user can see it. */
|
||||
it('keeps the chat pinned when the project write fails', async () => {
|
||||
mockAssign.mockRejectedValue(new Error('network'));
|
||||
const { result } = renderHook(() => ({
|
||||
assign: useAssignDroppedConversation(),
|
||||
unpin: useUnpinDroppedConversation(),
|
||||
}));
|
||||
|
||||
await drop(result.current.assign, result.current.unpin, {
|
||||
conversationId: 'c1',
|
||||
chatProjectId: 'p1',
|
||||
pinned: true,
|
||||
});
|
||||
|
||||
await waitFor(() => expect(mockAssign).toHaveBeenCalled());
|
||||
expect(mockPin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/* A write already in flight cannot answer for this drop: it can still fail,
|
||||
* and the path that started it may own no unpin at all — the row menu unfiles
|
||||
* a chat without unpinning it. The drop issues its own write and waits for
|
||||
* that one, which the per-conversation queue runs after the first. */
|
||||
it('issues its own write rather than trusting one already in flight', async () => {
|
||||
mockPendingAssignment = { token: 1, projectId: null };
|
||||
mockAssign.mockResolvedValue({ previousProjectId: 'p1', projectId: null });
|
||||
const { result } = renderHook(() => ({
|
||||
assign: useAssignDroppedConversation(),
|
||||
unpin: useUnpinDroppedConversation(),
|
||||
}));
|
||||
|
||||
await drop(result.current.assign, result.current.unpin, {
|
||||
conversationId: 'c1',
|
||||
chatProjectId: 'p1',
|
||||
pinned: true,
|
||||
});
|
||||
|
||||
expect(mockAssign).toHaveBeenCalledWith({ conversationId: 'c1', projectId: null });
|
||||
expect(mockPin).toHaveBeenCalledWith(
|
||||
{ conversationId: 'c1', pinned: false },
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
/* The same drop, when that in-flight write fails: the chat is still in its
|
||||
* project, so it keeps its pin too. */
|
||||
it('keeps the chat pinned when the write it waited for fails', async () => {
|
||||
mockPendingAssignment = { token: 1, projectId: null };
|
||||
mockAssign.mockRejectedValue(new Error('network'));
|
||||
const { result } = renderHook(() => ({
|
||||
assign: useAssignDroppedConversation(),
|
||||
unpin: useUnpinDroppedConversation(),
|
||||
}));
|
||||
|
||||
await drop(result.current.assign, result.current.unpin, {
|
||||
conversationId: 'c1',
|
||||
chatProjectId: 'p1',
|
||||
pinned: true,
|
||||
});
|
||||
|
||||
expect(mockAssign).toHaveBeenCalled();
|
||||
expect(mockPin).not.toHaveBeenCalled();
|
||||
});
|
||||
/* A chat this tab believes is already out of every project still gets the
|
||||
* write: the belief can be a snapshot another tab has moved on from, and
|
||||
* unpinning on it would leave the chat in a project and out of both lists.
|
||||
* The notice belongs to a move that happened, so a write that changed
|
||||
* nothing stays quiet. */
|
||||
it('confirms the removal with the server and announces only a real move', async () => {
|
||||
mockAssign.mockResolvedValue({ previousProjectId: null, projectId: null });
|
||||
const { result } = renderHook(() => ({
|
||||
assign: useAssignDroppedConversation(),
|
||||
unpin: useUnpinDroppedConversation(),
|
||||
}));
|
||||
|
||||
await drop(result.current.assign, result.current.unpin, {
|
||||
conversationId: 'c1',
|
||||
chatProjectId: null,
|
||||
pinned: true,
|
||||
});
|
||||
|
||||
expect(mockAssign).toHaveBeenCalledWith({ conversationId: 'c1', projectId: null });
|
||||
expect(mockShowToast).not.toHaveBeenCalled();
|
||||
expect(mockPin).toHaveBeenCalledWith(
|
||||
{ conversationId: 'c1', pinned: false },
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,8 +3,11 @@ import { useToastContext } from '@librechat/client';
|
|||
import { QueryKeys } from 'librechat-data-provider';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import type { TConversation } from 'librechat-data-provider';
|
||||
import {
|
||||
useAssignConversationToProjectMutation,
|
||||
usePinConversationMutation,
|
||||
} from '~/data-provider';
|
||||
import { getPendingAssignment } from '~/data-provider/Projects/mutations';
|
||||
import { useAssignConversationToProjectMutation } from '~/data-provider';
|
||||
import { NotificationSeverity } from '~/common';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
|
|
@ -77,40 +80,102 @@ export const useEffectiveProjectId = () => {
|
|||
);
|
||||
};
|
||||
|
||||
/** Files a dropped conversation, resolving to whether it now sits where the
|
||||
* drop asked. */
|
||||
export type AssignDroppedConversation = (
|
||||
item: ConversationDragItem,
|
||||
projectId: string | null,
|
||||
) => Promise<boolean>;
|
||||
|
||||
/** Unpins a dropped conversation, if it was pinned at all. */
|
||||
export type UnpinDroppedConversation = (item: ConversationDragItem) => void;
|
||||
|
||||
/** Files a dragged conversation into a project, or back into the root chats
|
||||
* list on `projectId: null`. The mutation owns every cache invalidation
|
||||
* (chats, pinned rows, project stats); this adds the toast feedback the
|
||||
* options-menu path already shows for the same action. */
|
||||
export const useAssignDroppedConversation = () => {
|
||||
* options-menu path already shows for the same action.
|
||||
*
|
||||
* Resolves to whether the chat now sits where the drop asked: `true` for a
|
||||
* drop that had nothing to file, `false` while another write is still on its
|
||||
* way there. A caller with a second half to apply can therefore wait for this
|
||||
* one instead of racing it. */
|
||||
export const useAssignDroppedConversation = (): AssignDroppedConversation => {
|
||||
const localize = useLocalize();
|
||||
const { showToast } = useToastContext();
|
||||
const assignConversation = useAssignConversationToProjectMutation();
|
||||
const effectiveProjectId = useEffectiveProjectId();
|
||||
|
||||
return useCallback(
|
||||
(item: ConversationDragItem, projectId: string | null) => {
|
||||
(item: ConversationDragItem, projectId: string | null): Promise<boolean> => {
|
||||
const conversationId = item.conversationId;
|
||||
if (!conversationId || effectiveProjectId(item) === projectId) {
|
||||
return;
|
||||
if (!conversationId) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
/* The mutation serializes these per conversation and records where each
|
||||
* is headed, so this only has to report the outcome. */
|
||||
void assignConversation.mutateAsync({ conversationId, projectId }).then(
|
||||
() =>
|
||||
showToast({
|
||||
message: localize('com_ui_project_updated'),
|
||||
severity: NotificationSeverity.SUCCESS,
|
||||
showIcon: true,
|
||||
}),
|
||||
() =>
|
||||
/* No local short-circuit. Every answer this side could give about where
|
||||
* the chat already sits is a guess: a pending write is a request rather
|
||||
* than an outcome, a cached project can be a snapshot another tab has
|
||||
* moved on from, and the drag item's own copy is older still. A drop that
|
||||
* acted on any of them could unpin a chat that stayed in its project,
|
||||
* leaving it out of both lists. So the write always goes, and the server's
|
||||
* answer is what the drop acts on; repeating an assignment the chat
|
||||
* already has is the no-op update it looks like, and the mutation queues
|
||||
* writes per conversation so it lands after any already out.
|
||||
*
|
||||
* The success notice still belongs to a move that happened, which is why
|
||||
* it reads the two project ids the response carries rather than the fact
|
||||
* that a request was sent. */
|
||||
return assignConversation.mutateAsync({ conversationId, projectId }).then(
|
||||
(result) => {
|
||||
if (result.previousProjectId !== result.projectId) {
|
||||
showToast({
|
||||
message: localize('com_ui_project_updated'),
|
||||
severity: NotificationSeverity.SUCCESS,
|
||||
showIcon: true,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
},
|
||||
() => {
|
||||
showToast({
|
||||
message: localize('com_ui_project_update_error'),
|
||||
severity: NotificationSeverity.ERROR,
|
||||
showIcon: true,
|
||||
}),
|
||||
});
|
||||
return false;
|
||||
},
|
||||
);
|
||||
},
|
||||
[assignConversation, effectiveProjectId, localize, showToast],
|
||||
[assignConversation, localize, showToast],
|
||||
);
|
||||
};
|
||||
|
||||
/** Unpins a dragged conversation, for a drop on the plain Chats list: a chat
|
||||
* landing there is being asked to be an ordinary chat, which a pinned one is
|
||||
* not. Silent on success — the row leaving the pinned section is the feedback
|
||||
* — and reports only the failure, as the row badge does. */
|
||||
export const useUnpinDroppedConversation = (): UnpinDroppedConversation => {
|
||||
const localize = useLocalize();
|
||||
const { showToast } = useToastContext();
|
||||
const pinConversation = usePinConversationMutation();
|
||||
|
||||
return useCallback(
|
||||
(item: ConversationDragItem) => {
|
||||
const conversationId = item.conversationId;
|
||||
if (!conversationId || item.pinned !== true) {
|
||||
return;
|
||||
}
|
||||
pinConversation.mutate(
|
||||
{ conversationId, pinned: false },
|
||||
{
|
||||
onError: () =>
|
||||
showToast({
|
||||
message: localize('com_ui_unpin_error'),
|
||||
severity: NotificationSeverity.ERROR,
|
||||
showIcon: true,
|
||||
}),
|
||||
},
|
||||
);
|
||||
},
|
||||
[pinConversation, localize, showToast],
|
||||
);
|
||||
};
|
||||
|
||||
|
|
@ -142,26 +207,47 @@ export const shouldSwapOnHover = ({
|
|||
return offsetY <= middleY;
|
||||
};
|
||||
|
||||
/** Rewrites only the slots the visible keys occupy in the stored order, so a
|
||||
* reorder performed while a filter hides part of the list keeps every hidden
|
||||
* key exactly where it was instead of dropping it. Visible keys the stored
|
||||
* order does not know about append at the end. */
|
||||
/** Which group of the Pinned section a stored key belongs to. The section
|
||||
* orders its two kinds independently, so a merge has to know them apart. */
|
||||
const keyKind = (key: string): 'convo' | 'favorite' =>
|
||||
key.startsWith('convo:') ? 'convo' : 'favorite';
|
||||
|
||||
/**
|
||||
* Rewrites only the slots the visible keys occupy in the stored order, so a
|
||||
* reorder performed while a filter hides part of the list keeps every hidden
|
||||
* key exactly where it was instead of dropping it. Visible keys the stored
|
||||
* order does not know about append after their own kind.
|
||||
*
|
||||
* The stored order is grouped first, because that is how the section reads it
|
||||
* back, and each kind is then substituted within its own run. An order saved
|
||||
* before the kinds were kept apart can interleave them, and merging across that
|
||||
* interleaving let a reorder of two visible chats carry a hidden chat between
|
||||
* them across a favorite — moving a row nobody had touched once the rest of the
|
||||
* pinned list finally arrived.
|
||||
*/
|
||||
export const mergeVisibleOrder = (stored: string[], visible: string[]): string[] => {
|
||||
const visibleSet = new Set(visible);
|
||||
const merged: string[] = [];
|
||||
let next = 0;
|
||||
for (const key of stored) {
|
||||
if (!visibleSet.has(key)) {
|
||||
merged.push(key);
|
||||
continue;
|
||||
const kinds: Array<'favorite' | 'convo'> = ['favorite', 'convo'];
|
||||
return kinds.flatMap((kind) => {
|
||||
const slots = stored.filter((key) => keyKind(key) === kind);
|
||||
const incoming = visible.filter((key) => keyKind(key) === kind);
|
||||
const merged: string[] = [];
|
||||
let next = 0;
|
||||
for (const key of slots) {
|
||||
if (!visibleSet.has(key)) {
|
||||
merged.push(key);
|
||||
continue;
|
||||
}
|
||||
if (next < incoming.length) {
|
||||
merged.push(incoming[next]);
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
if (next < visible.length) {
|
||||
merged.push(visible[next]);
|
||||
next++;
|
||||
/* Keys the stored order never held, such as a row pinned since it was
|
||||
* written. */
|
||||
for (; next < incoming.length; next += 1) {
|
||||
merged.push(incoming[next]);
|
||||
}
|
||||
}
|
||||
for (; next < visible.length; next++) {
|
||||
merged.push(visible[next]);
|
||||
}
|
||||
return merged;
|
||||
return merged;
|
||||
});
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import React from 'react';
|
||||
import { PinOff } from 'lucide-react';
|
||||
import { TooltipAnchor } from '@librechat/client';
|
||||
import { EModelEndpoint } from 'librechat-data-provider';
|
||||
import type { Agent, TModelSpec, TEndpointsConfig } from 'librechat-data-provider';
|
||||
import type { FavoriteModel } from '~/store/favorites';
|
||||
import SpecIcon from '~/components/Chat/Menus/Endpoints/components/SpecIcon';
|
||||
import UnpinButton from '~/components/Conversations/UnpinButton';
|
||||
import MinimalIcon from '~/components/Endpoints/MinimalIcon';
|
||||
import { useFavorites, useLocalize } from '~/hooks';
|
||||
import { renderAgentAvatar } from '~/utils';
|
||||
|
|
@ -141,35 +140,19 @@ export default function FavoriteItem(props: FavoriteItemProps) {
|
|||
<span className="truncate">{name}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={
|
||||
// Interactive by default so it's tappable on touch; only
|
||||
// hidden-until-hover on hover-capable pointers. Otherwise the
|
||||
// whole row is hover-dependent and the first tap just reveals
|
||||
// this instead of selecting (the iOS double-tap).
|
||||
'absolute right-1 flex items-center group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 [@media(hover:hover)]:pointer-events-none [@media(hover:hover)]:opacity-0'
|
||||
}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<TooltipAnchor
|
||||
description={localize('com_ui_unpin')}
|
||||
side="top"
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={localize('com_ui_unpin')}
|
||||
data-testid="favorite-unpin-button"
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-text-secondary transition-colors duration-150 hover:border-border-medium hover:bg-surface-active hover:text-text-primary focus-visible:border-border-medium focus-visible:bg-surface-active focus-visible:text-text-primary focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:hover)]:opacity-0"
|
||||
onClick={handleRemove}
|
||||
onKeyDown={(e: React.KeyboardEvent<HTMLButtonElement>) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PinOff className="size-4" aria-hidden={true} />
|
||||
</button>
|
||||
}
|
||||
{/* Inset by the same 4px the 28px control leaves above and below it in a
|
||||
36px row, which is also where a pinned chat keeps its last control, so
|
||||
the two row kinds line up. Clicks are swallowed here rather than
|
||||
reaching the row underneath. */}
|
||||
<div className="absolute right-1 flex items-center" onClick={(e) => e.stopPropagation()}>
|
||||
<UnpinButton
|
||||
testId="favorite-unpin-button"
|
||||
onClick={handleRemove}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.stopPropagation();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
260
e2e/specs/mock/scenarios/pinned-drag-rules.spec.ts
Normal file
260
e2e/specs/mock/scenarios/pinned-drag-rules.spec.ts
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
import { randomUUID } from 'crypto';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
import {
|
||||
chatsListRow,
|
||||
convoEntryKey,
|
||||
dragRowOnto,
|
||||
favoriteEntryKey,
|
||||
favoriteRowByName,
|
||||
isConversationPinned,
|
||||
openWithPinnedSection,
|
||||
pinnedConvoRow,
|
||||
pinnedRowKinds,
|
||||
pinnedRowNames,
|
||||
pinnedRows,
|
||||
pinnedSection,
|
||||
reloadWithPinnedSection,
|
||||
removePins,
|
||||
resetPinnedState,
|
||||
seedPinnedConversations,
|
||||
setFavorites,
|
||||
setPinnedOrder,
|
||||
} from './pinned.helpers';
|
||||
import type { SeededPin } from './pinned.helpers';
|
||||
import { getE2EUser } from '../../../setup/user';
|
||||
import { deleteConversations, seedConversations } from '../db';
|
||||
|
||||
/* Seeding a pinned list and reloading is the slow part of every test here, and it
|
||||
* runs in hooks, which do not read a `test.setTimeout` call made inside a test
|
||||
* body: a loaded machine timed the `beforeEach` out at the default 30s while the
|
||||
* test itself was allowed 60. Configured once for the file instead, with room
|
||||
* for the first test of a run, which also pays the app's cold start against a
|
||||
* database that may be a network hop away. */
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
const MOCK_FAVORITE_A = { endpoint: 'Mock Provider A', model: 'mock-model-a' } as const;
|
||||
const MOCK_FAVORITE_B = { endpoint: 'Mock Provider B', model: 'mock-model-b' } as const;
|
||||
|
||||
let seededPins: SeededPin[] = [];
|
||||
/** Chats seeded unpinned, which a test may leave pinned on purpose. */
|
||||
const unpinnedConversationIds: string[] = [];
|
||||
|
||||
test.afterEach(async ({ page }) => {
|
||||
const pins = seededPins.splice(0);
|
||||
const plain = unpinnedConversationIds.splice(0);
|
||||
/* A test that skipped on a pointer without hover seeded nothing and left no
|
||||
* page to read a token from: reaching for one here is what turns a skip into
|
||||
* a failure. */
|
||||
if (pins.length === 0 && plain.length === 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await resetPinnedState(page);
|
||||
} finally {
|
||||
await removePins(pins);
|
||||
if (plain.length > 0) {
|
||||
await deleteConversations(plain);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const uniqueTitles = (prefix: string, count: number): string[] =>
|
||||
Array.from({ length: count }, (_, index) => `${prefix} ${index + 1} ${randomUUID()}`);
|
||||
|
||||
const dragSource = (row: Locator): Locator => row.locator('xpath=..');
|
||||
|
||||
async function skipWithoutHover(page: Page): Promise<void> {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(!hasHover, 'pointer drag requires a hover-capable pointer');
|
||||
}
|
||||
test.describe('pinned drag rules', () => {
|
||||
test('dropping a pinned chat on Chats unpins it @scenario:dropping-a-pinned-chat-on-chats-unpins-it', async ({
|
||||
page,
|
||||
}) => {
|
||||
await skipWithoutHover(page);
|
||||
const [draggedTitle, remainingTitle] = uniqueTitles('drop-to-chats', 2);
|
||||
seededPins = await seedPinnedConversations([draggedTitle, remainingTitle]);
|
||||
|
||||
await openWithPinnedSection(page);
|
||||
const draggedRow = pinnedConvoRow(page, draggedTitle);
|
||||
await expect(draggedRow).toBeVisible();
|
||||
await expect(pinnedConvoRow(page, remainingTitle)).toBeVisible();
|
||||
|
||||
/** The old Chats drop filed the chat but left `pinned: true`, so it remained
|
||||
* visible in Pinned after the user had dragged it out of that section. */
|
||||
await dragRowOnto(
|
||||
page,
|
||||
dragSource(draggedRow),
|
||||
page.getByRole('button', { name: 'Chats', exact: true }),
|
||||
0.5,
|
||||
);
|
||||
|
||||
await expect(pinnedConvoRow(page, draggedTitle)).toHaveCount(0);
|
||||
await expect(chatsListRow(page, draggedTitle)).toBeVisible();
|
||||
await expect.poll(() => isConversationPinned(seededPins[0].conversationId)).toBe(false);
|
||||
|
||||
await reloadWithPinnedSection(page);
|
||||
await expect(pinnedSection(page)).toBeVisible();
|
||||
await expect(pinnedConvoRow(page, draggedTitle)).toHaveCount(0);
|
||||
await expect(chatsListRow(page, draggedTitle)).toBeVisible();
|
||||
});
|
||||
|
||||
test('dropping an unpinned chat on a pinned row pins it @scenario:dropping-a-chat-on-a-pinned-row-pins-it', async ({
|
||||
page,
|
||||
}) => {
|
||||
await skipWithoutHover(page);
|
||||
const [pinnedTitle] = uniqueTitles('pin-on-row', 1);
|
||||
const plainTitle = `pin-on-row plain ${randomUUID()}`;
|
||||
seededPins = await seedPinnedConversations([pinnedTitle]);
|
||||
const plain = randomUUID();
|
||||
await seedConversations(getE2EUser().email, [
|
||||
{ conversationId: plain, title: plainTitle, updatedAt: new Date() },
|
||||
]);
|
||||
unpinnedConversationIds.push(plain);
|
||||
|
||||
await openWithPinnedSection(page);
|
||||
await expect(pinnedConvoRow(page, pinnedTitle)).toBeVisible();
|
||||
const plainRow = chatsListRow(page, plainTitle);
|
||||
await expect(plainRow).toBeVisible();
|
||||
|
||||
/** The section takes a chat dropped anywhere on it, and a row is part of the
|
||||
* section: a release that lands on one rather than between two has to pin
|
||||
* the chat, not be swallowed by the row it landed on. */
|
||||
await dragRowOnto(page, plainRow, pinnedConvoRow(page, pinnedTitle), 0.5);
|
||||
|
||||
await expect(pinnedConvoRow(page, plainTitle)).toBeVisible();
|
||||
await expect.poll(() => isConversationPinned(plain)).toBe(true);
|
||||
});
|
||||
|
||||
test('a pinned chat cannot be dragged through a pinned model @scenario:a-pinned-chat-cannot-be-dragged-through-a-pinned-model', async ({
|
||||
page,
|
||||
}) => {
|
||||
await skipWithoutHover(page);
|
||||
/** One chat to start with: a second one below it would be a legitimate
|
||||
* same-kind neighbour for the pointer to swap with on its way up, and the
|
||||
* order would change for a reason that has nothing to do with the boundary
|
||||
* being tested. */
|
||||
const [draggedTitle] = uniqueTitles('kind-boundary', 1);
|
||||
seededPins = await seedPinnedConversations([draggedTitle]);
|
||||
|
||||
await openWithPinnedSection(page);
|
||||
await setFavorites(page, [MOCK_FAVORITE_A, MOCK_FAVORITE_B]);
|
||||
await reloadWithPinnedSection(page);
|
||||
await expect(favoriteRowByName(page, MOCK_FAVORITE_A.model)).toBeVisible();
|
||||
await expect(favoriteRowByName(page, MOCK_FAVORITE_B.model)).toBeVisible();
|
||||
await expect(pinnedRows(page)).toHaveCount(3);
|
||||
|
||||
const initialNames = await pinnedRowNames(page);
|
||||
const dragged = dragSource(pinnedConvoRow(page, draggedTitle));
|
||||
const favorite = favoriteRowByName(page, MOCK_FAVORITE_A.model);
|
||||
|
||||
/** Dropped on either half of a pinned model, because the half decides which
|
||||
* way a same-kind row would have been displaced: a chat that could pass
|
||||
* through this row would land above it from the top half and below it from
|
||||
* the bottom half, and the list cannot honour either. */
|
||||
await dragRowOnto(page, dragged, favorite, 0.25);
|
||||
await expect.poll(() => pinnedRowNames(page)).toEqual(initialNames);
|
||||
await dragRowOnto(page, dragged, favorite, 0.75);
|
||||
await expect.poll(() => pinnedRowNames(page)).toEqual(initialNames);
|
||||
|
||||
/** The same gesture must still reorder against the chat's own kind, or this
|
||||
* test would pass just as well against a drag source that does nothing. */
|
||||
const [neighbourTitle] = uniqueTitles('kind-boundary-neighbour', 1);
|
||||
seededPins.push(...(await seedPinnedConversations([neighbourTitle])));
|
||||
await reloadWithPinnedSection(page);
|
||||
await expect(pinnedRows(page)).toHaveCount(4);
|
||||
const withNeighbour = await pinnedRowNames(page);
|
||||
const lower = withNeighbour[3];
|
||||
const upper = withNeighbour[2];
|
||||
|
||||
await dragRowOnto(
|
||||
page,
|
||||
dragSource(pinnedConvoRow(page, lower)),
|
||||
pinnedConvoRow(page, upper),
|
||||
0.25,
|
||||
);
|
||||
await expect
|
||||
.poll(() => pinnedRowNames(page))
|
||||
.toEqual([
|
||||
`${MOCK_FAVORITE_A.model} (Model)`,
|
||||
`${MOCK_FAVORITE_B.model} (Model)`,
|
||||
lower,
|
||||
upper,
|
||||
]);
|
||||
});
|
||||
|
||||
/** A keyboard step at the boundary used to cross into the other row kind,
|
||||
* announcing a position from the combined list instead of refusing the move. */
|
||||
test('Alt+Arrow stops a pinned row at its kind edge @scenario:alt-arrow-stops-a-pinned-row-at-its-kinds-edge', async ({
|
||||
page,
|
||||
}) => {
|
||||
const [firstTitle] = uniqueTitles('keyboard-kind-edge', 1);
|
||||
seededPins = await seedPinnedConversations([firstTitle]);
|
||||
|
||||
await openWithPinnedSection(page);
|
||||
await setFavorites(page, [MOCK_FAVORITE_A]);
|
||||
await setPinnedOrder(page, [
|
||||
favoriteEntryKey(MOCK_FAVORITE_A),
|
||||
convoEntryKey(seededPins[0].conversationId),
|
||||
]);
|
||||
await reloadWithPinnedSection(page);
|
||||
await expect(favoriteRowByName(page, MOCK_FAVORITE_A.model)).toBeVisible();
|
||||
await expect(pinnedRows(page)).toHaveCount(2);
|
||||
|
||||
const firstChatFocus = pinnedConvoRow(page, firstTitle).getByRole('button').first();
|
||||
await firstChatFocus.focus();
|
||||
await firstChatFocus.press('Alt+ArrowUp');
|
||||
await expect
|
||||
.poll(() => pinnedRowNames(page))
|
||||
.toEqual([`${MOCK_FAVORITE_A.model} (Model)`, firstTitle]);
|
||||
await expect(pinnedSection(page).getByRole('status')).toHaveText('');
|
||||
|
||||
const [secondTitle] = uniqueTitles('keyboard-kind-edge', 1);
|
||||
const secondPins = await seedPinnedConversations([secondTitle]);
|
||||
seededPins.push(...secondPins);
|
||||
await setPinnedOrder(page, [
|
||||
favoriteEntryKey(MOCK_FAVORITE_A),
|
||||
convoEntryKey(seededPins[0].conversationId),
|
||||
convoEntryKey(secondPins[0].conversationId),
|
||||
]);
|
||||
await reloadWithPinnedSection(page);
|
||||
await expect(favoriteRowByName(page, MOCK_FAVORITE_A.model)).toBeVisible();
|
||||
await expect(pinnedRows(page)).toHaveCount(3);
|
||||
|
||||
const secondChatFocus = pinnedConvoRow(page, secondTitle).getByRole('button').first();
|
||||
await secondChatFocus.focus();
|
||||
await secondChatFocus.press('Alt+ArrowUp');
|
||||
await expect
|
||||
.poll(() => pinnedRowNames(page))
|
||||
.toEqual([`${MOCK_FAVORITE_A.model} (Model)`, secondTitle, firstTitle]);
|
||||
await expect(pinnedSection(page).getByRole('status')).toHaveText('Moved to position 1 of 2');
|
||||
});
|
||||
|
||||
test('a stored interleaved pinned order loads grouped @scenario:a-stored-interleaved-pinned-order-loads-grouped', async ({
|
||||
page,
|
||||
}) => {
|
||||
const [firstTitle, secondTitle] = uniqueTitles('stored-interleave', 2);
|
||||
seededPins = await seedPinnedConversations([firstTitle, secondTitle]);
|
||||
|
||||
await openWithPinnedSection(page);
|
||||
await setFavorites(page, [MOCK_FAVORITE_A]);
|
||||
/** A pre-grouping order is the persisted bug: if read literally, each row is
|
||||
* walled in by a different kind and can no longer swap with its neighbours. */
|
||||
await setPinnedOrder(page, [
|
||||
convoEntryKey(seededPins[0].conversationId),
|
||||
favoriteEntryKey(MOCK_FAVORITE_A),
|
||||
convoEntryKey(seededPins[1].conversationId),
|
||||
]);
|
||||
await reloadWithPinnedSection(page);
|
||||
|
||||
await expect(favoriteRowByName(page, MOCK_FAVORITE_A.model)).toBeVisible();
|
||||
await expect(pinnedRows(page)).toHaveCount(3);
|
||||
expect(await pinnedRowKinds(page)).toEqual(['favorite', 'convo', 'convo']);
|
||||
expect(await pinnedRowNames(page)).toEqual([
|
||||
`${MOCK_FAVORITE_A.model} (Model)`,
|
||||
firstTitle,
|
||||
secondTitle,
|
||||
]);
|
||||
});
|
||||
});
|
||||
256
e2e/specs/mock/scenarios/pinned-row-controls.spec.ts
Normal file
256
e2e/specs/mock/scenarios/pinned-row-controls.spec.ts
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
import { randomUUID } from 'crypto';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
import {
|
||||
backgroundColor,
|
||||
borderRadius,
|
||||
favoriteRowByName,
|
||||
isConversationPinned,
|
||||
isTransparent,
|
||||
openWithPinnedSection,
|
||||
pinnedConvoRow,
|
||||
reloadWithPinnedSection,
|
||||
removePins,
|
||||
resetPinnedState,
|
||||
seedPinnedConversations,
|
||||
setFavorites,
|
||||
} from './pinned.helpers';
|
||||
import type { ModelFavorite, SeededPin } from './pinned.helpers';
|
||||
|
||||
/* Seeding a pinned list and reloading is the slow part of every test here, and it
|
||||
* runs in hooks, which do not read a `test.setTimeout` call made inside a test
|
||||
* body: a loaded machine timed the `beforeEach` out at the default 30s while the
|
||||
* test itself was allowed 60. Configured once for the file instead, with room
|
||||
* for the first test of a run, which also pays the app's cold start against a
|
||||
* database that may be a network hop away. */
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
const FAVORITE: ModelFavorite = {
|
||||
endpoint: 'Mock Provider A',
|
||||
model: 'mock-model-a',
|
||||
};
|
||||
|
||||
const controlState = (locator: Locator) =>
|
||||
locator.evaluate((element) => {
|
||||
const style = getComputedStyle(element as HTMLElement);
|
||||
return {
|
||||
opacity: style.opacity,
|
||||
pointerEvents: style.pointerEvents,
|
||||
};
|
||||
});
|
||||
|
||||
const controlAppearance = (locator: Locator) =>
|
||||
locator.evaluate((element) => {
|
||||
const style = getComputedStyle(element as HTMLElement);
|
||||
const box = element.getBoundingClientRect();
|
||||
return {
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
color: style.color,
|
||||
radius: style.borderTopLeftRadius,
|
||||
};
|
||||
});
|
||||
|
||||
const nextFrame = (page: Page) =>
|
||||
page.evaluate(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => resolve());
|
||||
}),
|
||||
);
|
||||
|
||||
let seededPins: SeededPin[] = [];
|
||||
|
||||
test.describe('pinned row controls', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
seededPins = await seedPinnedConversations([
|
||||
`Pinned controls first ${randomUUID()}`,
|
||||
`Pinned controls second ${randomUUID()}`,
|
||||
]);
|
||||
await openWithPinnedSection(page);
|
||||
await setFavorites(page, [FAVORITE]);
|
||||
await reloadWithPinnedSection(page);
|
||||
});
|
||||
|
||||
test.afterEach(async ({ page }) => {
|
||||
const pins = seededPins;
|
||||
seededPins = [];
|
||||
await removePins(pins);
|
||||
await resetPinnedState(page);
|
||||
});
|
||||
|
||||
/** Regression: a control using the row radius filled its rounded corner-to-corner. */
|
||||
test('controls draw inside their row @scenario:pinned-row-controls-draw-inside-their-row', async ({
|
||||
page,
|
||||
}) => {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(!hasHover, 'pointer hover is a desktop-only path');
|
||||
const row = pinnedConvoRow(page, seededPins[0].title);
|
||||
const badge = row.getByTestId('convo-unpin-button');
|
||||
const restingRadius = await borderRadius(row);
|
||||
|
||||
await row.hover();
|
||||
const trigger = row.getByRole('button', { name: 'Conversation Menu Options' });
|
||||
await expect(trigger).toBeVisible();
|
||||
await trigger.hover();
|
||||
|
||||
expect(restingRadius).toBe(8);
|
||||
expect(await borderRadius(badge)).toBe(6);
|
||||
expect(await borderRadius(trigger)).toBe(6);
|
||||
expect(await borderRadius(row)).toBe(restingRadius);
|
||||
expect(isTransparent(await backgroundColor(trigger))).toBe(false);
|
||||
});
|
||||
|
||||
/** Regression: chat and favorite rows used different unpin colours and reveal rules. */
|
||||
test('both pinned kinds show the same unpin badge @scenario:both-pinned-kinds-show-the-same-unpin-badge', async ({
|
||||
page,
|
||||
}) => {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(!hasHover, 'badge reveal comparison is a desktop-only path');
|
||||
|
||||
const chatRow = pinnedConvoRow(page, seededPins[0].title);
|
||||
const favoriteRow = favoriteRowByName(page, FAVORITE.model);
|
||||
const chatBadge = chatRow.getByTestId('convo-unpin-button');
|
||||
const favoriteBadge = favoriteRow.getByTestId('favorite-unpin-button');
|
||||
const chatAppearance = await controlAppearance(chatBadge);
|
||||
const favoriteAppearance = await controlAppearance(favoriteBadge);
|
||||
|
||||
expect(favoriteAppearance).toEqual(chatAppearance);
|
||||
await expect
|
||||
.poll(() => controlState(chatBadge))
|
||||
.toEqual({
|
||||
opacity: '0',
|
||||
pointerEvents: 'none',
|
||||
});
|
||||
await expect
|
||||
.poll(() => controlState(favoriteBadge))
|
||||
.toEqual({
|
||||
opacity: '0',
|
||||
pointerEvents: 'none',
|
||||
});
|
||||
|
||||
await chatRow.hover();
|
||||
await expect
|
||||
.poll(() => controlState(chatBadge))
|
||||
.toEqual({
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
});
|
||||
|
||||
await favoriteRow.hover();
|
||||
await expect
|
||||
.poll(() => controlState(favoriteBadge))
|
||||
.toEqual({
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
});
|
||||
});
|
||||
|
||||
/** Regression: opening a row menu made its still-needed unpin badge disappear. */
|
||||
test('the unpin badge stays while its row menu is open @scenario:the-unpin-badge-stays-while-its-rows-menu-is-open', async ({
|
||||
page,
|
||||
}) => {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(!hasHover, 'pointer hover is a desktop-only path');
|
||||
const row = pinnedConvoRow(page, seededPins[0].title);
|
||||
const badge = row.getByTestId('convo-unpin-button');
|
||||
await row.hover();
|
||||
|
||||
const trigger = row.getByRole('button', { name: 'Conversation Menu Options' });
|
||||
await expect(trigger).toBeVisible();
|
||||
await trigger.click();
|
||||
const menu = page.getByRole('menu').last();
|
||||
await expect(menu).toBeVisible();
|
||||
await menu.hover();
|
||||
|
||||
await expect
|
||||
.poll(() => controlState(badge))
|
||||
.toEqual({
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
});
|
||||
await badge.click({ trial: true });
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(menu).toBeHidden();
|
||||
/** Closing the menu returns focus to the trigger, and a row holding focus
|
||||
* keeps its badge on purpose — the badge withdraws once neither the pointer
|
||||
* nor the keyboard is on the row. */
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||||
await page.mouse.move(1, 1);
|
||||
await expect
|
||||
.poll(() => controlState(badge))
|
||||
.toEqual({
|
||||
opacity: '0',
|
||||
pointerEvents: 'none',
|
||||
});
|
||||
});
|
||||
|
||||
/** Regression: mounting the overflow trigger after hover shifted the badge and caused a flicker. */
|
||||
test('hovering a pinned chat row holds its controls still @scenario:hovering-a-pinned-chat-row-holds-its-controls-still', async ({
|
||||
page,
|
||||
}) => {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(!hasHover, 'pointer hover is a desktop-only path');
|
||||
const row = pinnedConvoRow(page, seededPins[0].title);
|
||||
const badge = row.getByTestId('convo-unpin-button');
|
||||
const beforeHover = await badge.boundingBox();
|
||||
expect(beforeHover).not.toBeNull();
|
||||
const beforeHoverX = beforeHover?.x;
|
||||
expect(beforeHoverX).toBeDefined();
|
||||
|
||||
const rowBox = await row.boundingBox();
|
||||
expect(rowBox).not.toBeNull();
|
||||
await page.mouse.move(
|
||||
(rowBox?.x ?? 0) + (rowBox?.width ?? 0) / 2,
|
||||
(rowBox?.y ?? 0) + (rowBox?.height ?? 0) / 2,
|
||||
);
|
||||
const immediatelyAfterEnter = await badge.boundingBox();
|
||||
expect(immediatelyAfterEnter).not.toBeNull();
|
||||
const immediatelyAfterEnterX = immediatelyAfterEnter?.x;
|
||||
expect(immediatelyAfterEnterX).toBeDefined();
|
||||
|
||||
const trigger = row.getByRole('button', { name: 'Conversation Menu Options' });
|
||||
await expect(trigger).toBeVisible();
|
||||
await nextFrame(page);
|
||||
const afterTriggerMounted = await badge.boundingBox();
|
||||
expect(afterTriggerMounted).not.toBeNull();
|
||||
expect(
|
||||
Math.abs((afterTriggerMounted?.x ?? 0) - (immediatelyAfterEnterX ?? 0)),
|
||||
).toBeLessThanOrEqual(1);
|
||||
|
||||
const firstTriggerHandle = await trigger.elementHandle();
|
||||
expect(firstTriggerHandle).not.toBeNull();
|
||||
await firstTriggerHandle?.evaluate((element) => {
|
||||
element.setAttribute('data-e2e-mounted-once', 'true');
|
||||
});
|
||||
|
||||
await page.mouse.move(1, 1);
|
||||
await expect(trigger).toBeAttached();
|
||||
await row.hover();
|
||||
await expect(trigger).toBeVisible();
|
||||
await expect(trigger).toHaveAttribute('data-e2e-mounted-once', 'true');
|
||||
});
|
||||
|
||||
/** Regression: on touch, the first tap only revealed the badge instead of unpinning. */
|
||||
test('a touch tap reaches the unpin badge directly @scenario:a-touch-tap-reaches-the-unpin-badge-directly', async ({
|
||||
page,
|
||||
}) => {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(hasHover, 'direct badge tap is a touch-only path');
|
||||
|
||||
const row = pinnedConvoRow(page, seededPins[0].title);
|
||||
const badge = row.getByTestId('convo-unpin-button');
|
||||
await expect(badge).toBeVisible();
|
||||
await expect
|
||||
.poll(() => controlState(badge))
|
||||
.toEqual({
|
||||
opacity: '1',
|
||||
pointerEvents: 'auto',
|
||||
});
|
||||
|
||||
await badge.tap();
|
||||
await expect(row).toHaveCount(0);
|
||||
await expect.poll(() => isConversationPinned(seededPins[0].conversationId)).toBe(false);
|
||||
});
|
||||
});
|
||||
289
e2e/specs/mock/scenarios/pinned.helpers.ts
Normal file
289
e2e/specs/mock/scenarios/pinned.helpers.ts
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
import { randomUUID } from 'crypto';
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
import { getE2EUser } from '../../../setup/user';
|
||||
import { getAccessToken, requestJson } from '../helpers';
|
||||
import { deleteConversations, withMongo } from '../db';
|
||||
|
||||
/** `aria-label` of the Pinned section's region (`com_ui_pinned`). */
|
||||
export const PINNED_REGION = 'Pinned';
|
||||
|
||||
const userEmail = getE2EUser().email;
|
||||
|
||||
export type SeededPin = { conversationId: string; title: string };
|
||||
|
||||
/**
|
||||
* A pinned chat is an ordinary conversation carrying `pinned: true`; the sidebar
|
||||
* reads that flag to move the row out of the date groups and into the Pinned
|
||||
* section. Inserted directly, the way `seedConversations` does, so a spec can
|
||||
* choose the row's title and its position in the natural order without driving
|
||||
* the pin menu first.
|
||||
*/
|
||||
export async function seedPinnedConversations(titles: string[]): Promise<SeededPin[]> {
|
||||
const now = Date.now();
|
||||
const pins: SeededPin[] = titles.map((title) => ({ conversationId: randomUUID(), title }));
|
||||
await withMongo(async (db) => {
|
||||
const user = await db.collection('users').findOne({ email: userEmail });
|
||||
if (!user) {
|
||||
throw new Error(`E2E seed: user "${userEmail}" not found`);
|
||||
}
|
||||
await db.collection('conversations').insertMany(
|
||||
pins.map((pin, index) => ({
|
||||
conversationId: pin.conversationId,
|
||||
title: pin.title,
|
||||
user: String(user._id),
|
||||
endpoint: 'openAI',
|
||||
isArchived: false,
|
||||
pinned: true,
|
||||
/** Descending by `updatedAt` is the natural order of the section, so the
|
||||
* first title given is the first row rendered. */
|
||||
createdAt: new Date(now - index * 1000),
|
||||
updatedAt: new Date(now - index * 1000),
|
||||
__v: 0,
|
||||
})),
|
||||
);
|
||||
});
|
||||
return pins;
|
||||
}
|
||||
|
||||
/** Whether the stored conversation is still pinned, for the drop that unpins. */
|
||||
export async function isConversationPinned(conversationId: string): Promise<boolean> {
|
||||
return withMongo(async (db) => {
|
||||
const convo = await db.collection('conversations').findOne({ conversationId });
|
||||
return convo?.pinned === true;
|
||||
});
|
||||
}
|
||||
|
||||
export type ModelFavorite = { endpoint: string; model: string };
|
||||
|
||||
/**
|
||||
* The key a favorite model takes in the stored pinned order. The endpoint is
|
||||
* length-prefixed so that an endpoint or model containing `:` cannot collide
|
||||
* with another pair — the encoding the section itself uses.
|
||||
*/
|
||||
export const favoriteEntryKey = ({ endpoint, model }: ModelFavorite): string =>
|
||||
`model:${endpoint.length}:${endpoint}:${model}`;
|
||||
|
||||
/** The key a pinned chat takes in the stored pinned order. */
|
||||
export const convoEntryKey = (conversationId: string): string => `convo:${conversationId}`;
|
||||
|
||||
/** Pinned models/agents are the signed-in user's favorites, written through the
|
||||
* same route the star does, so the server's cache invalidation runs too. */
|
||||
export async function setFavorites(page: Page, favorites: ModelFavorite[]): Promise<void> {
|
||||
const token = await getAccessToken(page);
|
||||
await requestJson(page, {
|
||||
path: '/api/user/settings/favorites',
|
||||
token,
|
||||
method: 'POST',
|
||||
body: { favorites },
|
||||
});
|
||||
}
|
||||
|
||||
/** The per-user display order of the Pinned section. */
|
||||
export async function setPinnedOrder(page: Page, keys: string[]): Promise<void> {
|
||||
const token = await getAccessToken(page);
|
||||
await requestJson(page, {
|
||||
path: '/api/user/settings/pinned-order',
|
||||
token,
|
||||
method: 'POST',
|
||||
body: { pinnedOrder: keys },
|
||||
});
|
||||
}
|
||||
|
||||
/** Leaves the account with no favorites and no saved order, so one spec's
|
||||
* arrangement cannot decide another's. Requires a loaded page for its token. */
|
||||
export async function resetPinnedState(page: Page): Promise<void> {
|
||||
await setFavorites(page, []);
|
||||
await setPinnedOrder(page, []);
|
||||
}
|
||||
|
||||
/** Removes the seeded pinned chats. */
|
||||
export async function removePins(pins: SeededPin[]): Promise<void> {
|
||||
if (pins.length === 0) {
|
||||
return;
|
||||
}
|
||||
await deleteConversations(pins.map((pin) => pin.conversationId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Drags one row onto a point inside another and releases there.
|
||||
*
|
||||
* The list reorders on `dragover`, and only once the pointer has crossed the
|
||||
* hovered row's midpoint, so a drag that jumps straight to its destination in a
|
||||
* single move delivers too few events to reach that threshold and the list
|
||||
* never shifts. The pointer therefore steps: one short move to start the drag,
|
||||
* then a stepped traverse into the target.
|
||||
*
|
||||
* `fraction` is where inside the target row the pointer lands, measured from
|
||||
* its top — below 0.5 to move a row upwards, above 0.5 to move it down.
|
||||
*/
|
||||
export async function dragRowOnto(
|
||||
page: Page,
|
||||
source: Locator,
|
||||
target: Locator,
|
||||
fraction: number,
|
||||
): Promise<void> {
|
||||
const from = await source.boundingBox();
|
||||
const to = await target.boundingBox();
|
||||
if (!from || !to) {
|
||||
throw new Error('drag source and target must both be laid out');
|
||||
}
|
||||
/* The list disconnects its drag sources while the saved order reconciles, and
|
||||
* react-dnd marks a connected one `draggable`. Pressing on a row that is not
|
||||
* yet connected does not start a drag at all: the press and release become a
|
||||
* click, and the row navigates instead of moving. */
|
||||
await expect.poll(() => source.getAttribute('draggable'), { timeout: 15_000 }).toBe('true');
|
||||
const startX = from.x + from.width / 2;
|
||||
const startY = from.y + from.height / 2;
|
||||
const endX = to.x + to.width / 2;
|
||||
const endY = to.y + to.height * fraction;
|
||||
await page.mouse.move(startX, startY);
|
||||
await page.mouse.down();
|
||||
/** The first move is what the browser turns into `dragstart`. */
|
||||
await page.mouse.move(startX, startY - 8, { steps: 4 });
|
||||
await page.mouse.move(endX, endY, { steps: 24 });
|
||||
/** The list shifts rows under the pointer as it reorders, and the hover that
|
||||
* decides a swap reads the offset at the moment it fires. A pointer that
|
||||
* arrived in one last jump gets a single reading, taken while React may still
|
||||
* be rendering the previous one; a real hand keeps sending events. These
|
||||
* repeats are that, bounded. */
|
||||
for (let settle = 0; settle < 3; settle += 1) {
|
||||
await page.mouse.move(endX, endY + settle - 1, { steps: 2 });
|
||||
}
|
||||
await page.mouse.up();
|
||||
}
|
||||
|
||||
export const pinnedSection = (page: Page): Locator =>
|
||||
page.getByRole('region', { name: PINNED_REGION });
|
||||
|
||||
/** Every row of the Pinned section, in rendered order. */
|
||||
export const pinnedRows = (page: Page): Locator => pinnedSection(page).locator('ul > li');
|
||||
|
||||
export const pinnedConvoRow = (page: Page, title: string): Locator =>
|
||||
pinnedSection(page).getByTestId('convo-item').filter({ hasText: title });
|
||||
|
||||
export const favoriteRowByName = (page: Page, name: string): Locator =>
|
||||
pinnedSection(page).getByTestId('favorite-item').filter({ hasText: name });
|
||||
|
||||
/** The chats list below the Pinned section, where an unpinned chat reappears. */
|
||||
export const chatsListRow = (page: Page, title: string): Locator =>
|
||||
page.getByTestId('convo-item').filter({ hasText: title }).first();
|
||||
|
||||
/** Where the Pinned section sits: on screen, slid out of view, or not laid out
|
||||
* yet — three states, because the third one is not the second one. */
|
||||
type SidebarPlacement = 'on-screen' | 'off-screen' | 'unlaid';
|
||||
|
||||
const sidebarPlacement = async (page: Page): Promise<SidebarPlacement> => {
|
||||
const box = await pinnedSection(page).boundingBox();
|
||||
if (!box) {
|
||||
return 'unlaid';
|
||||
}
|
||||
return box.x >= 0 ? 'on-screen' : 'off-screen';
|
||||
};
|
||||
|
||||
/**
|
||||
* Brings the sidebar on screen. A narrow viewport keeps the drawer mounted and
|
||||
* slides it out of view instead of unmounting it, so every row still answers a
|
||||
* query while nothing on it can be tapped — the tap would land on the page
|
||||
* beside the drawer. The chat header's opener is what a person reaches for
|
||||
* there; no such control exists at desktop widths, where the panel is already
|
||||
* open, so a section that has merely not been laid out yet is waited for rather
|
||||
* than answered with a click that would never resolve.
|
||||
*/
|
||||
export async function ensureSidebarOnScreen(page: Page): Promise<void> {
|
||||
await expect.poll(() => sidebarPlacement(page), { timeout: 15_000 }).not.toBe('unlaid');
|
||||
if ((await sidebarPlacement(page)) === 'on-screen') {
|
||||
return;
|
||||
}
|
||||
const opener = page.getByRole('button', { name: 'Open sidebar' });
|
||||
/* Desktop keeps the panel open and renders no opener at all, so an x that is
|
||||
* still negative there is a panel mid-layout, not a closed drawer. */
|
||||
if ((await opener.count()) > 0) {
|
||||
await opener.first().click();
|
||||
}
|
||||
await expect.poll(() => sidebarPlacement(page), { timeout: 15_000 }).toBe('on-screen');
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until the rows will actually accept a move. Reordering is gated on the
|
||||
* saved order having arrived — a drag started before that is disconnected and a
|
||||
* keystroke is ignored — and the rows say so themselves: each one advertises
|
||||
* `Alt+ArrowUp Alt+ArrowDown` once the section is ready to move it. A test that
|
||||
* dragged without waiting would pass or fail on how fast the order query came
|
||||
* back.
|
||||
*/
|
||||
export async function waitForReorderReady(page: Page): Promise<void> {
|
||||
const rows = pinnedRows(page);
|
||||
if ((await rows.count()) === 0) {
|
||||
return;
|
||||
}
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
pinnedSection(page).evaluate(
|
||||
(section) =>
|
||||
section.querySelectorAll('ul > li').length > 0 &&
|
||||
Array.from(section.querySelectorAll('ul > li')).every(
|
||||
(row) => row.querySelector('[aria-keyshortcuts]') !== null,
|
||||
),
|
||||
),
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
/** Opens a fresh chat route and waits for the Pinned section to be reachable. */
|
||||
export async function openWithPinnedSection(page: Page): Promise<void> {
|
||||
await page.goto('/c/new', { timeout: 30_000 });
|
||||
await expect(pinnedSection(page)).toBeVisible({ timeout: 30_000 });
|
||||
await ensureSidebarOnScreen(page);
|
||||
await waitForReorderReady(page);
|
||||
}
|
||||
|
||||
/** Reloads and waits for the Pinned section to be reachable again: a reload
|
||||
* puts a narrow viewport's drawer back off screen. */
|
||||
export async function reloadWithPinnedSection(page: Page): Promise<void> {
|
||||
await page.reload({ timeout: 30_000 });
|
||||
await expect(pinnedSection(page)).toBeVisible({ timeout: 30_000 });
|
||||
await ensureSidebarOnScreen(page);
|
||||
await waitForReorderReady(page);
|
||||
}
|
||||
|
||||
/** The rendered order of the Pinned section as row kinds, for the grouping the
|
||||
* section guarantees: `favorite` for a pinned model/agent, `convo` for a chat. */
|
||||
export async function pinnedRowKinds(page: Page): Promise<string[]> {
|
||||
return pinnedSection(page).evaluate((section) =>
|
||||
Array.from(section.querySelectorAll('ul > li')).map((row) =>
|
||||
row.querySelector('[data-testid="favorite-item"]') ? 'favorite' : 'convo',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** The accessible names of the Pinned rows, in rendered order. */
|
||||
export async function pinnedRowNames(page: Page): Promise<string[]> {
|
||||
return pinnedSection(page).evaluate((section) =>
|
||||
Array.from(section.querySelectorAll('ul > li')).map((row) => {
|
||||
const favorite = row.querySelector('[data-testid="favorite-item"]');
|
||||
if (favorite) {
|
||||
return favorite.getAttribute('aria-label') ?? '';
|
||||
}
|
||||
return row.querySelector('[data-testid="convo-item"]')?.textContent?.trim() ?? '';
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The resolved corner radius of an element, in pixels. */
|
||||
export async function borderRadius(locator: Locator): Promise<number> {
|
||||
return locator.evaluate((node) =>
|
||||
parseFloat(getComputedStyle(node as HTMLElement).borderTopLeftRadius),
|
||||
);
|
||||
}
|
||||
|
||||
/** The painted background of an element, which is `transparent` until a control
|
||||
* actually fills under the pointer. */
|
||||
export async function backgroundColor(locator: Locator): Promise<string> {
|
||||
return locator.evaluate((node) => getComputedStyle(node as HTMLElement).backgroundColor);
|
||||
}
|
||||
|
||||
export const isTransparent = (color: string): boolean =>
|
||||
color === 'rgba(0, 0, 0, 0)' || color === 'transparent';
|
||||
154
e2e/specs/mock/scenarios/sidebar-row-action-fills.spec.ts
Normal file
154
e2e/specs/mock/scenarios/sidebar-row-action-fills.spec.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { randomUUID } from 'crypto';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
import { getE2EUser } from '../../../setup/user';
|
||||
import { deleteConversations, seedConversations } from '../db';
|
||||
import { backgroundColor, borderRadius, chatsListRow, isTransparent } from './pinned.helpers';
|
||||
|
||||
/* Seeding a pinned list and reloading is the slow part of every test here, and it
|
||||
* runs in hooks, which do not read a `test.setTimeout` call made inside a test
|
||||
* body: a loaded machine timed the `beforeEach` out at the default 30s while the
|
||||
* test itself was allowed 60. Configured once for the file instead, with room
|
||||
* for the first test of a run, which also pays the app's cold start against a
|
||||
* database that may be a network hop away. */
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
/**
|
||||
* Keep project creation on the same all-projects route as the existing project
|
||||
* coverage, so this scenario exercises the production creation and sidebar path.
|
||||
*/
|
||||
async function createProject(page: Page, name: string): Promise<string> {
|
||||
await page.goto('/projects', { timeout: 10000 });
|
||||
await page.getByRole('button', { name: 'New project' }).first().click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await dialog.getByRole('textbox', { name: 'Project name' }).fill(name);
|
||||
await dialog.getByRole('button', { name: 'Create project' }).click();
|
||||
|
||||
await expect(page.getByRole('heading', { name })).toBeVisible();
|
||||
const projectId = new URL(page.url()).pathname.split('/projects/')[1];
|
||||
expect(projectId).toBeTruthy();
|
||||
return projectId;
|
||||
}
|
||||
|
||||
async function assertPainted(locator: Locator): Promise<void> {
|
||||
await expect.poll(async () => isTransparent(await backgroundColor(locator))).toBe(false);
|
||||
}
|
||||
|
||||
async function boxOf(locator: Locator): Promise<{ left: number; right: number }> {
|
||||
const box = await locator.boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
return { left: box!.x, right: box!.x + box!.width };
|
||||
}
|
||||
|
||||
const uniqueName = (prefix: string) => `${prefix} ${randomUUID()}`;
|
||||
|
||||
let createdProject: { id: string; name: string } | undefined;
|
||||
let seededConversationId: string | undefined;
|
||||
|
||||
test.afterEach(async ({ page }) => {
|
||||
if (seededConversationId) {
|
||||
await deleteConversations([seededConversationId]);
|
||||
seededConversationId = undefined;
|
||||
}
|
||||
|
||||
if (createdProject) {
|
||||
await page.goto(`/projects/${createdProject.id}`, { timeout: 10000 });
|
||||
const projectButton = page
|
||||
.getByRole('button', { name: createdProject.name, exact: true })
|
||||
.first();
|
||||
await expect(projectButton).toBeVisible();
|
||||
const projectRow = projectButton.locator('..');
|
||||
await projectRow.hover();
|
||||
await projectRow.getByRole('button', { name: 'More options', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: 'Delete', exact: true }).click();
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'Delete', exact: true }).click();
|
||||
await expect(projectButton).toBeHidden();
|
||||
createdProject = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
test('project row actions hold their fill while their menu is open @scenario:project-row-actions-hold-their-fill-while-their-menu-is-open', async ({
|
||||
page,
|
||||
}) => {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(!hasHover, 'pointer hover is a desktop-only path');
|
||||
|
||||
const projectName = uniqueName('E2E action-fill project');
|
||||
const projectId = await createProject(page, projectName);
|
||||
createdProject = { id: projectId, name: projectName };
|
||||
|
||||
const projectButton = page.getByRole('button', { name: projectName, exact: true }).first();
|
||||
await expect(projectButton).toBeVisible();
|
||||
const projectRow = projectButton.locator('..');
|
||||
const newChatButton = projectRow.getByRole('link', {
|
||||
name: `New chat in ${projectName}`,
|
||||
exact: true,
|
||||
});
|
||||
const optionsButton = projectRow.getByRole('button', { name: 'More options', exact: true });
|
||||
|
||||
await projectRow.hover();
|
||||
await expect(newChatButton).toBeVisible();
|
||||
await expect(optionsButton).toBeVisible();
|
||||
|
||||
const rowRadius = await borderRadius(projectRow);
|
||||
expect(await borderRadius(newChatButton)).toBeLessThan(rowRadius);
|
||||
expect(await borderRadius(optionsButton)).toBeLessThan(rowRadius);
|
||||
|
||||
const newChatBox = await boxOf(newChatButton);
|
||||
const optionsBox = await boxOf(optionsButton);
|
||||
const rowBox = await boxOf(projectRow);
|
||||
expect(Math.abs(optionsBox.left - newChatBox.right - 4)).toBeLessThanOrEqual(0.5);
|
||||
expect(Math.abs(rowBox.right - optionsBox.right - 4)).toBeLessThanOrEqual(0.5);
|
||||
|
||||
await newChatButton.hover();
|
||||
await assertPainted(newChatButton);
|
||||
await optionsButton.hover();
|
||||
await assertPainted(optionsButton);
|
||||
|
||||
await optionsButton.click();
|
||||
await expect(page.getByRole('menu')).toBeVisible();
|
||||
await page.mouse.move(0, 0);
|
||||
await assertPainted(optionsButton);
|
||||
});
|
||||
|
||||
test('renaming a chat fills its save and cancel under the pointer @scenario:renaming-a-chat-fills-its-save-and-cancel-under-the-pointer', async ({
|
||||
page,
|
||||
}) => {
|
||||
const hasHover = await page.evaluate(() => matchMedia('(hover: hover)').matches);
|
||||
test.skip(!hasHover, 'pointer hover is a desktop-only path');
|
||||
|
||||
const originalTitle = uniqueName('E2E rename-fill chat');
|
||||
const renamedTitle = `${originalTitle} renamed`;
|
||||
seededConversationId = randomUUID();
|
||||
await seedConversations(getE2EUser().email, [
|
||||
{ conversationId: seededConversationId, title: originalTitle, updatedAt: new Date() },
|
||||
]);
|
||||
|
||||
await page.goto('/c/new', { timeout: 10000 });
|
||||
const row = chatsListRow(page, originalTitle);
|
||||
await expect(row).toBeVisible();
|
||||
await row.hover();
|
||||
await row.getByRole('button', { name: 'Conversation Menu Options', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: 'Rename', exact: true }).click();
|
||||
|
||||
/** The row's own locator matches on its title text, which the rename replaces
|
||||
* with an input value, so the open form is addressed from the page: only one
|
||||
* row renames at a time. */
|
||||
const form = page.getByRole('form', { name: 'Rename Conversation', exact: true });
|
||||
const input = form.getByRole('textbox', { name: 'New Conversation Title', exact: true });
|
||||
const cancelButton = form.getByRole('button', { name: 'Cancel', exact: true });
|
||||
const saveButton = form.getByRole('button', { name: 'Save', exact: true });
|
||||
await expect(input).toBeFocused();
|
||||
|
||||
await cancelButton.hover();
|
||||
await assertPainted(cancelButton);
|
||||
await saveButton.hover();
|
||||
await assertPainted(saveButton);
|
||||
expect(await borderRadius(cancelButton)).toBeCloseTo(6, 1);
|
||||
expect(await borderRadius(saveButton)).toBeCloseTo(6, 1);
|
||||
|
||||
await input.fill(renamedTitle);
|
||||
await saveButton.click();
|
||||
await expect(chatsListRow(page, renamedTitle)).toBeVisible();
|
||||
});
|
||||
|
|
@ -79,18 +79,16 @@ describe('Button', () => {
|
|||
</Button>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Open' })).toHaveClass(
|
||||
'size-8',
|
||||
'p-0',
|
||||
'rounded-lg',
|
||||
'hover:bg-surface-hover-alt',
|
||||
);
|
||||
const button = screen.getByRole('button', { name: 'Open' });
|
||||
|
||||
expect(button).toHaveClass('size-8', 'p-0', 'rounded-md', 'hover:bg-surface-hover-alt');
|
||||
expect(button).not.toHaveClass('rounded-lg');
|
||||
});
|
||||
|
||||
/**
|
||||
* Section actions sit close enough to their heading and to each other that
|
||||
* the default offset ring crosses a neighbour, so this variant has to win
|
||||
* both radius and ring — and stay distinct from `row-action` above.
|
||||
* both radius and ring.
|
||||
*/
|
||||
it('gives section actions an inset ring and a tighter radius', () => {
|
||||
render(
|
||||
|
|
@ -130,6 +128,8 @@ describe('Button', () => {
|
|||
expect(header).toContain('h-auto');
|
||||
expect(header).not.toContain('h-10');
|
||||
expect(header).not.toContain('px-4');
|
||||
/** A heading is not a control: nothing fills under the pointer. */
|
||||
expect(header).not.toContain('hover:bg-');
|
||||
});
|
||||
|
||||
it('still takes a size when a caller asks for one', () => {
|
||||
|
|
|
|||
|
|
@ -61,15 +61,22 @@ const buttonVariantRecipe = cva(
|
|||
'border border-border-light bg-transparent text-text-primary hover:bg-surface-secondary focus-visible:ring-text-primary focus-visible:ring-offset-0',
|
||||
secondary: 'bg-surface-secondary text-text-primary hover:bg-surface-hover',
|
||||
ghost: 'hover:bg-surface-hover hover:text-text-primary',
|
||||
'row-action': 'hover:bg-surface-hover-alt hover:text-text-primary',
|
||||
/**
|
||||
* A compact action living inside a list row — a pinned row's unpin
|
||||
* badge, a conversation's overflow trigger, a table row's controls. The
|
||||
* rows stay `rounded-lg`; this sits one step inside them, so it
|
||||
* overrides the base radius rather than matching its host.
|
||||
*/
|
||||
'row-action': 'rounded-md hover:bg-surface-hover-alt hover:text-text-primary',
|
||||
link: 'text-text-primary underline-offset-4 hover:underline',
|
||||
submit: 'bg-surface-submit text-text-on-status hover:bg-surface-submit-hover',
|
||||
/**
|
||||
* The toggle that heads a collapsible sidebar section, such as Chats,
|
||||
* Projects and Pinned. It reads as a quiet label rather than a control
|
||||
* until focused, and keeps its ring inset because these sit flush
|
||||
* against the section body. It carries its own metrics through the
|
||||
* compound below, since a section heading is sized by its text.
|
||||
* Projects and Pinned. It stays a quiet label rather than a control:
|
||||
* no hover fill, because a heading that lights up competes with the
|
||||
* rows it heads. Its ring is inset because these sit flush against the
|
||||
* section body, and it carries its own metrics through the compound
|
||||
* below, since a section heading is sized by its text.
|
||||
*/
|
||||
'section-header':
|
||||
'justify-start gap-1 rounded-lg px-1 py-2 text-xs font-bold text-text-secondary focus-visible:ring-inset focus-visible:ring-offset-0',
|
||||
|
|
@ -78,6 +85,8 @@ const buttonVariantRecipe = cva(
|
|||
* Unlike `row-action`, it recedes until hovered so the heading stays
|
||||
* the thing being read, and its ring sits inside the control because
|
||||
* these sit close enough that an offset one would cross a neighbour.
|
||||
* One radius step inside the heading row, like every other control that
|
||||
* sits on one.
|
||||
*/
|
||||
'section-action':
|
||||
'rounded-md text-text-secondary hover:bg-surface-active-alt hover:text-text-primary focus-visible:ring-inset focus-visible:ring-offset-0',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue