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

SkillInlineText.tsx

87 lines2.6 KB

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