Skip to content
Open
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
7 changes: 5 additions & 2 deletions src/components/ChatMarkdown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,11 @@ describe("mention highlighting", () => {
text: "@Atlas @Juniper @everyone", everyone: true,
mentionPeers: [{ name: "Atlas", color: "blue" }, { name: "Juniper", color: "red" }],
}));
expect(html).toContain('style="--mention-color:#286ef9">@Atlas');
expect(html).toContain('style="--mention-color:#ef3a3f">@Juniper');
expect(html).toContain('<span class="mention-highlight bot-identity mention-chip" data-bot-color="blue">');
expect(html).toContain('<span class="mention-chip-at">@</span>Atlas</span>');
expect(html).toContain('data-colour="#286ef9"');
expect(html).toContain('data-bot-color="red"');
expect(html).toContain('data-colour="#ef3a3f"');
expect(html).toContain('<span class="mention-highlight">@everyone</span>');
});
it("highlights known mentions in prose, lists and tables", () => {
Expand Down
12 changes: 11 additions & 1 deletion src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { knownImageSize, rememberRenderedSize, renderedSize } from "@/lib/image-
import { MarkdownImagePreview, MessageFolderFiles, OutsideWorkspaceFile, saveFailureText, useLocalFileSave, type MessageAttachmentContext } from "./AttachmentPreview";
import { ThreadLink, ThreadRefsContext, threadLinkFromProps, type ThreadRefsValue } from "./ThreadRefs";
import { MarkdownTable } from "./MarkdownTable";
import { MentionChip } from "./MentionText";
import { CodeBlock, CodePlate, codeHash } from "./CodeBlock";
import { Icon } from "./Icon";
import { appLogo } from "./connect-apps/logos";
Expand Down Expand Up @@ -563,6 +564,7 @@ interface MessageScope {
threads: ThreadRefsValue["threads"];
currentBotId?: string;
delivered?: DeliveredFiles;
mentionPeers?: readonly MentionPeer[];
}

export type DeliveredFiles = Readonly<Record<string, string>>;
Expand Down Expand Up @@ -692,6 +694,12 @@ function MarkdownLink({ href, children, ...rest }: { href?: string; children?: R
);
}

function MarkdownMention({ name, children }: { name: string; children: ReactNode }) {
const { mentionPeers = NO_MENTION_PEERS } = useContext(MessageScopeContext);
const bot = mentionPeers.find((peer) => !peer.person && peer.color && peer.name === name);
return bot?.color ? <MentionChip bot={{ ...bot, color: bot.color }} /> : children;
}

const MARKDOWN_COMPONENTS: Components = {
pre: MarkdownCode,
img: MarkdownImage,
Expand All @@ -705,6 +713,8 @@ const MARKDOWN_COMPONENTS: Components = {
const link = threadLinkFromProps(props as Record<string, unknown>);
if (link) return <ThreadLink target={link.target} ambiguous={link.ambiguous}>{props.children}</ThreadLink>;
const { node: _node, children, ...rest } = props;
const mentioned = (props as Record<string, unknown>)["data-mention-bot"];
if (typeof mentioned === "string") return <MarkdownMention name={mentioned}><span {...rest}>{children}</span></MarkdownMention>;
return <span {...rest}>{children}</span>;
},
a: MarkdownLink,
Expand Down Expand Up @@ -845,7 +855,7 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
};
const markdown = reveal ? draw() : markdownCache.render(text, variant, draw);
return (
<MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered }}>
<MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered, mentionPeers }}>
<div className="chat-md min-w-0 [&>:where(:not(:first-child))]:mt-2" data-revealing={reveal ? "" : undefined} style={reveal ? { "--rv-step": `${reveal.step}ms` } as CSSProperties : undefined}>{markdown}</div>
</MessageScopeContext.Provider>
);
Expand Down
8 changes: 5 additions & 3 deletions src/components/MentionColors.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, it } from "vitest";
import { MAUS_COLORS, MAUS_COLOR_NAMES } from "@/lib/mascot";
import { MAUS_COLOR_NAMES } from "@/lib/mascot";
import { MentionText } from "./MentionText";
import { ChatMarkdown } from "./ChatMarkdown";

Expand All @@ -13,10 +13,12 @@ it.each(["plain text", "Markdown"] as const)("keeps all ten bot colors independe
const html = renderToStaticMarkup(renderer === "plain text"
? createElement(MentionText, { text, peers: roster, everyone: true })
: createElement(ChatMarkdown, { text, mentionPeers: roster, everyone: true }));
const highlights = [...html.matchAll(/<span class="mention-highlight"(?: style="--mention-color:([^"]+)")?>([^<]+)<\/span>/g)]
const faceless = html.replace(/<span class="mention-highlight bot-identity mention-chip" (data-bot-color="[^"]+")>.*?<span class="mention-chip-at">@<\/span>([^<]+)<\/span>/g,
'<span class="mention-highlight bot-identity" $1>@$2</span>');
const highlights = [...faceless.matchAll(/<span class="mention-highlight(?: bot-identity)?"(?: data-bot-color="([^"]+)")?>([^<]+)<\/span>/g)]
.map(([, color, name]) => ({ name, color }));
expect(highlights).toEqual(ordered.flatMap(({ name, color }) => [
{ name: `@${name}`, color: MAUS_COLORS[color] },
{ name: `@${name}`, color },
{ name: "@everyone", color: undefined },
]));
expect(html.match(/<\/span> ordinary /g)).toHaveLength(ordered.length);
Expand Down
7 changes: 5 additions & 2 deletions src/components/MentionText.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ it("uses each bot's avatar palette and updates when its color changes", () => {
text: "@Atlas @Juniper @everyone", everyone: true,
peers: [{ name: "Atlas", color }, { name: "Juniper", color: "purple" }],
}));
expect(html).toContain(`style="--mention-color:${MAUS_COLORS[color]}">@Atlas`);
expect(html).toContain(`style="--mention-color:${MAUS_COLORS.purple}">@Juniper`);
expect(html).toContain(`<span class="mention-highlight bot-identity mention-chip" data-bot-color="${color}">`);
expect(html).toContain('<span class="mention-chip-at">@</span>Atlas</span>');
expect(html).toContain(`data-colour="${MAUS_COLORS[color]}"`);
expect(html).toContain(`data-bot-color="purple"`);
expect(html).toContain('<span class="mention-chip-at">@</span>Juniper</span>');
expect(html).toContain('<span class="mention-highlight">@everyone</span>');
}
});
Expand Down
42 changes: 37 additions & 5 deletions src/components/MentionText.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
import { Fragment, type CSSProperties, type ReactNode } from "react";
import { mentionClassName, mentionRanges, type MentionPeer, type MentionPerson } from "@/lib/mentions";
import { Fragment, useContext, type CSSProperties, type ReactNode } from "react";
import { mentionClassName, mentionRanges, type MentionBot, type MentionPeer, type MentionPerson } from "@/lib/mentions";
import { linkRanges } from "@/lib/link-ranges";
import { openBot } from "@/state/thread-navigation";
import { StoreRefContext } from "@/state/store-ref-context";
import { BotAvatar } from "./Avatar";

/** A bot mention as a chip: the bot's face and name in its colour. With `opens`, a click opens that bot's chat. */
export function MentionChip({ bot, opens = true }: { bot: MentionBot; opens?: boolean }) {
const store = useContext(StoreRefContext);
const className = "mention-highlight bot-identity mention-chip";
const body = <>
<BotAvatar bot={bot} size={16} animated={false} label="" />
<span className="mention-chip-at">@</span>{bot.name}
</>;
if (!opens || !store || !bot.id) return <span className={className} data-bot-color={bot.color}>{body}</span>;
const open = () => {
const found = store.state().bots.find((one) => one.id === bot.id);
if (found) openBot(store.dispatch, found);
};
return <button type="button" className={className} data-bot-color={bot.color} onClick={open}>{body}</button>;
}

/** The "@" of a bot mention in the composer's mirror, drawn as the bot's face. The glyph stays in the text, unseen, so the
* field's caret keeps its place. The face is wider than the "@", so it can meet a caret placed just before the mention. */
function MentionAt({ bot }: { bot: MentionBot }) {
return (
<span className="mention-at">
@<span className="mention-at-face" aria-hidden="true"><BotAvatar bot={bot} size={16} animated={false} label="" /></span>
</span>
);
}

/**
* `links` marks web addresses as link pills: "highlight" paints them only (the composer's mirror, which sits under the
* real field and must never change the text's layout), "open" makes each one a link that opens outside the app.
* `hoverStart` is where the address under the pointer starts, so the composer can show its box.
*/
export function MentionText({ text, peers, everyone = false, person, links, hoverStart, command }: {
export function MentionText({ text, peers, everyone = false, person, links, hoverStart, command, chips = true }: {
text: string; peers: readonly MentionPeer[]; everyone?: boolean; person?: MentionPerson; links?: "highlight" | "open";
hoverStart?: number | null;
/** The composer's slash command at the start of the text: painted in `color`, the text itself unchanged. */
command?: { end: number; color: string };
/** Bot mentions as chips. The composer's mirror draws each one's face over its "@" instead, keeping every glyph under the field's caret. */
chips?: boolean;
}) {
const addresses = links ? linkRanges(text) : [];
// a name inside an address is part of the address, not a mention
Expand All @@ -35,8 +66,9 @@ export function MentionText({ text, peers, everyone = false, person, links, hove
: <span className="link-pill" data-link-start={range.start} data-link-end={range.end} data-href={range.href}
data-hover={hoverStart === range.start ? "" : undefined}>{value}</span>;
} else {
const style = range.color ? { "--mention-color": range.color } as CSSProperties : undefined;
node = <span className={mentionClassName(range)} style={style}>{value}</span>;
node = !range.bot ? <span className={mentionClassName(range)}>{value}</span>
: chips ? <MentionChip bot={range.bot} />
: <span className={mentionClassName(range)} data-bot-color={range.bot.color}><MentionAt bot={range.bot} />{value.slice(1)}</span>;
}
return <Fragment key={range.start}>{prefix}{node}</Fragment>;
});
Expand Down
8 changes: 4 additions & 4 deletions src/components/MentionTextarea.dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ afterEach(() => {
vi.unstubAllGlobals();
});

it("draws its words in the field's own type and padding, so the caret stays at the end of the text", async () => {
it("draws its words in the field's own type and padding, 4px wider each side for a mention's face, so the caret stays at the end of the text", async () => {
vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
document.head.appendChild(document.createElement("style")).textContent =
".dock { font-size: 14px; line-height: 20px; padding: 4px 2px } .wide { font-size: 15px; line-height: 24px; padding: 4px }";
Expand All @@ -25,9 +25,9 @@ it("draws its words in the field's own type and padding, so the caret stays at t
});
const mirror = () => document.querySelector<HTMLElement>(".mention-editor-mirror")!.style;
await show("dock");
expect([mirror().fontSize, mirror().lineHeight, mirror().paddingLeft]).toEqual(["14px", "20px", "2px"]);
expect([mirror().fontSize, mirror().lineHeight, mirror().paddingLeft]).toEqual(["14px", "20px", "6px"]);
await show("wide");
expect([mirror().fontSize, mirror().lineHeight, mirror().paddingLeft], "and follows the field when its classes change").toEqual(["15px", "24px", "4px"]);
expect([mirror().fontSize, mirror().lineHeight, mirror().paddingLeft], "and follows the field when its classes change").toEqual(["15px", "24px", "8px"]);
act(() => root.unmount());
});

Expand All @@ -40,7 +40,7 @@ it("sits over the field where the wrapper pads it, so the typed words start wher
root.render(createElement(MentionTextarea, { inputRef, peers: [], wrapperClassName: "px-1.5", value: "hey", onChange: () => {} }));
});
const mirror = document.querySelector<HTMLElement>(".mention-editor-mirror")!.style;
expect([mirror.left, mirror.right]).toEqual(["6px", "auto"]);
expect([mirror.left, mirror.right, mirror.paddingLeft]).toEqual(["2px", "auto", "4px"]);
offsetLeft.mockRestore();
act(() => root.unmount());
});
Expand Down
3 changes: 2 additions & 1 deletion src/components/MentionTextarea.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ it.each(["auto", "rtl", "ltr"])("shares the %s direction between the native inpu
}));
expect(html).toContain(`<div dir="${dir}" aria-hidden="true" class="mention-editor-mirror`);
expect(html).toContain(`<textarea dir="${dir}"`);
expect(html.match(/class="mention-highlight"/g)).toHaveLength(3);
expect(html.match(/<span class="mention-highlight bot-identity" data-bot-color="blue"><span class="mention-at">@<span class="mention-at-face"/g)).toHaveLength(3);
expect(html).not.toContain("mention-chip");
});
10 changes: 7 additions & 3 deletions src/components/MentionTextarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { MentionText } from "./MentionText";
const TEXT_LAYOUT = ["font-family", "font-weight", "font-style", "font-stretch", "font-feature-settings", "font-variation-settings",
"letter-spacing", "word-spacing", "text-indent", "tab-size", "padding-top", "padding-right", "padding-bottom", "padding-left"] as const;
const ZOOMED_TEXT_LAYOUT = ["font-size", "line-height"] as const;
/** How far past the field's edges the mirror may paint: a mention's bot face is wider than the "@" it covers. */
const MIRROR_BLEED = 4;

/** Android WebView's WebSettings.setTextZoom scales font-size and line-height even under text-size-adjust: none, so
* copying getComputedStyle(input) onto the mirror applies the system font scale a second time. Adjust the written
Expand Down Expand Up @@ -95,11 +97,13 @@ export function MentionTextarea({ inputRef, peers, everyone = false, wrapperClas
for (const property of TEXT_LAYOUT) mirror.style.setProperty(property, style.getPropertyValue(property));
const mirrorStyle = getComputedStyle(mirror);
for (const property of ZOOMED_TEXT_LAYOUT) syncZoomedLength(mirror, mirrorStyle, property, style.getPropertyValue(property));
mirror.style.width = `${input.clientWidth}px`;
mirror.style.paddingLeft = `${(parseFloat(style.paddingLeft) || 0) + MIRROR_BLEED}px`;
mirror.style.paddingRight = `${(parseFloat(style.paddingRight) || 0) + MIRROR_BLEED}px`;
mirror.style.width = `${input.clientWidth + 2 * MIRROR_BLEED}px`;
// the field can carry a margin inside the wrapper, or the wrapper a padding; the mirror sits exactly over the field,
// or the text drifts off the caret
mirror.style.top = `${input.offsetTop}px`;
mirror.style.left = `${input.offsetLeft}px`;
mirror.style.left = `${input.offsetLeft - MIRROR_BLEED}px`;
mirror.style.right = "auto";
mirror.style.height = `${input.clientHeight}px`;
mirror.style.bottom = "auto";
Expand Down Expand Up @@ -135,7 +139,7 @@ export function MentionTextarea({ inputRef, peers, everyone = false, wrapperClas
}, [inputRef, resize, sync]);
return <div className={cn("mention-editor relative min-w-0 flex-1 self-center", wrapperClassName)}>
<div ref={mirrorRef} dir={props.dir} aria-hidden="true" data-command-hint={command?.hint ? "" : undefined} className="mention-editor-mirror pointer-events-none absolute inset-0 overflow-hidden">
<MentionText text={String(props.value ?? "")} peers={peers} everyone={everyone} links="highlight" hoverStart={hoverStart} command={command} />
<MentionText text={String(props.value ?? "")} peers={peers} everyone={everyone} links="highlight" chips={false} hoverStart={hoverStart} command={command} />
{command?.hint && <span className="slash-hint">{command.hint}</span>}{"\n"}
</div>
<textarea {...props} ref={setInput}
Expand Down
4 changes: 2 additions & 2 deletions src/components/ThreadRefs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,8 @@ describe("ThreadRefText with mention peers", () => {
text: "@Scout please look at #QA PR 245 today",
peers: [{ name: "Scout", color: "green" }],
}));
expect(markup).toContain('class="mention-highlight"');
expect(markup).toContain("@Scout");
expect(markup).toContain('<span class="mention-highlight bot-identity mention-chip" data-bot-color="green">');
expect(markup).toContain('<span class="mention-chip-at">@</span>Scout</span>');
expect(markup).toContain('data-thread-link="qa-245"');
expect(markup).toContain(">#QA PR 245</button>");
expect(markup).toContain(" today");
Expand Down
2 changes: 1 addition & 1 deletion src/lib/mentions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe("mention display ranges", () => {
describe("the @devs tag in display ranges", () => {
it("is drawn like a tag, in any chat, unless a bot has that name", () => {
expect(matches("@devs the page froze, @Devs! but not ops@devs.test or @devsite")).toEqual(["@devs", "@Devs"]);
expect(mentionRanges("@devs hi", [{ name: "Devs", color: "blue" }]).map((range) => range.color)).toEqual(["#286ef9"]);
expect(mentionRanges("@devs hi", [{ name: "Devs", color: "blue" }]).map((range) => range.bot?.color)).toEqual(["blue"]);
});
});

Expand Down
26 changes: 17 additions & 9 deletions src/lib/mentions.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { t } from "./i18n";
import { MAUS_COLORS, type MausColor } from "./mascot";
import type { BotAvatarProps } from "@/components/Avatar";
import { isMentionBoundary, isMentionNameContinuation } from "../../shared/mention-boundary";
import { personTagAt, personTagNames } from "../../shared/person-mention";
import { devsTagAt } from "../../shared/devs-mention";

/** A name the @ list offers: a bot's, or (`person`) a teammate's on a Team Cloud. */
export type MentionPeer = { name: string; hidden?: boolean; color?: MausColor; person?: true };
export type MentionRange = { start: number; end: number; color?: string; you?: true; person?: true };
export type MentionPeer = { name: string; hidden?: boolean; color?: MausColor; person?: true }
& Omit<Partial<BotAvatarProps["bot"]>, "name" | "color">;
export type MentionBot = MentionPeer & { color: MausColor };
export type MentionRange = { start: number; end: number; bot?: MentionBot; you?: true; person?: true };
export type MentionPerson = { profileName?: string | null };

export function sameMentionPerson(a?: MentionPerson, b?: MentionPerson): boolean {
Expand Down Expand Up @@ -74,23 +77,28 @@ export function mentionRanges(text: string, peers: readonly MentionPeer[], every
}
const length = all ? 8 : peer?.name.length ?? devsTagAt(rest, botNames);
if (length === undefined) continue;
// Only palette values enter CSS.
const color = !all && peer?.color && Object.hasOwn(MAUS_COLORS, peer.color) ? MAUS_COLORS[peer.color] : undefined;
ranges.push({ start: at, end: at + length + 1, ...(color ? { color } : {}), ...(!all && peer?.person ? { person: true as const } : {}) });
// Only palette names reach the data-bot-color attribute.
const bot = !all && peer && !peer.person && isMentionBot(peer) ? peer : undefined;
ranges.push({ start: at, end: at + length + 1, ...(bot ? { bot } : {}), ...(!all && peer?.person ? { person: true as const } : {}) });
at += length;
}
return ranges;
}

export function mentionClassName(range: Pick<MentionRange, "you" | "person">): string {
return range.you ? "mention-highlight mention-you" : range.person ? "mention-highlight mention-person" : "mention-highlight";
function isMentionBot(peer: MentionPeer): peer is MentionBot {
return Boolean(peer.color && Object.hasOwn(MAUS_COLORS, peer.color));
}

export function mentionClassName(range: Pick<MentionRange, "you" | "person" | "bot">): string {
return range.you ? "mention-highlight mention-you" : range.person ? "mention-highlight mention-person"
: range.bot ? "mention-highlight bot-identity" : "mention-highlight";
}

type MarkdownNode = {
type: string;
value?: string;
children?: MarkdownNode[];
data?: { hName: string; hProperties: { className: string; style?: string } };
data?: { hName: string; hProperties: { className: string; dataBotColor?: string; dataMentionBot?: string } };
};

export function remarkMentions({ peers, everyone = false, person }: { peers: readonly MentionPeer[]; everyone?: boolean; person?: MentionPerson }) {
Expand All @@ -108,7 +116,7 @@ export function remarkMentions({ peers, everyone = false, person }: { peers: rea
if (range.start > end) result.push({ type: "text", value: text.slice(end, range.start) });
result.push({ type: "mention", data: { hName: "span", hProperties: {
className: mentionClassName(range),
...(range.color ? { style: `--mention-color:${range.color}` } : {}),
...(range.bot ? { dataBotColor: range.bot.color, dataMentionBot: range.bot.name } : {}),
} },
children: [{ type: "text", value: text.slice(range.start, range.end) }] });
end = range.end;
Expand Down
Loading
Loading