Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0f8c29b96 | ||
|
|
9e994c1469 | ||
|
|
c832b7c860 | ||
|
|
8bfc45d29d | ||
|
|
5c16da6fba | ||
|
|
39eea0dcfd | ||
|
|
37f0951239 | ||
|
|
b2edc7e996 | ||
|
|
6b55b07089 |
No files matched your search
@@ -22,12 +22,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
|
||||
@@ -1,18 +1,207 @@
|
||||
import { memo, useMemo } from "react";
|
||||
import {
|
||||
getSharedHighlighter,
|
||||
type DiffsHighlighter,
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
memo,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
|
||||
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
|
||||
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
|
||||
const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_ENTRIES,
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
return match?.[1] ?? "text";
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
return node.map((child) => nodeToPlainText(child)).join("");
|
||||
}
|
||||
if (isValidElement<{ children?: ReactNode }>(node)) {
|
||||
return nodeToPlainText(node.props.children);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractCodeBlock(
|
||||
children: ReactNode,
|
||||
): { className: string | undefined; code: string } | null {
|
||||
const childNodes = Children.toArray(children);
|
||||
if (childNodes.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onlyChild = childNodes[0];
|
||||
if (
|
||||
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
|
||||
onlyChild.type !== "code"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
className: onlyChild.props.className,
|
||||
code: nodeToPlainText(onlyChild.props.children),
|
||||
};
|
||||
}
|
||||
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||
}
|
||||
|
||||
function estimateHighlightedSize(html: string, code: string): number {
|
||||
return Math.max(html.length * 2, code.length * 3);
|
||||
}
|
||||
|
||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
const cached = highlighterPromiseCache.get(language);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = getSharedHighlighter({
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const handleCopy = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
}
|
||||
void navigator.clipboard
|
||||
.writeText(code)
|
||||
.then(() => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
}
|
||||
setCopied(true);
|
||||
copiedTimerRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
copiedTimerRef.current = null;
|
||||
}, 1200);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [code]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
copiedTimerRef.current = null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-codeblock">
|
||||
<button
|
||||
type="button"
|
||||
className="chat-markdown-copy-button"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied" : "Copy code"}
|
||||
aria-label={copied ? "Copied" : "Copy code"}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SuspenseShikiCodeBlockProps {
|
||||
className: string | undefined;
|
||||
code: string;
|
||||
themeName: DiffThemeName;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
function SuspenseShikiCodeBlock({
|
||||
className,
|
||||
code,
|
||||
themeName,
|
||||
isStreaming,
|
||||
}: SuspenseShikiCodeBlockProps) {
|
||||
const language = extractFenceLanguage(className);
|
||||
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||
|
||||
if (cachedHighlightedHtml != null) {
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
}
|
||||
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||
);
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
a({ node: _node, href, ...props }) {
|
||||
@@ -38,17 +227,32 @@ function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
/>
|
||||
);
|
||||
},
|
||||
pre({ node: _node, children, ...props }) {
|
||||
const codeBlock = extractCodeBlock(children);
|
||||
if (!codeBlock) {
|
||||
return <pre {...props}>{children}</pre>;
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[cwd],
|
||||
[cwd, diffThemeName, isStreaming],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
||||
components={markdownComponents}
|
||||
>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||
{text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
@@ -2759,7 +2759,11 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown text={messageText} cwd={markdownCwd} />
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={markdownCwd}
|
||||
isStreaming={Boolean(row.message.streaming)}
|
||||
/>
|
||||
{(() => {
|
||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
|
||||
if (!turnSummary) return null;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
@@ -18,10 +19,47 @@ import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
const DIFF_PANEL_UNSAFE_CSS = `
|
||||
[data-diffs-header],
|
||||
[data-diff],
|
||||
[data-file],
|
||||
[data-error-wrapper],
|
||||
[data-virtualizer-buffer] {
|
||||
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-token-light-bg: transparent;
|
||||
--diffs-token-dark-bg: transparent;
|
||||
|
||||
--diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
|
||||
--diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
|
||||
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
|
||||
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
|
||||
|
||||
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
|
||||
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
|
||||
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
|
||||
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
|
||||
|
||||
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
|
||||
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
|
||||
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
|
||||
--diffs-bg-deletion-emphasis-override: color-mix(
|
||||
in srgb,
|
||||
var(--background) 80%,
|
||||
var(--destructive)
|
||||
);
|
||||
|
||||
background-color: var(--diffs-bg) !important;
|
||||
}
|
||||
|
||||
[data-file-info] {
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-block-color: var(--border) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
`;
|
||||
|
||||
type RenderablePatch =
|
||||
| {
|
||||
kind: "files";
|
||||
@@ -425,7 +463,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-card",
|
||||
"flex h-full min-w-0 flex-col bg-background",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
@@ -449,7 +487,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
ref={patchViewportRef}
|
||||
className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
|
||||
>
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
@@ -467,7 +508,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
@@ -478,7 +519,11 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
return (
|
||||
<div key={themedFileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file rounded-md"
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
@@ -486,6 +531,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
lineDiffType: "none",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -2,12 +2,9 @@ import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
}
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -314,6 +314,52 @@ label:has(> select#reasoning-effort) select {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock {
|
||||
position: relative;
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock pre {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 1.5rem;
|
||||
width: 1.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--background) 82%, transparent);
|
||||
color: var(--muted-foreground);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
color 120ms ease,
|
||||
border-color 120ms ease;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock:hover .chat-markdown-copy-button,
|
||||
.chat-markdown .chat-markdown-codeblock:focus-within .chat-markdown-copy-button {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button:hover {
|
||||
color: var(--foreground);
|
||||
border-color: color-mix(in srgb, var(--border) 70%, var(--foreground));
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-shiki .shiki {
|
||||
background: color-mix(in srgb, var(--muted) 78%, var(--background)) !important;
|
||||
}
|
||||
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -325,3 +371,15 @@ label:has(> select#reasoning-effort) select {
|
||||
padding: 0.35rem 0.45rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||
.diff-panel-viewport {
|
||||
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||
}
|
||||
|
||||
.diff-render-file {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.5rem;
|
||||
overflow: clip;
|
||||
background: color-mix(in srgb, var(--card) 92%, var(--background));
|
||||
}
|
||||
@@ -1,9 +1,24 @@
|
||||
export const DIFF_THEME_NAMES = {
|
||||
light: "pierre-light",
|
||||
dark: "pierre-dark",
|
||||
} as const;
|
||||
|
||||
export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
|
||||
|
||||
export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
|
||||
return theme === "dark" ? DIFF_THEME_NAMES.dark : DIFF_THEME_NAMES.light;
|
||||
}
|
||||
|
||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||
const FNV_PRIME_32 = 0x01000193;
|
||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||
|
||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
||||
export function fnv1a32(
|
||||
input: string,
|
||||
seed = FNV_OFFSET_BASIS_32,
|
||||
multiplier = FNV_PRIME_32,
|
||||
): number {
|
||||
let hash = seed >>> 0;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LRUCache } from "./lruCache";
|
||||
|
||||
describe("LRUCache", () => {
|
||||
it("returns null for missing keys", () => {
|
||||
const cache = new LRUCache<string>(2, 100);
|
||||
expect(cache.get("missing")).toBeNull();
|
||||
});
|
||||
|
||||
it("evicts oldest by max entries", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("promotes on get and evicts least recently used", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
|
||||
cache.set("c", "C", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
expect(cache.get("b")).toBeNull();
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("evicts by memory budget", () => {
|
||||
const cache = new LRUCache<string>(10, 25);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
interface CacheEntry<T> {
|
||||
value: T;
|
||||
approximateSize: number;
|
||||
}
|
||||
|
||||
export class LRUCache<T> {
|
||||
private cache = new Map<string, CacheEntry<T>>();
|
||||
private totalSize = 0;
|
||||
|
||||
constructor(
|
||||
private readonly maxEntries: number,
|
||||
private readonly maxMemoryBytes: number,
|
||||
) {}
|
||||
|
||||
get(key: string): T | null {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.promote(key, entry);
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key: string, value: T, approximateSize: number): void {
|
||||
const existing = this.cache.get(key);
|
||||
if (existing) {
|
||||
this.totalSize -= existing.approximateSize;
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
this.evictIfNeeded(approximateSize);
|
||||
this.cache.set(key, { value, approximateSize });
|
||||
this.totalSize += approximateSize;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cache.clear();
|
||||
this.totalSize = 0;
|
||||
}
|
||||
|
||||
private promote(key: string, entry: CacheEntry<T>): void {
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, entry);
|
||||
}
|
||||
|
||||
private evictIfNeeded(incomingSize: number): void {
|
||||
while (
|
||||
(this.cache.size >= this.maxEntries || this.totalSize + incomingSize > this.maxMemoryBytes) &&
|
||||
this.cache.size > 0
|
||||
) {
|
||||
const oldestKey = this.cache.keys().next().value;
|
||||
if (oldestKey === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
const oldestEntry = this.cache.get(oldestKey);
|
||||
if (oldestEntry) {
|
||||
this.totalSize -= oldestEntry.approximateSize;
|
||||
}
|
||||
this.cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
import "./index.css";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
|
||||
@@ -71,12 +71,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
},
|
||||
@@ -863,20 +861,14 @@
|
||||
|
||||
"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
|
||||
|
||||
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
||||
|
||||
"hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
||||
|
||||
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||
|
||||
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
||||
|
||||
"hast-util-whitespace": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
|
||||
|
||||
"headers-polyfill": ["[email protected]", "", {}, "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ=="],
|
||||
|
||||
"highlight.js": ["[email protected]", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
|
||||
|
||||
"hookable": ["[email protected]", "", {}, "sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw=="],
|
||||
|
||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||
@@ -983,8 +975,6 @@
|
||||
|
||||
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
|
||||
|
||||
"lowlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.0.0", "highlight.js": "~11.11.0" } }, "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ=="],
|
||||
|
||||
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||
@@ -1197,8 +1187,6 @@
|
||||
|
||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
||||
|
||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||
|
||||
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||
|
||||
"remark-parse": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],
|
||||
@@ -1361,8 +1349,6 @@
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
"unist-util-find-after": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ=="],
|
||||
|
||||
"unist-util-is": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
|
||||
|
||||
"unist-util-position": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],
|
||||
|
||||
Reference in new issue
Block a user