This commit is contained in:
zhu
2026-04-30 11:03:26 +08:00
parent 48ce6a8b0b
commit 08a6a69bd6
9 changed files with 566 additions and 42 deletions

View File

@@ -1,4 +1,8 @@
import type { BackgroundCommand } from './types';
import { getPlatformById } from '@/config/platforms';
import type { CrawlProgressStep, CrawlTaskState } from '@/types';
import type { BackgroundCommand, BackgroundResponse, CrawlStateResponse } from './types';
const CRAWL_TASK_STORAGE_KEY = 'crawlTaskState';
export async function handleInstalled(): Promise<void> {
console.log('[background] installed');
@@ -10,9 +14,148 @@ export async function handleStartup(): Promise<void> {
export async function handleWindowRemoved(windowId: number): Promise<void> {
console.log('[background] window removed', windowId);
const state = await getCrawlTaskState();
if (state?.windowId === windowId && state.status === 'running') {
await setCrawlTaskState({
...state,
status: 'canceled',
steps: state.steps.map((step, index) =>
index === state.currentStepIndex ? { ...step, status: 'failed', message: '爬取窗口已关闭' } : step,
),
});
}
}
export async function handleBackgroundCommand(message: BackgroundCommand): Promise<unknown> {
console.log('[background] message', message);
return { ok: true };
export async function handleBackgroundCommand(
message: BackgroundCommand,
): Promise<BackgroundResponse | CrawlStateResponse> {
switch (message.action) {
case 'START_CRAWL':
return startCrawl(message.payload.platformId);
case 'GET_CRAWL_STATE':
return { ok: true, data: await getCrawlTaskState() };
case 'CANCEL_CRAWL':
return cancelCrawl();
default:
return { ok: false, error: '未知的后台指令' };
}
}
async function startCrawl(platformId: string): Promise<CrawlStateResponse> {
const platform = getPlatformById(platformId);
if (!platform) {
return { ok: false, error: '平台配置不存在' };
}
const startedAt = Date.now();
const nextState: CrawlTaskState = {
id: `${platform.id}-${startedAt}`,
platformId: platform.id,
platformName: platform.name,
startedAt,
status: 'running',
currentStepIndex: 0,
steps: platform.steps.map<CrawlProgressStep>((step, index) => ({
name: step.name,
uniqueKey: step.uniqueKey,
status: index === 0 ? 'running' : 'pending',
})),
};
await setCrawlTaskState(nextState);
try {
const windowInfo = await createCrawlWindow(platform.baseUrl);
const stateWithWindow = { ...nextState, windowId: windowInfo.id };
await setCrawlTaskState(stateWithWindow);
return { ok: true, data: stateWithWindow };
} catch (error: unknown) {
const failedState: CrawlTaskState = {
...nextState,
status: 'failed',
steps: nextState.steps.map((step, index) =>
index === 0 ? { ...step, status: 'failed', message: '打开平台窗口失败' } : step,
),
};
await setCrawlTaskState(failedState);
return { ok: false, data: failedState, error: error instanceof Error ? error.message : '打开平台窗口失败' };
}
}
async function cancelCrawl(): Promise<CrawlStateResponse> {
const state = await getCrawlTaskState();
if (!state) {
return { ok: true, data: null };
}
const canceledState: CrawlTaskState = {
...state,
status: 'canceled',
steps: state.steps.map((step, index) =>
index === state.currentStepIndex ? { ...step, status: 'failed', message: '用户已取消' } : step,
),
};
await setCrawlTaskState(canceledState);
if (state.windowId) {
await removeWindow(state.windowId);
}
return { ok: true, data: canceledState };
}
async function getCrawlTaskState(): Promise<CrawlTaskState | null> {
const result = await chrome.storage.local.get(CRAWL_TASK_STORAGE_KEY);
const state = result[CRAWL_TASK_STORAGE_KEY];
return isCrawlTaskState(state) ? state : null;
}
async function setCrawlTaskState(state: CrawlTaskState): Promise<void> {
await chrome.storage.local.set({ [CRAWL_TASK_STORAGE_KEY]: state });
}
function createCrawlWindow(url: string): Promise<chrome.windows.Window> {
return new Promise((resolve, reject) => {
chrome.windows.create(
{
url,
type: 'normal',
focused: true,
width: 1280,
height: 900,
},
(windowInfo) => {
const runtimeError = chrome.runtime.lastError;
if (runtimeError) {
reject(new Error(runtimeError.message));
return;
}
if (!windowInfo?.id) {
reject(new Error('窗口创建失败'));
return;
}
resolve(windowInfo);
},
);
});
}
function removeWindow(windowId: number): Promise<void> {
return new Promise((resolve) => {
chrome.windows.remove(windowId, () => {
resolve();
});
});
}
function isCrawlTaskState(value: unknown): value is CrawlTaskState {
return typeof value === 'object' && value !== null && 'id' in value && 'steps' in value;
}

View File

@@ -1,4 +1,26 @@
export interface BackgroundCommand {
action: string;
payload?: unknown;
import type { CrawlTaskState } from '@/types';
export interface StartCrawlCommand {
action: 'START_CRAWL';
payload: {
platformId: string;
};
}
export interface GetCrawlStateCommand {
action: 'GET_CRAWL_STATE';
}
export interface CancelCrawlCommand {
action: 'CANCEL_CRAWL';
}
export type BackgroundCommand = StartCrawlCommand | GetCrawlStateCommand | CancelCrawlCommand;
export interface BackgroundResponse<T = unknown> {
ok: boolean;
data?: T;
error?: string;
}
export type CrawlStateResponse = BackgroundResponse<CrawlTaskState | null>;

View File

@@ -1,5 +1,219 @@
<script setup lang="ts"></script>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import type { CrawlTaskState } from '@/types';
<template></template>
const crawlState = ref<CrawlTaskState | null>(null);
const elapsedSeconds = ref(0);
const isPanelOpen = ref(false);
let timer: number | undefined;
<style lang="scss"></style>
const isVisible = computed(() => crawlState.value?.status === 'running');
onMounted(() => {
void refreshCrawlState();
timer = window.setInterval(() => {
updateElapsedSeconds();
void refreshCrawlState();
}, 1000);
});
onUnmounted(() => {
if (timer) {
window.clearInterval(timer);
}
});
async function refreshCrawlState() {
const response = await sendBackgroundMessage<CrawlTaskState | null>({ action: 'GET_CRAWL_STATE' });
if (response.ok) {
crawlState.value = response.data ?? null;
updateElapsedSeconds();
if (!isVisible.value) {
isPanelOpen.value = false;
}
}
}
function updateElapsedSeconds() {
if (!crawlState.value) {
elapsedSeconds.value = 0;
return;
}
elapsedSeconds.value = Math.max(0, Math.floor((Date.now() - crawlState.value.startedAt) / 1000));
}
function formatElapsed(totalSeconds: number): string {
const minutes = Math.floor(totalSeconds / 60).toString().padStart(2, '0');
const seconds = (totalSeconds % 60).toString().padStart(2, '0');
return `${minutes}:${seconds}`;
}
function getStepText(status: string): string {
const textMap: Record<string, string> = {
pending: '等待中',
running: '爬取中',
success: '已完成',
failed: '爬取失败',
};
return textMap[status] ?? status;
}
function sendBackgroundMessage<T>(message: unknown): Promise<{ ok: boolean; data?: T; error?: string }> {
if (typeof chrome === 'undefined' || !chrome.runtime?.sendMessage) {
return Promise.resolve({ ok: true, data: null as T });
}
return chrome.runtime.sendMessage(message);
}
</script>
<template>
<div v-if="isVisible && crawlState" class="dianshan-crawl-widget">
<button class="dianshan-crawl-button" type="button" @click="isPanelOpen = !isPanelOpen">
{{ formatElapsed(elapsedSeconds) }}
</button>
<section v-if="isPanelOpen" class="dianshan-crawl-panel">
<header class="dianshan-crawl-header">
<div>
<p>{{ crawlState.platformName }}</p>
<span>已运行 {{ formatElapsed(elapsedSeconds) }}</span>
</div>
</header>
<ol class="dianshan-crawl-timeline">
<li v-for="(step, index) in crawlState.steps" :key="step.uniqueKey" :class="`is-${step.status}`">
<span class="dianshan-crawl-dot"></span>
<div class="dianshan-crawl-step">
<strong>{{ index + 1 }}. {{ step.name }}</strong>
<em>{{ getStepText(step.status) }}</em>
<small v-if="step.message">{{ step.message }}</small>
</div>
</li>
</ol>
</section>
</div>
</template>
<style scoped>
.dianshan-crawl-widget {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 2147483647;
font-family: "Microsoft YaHei", "PingFang SC", Arial, sans-serif;
}
.dianshan-crawl-button {
width: 64px;
height: 64px;
border: 0;
border-radius: 50%;
color: #ffffff;
background: #059669;
box-shadow: 0 12px 30px rgba(15, 23, 42, 0.28);
cursor: pointer;
font-size: 14px;
font-weight: 700;
}
.dianshan-crawl-panel {
position: absolute;
right: 0;
bottom: 76px;
width: 300px;
padding: 16px;
border: 1px solid #dbe3ea;
border-radius: 8px;
color: #172033;
background: #ffffff;
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.2);
}
.dianshan-crawl-header {
margin-bottom: 14px;
}
.dianshan-crawl-header p {
margin: 0 0 4px;
font-size: 15px;
font-weight: 700;
}
.dianshan-crawl-header span {
color: #64748b;
font-size: 12px;
}
.dianshan-crawl-timeline {
display: grid;
gap: 12px;
margin: 0;
padding: 0;
list-style: none;
}
.dianshan-crawl-timeline li {
position: relative;
padding-left: 18px;
border-left: 2px solid #dbe3ea;
}
.dianshan-crawl-dot {
position: absolute;
top: 8px;
left: -7px;
width: 12px;
height: 12px;
border: 2px solid #ffffff;
border-radius: 50%;
background: #cbd5e1;
}
.dianshan-crawl-step {
display: grid;
gap: 4px;
padding: 10px;
border: 1px solid #dbe3ea;
border-radius: 8px;
background: #ffffff;
}
.dianshan-crawl-step strong {
font-size: 13px;
}
.dianshan-crawl-step em {
color: #64748b;
font-size: 12px;
font-style: normal;
}
.dianshan-crawl-step small {
color: #b91c1c;
}
.is-running .dianshan-crawl-dot,
.is-success .dianshan-crawl-dot {
background: #10b981;
}
.is-running .dianshan-crawl-step,
.is-success .dianshan-crawl-step {
border-color: #10b981;
background: #ecfdf5;
}
.is-failed .dianshan-crawl-dot {
background: #ef4444;
}
.is-failed .dianshan-crawl-step {
border-color: #ef4444;
background: #fef2f2;
}
</style>

View File

@@ -1,7 +1,7 @@
import { createApp } from 'vue';
import App from './App.vue';
/** 将内容脚本应用挂载到页面的 Shadow DOM 中。 */
/** 将内容脚本应用挂载到页面中。 */
function mountApp() {
if (document.getElementById('dianshan-crx-root')) {
return;
@@ -9,11 +9,10 @@ function mountApp() {
const container = document.createElement('div');
container.id = 'dianshan-crx-root';
const shadowRoot = container.attachShadow({ mode: 'open' });
const appRoot = document.createElement('div');
shadowRoot.appendChild(appRoot);
document.documentElement.appendChild(container);
container.appendChild(appRoot);
document.body.appendChild(container);
createApp(App).mount(appRoot);
}

View File

@@ -1,13 +1,17 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { PLATFORM_CONFIGS } from '@/config/platforms';
import { getToken, logout, mockLogin } from '@/shared/auth';
import type { CrawlTaskState } from '@/types';
const token = ref<string | null>(null);
const selectedPlatformId = ref(PLATFORM_CONFIGS[0]?.id ?? '');
const isLoading = ref(true);
const isScanning = ref(false);
const errorMessage = ref('');
const crawlState = ref<CrawlTaskState | null>(null);
const elapsedSeconds = ref(0);
let timer: number | undefined;
const manifest = getRuntimeManifest();
const extensionName = manifest?.name ?? '店闪';
@@ -20,12 +24,24 @@ const selectedPlatform = computed(() =>
);
const isLoggedIn = computed(() => token.value !== null);
const isCrawling = computed(() => crawlState.value?.status === 'running');
onMounted(async () => {
token.value = await getToken();
await refreshCrawlState();
timer = window.setInterval(() => {
updateElapsedSeconds();
void refreshCrawlState();
}, 1000);
isLoading.value = false;
});
onUnmounted(() => {
if (timer) {
window.clearInterval(timer);
}
});
async function handleLogin() {
errorMessage.value = '';
token.value = await mockLogin();
@@ -48,7 +64,18 @@ async function handleScan() {
isScanning.value = true;
try {
await openPlatformWindow(selectedPlatform.value.baseUrl);
const response = await sendBackgroundMessage<CrawlTaskState>({
action: 'START_CRAWL',
payload: { platformId: selectedPlatform.value.id },
});
if (!response.ok) {
errorMessage.value = response.error ?? '打开平台窗口失败';
return;
}
crawlState.value = response.data ?? null;
updateElapsedSeconds();
} catch (error: unknown) {
errorMessage.value = error instanceof Error ? error.message : '打开平台窗口失败';
} finally {
@@ -56,33 +83,68 @@ async function handleScan() {
}
}
function openPlatformWindow(url: string): Promise<void> {
if (typeof chrome === 'undefined' || !chrome.windows?.create) {
window.open(url, '_blank', 'width=1280,height=900');
return Promise.resolve();
async function handleCancelCrawl() {
const response = await sendBackgroundMessage<CrawlTaskState>({ action: 'CANCEL_CRAWL' });
crawlState.value = response.data ?? null;
}
async function refreshCrawlState() {
const response = await sendBackgroundMessage<CrawlTaskState | null>({ action: 'GET_CRAWL_STATE' });
if (response.ok) {
crawlState.value = response.data ?? null;
updateElapsedSeconds();
}
}
function updateElapsedSeconds() {
if (!crawlState.value) {
elapsedSeconds.value = 0;
return;
}
return new Promise((resolve, reject) => {
chrome.windows.create(
{
url,
type: 'popup',
focused: true,
width: 1280,
height: 900,
},
() => {
const runtimeError = chrome.runtime.lastError;
elapsedSeconds.value = Math.max(0, Math.floor((Date.now() - crawlState.value.startedAt) / 1000));
}
if (runtimeError) {
reject(new Error(runtimeError.message));
return;
}
function formatElapsed(totalSeconds: number): string {
const minutes = Math.floor(totalSeconds / 60).toString().padStart(2, '0');
const seconds = (totalSeconds % 60).toString().padStart(2, '0');
return `${minutes}:${seconds}`;
}
resolve();
},
);
});
function getStepClass(status: string): string {
if (status === 'running') {
return 'border-emerald-500 bg-emerald-50 text-emerald-700';
}
if (status === 'success') {
return 'border-green-500 bg-green-50 text-green-700';
}
if (status === 'failed') {
return 'border-red-500 bg-red-50 text-red-700';
}
return 'border-slate-300 bg-white text-slate-500';
}
function getStepText(status: string): string {
const textMap: Record<string, string> = {
pending: '等待中',
running: '爬取中',
success: '已完成',
failed: '爬取失败',
};
return textMap[status] ?? status;
}
function sendBackgroundMessage<T>(message: unknown): Promise<{ ok: boolean; data?: T; error?: string }> {
if (typeof chrome === 'undefined' || !chrome.runtime?.sendMessage) {
return Promise.resolve({ ok: true, data: null as T });
}
return chrome.runtime.sendMessage(message);
}
function getRuntimeManifest(): chrome.runtime.Manifest | null {
@@ -114,6 +176,37 @@ function getRuntimeManifest(): chrome.runtime.Manifest | null {
</button>
</template>
<template v-else-if="isCrawling && crawlState">
<section class="space-y-4">
<div class="flex items-center justify-between rounded-md bg-white px-3 py-2 shadow-sm">
<div>
<p class="text-sm font-medium text-slate-800">{{ crawlState.platformName }}</p>
<p class="text-xs text-slate-500">已运行 {{ formatElapsed(elapsedSeconds) }}</p>
</div>
<button type="button" class="text-xs text-red-600 transition hover:text-red-700"
@click="handleCancelCrawl">
取消
</button>
</div>
<ol class="space-y-3">
<li v-for="(step, index) in crawlState.steps" :key="step.uniqueKey"
class="relative border-l-2 border-slate-200 pl-4">
<span
class="absolute -left-[7px] top-1 h-3 w-3 rounded-full border-2 border-white bg-slate-300"
:class="{ 'bg-emerald-500': step.status === 'running' || step.status === 'success', 'bg-red-500': step.status === 'failed' }"></span>
<div class="rounded-md border px-3 py-2 text-sm" :class="getStepClass(step.status)">
<div class="flex items-center justify-between gap-3">
<span class="font-medium">{{ index + 1 }}. {{ step.name }}</span>
<span class="text-xs">{{ getStepText(step.status) }}</span>
</div>
<p v-if="step.message" class="mt-1 text-xs">{{ step.message }}</p>
</div>
</li>
</ol>
</section>
</template>
<template v-else>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-700">平台选择</span>

45
src/types/crawl.ts Normal file
View File

@@ -0,0 +1,45 @@
/**
* 单个爬取步骤的执行状态。
*/
export type CrawlStepStatus = 'pending' | 'running' | 'success' | 'failed';
/**
* 整体爬取任务状态。
*/
export type CrawlTaskStatus = 'running' | 'completed' | 'failed' | 'canceled';
/**
* 时间轴中的单个爬取步骤进度。
*/
export interface CrawlProgressStep {
/** 步骤名称,用于展示给用户。 */
name: string;
/** 步骤唯一标识,对应平台配置 steps 中的 uniqueKey。 */
uniqueKey: string;
/** 当前步骤执行状态。 */
status: CrawlStepStatus;
/** 状态补充说明,如失败原因。 */
message?: string;
}
/**
* 当前正在执行的爬取任务快照,供 popup 和 content script 同步展示。
*/
export interface CrawlTaskState {
/** 任务唯一标识。 */
id: string;
/** 当前爬取平台 ID。 */
platformId: string;
/** 当前爬取平台名称。 */
platformName: string;
/** 爬取窗口 ID由 background 创建窗口后写入。 */
windowId?: number;
/** 任务开始时间戳。 */
startedAt: number;
/** 当前任务状态。 */
status: CrawlTaskStatus;
/** 当前执行到的步骤下标。 */
currentStepIndex: number;
/** 平台 steps 映射出的时间轴进度。 */
steps: CrawlProgressStep[];
}

View File

@@ -1,3 +1,10 @@
export type {
CrawlProgressStep,
CrawlStepStatus,
CrawlTaskState,
CrawlTaskStatus,
} from './crawl';
export type {
PlatformClickCondition,
PlatformConfig,

View File

@@ -43,5 +43,6 @@ src:.
2.前提当1完成后点击popup的立即爬取已经可以打开一个新的窗口了
- 在所有网页(包括新打开的窗口和所有网页)的右下角都放一个圆形正计时(表示正在爬取中)
- 点击圆形正计时时出现一个popup以时间轴的形式表示当前爬取进度根据platforms.ts中配置的这个平台有多少个网页要爬
- 点击圆形正计时时出现一个popup内容如下
- 以时间轴的形式表示当前爬取进度根据platforms.ts中的steps
- 同时点击扩展的popup里的内容也变得和上面的时间轴内容一致显示爬取进度隐藏立即爬取等按钮

View File

@@ -1 +1 @@
{"root":["./manifest.config.ts","./message.js","./vite.config.ts","./src/background/index.ts","./src/background/service.ts","./src/background/types.ts","./src/config/platforms.ts","./src/content/app.vue","./src/content/main.ts","./src/options/app.vue","./src/options/main.ts","./src/popup/app.vue","./src/popup/main.ts","./src/shared/auth.ts","./src/types/index.ts","./src/types/platform.ts"],"version":"5.9.3"}
{"root":["./manifest.config.ts","./message.js","./vite.config.ts","./src/background/index.ts","./src/background/service.ts","./src/background/types.ts","./src/config/platforms.ts","./src/content/app.vue","./src/content/main.ts","./src/options/app.vue","./src/options/main.ts","./src/popup/app.vue","./src/popup/main.ts","./src/shared/auth.ts","./src/types/crawl.ts","./src/types/index.ts","./src/types/platform.ts"],"version":"5.9.3"}