Open History to see the last commit
1import { fileBasename } from "@t3tools/shared/path";
2import type { ThreadId } from "@t3tools/contracts";
3import { resolveMarkdownLinkPresentation } from "../../lib/markdownLinks";
4import type { MarkdownFileContextMenu } from "../../native/SelectableMarkdownText.types";
5import { hostPreviewMimeTypeFromExtension } from "@t3tools/shared/filePreview";
6
7import {
8 isAbsolutePath,
9 resolveWorkspaceFilePath,
10 resolveWorkspaceRelativeFilePath,
11} from "../files/filePath";
12
13export type FileChipAction = "copy-full-path" | "copy-relative-path" | "open-file" | "save";
14
15export interface FileChipTarget {
16 readonly fullPath?: string;
17 readonly relativePath?: string;
18}
19
20export function resolveFileChipTarget(
21 href: string,
22 workspaceRoot: string | null | undefined,
23): FileChipTarget | null {
24 const presentation = resolveMarkdownLinkPresentation(href);
25 if (presentation.kind !== "file") return null;
26 const relativePath = resolveWorkspaceRelativeFilePath(workspaceRoot, presentation.path);
27 const fullPath = isAbsolutePath(presentation.path)
28 ? presentation.path
29 : workspaceRoot && relativePath
30 ? resolveWorkspaceFilePath(workspaceRoot, relativePath)
31 : undefined;
32 if (!fullPath && !relativePath) return null;
33 return {
34 ...(fullPath ? { fullPath } : {}),
35 ...(relativePath ? { relativePath } : {}),
36 };
37}
38
39function fileChipMetadata(target: FileChipTarget) {
40 const path = target.fullPath ?? target.relativePath;
41 if (!path) return null;
42 const name = fileBasename(path);
43 const dot = name.lastIndexOf(".");
44 const mimeType = dot < 0 ? null : hostPreviewMimeTypeFromExtension(name.slice(dot));
45 return mimeType ? { path, name, mimeType } : null;
46}
47
48/** Use literal resolved paths so encoded filename characters are not decoded twice. */
49export function fileChipShareSource(target: FileChipTarget, threadId: ThreadId) {
50 const metadata = fileChipMetadata(target);
51 return metadata
52 ? {
53 name: metadata.name,
54 mimeType: metadata.mimeType,
55 resource: { _tag: "media-file" as const, threadId, path: metadata.path },
56 }
57 : null;
58}
59
60export function fileChipMenu(target: FileChipTarget): MarkdownFileContextMenu {
61 return {
62 title: target.fullPath ?? target.relativePath ?? "",
63 actions: [
64 ...(target.fullPath ? [{ id: "copy-full-path", title: "Copy full path" }] : []),
65 ...(target.relativePath ? [{ id: "copy-relative-path", title: "Copy relative path" }] : []),
66 { id: "open-file", title: "Open in file viewer" },
67 ...(fileChipMetadata(target)
68 ? [
69 {
70 id: "save",
71 title: "Save or share",
72 },
73 ]
74 : []),
75 ],
76 };
77}