Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Citation card: shared popover surface, buttons and quote mark

luishron12308a71795485f
diff --git a/src/components/CitationUI.dialog.test.ts b/src/components/CitationUI.dialog.test.ts
new file mode 100644
index 0000000000..8d374d23c2
--- /dev/null
+++ b/src/components/CitationUI.dialog.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CITATION_MAX_COMMENT_LENGTH, type CitationAttachment } from "@/lib/citations";
+import { CitationBadge } from "./CitationUI";
+
+const citation: CitationAttachment = {
+ kind: "citation", version: 1, id: "c1", quote: "first line\nsecond line", comment: "why", size: 22,
+ source: { ownerType: "bot", ownerId: "b1", threadId: "t1", messageId: "m1", start: 0, end: 22, prefix: "", suffix: "" },
+};
+
+let host: HTMLDivElement;
+let root: Root;
+const onChange = vi.fn();
+const dialog = (label: string) => document.querySelector<HTMLElement>(`[role="dialog"][aria-label="${label}"]`);
+const button = (within: HTMLElement, text: string) => [...within.querySelectorAll("button")].find((one) => one.textContent === text)!;
+const classes = (element: Element) => element.className.split(/\s+/);
+const press = (target: Element, key: string) => flushSync(() => { target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })); });
+function type(input: HTMLTextAreaElement, value: string) {
+ const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!;
+ flushSync(() => {
+ setValue.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+beforeEach(() => {
+ onChange.mockClear();
+ host = document.body.appendChild(document.createElement("div"));
+ root = createRoot(host);
+ flushSync(() => root.render(createElement(CitationBadge, { citation, onChange, onNavigate: async () => true })));
+ flushSync(() => host.querySelector<HTMLButtonElement>('button[aria-label^="Open citation"]')!.click());
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+});
+
+function openEditor(): HTMLElement {
+ flushSync(() => button(dialog("Citation details")!, "Edit comment").click());
+ return dialog("Comment on citation")!;
+}
+
+function expectSharedLook(card: HTMLElement) {
+ expect(classes(card)).toEqual(expect.arrayContaining(["popover-surface", "bg-menu", "rounded-xl", "text-start"]));
+ expect(card.querySelector("pre")).toBeNull();
+ const quote = card.querySelector<HTMLElement>("[data-citation-quote]")!;
+ expect(quote.textContent).toBe(citation.quote);
+ expect(quote.getAttribute("dir")).toBe("auto");
+ expect(classes(quote)).toEqual(expect.arrayContaining(["whitespace-pre-wrap", "border-s-2", "border-hairline"]));
+ expect(card.innerHTML).not.toMatch(/uppercase|text-\[1[01]px\]|text-white|bg-accent/);
+ for (const one of card.querySelectorAll("button")) {
+ expect(classes(one)).toContain("ui-button");
+ expect(one.className).not.toMatch(/text-\[|rounded-/);
+ }
+}
+
+describe("citation card and details pop-up", () => {
+ it("draws the details pop-up on the shared popover surface, with shared buttons and no primary", () => {
+ const details = dialog("Citation details")!;
+ expectSharedLook(details);
+ expect([...details.querySelectorAll("button")].map((one) => one.textContent)).toEqual(["Go to source", "Edit comment", "Close"]);
+ expect(details.querySelector(".ui-button-primary")).toBeNull();
+ });
+
+ it("draws the card the same way, with Save as its one primary action", () => {
+ const editor = openEditor();
+ expectSharedLook(editor);
+ expect([...editor.querySelectorAll(".ui-button-primary")].map((one) => one.textContent)).toEqual(["Save"]);
+ expect(button(editor, "Save").disabled).toBe(false);
+ });
+
+ it("turns Save off and says why once the comment is over the limit", () => {
+ const editor = openEditor();
+ const field = editor.querySelector("textarea")!;
+ type(field, "x".repeat(CITATION_MAX_COMMENT_LENGTH + 1));
+ expect(button(editor, "Save").disabled).toBe(true);
+ expect(field.getAttribute("aria-invalid")).toBe("true");
+ expect(editor.querySelector('[role="status"]')!.textContent).toBe("Comments can contain up to 4,000 characters.");
+ press(field, "Enter");
+ expect(onChange).not.toHaveBeenCalled();
+
+ type(field, "x".repeat(CITATION_MAX_COMMENT_LENGTH));
+ expect(button(editor, "Save").disabled).toBe(false);
+ expect(editor.querySelector('[role="status"]')).toBeNull();
+ });
+
+ it("closes on Escape without saving", () => {
+ const editor = openEditor();
+ type(editor.querySelector("textarea")!, "changed");
+ press(editor.querySelector("textarea")!, "Escape");
+ expect(dialog("Comment on citation")).toBeNull();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/components/CitationUI.tsx b/src/components/CitationUI.tsx
index 774ab6579b..216e7f3e8c 100644
--- a/src/components/CitationUI.tsx
+++ b/src/components/CitationUI.tsx
@@ -28,6 +28,19 @@ function focusComposer(): void {
requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>('[data-tour="composer"] textarea')?.focus());
}
+const CITATION_POPOVER = "popover-surface fixed z-50 rounded-xl border border-hairline/50 bg-menu p-3 text-start text-ink shadow-2xl shadow-black/50";
+const CITATION_NOTE = "text-[12px] leading-4";
+const CITATION_BUTTON = "ui-button touch:min-h-10";
+
+function CitationQuote({ quote, className }: { quote: string; className: string }) {
+ return (
+ <>
+ <div className={cn(CITATION_NOTE, "mb-1 text-ink-tertiary")}>{t("chat.citation.quoted")}</div>
+ <div dir="auto" data-citation-quote className={cn("overflow-y-auto whitespace-pre-wrap border-s-2 border-hairline ps-3 text-[13px] leading-[18px] text-ink-secondary [overflow-wrap:anywhere]", className)}>{quote}</div>
+ </>
+ );
+}
+
function CitationEditor({
citation,
point,
@@ -65,7 +78,7 @@ function CitationEditor({
ref={ref}
role="dialog"
aria-label={t("chat.citation.commentDialog")}
- className="fixed z-50 w-[min(28rem,calc(100vw-1rem))] rounded-xl border border-hairline/50 bg-panel p-3 text-ink shadow-2xl"
+ className={cn(CITATION_POPOVER, "w-[min(28rem,calc(100vw-1rem))]")}
style={point}
onKeyDown={(event) => {
event.stopPropagation();
@@ -75,10 +88,7 @@ function CitationEditor({
}
}}
>
- <div className="mb-2 max-h-36 overflow-auto rounded-lg border border-hairline/30 bg-inset px-3 py-2">
- <div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-ink-secondary">{t("chat.citation.quoted")}</div>
- <pre dir="auto" className="whitespace-pre-wrap break-words font-sans text-[12px] leading-relaxed">{citation.quote}</pre>
- </div>
+ <CitationQuote quote={citation.quote} className="max-h-36" />
<textarea
ref={inputRef}
dir="auto"
@@ -94,12 +104,12 @@ function CitationEditor({
if (!tooLong) onSave(withCitationComment(citation, comment));
}
}}
- className="w-full resize-none rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] outline-none focus:border-accent"
+ className="mt-3 block w-full resize-none rounded-lg border border-hairline/60 bg-inset px-3 py-2 text-[13px] leading-[18px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent aria-invalid:border-danger"
/>
- {tooLong && <p role="status" className="mt-1 text-[11px] text-danger">{t("chat.citation.commentTooLong", { count: CITATION_MAX_COMMENT_LENGTH.toLocaleString(intlLocale()) })}</p>}
- <div className="mt-2 flex justify-end gap-2">
- <button type="button" onClick={onCancel} className="rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-raised">{t("common.cancel")}</button>
- <button type="button" disabled={tooLong} onClick={() => onSave(withCitationComment(citation, comment))} className="rounded-lg bg-accent px-3 py-1.5 text-[12px] font-medium text-white disabled:opacity-40">{t("common.save")}</button>
+ {tooLong && <p role="status" className={cn(CITATION_NOTE, "mt-1 text-danger")}>{t("chat.citation.commentTooLong", { count: CITATION_MAX_COMMENT_LENGTH.toLocaleString(intlLocale()) })}</p>}
+ <div className="mt-3 flex justify-end gap-2">
+ <button type="button" onClick={onCancel} className={CITATION_BUTTON}>{t("common.cancel")}</button>
+ <button type="button" disabled={tooLong} onClick={() => onSave(withCitationComment(citation, comment))} className={cn(CITATION_BUTTON, "ui-button-primary")}>{t("common.save")}</button>
</div>
</div>,
document.body,
@@ -334,7 +344,7 @@ export function CitationBadge({
<div
role="dialog"
aria-label={t("chat.citation.details")}
- className="fixed z-50 w-[min(30rem,calc(100vw-1rem))] rounded-xl border border-hairline/50 bg-panel p-3 text-left text-ink shadow-2xl"
+ className={cn(CITATION_POPOVER, "w-[min(30rem,calc(100vw-1rem))]")}
style={point}
ref={(element) => {
detailsRef.current = element;
@@ -344,16 +354,13 @@ export function CitationBadge({
if (event.key === "Escape") { event.preventDefault(); setOpen(false); restoreTriggerFocus(); }
}}
>
- <div className="max-h-56 overflow-auto rounded-lg bg-inset px-3 py-2">
- <div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-ink-secondary">{t("chat.citation.quoted")}</div>
- <pre dir="auto" className="whitespace-pre-wrap break-words font-sans text-[12px] leading-relaxed">{citation.quote}</pre>
- </div>
- {citation.comment && <div className="mt-2 text-[12px]"><span className="font-semibold">{t("chat.citation.comment")}</span> <span className="whitespace-pre-wrap">{citation.comment}</span></div>}
- {unavailable && <p role="status" className="mt-2 text-[11px] text-warning">{t("chat.citation.unavailable")}</p>}
+ <CitationQuote quote={citation.quote} className="max-h-56" />
+ {citation.comment && <div dir="auto" className="mt-3 text-[13px] leading-[18px] [overflow-wrap:anywhere]"><span className="font-medium">{t("chat.citation.comment")}</span> <span className="whitespace-pre-wrap">{citation.comment}</span></div>}
+ {unavailable && <p role="status" className={cn(CITATION_NOTE, "mt-2 text-warning")}>{t("chat.citation.unavailable")}</p>}
<div className="mt-3 flex justify-end gap-2">
- {onNavigate && <button type="button" onClick={() => { void onNavigate().then((found) => { setUnavailable(!found); if (found) setOpen(false); }); }} className="rounded-lg border border-hairline/40 px-3 py-1.5 text-[12px] hover:bg-raised">{t("chat.citation.goToSource")}</button>}
- {onChange && <button type="button" onClick={() => { setOpen(false); setEditing(true); }} className="rounded-lg border border-hairline/40 px-3 py-1.5 text-[12px] hover:bg-raised">{t("chat.citation.editComment")}</button>}
- <button type="button" onClick={() => { setOpen(false); restoreTriggerFocus(); }} className="rounded-lg bg-accent px-3 py-1.5 text-[12px] text-white">{t("common.close")}</button>
+ {onNavigate && <button type="button" onClick={() => { void onNavigate().then((found) => { setUnavailable(!found); if (found) setOpen(false); }); }} className={CITATION_BUTTON}>{t("chat.citation.goToSource")}</button>}
+ {onChange && <button type="button" onClick={() => { setOpen(false); setEditing(true); }} className={CITATION_BUTTON}>{t("chat.citation.editComment")}</button>}
+ <button type="button" onClick={() => { setOpen(false); restoreTriggerFocus(); }} className={CITATION_BUTTON}>{t("common.close")}</button>
</div>
</div>,
document.body,
diff --git a/src/components/chat-dir-auto.test.ts b/src/components/chat-dir-auto.test.ts
index d04eaa0f38..ba985cb441 100644
--- a/src/components/chat-dir-auto.test.ts
+++ b/src/components/chat-dir-auto.test.ts
@@ -25,8 +25,7 @@ describe("chat text follows the writer's direction", () => {
expectDirAuto("TaskPicker.tsx", "task.threadId === bot.threadId");
expectDirAuto("SearchResults.tsx", "line-clamp-2");
- const quotes = source("CitationUI.tsx").match(/<pre dir="auto"[^>]*>\{citation\.quote\}/g) ?? [];
- expect(quotes).toHaveLength(2);
+ expectDirAuto("CitationUI.tsx", "data-citation-quote");
expectDirAuto("PinnedMessagesMenu.tsx", "{pin.text}");
});
});