Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 204 additions & 0 deletions apps/editor-remote/src/components/editor/ChipEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { Reorder } from 'framer-motion';
import { SIDEBAR_VIEWS, TOOL_GROUPS, chipKey } from '@velobits/app-core/constants/tools';
import type { SidebarChip } from '@velobits/app-core/types/tools';
import type {
SidebarChipsContextValue,
ToolGroupsContextValue,
} from '@velobits/app-core/types/context';
import type { ShowAlertFn } from '@velobits/app-core/types/alert';
import {
GripVerticalIcon,
PlusIcon,
RotateCcwIcon,
SearchIcon,
XIcon,
} from '@velobits/design-system';
import { chipLabel } from './chipUtils';

const EDITOR_WIDTH = 264;
const EDITOR_MAX_HEIGHT = 440;
const GAP = 8;

interface ChipEditorProps {
/** Rect of the trigger button — the popover opens beside/below it. */
anchor: DOMRect;
onClose: () => void;
sidebarChips: SidebarChipsContextValue;
toolGroups: ToolGroupsContextValue;
showAlert: ShowAlertFn;
}

interface AddRow {
chip: SidebarChip;
label: string;
}

/**
* The chip-row editor popover: drag to reorder the current chips, remove with
* an undo toast, add smart views / your groups / catalog groups (labels match
* the panel section headers), reset to the default row.
*/
export default function ChipEditor({
anchor,
onClose,
sidebarChips,
toolGroups,
showAlert,
}: ChipEditorProps) {
const { chips } = sidebarChips;
const [query, setQuery] = useState('');
// Reorder works on a local draft and commits on drag end — committing every
// intermediate onReorder frame would spam whole-list PUTs.
const [draft, setDraft] = useState<SidebarChip[]>(chips);
useEffect(() => setDraft(chips), [chips]);

useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onClose]);

const present = useMemo(() => new Set(chips.map((c) => chipKey(c))), [chips]);
const q = query.trim().toLowerCase();

const addSections = useMemo(() => {
const match = (label: string) => !q || label.toLowerCase().includes(q);
const views: AddRow[] = SIDEBAR_VIEWS.filter(
(v) => !present.has(`view:${v.id}`) && match(v.label)
).map((v) => ({ chip: { type: 'view', id: v.id }, label: v.label }));
const custom: AddRow[] = toolGroups.groups
.filter((g) => !present.has(`custom_group:${g.id}`) && match(g.name))
.map((g) => ({ chip: { type: 'custom_group', id: g.id }, label: g.name }));
const catalog: AddRow[] = TOOL_GROUPS.filter(
(g) => !present.has(`group:${g.id}`) && match(g.label)
).map((g) => ({ chip: { type: 'group', id: g.id }, label: g.label }));
return [
{ title: 'Views', rows: views },
{ title: 'Your groups', rows: custom },
{ title: 'Catalog', rows: catalog },
].filter((s) => s.rows.length > 0);
}, [present, toolGroups.groups, q]);

const removeWithUndo = (chip: SidebarChip, label: string) => {
const prev = [...chips];
sidebarChips.removeChip(chip);
showAlert(`Removed "${label}" from your sidebar`, 'info', {
action: { label: 'Undo', onClick: () => sidebarChips.setChips(prev) },
});
};

const resetWithUndo = () => {
const prev = [...chips];
sidebarChips.resetChips();
showAlert('Sidebar reset to defaults', 'info', {
action: { label: 'Undo', onClick: () => sidebarChips.setChips(prev) },
});
onClose();
};

// Clamp to the viewport, preferring the right side of the anchor.
let left = anchor.right + GAP;
if (left + EDITOR_WIDTH > window.innerWidth) left = anchor.left - EDITOR_WIDTH - GAP;
if (left < GAP) left = GAP;
const top = Math.max(GAP, Math.min(anchor.top, window.innerHeight - EDITOR_MAX_HEIGHT - GAP));

return createPortal(
<>
<div className="tu-group-menu-backdrop" onClick={onClose} />
<div
className="tu-chip-editor"
style={{ top, left, width: EDITOR_WIDTH, maxHeight: EDITOR_MAX_HEIGHT }}
role="dialog"
aria-label="Customize sidebar"
>
<div className="tu-chip-editor-title">Sidebar</div>

<Reorder.Group
axis="y"
values={draft.map((c) => chipKey(c))}
onReorder={(keys: string[]) => {
const byKey = new Map(draft.map((c) => [chipKey(c), c]));
setDraft(keys.map((k) => byKey.get(k)!).filter(Boolean));
}}
className="tu-chip-editor-list"
as="div"
>
{draft.map((chip) => {
const label = chipLabel(chip, toolGroups.groups);
if (label === null) return null;
const isAll = chip.type === 'view' && chip.id === 'all';
return (
<Reorder.Item
key={chipKey(chip)}
value={chipKey(chip)}
as="div"
className="tu-chip-editor-item"
onDragEnd={() => sidebarChips.setChips(draft)}
>
<span className="tu-chip-editor-grip" aria-hidden="true">
<GripVerticalIcon size={12} />
</span>
<span className="tu-chip-editor-name">{label}</span>
{!isAll && (
<button
className="tu-chip-editor-remove"
onClick={() => removeWithUndo(chip, label)}
aria-label={`Remove ${label} from sidebar`}
title="Remove from sidebar"
>
<XIcon size={12} />
</button>
)}
</Reorder.Item>
);
})}
</Reorder.Group>

<div className="tu-chip-editor-search">
<SearchIcon size={12} />
<input
value={query}
placeholder="Find a group…"
onChange={(e) => setQuery(e.target.value)}
aria-label="Filter addable chips"
/>
</div>

<div className="tu-chip-editor-sections">
{addSections.map((section) => (
<div key={section.title}>
<div className="tu-chip-editor-section">{section.title}</div>
{section.rows.map((row) => (
<button
key={chipKey(row.chip)}
className="tu-chip-editor-add"
onClick={() => sidebarChips.addChip(row.chip)}
>
<PlusIcon size={12} />
<span className="tu-chip-editor-name">{row.label}</span>
</button>
))}
</div>
))}
{addSections.length === 0 && (
<div className="tu-chip-editor-empty">
{q ? 'No matches' : 'Everything is already on your sidebar'}
</div>
)}
</div>

{sidebarChips.isCustomized && (
<button className="tu-chip-editor-reset" onClick={resetWithUndo}>
<RotateCcwIcon size={12} />
<span>Reset to defaults</span>
</button>
)}
</div>
</>,
document.body
);
}
68 changes: 46 additions & 22 deletions apps/editor-remote/src/components/editor/TextForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -477,12 +477,29 @@ const defaultFavorites: FavoritesContextValue = {
toggleFavorite: vi.fn(),
};

const defaultSidebarChips = {
chips: [
{ type: 'view' as const, id: 'all' },
{ type: 'view' as const, id: 'pinned' },
{ type: 'view' as const, id: 'recent' },
{ type: 'view' as const, id: 'suggested' },
],
ready: true,
isCustomized: false,
addChip: vi.fn(),
removeChip: vi.fn(),
moveChip: vi.fn(),
setChips: vi.fn(),
resetChips: vi.fn(),
};

const defaultProps = {
showAlert: vi.fn(),
isAuthenticated: false,
user: null,
toolGroups: defaultToolGroups,
favorites: defaultFavorites,
sidebarChips: defaultSidebarChips,
subscription: null,
mode: 'dark',
setMode: vi.fn(),
Expand Down Expand Up @@ -512,11 +529,16 @@ describe('TextForm', () => {
expect(document.querySelector('.tu-activity-bar')).toBeInTheDocument();
});

it('renders activity bar buttons for each USE_CASE_TABS', () => {
it('renders activity bar buttons for the sidebar chips', () => {
render(<TextForm {...defaultProps} />);
const activityBtns = document.querySelectorAll('.tu-activity-btn');
// Should have buttons for: all, writing, transform, code, ai, language, encode + special buttons
expect(activityBtns.length).toBeGreaterThanOrEqual(7);
// All/Pinned/Recent (Suggested hides at 0) + customize + Templates/History
expect(activityBtns.length).toBeGreaterThanOrEqual(5);
expect(document.querySelector('[aria-label="All Tools"]')).toBeInTheDocument();
expect(document.querySelector('[aria-label="Pinned"]')).toBeInTheDocument();
expect(document.querySelector('[aria-label="Customize sidebar"]')).toBeInTheDocument();
// Suggested is hidden while there are no suggestions
expect(document.querySelector('[aria-label="Suggested"]')).not.toBeInTheDocument();
});

it('renders the sidebar when sidebarOpen=true', () => {
Expand Down Expand Up @@ -557,13 +579,18 @@ describe('TextForm', () => {
expect(document.querySelector('.tu-sidebar-header span')?.textContent).toContain('All Tools');
});

it('switches tab once when the onboarding starter-kit event fires', () => {
it('switches view once when the onboarding starter-kit event fires', () => {
render(<TextForm {...defaultProps} />);
expect(document.querySelector('.tu-sidebar-header span')?.textContent).toContain('All Tools');
// The event carries chip keys since the chips replaced category tabs
act(() => {
window.dispatchEvent(new CustomEvent('fmx:onboarding-tab', { detail: { tab: 'code' } }));
window.dispatchEvent(
new CustomEvent('fmx:onboarding-tab', { detail: { tab: 'group:developer' } })
);
});
expect(document.querySelector('.tu-sidebar-header span')?.textContent).toContain('Code & Data');
expect(document.querySelector('.tu-sidebar-header span')?.textContent).toContain(
'Developer Tools'
);
});

it('passes the toolGroups context through to ToolPanel', () => {
Expand Down Expand Up @@ -717,12 +744,12 @@ describe('TextForm', () => {
expect(screen.getByTestId('tool-panel')).toBeInTheDocument();
});

it('switches to favourites panel when favourites activity button is clicked', () => {
it('keeps the tool panel mounted when the Pinned chip is clicked', () => {
render(<TextForm {...defaultProps} />);
// Click the favourites button (heart icon button)
const favBtn = document.querySelector('.tu-activity-btn[data-tooltip="Favourites"]');
fireEvent.click(favBtn!);
expect(screen.getByText(/No favourite tools yet/)).toBeInTheDocument();
const pinnedBtn = document.querySelector('.tu-activity-btn[data-tooltip="Pinned"]');
fireEvent.click(pinnedBtn!);
// Pinned is a ToolPanel view (the old separate favourites panel is gone)
expect(screen.getByTestId('tool-panel')).toBeInTheDocument();
});

it('switches to templates panel when templates activity button is clicked', () => {
Expand All @@ -739,9 +766,9 @@ describe('TextForm', () => {
expect(screen.getByText('No operations yet')).toBeInTheDocument();
});

it('shows "Explore categories" heading in landing page', () => {
it('shows "Explore groups" heading in landing page', () => {
render(<TextForm {...defaultProps} />);
expect(screen.getByText('Explore categories')).toBeInTheDocument();
expect(screen.getByText('Explore groups')).toBeInTheDocument();
});

it('shows keyboard shortcuts section in authenticated landing page', () => {
Expand Down Expand Up @@ -1145,19 +1172,15 @@ describe('TextForm tool groups and favorites (post-gamification-removal)', () =>
expect(screen.getByText('Fix Grammar')).toBeInTheDocument();
});

it('favourites sidebar panel works from the favorites prop', () => {
const toggleFavorite = vi.fn();
it('shows the favorites count in the header when the Pinned chip is active', () => {
const props = {
...defaultProps,
favorites: { favorites: ['fix_grammar'], toggleFavorite },
favorites: { favorites: ['fix_grammar'], toggleFavorite: vi.fn() },
};
render(<TextForm {...props} />);
const favBtn = document.querySelector('.tu-activity-btn[data-tooltip="Favourites"]');
const favBtn = document.querySelector('.tu-activity-btn[data-tooltip="Pinned"]');
fireEvent.click(favBtn!);
expect(screen.getByText('Fix Grammar')).toBeInTheDocument();
const removeBtn = document.querySelector('.tu-titem-fav--active');
fireEvent.click(removeBtn!);
expect(toggleFavorite).toHaveBeenCalledWith('fix_grammar');
expect(screen.getByText('Pinned')).toBeInTheDocument();
});

it('passes favorites and toolGroups to ToolPanel', () => {
Expand Down Expand Up @@ -1257,7 +1280,8 @@ describe('TextForm mobile (max-width: 768px)', () => {
render(<TextForm {...defaultProps} />);
fireEvent.click(screen.getByRole('button', { name: 'Browse tools' }));
const tabs = document.querySelectorAll('.tu-sheet-tab');
expect(tabs.length).toBe(3);
// Templates + History (Favourites became the Pinned view chip)
expect(tabs.length).toBe(2);
const historyTab = Array.from(tabs).find((t) => t.textContent?.includes('History'));
fireEvent.click(historyTab as HTMLElement);
// sidebar header title switches to the History panel
Expand Down
Loading
Loading