feat: 初始化ReadMD Chrome扩展项目

- 实现网页内容提取并导出为Markdown文件
- 支持自动识别和手动选择区域两种提取模式
- 使用Mozilla Readability算法提取页面主要内容
- 使用Turndown将HTML转换为Markdown
- React + Vite + TypeScript 技术栈
- 支持图片URL保留、复制到剪贴板、直接下载

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
ddshi 2026-01-23 14:36:51 +08:00
commit c158ff28bd
37 changed files with 6188 additions and 0 deletions

View File

@ -0,0 +1,12 @@
{
"permissions": {
"allow": [
"Bash(npm install)",
"Bash(npm install:*)",
"Bash(npx tailwindcss init:*)",
"Bash(npm run build)",
"Bash(git init:*)",
"Bash(git add:*)"
]
}
}

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
eslint.config.js Normal file
View File

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

8
icons/icon128.svg Normal file
View File

@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none">
<rect width="128" height="128" rx="24" fill="#22C55E"/>
<path d="M90 28H38a10 10 0 0 0-10 10v52a10 10 0 0 0 10 10h52a10 10 0 0 0 10-10V38l-26-26z" fill="white"/>
<path d="M58 38l18 18-18 18" stroke="#22C55E" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M68 56h28" stroke="#22C55E" stroke-width="4" stroke-linecap="round"/>
<path d="M68 70h28" stroke="#22C55E" stroke-width="4" stroke-linecap="round"/>
<path d="M68 84h16" stroke="#22C55E" stroke-width="4" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 605 B

5
icons/icon16.svg Normal file
View File

@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none">
<rect width="16" height="16" rx="2" fill="#22C55E"/>
<path d="M12 4H4a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6l-4-4z" fill="white"/>
<path d="M8 5.5L10.5 8 8 10.5" stroke="#22C55E" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 342 B

8
icons/icon48.svg Normal file
View File

@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none">
<rect width="48" height="48" rx="8" fill="#22C55E"/>
<path d="M34 10H14a4 4 0 0 0-4 4v20a4 4 0 0 0 4 4h20a4 4 0 0 0 4-4V14l-10-10z" fill="white"/>
<path d="M22 14l7 7-7 7" stroke="#22C55E" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M26 21h10" stroke="#22C55E" stroke-width="2" stroke-linecap="round"/>
<path d="M26 26h10" stroke="#22C55E" stroke-width="2" stroke-linecap="round"/>
<path d="M26 31h6" stroke="#22C55E" stroke-width="2" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 583 B

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/icons/icon16.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ReadMD - 网页转Markdown</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

39
manifest.json Normal file
View File

@ -0,0 +1,39 @@
{
"manifest_version": 3,
"name": "ReadMD - 网页转Markdown",
"version": "1.0.0",
"description": "将网页内容提取并导出为Markdown文件",
"permissions": [
"activeTab",
"storage",
"downloads"
],
"host_permissions": [
"<all_urls>"
],
"action": {
"default_popup": "src/popup/index.html",
"default_icon": {
"16": "icons/icon16.svg",
"48": "icons/icon48.svg",
"128": "icons/icon128.svg"
}
},
"background": {
"service_worker": "src/background/index.ts",
"type": "module"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["src/content/index.ts"],
"run_at": "document_idle"
}
],
"options_page": "src/options/index.html",
"icons": {
"16": "icons/icon16.svg",
"48": "icons/icon48.svg",
"128": "icons/icon128.svg"
}
}

4728
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "readmd",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0",
"turndown": "^7.2.2"
},
"devDependencies": {
"@crxjs/vite-plugin": "^2.3.0",
"@eslint/js": "^9.39.1",
"@mozilla/readability": "^0.6.0",
"@tailwindcss/postcss": "^4.1.18",
"@types/chrome": "^0.1.36",
"@types/node": "^24.10.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@types/turndown": "^5.0.6",
"@vitejs/plugin-react": "^5.1.1",
"autoprefixer": "^10.4.23",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.18",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
"vite": "^7.2.4"
}
}

6
postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}

1
public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

1
src/assets/react.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

39
src/background/index.ts Normal file
View File

@ -0,0 +1,39 @@
// Background Service Worker
// 处理下载等后台任务
import type { ExtractedContent } from '../types';
import { generateMarkdown } from '../utils/markdown';
import { downloadMarkdown, generateFilename } from '../utils/download';
// 监听来自popup的消息
chrome.runtime.onMessage.addListener((message: any, _sender: any, sendResponse: (response?: any) => void) => {
if (message.action === 'download') {
handleDownload(message.data)
.then(() => sendResponse({ success: true }))
.catch(error => sendResponse({ success: false, error: error?.message || 'Download failed' }));
return true; // 异步响应
}
if (message.action === 'copy') {
sendResponse({ success: false, error: 'Copy should be handled in popup' });
return false;
}
return false;
});
// 处理下载
async function handleDownload(data: { content: ExtractedContent; options: { includeTitle: boolean; includeUrl: boolean } }): Promise<void> {
const { content, options } = data;
const markdown = generateMarkdown(content, options);
const filename = generateFilename(content.title);
await downloadMarkdown(markdown, filename);
}
// 下载完成后清理
chrome.downloads.onChanged.addListener((downloadDelta: any) => {
if (downloadDelta.state && downloadDelta.state.current === 'complete') {
console.log('ReadMD: Download completed', downloadDelta.id);
}
});

172
src/content/index.ts Normal file
View File

@ -0,0 +1,172 @@
// 内容脚本 - 注入到网页中提取内容
import { Readability } from '@mozilla/readability';
import { createTurndownService } from '../utils/markdown';
import type { ChromeMessage, ContentScriptResponse, ExtractedContent } from '../types';
// 调试记录content script已加载
console.log('ReadMD: Content script loaded on', window.location.href);
// 注入高亮样式
function injectHighlightStyles(): void {
const style = document.createElement('style');
style.id = 'readmd-highlight-styles';
style.textContent = `
.readmd-highlight {
outline: 2px solid #4CAF50 !important;
background-color: rgba(76, 175, 80, 0.1) !important;
}
.readmd-selection-mode {
cursor: crosshair !important;
}
`;
document.head.appendChild(style);
}
// 使用Readability提取主要内容
function extractWithReadability(): ExtractedContent | null {
try {
const reader = new Readability(document);
const article = reader.parse();
if (!article) {
return null;
}
const turndownService = createTurndownService();
const htmlContent = article.content || '';
const markdown = turndownService.turndown(htmlContent);
return {
title: article.title || document.title || 'Untitled',
url: window.location.href,
content: htmlContent,
markdown: markdown,
excerpt: article.excerpt || ''
};
} catch (error) {
console.error('Readability extraction failed:', error);
return null;
}
}
// 提取用户选择的区域
function extractSelection(): ExtractedContent | null {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
const range = selection.getRangeAt(0);
// 获取选中的HTML
const selectedHtml = range.cloneContents();
const div = document.createElement('div');
div.appendChild(selectedHtml);
const html = div.innerHTML;
// 如果没有选中内容返回null
if (!html.trim()) {
return null;
}
const turndownService = createTurndownService();
const markdown = turndownService.turndown(html);
return {
title: document.title,
url: window.location.href,
content: html,
markdown: markdown,
excerpt: ''
};
}
// 清除高亮
function clearHighlights(): void {
const highlights = document.querySelectorAll('.readmd-highlight');
highlights.forEach(el => {
el.classList.remove('readmd-highlight');
});
}
// 高亮选中的区域
function highlightSelection(): void {
clearHighlights();
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return;
try {
const range = selection.getRangeAt(0);
range.cloneContents().querySelectorAll('*').forEach(el => {
el.classList.add('readmd-highlight');
});
} catch {
// 某些情况下可能无法高亮,忽略错误
}
}
// 处理来自popup的消息
function handleMessage(message: ChromeMessage, _sender: any, sendResponse: (response: ContentScriptResponse) => void): boolean {
switch (message.action) {
case 'extract':
// 自动提取页面主要内容
const content = extractWithReadability();
if (content) {
sendResponse({ success: true, data: content });
} else {
sendResponse({ success: false, error: '无法提取页面内容' });
}
break;
case 'extractSelection':
// 提取用户选择的区域
const selectionContent = extractSelection();
if (selectionContent) {
sendResponse({ success: true, data: selectionContent });
} else {
sendResponse({ success: false, error: '请先选择要提取的内容' });
}
break;
case 'preview':
// 高亮选中的区域
highlightSelection();
const previewContent = extractSelection();
sendResponse({
success: !!previewContent,
data: previewContent || undefined,
error: previewContent ? undefined : '请先选择要预览的内容'
});
break;
default:
sendResponse({ success: false, error: '未知操作' });
}
// 返回true表示异步响应
return true;
}
// 初始化
function init(): void {
injectHighlightStyles();
// 监听来自popup/background的消息
chrome.runtime.onMessage.addListener(handleMessage);
console.log('ReadMD: Content script initialized');
}
// 页面加载完成后初始化
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
// 导出onExecute供loader使用
export function onExecute(): void {
console.log('ReadMD: onExecute called');
}

10
src/content/styles.css Normal file
View File

@ -0,0 +1,10 @@
/* Content Script Styles */
.readmd-highlight {
outline: 2px solid #4CAF50 !important;
background-color: rgba(76, 175, 80, 0.1) !important;
}
.readmd-selection-mode {
cursor: crosshair !important;
}

View File

@ -0,0 +1,48 @@
import { useState, useEffect, useCallback } from 'react';
import type { UserSettings } from '../types';
// 默认设置
const defaultSettings: UserSettings = {
includeTitle: true,
includeUrl: true,
simplifyMode: false,
imageMode: 'url'
};
// 从chrome.storage读取设置
export function useChromeStorage() {
const [settings, setSettings] = useState<UserSettings>(defaultSettings);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
// 加载设置
const loadSettings = useCallback(async () => {
try {
const result = await chrome.storage.sync.get('readmdSettings');
if (result.readmdSettings) {
setSettings({ ...defaultSettings, ...result.readmdSettings });
}
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
}, []);
// 保存设置
const saveSettings = useCallback(async (newSettings: Partial<UserSettings>) => {
try {
const updatedSettings = { ...settings, ...newSettings };
await chrome.storage.sync.set({ readmdSettings: updatedSettings });
setSettings(updatedSettings);
} catch (err) {
setError(err as Error);
}
}, [settings]);
useEffect(() => {
loadSettings();
}, [loadSettings]);
return { settings, saveSettings, loading, error, reload: loadSettings };
}

13
src/index.css Normal file
View File

@ -0,0 +1,13 @@
@import "tailwindcss";
/* Chrome扩展Popup专用样式 */
html {
width: 320px;
height: auto;
}
body {
margin: 0;
padding: 0;
width: 320px;
}

23
src/main.tsx Normal file
View File

@ -0,0 +1,23 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import { Popup } from './popup/Popup'
// Chrome扩展环境
const rootElement = document.getElementById('root');
// 如果存在root元素普通开发环境正常渲染
if (rootElement) {
createRoot(rootElement).render(
<StrictMode>
<Popup />
</StrictMode>,
)
} else {
// Chrome扩展环境直接渲染到document body
createRoot(document.body).render(
<StrictMode>
<Popup />
</StrictMode>,
)
}

View File

@ -0,0 +1,8 @@
import { createRoot } from 'react-dom/client';
import { OptionsPage } from './OptionsPageComponent';
// 创建根节点并渲染
const rootElement = document.getElementById('root');
if (rootElement) {
createRoot(rootElement).render(<OptionsPage />);
}

View File

@ -0,0 +1,122 @@
import { useChromeStorage } from '../hooks/useChromeStorage';
import type { UserSettings } from '../types';
export function OptionsPage() {
const { settings, saveSettings, loading } = useChromeStorage();
if (loading) {
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-8 px-4">
<div className="max-w-md mx-auto">
{/* 标题 */}
<div className="flex items-center gap-3 mb-8">
<svg className="w-10 h-10 text-green-500" viewBox="0 0 24 24" fill="currentColor">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z"/>
<path d="M8 12h8v2H8zm0 4h8v2H8z"/>
</svg>
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">ReadMD </h1>
<p className="text-sm text-gray-500 dark:text-gray-400"></p>
</div>
</div>
{/* 设置卡片 */}
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 space-y-6">
{/* 导出选项 */}
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4"></h2>
<div className="space-y-3">
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={settings.includeTitle}
onChange={(e) => saveSettings({ includeTitle: e.target.checked })}
className="w-5 h-5 text-blue-500 rounded focus:ring-blue-500"
/>
<div>
<div className="text-sm font-medium text-gray-900 dark:text-white"></div>
<div className="text-xs text-gray-500 dark:text-gray-400">Markdown中包含页面标题</div>
</div>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={settings.includeUrl}
onChange={(e) => saveSettings({ includeUrl: e.target.checked })}
className="w-5 h-5 text-blue-500 rounded focus:ring-blue-500"
/>
<div>
<div className="text-sm font-medium text-gray-900 dark:text-white"></div>
<div className="text-xs text-gray-500 dark:text-gray-400"></div>
</div>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={settings.simplifyMode}
onChange={(e) => saveSettings({ simplifyMode: e.target.checked })}
className="w-5 h-5 text-blue-500 rounded focus:ring-blue-500"
/>
<div>
<div className="text-sm font-medium text-gray-900 dark:text-white"></div>
<div className="text-xs text-gray-500 dark:text-gray-400">广</div>
</div>
</label>
</div>
</div>
{/* 图片处理 */}
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4"></h2>
<div className="space-y-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
</label>
<select
value={settings.imageMode}
onChange={(e) => saveSettings({ imageMode: e.target.value as UserSettings['imageMode'] })}
className="w-full py-2.5 px-3 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="url">URL链接</option>
<option value="base64">Base64内嵌线</option>
<option value="download"></option>
</select>
<p className="text-xs text-gray-500 dark:text-gray-400">
{settings.imageMode === 'url' && '图片保持原始链接,文件体积小,需要网络连接'}
{settings.imageMode === 'base64' && '图片转为Base64编码可离线查看文件体积较大'}
{settings.imageMode === 'download' && '图片会下载到指定文件夹MD中引用相对路径'}
</p>
</div>
</div>
</div>
{/* 快捷键信息 */}
<div className="mt-6 bg-blue-50 dark:bg-blue-900/20 rounded-xl p-4">
<h3 className="text-sm font-semibold text-blue-900 dark:text-blue-300 mb-2">使</h3>
<ul className="text-xs text-blue-700 dark:text-blue-400 space-y-1">
<li></li>
<li>"自动提取"</li>
<li>"选择区域"</li>
<li>Markdown文件</li>
</ul>
</div>
{/* 版本信息 */}
<div className="mt-6 text-center text-xs text-gray-400 dark:text-gray-500">
ReadMD v1.0.0
</div>
</div>
</div>
);
}

13
src/options/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/icons/icon16.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ReadMD 设置</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./OptionsPage.tsx"></script>
</body>
</html>

207
src/popup/Popup.tsx Normal file
View File

@ -0,0 +1,207 @@
import { useState } from 'react';
import { ExtractButton } from './components/ExtractButton';
import { OptionsPanel } from './components/OptionsPanel';
import { PreviewModal } from './components/PreviewModal';
import { useChromeStorage } from '../hooks/useChromeStorage';
import { copyToClipboard } from '../utils/download';
import type { ExtractedContent } from '../types';
// 状态消息类型
type StatusType = 'idle' | 'loading' | 'success' | 'error';
export function Popup() {
const { settings, saveSettings, loading: settingsLoading } = useChromeStorage();
const [extractedContent, setExtractedContent] = useState<ExtractedContent | null>(null);
const [status, setStatus] = useState<{ type: StatusType; message: string }>({ type: 'idle', message: '' });
const [showPreview, setShowPreview] = useState(false);
const [mode, setMode] = useState<'auto' | 'selection'>('auto');
// 显示状态消息
const showStatus = (type: StatusType, message: string) => {
setStatus({ type, message });
if (type !== 'loading') {
setTimeout(() => setStatus({ type: 'idle', message: '' }), 3000);
}
};
// 获取当前标签页
const getCurrentTab = async (): Promise<any> => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab) throw new Error('无法获取当前标签页');
return tab;
};
// 提取内容
const handleExtract = async () => {
try {
showStatus('loading', mode === 'selection' ? '请在页面上选择内容...' : '正在提取内容...');
const tab = await getCurrentTab();
if (!tab.id) throw new Error('标签页无效');
// 发送消息给content script
const response = await chrome.tabs.sendMessage(tab.id, {
action: mode === 'selection' ? 'extractSelection' : 'extract'
});
if (response.success && response.data) {
setExtractedContent(response.data);
setShowPreview(true);
showStatus('success', '提取成功!');
} else {
showStatus('error', response.error || '提取失败');
}
} catch (error) {
console.error('提取失败:', error);
showStatus('error', error instanceof Error ? error.message : '提取失败');
}
};
// 复制到剪贴板
const handleCopy = async () => {
if (!extractedContent) return;
try {
const markdown = generateMarkdown(extractedContent, {
includeTitle: settings.includeTitle,
includeUrl: settings.includeUrl
});
await copyToClipboard(markdown);
showStatus('success', '已复制到剪贴板!');
} catch {
showStatus('error', '复制失败');
}
};
// 下载文件
const handleDownload = async () => {
if (!extractedContent) return;
try {
const markdown = generateMarkdown(extractedContent, {
includeTitle: settings.includeTitle,
includeUrl: settings.includeUrl
});
const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' });
const url = URL.createObjectURL(blob);
// 使用chrome.downloads API
const filename = `${extractedContent.title.replace(/[<>:"/\\|?*]/g, '_').substring(0, 100)}.md`;
await chrome.downloads.download({
url: url,
filename: filename,
saveAs: false
});
URL.revokeObjectURL(url);
showStatus('success', '下载完成!');
} catch {
showStatus('error', '下载失败');
}
};
// 生成Markdown
const generateMarkdown = (content: ExtractedContent, options: { includeTitle: boolean; includeUrl: boolean }): string => {
let md = '';
// Frontmatter
md += '---\n';
if (options.includeTitle) {
md += `title: "${content.title.replace(/"/g, '\\"')}"\n`;
}
if (options.includeUrl) {
md += `source: ${content.url}\n`;
}
md += '---\n\n';
// 标题
if (options.includeTitle) {
md += `# ${content.title}\n\n`;
}
// 原文链接
if (options.includeUrl) {
md += `> 原文链接: [${content.title}](${content.url})\n\n`;
}
// 内容
md += content.markdown;
return md;
};
if (settingsLoading) {
return (
<div className="w-80 p-4 flex items-center justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
</div>
);
}
return (
<div className="w-80 p-4 bg-white dark:bg-gray-900">
{/* 标题 */}
<div className="flex items-center gap-2 mb-4">
<svg className="w-8 h-8 text-green-500" viewBox="0 0 24 24" fill="currentColor">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2l5 5h-5V4zM6 20V4h6v6h6v10H6z"/>
<path d="M8 12h8v2H8zm0 4h8v2H8z"/>
</svg>
<h1 className="text-xl font-bold text-gray-900 dark:text-white">ReadMD</h1>
</div>
{/* 提取按钮 */}
<ExtractButton
loading={status.type === 'loading'}
onExtract={handleExtract}
mode={mode}
onModeChange={setMode}
/>
{/* 状态消息 */}
{status.message && (
<div className={`mt-3 p-2 rounded-lg text-sm ${
status.type === 'success' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400' :
status.type === 'error' ? 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400' :
status.type === 'loading' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400' :
'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300'
}`}>
{status.message}
</div>
)}
{/* 分隔线 */}
<hr className="my-4 border-gray-200 dark:border-gray-700" />
{/* 选项面板 */}
<OptionsPanel
settings={settings}
onSettingsChange={saveSettings}
/>
{/* 预览弹窗 */}
{showPreview && extractedContent && (
<PreviewModal
content={extractedContent}
onClose={() => setShowPreview(false)}
onCopy={handleCopy}
onDownload={handleDownload}
/>
)}
{/* 页脚 */}
<div className="mt-4 text-center text-xs text-gray-500 dark:text-gray-400">
<a
href="#"
onClick={(e) => {
e.preventDefault();
chrome.runtime.openOptionsPage();
}}
className="hover:text-gray-700 dark:hover:text-gray-200"
>
</a>
</div>
</div>
);
}

View File

@ -0,0 +1,59 @@
interface ExtractButtonProps {
loading: boolean;
onExtract: () => void;
mode: 'auto' | 'selection';
onModeChange: (mode: 'auto' | 'selection') => void;
}
export function ExtractButton({ loading, onExtract, mode, onModeChange }: ExtractButtonProps) {
return (
<div className="space-y-3">
{/* 提取模式切换 */}
<div className="flex gap-2 p-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
<button
onClick={() => onModeChange('auto')}
className={`flex-1 py-2 px-3 text-sm rounded-md transition-colors ${
mode === 'auto'
? 'bg-blue-500 text-white'
: 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
}`}
>
</button>
<button
onClick={() => onModeChange('selection')}
className={`flex-1 py-2 px-3 text-sm rounded-md transition-colors ${
mode === 'selection'
? 'bg-blue-500 text-white'
: 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
}`}
>
</button>
</div>
{/* 主提取按钮 */}
<button
onClick={onExtract}
disabled={loading}
className={`w-full py-3 px-4 rounded-lg font-medium text-white transition-all ${
loading
? 'bg-gray-400 cursor-not-allowed'
: 'bg-green-500 hover:bg-green-600 active:scale-95'
}`}
>
{loading ? (
<span className="flex items-center justify-center gap-2">
<svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
...
</span>
) : (
'提取并导出Markdown'
)}
</button>
</div>
);
}

View File

@ -0,0 +1,59 @@
import type { UserSettings } from '../../types';
interface OptionsPanelProps {
settings: UserSettings;
onSettingsChange: (settings: Partial<UserSettings>) => void;
}
export function OptionsPanel({ settings, onSettingsChange }: OptionsPanelProps) {
return (
<div className="space-y-3">
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300"></h4>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={settings.includeTitle}
onChange={(e) => onSettingsChange({ includeTitle: e.target.checked })}
className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
/>
<span className="text-sm text-gray-700 dark:text-gray-300"></span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={settings.includeUrl}
onChange={(e) => onSettingsChange({ includeUrl: e.target.checked })}
className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
/>
<span className="text-sm text-gray-700 dark:text-gray-300"></span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={settings.simplifyMode}
onChange={(e) => onSettingsChange({ simplifyMode: e.target.checked })}
className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
/>
<span className="text-sm text-gray-700 dark:text-gray-300">广</span>
</label>
<div className="pt-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
</label>
<select
value={settings.imageMode}
onChange={(e) => onSettingsChange({ imageMode: e.target.value as UserSettings['imageMode'] })}
className="w-full py-2 px-3 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<option value="url">URL链接</option>
<option value="base64">Base64</option>
<option value="download"></option>
</select>
</div>
</div>
);
}

View File

@ -0,0 +1,94 @@
import { useState } from 'react';
import type { ExtractedContent } from '../../types';
import { generateMarkdown } from '../../utils/markdown';
interface PreviewModalProps {
content: ExtractedContent | null;
onClose: () => void;
onCopy: () => void;
onDownload: () => void;
}
export function PreviewModal({ content, onClose, onCopy, onDownload }: PreviewModalProps) {
const [showRaw, setShowRaw] = useState(false);
if (!content) return null;
const markdown = generateMarkdown(content, {
includeTitle: true,
includeUrl: true
});
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-900 rounded-xl shadow-2xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col">
{/* 标题栏 */}
<div className="flex items-center justify-between p-4 border-b dark:border-gray-700">
<h3 className="font-semibold text-gray-900 dark:text-white"></h3>
<button
onClick={onClose}
className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* 内容预览 */}
<div className="flex-1 overflow-auto p-4">
<div className="text-sm text-gray-600 dark:text-gray-400 mb-2">{content.title}</div>
{/* 切换按钮 */}
<div className="flex gap-2 mb-3">
<button
onClick={() => setShowRaw(false)}
className={`px-3 py-1 text-xs rounded ${!showRaw ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700'}`}
>
</button>
<button
onClick={() => setShowRaw(true)}
className={`px-3 py-1 text-xs rounded ${showRaw ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700'}`}
>
Markdown
</button>
</div>
{showRaw ? (
<pre className="text-xs bg-gray-100 dark:bg-gray-800 p-3 rounded overflow-auto max-h-64 whitespace-pre-wrap">
{markdown}
</pre>
) : (
<div
className="prose prose-sm max-w-none dark:prose-invert overflow-auto max-h-64"
dangerouslySetInnerHTML={{
__html: content.markdown
.replace(/^# .+$/m, '') // 移除标题
.replace(/> .+$/gm, '') // 移除引用
.replace(/```[\s\S]*?```/g, '[代码块]') // 简化代码块
.replace(/\n/g, '<br/>') // 换行
}}
/>
)}
</div>
{/* 操作按钮 */}
<div className="p-4 border-t dark:border-gray-700 flex gap-2">
<button
onClick={onCopy}
className="flex-1 py-2 px-4 bg-blue-500 hover:bg-blue-600 text-white rounded-lg text-sm font-medium transition-colors"
>
</button>
<button
onClick={onDownload}
className="flex-1 py-2 px-4 bg-green-500 hover:bg-green-600 text-white rounded-lg text-sm font-medium transition-colors"
>
MD文件
</button>
</div>
</div>
</div>
);
}

13
src/popup/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/icons/icon16.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ReadMD</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="../main.tsx"></script>
</body>
</html>

61
src/types/chrome.d.ts vendored Normal file
View File

@ -0,0 +1,61 @@
// Chrome扩展API类型声明
declare const chrome: {
tabs: {
query: (options: { active?: boolean; currentWindow?: boolean }) => Promise<Array<{ id?: number; title?: string; url?: string }>>;
sendMessage: (tabId: number, message: any) => Promise<any>;
};
runtime: {
onMessage: {
addListener: (callback: (message: any, sender: any, sendResponse: (response?: any) => void) => boolean | void) => void;
};
openOptionsPage: () => Promise<void>;
};
downloads: {
download: (options: { url: string; filename?: string; saveAs?: boolean }) => Promise<number>;
onChanged: {
addListener: (callback: (downloadDelta: any) => void) => void;
};
};
storage: {
sync: {
get: (keys?: string | string[] | object) => Promise<any>;
set: (items: object) => Promise<void>;
};
local: {
get: (keys?: string | string[] | object) => Promise<any>;
set: (items: object) => Promise<void>;
};
};
};
// 声明 TurndownService
declare class TurndownService {
constructor(options?: {
headingStyle?: 'atx' | 'setext';
codeBlockStyle?: 'fenced' | 'indented';
bulletListMarker?: '-' | '*' | '+';
emDelimiter?: '*' | '_';
strongDelimiter?: '**' | '__';
linkStyle?: 'inlined' | 'referenced';
preformattedCode?: boolean;
});
turndown(html: string): string;
addRule(key: string, rule: {
filter: string | string[] | ((node: any) => boolean);
replacement: (content: string, node: any) => string;
}): void;
}
// 声明 Readability
declare class Readability {
constructor(doc: Document);
parse(): {
title: string;
content: string;
textContent: string;
length: number;
excerpt: string;
byline: string;
dir: string;
} | null;
}

36
src/types/index.ts Normal file
View File

@ -0,0 +1,36 @@
// 提取的内容元数据
export interface ExtractedContent {
title: string;
url: string;
content: string;
markdown: string;
excerpt?: string;
}
// 提取选项
export interface ExtractOptions {
includeTitle: boolean;
includeUrl: boolean;
simplifyMode: boolean;
}
// 用户设置
export interface UserSettings {
includeTitle: boolean;
includeUrl: boolean;
simplifyMode: boolean;
imageMode: 'url' | 'base64' | 'download';
}
// Chrome消息类型
export interface ChromeMessage {
action: 'extract' | 'extractSelection' | 'preview' | 'copy' | 'download';
options?: ExtractOptions;
}
// 内容脚本响应
export interface ContentScriptResponse {
success: boolean;
data?: ExtractedContent;
error?: string;
}

36
src/utils/download.ts Normal file
View File

@ -0,0 +1,36 @@
// 下载Markdown文件
export async function downloadMarkdown(content: string, filename: string): Promise<void> {
const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
const url = URL.createObjectURL(blob);
try {
// 使用浏览器原生的下载功能
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} finally {
URL.revokeObjectURL(url);
}
}
// 复制到剪贴板
export async function copyToClipboard(text: string): Promise<void> {
await navigator.clipboard.writeText(text);
}
// 生成安全的文件名
export function sanitizeFilename(title: string): string {
return title
.replace(/[<>:"/\\|?*]/g, '_') // 替换非法字符
.replace(/[\s\n\r]+/g, ' ') // 替换空白字符
.trim()
.substring(0, 100); // 限制长度
}
// 生成Markdown文件名
export function generateFilename(title: string): string {
return `${sanitizeFilename(title)}.md`;
}

103
src/utils/markdown.ts Normal file
View File

@ -0,0 +1,103 @@
import TurndownService from 'turndown';
import type { ExtractedContent } from '../types';
// 创建Turndown服务实例
export function createTurndownService(): TurndownService {
const service = new TurndownService({
headingStyle: 'atx', // ATX风格标题 (# ## ###)
codeBlockStyle: 'fenced', // 代码块使用 fenced (```)
bulletListMarker: '-', // 无序列表使用 -
emDelimiter: '*', // 斜体使用 *
strongDelimiter: '**', // 粗体使用 **
linkStyle: 'inlined', // 链接内联样式
preformattedCode: true, // 保留代码格式
});
// 自定义规则:处理图片
service.addRule('image', {
filter: 'img',
replacement: function(_content, node) {
const img = node as HTMLImageElement;
const alt = img.alt || '';
const src = img.src || '';
return `\n![${alt}](${src})\n`;
}
});
// 自定义规则:处理代码块
service.addRule('code', {
filter: function(node) {
return (
node.nodeName === 'CODE' &&
node.parentElement?.nodeName !== 'PRE'
);
},
replacement: function(content) {
return '`' + content + '`';
}
});
// 自定义规则处理pre标签
service.addRule('pre', {
filter: 'pre',
replacement: function(content) {
return '\n```\n' + content + '\n```\n';
}
});
// 自定义规则:处理表格
service.addRule('tables', {
filter: 'table',
replacement: function(content) {
// 简单的表格转换
return '\n' + content + '\n';
}
});
// 自定义规则:处理引用
service.addRule('blockquote', {
filter: 'blockquote',
replacement: function(content) {
return '\n> ' + content.trim().split('\n').join('\n> ') + '\n';
}
});
return service;
}
// 生成带Frontmatter的Markdown
export function generateMarkdown(content: ExtractedContent, options: { includeTitle: boolean; includeUrl: boolean }): string {
let md = '';
// Frontmatter
md += '---\n';
if (options.includeTitle) {
md += `title: "${content.title.replace(/"/g, '\\"')}"\n`;
}
if (options.includeUrl) {
md += `source: ${content.url}\n`;
}
md += '---\n\n';
// 标题
if (options.includeTitle) {
md += `# ${content.title}\n\n`;
}
// 原文链接
if (options.includeUrl) {
md += `> 原文链接: [${content.title}](${content.url})\n\n`;
}
// 内容
md += content.markdown;
return md;
}
// 从HTML提取纯文本用于excerpt
export function extractExcerpt(html: string, maxLength: number = 200): string {
const text = html.replace(/<[^>]*>/g, '').trim();
if (text.length <= maxLength) return text;
return text.substring(0, maxLength).trim() + '...';
}

11
tailwind.config.js Normal file
View File

@ -0,0 +1,11 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

28
tsconfig.app.json Normal file
View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

26
tsconfig.node.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

20
vite.config.ts Normal file
View File

@ -0,0 +1,20 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { chromeExtension } from '@crxjs/vite-plugin'
import manifest from './manifest.json'
// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
chromeExtension({ manifest }),
],
build: {
outDir: 'dist',
rollupOptions: {
input: {
main: 'index.html',
},
},
},
})