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(mail): 保存新段落前统一还原邮件原始样式

Dash6591d8e37399
diff --git a/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs b/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs
index f61ef330e7..14d4683496 100644
--- a/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs
@@ -66,6 +66,13 @@ export default {
if (selected === 'edit-mail-body') {
await page.locator('iframe[aria-busy="false"]').waitFor();
const body = page.frameLocator('iframe');
+ await body.getByText('Last paragraph', {exact: true}).click();
+ await page.keyboard.press('End');
+ await page.keyboard.press('Enter');
+ await page.keyboard.type('New paragraph');
+ await page.waitForFunction(() => document.querySelector('[data-testid="saved-body"]').textContent.includes('New paragraph'));
+ const split = await page.getByTestId('saved-body').textContent();
+ if (split.includes('color-mix') || split.includes('data-cindy') || split.includes('!important')) throw new Error('Native paragraph insertion saved preview paint');
await body.getByText('formatted', {exact: true}).click();
const selectAll = async () => {
await page.keyboard.press('ControlOrMeta+a');
@@ -85,7 +92,10 @@ export default {
await page.keyboard.press('ControlOrMeta+z');
await page.waitForFunction(() => document.querySelector('[data-testid="saved-body"]').textContent.includes('Last paragraph'));
saved = await page.getByTestId('saved-body').textContent();
- if (!saved.includes('cid:logo') || saved.includes('data:image') || saved.includes('data-cindy') || !saved.includes('#123456')) throw new Error(`Saved HTML leaked preview state or lost authored styles/CID: ${saved}`);
+ // Native paragraph insertion may normalize #123456 to rgb(18, 52, 86).
+ // Verify the authored color rather than its equivalent CSS spelling.
+ const savedColor = await page.evaluate(html => new DOMParser().parseFromString(html, 'text/html').body.style.color, saved);
+ if (!saved.includes('cid:logo') || saved.includes('data:image') || saved.includes('data-cindy') || savedColor !== 'rgb(18, 52, 86)') throw new Error(`Saved HTML leaked preview state or lost authored styles/CID: ${saved}`);
await page.getByRole('button', {name:'Reopen saved'}).click();
await page.locator('iframe[aria-busy="false"]').waitFor();
await body.getByText('formatted', {exact:true}).waitFor();
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
index bf82e4fab3..dd216ad744 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
@@ -137,6 +137,44 @@ it('adapts authored mail colors to the app theme and restores them without chang
if (oldStyle === null) root.removeAttribute('style'); else root.setAttribute('style', oldStyle);
}
});
+// Unit regression for #6878 review r4355813972: native paragraph/inline splits
+// clone preview paint after the serializer's initial snapshot. Existing theme
+// tests only edited text in pre-existing nodes. Saving and theme cleanup must
+// both preserve authored styles on these new nodes without reloading the frame.
+it('restores authored paint on cloned paragraphs and inline nodes before saving and when changing theme', async () => {
+ const root = document.documentElement, oldClass = root.className, oldStyle = root.getAttribute('style');
+ try {
+ root.classList.add('dark');
+ root.style.setProperty('--surface', '#181818');
+ root.style.setProperty('--text-primary', '#eeeeee');
+ const change = vi.fn();
+ render(<MailHtmlPreview value='<p style="background:white;color:black"><strong style="color:#123456">Original</strong></p>' onChange={change} />);
+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement, doc = frame.contentDocument!;
+ doc.open(); doc.write(frame.srcdoc); doc.close(); fireEvent.load(frame);
+ const paragraph = doc.querySelector('p')!.cloneNode(true) as HTMLElement;
+ doc.body.append(paragraph);
+ paragraph.querySelector('strong')!.textContent = 'New paragraph';
+ fireEvent.input(paragraph);
+ const saved = change.mock.calls.at(-1)![0];
+ const parsed = new DOMParser().parseFromString(saved, 'text/html');
+ const next = parsed.querySelectorAll('p')[1];
+ expect(next.style.backgroundColor).toBe('white');
+ expect(next.style.color).toBe('black');
+ expect(next.querySelector('strong')!.style.color).toBe('rgb(18, 52, 86)');
+ expect(saved).not.toMatch(/color-mix|data-cindy|!important/);
+ await act(async () => { root.classList.remove('dark'); });
+ expect(paragraph.style.backgroundColor).toBe('white');
+ expect(paragraph.style.color).toBe('black');
+ expect(paragraph.querySelector('strong')!.style.color).toBe('rgb(18, 52, 86)');
+ await act(async () => { root.classList.add('dark'); });
+ fireEvent.input(paragraph);
+ expect(change.mock.calls.at(-1)![0]).toBe(saved);
+ expect(frame.contentDocument).toBe(doc);
+ } finally {
+ cleanup(); root.className = oldClass;
+ if (oldStyle === null) root.removeAttribute('style'); else root.setAttribute('style', oldStyle);
+ }
+});
// Initial paint is hidden until themed; updates from the other editor must
// change the existing document before paint, without a blank loading frame.
it('themes the first load and updates other-view content without reloading or hiding', () => {
diff --git a/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts b/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts
index 1ad2342c25..83b13cdd52 100644
--- a/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts
+++ b/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts
@@ -1,24 +1,16 @@
import { mailTextParagraphs, safeMailDocument, type MailInlineImage } from '@cindy/maker-shared/mail-text-edit';
+import { restoreMailPreviewPaint } from './mailPreviewAppearance';
-/** Capture authored paint before the preview theme changes it. Only sanitized
+/** Restore authored paint on a clone before saving. Only sanitized
* markup is saved; local image URLs and editor attributes never leave the UI. */
export function mailBodySerializer(doc: Document, source: string, images: () => readonly MailInlineImage[] = () => []) {
- const styles = new WeakMap<Element, string | null>();
- for (const el of [doc.body, ...doc.body.querySelectorAll('*')]) {
- styles.set(el, el.getAttribute('style'));
- }
const head = safeMailDocument(source).match(/<head>([\s\S]*?)<\/head>/)?.[1] ?? '';
return () => {
const inert = doc.createElement('template').content.ownerDocument;
const body = inert.importNode(doc.body, true) as HTMLElement;
- const live = [doc.body, ...doc.body.querySelectorAll('*')];
+ restoreMailPreviewPaint(body);
const copies = [body, ...body.querySelectorAll('*')];
- copies.forEach((copy, i) => {
- if (styles.has(live[i])) {
- const style = styles.get(live[i]);
- if (style == null) copy.removeAttribute('style');
- else copy.setAttribute('style', style);
- }
+ copies.forEach(copy => {
// Restore only an attachment supplied by the Host, never a reference
// taken straight from mutable editor DOM. Unresolved original cid: URLs
// already survive cloning; local preview URLs are stripped below.
diff --git a/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts b/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts
index 2422ceb74b..e0550b5cc5 100644
--- a/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts
+++ b/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts
@@ -1,6 +1,23 @@
+const authoredStyleAttribute = 'data-cindy-mail-authored-style';
+
+/** Restore both live nodes and browser-created clones from the same preview
+ * metadata. The mail sanitizer strips this attribute from incoming/outgoing HTML. */
+export function restoreMailPreviewPaint(root: Element): void {
+ for (const el of [root, ...root.querySelectorAll(`[${authoredStyleAttribute}]`)]) {
+ const encoded = el.getAttribute(authoredStyleAttribute);
+ if (encoded === null) continue;
+ el.removeAttribute(authoredStyleAttribute);
+ try {
+ const style: unknown = JSON.parse(encoded);
+ if (style === null) el.removeAttribute('style');
+ else if (typeof style === 'string') el.setAttribute('style', style);
+ } catch { /* Invalid transient metadata is never interpreted as a style. */ }
+ }
+}
+
/** Preview-only paint. Source HTML, CID images and editing spans stay intact. */
export function followMailPreviewTheme(doc: Document, host: Document): () => void {
- let restore = () => {};
+ const restore = () => restoreMailPreviewPaint(doc.documentElement);
let previous = '';
const paint = () => {
const root = host.documentElement;
@@ -26,11 +43,6 @@ export function followMailPreviewTheme(doc: Document, host: Document): () => voi
return { el, style: el.getAttribute('style'), color: css.color, background: css.backgroundColor,
image: css.backgroundImage, border: css.borderTopColor };
});
- restore = () => {
- for (const { el, style } of authored) {
- if (style === null) el.removeAttribute('style'); else el.setAttribute('style', style);
- }
- };
const colorInfo = (color: string) => {
const rgb = color.match(/^rgba?\(([^)]+)\)/)?.[1].split(/[, /]+/).map(Number);
if (!rgb || rgb.length < 3 || rgb[3] === 0) return null;
@@ -41,6 +53,9 @@ export function followMailPreviewTheme(doc: Document, host: Document): () => voi
};
for (const entry of authored) {
const { el } = entry;
+ // Native Enter/split/undo can clone these nodes. Carry the authored
+ // style with the clone so neither saving nor cleanup relies on identity.
+ el.setAttribute(authoredStyleAttribute, JSON.stringify(entry.style));
const set = (name: string, value: string) => el.style.setProperty(name, value, 'important');
const background = colorInfo(entry.background), foreground = colorInfo(entry.color);
if (background && background.brightness > 0.25) {