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

markdown-links.ts

77 lines2.6 KB

1import { fileBasename, workspaceRelativeFilePath } from "@t3tools/shared/path";
2import {
3 inlineCodeFilePathCandidate,
4 normalizeMarkdownLinkDestination,
5 resolveMarkdownFileLinkTarget,
6} from "@t3tools/shared/markdownLinks";
7import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks";
8​
9import { formatWorkspaceRelativePath } from "./filePathDisplay";
10import { isTerminalLinkActivation } from "./terminal-links";
11​
12export interface MarkdownFileLinkMeta {
13 filePath: string;
14 targetPath: string;
15 displayPath: string;
16 workspaceRelativePath: string | null;
17 basename: string;
18 line?: number;
19 column?: number;
21​
22export function shouldOpenMarkdownFileLinkInEditor(
23 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
24 platform?: string,
25): boolean {
26 return isTerminalLinkActivation(event, platform);
28​
29export function shouldOpenMarkdownFileLinkInBrowserByDefault(path: string): boolean {
30 return /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
32​
33export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {
34 if (!href) return null;
35 const target = parseFileUrlHref(normalizeMarkdownLinkDestination(href));
36 return target ? `${target.path}${target.hash}` : null;
38​
39/**
40 * Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,
41 * `origin/main`) rather than deliberate link destinations, so auto-linking
42 * them demands stronger path evidence than an explicit markdown link does:
43 * an unambiguous path prefix, a file extension, or a :line suffix.
44 */
45export function resolveInlineCodeFileLinkMeta(
46 codeText: string,
47 cwd?: string,
48 baseDir: string | undefined = cwd,
49): MarkdownFileLinkMeta | null {
50 const candidate = inlineCodeFilePathCandidate(codeText);
51 if (candidate === null) return null;
52​
53 return resolveMarkdownFileLinkMeta(candidate, cwd, baseDir);
55​
56export function resolveMarkdownFileLinkMeta(
57 href: string | undefined,
58 cwd?: string,
59 baseDir: string | undefined = cwd,
60): MarkdownFileLinkMeta | null {
61 const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir);
62 if (!targetPath) return null;
63 return buildFileLinkMetaFromTarget(targetPath, cwd);
65​
66function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
67 const { path, line, column } = splitFilePathPosition(targetPath);
68 return {
69 filePath: path,
70 targetPath,
71 displayPath: formatWorkspaceRelativePath(targetPath, cwd),
72 workspaceRelativePath: workspaceRelativeFilePath(path, cwd),
73 basename: fileBasename(path),
74 ...(line !== undefined ? { line } : {}),
75 ...(column !== undefined ? { column } : {}),
76 };