// ==UserScript== // @name 接口出参修改器(Mock Response Modifier) // @namespace mock-response-modifier // @version 1.0.1 // @description 拦截页面 fetch/XHR 请求,支持出参替换、字段合并、规则排序、请求出参带入及侧边吸附悬浮面板。 // @match *://*/* // @run-at document-start // @grant GM_setValue // @grant GM_getValue // @grant unsafeWindow // @license MIT // ==/UserScript== (function () { 'use strict'; const pageWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const RULES_KEY = 'mock_rules_v1'; const LOG_KEY = 'mock_req_log_v1'; const BALL_POSITION_KEY = 'mock_ball_position_v1'; const BALL_SIZE = 48; const SNAP_WIDTH = 8; const SNAP_HEIGHT = 68; const EDGE_GAP = 8; const BADGE_CSS = 'background:#1677ff;color:#fff;padding:1px 5px;border-radius:3px;font-weight:bold;'; const TAG = '%c[出参修改器]%c '; let rules = load(RULES_KEY, []); let reqLog = load(LOG_KEY, []); if (!Array.isArray(reqLog)) reqLog = []; if (reqLog.length > 30) { reqLog = reqLog.slice(-30); try { GM_setValue(LOG_KEY, JSON.stringify(reqLog)); } catch (e) { } } const savedBallPosition = load(BALL_POSITION_KEY, null); let ballSnapSide = savedBallPosition && (savedBallPosition.side === 'left' || savedBallPosition.side === 'right') ? savedBallPosition.side : null; let ballTopRatio = savedBallPosition && Number.isFinite(Number(savedBallPosition.topRatio)) ? Math.max(0, Math.min(1, Number(savedBallPosition.topRatio))) : 0.8; let ballExpandedForPanel = false; let panel = null; let uiRoot = null; let ballHost = null; let ballRoot = null; let open = false; let editingRuleId = null; let toastTimer = null; let dragState = null; let ruleDrag = null; let suppressNextClick = false; let suppressClickTimer = null; console.log(TAG + '脚本已注入 document-start,开始劫持页面 fetch/XHR', BADGE_CSS, ''); function load(key, def) { try { const v = GM_getValue(key); return v ? JSON.parse(v) : def; } catch (e) { return def; } } function saveRules() { GM_setValue(RULES_KEY, JSON.stringify(rules)); updateIndicator(); } function saveLog() { if (reqLog.length > 30) reqLog = reqLog.slice(-30); GM_setValue(LOG_KEY, JSON.stringify(reqLog)); } function matchRule(url, method) { if (!url) return null; const m = (method || 'GET').toUpperCase(); for (const r of rules) { if (!r.enabled) continue; if (r.method !== '*' && String(r.method || '*').toUpperCase() !== m) continue; if (!url.includes(r.url)) continue; try { JSON.parse(r.body); } catch (e) { continue; } return r; } return null; } function deepMerge(target, patch) { if (Array.isArray(patch)) return patch; if (patch !== null && typeof patch === 'object') { const out = target !== null && typeof target === 'object' && !Array.isArray(target) ? target : {}; for (const k of Object.keys(patch)) { out[k] = deepMerge(out[k], patch[k]); } return out; } return patch; } const sleep = (ms) => ms ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve(); function recordRequest(url, method, rule) { const hasEnabledRules = rules.some((r) => Boolean(r.enabled)); const entry = { url: String(url || ''), method: String(method || 'GET').toUpperCase(), time: Date.now(), status: hasEnabledRules ? (rule ? 'pending' : 'miss') : null, ruleMode: rule ? rule.mode : null, ruleId: rule ? rule.id : null }; reqLog.push(entry); saveLog(); if (panel) renderLog(); return entry; } function updateRequestStatus(entry, status) { if (!entry) return; entry.status = status; saveLog(); if (panel) renderLog(); } /* ---------------- Hook fetch ---------------- */ const rawFetch = pageWindow.fetch; pageWindow.fetch = async function (input, init) { let url = ''; let method = (init && init.method) || 'GET'; if (typeof input === 'string') { url = input; } else if (input && typeof input.url === 'string') { url = input.url; method = (init && init.method) || input.method || 'GET'; } else if (input && typeof input.href === 'string') { url = input.href; } method = String(method || 'GET').toUpperCase(); const rule = matchRule(url, method); const logEntry = recordRequest(url, method, rule); if (!rule) { const res = rawFetch.apply(this, arguments); // 异步捕获真实出参,不阻塞页面 Promise.resolve(res) .then((response) => { if (!response || typeof response.clone !== 'function') { return; } return response.clone().text().then((text) => { logEntry.response = text; saveLog(); if (panel) renderLog(); }); }) .catch(() => { }); return res; } console.log(TAG + '命中 fetch 规则:', BADGE_CSS, '', method, url, '-> 模式:', rule.mode); try { await sleep(Math.max(0, Number(rule.delay) || 0)); if (rule.mode === 'replace') { // 真实请求仍会发出;页面拿到的是下面构造的模拟响应。 // 不等待真实响应,避免网络较慢时影响前端调试流程。 try { Promise.resolve(rawFetch.apply(this, arguments)).catch((requestError) => { console.warn(TAG + '整体替换规则对应的真实请求失败(模拟响应仍会返回)', BADGE_CSS, '', requestError); }); } catch (requestError) { console.warn(TAG + '整体替换规则对应的真实请求发起失败(模拟响应仍会返回)', BADGE_CSS, '', requestError); } logEntry.response = rule.body; saveLog(); const response = new Response(rule.body, { status: 200, statusText: 'OK', headers: { 'Content-Type': 'application/json; charset=utf-8' } }); updateRequestStatus(logEntry, 'replaced'); return response; } const res = await rawFetch.apply(this, arguments); try { const realData = await res.clone().json(); const merged = deepMerge(realData, JSON.parse(rule.body)); console.log(TAG + 'fetch merge 结果:', BADGE_CSS, '', merged); logEntry.response = JSON.stringify(merged); saveLog(); const response = new Response(JSON.stringify(merged), { status: res.status, statusText: res.statusText, headers: { 'Content-Type': 'application/json; charset=utf-8' } }); updateRequestStatus(logEntry, 'merged'); return response; } catch (e) { updateRequestStatus(logEntry, 'failed'); console.warn( TAG + 'merge 模式解析真实响应失败,放行原始响应', BADGE_CSS, '', e ); return res; } } catch (e) { updateRequestStatus(logEntry, 'failed'); throw e; } }; /* ---------------- Hook XMLHttpRequest ---------------- */ const RawXHR = pageWindow.XMLHttpRequest; function PatchedXHR() { const xhr = new RawXHR(); let rule = null; let logEntry = null; let handled = false; const origOpen = xhr.open; xhr.open = function (method, url) { method = String(method || 'GET').toUpperCase(); rule = matchRule(String(url), method); logEntry = recordRequest(String(url), method, rule); handled = false; return origOpen.apply(this, arguments); }; xhr.addEventListener('readystatechange', function () { if (xhr.readyState !== 4 || handled) return; handled = true; // 在改写响应前捕获真实出参 const rawText = readXhrRawText(xhr); if (rawText && logEntry) { logEntry.response = rawText; saveLog(); if (panel) renderLog(); } if (!rule) return; try { const patched = patchXhrResponse(xhr, rule); if (patched) { updateRequestStatus( logEntry, rule.mode === 'replace' ? 'replaced' : 'merged' ); } else { updateRequestStatus(logEntry, 'failed'); } } catch (e) { updateRequestStatus(logEntry, 'failed'); console.warn(TAG + 'XHR 出参修改失败', BADGE_CSS, '', e); } }); return xhr; } PatchedXHR.UNSENT = RawXHR.UNSENT; PatchedXHR.OPENED = RawXHR.OPENED; PatchedXHR.HEADERS_RECEIVED = RawXHR.HEADERS_RECEIVED; PatchedXHR.LOADING = RawXHR.LOADING; PatchedXHR.DONE = RawXHR.DONE; pageWindow.XMLHttpRequest = PatchedXHR; function readXhrRawText(xhr) { try { if (xhr.responseType === '' || xhr.responseType === 'text') { return xhr.responseText || ''; } if (xhr.responseType === 'json') { return xhr.response == null ? '' : JSON.stringify(xhr.response); } } catch (e) { } return ''; } function patchXhrResponse(xhr, rule) { let body = rule.body; if (rule.mode === 'merge') { let realData; try { if (xhr.responseType === 'json') { realData = xhr.response; } else if (xhr.responseType === '' || xhr.responseType === 'text') { const raw = xhr.responseText; if (!raw) return false; realData = JSON.parse(raw); } else { return false; } body = JSON.stringify(deepMerge(realData, JSON.parse(rule.body))); } catch (e) { return false; } } const isJsonType = xhr.responseType === 'json'; let jsonVal; let jsonParsed = false; try { jsonVal = JSON.parse(body); jsonParsed = true; } catch (e) { } const props = { responseText: { configurable: true, get: () => body }, response: { configurable: true, get: () => (isJsonType && jsonParsed ? jsonVal : body) } }; if (rule.mode === 'replace') { props.status = { configurable: true, get: () => 200 }; props.statusText = { configurable: true, get: () => 'OK' }; } let patched = false; for (const [key, descriptor] of Object.entries(props)) { try { Object.defineProperty(xhr, key, descriptor); if (key === 'response' || key === 'responseText') { patched = true; } } catch (e) { } } if (rule.mode === 'replace' && patched) { console.log(TAG + '已替换 XHR 出参:', BADGE_CSS, '', rule.method, rule.url); } else if (patched) { console.log( TAG + '已合并 XHR 出参:', BADGE_CSS, '', rule.method, rule.url, isJsonType ? jsonVal : body ); } return patched; } /* ---------------- Floating button and dragging ---------------- */ function whenBodyReady(cb) { if (document.body) return cb(); const t = setInterval(() => { if (document.body) { clearInterval(t); cb(); } }, 200); } whenBodyReady(() => { ballHost = document.createElement('div'); Object.assign(ballHost.style, { position: 'fixed', right: '20px', bottom: '20px', zIndex: '2147483647', width: `${BALL_SIZE}px`, height: `${BALL_SIZE}px` }); ballRoot = ballHost.attachShadow({mode: 'open'}); ballRoot.innerHTML = ` `; const bubble = ballRoot.querySelector('.bubble'); bubble.addEventListener('pointerdown', onBallPointerDown); bubble.addEventListener('click', (event) => { if (suppressNextClick) { suppressNextClick = false; event.preventDefault(); event.stopPropagation(); return; } // 点击吸附竖条:临时展开成 M 按钮并打开面板;关闭面板后恢复竖条。 if (ballSnapSide && !ballExpandedForPanel) { ballExpandedForPanel = true; applySnappedBallPosition(true); togglePanel(); return; } togglePanel(); }); window.addEventListener('pointermove', onBallPointerMove, true); window.addEventListener('pointerup', onBallPointerUp, true); window.addEventListener('pointercancel', onBallPointerUp, true); window.addEventListener('pointermove', onRuleDragMove, true); window.addEventListener('pointerup', onRuleDragUp, true); window.addEventListener('pointercancel', onRuleDragUp, true); window.addEventListener('resize', () => { if (ballSnapSide) applySnappedBallPosition(false); else clampBallToViewport(); positionPanel(); }); document.body.appendChild(ballHost); if (ballSnapSide) applySnappedBallPosition(false); updateIndicator(); }); function updateIndicator() { if (!ballRoot) return; const bubble = ballRoot.querySelector('.bubble'); if (!bubble) return; const active = rules.some((r) => Boolean(r.enabled)); bubble.classList.toggle('has-enabled-rules', active); bubble.classList.toggle('no-enabled-rules', !active); const title = active ? '接口出参修改器:有启用规则' : '接口出参修改器:没有启用规则'; bubble.title = title; bubble.setAttribute('aria-label', title); } function onBallPointerDown(event) { if (event.button !== 0) return; const rect = ballHost.getBoundingClientRect(); dragState = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, left: rect.left, top: rect.top, moved: false }; } function getVisibleViewport() { const root = document.documentElement; return { // clientWidth excludes the classic vertical scrollbar, so the handle // remains inside the visible page area instead of sitting underneath it. width: Math.max(1, root && root.clientWidth || window.innerWidth), height: Math.max(1, root && root.clientHeight || window.innerHeight) }; } function setBallTransition(enabled) { if (!ballHost) return; ballHost.style.transition = enabled ? 'left .18s ease, top .18s ease, width .16s ease, height .16s ease' : 'none'; } function updateBallVisual() { if (!ballRoot) return; const bubble = ballRoot.querySelector('.bubble'); if (!bubble) return; bubble.classList.toggle('edge-snapped', Boolean(ballSnapSide && !ballExpandedForPanel)); } function saveBallPosition() { GM_setValue(BALL_POSITION_KEY, JSON.stringify({ side: ballSnapSide, topRatio: ballTopRatio })); } function applySnappedBallPosition(animate = false) { if (!ballHost || !ballSnapSide) return; const viewport = getVisibleViewport(); const height = ballExpandedForPanel ? BALL_SIZE : SNAP_HEIGHT; const width = ballExpandedForPanel ? BALL_SIZE : SNAP_WIDTH; const trackHeight = Math.max(0, viewport.height - SNAP_HEIGHT - EDGE_GAP * 2); const barTop = EDGE_GAP + ballTopRatio * trackHeight; const top = ballExpandedForPanel ? barTop + (SNAP_HEIGHT - BALL_SIZE) / 2 : barTop; const left = ballSnapSide === 'left' ? EDGE_GAP : viewport.width - EDGE_GAP - width; setBallTransition(animate); Object.assign(ballHost.style, { width: `${width}px`, height: `${height}px`, left: `${left}px`, top: `${Math.max(EDGE_GAP, Math.min(top, viewport.height - height - EDGE_GAP))}px`, right: 'auto', bottom: 'auto' }); updateBallVisual(); if (animate) { setTimeout(() => { if (ballHost && !dragState) ballHost.style.transition = ''; }, 240); } } function onBallPointerMove(event) { if (!dragState || event.pointerId !== dragState.pointerId || !ballHost) { return; } const dx = event.clientX - dragState.startX; const dy = event.clientY - dragState.startY; if (!dragState.moved && Math.hypot(dx, dy) < 4) return; if (!dragState.moved) { dragState.moved = true; // 从竖条开始拖动时,先展开成完整按钮,并把鼠标保持在按钮附近。 if (ballSnapSide && !ballExpandedForPanel) { const side = ballSnapSide; const viewport = getVisibleViewport(); const left = side === 'left' ? EDGE_GAP : viewport.width - EDGE_GAP - BALL_SIZE; const top = Math.max( EDGE_GAP, Math.min(event.clientY - BALL_SIZE / 2, viewport.height - BALL_SIZE - EDGE_GAP) ); ballHost.style.width = `${BALL_SIZE}px`; ballHost.style.height = `${BALL_SIZE}px`; ballHost.style.left = `${left}px`; ballHost.style.top = `${top}px`; ballHost.style.right = 'auto'; ballHost.style.bottom = 'auto'; ballSnapSide = null; ballExpandedForPanel = false; updateBallVisual(); // 重设拖动基准,避免竖条展开成按钮时产生位置跳跃。 dragState.startX = event.clientX; dragState.startY = event.clientY; dragState.left = left; dragState.top = top; } else if (ballSnapSide && ballExpandedForPanel) { // 面板打开时拖动已展开的 M 按钮,就从吸附状态脱离。 ballSnapSide = null; ballExpandedForPanel = false; updateBallVisual(); } setBallTransition(false); const bubble = ballRoot && ballRoot.querySelector('.bubble'); if (bubble) bubble.classList.add('dragging'); } const left = dragState.left + (event.clientX - dragState.startX); const top = dragState.top + (event.clientY - dragState.startY); ballHost.style.left = `${left}px`; ballHost.style.top = `${top}px`; ballHost.style.right = 'auto'; ballHost.style.bottom = 'auto'; clampBallToViewport(); positionPanel(); event.preventDefault(); } function onBallPointerUp(event) { if ( !dragState || (event.pointerId !== undefined && event.pointerId !== dragState.pointerId) ) { return; } const didMove = dragState.moved; dragState = null; const bubble = ballRoot && ballRoot.querySelector('.bubble'); if (bubble) bubble.classList.remove('dragging'); if (didMove) { suppressNextClick = true; if (suppressClickTimer) clearTimeout(suppressClickTimer); suppressClickTimer = setTimeout(() => { suppressNextClick = false; }, 350); snapBallToSide(); } } function snapBallToSide() { if (!ballHost) return; const viewport = getVisibleViewport(); const rect = ballHost.getBoundingClientRect(); // 只有距离屏幕左右边缘 20px 以内才吸附 const SNAP_THRESHOLD = 20; const distanceLeft = rect.left; const distanceRight = viewport.width - rect.right; // 两侧都不够近:保持 M 按钮原位置,不吸附 if (Math.min(distanceLeft, distanceRight) > SNAP_THRESHOLD) { ballSnapSide = null; ballExpandedForPanel = false; // 确保恢复为完整 M 按钮 setBallTransition(true); ballHost.style.width = `${BALL_SIZE}px`; ballHost.style.height = `${BALL_SIZE}px`; updateBallVisual(); saveBallPosition(); positionPanel(); setTimeout(() => { if (ballHost && !dragState) { ballHost.style.transition = ''; } }, 240); return; } // 靠近哪一侧,就吸附到哪一侧 ballSnapSide = distanceLeft <= distanceRight ? 'left' : 'right'; ballExpandedForPanel = false; const centerY = rect.top + rect.height / 2; const maxTop = Math.max( EDGE_GAP, viewport.height - SNAP_HEIGHT - EDGE_GAP ); const top = Math.max( EDGE_GAP, Math.min(centerY - SNAP_HEIGHT / 2, maxTop) ); const trackHeight = Math.max( 1, viewport.height - SNAP_HEIGHT - EDGE_GAP * 2 ); ballTopRatio = Math.max( 0, Math.min(1, (top - EDGE_GAP) / trackHeight) ); applySnappedBallPosition(true); saveBallPosition(); positionPanel(); } function clampBallToViewport() { if (!ballHost) return; const viewport = getVisibleViewport(); const rect = ballHost.getBoundingClientRect(); const maxLeft = Math.max(EDGE_GAP, viewport.width - rect.width - EDGE_GAP); const maxTop = Math.max(EDGE_GAP, viewport.height - rect.height - EDGE_GAP); const left = Math.min(maxLeft, Math.max(EDGE_GAP, rect.left)); const top = Math.min(maxTop, Math.max(EDGE_GAP, rect.top)); ballHost.style.left = `${left}px`; ballHost.style.top = `${top}px`; ballHost.style.right = 'auto'; ballHost.style.bottom = 'auto'; } function positionPanel() { if (!panel || !ballHost || !uiRoot) return; const viewport = getVisibleViewport(); const ballRect = ballHost.getBoundingClientRect(); const shell = uiRoot.querySelector('.shell'); if (!shell) return; const gap = 12; const edge = EDGE_GAP; // 面板宽度不超过可见网页区域,并为侧边吸附预留向内展开的空间。 let maxWidth = Math.min(560, viewport.width - edge * 2); if (ballSnapSide === 'left') { maxWidth = Math.min(maxWidth, viewport.width - ballRect.right - gap - edge); } else if (ballSnapSide === 'right') { maxWidth = Math.min(maxWidth, ballRect.left - gap - edge); } panel.style.width = `${Math.max(160, maxWidth)}px`; // 恢复自然高度后再计算面板应放在按钮上方还是下方。 shell.style.maxHeight = ''; const naturalHeight = panel.getBoundingClientRect().height; const spaceAbove = Math.max(0, ballRect.top - gap - edge); const spaceBelow = Math.max(0, viewport.height - ballRect.bottom - gap - edge); let placeAbove; let availableSpace; if (naturalHeight <= spaceAbove) { placeAbove = true; availableSpace = spaceAbove; } else if (naturalHeight <= spaceBelow) { placeAbove = false; availableSpace = spaceBelow; } else { placeAbove = spaceAbove >= spaceBelow; availableSpace = placeAbove ? spaceAbove : spaceBelow; } if (naturalHeight > availableSpace) { shell.style.maxHeight = `${Math.max(0, availableSpace)}px`; } const panelRect = panel.getBoundingClientRect(); const panelWidth = panelRect.width; let left; if (ballSnapSide === 'left') { left = ballRect.right + gap; } else if (ballSnapSide === 'right') { left = ballRect.left - gap - panelWidth; } else { // 未吸附时,面板右侧尽量与悬浮按钮右侧对齐。 left = ballRect.right - panelWidth + 4; } left = Math.max(edge, Math.min(left, viewport.width - panelWidth - edge)); const proposedTop = placeAbove ? ballRect.top - gap - panelRect.height : ballRect.bottom + gap; const maxTop = Math.max(edge, viewport.height - panelRect.height - edge); const top = Math.max(edge, Math.min(proposedTop, maxTop)); panel.style.left = `${left}px`; panel.style.top = `${top}px`; panel.style.right = 'auto'; panel.style.bottom = 'auto'; } /* ---------------- Management panel ---------------- */ function togglePanel() { if (open) { if (panel) panel.remove(); panel = null; uiRoot = null; open = false; editingRuleId = null; if (toastTimer) clearTimeout(toastTimer); if (ballSnapSide && ballExpandedForPanel) { ballExpandedForPanel = false; applySnappedBallPosition(true); } return; } open = true; panel = document.createElement('div'); Object.assign(panel.style, { position: 'fixed', left: '8px', top: '8px', zIndex: '2147483646', width: 'min(560px, calc(100vw - 32px))', maxHeight: 'calc(100vh - 16px)' }); uiRoot = panel.attachShadow({mode: 'open'}); uiRoot.innerHTML = `
M

接口出参修改器

Mock Response Modifier · API 调试辅助工具
FETCH / XHR 拦截已启用
规则总数
0
已启用
0
请求记录
0

生效规则 0

按列表顺序匹配,命中第一条

最近请求 0

点击请求可自动填入接口地址、方法和出参 JSON;建议把 URL 缩短为稳定的路径关键字。
`; document.body.appendChild(panel); const editorToggle = uiRoot.querySelector('#mock-editor-toggle'); editorToggle.addEventListener('click', () => { const section = uiRoot.querySelector('#mock-editor-section'); setEditorCollapsed(!section.classList.contains('collapsed')); positionPanel(); }); editorToggle.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); const section = uiRoot.querySelector('#mock-editor-section'); setEditorCollapsed(!section.classList.contains('collapsed')); positionPanel(); } }); setEditorCollapsed(true); uiRoot.querySelector('#mock-close') .addEventListener('click', togglePanel); uiRoot.querySelector('#mock-submit') .addEventListener('click', submitRule); uiRoot.querySelector('#mock-cancel-edit') .addEventListener('click', () => { resetEditor(); showToast('已退出编辑模式。'); positionPanel(); }); uiRoot.querySelector('#mock-clear-log') .addEventListener('click', () => { reqLog = []; saveLog(); renderLog(); showToast('请求记录已清空。'); }); uiRoot.querySelector('#mock-log-filter') .addEventListener('input', renderLog); uiRoot.querySelector('#mock-body') .addEventListener('input', updateJsonStatus); uiRoot.querySelector('#mock-mode') .addEventListener('change', updateModeHelp); uiRoot.querySelector('#mock-format') .addEventListener('click', formatJson); uiRoot.addEventListener('keydown', (event) => { if (event.key === 'Escape') togglePanel(); }); renderRules(); renderLog(); updateModeHelp(); updateJsonStatus(); requestAnimationFrame(positionPanel); } function updateStats() { if (!uiRoot) return; const enabled = rules.filter((r) => Boolean(r.enabled)).length; const values = { '#mock-stat-rules': rules.length, '#mock-stat-enabled': enabled, '#mock-stat-requests': reqLog.length, '#mock-rule-count': rules.length, '#mock-log-count': reqLog.length }; for (const [selector, value] of Object.entries(values)) { const el = uiRoot.querySelector(selector); if (el) el.textContent = String(value); } } /* ---------------- 规则拖动排序 ---------------- */ function onRuleDragStart(event) { if (event.button !== 0 || !uiRoot) return; // 开关、按钮等交互元素不触发拖拽 if ( event.target.closest && event.target.closest('input,button,select,textarea,a') ) { return; } ruleDrag = { pointerId: event.pointerId, card: event.currentTarget, startY: event.clientY, started: false }; } function onRuleDragMove(event) { if (!ruleDrag || event.pointerId !== ruleDrag.pointerId) return; if (!ruleDrag.started) { if (Math.abs(event.clientY - ruleDrag.startY) < 4) return; ruleDrag.started = true; startRuleDragVisual(); } event.preventDefault(); // 幽灵卡片实时跟随鼠标 if (ruleDrag.ghost) { ruleDrag.ghost.style.top = `${event.clientY - ruleDrag.offsetY}px`; } const list = uiRoot && uiRoot.querySelector('#mock-rules'); if (!list) return; const rect = list.getBoundingClientRect(); // 拖到列表上下边缘时自动滚动 if (event.clientY < rect.top + 18) list.scrollTop -= 10; else if (event.clientY > rect.bottom - 18) list.scrollTop += 10; const placeholder = list.querySelector('.drag-placeholder'); if (!placeholder) return; const cards = [ ...list.querySelectorAll('.rule-card:not(.drag-placeholder)') ]; const next = cards.find((card) => { const r = card.getBoundingClientRect(); return event.clientY < r.top + r.height / 2; }); // 位置没变化就不触发动画 if ( (next && placeholder.nextElementSibling === next) || (!next && placeholder === list.lastElementChild) ) { return; } flipMove(() => { if (next) list.insertBefore(placeholder, next); else list.appendChild(placeholder); }); } function startRuleDragVisual() { const card = ruleDrag.card; const rect = card.getBoundingClientRect(); // 克隆一份卡片作为浮动幽灵,跟随鼠标 const ghost = card.cloneNode(true); ghost.classList.add('drag-ghost'); ghost.style.width = `${rect.width}px`; ghost.style.left = `${rect.left}px`; ghost.style.top = `${rect.top}px`; uiRoot.appendChild(ghost); ruleDrag.ghost = ghost; ruleDrag.offsetY = ruleDrag.startY - rect.top; // 原卡片变成虚线占位 card.classList.add('drag-placeholder'); } // FLIP:先记录旧位置,变更 DOM 后让其他卡片平滑滑动到新位置 function flipMove(mutate) { const list = uiRoot && uiRoot.querySelector('#mock-rules'); if (!list) { mutate(); return; } const tops = new Map( [...list.querySelectorAll('.rule-card')] .filter((c) => !c.classList.contains('drag-placeholder')) .map((c) => [c, c.getBoundingClientRect().top]) ); mutate(); for (const [card, prevTop] of tops) { if (!card.isConnected) continue; const delta = prevTop - card.getBoundingClientRect().top; if (Math.abs(delta) < 1) continue; card.style.transition = 'none'; card.style.transform = `translateY(${delta}px)`; card.getBoundingClientRect(); card.style.transition = ''; card.style.transform = ''; } } function onRuleDragUp(event) { if (!ruleDrag) return; if ( event.pointerId !== undefined && event.pointerId !== ruleDrag.pointerId ) { return; } const {card, ghost, started} = ruleDrag; ruleDrag = null; if (!started) return; // 幽灵卡片淡出 if (ghost) { ghost.classList.add('dropping'); setTimeout(() => ghost.remove(), 200); } if (!card.isConnected || !uiRoot) return; card.classList.remove('drag-placeholder'); const list = uiRoot.querySelector('#mock-rules'); if (!list) return; // 按拖拽后的 DOM 顺序重排规则数组 const order = [...list.querySelectorAll('.rule-card')] .map((el) => el.dataset.id); const map = new Map(rules.map((r) => [r.id, r])); const next = []; for (const id of order) { const rule = map.get(id); if (rule) next.push(rule); } if (next.length !== rules.length) return; rules = next; saveRules(); renderRules(); renderLog(); showToast('规则顺序已更新,按新顺序匹配。'); } function renderRules() { const box = uiRoot && uiRoot.querySelector('#mock-rules'); if (!box) return; box.replaceChildren(); if (!rules.length) { const empty = document.createElement('div'); empty.className = 'empty'; empty.innerHTML = '
⌁
' + '还没有配置规则' + '在下方添加一条规则,或从最近请求中选择接口。'; box.appendChild(empty); updateStats(); requestAnimationFrame(positionPanel); return; } rules.forEach((r, index) => { const card = document.createElement('article'); card.className = 'rule-card'; card.dataset.id = r.id; card.addEventListener('pointerdown', onRuleDragStart); const line = document.createElement('div'); line.className = 'rule-line'; const enabled = document.createElement('input'); enabled.type = 'checkbox'; enabled.className = 'rule-switch'; enabled.checked = Boolean(r.enabled); enabled.title = r.enabled ? '点击禁用规则' : '点击启用规则'; enabled.setAttribute('aria-label', `启用规则:${r.url}`); enabled.addEventListener('change', () => { r.enabled = enabled.checked; saveRules(); enabled.title = r.enabled ? '点击禁用规则' : '点击启用规则'; updateStats(); renderLog(); }); const method = document.createElement('span'); method.className = 'method'; method.textContent = r.method || '*'; const url = document.createElement('div'); url.className = 'rule-url'; url.textContent = r.url || '(未设置 URL)'; url.title = r.url || ''; const mode = document.createElement('span'); mode.className = `mode${r.mode === 'replace' ? ' replace' : ''}`; mode.textContent = r.mode === 'replace' ? '替换' : '合并'; line.append(enabled, method, url, mode); const meta = document.createElement('div'); meta.className = 'rule-meta'; const delay = document.createElement('span'); delay.className = 'rule-delay'; delay.textContent = Number(r.delay) > 0 ? `延迟 ${Number(r.delay)} ms` : '无延迟'; const actions = document.createElement('div'); actions.className = 'actions'; const edit = document.createElement('button'); edit.type = 'button'; edit.className = 'mini-btn'; edit.textContent = '编辑'; edit.addEventListener('click', () => startEditRule(r)); const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'mini-btn danger'; remove.textContent = '删除'; remove.addEventListener('click', () => { rules.splice(index, 1); if (editingRuleId === r.id) resetEditor(); saveRules(); renderRules(); showToast('规则已删除。'); }); actions.append(edit, remove); meta.append(delay, actions); card.append(line, meta); box.appendChild(card); }); updateStats(); requestAnimationFrame(positionPanel); } function renderLog() { const box = uiRoot && uiRoot.querySelector('#mock-log'); if (!box) return; box.replaceChildren(); const query = ( uiRoot.querySelector('#mock-log-filter')?.value || '' ).trim().toLowerCase(); const showStatuses = rules.some((r) => Boolean(r.enabled)); const list = reqLog.slice(-30).reverse().filter((item) => { if (!query) return true; return `${item.method || ''} ${item.url || ''}` .toLowerCase() .includes(query); }); if (!list.length) { const empty = document.createElement('div'); empty.className = 'empty'; empty.innerHTML = query ? '没有匹配的请求换个关键字试试。' : '暂时没有请求记录页面发起接口请求后,会显示在这里。'; box.appendChild(empty); updateStats(); requestAnimationFrame(positionPanel); return; } list.forEach((it) => { const row = document.createElement('button'); row.type = 'button'; row.className = 'request-row'; row.title = it.response ? '点击填入接口地址、方法和出参 JSON' : '点击填入新增规则表单'; const main = document.createElement('div'); main.className = 'request-main'; const bottom = document.createElement('div'); bottom.className = 'request-bottom'; const method = document.createElement('span'); method.className = 'method'; method.textContent = it.method || 'GET'; const url = document.createElement('span'); url.className = 'request-url'; url.textContent = it.url || '(未知 URL)'; url.title = it.url || ''; const time = document.createElement('span'); time.className = 'request-time'; time.textContent = it.time ? new Date(it.time).toLocaleTimeString('zh-CN', { hour12: false }) : ''; bottom.appendChild(method); if (showStatuses && it.status) { const statusLabels = { pending: ['处理中', 'pending'], miss: ['未命中', 'miss'], merged: ['已合并', 'merged'], replaced: ['已替换', 'replaced'], failed: ['修改失败', 'failed'] }; const info = statusLabels[it.status]; if (info) { const badge = document.createElement('span'); badge.className = `status-badge ${info[1]}`; badge.textContent = info[0]; bottom.appendChild(badge); } } main.append(bottom, url); row.append(main, time); row.addEventListener('click', () => { // 从请求列表创建规则时,先退出旧规则编辑态,避免误覆盖已有规则。 resetEditor(); uiRoot.querySelector('#mock-url').value = it.url || ''; setMethodValue(it.method || 'GET'); const bodyArea = uiRoot.querySelector('#mock-body'); if (bodyArea) { bodyArea.value = it.response || ''; updateJsonStatus(); } setEditorCollapsed(false); uiRoot.querySelector('#mock-url').focus(); showToast( it.response ? '接口地址、方法和出参 JSON 已填入。建议删掉动态参数,只保留稳定的 URL 关键字。' : '接口地址已填入(该请求未记录到出参)。建议删掉动态参数,只保留稳定的 URL 关键字。' ); positionPanel(); }); box.appendChild(row); }); updateStats(); requestAnimationFrame(positionPanel); } function setMethodValue(method) { const select = uiRoot && uiRoot.querySelector('#mock-method'); if (!select) return; const value = String(method || '*').toUpperCase(); if (![...select.options].some((option) => option.value === value)) { const option = document.createElement('option'); option.value = value; option.textContent = value; select.appendChild(option); } select.value = value; } function setEditorCollapsed(collapsed) { if (!uiRoot) return; const section = uiRoot.querySelector('#mock-editor-section'); const toggle = uiRoot.querySelector('#mock-editor-toggle'); const hint = uiRoot.querySelector('#mock-editor-hint'); if (!section) return; section.classList.toggle('collapsed', collapsed); if (toggle) { toggle.setAttribute('aria-expanded', String(!collapsed)); } if (hint) { hint.textContent = collapsed ? '点击展开' : '点击收起'; } } function startEditRule(rule) { if (!uiRoot) return; editingRuleId = rule.id; uiRoot.querySelector('#mock-url').value = rule.url || ''; setMethodValue(rule.method || '*'); uiRoot.querySelector('#mock-mode').value = rule.mode === 'replace' ? 'replace' : 'merge'; uiRoot.querySelector('#mock-body').value = rule.body || ''; uiRoot.querySelector('#mock-delay').value = String(Math.max(0, Number(rule.delay) || 0)); uiRoot.querySelector('#mock-editor-title').textContent = '编辑规则'; uiRoot.querySelector('#mock-editor-icon').textContent = '✎'; uiRoot.querySelector('#mock-submit').textContent = '保存修改'; uiRoot.querySelector('#mock-cancel-edit').hidden = false; updateModeHelp(); updateJsonStatus(); setEditorCollapsed(false); uiRoot.querySelector('#mock-editor-section').scrollIntoView({ behavior: 'smooth', block: 'start' }); uiRoot.querySelector('#mock-url').focus({preventScroll: true}); positionPanel(); } function resetEditor() { if (!uiRoot) { editingRuleId = null; return; } editingRuleId = null; uiRoot.querySelector('#mock-url').value = ''; uiRoot.querySelector('#mock-method').value = '*'; uiRoot.querySelector('#mock-mode').value = 'replace'; uiRoot.querySelector('#mock-body').value = ''; uiRoot.querySelector('#mock-delay').value = '0'; uiRoot.querySelector('#mock-editor-title').textContent = '新增规则'; uiRoot.querySelector('#mock-editor-icon').textContent = '+'; uiRoot.querySelector('#mock-submit').textContent = '+ 添加规则'; uiRoot.querySelector('#mock-cancel-edit').hidden = true; updateModeHelp(); updateJsonStatus(); setEditorCollapsed(true); positionPanel(); } function submitRule() { if (!uiRoot) return; const url = uiRoot.querySelector('#mock-url').value.trim(); const body = uiRoot.querySelector('#mock-body').value.trim(); const method = uiRoot.querySelector('#mock-method').value; const mode = uiRoot.querySelector('#mock-mode').value; const delayInput = Number( uiRoot.querySelector('#mock-delay').value ); const delay = Number.isFinite(delayInput) ? Math.max(0, Math.min(60000, Math.round(delayInput))) : 0; if (!url || !body) { return showToast( 'URL 关键字和出参 JSON 都不能为空。', true ); } try { JSON.parse(body); } catch (error) { updateJsonStatus(); return showToast(`JSON 格式错误:${error.message}`, true); } if (editingRuleId) { const rule = rules.find((item) => item.id === editingRuleId); if (!rule) { resetEditor(); return showToast('这条规则已不存在,请重新选择。', true); } Object.assign(rule, { url, body, method, mode, delay }); saveRules(); renderRules(); resetEditor(); showToast('规则修改已保存,并立即生效。'); return; } rules.push({ id: 'r' + Date.now() + Math.random().toString(36).slice(2, 7), url, body, method, mode, enabled: true, delay }); saveRules(); renderRules(); resetEditor(); showToast('规则添加成功,已立即生效。'); } function updateModeHelp() { const help = uiRoot && uiRoot.querySelector('#mock-mode-help'); if (!help) return; const mode = uiRoot.querySelector('#mock-mode').value; help.textContent = mode === 'replace' ? '整体替换:真实请求正常发送,在真实请求完成后覆盖响应内容。' : '合并字段:真实请求正常发送,只覆盖你填写的字段,其余字段保留;数组会整体替换。'; } function updateJsonStatus() { const status = uiRoot && uiRoot.querySelector('#mock-json-status'); if (!status) return; const body = uiRoot.querySelector('#mock-body').value.trim(); status.className = 'json-status'; if (!body) { status.textContent = '请输入合法 JSON。整体替换需填完整出参;合并模式只需填写要覆盖的字段。'; return; } try { JSON.parse(body); status.classList.add('ok'); status.textContent = '✓ JSON 格式正确'; } catch (error) { status.classList.add('bad'); status.textContent = `JSON 格式有误:${error.message}`; } } function formatJson() { if (!uiRoot) return; const area = uiRoot.querySelector('#mock-body'); try { area.value = JSON.stringify( JSON.parse(area.value), null, 2 ); updateJsonStatus(); showToast('JSON 已格式化。'); } catch (error) { updateJsonStatus(); showToast(`无法格式化:${error.message}`, true); } } function showToast(message, isError = false) { if (!uiRoot) return; const rootAtCall = uiRoot; const toast = rootAtCall.querySelector('#mock-toast'); if (!toast) return; if (toastTimer) clearTimeout(toastTimer); toast.textContent = message; toast.className = `toast show${isError ? ' error' : ''}`; requestAnimationFrame(positionPanel); toastTimer = setTimeout(() => { if (uiRoot === rootAtCall) { toast.className = 'toast'; toast.textContent = ''; positionPanel(); } }, 3200); } })();