Open History to see the last commit
1import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
2import { Children, cloneElement, isValidElement, type ReactNode } from "react";
3import { matchInlineSkills, type InlineSkill } from "@t3tools/shared/inlineSkills";
4
5import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip";
6import { ContextChip, ContextChipLabel } from "../ContextChip";
7
8function SkillInlineText(props: { text: string; skills: ReadonlyArray<InlineSkill> }) {
9 const nodes: ReactNode[] = [];
10 let cursor = 0;
11
12 for (const { start, end, skill, rawText } of matchInlineSkills(props.text, props.skills)) {
13 if (start > cursor) {
14 nodes.push(props.text.slice(cursor, start));
15 }
16 nodes.push(<SkillChip key={`${start}:${skill.name}`} skill={skill} rawText={rawText} />);
17 cursor = end;
18 }
19
20 if (cursor === 0) {
21 return <>{props.text}</>;
22 }
23 if (cursor < props.text.length) {
24 nodes.push(props.text.slice(cursor));
25 }
26 return <>{nodes}</>;
27}
28
29export function renderSkillInlineMarkdownChildren(
30 children: ReactNode,
31 skills: ReadonlyArray<InlineSkill>,
32): ReactNode {
33 return Children.map(children, (child) => {
34 if (typeof child === "string") {
35 return <SkillInlineText text={child} skills={skills} />;
36 }
37 if (!isValidElement<{ children?: ReactNode; node?: { tagName?: string } }>(child)) {
38 return child;
39 }
40 // Custom markdown components replace intrinsic types; check their hast tags.
41 const markdownTagName = typeof child.type === "string" ? child.type : child.props.node?.tagName;
42 if (markdownTagName === "code" || markdownTagName === "a") {
43 return child;
44 }
45 if (!("children" in child.props)) {
46 return child;
47 }
48 return cloneElement(
49 child,
50 undefined,
51 renderSkillInlineMarkdownChildren(child.props.children, skills),
52 );
53 });
54}
55
56function SkillChip(props: { skill: InlineSkill; rawText: string }) {
57 return (
58 <ContextChip kind="skill" data-markdown-copy={props.rawText}>
59 <SkillChipIcon />
60 <ContextChipLabel>{formatProviderSkillDisplayName(props.skill)}</ContextChipLabel>
61 </ContextChip>
62 );
63}
64
65export function SkillChipIcon() {
66 return (
67 <span
68 aria-hidden="true"
69 className="contents"
70 dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
71 />
72 );
73}