feat(markdown): show the GitHub mark for github.com links (#10324)
Co-authored-by: Claude Code <[email protected]>
This commit is contained in:
1 parent
a495385584
commit
272d6d747e
12 files changed
+135
-27
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 1.7 KiB |
@@ -60,14 +60,16 @@ static void T3MarkdownTextApplyAttachments(
|
||||
NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
|
||||
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
|
||||
UIImage *image = images[imageUri];
|
||||
if ([imageUri hasPrefix:@"sf:"]) {
|
||||
NSString *symbolName = [imageUri substringFromIndex:3];
|
||||
UIColor *foregroundColor =
|
||||
[attributedString attribute:NSForegroundColorAttributeName
|
||||
atIndex:attachmentRange.location
|
||||
effectiveRange:nil] ?: UIColor.labelColor;
|
||||
image = [[UIImage systemImageNamed:symbolName] imageWithTintColor:foregroundColor
|
||||
renderingMode:UIImageRenderingModeAlwaysOriginal];
|
||||
const BOOL isSymbol = [imageUri hasPrefix:@"sf:"];
|
||||
if (isSymbol) {
|
||||
image = [UIImage systemImageNamed:[imageUri substringFromIndex:3]];
|
||||
}
|
||||
UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
|
||||
atIndex:attachmentRange.location
|
||||
effectiveRange:nil];
|
||||
if (image != nil && (isSymbol || attachmentRange.tintWithForeground)) {
|
||||
image = [image imageWithTintColor:foregroundColor ?: UIColor.labelColor
|
||||
renderingMode:UIImageRenderingModeAlwaysOriginal];
|
||||
}
|
||||
attachment.image = image ?: [[UIImage alloc] init];
|
||||
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
|
||||
@@ -79,8 +81,15 @@ static void T3MarkdownTextApplyAttachments(
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
NSAttributedString *attachmentString =
|
||||
[NSAttributedString attributedStringWithAttachment:attachment];
|
||||
NSMutableAttributedString *attachmentString =
|
||||
[[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
|
||||
// Keep the run color on the attachment so a later re-apply (after the image
|
||||
// loads asynchronously) still tints with the link color, not labelColor.
|
||||
if (foregroundColor != nil) {
|
||||
[attachmentString addAttribute:NSForegroundColorAttributeName
|
||||
value:foregroundColor
|
||||
range:NSMakeRange(0, attachmentString.length)];
|
||||
}
|
||||
[attributedString replaceCharactersInRange:range withAttributedString:attachmentString];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,8 @@ struct T3MarkdownTextAttachmentRange {
|
||||
size_t location;
|
||||
size_t length;
|
||||
std::string imageUri;
|
||||
/// Recolor the loaded image with the run's foreground color, like `sf:` symbols.
|
||||
bool tintWithForeground;
|
||||
};
|
||||
|
||||
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace facebook::react {
|
||||
static constexpr Float ParagraphStyleEncodingOffset = 1000;
|
||||
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
|
||||
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
|
||||
static constexpr auto LinkAttachmentNativeIdPrefix = "t3-link:";
|
||||
|
||||
static void applyParagraphStyles(
|
||||
NSMutableAttributedString *attributedString,
|
||||
@@ -192,6 +193,7 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
utf16Offset,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
|
||||
false,
|
||||
});
|
||||
} else if (
|
||||
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
@@ -200,6 +202,15 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
1,
|
||||
props.nativeId.substr(
|
||||
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
|
||||
false,
|
||||
});
|
||||
} else if (
|
||||
props.nativeId.rfind(LinkAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(LinkAttachmentNativeIdPrefix)),
|
||||
true,
|
||||
});
|
||||
}
|
||||
utf16Offset += fragmentLength;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"exports": {
|
||||
".": "./index.ts",
|
||||
"./file-icons": "./src/markdownFileIcons.ts",
|
||||
"./link-icons": "./src/markdownLinkIcons.ts",
|
||||
"./links": "./src/markdownLinks.ts",
|
||||
"./markdown": "./src/nativeMarkdownText.ts",
|
||||
"./primitive": "./src/MarkdownTextPrimitive.tsx",
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import { markdownFileIconSource } from "./markdownFileIcons";
|
||||
import { markdownLinkIconSource } from "./markdownLinkIcons";
|
||||
import { resolveMarkdownLinkIcon } from "./markdownLinks";
|
||||
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
|
||||
import type {
|
||||
MarkdownFileContextMenu,
|
||||
@@ -177,10 +179,14 @@ export function NativeMarkdownSelectableText(props: {
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const menu = useContext(MarkdownFileContextMenuContext);
|
||||
const containsInlineFileIcon = props.runs.some((run) => run.fileIcon != null);
|
||||
const containsInlineIcon = props.runs.some(
|
||||
(run) =>
|
||||
run.fileIcon != null ||
|
||||
(run.externalHost != null && resolveMarkdownLinkIcon(run.externalHost) !== null),
|
||||
);
|
||||
const attachAndroidText = useCallback(
|
||||
(textView: RNText | null) => {
|
||||
if (Platform.OS !== "android" || !containsInlineFileIcon || textView === null) {
|
||||
if (Platform.OS !== "android" || !containsInlineIcon || textView === null) {
|
||||
return;
|
||||
}
|
||||
const reactTag = findNodeHandle(textView);
|
||||
@@ -188,7 +194,7 @@ export function NativeMarkdownSelectableText(props: {
|
||||
installMarkdownCopySanitizer(reactTag);
|
||||
}
|
||||
},
|
||||
[containsInlineFileIcon],
|
||||
[containsInlineIcon],
|
||||
);
|
||||
const occurrences = new Map<string, number>();
|
||||
const prefixedExternalLinks = new Set<string>();
|
||||
@@ -198,6 +204,7 @@ export function NativeMarkdownSelectableText(props: {
|
||||
occurrences.set(signature, occurrence + 1);
|
||||
|
||||
let text = run.text;
|
||||
let linkIcon = null;
|
||||
if (run.fileIcon && Platform.OS === "ios") {
|
||||
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
|
||||
} else if (run.skillName && run.skillLabel) {
|
||||
@@ -207,10 +214,15 @@ export function NativeMarkdownSelectableText(props: {
|
||||
: `$${run.skillName}`;
|
||||
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
|
||||
prefixedExternalLinks.add(run.href);
|
||||
text = `${EXTERNAL_LINK_PREFIX}${text}`;
|
||||
linkIcon = resolveMarkdownLinkIcon(run.externalHost);
|
||||
if (linkIcon === null) {
|
||||
text = `${EXTERNAL_LINK_PREFIX}${text}`;
|
||||
} else if (Platform.OS === "ios") {
|
||||
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
|
||||
}
|
||||
}
|
||||
|
||||
return { key: `${signature}:${occurrence}`, run, text };
|
||||
return { key: `${signature}:${occurrence}`, run, text, linkIcon };
|
||||
});
|
||||
// T3MarkdownText only rebuilds its attributed string during native layout. A
|
||||
// color-only child update can otherwise leave the previous appearance cached.
|
||||
@@ -248,7 +260,7 @@ export function NativeMarkdownSelectableText(props: {
|
||||
lineHeight: props.textStyle.lineHeight,
|
||||
}}
|
||||
>
|
||||
{keyedRuns.map(({ key, run, text }) => {
|
||||
{keyedRuns.map(({ key, run, text, linkIcon }) => {
|
||||
const href = run.href;
|
||||
const contextMenu = run.fileIcon && href ? menu?.fileContextMenu(href) : undefined;
|
||||
return (
|
||||
@@ -260,7 +272,9 @@ export function NativeMarkdownSelectableText(props: {
|
||||
? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
|
||||
: run.skillName
|
||||
? "t3-skill:sf:cube"
|
||||
: undefined
|
||||
: linkIcon
|
||||
? `t3-link:${Image.resolveAssetSource(markdownLinkIconSource(linkIcon)).uri}`
|
||||
: undefined
|
||||
: undefined
|
||||
}
|
||||
contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
|
||||
@@ -284,6 +298,12 @@ export function NativeMarkdownSelectableText(props: {
|
||||
>
|
||||
{Platform.OS === "android" && run.fileIcon ? (
|
||||
<Image source={markdownFileIconSource(run.fileIcon)} style={styles.inlineIcon} />
|
||||
) : Platform.OS === "android" && linkIcon ? (
|
||||
<Image
|
||||
source={markdownLinkIconSource(linkIcon)}
|
||||
style={styles.inlineIcon}
|
||||
tintColor={props.textStyle.linkColor}
|
||||
/>
|
||||
) : null}
|
||||
{text}
|
||||
</MarkdownTextPrimitive>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { ImageSourcePropType } from "react-native";
|
||||
|
||||
import type { MarkdownLinkIcon } from "./markdownLinks";
|
||||
|
||||
// Black-on-transparent marks; callers tint them with the link color.
|
||||
const MARKDOWN_LINK_ICON_SOURCES = {
|
||||
github: require("../assets/link-icons/github.png"),
|
||||
} as const satisfies Readonly<Record<MarkdownLinkIcon, ImageSourcePropType>>;
|
||||
|
||||
export function markdownLinkIconSource(icon: MarkdownLinkIcon): ImageSourcePropType {
|
||||
return MARKDOWN_LINK_ICON_SOURCES[icon];
|
||||
}
|
||||
@@ -33,6 +33,18 @@ export type MarkdownLinkPresentation =
|
||||
|
||||
export type MarkdownFileIcon = keyof typeof MARKDOWN_FILE_ICON_SOURCES;
|
||||
|
||||
export type MarkdownLinkIcon = "github";
|
||||
|
||||
/**
|
||||
* Sites whose brand mark replaces the generic external-link glyph. The marks
|
||||
* are monochrome and tinted with the link color, so they follow the theme.
|
||||
*/
|
||||
export function resolveMarkdownLinkIcon(host: string): MarkdownLinkIcon | null {
|
||||
const hostname = host.toLowerCase();
|
||||
if (hostname === "github.com" || hostname.endsWith(".github.com")) return "github";
|
||||
return null;
|
||||
}
|
||||
|
||||
const FILE_ICON_BY_NAME: Readonly<Record<string, MarkdownFileIcon>> = {
|
||||
".babelrc": "babel",
|
||||
".babelrc.json": "babel",
|
||||
|
||||
@@ -134,9 +134,11 @@ import {
|
||||
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
|
||||
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
|
||||
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
|
||||
import { markdownLinkIconSource } from "@t3tools/mobile-markdown-text/link-icons";
|
||||
import {
|
||||
normalizeNativeMarkdownUrl,
|
||||
resolveMarkdownInlineCodePresentation,
|
||||
resolveMarkdownLinkIcon,
|
||||
resolveMarkdownLinkPresentation,
|
||||
} from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
@@ -606,7 +608,8 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
|
||||
readonly onPress: (href: string) => void;
|
||||
}) {
|
||||
const [failedHost, setFailedHost] = useState<string | null>(null);
|
||||
const faviconUrl = faviconUrlForOrigin(`https://${props.host}`);
|
||||
const linkIcon = resolveMarkdownLinkIcon(props.host);
|
||||
const faviconUrl = linkIcon ? null : faviconUrlForOrigin(`https://${props.host}`);
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
@@ -617,9 +620,15 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
|
||||
textDecorationLine: "none",
|
||||
}}
|
||||
>
|
||||
{faviconUrl !== null &&
|
||||
failedHost !== props.host &&
|
||||
!failedMarkdownFaviconHosts.has(props.host) ? (
|
||||
{linkIcon ? (
|
||||
<Image
|
||||
source={markdownLinkIconSource(linkIcon)}
|
||||
style={markdownLinkStyles.inlineIcon}
|
||||
tintColor={props.color}
|
||||
/>
|
||||
) : faviconUrl !== null &&
|
||||
failedHost !== props.host &&
|
||||
!failedMarkdownFaviconHosts.has(props.host) ? (
|
||||
<Image
|
||||
source={{
|
||||
uri: faviconUrl,
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
resolveMarkdownLinkIcon,
|
||||
resolveMarkdownLinkPresentation,
|
||||
} from "@t3tools/mobile-markdown-text/links";
|
||||
|
||||
describe("resolveMarkdownLinkIcon", () => {
|
||||
it("gives GitHub hosts the brand mark and everything else the generic glyph", () => {
|
||||
expect(resolveMarkdownLinkIcon("github.com")).toBe("github");
|
||||
expect(resolveMarkdownLinkIcon("GitHub.com")).toBe("github");
|
||||
expect(resolveMarkdownLinkIcon("gist.github.com")).toBe("github");
|
||||
expect(resolveMarkdownLinkIcon("github.community")).toBeNull();
|
||||
expect(resolveMarkdownLinkIcon("notgithub.com")).toBeNull();
|
||||
expect(resolveMarkdownLinkIcon("example.com")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveMarkdownLinkPresentation", () => {
|
||||
it("treats protocol-relative media as an external URL, not a filesystem path", () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
import { Button } from "./ui/button";
|
||||
import { setMarkdownTaskChecked } from "./files/filePreviewMode";
|
||||
|
||||
@@ -78,10 +79,10 @@ describe("ChatMarkdown favicon privacy", () => {
|
||||
const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(markdown("https://github.com"));
|
||||
renderer = create(markdown("https://example.com"));
|
||||
});
|
||||
expect(renderer!.root.findAllByType("img").map((image) => image.props.src)).toEqual([
|
||||
"https://www.google.com/s2/favicons?domain=github.com&sz=32",
|
||||
"https://www.google.com/s2/favicons?domain=example.com&sz=32",
|
||||
]);
|
||||
for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) {
|
||||
await act(async () => {
|
||||
@@ -90,9 +91,15 @@ describe("ChatMarkdown favicon privacy", () => {
|
||||
expect(renderer!.root.findAllByType("img")).toHaveLength(0);
|
||||
}
|
||||
await act(async () => {
|
||||
renderer!.update(markdown("https://github.com"));
|
||||
renderer!.update(markdown("https://example.com"));
|
||||
});
|
||||
expect(renderer!.root.findAllByType("img")).toHaveLength(1);
|
||||
// GitHub links draw the brand mark in currentColor instead of fetching a favicon.
|
||||
await act(async () => {
|
||||
renderer!.update(markdown("https://github.com/pingdotgg/t3code/pull/1"));
|
||||
});
|
||||
expect(renderer!.root.findAllByType("img")).toHaveLength(0);
|
||||
expect(renderer!.root.findAllByType(GitHubIcon)).toHaveLength(1);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
|
||||
@@ -119,6 +119,7 @@ import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
import { RenderErrorBoundary } from "./RenderErrorBoundary";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { getClientSettings, useClientSettings } from "../hooks/useSettings";
|
||||
@@ -1189,15 +1190,25 @@ const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
|
||||
/** Hosts whose favicon request already failed this session — skip straight to the globe. */
|
||||
const failedFaviconHosts = new Set<string>();
|
||||
|
||||
/** Sites whose brand mark (drawn in `currentColor`) replaces the fetched favicon so it follows the theme. */
|
||||
function brandLinkIcon(host: string): typeof GitHubIcon | null {
|
||||
const hostname = host.toLowerCase();
|
||||
if (hostname === "github.com" || hostname.endsWith(".github.com")) return GitHubIcon;
|
||||
return null;
|
||||
}
|
||||
|
||||
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
|
||||
const [failedHost, setFailedHost] = useState<string | null>(null);
|
||||
const faviconUrl = faviconUrlForOrigin(`https://${host}`);
|
||||
const BrandIcon = brandLinkIcon(host);
|
||||
const faviconUrl = BrandIcon ? null : faviconUrlForOrigin(`https://${host}`);
|
||||
return (
|
||||
<span
|
||||
className="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"
|
||||
aria-hidden
|
||||
>
|
||||
{faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
|
||||
{BrandIcon ? (
|
||||
<BrandIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
|
||||
) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
|
||||
<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
|
||||
) : (
|
||||
<img
|
||||
|
||||
Reference in new issue
Block a user