Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SkillInlineText.tsx

92 lines2.7 KB

1import { Children, cloneElement, isValidElement, type ReactNode } from "react";
2import type { ServerProviderSkill } from "@t3tools/contracts";
3​
4import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
5import {
6 CHAT_INLINE_CHIP_CLASS_NAME,
7 CHAT_INLINE_CHIP_LABEL_CLASS_NAME,
8 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
9 SKILL_CHIP_ICON_SVG,
10} from "../composerInlineChip";
11import { cn } from "~/lib/utils";
12​
13const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g;
14​
15type InlineSkill = Pick<ServerProviderSkill, "name" | "displayName">;
16​
17export function SkillInlineText(props: { text: string; skills: ReadonlyArray<InlineSkill> }) {
18 const nodes: ReactNode[] = [];
19 let cursor = 0;
20​
21 for (const match of props.text.matchAll(SKILL_TOKEN_REGEX)) {
22 const prefix = match[1] ?? "";
23 const name = match[2] ?? "";
24 const start = (match.index ?? 0) + prefix.length;
25 const rawText = `$${name}`;
26 const skill = props.skills.find((candidate) => candidate.name === name);
27 if (!skill) {
28 continue;
29 }
30​
31 if (start > cursor) {
32 nodes.push(props.text.slice(cursor, start));
33 }
34 nodes.push(<SkillChip key={`${start}:${name}`} skill={skill} rawText={rawText} />);
35 cursor = start + rawText.length;
36 }
37​
38 if (cursor === 0) {
39 return <>{props.text}</>;
40 }
41 if (cursor < props.text.length) {
42 nodes.push(props.text.slice(cursor));
43 }
44 return <>{nodes}</>;
46​
47export function renderSkillInlineMarkdownChildren(
48 children: ReactNode,
49 skills: ReadonlyArray<InlineSkill>,
50): ReactNode {
51 return Children.map(children, (child) => {
52 if (typeof child === "string") {
53 return <SkillInlineText text={child} skills={skills} />;
54 }
55 if (!isValidElement<{ children?: ReactNode }>(child)) {
56 return child;
57 }
58 if (child.type === "code" || child.type === "a") {
59 return child;
60 }
61 if (!("children" in child.props)) {
62 return child;
63 }
64 return cloneElement(
65 child,
66 undefined,
67 renderSkillInlineMarkdownChildren(child.props.children, skills),
68 );
69 });
71​
72function SkillChip(props: { skill: InlineSkill; rawText: string }) {
73 return (
74 <span className="inline-flex align-middle leading-none" data-markdown-copy={props.rawText}>
75 <span
76 className={cn(
77 CHAT_INLINE_CHIP_CLASS_NAME,
78 "border-fuchsia-500/25 bg-fuchsia-500/12 text-fuchsia-700 dark:text-fuchsia-300",
79 )}
80 >
81 <span
82 aria-hidden="true"
83 className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
84 dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
85 />
86 <span className={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}>
87 {formatProviderSkillDisplayName(props.skill)}
88 </span>
89 </span>
90 </span>
91 );