Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client/public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@
},
"avatar": {
"title": "Site Avatar",
"desc": "Set the avatar shown in the navigation bar by URL, upload, or drag and drop",
"desc": "Set the avatar shown in the navigation bar by URL, upload, or drag and drop. SVG logos are inverted automatically in dark mode; append #no-invert to the URL to disable",
"label": "Avatar URL"
},
"page_size": {
Expand Down
2 changes: 1 addition & 1 deletion client/public/locales/ja/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@
},
"avatar": {
"title": "サイトアバター",
"desc": "ナビゲーションバーに表示する画像を URL、アップロード、またはドラッグ&ドロップで設定します",
"desc": "ナビゲーションバーに表示する画像を URL、アップロード、またはドラッグ&ドロップで設定します。SVG ロゴはダークモードで自動的に反転されます。無効にするには URL に #no-invert を追加してください",
"label": "アバター URL"
},
"page_size": {
Expand Down
2 changes: 1 addition & 1 deletion client/public/locales/zh-CN/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@
},
"avatar": {
"title": "站点头像",
"desc": "设置显示在导航栏的头像,支持填写 URL、上传图片或拖拽上传",
"desc": "设置显示在导航栏的头像,支持填写 URL、上传图片或拖拽上传。SVG 头像在暗色模式下自动反色,URL 后加 #no-invert 可停用",
"label": "头像 URL"
},
"page_size": {
Expand Down
2 changes: 1 addition & 1 deletion client/public/locales/zh-TW/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@
},
"avatar": {
"title": "網站頭像",
"desc": "設定顯示在導覽列的頭像,支援填寫 URL、上傳圖片或拖拽上傳",
"desc": "設定顯示在導覽列的頭像,支援填寫 URL、上傳圖片或拖拽上傳。SVG 頭像在暗色模式下自動反色,URL 後加 #no-invert 可停用",
"label": "頭像 URL"
},
"page_size": {
Expand Down
3 changes: 2 additions & 1 deletion client/src/components/admin-layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import { Link, useLocation } from "wouter";
import { useSiteConfig } from "../hooks/useSiteConfig";
import { ImageWithFallback } from "./image-with-fallback";
import { darkInvertImageClass } from "../utils/image-dark-invert";

function AdminNavItem({
href,
Expand Down Expand Up @@ -50,7 +51,7 @@ export function AdminLayout({
<div className="rounded-2xl border border-black/10 bg-w p-5 dark:border-white/10">
<Link href="/" className="flex items-center gap-4 rounded-xl px-2 py-2 transition-colors hover:bg-neutral-50 dark:hover:bg-white/5">
{siteConfig.avatar ? (
<ImageWithFallback src={siteConfig.avatar} alt={siteConfig.name} className="h-12 w-12 rounded-2xl border border-black/10 dark:border-white/10" />
<ImageWithFallback src={siteConfig.avatar} alt={siteConfig.name} className="h-12 w-12 rounded-2xl border border-black/10 dark:border-white/10" imageClassName={darkInvertImageClass(siteConfig.avatar)} />
) : null}
<div className="min-w-0">
<p className="truncate text-base font-semibold t-primary">{siteConfig.name}</p>
Expand Down
2 changes: 2 additions & 0 deletions client/src/components/image-upload-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isImageFile,
uploadImageFile,
} from "../utils/image-upload";
import { darkInvertImageClass } from "../utils/image-dark-invert";

type ImageUploadInputProps = {
value: string;
Expand Down Expand Up @@ -74,6 +75,7 @@ export function ImageUploadInput({
src={value}
alt={t("upload.image.preview_alt")}
className="h-full w-full bg-transparent"
imageClassName={darkInvertImageClass(value)}
/>
) : (
<i className="ri-image-line text-3xl text-neutral-400" aria-hidden="true" />
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/markdown_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ export function MarkdownEditor({ content, setContent, placeholder = "> Write you
onChange={upChange}
className="hidden"
type="file"
accept="image/gif,image/jpeg,image/jpg,image/png"
accept="image/gif,image/jpeg,image/jpg,image/png,image/svg+xml"
/>
<MarkdownToolButton
label={label}
Expand Down
2 changes: 2 additions & 0 deletions client/src/components/site-header/primitives/brand-link.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Link } from "wouter";
import type { SiteHeaderConfig } from "../shared";
import { ImageWithFallback } from "../../image-with-fallback";
import { darkInvertImageClass } from "../../../utils/image-dark-invert";

export function BrandLink({
siteConfig,
Expand Down Expand Up @@ -28,6 +29,7 @@ export function BrandLink({
src={siteConfig.avatar}
alt={siteConfig.name}
className={avatarClassName || (compact ? "h-10 w-10 rounded-full border-2" : "h-12 w-12 rounded-2xl border-2")}
imageClassName={darkInvertImageClass(siteConfig.avatar)}
/>
) : null}
<div className={`${showAvatar ? (compact ? "mx-2" : "mx-4") : ""} flex min-w-0 flex-col items-start justify-center`}>
Expand Down
2 changes: 2 additions & 0 deletions client/src/page/settings-items.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Button } from "../components/button";
import { useConfirm } from "../components/dialog";
import { ImageUploadInput } from "../components/image-upload-input";
import { ImageWithFallback } from "../components/image-with-fallback";
import { darkInvertImageClass } from "../utils/image-dark-invert";
import {
SettingsCard,
SettingsCardBody,
Expand Down Expand Up @@ -230,6 +231,7 @@ export function ItemImageInput({
src={value}
alt={configKeyTitle}
className={`h-10 w-10 ${shape === "circle" ? "rounded-full" : "rounded-2xl"}`}
imageClassName={darkInvertImageClass(value)}
/>
) : null}
<span className="max-w-56 truncate text-sm text-neutral-500 dark:text-neutral-400">
Expand Down
68 changes: 68 additions & 0 deletions client/src/utils/__tests__/image-dark-invert.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, it, expect } from "bun:test";
import {
shouldInvertImageInDarkMode,
darkInvertImageClass,
} from "../image-dark-invert";

describe("shouldInvertImageInDarkMode", () => {
it("returns true for .svg URLs", () => {
expect(shouldInvertImageInDarkMode("https://img.example.com/logo.svg")).toBe(true);
expect(shouldInvertImageInDarkMode("logo.svg")).toBe(true);
expect(shouldInvertImageInDarkMode("/images/a.b.svg")).toBe(true);
});

it("is case-insensitive for the .svg extension", () => {
expect(shouldInvertImageInDarkMode("https://img.example.com/LOGO.SVG")).toBe(true);
});

it("ignores query strings and hash metadata when detecting the extension", () => {
expect(shouldInvertImageInDarkMode("https://img.example.com/logo.svg?v=2")).toBe(true);
expect(
shouldInvertImageInDarkMode("https://img.example.com/logo.svg#blurhash=abc&width=10&height=10"),
).toBe(true);
});

it("returns true for svg data URIs", () => {
expect(
shouldInvertImageInDarkMode("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iLyoqLyI+"),
).toBe(true);
expect(
shouldInvertImageInDarkMode("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'></svg>"),
).toBe(true);
});

it("returns false for non-SVG sources", () => {
expect(shouldInvertImageInDarkMode("https://img.example.com/logo.png")).toBe(false);
expect(shouldInvertImageInDarkMode("https://img.example.com/avatar.webp")).toBe(false);
expect(shouldInvertImageInDarkMode("data:image/png;base64,iVBOR")).toBe(false);
expect(shouldInvertImageInDarkMode("https://img.example.com/logo.svg.png")).toBe(false);
});

it("returns false for empty or missing sources", () => {
expect(shouldInvertImageInDarkMode(undefined)).toBe(false);
expect(shouldInvertImageInDarkMode(null)).toBe(false);
expect(shouldInvertImageInDarkMode("")).toBe(false);
expect(shouldInvertImageInDarkMode(" ")).toBe(false);
});

it("respects the #no-invert opt-out flag", () => {
expect(shouldInvertImageInDarkMode("https://img.example.com/logo.svg#no-invert")).toBe(false);
expect(
shouldInvertImageInDarkMode("https://img.example.com/logo.svg#blurhash=abc&no-invert"),
).toBe(false);
expect(
shouldInvertImageInDarkMode("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iLyoqLyI+#no-invert"),
).toBe(false);
});
});

describe("darkInvertImageClass", () => {
it("returns dark:invert for SVG sources", () => {
expect(darkInvertImageClass("https://img.example.com/logo.svg")).toBe("dark:invert");
});

it("returns an empty string otherwise", () => {
expect(darkInvertImageClass("https://img.example.com/logo.png")).toBe("");
expect(darkInvertImageClass(undefined)).toBe("");
});
});
33 changes: 33 additions & 0 deletions client/src/utils/image-dark-invert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const NO_INVERT_FLAG = "no-invert";

/**
* Monochrome SVG logos are unreadable on dark backgrounds. Detect SVG sources
* (URL or data URI) so callers can apply `dark:invert` in dark mode.
*
* Opt out by appending `#no-invert` to the URL, mirroring the existing
* `#blurhash=` URL-fragment metadata convention.
*/
export function shouldInvertImageInDarkMode(src?: string | null): boolean {
if (!src) {
return false;
}

const [baseUrl = "", fragment = ""] = src.split("#", 2);
if (fragment === NO_INVERT_FLAG || new URLSearchParams(fragment).has(NO_INVERT_FLAG)) {
return false;
}

const [path = ""] = baseUrl.split("?", 2);
const normalized = path.trim().toLowerCase();
if (normalized.startsWith("data:image/svg+xml")) {
return true;
}
return normalized.endsWith(".svg");
}

/**
* Tailwind class that inverts the image in dark mode when `src` is an SVG.
*/
export function darkInvertImageClass(src?: string | null): string {
return shouldInvertImageInDarkMode(src) ? "dark:invert" : "";
}
123 changes: 123 additions & 0 deletions server/src/services/__tests__/favicon.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,129 @@ describe('FaviconService', () => {
}
});

it('should serve SVG avatar directly as favicon when avatar is an SVG', async () => {
const clientConfig = new TestCacheImpl();
await clientConfig.set('site.avatar', 'https://example.com/logo.svg');

app = new Hono<{ Bindings: Env; Variables: Variables }>();
app.use(createMiddleware<{ Bindings: Env; Variables: Variables }>(async (c, next) => {
c.set('db', db);
c.set('cache', new TestCacheImpl());
c.set('serverConfig', new TestCacheImpl());
c.set('clientConfig', clientConfig);
c.set('jwt', {
sign: async (payload: any) => `mock_token_${payload.id}`,
verify: async (token: string) => token.startsWith('mock_token_') ? { id: 1 } : null,
} as JWTUtils);
c.set('oauth2', undefined);
c.set('env', env);
c.set('uid', 1);
c.set('admin', true);
await next();
}));
app.route('/', FaviconService());

const svgContent = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"></svg>';
const originalFetch = globalThis.fetch;
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string'
? input
: input instanceof URL
? input.toString()
: input.url;

if (url === 'https://example.com/logo.svg') {
return new Response(svgContent, {
status: 200,
headers: { 'Content-Type': 'image/svg+xml' },
});
}

const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
if (url.endsWith('/images/favicon.svg') && method === 'PUT') {
return new Response(null, { status: 200 });
}

if (url.endsWith('/images/favicon.svg')) {
return new Response('missing', { status: 404 });
}

if (url.endsWith('/images/favicon.webp')) {
return new Response('missing', { status: 404 });
}

return originalFetch(input, init);
};

try {
const res = await app.request('/', { method: 'GET' }, env);
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toBe('image/svg+xml');
expect(await res.text()).toBe(svgContent);
} finally {
globalThis.fetch = originalFetch;
}
});

it('should serve cached SVG favicon without refetching the avatar', async () => {
const clientConfig = new TestCacheImpl();
await clientConfig.set('site.avatar', 'https://example.com/logo.svg');

app = new Hono<{ Bindings: Env; Variables: Variables }>();
app.use(createMiddleware<{ Bindings: Env; Variables: Variables }>(async (c, next) => {
c.set('db', db);
c.set('cache', new TestCacheImpl());
c.set('serverConfig', new TestCacheImpl());
c.set('clientConfig', clientConfig);
c.set('jwt', {
sign: async (payload: any) => `mock_token_${payload.id}`,
verify: async (token: string) => token.startsWith('mock_token_') ? { id: 1 } : null,
} as JWTUtils);
c.set('oauth2', undefined);
c.set('env', env);
c.set('uid', 1);
c.set('admin', true);
await next();
}));
app.route('/', FaviconService());

const cachedSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">cached</svg>';
const originalFetch = globalThis.fetch;
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string'
? input
: input instanceof URL
? input.toString()
: input.url;

if (url === 'https://example.com/logo.svg') {
return new Response('avatar should not be fetched when cache exists', { status: 500 });
}

if (url.endsWith('/images/favicon.svg')) {
return new Response(cachedSvg, {
status: 200,
headers: { 'Content-Type': 'image/svg+xml' },
});
}

if (url.endsWith('/images/favicon.webp')) {
return new Response('missing', { status: 404 });
}

return originalFetch(input, init);
};

try {
const res = await app.request('/', { method: 'GET' }, env);
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toBe('image/svg+xml');
expect(await res.text()).toBe(cachedSvg);
} finally {
globalThis.fetch = originalFetch;
}
});

it('should return favicon through R2 API when S3_ACCESS_HOST is missing', async () => {
const r2Env = createMockEnv({
S3_ACCESS_HOST: '' as any,
Expand Down
Loading
Loading