Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 修复置顶项目无法拖动排序

davidd57350f89b65
diff --git a/apps/desktop/scripts/check-pinned-native-drag.mjs b/apps/desktop/scripts/check-pinned-native-drag.mjs
new file mode 100644
index 0000000000..b2924721c4
--- /dev/null
+++ b/apps/desktop/scripts/check-pinned-native-drag.mjs
@@ -0,0 +1,171 @@
+#!/usr/bin/env node
+// Real Chromium drag gestures against production sorting components and CSS.
+// Run: node apps/desktop/scripts/check-pinned-native-drag.mjs <Chromium executable>
+// Add --stylesheet-ref=<pre-fix commit> to demonstrate the CSS regression.
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import esbuild from 'esbuild';
+import postcss from 'postcss';
+import tailwind from 'tailwindcss';
+import loadConfig from 'tailwindcss/loadConfig.js';
+import { chromium } from 'playwright-core';
+
+const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const root = path.resolve(desktop, '../..');
+const renderer = path.join(desktop, 'src/renderer');
+const fixture = path.join(desktop, 'scripts/fixtures/pinned-native-drag.tsx');
+const temp = mkdtempSync(path.join(os.tmpdir(), 'cindy-pinned-native-drag-'));
+const stylesheetRef = process.argv
+ .find((arg) => arg.startsWith('--stylesheet-ref='))
+ ?.split('=')[1];
+let browser;
+
+try {
+ const config = loadConfig(path.join(desktop, 'tailwind.config.ts'));
+ config.content = [
+ fixture,
+ path.join(renderer, 'components/sidebar/SortableList.tsx'),
+ path.join(renderer, 'features/cc-agent/sidebar/{CardMasonry,DraggableCardColumns}.tsx'),
+ ];
+ const globals = stylesheetRef
+ ? execFileSync(
+ 'git',
+ ['show', `${stylesheetRef}:apps/desktop/src/renderer/styles/globals.css`],
+ { cwd: root, encoding: 'utf8' },
+ )
+ : readFileSync(path.join(renderer, 'styles/globals.css'), 'utf8');
+ const css = (
+ await postcss([tailwind(config)]).process(
+ readFileSync(path.join(renderer, 'styles/generated/tokens.css'), 'utf8') +
+ '\n' +
+ globals.replace(/^@import.*$/gm, ''),
+ { from: undefined },
+ )
+ ).css;
+ const bundle = await esbuild.build({
+ entryPoints: [fixture],
+ bundle: true,
+ write: false,
+ outfile: path.join(temp, 'fixture.js'),
+ platform: 'browser',
+ format: 'iife',
+ jsx: 'automatic',
+ tsconfig: path.join(desktop, 'tsconfig.json'),
+ define: { 'import.meta.env.DEV': 'false', 'import.meta.env.PROD': 'true' },
+ });
+ const script = bundle.outputFiles[0].text;
+ browser = await chromium.launch({
+ headless: true,
+ ...(process.argv[2] && !process.argv[2].startsWith('--')
+ ? { executablePath: process.argv[2] }
+ : {}),
+ });
+ const page = await browser.newPage({ viewport: { width: 900, height: 900 } });
+ page.setDefaultTimeout(5000);
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.route('**/*', (route) =>
+ route.request().url().startsWith('http://fixture.local/')
+ ? route.fulfill({
+ contentType: 'text/html',
+ body:
+ '<!doctype html><html><head><meta charset="utf-8">' +
+ `<style>${css}</style></head><body><main id="root"></main><script>${script.replace(/<\/script/gi, '<\\/script')}</script></body></html>`,
+ })
+ : route.abort(),
+ );
+
+ const buckets = () =>
+ page
+ .getByTestId('pins')
+ .locator('[data-sortable-native-dnd]')
+ .evaluateAll((lists) =>
+ lists.map((list) =>
+ Array.from(list.children).map(
+ (row) => row.getAttribute('data-sortable-id') ?? row.getAttribute('data-card-id'),
+ ),
+ ),
+ );
+ async function drag(source, target, finish = 'inside') {
+ const before = await buckets();
+ const a = await source.boundingBox();
+ const b = await target.boundingBox();
+ assert(a && b, 'drag endpoints must be visible');
+ const x = a.x + Math.min(32, a.width / 2),
+ y = a.y + a.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 10, y, { steps: 5 });
+ await page.mouse.move(b.x + Math.min(32, b.width / 2), b.y + b.height / 2, { steps: 20 });
+ await page.waitForTimeout(180); // Allow Sortable's native dragover loop to settle.
+ if (finish !== 'inside') {
+ assert.notDeepEqual(await buckets(), before, 'cancellation must follow a temporary DOM move');
+ if (finish === 'escape') await page.keyboard.press('Escape');
+ else {
+ const outside = await page.getByTestId('outside').boundingBox();
+ await page.mouse.move(outside.x + outside.width / 2, outside.y + outside.height / 2, {
+ steps: 10,
+ });
+ }
+ }
+ await page.mouse.up();
+ if (finish !== 'inside') {
+ assert.deepEqual(await buckets(), before, 'cancelled/external drops must restore the DOM');
+ }
+ }
+ const order = async () => JSON.parse(await page.getByTestId('order').textContent());
+ const initial = ['project-a', 'task', 'project-b', 'project-c'];
+ for (const theme of ['light', 'dark']) {
+ for (const [mode, columns] of [
+ ['text', 1],
+ ['list', 1],
+ ['card', 1],
+ ['card', 2],
+ ['card', 3],
+ ]) {
+ const url = `http://fixture.local/?theme=${theme}&mode=${mode}&columns=${columns}`;
+ await page.goto(url);
+ await page.getByTestId('order').waitFor();
+ const title = page.getByTestId('project-a-title');
+ await drag(title, page.getByTestId('project-c-title'));
+ await page.waitForFunction(
+ () => Number(document.querySelector('[data-testid="writes"]').textContent) > 0,
+ );
+ assert.notDeepEqual(
+ await order(),
+ initial,
+ `${theme}/${mode}/${columns}: project must reorder`,
+ );
+
+ await page.goto(url);
+ await page
+ .getByTestId('project-a')
+ .getByRole('button', { name: 'Action', exact: true })
+ .click();
+ assert.equal(await page.getByTestId('clicks').textContent(), '1');
+ await page.getByRole('textbox', { name: 'project-a rename' }).fill('Edited');
+ await drag(page.getByTestId('project-a-child'), page.getByTestId('project-c-title'));
+ assert.deepEqual(await order(), initial, 'child rows must not reorder the project');
+ assert.equal(await page.getByTestId('writes').textContent(), '0');
+
+ // First move through the list, then leave it; the temporary move must not save.
+ await drag(title, page.getByTestId('project-c-title'), 'escape');
+ assert.deepEqual(await order(), initial, 'Escape must restore the original order');
+ assert.equal(await page.getByTestId('writes').textContent(), '0');
+ await drag(title, page.getByTestId('project-c-title'), 'outside');
+ assert.deepEqual(await order(), initial, 'outside drops must not save');
+ assert.equal(await page.getByTestId('writes').textContent(), '0');
+ console.log(
+ `PASS ${theme}/${mode}/${columns}: reorder, controls, child boundary, Escape, outside drop`,
+ );
+ }
+ }
+ assert.deepEqual(errors, [], 'browser page errors');
+} finally {
+ await browser?.close();
+ rmSync(temp, { recursive: true, force: true });
+}
diff --git a/apps/desktop/scripts/fixtures/pinned-native-drag.tsx b/apps/desktop/scripts/fixtures/pinned-native-drag.tsx
new file mode 100644
index 0000000000..462a811f86
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/pinned-native-drag.tsx
@@ -0,0 +1,88 @@
+import { useState } from 'react';
+import { createRoot } from 'react-dom/client';
+
+import { SortableList } from '../../src/renderer/components/sidebar/SortableList';
+import { CardMasonry } from '../../src/renderer/features/cc-agent/sidebar/CardMasonry';
+import { defaultDark } from '../../src/renderer/themes/builtin/default-dark';
+import { defaultLight } from '../../src/renderer/themes/builtin/default-light';
+import '../../src/renderer/themes/colors';
+import { themeService } from '../../src/renderer/themes/theme-service';
+
+const params = new URLSearchParams(location.search);
+const mode = params.get('mode') ?? 'text';
+const columns = Number(params.get('columns') ?? 1);
+themeService.applyTheme(params.get('theme') === 'dark' ? defaultDark : defaultLight);
+
+function App() {
+ const [items, setItems] = useState(['project-a', 'task', 'project-b', 'project-c']);
+ const [writes, setWrites] = useState(0);
+ const [clicks, setClicks] = useState(0);
+ const renderItem = (id: string) =>
+ id === 'task' ? (
+ <div
+ data-testid={id}
+ data-split-group-drag-source="true"
+ draggable
+ className="flex h-10 items-center rounded-lg bg-[var(--surface-elevated)] px-3"
+ >
+ Pinned task
+ </div>
+ ) : (
+ <div data-testid={id} className="rounded-lg bg-[var(--surface-elevated)]">
+ <div
+ data-project-header="true"
+ role="button"
+ tabIndex={0}
+ className="flex h-10 select-none items-center gap-2 px-3"
+ >
+ <span data-testid={`${id}-title`} className="min-w-0 flex-1">
+ {id}
+ </span>
+ <button type="button" onClick={() => setClicks((n) => n + 1)}>
+ Action
+ </button>
+ </div>
+ <div data-no-drag className="p-2">
+ <input aria-label={`${id} rename`} defaultValue="Rename" className="w-full" />
+ <div data-testid={`${id}-child`}>Child task</div>
+ </div>
+ </div>
+ );
+ const props = {
+ items,
+ getId: (id: string) => id,
+ renderItem,
+ forceFallback: params.get('fallback') === 'true',
+ reducedMotion: true,
+ onReorder: (ids: string[]) => {
+ setItems(ids);
+ setWrites((n) => n + 1);
+ },
+ };
+ return (
+ <>
+ <div
+ data-testid="pins"
+ style={{ width: mode === 'card' ? [220, 340, 460][columns - 1] : 460 }}
+ >
+ {mode === 'card' ? (
+ <CardMasonry {...props} />
+ ) : (
+ <SortableList {...props} className="flex flex-col gap-1" />
+ )}
+ </div>
+ <output data-testid="order">{JSON.stringify(items)}</output>
+ <output data-testid="writes">{writes}</output>
+ <output data-testid="clicks">{clicks}</output>
+ <div
+ data-testid="outside"
+ className="fixed right-4 top-4 h-40 w-40 border border-[var(--border-default)]"
+ onDragOver={(event) => event.preventDefault()}
+ >
+ Outside the pinned list
+ </div>
+ </>
+ );
+}
+
+createRoot(document.getElementById('root')!).render(<App />);
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index fd47ae5df8..5ad116cefd 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -68,6 +68,14 @@
-webkit-user-drag: none;
}
+ /* Native Sortable marks its direct row draggable after pointerdown. Restore
+ its subtree too: Chromium can start the drag on a project title or icon.
+ Filtered controls never arm the row, and fallback lists stay unchanged. */
+ [data-sortable-native-dnd='true'] > [draggable='true'],
+ [data-sortable-native-dnd='true'] > [draggable='true'] * {
+ -webkit-user-drag: element !important;
+ }
+
/* SessionItem 是同窗分屏的原生 HTML5 拖拽源。拖拽通常从标题、图标或时间
子节点起手,所以必须与 composer atom 一样让整棵子树恢复 element drag;
行内按钮仍由 onDragStart 的交互区守卫 preventDefault,不会误触发分屏。 */