Open History to see the last commit
1import type { EditorId } from "@t3tools/contracts";
2import { useAtomValue } from "@effect/atom-react";
3import { Atom } from "effect/reactivity";
4import { flushSync } from "react-dom";
5import { createRoot } from "react-dom/client";
6
7import { editorIconOptions } from "./components/editorIcons";
8import { useTheme } from "./hooks/useTheme";
9
10const ICON_PIXELS = 32;
11const SVG_NS = "http://www.w3.org/2000/svg";
12const NO_ICONS: ReadonlyMap<EditorId, string> = new Map();
13
14// Logos are styled by Tailwind and the theme, so render them in the document and inline the
15// computed paint before rasterizing; native menus only accept bitmaps.
16async function rasterizeEditorIcon(editor: EditorId): Promise<string | null> {
17 const option = editorIconOptions(navigator.platform).find(({ value }) => value === editor);
18 if (option === undefined) return null;
19 const host = document.createElement("div");
20 host.setAttribute("aria-hidden", "true");
21 host.style.cssText = "position:fixed;left:-10000px;top:0;width:16px;height:16px;";
22 document.body.append(host);
23 const root = createRoot(host);
24 try {
25 flushSync(() =>
26 root.render(
27 <option.Icon
28 className={
29 option.kind === "brand" ? "size-4 text-foreground" : "size-4 text-muted-foreground"
30 }
31 />,
32 ),
33 );
34 const svg = host.querySelector("svg");
35 if (svg === null) return null;
36 const clone = svg.cloneNode(true) as SVGSVGElement;
37 const sources = [svg, ...svg.querySelectorAll("*")];
38 const targets = [clone, ...clone.querySelectorAll("*")];
39 sources.forEach((source, index) => {
40 const computed = getComputedStyle(source);
41 const target = targets[index];
42 target?.setAttribute(
43 "style",
44 `${target.getAttribute("style") ?? ""};fill:${computed.fill};stroke:${computed.stroke}`,
45 );
46 });
47 clone.removeAttribute("class");
48 clone.setAttribute("xmlns", SVG_NS);
49 clone.setAttribute("width", String(ICON_PIXELS));
50 clone.setAttribute("height", String(ICON_PIXELS));
51 const image = new Image();
52 image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(clone))}`;
53 await image.decode();
54 const canvas = document.createElement("canvas");
55 canvas.width = ICON_PIXELS;
56 canvas.height = ICON_PIXELS;
57 const context = canvas.getContext("2d");
58 if (context === null) return null;
59 context.drawImage(image, 0, 0, ICON_PIXELS, ICON_PIXELS);
60 return canvas.toDataURL("image/png");
61 } catch {
62 return null;
63 } finally {
64 root.unmount();
65 host.remove();
66 }
67}
68
69// Keyed by theme and editor list; both change rarely, and each key rasterizes once.
70const editorMenuIconsAtom = Atom.family((key: string) =>
71 Atom.make((get): ReadonlyMap<EditorId, string> => {
72 const editors = key
73 .slice(key.indexOf("|") + 1)
74 .split(",")
75 .filter(Boolean) as EditorId[];
76 // Render outside the reading component's render pass.
77 void Promise.resolve().then(async () => {
78 const icons = new Map<EditorId, string>();
79 for (const editor of editors) {
80 const icon = await rasterizeEditorIcon(editor);
81 if (icon !== null) icons.set(editor, icon);
82 }
83 if (icons.size > 0) get.setSelf(icons);
84 });
85 return NO_ICONS;
86 }).pipe(Atom.keepAlive, Atom.withLabel(`editor-menu-icons:${key}`)),
87);
88
89/** PNG data URLs of editor logos for context menus; empty until rendered. */
90export function useEditorMenuIcons(
91 editors: ReadonlyArray<EditorId>,
92): ReadonlyMap<EditorId, string> {
93 const { resolvedTheme } = useTheme();
94 return useAtomValue(editorMenuIconsAtom(`${resolvedTheme}|${editors.join(",")}`));
95}