feat: 扩展本地主题兼容能力

This commit is contained in:
SkyJourney
2026-07-26 00:26:43 +08:00
parent fa07472428
commit ec14f7970a
7 changed files with 769 additions and 130 deletions
+13 -3
View File
@@ -13,7 +13,7 @@
- Markdown、Front Matter、安全过滤和扩展语法渲染核心;
- 表格、任务列表、脚注、代码高亮、KaTeX 和 Mermaid
- iframe 隔离的 A4 页面预览与主题切换;
- 内置 Typora 风格主题,以及仅供本机使用的 Typora 默认主题导入工具;
- 内置 Typora 风格主题,以及仅供本机使用的三套白色 Typora 默认主题导入工具;
- Docker 与 PDF 渲染目录预留。
Chromium PDF 下载、完整导出配置面板和本地资源文件处理将在后续阶段实现。
@@ -37,16 +37,26 @@ npm run dev
## 本地导入 Typora 默认主题
项目不会打包或提交 Typora 官方默认主题。如本机已安装 Typora,可以将 GitHub 默认主题复制到 Git 忽略的本地主题目录:
项目不会打包或提交 Typora 官方默认主题。如本机已安装 Typora,可以将 GitHub、Pixyll 和 Whitey 三套适合打印的白色默认主题及 Typora 基础 CSS 复制到 Git 忽略的本地主题目录:
```powershell
npm run theme:import-typora
```
默认读取 `%APPDATA%\Typora\themes`,写入 `.local\themes\typora-github`。启动开发服务后,主题会出现在预览页面的主题选择器中。导入工具不会覆盖已存在的目标目录;如需重新导入,请先自行确认并移走旧目录。
默认从 Typora 安装目录的 `resources\style` 读取基础 CSS、主题和资源,写入 `.local\themes\typora-*`。启动开发服务后,这些主题会出现在预览页面的主题选择器中。
导入工具不会默认覆盖已存在的目标。确认替换本地副本时使用:
```powershell
npm run theme:import-typora -- --replace
```
旧副本会移动到 `.local\theme-backups`
本地主题由动态主题注册器加载,CSS 中的相对字体和图片会通过受限资源接口提供。外部 URL、越界路径和符号链接逃逸会被拒绝。
自定义主题目录、`theme.json`、CSS 组合顺序、资源引用和安全限制详见 [主题开发指南](docs/THEMES.md)。
## 测试与构建
```powershell
+107 -14
View File
@@ -7,6 +7,7 @@ import {
import {
extname,
isAbsolute,
posix,
relative,
resolve,
sep
@@ -39,6 +40,10 @@ const assetContentTypes: Record<string, string> = {
".woff2": "font/woff2"
};
const cssImportPattern =
/@import\s+(?:url\(\s*(?:\"([^\"]+)\"|'([^']+)'|([^'\"\s)]+))\s*\)|\"([^\"]+)\"|'([^']+)')\s*;/gi;
const maximumCssImportDepth = 8;
function isMissingFileError(error: unknown) {
return (
error instanceof Error &&
@@ -119,6 +124,9 @@ async function readThemeRoot(
throw new Error("主题 bundled 标记与来源不一致");
}
if (manifest.base) {
await resolveThemeFile(directory, manifest.base);
}
await resolveThemeFile(directory, manifest.entry);
if (manifest.print) {
await resolveThemeFile(directory, manifest.print);
@@ -145,13 +153,12 @@ function encodeAssetPath(path: string) {
.join("/");
}
function prepareThemeCss(css: string, themeId: string) {
const withoutTyporaExportIncludes = css.replace(
/^\s*@include-when-export\s+url\([^;\r\n]+;\s*$/gim,
""
);
return withoutTyporaExportIncludes.replace(
function prepareCssSegment(
css: string,
themeId: string,
cssDirectory: string
) {
return css.replace(
/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,
(match, _quote: string, rawValue: string) => {
const value = rawValue.trim();
@@ -171,11 +178,96 @@ function prepareThemeCss(css: string, themeId: string) {
throw new Error(`主题资源路径不安全:${value}`);
}
return `url("/api/themes/${encodeURIComponent(themeId)}/assets/${encodeAssetPath(normalized)}")`;
const assetPath = posix.normalize(posix.join(cssDirectory, normalized));
if (
assetPath === ".." ||
assetPath.startsWith("../") ||
assetPath.startsWith("/")
) {
throw new Error(`主题资源路径越界:${value}`);
}
return `url("/api/themes/${encodeURIComponent(themeId)}/assets/${encodeAssetPath(assetPath)}")`;
}
);
}
function readImportedPath(match: RegExpMatchArray) {
return match.slice(1).find((value): value is string => value !== undefined);
}
function normalizeCssPath(relativePath: string) {
const normalized = relativePath.replaceAll("\\", "/");
if (
normalized.startsWith("/") ||
normalized.split("/").includes("..") ||
/^[a-z][a-z0-9+.-]*:/i.test(normalized)
) {
throw new Error(`主题 CSS 路径不安全:${relativePath}`);
}
return posix.normalize(normalized.replace(/^\.\//, ""));
}
async function loadThemeCssFile(
theme: ThemeRecord,
relativePath: string,
importStack: string[] = []
): Promise<string> {
const normalizedPath = normalizeCssPath(relativePath);
if (importStack.includes(normalizedPath)) {
throw new Error(
`主题 CSS 存在循环引用:${[...importStack, normalizedPath].join(" -> ")}`
);
}
if (importStack.length >= maximumCssImportDepth) {
throw new Error(`主题 CSS 导入层级超过 ${maximumCssImportDepth}`);
}
const cssPath = await resolveThemeFile(theme.directory, normalizedPath);
const css = (await readFile(cssPath, "utf8")).replace(
/^\s*@include-when-export\s+url\([^;\r\n]+;\s*$/gim,
""
);
const cssDirectory = posix.dirname(normalizedPath);
const matches = [...css.matchAll(cssImportPattern)];
let result = "";
let previousEnd = 0;
for (const match of matches) {
const matchStart = match.index ?? 0;
result += prepareCssSegment(
css.slice(previousEnd, matchStart),
theme.manifest.id,
cssDirectory
);
const importedPath = readImportedPath(match);
if (!importedPath) {
throw new Error(`无法解析主题 CSS 导入:${match[0]}`);
}
const normalizedImport = normalizeCssPath(importedPath);
const importPath = posix.normalize(posix.join(cssDirectory, normalizedImport));
result += await loadThemeCssFile(theme, importPath, [
...importStack,
normalizedPath
]);
previousEnd = matchStart + match[0].length;
}
const remainder = css.slice(previousEnd);
result += prepareCssSegment(
remainder,
theme.manifest.id,
cssDirectory
);
if (/@import\b/i.test(result)) {
throw new Error("主题包含不支持的 CSS @import 语法");
}
return result;
}
export function createThemeRegistry(options: ThemeRegistryOptions) {
async function list() {
const [bundledThemes, localThemes] = await Promise.all([
@@ -206,16 +298,17 @@ export function createThemeRegistry(options: ThemeRegistryOptions) {
}
const cssFiles = [
await resolveThemeFile(theme.directory, theme.manifest.entry),
...(theme.manifest.base ? [theme.manifest.base] : []),
theme.manifest.entry,
...(theme.manifest.print
? [await resolveThemeFile(theme.directory, theme.manifest.print)]
? [theme.manifest.print]
: [])
];
const css = (
await Promise.all(cssFiles.map((path) => readFile(path, "utf8")))
return (
await Promise.all(
cssFiles.map((path) => loadThemeCssFile(theme, path))
)
).join("\n");
return prepareThemeCss(css, themeId);
}
async function getAsset(themeId: string, assetPath: string) {
+106 -19
View File
@@ -4,10 +4,32 @@ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildApp } from "../src/app.js";
import { createThemeRegistry } from "../src/theme-registry.js";
let app: FastifyInstance | undefined;
let temporaryDirectory: string | undefined;
function localThemeManifest(
id: string,
overrides: Record<string, unknown> = {}
) {
return {
manifestVersion: 1,
id,
name: "本地测试主题",
version: "local",
description: "本地主题测试",
author: "test",
license: "local-only",
entry: "theme.css",
domPreset: "typora",
defaultFontSize: "16px",
supportedFeatures: ["code", "table"],
bundled: false,
...overrides
};
}
afterEach(async () => {
await app?.close();
if (temporaryDirectory) {
@@ -64,36 +86,42 @@ describe("预览 API", () => {
it("发现本地主题并安全提供相对字体资源", async () => {
temporaryDirectory = await mkdtemp(join(tmpdir(), "md-to-pdf-theme-"));
const themeDirectory = join(temporaryDirectory, "local-test");
await mkdir(join(themeDirectory, "fonts"), { recursive: true });
await mkdir(join(themeDirectory, "partials", "fonts"), {
recursive: true
});
await writeFile(
join(themeDirectory, "theme.json"),
JSON.stringify({
manifestVersion: 1,
id: "local-test",
name: "本地测试主题",
version: "local",
description: "本地主题测试",
author: "test",
license: "local-only",
entry: "theme.css",
domPreset: "typora",
defaultFontSize: "16px",
supportedFeatures: ["code", "table"],
bundled: false
}),
JSON.stringify(
localThemeManifest("local-test", {
base: "typora-base.css"
})
),
"utf8"
);
await writeFile(
join(themeDirectory, "typora-base.css"),
"/* base-layer */ table { width: 100%; border-collapse: collapse; }",
"utf8"
);
await writeFile(
join(themeDirectory, "theme.css"),
[
"@include-when-export url(https://example.com/font.css);",
"@font-face { src: url('./fonts/test.woff2') format('woff2'); }",
"@import \"partials/typography.css\";",
"#write { font-family: LocalTest; }"
].join("\n"),
"utf8"
);
await writeFile(
join(themeDirectory, "fonts", "test.woff2"),
join(themeDirectory, "partials", "typography.css"),
[
"/* imported-layer */",
"@font-face { src: url('./fonts/test.woff2') format('woff2'); }"
].join("\n"),
"utf8"
);
await writeFile(
join(themeDirectory, "partials", "fonts", "test.woff2"),
Buffer.from([0, 1, 2, 3])
);
@@ -123,15 +151,74 @@ describe("预览 API", () => {
expect(cssResponse.statusCode).toBe(200);
expect(cssResponse.body).not.toContain("@include-when-export");
expect(cssResponse.body).toContain(
"/api/themes/local-test/assets/fonts/test.woff2"
"/api/themes/local-test/assets/partials/fonts/test.woff2"
);
expect(cssResponse.body.indexOf("base-layer")).toBeLessThan(
cssResponse.body.indexOf("imported-layer")
);
expect(cssResponse.body.indexOf("imported-layer")).toBeLessThan(
cssResponse.body.indexOf("font-family: LocalTest")
);
const assetResponse = await app.inject({
method: "GET",
url: "/api/themes/local-test/assets/fonts/test.woff2"
url: "/api/themes/local-test/assets/partials/fonts/test.woff2"
});
expect(assetResponse.statusCode).toBe(200);
expect(assetResponse.headers["content-type"]).toContain("font/woff2");
expect(assetResponse.rawPayload).toEqual(Buffer.from([0, 1, 2, 3]));
});
it("拒绝主题 CSS 循环导入", async () => {
temporaryDirectory = await mkdtemp(join(tmpdir(), "md-to-pdf-theme-"));
const bundledRoot = join(temporaryDirectory, "bundled");
const localRoot = join(temporaryDirectory, "local");
const themeDirectory = join(localRoot, "cycle-test");
await mkdir(bundledRoot, { recursive: true });
await mkdir(themeDirectory, { recursive: true });
await writeFile(
join(themeDirectory, "theme.json"),
JSON.stringify(localThemeManifest("cycle-test")),
"utf8"
);
await writeFile(
join(themeDirectory, "theme.css"),
'@import "nested.css";',
"utf8"
);
await writeFile(
join(themeDirectory, "nested.css"),
'@import "theme.css";',
"utf8"
);
const registry = createThemeRegistry({ bundledRoot, localRoot });
await expect(registry.getCss("cycle-test")).rejects.toThrow(
"主题 CSS 存在循环引用"
);
});
it("拒绝主题 CSS 导入外部地址", async () => {
temporaryDirectory = await mkdtemp(join(tmpdir(), "md-to-pdf-theme-"));
const bundledRoot = join(temporaryDirectory, "bundled");
const localRoot = join(temporaryDirectory, "local");
const themeDirectory = join(localRoot, "external-test");
await mkdir(bundledRoot, { recursive: true });
await mkdir(themeDirectory, { recursive: true });
await writeFile(
join(themeDirectory, "theme.json"),
JSON.stringify(localThemeManifest("external-test")),
"utf8"
);
await writeFile(
join(themeDirectory, "theme.css"),
'@import "https://example.com/theme.css";',
"utf8"
);
const registry = createThemeRegistry({ bundledRoot, localRoot });
await expect(registry.getCss("external-test")).rejects.toThrow(
"主题 CSS 路径不安全"
);
});
});
+53 -40
View File
@@ -19,11 +19,12 @@ main
已有提交:
```text
fa07472 feat: 实现网页实时预览
7224dfd feat: 实现 Markdown 渲染核心
ec48bce chore: 初始化项目骨架
```
当前工作区存在未提交修改,主要是网页实时预览、预览 API、动态主题注册和本地 Typora 主题导入。接手时必须保留并审查这些修改,不要重置工作区。
当前工作区存在未提交修改,主要是主题基础 CSS 组合、安全的 CSS `@import` 展开、三套本地 Typora 默认主题导入和主题开发文档。接手时必须保留并审查这些修改,不要重置工作区。
## 2. 已完成
@@ -59,14 +60,16 @@ ec48bce chore: 初始化项目骨架
- 主题 ID、名称、版本、作者、许可证;
- DOM 预设;
- 支持能力声明;
- 主体 CSS 和打印 CSS
- 可选基础 CSS、主体 CSS 和打印 CSS
- 自制 Typora 风格主题;
- `#write` 兼容文档结构;
- 内置主题和 `.local/themes` 本地主题动态扫描;
- 按基础 CSS、主体 CSS、打印 CSS 的固定顺序组合;
- 主题内相对 CSS `@import` 安全展开;
- 主题 CSS 相对资源重写与受限资源接口;
- 目录匹配、真实路径包含关系和外部 URL 安全检查。
内置主题为项目自有实现,没有复制 Typora 官方默认主题。用户可以通过导入工具将本机已安装的 Typora GitHub 默认主题复制到 Git 忽略的 `.local/themes/typora-github`,该副本仅供本机使用,不进入仓库或发布包。
内置主题为项目自有实现,没有复制 Typora 官方默认主题。用户可以通过导入工具将本机已安装的 Typora 基础 CSS以及 GitHub、Pixyll 和 Whitey 三套适合打印的白色默认主题复制到 Git 忽略的 `.local/themes`。这些副本仅供本机使用,不进入仓库、容器或发布包。
### 2.4 Markdown 渲染核心
@@ -88,43 +91,48 @@ ec48bce chore: 初始化项目骨架
- 统一 `<article id="write">` 输出;
- 5 项渲染单元测试。
### 2.5 网页实时预览
提交 `fa07472` 已完成:
- 可测试的 Fastify `buildApp()`
- `POST /api/render` 服务端统一 Markdown 渲染;
- 动态主题清单、CSS 和资源 API;
- Markdown 编辑及本地 `.md` 文件读取;
- 250ms 防抖 A4 实时预览;
- iframe 隔离主题 CSS
- KaTeX、highlight.js 和按需加载的 Mermaid
- 桌面双栏与移动端上下布局;
- 5 项渲染器测试和 4 项后端测试。
## 3. 当前未提交工作
以下内容已写入工作区,但尚未提交:
### 3.1 后端预览 API
### 3.1 主题清单与服务端主题注册
- 将 Fastify 应用拆分为可测试的 `buildApp()`
- `POST /api/render`:接收 Markdown 并返回安全渲染结果。
- `GET /api/themes`:动态返回内置和本地可用主题
- `GET /api/themes/:themeId/css`:返回主题 CSS 和打印 CSS
- `GET /api/themes/:themeId/assets/*`:返回经过路径校验的主题字体和图片
- 增加请求体积和参数类型检查
- 增加 4 项后端 API 测试
- 主题清单新增可选 `base` 字段
- CSS 按基础 CSS、主体 CSS、打印 CSS 的顺序组合,预览与未来 PDF 可复用同一结果。
- 支持带引号或 `url()` 写法的相对 `@import`
- 限制导入深度为 8 层,并检测循环引用
- 阻止外部 URL、绝对路径和 `..` 越界导入
- 按每个 CSS 文件所在目录重写相对字体和图片 URL
- 增加基础 CSS 组合、相对导入、循环导入和外部导入测试,后端测试增至 6 项
### 3.2 网页预览
### 3.2 本地 Typora 默认主题导入
- Markdown 文本编辑区;
- 本地 `.md` 文件读取;
- 250ms 防抖实时预览;
- 固定 210mm 宽度的 A4 纸张效果;
- 内置和本地主题选择;
- iframe 隔离主题 CSS,避免主题影响应用界面;
- KaTeX 样式;
- highlight.js 样式;
- Mermaid 浏览器渲染;
- Mermaid 改为按需加载;
- Mermaid 使用逐个 `render()` 后注入安全 SVG
- 桌面双栏与移动端上下布局;
- PDF 按钮保留为下一阶段入口。
- 导入器从本机 Typora 安装目录读取 `resources/style`
- 一次导入 GitHub、Pixyll 和 Whitey 三套适合打印的白色默认主题。
- 每套本地主题包含独立的 Typora 基础 CSS、主题 CSS 和所需资源。
- 主题版本从 Typora `resources/package.json` 读取;当前本机版本为 1.14.7。
- 默认拒绝覆盖已有主题;`--replace` 使用暂存目录并将旧副本备份到 `.local/theme-backups/<时间戳>`
- 当前三套主题及替换操作产生的备份均位于被 Git 忽略的 `.local`,不得提交或发布。
### 3.3 文档及依赖
- README 已更新为预览阶段状态
- `npm run theme:import-typora` 本地主题导入命令
- `.local/` 已加入 Git 忽略规则
- 增加 Mermaid、KaTeX、highlight.js 和后端测试依赖。
- `package-lock.json` 已更新。
- README 已更新三套本地 Typora 主题的导入和替换说明
- `docs/THEMES.md`,说明主题目录、清单字段、CSS 加载顺序、`#write` DOM、相对资源、安全限制和自定义主题流程
- `npm run theme:import-typora` 保持为本地导入入口
## 4. 已执行验证
@@ -140,22 +148,25 @@ git diff --check
结果:
- 渲染器测试:5 项通过;
- 后端测试:4 项通过;
- 后端测试:6 项通过;
- 全项目类型检查通过;
- 生产构建通过;
- `git diff --check` 通过,仅出现工作区 LF 将来可能转为 CRLF 的提示
- `git diff --check` 通过,仅出现工作区 LF 将来可能转为 CRLF 的提示
- 导入器默认的已存在目标保护通过;
- GitHub、Pixyll 和 Whitey 三套本地主题的 CSS API 均返回成功,组合结果无残留 `@import`
已使用浏览器插件完成视觉验证:
- 导入并打开 `tmp/数据中台项目周报_2026_W30.md`
- 参考 `tmp/数据中台项目周报_2026_W30.pdf` 的 Typora 输出;
- A4 纸张宽度、标题、长表格和滚动布局正常
- 本地 Typora GitHub 主题及 Open Sans 字体加载正常
- 内置主题与本地主题切换正常
- GitHub、Pixyll 和 Whitey 三套保留的本地主题均可正常切换
- 三套主题中的表格均为 `border-collapse: collapse`、单元格间距为 0,并铺满 `#write` 内容宽度
- GitHub 表格边框颜色与主题定义的 `#dfe2e5` 一致
- Open Sans、PT Serif 和 Merriweather 字体资源均成功加载;
- KaTeX、代码高亮和 Mermaid 正常显示;
- 浏览器控制台无警告或错误。
视觉验证所启动的开发服务进程树已清理,3001 和 5173 端口无残留监听
为方便用户继续检查,开发服务当前仍在后台运行,前端监听 5173,后端监听 3001
## 5. 当前注意事项
@@ -163,7 +174,9 @@ git diff --check
- `apps/web/src/App.tsx` 是当前预览实现的主要文件。
- `apps/server/src/app.ts` 是新增的可测试 Fastify 应用。
- `apps/server/src/theme-registry.ts` 负责内置和本地主题发现、CSS 处理及资源安全。
- `.local/themes/typora-github` 是用户本机副本,已被 Git 忽略,不得提交。
- `.local/themes/typora-*` 是用户本机副本,已被 Git 忽略,不得提交。
- `.local/theme-backups` 中保留 GitHub、Pixyll 和 Whitey 的可恢复备份;Newsprint 和 Night 的当前副本及备份已按用户要求删除。
- Typora 官方资源是 All Rights Reserved,仅限当前用户本机使用,不进入 Git、容器或发布包。
- Mermaid 已按需加载,但生产构建仍提示 `mermaid.core``cynefin` 两个分块超过 500 kB;这不影响功能,可后续优化。
- PDF 生成尚未实现。
- 资源目录上传、本地相对图片、临时目录和路径安全尚未实现。
@@ -171,12 +184,12 @@ git diff --check
## 6. 推荐接手顺序
### 阶段一:提交网页预览
### 阶段一:提交主题兼容增强
网页预览、动态主题、本地 Typora 主题导入、全量验证和视觉检查均已完成。用户确认后创建独立提交:
网页实时预览已在 `fa07472` 提交。当前主题基础 CSS、三套本地 Typora 主题导入、主题开发文档、全量验证和视觉检查均已完成。用户确认后创建独立提交:
```text
feat: 实现网页实时预览
feat: 扩展本地主题兼容能力
```
### 阶段二:实现真实 PDF
+275
View File
@@ -0,0 +1,275 @@
# 主题开发指南
主题用于控制 Markdown 正文的字体、颜色、标题、表格、引用、代码块、公式和图表等视觉样式。纸张尺寸、页边距、页眉页脚、页码和 PDF 元数据属于导出配置,不应写入主题。
网页预览与未来的 Chromium PDF 必须使用相同的 `<article id="write">`、Markdown 渲染结果、主题 CSS 和打印 CSS。
## 1. 主题位置
项目支持两类主题:
```text
themes/<theme-id>/ 随项目分发的内置主题
.local/themes/<theme-id>/ 仅供当前设备使用的本地主题
```
- 内置主题的 `bundled` 必须为 `true`,并具有允许项目分发的明确许可证。
- 本地主题的 `bundled` 必须为 `false`,整个 `.local/` 目录已被 Git 忽略。
- 主题目录名必须与清单中的 `id` 完全一致。
## 2. 目录结构
最小主题:
```text
.local/themes/example/
├── theme.json
└── theme.css
```
包含基础层、打印层和资源的主题:
```text
.local/themes/example/
├── theme.json
├── base.css
├── theme.css
├── print.css
├── partials/
│ └── code.css
├── fonts/
│ └── example.woff2
└── images/
└── quote.svg
```
每个主题必须自包含,不得通过 `../` 引用主题目录外的共享文件。
## 3. `theme.json`
完整示例:
```json
{
"manifestVersion": 1,
"id": "example",
"name": "示例主题",
"version": "1.0.0",
"description": "用于演示主题清单的本地主题。",
"author": "示例作者",
"license": "MIT",
"base": "base.css",
"entry": "theme.css",
"print": "print.css",
"domPreset": "typora",
"defaultFontSize": "16px",
"supportedFeatures": [
"code",
"table",
"task-list",
"footnote",
"katex",
"mermaid"
],
"bundled": false
}
```
字段说明:
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `manifestVersion` | 是 | 当前固定为 `1`。 |
| `id` | 是 | 小写字母、数字和连字符组成,且必须与目录名一致。 |
| `name` | 是 | 主题选择器中显示的名称。 |
| `version` | 是 | 主题版本,最长 30 个字符。 |
| `description` | 是 | 主题用途与来源说明。 |
| `author` | 是 | 作者或维护者。 |
| `license` | 是 | 许可证或本地使用边界。 |
| `base` | 否 | 可复用的基础 CSS。 |
| `entry` | 是 | 主题主体 CSS。 |
| `print` | 否 | 打印 CSS,建议将规则放入 `@media print`。 |
| `domPreset` | 是 | 当前支持 `typora``github``generic`。 |
| `defaultFontSize` | 是 | 主题建议的正文基准字号。 |
| `supportedFeatures` | 是 | 支持能力声明。 |
| `bundled` | 是 | 内置主题为 `true`,本地主题为 `false`。 |
支持能力值包括:
```text
code
table
task-list
footnote
katex
mermaid
```
## 4. CSS 组合顺序
服务端按以下顺序组合 CSS
```text
base
→ entry
→ print
```
后加载的规则可以覆盖前面的规则。推荐职责:
- `base`:元素归一化、通用排版和分页基础规则。
- `entry`:颜色、字体、标题、表格、引用和代码块等主题视觉。
- `print`:只在打印时生效的分页与颜色调整。
如果主题不需要基础层或打印层,可以省略相应字段。
## 5. DOM 约定
渲染器输出的正文根节点固定为:
```html
<article id="write">
<!-- 安全 Markdown HTML -->
</article>
```
主题应优先使用以下选择器:
```css
#write {
color: #24292f;
font-family: system-ui, sans-serif;
line-height: 1.7;
}
#write h1,
#write h2 {
break-after: avoid-page;
}
#write table {
width: 100%;
border-collapse: collapse;
border-spacing: 0;
}
#write th,
#write td {
border: 1px solid #d0d7de;
padding: 0.5em 0.75em;
}
```
不要依赖 Typora 编辑器窗口、侧边栏、焦点状态或源码模式专用 DOM。当前预览和未来 PDF 不会添加 `typora-export` 类,纸张边距由导出配置负责。
## 6. 字体、图片和 CSS 导入
CSS 中可以使用主题目录内的相对资源:
```css
@font-face {
font-family: "Example";
src: url("./fonts/example.woff2") format("woff2");
}
#write blockquote {
background-image: url("./images/quote.svg");
}
```
嵌套 CSS 可以使用相对于自身文件的资源:
```css
/* theme.css */
@import "partials/code.css";
```
```css
/* partials/code.css */
@font-face {
font-family: "Example Mono";
src: url("./fonts/example-mono.woff2") format("woff2");
}
```
允许通过资源接口提供的扩展名:
```text
.gif .jpeg .jpg .png .svg .webp
.ttf .woff .woff2
```
CSS `@import` 会在服务端展开,不作为静态资源直接返回。
## 7. 安全限制
主题注册器会拒绝:
- HTTP、HTTPS、协议相对地址和其他外部 URL;
- 绝对文件路径;
-`..` 的 CSS、字体或图片路径;
- 逃出主题目录的符号链接;
- 非文件资源;
- CSS 循环导入;
- 超过 8 层的 CSS 导入;
- 不支持的 `@import` 语法;
- 不在允许列表中的静态资源类型。
`data:` URL 和同文档 `#fragment` 引用可以保留。Typora 专用的 `@include-when-export` 外部字体声明会被移除,主题应同时提供本地字体文件或可靠的系统字体回退。
## 8. 创建本地主题
1.`.local/themes` 下创建与主题 ID 同名的目录。
2. 编写 `theme.json` 和入口 CSS。
3. 启动开发服务:
```powershell
npm run dev
```
4. 打开主题选择器检查主题是否出现。
5. 使用包含标题、表格、代码、公式和 Mermaid 的 Markdown 验证。
6. 检查浏览器控制台、窄屏布局和打印样式。
主题清单或资源路径无效时,服务端会拒绝加载该主题,而不是跳过安全检查。
## 9. 本地导入 Typora 默认主题
本机安装 Typora 后,可以导入 GitHub、Pixyll 和 Whitey 三套适合打印的白色默认主题:
```powershell
npm run theme:import-typora
```
导入工具从 Typora 安装目录读取:
```text
resources/style/base.css
resources/style/themes/
```
每套主题都会获得独立的 `typora-base.css`、主题 CSS、资源目录和 `theme.json`。已有目标默认不会被覆盖。
确认替换现有本地副本时使用:
```powershell
npm run theme:import-typora -- --replace
```
替换前会先在临时目录完整生成主题;旧副本移动到:
```text
.local/theme-backups/
```
Typora 当前没有为这些文件提供允许项目再分发的明确许可证,因此导入结果只能保存在 `.local`,不得提交到 Git、打包进容器或随项目发布。
## 10. 提交内置主题前检查
- 许可证明确允许再分发,并在清单和说明中记录。
- 主题目录不包含用户文档、临时文件或无关资源。
- `npm test` 通过。
- `npm run typecheck` 通过。
- `npm run build` 通过。
- `git diff --check` 通过。
- 浏览器检查表格、长代码块、KaTeX、Mermaid、字体和分页边界。
+1
View File
@@ -19,6 +19,7 @@ export const themeManifestSchema = z.object({
description: z.string().max(500),
author: z.string().max(100),
license: z.string().max(100),
base: z.string().endsWith(".css").optional(),
entry: z.string().endsWith(".css"),
print: z.string().endsWith(".css").optional(),
domPreset: z.enum(["typora", "github", "generic"]),
+214 -54
View File
@@ -1,16 +1,53 @@
import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
import {
access,
cp,
mkdir,
mkdtemp,
readFile,
rename,
rm,
writeFile
} from "node:fs/promises";
import { constants } from "node:fs";
import { access } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const sourceRoot =
process.env.TYPORA_THEME_DIR ??
join(process.env.APPDATA ?? "", "Typora", "themes");
const sourceCss = join(sourceRoot, "github.css");
const sourceAssets = join(sourceRoot, "github");
const targetRoot = join(projectRoot, ".local", "themes", "typora-github");
const localRoot = join(projectRoot, ".local");
const targetRoot = join(localRoot, "themes");
const backupRoot = join(localRoot, "theme-backups");
const replaceExisting = process.argv.slice(2).includes("--replace");
const unknownArguments = process.argv
.slice(2)
.filter((argument) => argument !== "--replace");
if (unknownArguments.length > 0) {
throw new Error(`不支持的参数:${unknownArguments.join(", ")}`);
}
const typoraThemes = [
{
key: "github",
name: "Typora 默认(GitHub,本地)"
},
{
key: "pixyll",
name: "Typora 默认(Pixyll,本地)"
},
{
key: "whitey",
name: "Typora 默认(Whitey,本地)"
}
];
async function pathExists(path) {
try {
await access(path, constants.F_OK);
return true;
} catch {
return false;
}
}
async function assertReadable(path, label) {
try {
@@ -20,59 +57,182 @@ async function assertReadable(path, label) {
}
}
await assertReadable(sourceCss, "Typora GitHub 主题");
await assertReadable(sourceAssets, "Typora GitHub 主题资源目录");
async function findTyporaInstallRoot() {
const candidates = [
process.env.TYPORA_INSTALL_DIR,
process.env.ProgramFiles
? join(process.env.ProgramFiles, "Typora")
: undefined,
process.env["ProgramFiles(x86)"]
? join(process.env["ProgramFiles(x86)"], "Typora")
: undefined,
process.env.LOCALAPPDATA
? join(process.env.LOCALAPPDATA, "Programs", "Typora")
: undefined
].filter(Boolean);
for (const candidate of candidates) {
if (
await pathExists(join(candidate, "resources", "style", "base.css"))
) {
return candidate;
}
}
try {
await access(targetRoot, constants.F_OK);
throw new Error(
`目标目录已存在:${targetRoot}\n请先人工确认并移走旧目录,再重新导入。`
"未找到 Typora 安装目录。请通过 TYPORA_INSTALL_DIR 指定安装根目录。"
);
} catch (error) {
if (error instanceof Error && error.message.startsWith("目标目录已存在")) {
throw error;
}
const installRoot = await findTyporaInstallRoot();
const sourceThemeRoot =
process.env.TYPORA_THEME_DIR ??
join(installRoot, "resources", "style", "themes");
const sourceBaseCss =
process.env.TYPORA_BASE_CSS ??
join(installRoot, "resources", "style", "base.css");
const packagePath = join(installRoot, "resources", "package.json");
const typoraVersion = (await pathExists(packagePath))
? JSON.parse(await readFile(packagePath, "utf8")).version ?? "local"
: "local";
await assertReadable(sourceBaseCss, "Typora 基础 CSS");
await assertReadable(sourceThemeRoot, "Typora 默认主题目录");
for (const theme of typoraThemes) {
await assertReadable(
join(sourceThemeRoot, `${theme.key}.css`),
`Typora ${theme.key} 主题`
);
}
const existingTargets = [];
for (const theme of typoraThemes) {
const target = join(targetRoot, `typora-${theme.key}`);
if (await pathExists(target)) {
existingTargets.push(target);
}
}
if (existingTargets.length > 0 && !replaceExisting) {
throw new Error(
[
"以下目标目录已存在:",
...existingTargets.map((path) => `- ${path}`),
"如已确认替换这些本地副本,请使用 --replace。"
].join("\n")
);
}
await mkdir(localRoot, { recursive: true });
await mkdir(targetRoot, { recursive: true });
await cp(sourceAssets, join(targetRoot, "github"), {
recursive: true,
errorOnExist: true,
force: false
});
await writeFile(
join(targetRoot, "github.css"),
await readFile(sourceCss, "utf8"),
"utf8"
);
const stagingRoot = await mkdtemp(join(localRoot, ".typora-import-"));
const manifest = {
manifestVersion: 1,
id: "typora-github",
name: "Typora 默认(GitHub,本地)",
version: "local",
description:
"从本机 Typora 安装导入,仅供当前设备个人使用,不进入 Git、容器或发布包。",
author: "Typora",
license: "本地个人使用,未随项目分发",
entry: "github.css",
domPreset: "typora",
defaultFontSize: "16px",
supportedFeatures: [
"code",
"table",
"task-list",
"footnote",
"katex",
"mermaid"
],
bundled: false
};
try {
for (const theme of typoraThemes) {
const id = `typora-${theme.key}`;
const stagingThemeRoot = join(stagingRoot, id);
const sourceCss = join(sourceThemeRoot, `${theme.key}.css`);
const sourceAssets = join(sourceThemeRoot, theme.key);
await writeFile(
join(targetRoot, "theme.json"),
`${JSON.stringify(manifest, null, 2)}\n`,
"utf8"
);
await mkdir(stagingThemeRoot, { recursive: true });
await writeFile(
join(stagingThemeRoot, "typora-base.css"),
await readFile(sourceBaseCss, "utf8"),
"utf8"
);
await writeFile(
join(stagingThemeRoot, `${theme.key}.css`),
await readFile(sourceCss, "utf8"),
"utf8"
);
if (await pathExists(sourceAssets)) {
await cp(sourceAssets, join(stagingThemeRoot, theme.key), {
recursive: true,
errorOnExist: true,
force: false
});
}
console.log(`已导入本地 Typora 主题:${targetRoot}`);
const manifest = {
manifestVersion: 1,
id,
name: theme.name,
version: typoraVersion,
description:
`从本机 Typora ${typoraVersion} 安装导入,仅供当前设备个人使用,` +
"不进入 Git、容器或发布包。",
author: "Typora",
license: "本地个人使用,未随项目分发",
base: "typora-base.css",
entry: `${theme.key}.css`,
domPreset: "typora",
defaultFontSize: "16px",
supportedFeatures: [
"code",
"table",
"task-list",
"footnote",
"katex",
"mermaid"
],
bundled: false
};
await writeFile(
join(stagingThemeRoot, "theme.json"),
`${JSON.stringify(manifest, null, 2)}\n`,
"utf8"
);
}
let currentBackupRoot;
if (existingTargets.length > 0) {
const backupStamp = new Date()
.toISOString()
.replaceAll(":", "")
.replaceAll(".", "");
currentBackupRoot = join(backupRoot, backupStamp);
await mkdir(currentBackupRoot, { recursive: true });
}
const installedThemes = [];
const backedUpThemes = [];
try {
for (const theme of typoraThemes) {
const id = `typora-${theme.key}`;
const target = join(targetRoot, id);
if (await pathExists(target)) {
const backup = join(currentBackupRoot, id);
await rename(target, backup);
backedUpThemes.push({ target, backup });
}
await rename(join(stagingRoot, id), target);
installedThemes.push(target);
}
} catch (error) {
for (const target of installedThemes.reverse()) {
await rm(target, { recursive: true, force: true });
}
for (const { target, backup } of backedUpThemes.reverse()) {
if (await pathExists(backup)) {
await rename(backup, target);
}
}
throw error;
}
console.log(`Typora 安装目录:${installRoot}`);
console.log(`Typora 版本:${typoraVersion}`);
for (const theme of typoraThemes) {
console.log(
`已导入本地主题:${join(targetRoot, `typora-${theme.key}`)}`
);
}
if (currentBackupRoot) {
console.log(`旧主题备份:${currentBackupRoot}`);
}
} finally {
await rm(stagingRoot, { recursive: true, force: true });
}