// ==UserScript== // @name 摸鱼伪装 // @namespace douyin-content-workspace // @version 2.4.6 // @description 在会话工作台浏览抖音、B 站和知乎,使用原生播放和评论。 // @match https://www.douyin.com/* // @match https://www.bilibili.com/* // @match https://search.bilibili.com/* // @match https://www.zhihu.com/* // @match https://zhuanlan.zhihu.com/* // @noframes // @run-at document-start // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_addStyle // @license MIT // ==/UserScript== /* MIT License Copyright (c) 2026 Douyin Content Workspace contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Upstream WeCom interface and styles from linuxdo-wecom-ui https://github.com/Blackwindow6/linuxdo-wecom-ui/blob/0ba07ea10f142724de2411d0fefec6c4e59c46c9/linuxdo-wecom.user.js The MIT License (MIT) Copyright (c) 2026 Richy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (() => { 'use strict'; const USE_PRISTINE_VIEWS = true; const WORKSPACE_THEME_LABELS = {"wecom":"企微式","feishu":"飞书式","native":"抖音原版"}; const NATIVE_CSS = "/* Keep the original scrollers and their pagination geometry. Only place the\n current player inside the workbench's transparent preview opening. */\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-layout-path] {\n overflow: visible !important;\n clip-path: none !important;\n contain: none !important;\n}\n\n/* Keep the selected player above Douyin's preloaded modal and slide layers.\n The workspace iframe is one layer higher and exposes the player's slot. */\nhtml[data-dw-mode]:not([data-dw-fullscreen]):has([data-dw-player-placed]:not([data-dw-player-suppressed])) [data-dw-layout-path] {\n z-index: 2147482999 !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-placed] {\n position: fixed !important;\n inset: var(--dw-player-top, 0px) auto auto var(--dw-player-left, 0px) !important;\n width: var(--dw-player-width) !important;\n height: var(--dw-player-height) !important;\n max-width: none !important;\n max-height: none !important;\n margin: 0 !important;\n transform: none !important;\n box-sizing: border-box !important;\n overflow: hidden !important;\n border-radius: var(--dw-player-radius, 12px) !important;\n clip-path: var(--dw-player-clip, none) !important;\n background: #111721 !important;\n z-index: 8 !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-suppressed] {\n opacity: 0 !important;\n pointer-events: none !important;\n clip-path: inset(50%) !important;\n}\n\n/* For video previews, the workbench shows only the native frame and controls.\n Preserve the Douyin nodes so its playback state and event handlers stay live. */\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-track]\n > :not([data-dw-player-track], [data-dw-player-placed], [id^=\"login-full-panel-\"],\n :has([id^=\"login-full-panel-\"], #douyin_login_comp_flat_panel_title)) {\n opacity: 0 !important;\n pointer-events: none !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-compact] {\n isolation: isolate !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-compact] * {\n visibility: hidden !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-compact]\n :is(video, xg-controls, .xgplayer-controls, .douyin-player-controls, [data-e2e=\"video-controls\"]),\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-compact]\n :is(xg-controls, .xgplayer-controls, .douyin-player-controls, [data-e2e=\"video-controls\"]) * {\n visibility: visible !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-compact]\n :is(\n [data-e2e=\"video-player-auto-play\"],\n [data-e2e=\"video-player-share\"],\n [data-e2e=\"video-share-container\"],\n .xgplayer-immersive-switch-setting,\n .xgplayer-watch-later,\n .xgplayer-page-full-screen,\n .xgplayer-time-action-tip,\n .xgTips\n ) {\n display: none !important;\n}\n\n/* The original panel still provides the scroll geometry, data, and editor.\n Match its enclosing sidecar too, since the adapter can mark just its list. */\nhtml[data-dw-mode]:not([data-dw-fullscreen])\n :is(\n [data-dw-native-comments],\n :is(#videoSideCard, #videoSideBar):has([data-dw-native-comments])\n ):not(\n [data-dw-native-player],\n [data-dw-native-comments-interactive],\n :has([data-dw-native-player], [data-dw-native-comments-interactive])\n ) {\n opacity: 0 !important;\n pointer-events: none !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-placed] > xg-video-container {\n inset: 0 !important;\n width: 100% !important;\n height: 100% !important;\n}\n\nhtml[data-dw-mode]:not([data-dw-fullscreen]) [data-dw-player-placed] xg-video-container video {\n inset: 0 !important;\n margin: 0 !important;\n width: 100% !important;\n height: 100% !important;\n object-fit: contain !important;\n}\n\n#douyin-workspace-resume {\n position: fixed;\n z-index: 2147483000;\n bottom: 20px;\n right: 20px;\n padding: 8px 15px;\n border: 1px solid #b1c9c9;\n border-radius: 20px;\n background: #f2fbf9;\n color: #153c3d;\n box-shadow: 0 2px 12px #12292b26;\n cursor: pointer;\n font: 600 13px/1.4 system-ui, sans-serif;\n}\n\n#douyin-workspace-resume:focus-visible {\n outline: 2px solid #1b776f;\n outline-offset: 3px;\n}\n\nhtml[data-dw-fullscreen]:not([data-dw-inline-fullscreen]) #douyin-workspace,\nhtml[data-dw-fullscreen] #douyin-workspace-resume {\n visibility: hidden !important;\n}\n"; // The host remains in charge of loading, navigation, playback, and submitting comments. // This adapter only reads or operates the ordinary controls exposed in the current page. function videoIdentity(url) { if (!url) return null; const detailId = url.searchParams.get("modal_id"); const match = url.pathname.match(/\/(video|note|slides)\/(\d+)(?:\/|$)/); if (match) return { id: match[2], kind: match[1] === "video" ? "video" : "image" }; if (detailId && /^\d+$/.test(detailId)) return { id: detailId, kind: "" }; return null; } function douyinRoute(url) { if (!url) return { kind: "other", channel: "", query: "", detailId: "" }; const path = url.pathname; const detailId = videoIdentity(url)?.id || ""; const searchMatch = path.match(/^\/(?:root\/)?search\/(.*)/); if (searchMatch) { let query = searchMatch[1]; try { query = decodeURIComponent(query); } catch { /* browser URL contains literal percent characters */ } return { kind: "search", channel: "search", query, detailId }; } if (path === "/" && url.searchParams.has("recommend")) { return { kind: "recommend", channel: "recommend", query: "", detailId }; } if (path.startsWith("/jingxuan") || path === "/") { const subpath = path.replace(/^\/jingxuan\/?/, "").replace(/\/$/, ""); return { kind: "curated", channel: subpath ? "curated:" + subpath : "curated", query: "", detailId }; } if (detailId) return { kind: "detail", channel: "curated", query: "", detailId }; return { kind: "other", channel: "", query: "", detailId: "" }; } function createDouyinAdapter(onChange, page = window) { const { document, location, history, HTMLInputElement, HTMLTextAreaElement } = page; const workOrigin = "https://www.douyin.com"; const commentRowSelector = [ '[data-e2e="comment-item"]', '[data-e2e="commentItem"]', ".comment-item", "[data-comment-id]", ].join(","); const expandReplyLabel = /^(?:展开|查看|更多|加载).{0,20}(?:回复|评论)/; const curatedPanelSelectors = [ '.semi-tabs-pane-active[id^="semiTabPanel"]', '[role="tabpanel"]:not([hidden])', '[id^="semiTabPanel"]:not([hidden])', ]; const recommendSelectors = ['[data-e2e="feed-active-video"]', ".swiper-slide-active"]; const modalSelector = '[data-e2e="modal-video-container"], #dy-modal-video-container-waterFall'; const detailScopeSelector = [...recommendSelectors, '.sliderVideo', '[id="sliderVideo"]', '[data-e2e="video-detail"]', '[data-e2e="note-detail"]', '[data-e2e="image-detail"]'].join(','); const searchPanelSelectors = [ '#search-result-container ul[data-e2e="scroll-list"]', '#searchResult [data-e2e="scroll-list"]', '.search-horizontal-new-layout [data-e2e="scroll-list"]', 'ul[data-e2e="scroll-list"]', '[data-e2e="search-result"]', '#searchResult', ".search-result-container", ]; const cardSelector = [ '[data-e2e="video-card"]', '[data-e2e="feed-item"]', '[data-e2e="search-card"]', '[data-e2e="search-result-card"]', ".search-result-card", ".discover-video-card-item[data-aweme-id]", "[data-aweme-id]", "[data-video-id]", ].join(","); const commentPanelSelectors = [ "[data-e2e='comment-panel']", "#videoSideCard", "#videoSideBar", '[data-e2e="comment-list"]', ".comment-list-container", ".comment-container", ]; const inputSelectors = [ '.comment-input-container [contenteditable="true"]', '.comment-input-container textarea', '[data-e2e="comment-input"] [contenteditable="true"]', '[data-e2e="comment-input"][contenteditable="true"]', 'textarea[data-e2e="comment-input"]', '[contenteditable="true"][role="textbox"]', '.comment-input-container input', "textarea", '[contenteditable="true"]', ]; const commentTriggerSelectors = [ '[data-e2e="feed-comment-icon"]', '[data-e2e="video-player-comment"]', 'button[aria-label*="评论"]', '[role="button"][aria-label*="评论"]', '.xgplayer-comment', ]; const marks = new Map(); const channelsById = new Map(); const videoNodes = new Map(); const commentNodes = new Map(); const viewedRecommendations = new Map(); const feedHistory = new Map(); const nativeListeners = new Map(); const uncertainComments = new Map(); const confirmedReplies = new Map(); const deferredChannelKey = "douyin-content-workspace:next-channel"; const lastFeedKey = "douyin-content-workspace:last-feed"; const keepsDetailList = USE_PRISTINE_VIEWS && page.top === page.self; const defaultChannels = [ { id: "curated", kind: "curated", label: "精选", href: "/jingxuan" }, { id: "recommend", kind: "recommend", label: "推荐", href: "/?recommend=1" }, ]; const interactionSelector = 'button,[role="button"],[aria-label],a,span,p'; let running = false; let observer; let routeWatch; let scheduled; let publishSignature = ""; let state; let nodes = {}; let currentRouteUrl = ""; let feedEnteredAt = 0; let pendingItem; let modalReturnAddress; let modalOriginEntry; let nativeCommentsRevealed = false; let nativeCommentsFor = ""; let submitting = false; let actionTime = 0; let deferredChannel; let navigationRequest = 0; let lastFeed; let lastFeedSignature = ""; function query(root, selectors) { if (!root) return null; for (const selector of selectors) { const node = root.querySelector(selector); if (node) return node; } return null; } function clean(value) { return (value || "").trim().replace(/\s+/g, " "); } function nodeText(node) { return clean(node?.textContent); } function semanticLabel(node) { return clean(node?.getAttribute("aria-label") || node?.getAttribute("title") || nodeText(node)); } function isActive(node) { if (!node?.isConnected || node.closest('[hidden],[aria-hidden="true"]')) return false; return node.getClientRects().length > 0; } function isShown(node) { if (!isActive(node)) return false; const rect = node.getBoundingClientRect(); if (!rect.width || !rect.height || rect.right <= 0 || rect.bottom <= 0 || rect.left >= page.innerWidth || rect.top >= page.innerHeight) return false; for (let element = node; element; element = element.parentElement) { const style = page.getComputedStyle(element); if (style.visibility !== "visible" || Number(style.opacity) === 0) return false; } return true; } function visibleLoginDialog() { if (isShown(document.getElementById("douyin_login_comp_flat_panel_title"))) return true; const titlePattern = /^(?:登录后免费畅享高清视频|登录后畅享高清(?:视频)?|登录抖音)$/; const loginMethod = /扫码登录|验证码登录|密码登录|手机号登录|登录即代表同意/; const dialogs = document.querySelectorAll( '[role="dialog"], [data-e2e*="login"], [class*="login-modal"], [class*="LoginModal"]', ); if (Array.from(dialogs).some((node) => /登录后免费畅享高清视频|扫码登录|登录抖音/.test(nodeText(node)) && isShown(node))) return true; // Some versions mount the login card as regular divs inside the player. const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT, { acceptNode(node) { const parent = node.parentElement; return titlePattern.test(clean(node.data)) && !parent?.matches("script,style,template") ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; }, }); while (walker.nextNode()) { const title = walker.currentNode.parentElement; if (!isShown(title)) continue; let context = title.parentElement; for (let depth = 0; context && context !== document.body && depth < 7; depth++, context = context.parentElement) { if (loginMethod.test(nodeText(context)) && isShown(context)) return true; } } return false; } function matchingControl(root, pattern, explicit = []) { const direct = query(root, explicit); if (direct && isActive(direct)) return direct; return Array.from(root?.querySelectorAll(interactionSelector) || []).find((node) => { const label = semanticLabel(node); if (!label || !pattern.test(label) || !isActive(node)) return false; return node.matches("button,[role='button'],a,[aria-label]") || !Array.from(node.children).some((child) => pattern.test(semanticLabel(child))); }); } function setMark(name, node, value = "") { const attribute = "data-dw-native-" + name; const old = marks.get(name); if (old && old.node === node && old.value === value) return; old?.node.removeAttribute(attribute); marks.delete(name); if (!node) return; node.setAttribute(attribute, value); marks.set(name, { node, value }); } function address(raw = location.href) { try { const url = new URL(raw, workOrigin); return url.origin === workOrigin ? url : null; } catch { return null; } } function mediaUrl(root) { const link = root.matches?.('[href]') ? root : query(root, [ '.jingxuanVideoCard[href]', 'a[href*="/video/"]', 'a[href*="/note/"]', 'a[href*="/slides/"]', 'a[href*="modal_id="]', ]); const url = address(link?.getAttribute("href") || "/"); return videoIdentity(url) ? url : null; } function imageSource(image) { const raw = image?.currentSrc || image?.getAttribute("src") || image?.getAttribute("data-src") || ""; if (/^data:image\/(?:avif|gif|jpeg|png|svg\+xml|webp)[;,]/i.test(raw)) return raw; try { const url = new URL(raw, workOrigin); return raw && (url.protocol === "https:" || url.protocol === "http:" || (url.protocol === "blob:" && url.origin === workOrigin)) ? url.href : ""; } catch { return ""; } } function accountAvatar() { const header = document.getElementById('douyin-header'); const accountLink = [...(header?.querySelectorAll('a[href*="/user/self"]') || [])].find((link) => { const url = address(link.getAttribute('href')); return url?.origin === workOrigin && /^\/user\/self\/?$/.test(url.pathname) && link.querySelector('img'); }); const accountImage = imageSource(accountLink?.querySelector('img')); if (accountImage) return accountImage; const explicit = query(header, [ '[data-e2e="header-user-avatar"] img', '[data-e2e="user-avatar"] img', 'img[data-e2e="header-user-avatar"]', 'img[data-e2e="user-avatar"]', '[data-e2e="user-center"] img', '[aria-label="个人主页"] img', '[aria-label="个人中心"] img', ]); if (explicit) return imageSource(explicit); const candidates = [...(header?.querySelectorAll('img[src*="aweme-avatar"], img[data-src*="aweme-avatar"]') || [])] .filter((image) => !image.closest('[data-e2e="notice-entry"], [data-e2e="im-entry"], [role="menu"], [role="dialog"]')); return candidates.length === 1 ? imageSource(candidates[0]) : ''; } function routes() { const url = address(); const route = douyinRoute(url); if (route.kind === "curated") { const mapped = [...channelsById.values()].find((channel) => channel.href === url.pathname); if (mapped) route.channel = mapped.id; } return route; } function safeClick(node) { if (!node?.isConnected || typeof node.click !== "function") return false; const openExternally = node.matches("a[target]") && node.target !== "_self"; const originalTarget = openExternally ? node.getAttribute("target") : null; if (openExternally) node.setAttribute("target", "_self"); try { node.click(); return true; } finally { if (originalTarget) node.setAttribute("target", originalTarget); } } function channelTabs(detail) { return Array.from(document.querySelectorAll('[role="tab"][id^="semiTab"],[data-e2e="jingxuan-category"] [role="tab"]')) .filter((tab) => !detail?.contains(tab) && isActive(tab) && semanticLabel(tab)); } function readChannels(route, detail) { const tabs = new Map(); const discovered = channelTabs(detail); for (const tab of discovered) { const label = semanticLabel(tab); const previous = [...channelsById.values()].find((channel) => channel.label === label); const selected = tab.getAttribute("aria-selected") === "true"; const tabPath = address(tab.closest("a[href]")?.getAttribute("href") || "/")?.pathname; const concretePath = tabPath && tabPath.startsWith("/jingxuan") ? tabPath : ""; const id = label === "全部" ? "curated" : previous?.id || ( selected && route.kind === "curated" && route.channel !== "curated" ? route.channel : "curated:" + label ); const href = concretePath || (selected && route.kind === "curated" ? location.pathname : previous?.href || ""); if (id !== "curated") channelsById.set(id, { id, kind: "curated", label, href }); tabs.set(id, tab); } nodes.tabs = tabs; const selectedTab = discovered.find((tab) => tab.getAttribute("aria-selected") === "true"); if (selectedTab && route.kind === "curated") { const selection = [...tabs].find(([, node]) => node === selectedTab); if (selection) route.channel = selection[0]; } if (running && route.kind === "curated" && discovered.length) finishCategoryNavigation(discovered, selectedTab); return [...defaultChannels, ...channelsById.values()]; } function finishCategoryNavigation(tabs, selectedTab) { let request = deferredChannel; try { request ||= JSON.parse(sessionStorage.getItem(deferredChannelKey)); } catch { /* in-memory request remains */ } if (!request) return; const target = request.until > Date.now() && tabs.find((tab) => semanticLabel(tab) === request.label); if (!target && request.until > Date.now()) return; deferredChannel = undefined; try { sessionStorage.removeItem(deferredChannelKey); } catch { /* nothing persisted */ } if (target && target !== selectedTab) queueMicrotask(() => { safeClick(target); schedule(); }); } function locateFeed(route) { if (route.kind === "curated") { return query(document, curatedPanelSelectors) || query(document, ['[data-e2e="jingxuan-feed"]', "#douyin-right-container main", "#douyin-right-container"]); } if (route.kind === "search") return query(document, searchPanelSelectors) || query(document, ["main"]); if (route.kind === "recommend") return query(document, [".page-recommend-container", "#slidelist"]); return null; } function findCover(card) { const known = query(card, [ '.discover-video-card-img[alt]', '[data-e2e="video-cover"] img', 'img[data-e2e="video-cover"]', "img[alt]:not([alt=''])", ]); if (known) return known; return Array.from(card.querySelectorAll("img")).find((image) => { const box = image.getBoundingClientRect(); return box.width >= 60 && box.height >= 40 && imageSource(image); }); } function contentRoots(feed) { if (!feed) return []; const matches = [...feed.querySelectorAll(cardSelector)]; for (const link of feed.querySelectorAll('a[href*="/video/"],a[href*="/note/"],a[href*="/slides/"],a[href*="modal_id="]')) { const container = link.closest(cardSelector) || link.closest("li,article") || link; if (findCover(container) || container.textContent.trim()) matches.push(container); } const candidates = new Set(matches); const unique = [...candidates].filter((card) => { for (let ancestor = card.parentElement; ancestor && ancestor !== feed; ancestor = ancestor.parentElement) { if (candidates.has(ancestor)) return false; } return true; }); if (unique.length >= 3) return unique; // Some curated layouts use anonymous card wrappers. Their cover alt and metadata are exposed. const visualCards = []; for (const image of feed.querySelectorAll("img[alt]:not([alt=''])")) { const alt = clean(image.alt); const box = image.getBoundingClientRect(); if (alt.length < 4 || box.width < 55 || box.height < 40 || !imageSource(image)) continue; let candidate = image.parentElement; for (let depth = 0; candidate && candidate !== feed && depth < 6; depth++, candidate = candidate.parentElement) { const text = nodeText(candidate); const covers = candidate.querySelectorAll("img[alt]:not([alt=''])"); if (covers.length > 2) break; if (text.includes(alt.slice(0, Math.min(alt.length, 12))) || /@[^\s].{0,50}(?:·|•)/.test(text)) { visualCards.push(candidate); break; } } } return [...new Set([...unique, ...visualCards])]; } function durationText(root, video) { const seconds = video?.duration; if (Number.isFinite(seconds) && seconds > 0) { const whole = Math.floor(seconds); const minutes = Math.floor(whole / 60); return minutes + ":" + String(whole % 60).padStart(2, "0"); } const typed = nodeText(query(root, ['[data-e2e="video-duration"]', "[data-duration]", ".duration"])); if (typed) return typed; const durationNode = Array.from(root.querySelectorAll("span,p,div")).find((element) => element.childElementCount === 0 && /^\d{1,2}:\d{2}(?::\d{2})?$/.test(nodeText(element)), ); return nodeText(durationNode); } const workIdAttributes = ['data-aweme-id', 'data-video-id', 'data-item-id', 'data-note-id']; function ownWorkId(node) { if (!node) return ''; return workIdAttributes.map((name) => node.getAttribute(name)).find((value) => /^\d{10,30}$/.test(value || '')) || node.getAttribute('class')?.match(/(?:^|\s)video_(\d{10,30})(?=\s|$)/)?.[1] || ''; } function workId(root) { return ownWorkId(root) || ownWorkId(query(root, workIdAttributes.map((name) => `[${name}]`))); } function cleanAuthor(text) { return clean(text).replace(/^@\s*/, "").split(/\s+[·•]\s+/, 1)[0]; } function workTime(root, author, authorLabel) { const stamp = query(root, ['[data-e2e="video-publish-time"]', 'time']); const explicit = nodeText(stamp) || clean(stamp?.getAttribute('datetime')); if (explicit) return explicit; const sibling = nodeText(author?.nextElementSibling); const notes = [sibling.match(/^[·•]\s*(.+)$/)?.[1], ...authorLabel.split(/\s*[·•]\s*/).slice(1)]; return notes.find((note) => note && /^(?:刚刚|(?:今天|昨天|前天)(?:\s+\d{1,2}:\d{2})?|\d+\s*(?:秒|分钟|小时|天|周|个?月|年)前|(?:\d{4}年)?\d{1,2}月\d{1,2}日|(?:\d{4}[-/])?\d{1,2}[-/]\d{1,2})$/.test(note)) || ''; } function readItem(root, route, active = false, video) { if (!root) return null; const url = mediaUrl(root); const media = videoIdentity(url); const image = findCover(root); const titleNode = query(root, [ '[data-e2e="video-desc"]', '[data-e2e="video-title"]', '[data-e2e="search-card-title"]', "h1", "h2", "h3", "[data-title]", ]); const title = clean(titleNode?.getAttribute("title") || titleNode?.getAttribute("data-title") || nodeText(titleNode) || image?.alt || root.getAttribute("aria-label") || (active ? pendingItem?.title : "") || (active && route.kind === "detail" ? document.title.replace(/\s+-\s+抖音$/, "") : "")); if (!title || /^广告$|^广告详情$|^直播中$/.test(title)) return null; const authorContainer = query(root, [ '[data-e2e="video-author"]', '[data-e2e="video-share-author"]', '[data-e2e="video-author-nickname"]', '[data-e2e="user-info"]', '[data-e2e="search-card-author"]', '#video-info-wrap a[href*="/user/"]', 'a[href*="/user/"]', ]); const authorNode = authorContainer?.matches('[data-e2e="user-info"]') ? Array.from(authorContainer.querySelectorAll('a[href*="/user/"]')).find((link) => nodeText(link)) || authorContainer : authorContainer; const nativeAuthor = semanticLabel(authorNode); const authorHint = nativeAuthor ? null : Array.from(root.querySelectorAll("span,p,div")).find((element) => { const text = nodeText(element); return text.length < 80 && /^@\s*[^@]/.test(text) && !Array.from(element.children).some((child) => /^@/.test(nodeText(child))); }); const authorLabel = nativeAuthor || nodeText(authorHint); const author = cleanAuthor(authorLabel || (active ? pendingItem?.author : "")); const time = workTime(root, authorNode || authorHint, authorLabel) || (active ? pendingItem?.time || "" : ""); const playerAvatar = active ? query(root, ['[data-e2e="live-avatar"] img']) : null; const avatar = imageSource(query(authorContainer, ["img"])) || imageSource(query(root, ['[data-e2e="video-avatar"] img', 'img[data-e2e="video-avatar"]'])) || (playerAvatar?.closest('a[href*="/user/"]') ? imageSource(playerAvatar) : ""); const cover = (active ? pendingItem?.cover || "" : "") || clean(video?.poster) || imageSource(image); const id = (active ? route.detailId : "") || media?.id || workId(root) || (active && pendingItem?.id) || ["work", title, author, cover.split("?", 1)[0]].join("|"); const gallery = root.matches('[data-e2e="image-detail"],[data-e2e="note-detail"]') || root.querySelector('[data-e2e="slides-container"],[data-e2e="photo-player"],[data-e2e="image-player"]'); const routeMediaKind = active ? videoIdentity(address())?.kind : ""; const kind = routeMediaKind || media?.kind || (gallery || /图文|组图/.test(root.getAttribute("aria-label") || "") ? "image" : "") || (active && pendingItem?.kind) || "video"; const canonical = /^\d+$/.test(id) ? workOrigin + "/" + (kind === "image" ? "note" : "video") + "/" + id : ""; return { id, title, author, avatar, cover, kind, time, duration: durationText(root, video), url: media?.id === id && !url.searchParams.has("modal_id") ? url.href : canonical, }; } function locateDetails(route, feed) { const modals = route.detailId ? [...document.querySelectorAll(modalSelector)].filter(isActive) : []; const standalone = route.kind === "detail" ? query(document, [ '[data-e2e="video-detail"]', '[data-e2e="note-detail"]', '[data-e2e="image-detail"]', ".video-detail-container", ".note-detail-container", "main", ]) : null; const dialog = route.detailId && !modals.length && !standalone ? Array.from(document.querySelectorAll('[role="dialog"]')).find((element) => isActive(element) && (element.matches('[data-e2e="video-detail"],[data-e2e="image-detail"]') || element.querySelector('video,[data-e2e="video-detail"],[data-e2e="image-detail"],[data-e2e="image-player"]')), ) : null; let detail = null; let scope = null; if (route.detailId) { for (const root of [...modals, standalone, dialog].filter(Boolean)) { const candidates = [root, ...root.querySelectorAll(detailScopeSelector)]; const match = candidates.find((node) => ownWorkId(node) === route.detailId && isActive(node)); if (match) { scope = match; detail = match.closest(modalSelector) || root; break; } } if (!detail) { detail = modals[0] || standalone || dialog; const current = query(detail, recommendSelectors) || detail; if (!ownWorkId(current)) scope = current; } } else if (route.kind === 'recommend') { scope = query(feed || document, recommendSelectors) || feed; } const video = scope?.querySelector("video"); const player = video?.closest(".basePlayerContainer,.xgplayer,.douyin-player") || query(scope, [ '[data-e2e="image-player"]', '[data-e2e="photo-player"]', '[data-e2e="slides-container"]', ".playerContainer", ".basePlayerContainer", '[data-e2e="player-container"]', '[data-e2e="player"]', ]) || video || null; return { detail, scope, player, video }; } function locateComments(scope) { if (!scope) return null; const candidates = commentPanelSelectors.flatMap((selector) => [...scope.querySelectorAll(selector)]); const hydrated = candidates.find((panel) => isActive(panel) && panel.querySelector(commentRowSelector)); const ready = hydrated || candidates.find((panel) => isActive(panel) && (inputSelectors.some((selector) => panel.querySelector(selector)) || /评论|暂无/.test(nodeText(panel)))); return ready || null; } function commentPart(row, selectors) { for (const selector of selectors) { const match = Array.from(row.querySelectorAll(selector)).find((node) => node.closest(commentRowSelector) === row, ); if (match) return match; } return null; } function isReplyingTo(row) { return Array.from(row?.querySelectorAll(".comment-item-stats-container span") || []).some((node) => node.closest(commentRowSelector) === row && nodeText(node) === "回复中", ); } function readComment(row, parent) { const datePattern = /^(?:刚刚|今天|昨天|前天|\d{1,4}[-年/]\d{1,2}|\d{1,2}月\d{1,2}日|\d+\s*(?:秒|分钟|小时|天|周|星期|个?月|年)前)/; const authorLine = commentPart(row, ['.comment-item-info-wrap']); const adjacentBody = authorLine?.nextElementSibling; const adjacentDate = adjacentBody?.nextElementSibling; const hasAdjacentDate = datePattern.test(nodeText(adjacentDate)); const adjacentActions = adjacentDate?.nextElementSibling; const nativeActionRow = adjacentActions?.matches('.comment-item-stats-container') || adjacentActions?.querySelector('.comment-item-stats-container'); const authorNode = commentPart(row, [ '[data-e2e="comment-user-name"]', '[data-e2e="comment-user"]', '[data-e2e="comment-author"]', '.comment-item-info-wrap a[href*="/user/"]', ".comment-user-name", ".comment-nickname", 'a[href*="/user/"]', ]); const textNode = commentPart(row, [ '[data-e2e="comment-content"]', '[data-e2e="comment-text"]', ".comment-content", ".comment-text", ".comment-item-text", ".comment-item-content", "[data-comment-text]", ]) || (hasAdjacentDate || nativeActionRow ? adjacentBody : null); const author = cleanAuthor(semanticLabel(authorNode)); const timeNode = commentPart(row, [ '[data-e2e="comment-time"]', ".comment-time", ".comment-item-time", "time", ]); const lines = (row.innerText || "").split("\n").map(clean).filter(Boolean); const dateIndex = lines.findIndex((part) => datePattern.test(part)); const time = nodeText(timeNode) || (hasAdjacentDate ? nodeText(adjacentDate) : "") || (dateIndex >= 0 ? lines[dateIndex] : ""); const likes = nodeText(commentPart(row, [ '[data-e2e="comment-like-count"]', '[data-e2e="comment-like"]', ".comment-like-count", ])); const images = [...(textNode?.querySelectorAll('img[src]') || [])]; const emoji = images.filter((image) => /^\[[^\]]+\]$/.test(image.alt)); const media = images.find((image) => !emoji.includes(image)); let commentText = nodeText(textNode); if (emoji.length) { const copy = textNode.cloneNode(true); for (const image of copy.querySelectorAll('img[alt]')) { if (/^\[[^\]]+\]$/.test(image.alt)) image.replaceWith(image.alt); } commentText = nodeText(copy); } const authorIndex = author ? lines.findIndex((part) => cleanAuthor(part) === author) : -1; const textLines = dateIndex > authorIndex && authorIndex >= 0 ? lines.slice(authorIndex + 1, dateIndex).filter((line) => !/^(?:作者|置顶|赞过|回复)$/.test(line)) : []; if (textLines.length > 1 && /^(?:\.\.\.|…)$/.test(textLines[0])) textLines.shift(); const text = textNode ? commentText || (media ? media.alt || "图片评论" : "") : textLines.join("\n"); if (!text) return null; const avatar = imageSource(commentPart(row, [ '[data-e2e="comment-avatar"] img', 'img[data-e2e="comment-avatar"]', '.comment-item-avatar img', 'a[href*="/user/"] img', ".comment-avatar img", ])); const expansion = Array.from(row.querySelectorAll(interactionSelector)).find((node) => node.closest(commentRowSelector) === row && expandReplyLabel.test(semanticLabel(node)), ); const countText = semanticLabel(expansion); const id = row.getAttribute("data-comment-id") || row.getAttribute("data-cid") || (row.id === "comment-item" ? "" : row.id) || [parent?.id || "comment", author, text, time].join("|"); const replyCount = Number(countText.match(/\d+/)?.[0]) || ( Number(row.getAttribute("data-reply-count")) || (expansion ? 1 : 0) ); return { id, author, avatar, text, time, likes, replyCount, parentId: parent?.id || "", canExpand: Boolean(expansion), canReply: Boolean(commentPart(row, [ '[data-e2e="comment-reply"]', '[data-e2e="reply-button"]', 'button[aria-label*="回复"]', ]) || matchingControl(row, /^回复$/) || isReplyingTo(row)), media: imageSource(media), replies: [], }; } function commentTree(panel) { commentNodes.clear(); if (!panel) return []; const comments = []; const byNode = new Map(); for (const row of panel.querySelectorAll(commentRowSelector)) { if (!isActive(row)) continue; const ancestor = row.parentElement?.closest(commentRowSelector); const parentRow = ancestor || commentParentRow(panel, row); const parent = byNode.get(parentRow); const comment = readComment(row, parent); if (!comment || commentNodes.has(comment.id)) continue; commentNodes.set(comment.id, row); byNode.set(row, comment); (parent ? parent.replies : comments).push(comment); } return comments; } function commentParentRow(panel, row) { const parentId = row.getAttribute("data-parent-id") || row.getAttribute("data-reply-to"); if (parentId) return commentNodes.get(parentId); const branch = row.closest('[data-e2e="comment-replies"],[data-e2e="sub-comment-list"],.sub-comments,.comment-reply-list'); if (!branch || branch === panel) return null; const section = branch.parentElement; const top = section?.querySelector(commentRowSelector); return top && !branch.contains(top) ? top : null; } function scrollContainer(element) { let node = element; while (node && node !== document.body) { const overflow = getComputedStyle(node).overflowY; if (/auto|scroll|overlay/.test(overflow) && node.scrollHeight > node.clientHeight + 2) return node; node = node.parentElement; } return document.scrollingElement || document.documentElement; } function scrollEnd(container) { if (!container) return false; container.scrollTop = container.scrollHeight; container.dispatchEvent(new Event("scroll", { bubbles: true })); schedule(); return true; } function rememberFeed(route, entries, current) { const key = route.kind + "/" + route.channel + "/" + route.query; if (!feedHistory.has(key)) feedHistory.set(key, new Map()); const historyForRoute = feedHistory.get(key); for (const entry of entries) { const previous = historyForRoute.get(entry.id); historyForRoute.set(entry.id, { ...entry, time: entry.time || previous?.time || "", avatar: entry.avatar || previous?.avatar || "" }); } const opened = historyForRoute.get(current?.id); if (opened) historyForRoute.set(opened.id, { ...opened, time: opened.time || current.time, avatar: opened.avatar || current.avatar }); if (feedHistory.size > 24) feedHistory.delete(feedHistory.keys().next().value); return [...historyForRoute.values()]; } function retainFeed(items) { if (!items.length) return; const candidates = items.slice(0, 80).filter((item) => videoIdentity(address(item.url))?.id === item.id); if (!candidates.length) return; const signature = JSON.stringify(candidates); if (signature === lastFeedSignature) return; lastFeed = candidates; lastFeedSignature = signature; try { page.sessionStorage.setItem(lastFeedKey, signature); } catch { /* the current document keeps the list */ } } function detailItems(route, active) { if (lastFeed === undefined) { try { const saved = JSON.parse(page.sessionStorage.getItem(lastFeedKey) || "[]"); lastFeed = Array.isArray(saved) ? saved.slice(0, 80).filter((item) => item?.id && videoIdentity(address(item.url))?.id === item.id) : []; } catch { lastFeed = []; } } const items = new Map(lastFeed.map((item) => [item.id, item])); if (!items.size) { for (const row of document.querySelectorAll('[data-e2e="aweme-relate"] li')) { const media = videoIdentity(mediaUrl(row)); if (!media || items.has(media.id)) continue; const item = readItem(row, route); if (item) items.set(item.id, item); if (items.size >= 80) break; } } const list = [...items.values()]; return active && !items.has(active.id) ? [active, ...list] : list; } function read() { const route = routes(); const baseAddress = location.pathname + (route.kind === "recommend" ? "?recommend=1" : ""); if (currentRouteUrl !== baseAddress) { currentRouteUrl = baseAddress; feedEnteredAt = Date.now(); pendingItem = undefined; nativeCommentsRevealed = false; } const feed = locateFeed(route); const { detail, scope, player, video } = locateDetails(route, feed); const panel = locateComments(scope) || (scope && detail && detail !== scope ? locateComments(detail) : null) || (route.kind === "recommend" && scope !== feed ? locateComments(feed) : null) || (route.kind === "detail" ? locateComments(document) : null); const lazyCommentList = route.kind === "detail" && query(document, ['[data-e2e="comment-list"]', ".comment-mainContent"]); const channels = readChannels(route, detail); const entries = []; videoNodes.clear(); if (route.kind === "curated" || route.kind === "search") { for (const card of contentRoots(feed)) { if (!isActive(card) || card.closest('[data-e2e="modal-video-container"]')) continue; const item = readItem(card, route); if (!item || videoNodes.has(item.id)) continue; videoNodes.set(item.id, card); entries.push(item); } } const current = readItem(scope, route, true, video); if (current && scope) { videoNodes.set(current.id, scope); if (route.kind === "recommend" && !route.detailId) { viewedRecommendations.set(current.id, current); if (viewedRecommendations.size > 300) viewedRecommendations.delete(viewedRecommendations.keys().next().value); } } const active = current || (route.detailId && pendingItem?.id === route.detailId ? pendingItem : null); if (nativeCommentsRevealed && nativeCommentsFor !== active?.id) nativeCommentsRevealed = false; let items; if (route.kind === "recommend") items = [...viewedRecommendations.values()]; else if (route.kind === "detail") items = keepsDetailList ? detailItems(route, active) : [active].filter(Boolean); else items = rememberFeed(route, entries, current); if (keepsDetailList && ["curated", "search", "recommend"].includes(route.kind)) retainFeed(items); const comments = commentTree(panel); if (active && uncertainComments.size) reconcileReplies(active.id, comments); const loginHint = query(scope || detail, ['.comment-input-un-login-container']) || matchingControl(panel, /^(?:登录|立即登录|(?:请先)?登录后.{0,35}(?:评论|回复)|请先登录)$/); const searchLogin = route.kind === "search" && !entries.length && Boolean(matchingControl( document, /^登录后即可搜索更多精彩视频$/, ['[data-e2e="search-login"]', '#search-result-container .search-login-mask'], )); const opening = Boolean(route.detailId || route.kind === "recommend"); const loginDialog = (opening || route.kind === "search") && visibleLoginDialog(); const nativeGate = searchLogin || (route.kind === "recommend" && !active && loginDialog); const trigger = query(scope, commentTriggerSelectors) || (scope ? query(detail, commentTriggerSelectors) : null); const listScroll = feed ? scrollContainer( feed.closest(".jingxuan-scroll-element") || query(feed, [".jingxuan-scroll-element", ".jingxuanFeedList"]) || videoNodes.get(entries.at(-1)?.id) || feed, ) : null; const feedTail = (query(feed, [".jingxuan-scroll-element"]) || feed)?.lastElementChild; const feedTailText = nodeText(feedTail); const feedRetry = /服务超时|加载失败|网络异常|重新刷新/.test(feedTailText) && matchingControl(feedTail, /^(?:刷新|重试|重新加载|点击重试)$/); const feedLoading = !feedRetry && /^(?:正在加载(?:更多)?(?:中)?|加载中)[.…]*$/.test(feedTailText); const ended = /^(?:没有更多(?:了)?|已经到底了|暂无搜索结果)$/.test(feedTailText) || (feed && matchingControl(feed, /^(?:没有更多(?:了)?|已经到底了|暂无搜索结果)$/)); const commentsEnded = panel && matchingControl(panel, /^(?:没有更多评论(?:了)?|暂无评论|评论已全部加载)$/); const commentRetry = panel && matchingControl(panel, /^(?:点击|请点击)?(?:重试|重新加载|刷新)(?:评论|数据)?$/, ['[data-e2e="comment-retry"]']); const commentLoading = panel && !comments.length && !commentRetry && matchingControl(panel, /^(?:正在)?加载中[.…]*$/); const commentsState = panel ? loginHint ? 'login' : comments.length ? 'ready' : commentRetry ? 'error' : commentsEnded ? 'empty' : commentLoading ? 'loading' : 'unavailable' : trigger || lazyCommentList ? 'closed' : 'unavailable'; const canOpenComments = Boolean(trigger || panel || lazyCommentList); nodes = { ...nodes, detail, feed, scope, player, video, panel, lazyCommentList, trigger, commentRetry, listScroll, feedRetry }; if (running) { setMark("feed", feed); setMark("detail", detail); setMark("active", scope); setMark("player", player); setMark("comments", panel); setMark("comments-interactive", nativeCommentsRevealed ? panel : null); setMark("aux", query(document, ["#douyin-header", "#douyin-navigation"])); } const realCuratedFeed = feed?.matches([...curatedPanelSelectors, '[data-e2e="jingxuan-feed"]'].join(",")); const realSearchFeed = feed?.matches(searchPanelSelectors.join(",")); const rendered = Boolean( route.kind === "curated" && (realCuratedFeed || entries.length) || route.kind === "search" && (realSearchFeed || entries.length || searchLogin) || route.kind === "recommend" && (scope || feed) || route.kind === "detail" && (detail || player), ); const nativePageReady = rendered || (document.readyState === "complete" && (route.kind === "other" || Date.now() - feedEnteredAt > 6500)); return { route, channels, items, active, comments, nativePageReady, accountAvatar: accountAvatar(), compatible: route.kind !== "other" && (USE_PRISTINE_VIEWS || !nativePageReady || rendered), nativeDetail: opening && Boolean(player), mediaKind: opening ? active?.kind || (video ? "video" : "image") : "", canLoadMore: Boolean(listScroll && (route.kind === "curated" || route.kind === "search") && !ended && !searchLogin), feedState: ended ? "ended" : feedRetry ? "retry" : feedLoading ? "loading" : "ready", canCompose: Boolean(panel && !loginHint && (getEditor(panel) || getComposer(panel))), canStep: route.kind === "recommend" || Boolean(route.detailId && items.length > 1), canOpenComments, canRetryComments: Boolean(commentRetry), canLoadMoreComments: Boolean(panel && comments.length && !commentsEnded), commentsOpen: Boolean(panel), commentsState, confirmedReplies: [...confirmedReplies.values()].filter((reply) => reply.videoId === active?.id), nativeLogin: Boolean(nativeGate || loginDialog), nativeGate, loading: !rendered && !nativePageReady, }; } function update() { scheduled = undefined; if (!running) return; state = read(); const signature = JSON.stringify(state); if (publishSignature === signature) return; publishSignature = signature; onChange?.(state); } function schedule() { if (running && scheduled === undefined) scheduled = setTimeout(update, 65); } function start() { if (running) return state; running = true; publishSignature = ""; observer = new MutationObserver((changes) => { if (changes.some(({ target }) => !target.parentElement?.closest("[data-dw-workspace]"))) schedule(); }); observer.observe(document.body || document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: [ "aria-selected", "aria-hidden", "hidden", "data-e2e", "data-comment-show", "data-comment-id", "src", "href", "alt", "poster", "contenteditable", ], }); for (const event of ["popstate", "pageshow", "hashchange", "loadedmetadata"]) { page.addEventListener(event, schedule, true); nativeListeners.set(event, schedule); } let lastUrl = location.href; routeWatch = setInterval(() => { if (lastUrl !== location.href || !state?.nativePageReady) { lastUrl = location.href; schedule(); } }, 450); update(); return state; } function stop() { if (!running) return; running = false; navigationRequest += 1; observer.disconnect(); clearInterval(routeWatch); clearTimeout(scheduled); scheduled = undefined; for (const [event, listener] of nativeListeners) page.removeEventListener(event, listener, true); nativeListeners.clear(); for (const name of [...marks.keys()]) setMark(name, null); nativeCommentsRevealed = false; } function destroy() { stop(); feedHistory.clear(); channelsById.clear(); viewedRecommendations.clear(); videoNodes.clear(); commentNodes.clear(); uncertainComments.clear(); confirmedReplies.clear(); } function navigate(target) { const channel = typeof target === "string" ? (state?.channels || defaultChannels).find((entry) => entry.id === target) : target; if (!channel) return false; const request = ++navigationRequest; const original = location.href; if (state?.route.detailId) pause(); const tab = nodes.tabs?.get(channel.id); if (tab && safeClick(tab)) { retryNativeNavigation(request, original, () => { const label = channel.id === "curated" ? "全部" : channel.label; const current = channelTabs(nodes.detail).find((entry) => semanticLabel(entry) === label); return current?.getAttribute("aria-selected") !== "true" && safeClick(current); }); schedule(); return true; } if (!channel.href && channel.kind === "curated") { deferredChannel = { label: channel.label, until: Date.now() + 8000 }; try { sessionStorage.setItem(deferredChannelKey, JSON.stringify(deferredChannel)); } catch { /* same-page navigation still works */ } } const url = address(channel.href || "/jingxuan"); if (!url) return false; const link = Array.from(document.querySelectorAll("#douyin-navigation a[href]")).find((node) => { const href = address(node.getAttribute("href")); return href?.pathname === url.pathname && href.searchParams.get("recommend") === url.searchParams.get("recommend"); }); if (!link || !safeClick(link)) location.assign(url.href); schedule(); return true; } function search(queryText) { const keyword = clean(queryText); if (!keyword) return false; navigationRequest += 1; if (state?.route.detailId) pause(); const url = new URL("/search/" + encodeURIComponent(keyword), workOrigin); url.searchParams.set("type", "video"); if (url.href !== location.href) location.assign(url.href); return true; } // The curated page can render its initial HTML before attaching UI handlers. // Keep a retry tied to the user's intent and the same route. function retryNativeNavigation(request, origin, click, fallback) { if (location.href !== origin) return; const delays = document.readyState === "complete" ? [700] : [450, 1200, 2500, 4000]; const stillCurrent = () => running && navigationRequest === request && location.href === origin; for (const [index, delay] of delays.entries()) { setTimeout(() => { if (!stillCurrent()) return; if (click()) schedule(); if (index === delays.length - 1 && fallback) { setTimeout(() => { if (stillCurrent()) location.assign(fallback); }, 750); } }, delay); } } function clickWithoutLeaving(node) { const link = node?.closest("a[target]"); const target = link?.getAttribute("target"); const preventNavigation = (event) => { if (!event.destination.sameDocument && event.cancelable) event.preventDefault(); }; const preventLink = (event) => { if (event.target.closest?.("a[href]")) event.preventDefault(); }; page.navigation?.addEventListener("navigate", preventNavigation); page.addEventListener("click", preventLink); try { if (target) link.setAttribute("target", "_self"); return safeClick(node); } finally { if (target) link.setAttribute("target", target); page.removeEventListener("click", preventLink); page.navigation?.removeEventListener("navigate", preventNavigation); } } function open(item, inPlace = false) { if (!item) return false; const request = ++navigationRequest; const original = location.href; const candidate = videoNodes.get(item.id); if (candidate && candidate === nodes.scope && (state?.route.kind === "recommend" || state?.route.detailId)) return true; pendingItem = item; if (state?.route.detailId && nodes.video && state.active?.id !== item.id) pause(); const coverControl = query(candidate, ['img.discover-video-card-img[alt]']); const link = candidate?.matches("[href]") ? candidate : query(candidate, ['.jingxuanVideoCard[href]', 'a[href*="/video/"]', 'a[href*="/note/"]', 'a[href*="modal_id="]']); if (!state?.route.detailId) { modalReturnAddress = location.href; modalOriginEntry = { index: page.navigation?.currentEntry?.index, length: history.length }; } const click = inPlace ? clickWithoutLeaving : safeClick; if (candidate && click(coverControl || link || candidate)) { const url = address(item.url || "/"); if (videoIdentity(url) && url.href !== original) { retryNativeNavigation(request, original, () => { const live = videoNodes.get(item.id); if (!live) return false; return click(query(live, ['img.discover-video-card-img', '.jingxuanVideoCard[href]', 'a[href*="/video/"]', 'a[href*="/note/"]']) || live); }, inPlace ? undefined : url.href); } schedule(); return true; } const url = address(item.url || "/"); if (!videoIdentity(url)) return false; if (!inPlace) location.assign(url.href); return true; } function close() { navigationRequest += 1; if (!routes().detailId) return false; pause(); nativeCommentsRevealed = false; const button = matchingControl(nodes.detail, /^(?:关闭|返回|退出播放)$/, [ '[data-e2e="close-btn"]', '[data-e2e="close-button"]', '[data-e2e="video-close"]', 'button[aria-label="关闭"]', '[aria-label="关闭播放器"]', ".xgplayer-close", ]); if (!safeClick(button)) { const current = address(); if (current.searchParams.has("modal_id")) { current.searchParams.delete("modal_id"); const returnUrl = address(modalReturnAddress || "/"); const currentEntryIndex = window.navigation?.currentEntry?.index; const hasModalEntry = Number.isInteger(currentEntryIndex) && Number.isInteger(modalOriginEntry?.index) ? currentEntryIndex > modalOriginEntry.index : history.length > (modalOriginEntry?.length || history.length); if (modalReturnAddress && hasModalEntry && returnUrl?.pathname === current.pathname) history.back(); else location.assign(current.href); } else { location.assign(modalReturnAddress || workOrigin + "/jingxuan"); } } schedule(); return true; } function more() { if (Date.now() - actionTime < 550 || !state?.canLoadMore || state.feedState === "loading") return false; actionTime = Date.now(); if (nodes.feedRetry) { const retried = safeClick(nodes.feedRetry); if (retried) schedule(); return retried; } const button = matchingControl(nodes.feed, /^(?:加载更多|查看更多(?:视频)?|更多视频)$/); return safeClick(button) || scrollEnd(nodes.listScroll); } function step(direction) { const reverse = direction === -1 || direction === "prev" || direction === "previous"; const selector = reverse ? '.xgplayer-playswitch-prev,.douyin-player-playswitch-prev,[data-e2e="previous-video"],[data-e2e="video-switch-prev-arrow"]' : '.xgplayer-playswitch-next,.douyin-player-playswitch-next,[data-e2e="next-video"],[data-e2e="video-switch-next-arrow"]'; const control = query(nodes.scope || nodes.detail || nodes.feed, [selector]) || query(nodes.detail || nodes.feed, [selector]); if (safeClick(control)) { schedule(); return true; } if (state?.route.kind === "recommend") { const target = document.activeElement; if (target?.matches?.("textarea,input,[contenteditable='true']")) target.blur(); const key = reverse ? "ArrowUp" : "ArrowDown"; document.dispatchEvent(new KeyboardEvent("keydown", { key, code: key, bubbles: true, cancelable: true })); schedule(); return true; } const currentIndex = state?.items.findIndex((item) => item.id === state.active?.id || item.id === pendingItem?.id, ) ?? -1; const item = state?.items[currentIndex + (reverse ? -1 : 1)]; return currentIndex >= 0 && Boolean(item && open(item)); } function pause() { if (!nodes.video) return false; nodes.video.pause(); return true; } function openComments(retry = false) { if (retry && nodes.commentRetry && safeClick(nodes.commentRetry)) { schedule(); return true; } if (nodes.panel) return true; if (nodes.lazyCommentList) { nodes.lazyCommentList.scrollIntoView({ block: "start" }); schedule(); return true; } const opened = safeClick(nodes.trigger); if (opened) schedule(); return opened; } function revealComments() { if (!openComments()) return false; nativeCommentsRevealed = true; nativeCommentsFor = state?.active?.id || ""; if (nodes.panel) setMark("comments-interactive", nodes.panel); schedule(); return true; } function moreComments() { if (!nodes.panel) return false; const moreButton = matchingControl(nodes.panel, /^(?:加载|查看)更多(?:评论)?$/); const commentList = query(nodes.panel, ['[data-e2e="comment-list"]', ".comment-list", ".comment-list-container"]); const commentRows = [...nodes.panel.querySelectorAll(commentRowSelector)]; const scroll = scrollContainer(commentRows[0] || commentList || nodes.panel); if (safeClick(moreButton) || (scroll !== document.scrollingElement && scrollEnd(scroll))) return true; const last = commentRows.at(-1); if (!last) return false; last.scrollIntoView({ block: "end" }); schedule(); return true; } function expandComment(id) { const row = commentNodes.get(id); // Douyin may attach the handler to the label's container inside the button. const label = row && commentPart(row, ['.comment-reply-expand-btn span:not([role="img"])']); const control = isActive(label) && expandReplyLabel.test(semanticLabel(label)) ? label : matchingControl(row, expandReplyLabel, [ '[data-e2e="comment-expand-replies"]', '[data-e2e="comment-more-replies"]', ]); if (control?.closest(commentRowSelector) !== row || !safeClick(control)) return false; schedule(); return true; } function getComposer(panel) { const selectors = [ "#comment-input-container", ".comment-input-container", '[data-e2e="comment-composer"]', '[data-e2e="comment-input"]', ".comment-input-wrap", ]; const composer = query(panel, selectors) || query(nodes.scope || nodes.detail, selectors); return composer && isActive(composer) ? composer : null; } function findEditor(scope, row = null) { if (!scope) return null; const available = (editor) => editor.closest(commentRowSelector) === row && isActive(editor) && !editor.disabled && !editor.readOnly; if (scope.matches('[contenteditable="true"],textarea,input[type="text"]') && available(scope)) return scope; for (const selector of inputSelectors) { const editor = Array.from(scope.querySelectorAll(selector)).find(available); if (editor) return editor; } return null; } function getEditor(panel) { return findEditor(getComposer(panel) || panel); } function getInlineReplyEditor(row) { return row ? findEditor(commentPart(row, [".comment-input-inner-container"]), row) : null; } function fieldValue(editor) { return typeof editor?.value === "string" ? editor.value : editor?.innerText ?? editor?.textContent ?? ""; } function setInputText(editor, value) { if (clean(fieldValue(editor)) === clean(value)) return true; if (editor instanceof HTMLInputElement || editor instanceof HTMLTextAreaElement) { const base = editor instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(base, "value").set.call(editor, value); editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: value })); editor.dispatchEvent(new Event("change", { bubbles: true })); return clean(fieldValue(editor)) === clean(value); } if (editor.matches(".public-DraftEditor-content") && !clean(fieldValue(editor))) { // Let the controlled editor import the draft into its own state, without moving focus across frames. const data = new page.DataTransfer(); data.setData("text/plain", value); const paste = new page.ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); if (!editor.dispatchEvent(paste)) return true; } editor.focus({ preventScroll: true }); const selection = page.getSelection(); const range = document.createRange(); range.selectNodeContents(editor); selection?.removeAllRanges(); selection?.addRange(range); const changed = document.execCommand?.("insertText", false, value); if (!changed) { editor.textContent = value; editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: value })); } return clean(fieldValue(editor)) === clean(value); } function matchingComment(id, comments) { for (const comment of comments) { if (comment.id === id) return comment; const match = matchingComment(id, comment.replies); if (match) return match; } return null; } function flatComments(comments) { return comments.flatMap((comment) => [comment, ...flatComments(comment.replies)]); } function reconcileReplies(videoId, comments) { const rows = flatComments(comments); for (const [key, reply] of uncertainComments) { if (reply.videoId !== videoId) continue; if (reply.editor.isConnected && reply.editor.getAttribute("contenteditable") === "false" && clean(fieldValue(reply.editor)) === reply.message) continue; const posted = rows.find((comment) => !reply.before.has(comment.id) && clean(comment.text) === reply.message && (reply.targetId ? comment.parentId === reply.threadId || comment.parentId === reply.targetId : !comment.parentId)); if (posted) { const receipt = { key, videoId, commentId: posted.id, threadId: reply.threadId }; confirmedReplies.set(key, receipt); if (confirmedReplies.size > 24) confirmedReplies.delete(confirmedReplies.keys().next().value); uncertainComments.delete(key); } else if (reply.threadId && !reply.expanded && (!reply.editor.isConnected || !clean(fieldValue(reply.editor)))) { const thread = matchingComment(reply.threadId, comments); if (thread?.canExpand && !thread.replies.length) { reply.expanded = true; expandComment(thread.id); } } } } function waitUntil(check, timeout) { const until = Date.now() + timeout; return new Promise((resolve) => { function poll() { const result = check(); if (result || Date.now() >= until) resolve(result); else setTimeout(poll, 80); } poll(); }); } function commentPage() { const item = state?.active; const url = address(item?.url || "/"); if (url && /^\/(?:video|note|slides)\/\d+/.test(url.pathname)) return url.href; const id = state?.route.detailId || item?.id; if (!/^\d+$/.test(id || "")) return ""; return workOrigin + "/" + (item?.kind === "image" ? "note" : "video") + "/" + id; } function login() { const button = matchingControl(document, /^(?:请先登录|立即登录|登录)$/, [ '#comment-input-container .comment-input-un-login-container', '#douyin-header [data-e2e="login-button"]', '#douyin-header button[aria-label="登录"]', ]); return safeClick(button); } function replyLabels(editor) { const composer = getComposer(nodes.panel); return [ editor.getAttribute("placeholder"), editor.getAttribute("data-placeholder"), editor.getAttribute("aria-label"), nodeText(query(composer, ['[data-e2e="comment-reply-target"]', '.comment-reply-target'])), ].filter(Boolean); } function replyTargetId(editor) { return editor.closest("[data-reply-to]")?.getAttribute("data-reply-to") || getComposer(nodes.panel)?.getAttribute("data-reply-to") || ""; } function replyLabelAuthor(label) { const matched = clean(label).match(/^(?:回复\s*(?:给\s*)?|Reply to\s+)[@@]?\s*(.+?)\s*[::]?$/i); return matched?.[1] || ""; } function matchesInlineReplyEditor(editor, row, author) { if (!row || editor.closest(commentRowSelector) !== row || !isReplyingTo(row)) return false; const placeholder = editor.ownerDocument.getElementById(editor.getAttribute("aria-describedby") || ""); const label = editor.closest(".comment-input-inner-container")?.contains(placeholder) ? nodeText(placeholder) : ""; // Draft.js removes its placeholder when text is entered; the active row remains the target. return !label || replyLabelAuthor(label) === author; } function nativeReplyQuote(editor) { const quote = editor.closest(".comment-input-inner-container")?.previousElementSibling; const label = nodeText(quote?.firstElementChild); const prefix = /^回复\s*[@@]\s*/; return prefix.test(label) ? { quote, label: label.replace(prefix, "") } : null; } function matchesNativeReplyQuote(label, target, row) { if (!target.author || !label.startsWith(target.author) || !row?.isConnected) return false; const excerpt = label.slice(target.author.length).match(/^\s*[::]\s*(.*)$/)?.[1]; return Boolean(excerpt && clean(excerpt) === clean(target.text) && isReplyingTo(row)); } function hasReplyTarget(editor) { return Boolean(replyTargetId(editor) || nativeReplyQuote(editor) || replyLabels(editor).some((label) => { const author = replyLabelAuthor(label); return author && author !== "评论"; })); } async function reply(text, commentId) { const message = (text || "").trim(); if (!message) return { ok: false, reason: "请输入评论。" }; if (submitting) return { ok: false, reason: "上一条评论正在提交。" }; if (!state?.active || !nodes.panel) return { ok: false, reason: "请先打开视频评论。" }; if (state.commentsState === "login") return { ok: false, reason: "登录抖音后可发表评论。" }; const session = location.href; const activeId = state.active.id; const submissionKey = JSON.stringify([activeId, commentId || "", message]); if (uncertainComments.has(submissionKey)) { return { ok: false, pending: true, reason: "这条回复正在等待抖音确认,出现后会显示在这里。" }; } const stillCurrent = () => running && location.href === session && state?.active?.id === activeId; const messagesBefore = new Set(flatComments(state.comments).map((comment) => comment.id)); const target = commentId ? matchingComment(commentId, state.comments) : null; if (commentId && !target) return { ok: false, reason: "找不到要回复的评论,请重新选择。" }; submitting = true; try { const currentRow = () => commentId ? commentNodes.get(commentId) : null; const currentEditor = () => getInlineReplyEditor(currentRow()) || getEditor(nodes.panel); const openReplyEditor = () => { const row = currentRow(); const control = matchingControl(row, /^回复$/, [ '[data-e2e="comment-reply"]', '[data-e2e="reply-button"]', 'button[aria-label*="回复"]', ]); return Boolean(row && control?.closest(commentRowSelector) === row && safeClick(control)); }; const oldEditor = currentEditor(); const uniqueAuthor = target?.author && flatComments(state.comments) .filter((comment) => comment.author === target.author).length === 1; const matchesEditor = (candidate, allowSharedLabel = true) => { if (!candidate) return false; if (!target) return !hasReplyTarget(candidate); if (candidate.closest(commentRowSelector)) return matchesInlineReplyEditor(candidate, currentRow(), target.author); const targetId = replyTargetId(candidate); if (targetId) return targetId === commentId; const quote = nativeReplyQuote(candidate); if (quote) return matchesNativeReplyQuote(quote.label, target, currentRow()); const displayedAuthor = replyLabels(candidate).map(replyLabelAuthor).find(Boolean); return allowSharedLabel && uniqueAuthor && displayedAuthor === target.author; }; if (target) { if (!matchesEditor(oldEditor, false) && !openReplyEditor()) { return { ok: false, reason: "抖音未开放该条评论的回复入口。" }; } } else if (oldEditor && hasReplyTarget(oldEditor)) { const cancel = matchingControl(getComposer(nodes.panel), /^取消回复$/, [ '[data-e2e="cancel-comment-reply"]', '[aria-label="取消回复"]', ]); const closeQuote = nativeReplyQuote(oldEditor)?.quote.querySelector(":scope > svg.DADTc4UZ"); if (!safeClick(cancel)) { if (!isActive(closeQuote)) return { ok: false, reason: "请先在抖音原生输入框取消上一条回复。" }; closeQuote.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); } } const waitForEditor = () => waitUntil(() => { if (!stillCurrent()) return null; const candidate = currentEditor(); return matchesEditor(candidate) ? candidate : null; }, 1300); let editor = await waitForEditor(); if (!stillCurrent()) return { ok: false, reason: "视频已切换,草稿已保留。" }; if (!editor) return { ok: false, reason: target ? "无法确认原生回复对象,请使用抖音输入框。" : "抖音评论输入框尚未就绪。" }; const waitForSendButton = () => waitUntil(() => { if (!stillCurrent()) return null; const current = currentEditor(); if (!matchesEditor(current) || clean(fieldValue(current)) !== clean(message)) return null; const composer = current.closest(commentRowSelector) ? current.closest(".comment-input-inner-container") : null; const scope = composer || getComposer(nodes.panel) || current.parentElement?.parentElement; const control = matchingControl(scope, /^(?:发送|发布)$/, [ '[data-e2e="comment-send"]', '[data-e2e="publish-comment"]', '[aria-label="发送"]', '.commentInput-right-ct .wchsYBpK:has(> svg)', ]); return control && !control.disabled && control.getAttribute("aria-disabled") !== "true" ? { control, editor: current } : null; }, 1000); const wasInline = Boolean(editor.closest(commentRowSelector)); const staged = setInputText(editor, message); let submission = staged ? await waitForSendButton() : null; if (!submission && wasInline && stillCurrent()) { const row = currentRow(); const replacement = getInlineReplyEditor(row); if (!isReplyingTo(row) && openReplyEditor()) editor = await waitForEditor(); else editor = replacement; if (editor && matchesInlineReplyEditor(editor, currentRow(), target.author) && !clean(fieldValue(editor)) && stillCurrent() && setInputText(editor, message)) { submission = await waitForSendButton(); } } if (!stillCurrent()) return { ok: false, reason: "视频已切换,草稿已保留。" }; const readyEditor = currentEditor(); if (!matchesEditor(readyEditor) || clean(fieldValue(readyEditor)) !== clean(message)) { return { ok: false, reason: "抖音的回复框已关闭或清空,草稿已保留。" }; } if (submission?.editor !== readyEditor) { return { ok: false, reason: "抖音的发送按钮还未就绪,草稿已保留。" }; } const thread = target && state.comments.find((comment) => comment.id === target.id || matchingComment(target.id, comment.replies)); const receipt = { videoId: activeId, targetId: target?.id, threadId: thread?.id || target?.parentId || target?.id, message: clean(message), before: messagesBefore, editor: readyEditor }; confirmedReplies.delete(submissionKey); uncertainComments.set(submissionKey, receipt); if (uncertainComments.size > 120) uncertainComments.delete(uncertainComments.keys().next().value); if (!safeClick(submission.control)) { uncertainComments.delete(submissionKey); return { ok: false, reason: "抖音的发送按钮还未就绪,草稿已保留。" }; } schedule(); await waitUntil(() => !stillCurrent() || confirmedReplies.has(submissionKey), 12000); const posted = confirmedReplies.get(submissionKey); return posted ? { ok: true, posted } : { ok: false, pending: true, reason: readyEditor.isConnected && readyEditor.getAttribute("contenteditable") === "false" ? "抖音仍在提交,回复出现后会显示在这里。" : "回复暂未出现在评论列表,草稿已保留。", }; } finally { submitting = false; } } return { read, getSnapshot: () => state || read(), start, stop, destroy, navigate, search, open, close, more, step, pause, hasPendingReply: (videoId) => [...uncertainComments.values()].some((reply) => reply.videoId === videoId), openComments, revealComments, moreComments, expandComment, reply, commentPage, login, }; } function workroomText(value) { if (value && typeof value === 'object') { return String(value.name ?? value.nickname ?? value.text ?? ''); } return String(value ?? ''); } function workroomEscape(value) { return workroomText(value).replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }[character])); } function workroomURL(value, nativePage = false) { if (!value) return ''; try { const url = new URL(String(value), location.href); if (url.protocol !== 'https:') return ''; if (nativePage && !(url.hostname === 'douyin.com' || url.hostname.endsWith('.douyin.com'))) return ''; return url.href; } catch { return ''; } } const WORKSPACE_SITES = [ { id: 'douyin', label: '抖音', hosts: ['www.douyin.com'], home: 'https://www.douyin.com/jingxuan', groups: { curated: '精选群', recommend: '推荐群' }, }, { id: 'bilibili', label: 'B 站', hosts: ['www.bilibili.com', 'search.bilibili.com'], home: 'https://www.bilibili.com/', groups: { curated: 'B 站推荐群', popular: 'B 站热门群' }, channels: [ { id: 'curated', kind: 'curated', label: 'B 站推荐', href: 'https://www.bilibili.com/' }, { id: 'popular', kind: 'curated', label: 'B 站热门', href: 'https://www.bilibili.com/v/popular/all' }, ], search: (query) => `https://search.bilibili.com/all?keyword=${encodeURIComponent(query)}`, }, { id: 'zhihu', label: '知乎', hosts: ['www.zhihu.com', 'zhuanlan.zhihu.com'], home: 'https://www.zhihu.com/', groups: { curated: '知乎推荐群', popular: '知乎热榜群' }, channels: [ { id: 'curated', kind: 'curated', label: '知乎推荐', href: 'https://www.zhihu.com/' }, { id: 'popular', kind: 'curated', label: '知乎热榜', href: 'https://www.zhihu.com/hot' }, ], search: (query) => `https://www.zhihu.com/search?type=content&q=${encodeURIComponent(query)}`, }, ]; function workspaceSite(url = location) { return WORKSPACE_SITES.find((site) => site.hosts.includes(url.hostname)); } function workspaceSiteURL(value, base = location.href) { if (!value) return null; try { const url = new URL(value, base); return url.protocol === 'https:' && !url.username && !url.password ? url : null; } catch { return null; } } function workspaceContent(value, base = location.href) { const url = workspaceSiteURL(value, base); const site = url && workspaceSite(url); if (!site) return null; const path = url.pathname.replace(/\/$/, ''); if (site.id === 'douyin') { const match = path.match(/^\/video\/(\d+)$/); return match && { id: match[1], kind: 'video', url: url.href }; } if (site.id === 'bilibili' && url.hostname === 'www.bilibili.com') { const match = path.match(/^\/video\/(BV[\da-zA-Z]{10}|av\d+)$/); if (!match) return null; const part = url.searchParams.get('p'); const href = `https://www.bilibili.com/video/${match[1]}/${/^\d+$/.test(part) ? `?p=${part}` : ''}`; return { id: match[1], kind: 'video', url: href }; } if (site.id !== 'zhihu') return null; const article = url.hostname === 'zhuanlan.zhihu.com' && path.match(/^\/p\/(\d+)$/); if (article) return { id: `article:${article[1]}`, kind: 'article', url: url.origin + path }; if (url.hostname !== 'www.zhihu.com') return null; const question = path.match(/^\/question\/(\d+)(?:\/answer\/(\d+))?$/); if (!question) return null; return { id: question[2] ? `answer:${question[2]}` : `question:${question[1]}`, questionId: question[1], kind: question[2] ? 'answer' : 'question', url: url.origin + path, }; } function createWorkspaceAdapter(site, onChange, page = window) { if (site.id === 'douyin') return createDouyinAdapter(onChange, page); const native = site.id === 'bilibili' ? createBilibiliPage(page) : createZhihuPage(page); return createNativeSiteAdapter(site, native, onChange, page); } function siteText(node) { return (typeof node === 'string' ? node : node?.textContent || '').replace(/[\u200b\ufeff]/g, '').replace(/\s+/g, ' ').trim(); } function siteButton(root, label, selector = 'button,[role="button"],a') { if (!root) return null; return [...root.querySelectorAll(selector)].find((node) => !node.disabled && node.getAttribute('aria-disabled') !== 'true' && label.test(node.getAttribute('aria-label') || node.getAttribute('title') || siteText(node)), ) || null; } function siteClick(control) { if (!control?.isConnected || control.disabled || control.getAttribute('aria-disabled') === 'true') return false; control.click(); return true; } function siteImage(node, base) { const image = node?.matches?.('img') ? node : node?.querySelector('img'); return workspaceSiteURL(image?.getAttribute('data-actualsrc') || image?.currentSrc || image?.getAttribute('src') || image?.getAttribute('data-src'), base)?.href || ''; } function siteEditorValue(editor) { return typeof editor?.value === 'string' ? editor.value : editor?.textContent || ''; } function siteReplyHint(hint, author) { if (!author) return false; const match = siteText(hint).match(/^回复\s*(?:给\s*)?[@@]?\s*(.+?)\s*[::]?$/); return match?.[1] === author; } function setSiteEditor(page, editor, text) { if (siteText(siteEditorValue(editor)) === siteText(text)) return true; if (editor.matches('textarea,input')) { const prototype = editor.matches('textarea') ? page.HTMLTextAreaElement.prototype : page.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value').set.call(editor, text); editor.dispatchEvent(new page.InputEvent('input', { bubbles: true, composed: true, inputType: 'insertText', data: text })); return siteText(siteEditorValue(editor)) === siteText(text); } if (!editor.isContentEditable) return false; const transfer = new page.DataTransfer(); transfer.setData('text/plain', text); if (!siteText(siteEditorValue(editor)) && !editor.dispatchEvent(new page.ClipboardEvent('paste', { clipboardData: transfer, bubbles: true, composed: true, cancelable: true, }))) return true; editor.focus({ preventScroll: true }); const selection = editor.getRootNode().getSelection?.() || page.getSelection(); const range = page.document.createRange(); range.selectNodeContents(editor); selection?.removeAllRanges(); selection?.addRange(range); page.document.execCommand('insertText', false, text); return siteText(siteEditorValue(editor)) === siteText(text); } function scrollSiteEnd(page, element) { let scroll = element; while (scroll && scroll !== page.document.body) { if (/auto|scroll|overlay/.test(page.getComputedStyle(scroll).overflowY) && scroll.scrollHeight > scroll.clientHeight + 2) break; scroll = scroll.parentElement; } if (!scroll || scroll === page.document.body) scroll = page.document.scrollingElement; if (!scroll) return false; const bottom = scroll.scrollHeight - scroll.clientHeight; scroll.scrollTop = bottom; scroll.dispatchEvent(new page.Event('scroll', { bubbles: true })); return bottom > 0; } function createNativeSiteAdapter(site, native, onChange, page) { const { document, location } = page; const isTop = page.top === page.self; const cacheKey = `douyin-content-workspace:feed:${site.id}`; const feeds = new Map(); const pending = new Map(); const receipts = new Map(); let state; let current = {}; let comments = new Map(); let observer; let running = false; let timer; let watchdog; let signature = ''; let lastFeed; let savedFingerprint = ''; let lastAction = 0; let refreshRequest; let refreshFailed = false; let sending = false; let previousAddress = ''; let routeSince = 0; let observedRoots = new WeakSet(); function saveFeed(items, route) { if (!isTop || !items.length) return; lastFeed = { items: items.slice(0, 80), channel: route.channel, href: location.href }; const value = JSON.stringify(lastFeed); if (value === savedFingerprint) return; savedFingerprint = value; try { page.sessionStorage.setItem(cacheKey, value); } catch { /* memory cache remains available */ } } function savedFeed() { if (!isTop) return null; if (lastFeed !== undefined) return lastFeed; try { const saved = JSON.parse(page.sessionStorage.getItem(cacheKey) || 'null'); lastFeed = saved && Array.isArray(saved.items) ? saved : null; } catch { lastFeed = null; } return lastFeed; } function read() { const route = native.route(); if (previousAddress !== location.href) { previousAddress = location.href; routeSince = Date.now(); lastAction = 0; refreshRequest = undefined; refreshFailed = false; } let items = []; let active = null; let discussion = {}; let feed = {}; let detail = {}; if (route.kind === 'detail') { const saved = savedFeed(); if (saved?.channel) route.channel = saved.channel; detail = native.detail(route); active = detail.item || null; if (active) discussion = native.comments(detail) || {}; const list = new Map((saved?.items || detail.items || []).map((item) => [item.id, item])); if (active && !list.has(active.id)) list.set(active.id, active); items = [...list.values()]; } else if (route.kind === 'curated' || route.kind === 'search') { feed = native.feed(route); const key = `${route.channel}:${route.query || ''}`; // Keep the existing batch visible until the native control returns new cards. const refreshed = refreshRequest && feed.items?.some((item) => !refreshRequest.before.has(item.id)); const list = (refreshed ? undefined : feeds.get(key)) || new Map(); if (refreshed || (refreshRequest && Date.now() >= refreshRequest.deadline)) { refreshFailed = !refreshed; refreshRequest = undefined; } for (const item of feed.items || []) list.set(item.id, item); if (list.size > 300) list.delete(list.keys().next().value); feeds.set(key, list); if (feeds.size > 8) feeds.delete(feeds.keys().next().value); items = [...list.values()]; saveFeed(items, route); } comments = new Map(); function projectRow({ node, replies = [], ...row }) { comments.set(row.id, { node, row }); return { ...row, replies: replies.map(projectRow) }; } const rows = (discussion.rows || []).map(projectRow); if (observer) { for (const root of discussion.roots || []) { if (!root || observedRoots.has(root)) continue; observer.observe(root, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['disabled', 'aria-disabled', 'contenteditable', 'hidden'] }); observedRoots.add(root); } } for (const [key, submission] of pending) { if (submission.videoId !== active?.id) continue; if (submission.editor.isConnected && submission.editor.getAttribute('contenteditable') === 'false' && siteText(siteEditorValue(submission.editor)) === submission.message) continue; const posted = [...comments.values()].find(({ row }) => !submission.before.has(row.id) && siteText(row.text) === submission.message && (submission.threadId ? row.parentId === submission.threadId : !row.parentId)); if (posted) { receipts.set(key, { key, videoId: active.id, commentId: posted.row.id, threadId: submission.threadId }); if (receipts.size > 24) receipts.delete(receipts.keys().next().value); pending.delete(key); } } if (detail.player !== current.player) current.player?.removeAttribute('data-dw-native-player'); if (running && !detail.player?.hasAttribute('data-dw-native-player')) detail.player?.setAttribute('data-dw-native-player', ''); if (discussion.panel !== current.discussion?.panel) current.discussion?.panel?.removeAttribute('data-dw-native-comments'); if (running && !discussion.panel?.hasAttribute('data-dw-native-comments')) discussion.panel?.setAttribute('data-dw-native-comments', ''); current = { ...detail, feed, discussion }; const loading = route.kind !== 'other' && !active && !items.length && !feed.ended; return { route, items, active, channels: site.channels, compatible: route.kind !== 'other', accountAvatar: native.accountAvatar?.(), loading, mediaKind: active?.kind, nativeDetail: Boolean(detail.player), nativePageReady: !loading, feedState: feed.ended ? 'ended' : feed.loading ? 'loading' : 'ready', canLoadMore: Boolean(items.length && !feed.ended && feed.container), canRefreshFeed: Boolean(feed.refresh), feedRefreshState: refreshRequest ? 'loading' : refreshFailed ? 'retry' : 'ready', nativeLogin: Boolean(detail.login), comments: rows, commentsOpen: Boolean(discussion.panel && (rows.length || discussion.open)), commentsState: rows.length ? 'ready' : discussion.login ? 'login' : discussion.ended ? 'empty' : discussion.panel ? 'loading' : 'closed', canOpenComments: Boolean(discussion.panel || detail.commentsButton), canLoadMoreComments: Boolean(discussion.more || discussion.next), canCompose: Boolean((rows.some((row) => row.canReply || row.replies.some((reply) => reply.canReply)) || native.editor(discussion.panel)) && !detail.login && !discussion.login), confirmedReplies: [...receipts.values()].filter((receipt) => receipt.videoId === active?.id), }; } function update() { timer = undefined; if (!running) return; state = read(); const next = JSON.stringify(state); if (next === signature) return; signature = next; onChange(); } function schedule() { if (running && !timer) timer = page.setTimeout(update, 90); } function start() { if (running) return state; running = true; signature = ''; observedRoots = new WeakSet(); observer = new page.MutationObserver(schedule); observer.observe(document.body || document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['href', 'src', 'hidden', 'aria-busy', 'contenteditable'], }); page.addEventListener('popstate', schedule); page.addEventListener('loadedmetadata', schedule, true); // Feed routes can change through history.replaceState and an open shadow root can hydrate silently. watchdog = page.setInterval(() => { if (location.href !== previousAddress || pending.size || refreshRequest || (!state?.nativePageReady && Date.now() - routeSince < 18000) || (state?.route.kind === 'detail' && !state.commentsOpen)) schedule(); }, 550); update(); return state; } function stop() { if (!running) return; running = false; observer.disconnect(); observer = undefined; page.removeEventListener('popstate', schedule); page.removeEventListener('loadedmetadata', schedule, true); page.clearInterval(watchdog); page.clearTimeout(timer); timer = undefined; refreshRequest = undefined; refreshFailed = false; current.player?.removeAttribute('data-dw-native-player'); current.discussion?.panel?.removeAttribute('data-dw-native-comments'); } function destroy() { stop(); pending.clear(); receipts.clear(); comments.clear(); } function go(value) { const url = workspaceSiteURL(value, location.href); if (!url || !site.hosts.includes(url.hostname)) return false; if (url.href !== location.href) location.assign(url.href); return true; } function open(item, inPlace) { if (!workspaceContent(item?.url, location.href)) return false; return inPlace || go(item.url); } function close() { pause(); if (native.route().kind === 'detail') return go(savedFeed()?.href || site.home); return true; } function pause() { current.player?.querySelector('video')?.pause(); } function more() { if (!state?.canLoadMore || current.feed.loading || refreshRequest || Date.now() - lastAction < 550) return false; lastAction = Date.now(); const loaded = siteClick(current.feed.more) || scrollSiteEnd(page, current.feed.container); schedule(); return loaded; } function refreshFeed() { if (!current.feed.refresh || refreshRequest || Date.now() - lastAction < 550) return false; const before = new Set(current.feed.items.map(({ id }) => id)); if (!siteClick(current.feed.refresh)) return false; lastAction = Date.now(); refreshRequest = { before, deadline: lastAction + 10000 }; refreshFailed = false; schedule(); return true; } function openComments() { if (current.discussion.panel) { current.discussion.panel.scrollIntoView({ block: 'start' }); schedule(); return true; } if (!siteClick(current.commentsButton)) return false; schedule(); return true; } function expandComment(id) { const target = comments.get(id); const opened = Boolean(target && siteClick(native.expandReply(target.node))); if (opened) schedule(); return opened; } function moreComments() { const { next, panel, sentinel } = current.discussion; const loaded = siteClick(next); if (!loaded && sentinel) sentinel.scrollIntoView({ block: 'nearest' }); schedule(); return loaded || Boolean(sentinel) || (panel && scrollSiteEnd(page, panel)); } function waitFor(check, timeout) { const end = Date.now() + timeout; return new Promise((resolve) => { function poll() { const result = check(); if (result || Date.now() >= end || !running) resolve(result); else page.setTimeout(poll, 80); } poll(); }); } async function reply(text, commentId) { const message = siteText(text); const active = state?.active; if (!message || !active || sending) return { ok: false, reason: '评论输入框尚未就绪,草稿已保留。' }; const key = JSON.stringify([active.id, commentId || '', text.trim()]); if (pending.has(key)) return { ok: false, pending: true, reason: '原站还在确认这条回复。' }; const selected = commentId ? comments.get(commentId) : null; if (commentId && !selected) return { ok: false, reason: '原评论已变化,请重新选择回复对象。' }; const address = location.href; const stillCurrent = () => running && location.href === address && state?.active?.id === active.id; const before = new Set(comments.keys()); const threadId = selected?.row.parentId || selected?.row.id; sending = true; try { const prior = native.editor(current.discussion.panel); if (selected && !siteClick(native.replyButton(selected.node))) { return { ok: false, reason: '原站未开放此评论的回复入口,草稿已保留。' }; } let bound; const verifiedEditor = () => native.editor(current.discussion.panel, selected, prior, bound); const editor = await waitFor(() => stillCurrent() && verifiedEditor(), 1600); bound = editor; if (!editor || !setSiteEditor(page, editor, text.trim())) { return { ok: false, reason: '原站回复框尚未就绪,草稿已保留。' }; } const control = await waitFor(() => stillCurrent() && siteText(siteEditorValue(editor)) === message && verifiedEditor() === editor && native.sendButton(editor), 1400); if (!control || !stillCurrent() || verifiedEditor() !== editor || siteText(siteEditorValue(editor)) !== message || !siteClick(control)) { return { ok: false, reason: '原站回复对象或发送状态已变化,草稿已保留。' }; } pending.set(key, { videoId: active.id, before, threadId, message, editor }); if (pending.size > 80) pending.delete(pending.keys().next().value); receipts.delete(key); schedule(); const posted = await waitFor(() => receipts.get(key), 12000); return posted ? { ok: true, posted } : { ok: false, pending: true, reason: '原站还在确认回复,确认后会显示在这里。' }; } finally { sending = false; } } return { start, stop, destroy, read, getSnapshot: () => state || read(), open, close, pause, more, refreshFeed, navigate: (channel) => go(channel?.href), search: (query) => go(site.search(query)), openComments, revealComments: openComments, expandComment, moreComments, expandContent: () => siteClick(current.expandButton), commentPage: () => state?.active?.url, login: () => native.login(), hasPendingReply: (id) => [...pending.values()].some((submission) => submission.videoId === id), reply, }; } function biliFind(root, selector) { if (!root) return null; const direct = root.querySelector(selector); if (direct) return direct; for (const child of root.querySelectorAll('*')) { const match = child.shadowRoot && biliFind(child.shadowRoot, selector); if (match) return match; } return null; } function biliOwner(element, tag) { for (let node = element; node; node = node.parentElement || node.getRootNode().host) { if (node.localName === tag) return node; } return null; } function bilibiliRoute(location) { const path = location.pathname; const item = workspaceContent(location.href); if (item) return { kind: 'detail', channel: 'curated', detailId: item.id, item }; if (location.hostname === 'search.bilibili.com') { return { kind: 'search', channel: 'search', query: new URLSearchParams(location.search).get('keyword') || '' }; } if (/^\/v\/popular(?:\/|$)/.test(path)) return { kind: 'curated', channel: 'popular' }; return path === '/' ? { kind: 'curated', channel: 'curated' } : { kind: 'other', channel: '' }; } function createBilibiliPage(page) { const { document, location } = page; const playerSelector = '#bilibili-player,.bpx-player-container,#bofqi'; const cardsSelector = '.bili-video-card,.video-card,.video-page-card-small,.rank-item'; const replySelector = 'bili-comment-reply-renderer'; const editorSelector = 'textarea,[contenteditable="true"]'; function card(node) { const title = node.querySelector('.bili-video-card__info--tit,.video-name,.title,.info .title,h3'); const links = [...node.querySelectorAll('a[href*="/video/"]')]; const link = (title?.matches('a') ? title : title?.querySelector('a[href]')) || links.at(-1); const item = workspaceContent(link?.getAttribute('href'), location.href); const name = siteText(title) || siteText(link?.getAttribute('title')) || siteText(link); if (!item || !name) return null; const author = node.querySelector('.bili-video-card__info--author,.up-name,.name'); return { ...item, title: name, author: siteText(author) || siteText(node.querySelector('a[href*="space.bilibili.com"]')), time: siteText(node.querySelector('.bili-video-card__info--date,.pubdate')).replace(/^·\s*/, ''), cover: siteImage(node.querySelector('picture,.bili-video-card__cover,.cover') || node, location.href), duration: siteText(node.querySelector('.bili-video-card__stats__duration,.duration')), }; } function cards(root) { return [...root.querySelectorAll(cardsSelector)].map(card).filter(Boolean); } function feed(current) { const root = document.querySelector(current.kind === 'search' ? '.search-page,.search-content,main' : current.channel === 'popular' ? '.popular-list,.popular-container,main' : '.feed2,.bili-feed4,.bili-feed,.recommended-container,main') || document.body; const refresh = current.channel === 'curated' ? document.querySelector('button.roll-btn') || siteButton(document, /^换\s*一\s*换$/) : null; const more = refresh || siteButton(root, /^(?:加载更多|下一页|查看更多)$/); return { items: root ? cards(root) : [], container: root, more, refresh, ended: Boolean(root?.querySelector('.no-more,.search-empty')) }; } function detail(current) { const player = document.querySelector(playerSelector); const title = document.querySelector('h1.video-title,h1'); const owner = document.querySelector('.up-info-container,.up-info--right,.up-info'); const author = owner?.querySelector('.up-name,.up-info--name') || document.querySelector('.up-name'); const related = document.querySelector('#reco_list,.recommend-list-v1,.recommend-list'); return { player, item: title && { ...current.item, title: siteText(title), author: siteText(author), avatar: siteImage(owner, location.href), time: siteText(document.querySelector('.pubdate-text,.video-info-detail .pubdate')), cover: workspaceSiteURL(document.querySelector('meta[property="og:image"]')?.content, location.href)?.href || '', }, items: related ? cards(related) : [], login: [...document.querySelectorAll('.bili-mini-login')].some((node) => node.getClientRects().length), }; } function replyButton(node) { const root = node?.shadowRoot; const actions = root?.querySelector('bili-comment-action-buttons-renderer')?.shadowRoot || root; return actions?.querySelector('#reply button,button#reply') || siteButton(actions, /^回复$/); } function commentRecord(node, parentId = '') { const root = node?.shadowRoot; if (!root) return null; const data = node.data; const header = root.querySelector('#header'); const authorLink = biliFind(header || root, 'a[href*="space.bilibili.com"], .user-name, #user-name'); const author = siteText(data?.member?.uname || authorLink); const content = root.querySelector('#content'); const rich = content?.querySelector('bili-rich-text,bili-comment-rich-text')?.shadowRoot; const text = siteText(data?.content?.message || rich?.querySelector('#contents,#text') || content); if (!text && !author) return null; const time = siteText(biliFind(root, '#pubdate,.reply-time,.pubdate')) || (data?.ctime ? new Date(data.ctime * 1000).toLocaleDateString('zh-CN') : ''); const id = String(data?.rpid_str || node.getAttribute('data-reply-id') || [parentId, author, time, text].join('|')); return { id, author, text, time, parentId, node, avatar: workspaceSiteURL(data?.member?.avatar, location.href)?.href || siteImage(root.querySelector('#user-avatar'), location.href), likes: data?.like ? String(data.like) : '', canReply: Boolean(replyButton(node)), }; } function threadFor(node) { return biliOwner(node, 'bili-comment-thread-renderer'); } function expandReply(node) { const root = threadFor(node)?.shadowRoot; const replies = root?.querySelector('bili-comment-replies-renderer')?.shadowRoot || root; const trigger = replies?.querySelector('#view-more bili-text-button,#more bili-text-button'); return trigger?.shadowRoot?.querySelector('button') || trigger || replies?.querySelector('#view-more,#more') || siteButton(replies, /^(?:展开|查看|共|更多).*(?:条|回复)|^展开回复$/, 'button,a,[role="button"],.view-more,#view-more'); } function comments() { const panel = document.querySelector('bili-comments,#commentapp'); const host = panel?.matches('bili-comments') ? panel : panel?.querySelector('bili-comments'); const root = host?.shadowRoot; if (!root) return { panel }; const roots = [root]; const rows = []; for (const thread of root.querySelectorAll('bili-comment-thread-renderer')) { const shadow = thread.shadowRoot; const node = shadow?.querySelector('bili-comment-renderer'); const item = commentRecord(node); if (!item) continue; if (thread.data?.rpid_str) item.id = String(thread.data.rpid_str); roots.push(shadow, node.shadowRoot); const repliesRoot = shadow.querySelector('bili-comment-replies-renderer')?.shadowRoot || shadow; const replies = [...repliesRoot.querySelectorAll(replySelector)].map((child) => commentRecord(child, item.id)).filter(Boolean); for (const child of replies) roots.push(child.node.shadowRoot); const expand = expandReply(node); const count = Number(siteText(repliesRoot.querySelector('#view-more,#more') || expand).match(/\d+/)?.[0]) || Number(node.data?.rcount) || replies.length; rows.push({ ...item, replies, replyCount: count || Number(Boolean(expand)), canExpand: Boolean(expand) }); roots.push(repliesRoot); } const ended = /没有更多|全部加载|暂无评论|还没有评论/.test(siteText(root.querySelector('#end'))) || /^(?:暂无评论|还没有评论)$/.test(siteText(root.querySelector('#contents'))); return { panel: host, rows, roots, open: rows.length > 0 || ended, ended, more: !ended, next: siteButton(root, /^(?:加载更多|查看更多评论|下一页)$/), sentinel: root.querySelector('#end'), login: [...document.querySelectorAll('.bili-mini-login')].some((node) => node.getClientRects().length), }; } function editor(panel, selected, prior, bound) { const root = panel?.shadowRoot; if (!root) return null; if (!selected) return biliFind(root.querySelector('#header') || root, editorSelector); const thread = threadFor(selected.node); const host = thread?.shadowRoot; const box = biliFind(host, 'bili-comment-box'); const edit = biliFind(box?.shadowRoot || host, editorSelector); if (!edit || !selected.node.isConnected) return null; const hint = siteText(edit.getAttribute('placeholder') || edit.getAttribute('data-placeholder') || biliFind(box?.shadowRoot, '#placeholder')?.textContent); if (/回复/.test(hint)) { // Some builds remove the hint after typing. Keep the same verified DOM editor in that case. return siteReplyHint(hint, selected.row.author) ? edit : null; } return edit === bound || (edit !== prior && !selected.row.parentId) ? edit : null; } function sendButton(edit) { const box = biliOwner(edit, 'bili-comment-box'); const root = box?.shadowRoot || edit.getRootNode(); const control = biliFind(root, '#pub button,#publish button,#send button,button#send,button#publish,[data-e2e="comment-send"]') || siteButton(root, /^(?:发布|发送)$/); return control && !control.disabled && control.getAttribute('aria-disabled') !== 'true' ? control : null; } function login() { return siteClick(document.querySelector('.header-login-entry,.right-entry__outside.go-login-btn') || siteButton(document, /^登录$/)); } const accountAvatar = () => siteImage(document.querySelector('.header-avatar-wrap,.bili-header__avatar'), location.href); return { route: () => bilibiliRoute(location), feed, detail, comments, expandReply, replyButton, editor, sendButton, login, accountAvatar }; } function zhihuReadingHtml(content, base) { if (!content) return ''; const doc = content.ownerDocument; const result = doc.createElement('div'); const allowed = new Set(['P','H1','H2','H3','H4','H5','BR','HR','B','STRONG','I','EM','S','DEL','U','SUP','SUB', 'OL','UL','LI','BLOCKQUOTE','PRE','CODE','A','IMG','FIGURE','FIGCAPTION','TABLE','THEAD','TBODY','TR','TH','TD']); const discard = new Set(['SCRIPT','STYLE','NOSCRIPT','IFRAME','OBJECT','EMBED','FORM','INPUT','BUTTON','SVG','TEMPLATE']); function copy(node, parent) { if (node.nodeType === 3) { parent.append(doc.createTextNode(node.textContent)); return; } if (node.nodeType !== 1 || node.namespaceURI !== 'http://www.w3.org/1999/xhtml' || discard.has(node.tagName) || node.hidden || node.getAttribute('aria-hidden') === 'true') return; let destination = parent; if (allowed.has(node.tagName)) { const clean = doc.createElement(node.tagName.toLowerCase()); if (node.tagName === 'IMG') { const url = workspaceSiteURL(node.getAttribute('data-actualsrc') || node.getAttribute('src') || node.getAttribute('data-src'), base); if (!url) return; clean.src = url.href; clean.alt = node.getAttribute('alt') || ''; clean.loading = 'lazy'; clean.referrerPolicy = 'no-referrer'; } else if (node.tagName === 'A') { const url = workspaceSiteURL(node.getAttribute('href'), base); if (url) { clean.href = url.href; clean.target = '_blank'; clean.rel = 'noopener noreferrer'; } } parent.append(clean); destination = clean; } for (const child of node.childNodes) copy(child, destination); } for (const child of content.childNodes) copy(child, result); return result.innerHTML; } function createZhihuPage(page) { const { document, location } = page; const articleSelector = '.Post-Main,.Post-Content,.ArticleItem,main,article'; const answerSelector = '.AnswerItem,[data-za-detail-view-element_name="AnswerItem"]'; const editorSelector = 'textarea,[contenteditable="true"]'; const rowSelector = '.CommentItemV2,.CommentItem,[data-comment-id],[id^="comment-"]'; function route() { const path = location.pathname.replace(/\/$/, '') || '/'; const item = workspaceContent(location.href); if (item) return { kind: 'detail', channel: 'curated', detailId: item.id, item }; if (location.hostname !== 'www.zhihu.com') return { kind: 'other', channel: '' }; if (path === '/search') { return { kind: 'search', channel: 'search', query: new URLSearchParams(location.search).get('q') || '' }; } if (path === '/hot' || path === '/') return { kind: 'curated', channel: path === '/hot' ? 'popular' : 'curated' }; return { kind: 'other', channel: '' }; } function cardMetadata(node) { const raw = node.getAttribute('data-zop') || node.querySelector('.ContentItem[data-zop]')?.getAttribute('data-zop'); try { return JSON.parse(raw || '{}') || {}; } catch { return {}; } } function authorInfo(node, metadata) { const profile = node.querySelector('.AuthorInfo,.AuthorInfo-head'); const names = profile?.querySelectorAll('[itemprop="name"],.AuthorInfo-name,.UserLink-link,a[href*="/people/"]') || []; return { author: [...names].map((name) => siteText(name.getAttribute('content') || name)).find(Boolean) || siteText(node.querySelector('.AuthorInfo-name')) || siteText(metadata.authorName), avatar: siteImage((profile || node).querySelector('.AuthorInfo-avatarWrapper,.Avatar'), location.href), }; } function contentLink(node, questionId, metadata = cardMetadata(node)) { const links = [ ...node.querySelectorAll('a[href*="/question/"],a[href*="zhuanlan.zhihu.com/p/"],a[href^="/p/"]'), ...node.querySelectorAll('meta[itemprop="url"],link[itemprop="url"]'), ]; const targets = links.map((link) => workspaceContent(link.getAttribute('href') || link.getAttribute('content'), location.href)) .filter(Boolean); const full = targets.find(({ kind }) => kind !== 'question'); if (full) return full; const question = questionId || targets[0]?.questionId; if (question && /^\d+$/.test(metadata.itemId) && (metadata.type === 'answer' || node.matches(answerSelector))) { return workspaceContent(`/question/${question}/answer/${metadata.itemId}`, 'https://www.zhihu.com/'); } return targets[0] || null; } function card(node, questionId) { const metadata = cardMetadata(node); const identity = contentLink(node, questionId, metadata); if (!identity) return null; const title = siteText(node.querySelector('.ContentItem-title,.HotItem-title,h2,h3')); if (!title && !questionId) return null; return { ...identity, title, ...authorInfo(node, metadata), summary: siteText(node.querySelector('.RichContent-inner,.HotItem-excerpt,.RichContent')).slice(0, 250), time: siteText(node.querySelector('.ContentItem-time,time')), cover: siteImage(node.querySelector('.RichContent-cover,.HotItem-img'), location.href), }; } function feed(current) { const root = document.querySelector(current.kind === 'search' ? '.SearchResult-CardList,.SearchMain,main' : current.channel === 'popular' ? '.HotList-list,.HotList,main' : '.Topstory-recommend,.Topstory-main,main') || document.body; const items = [...(root?.querySelectorAll(current.channel === 'popular' ? '.HotItem' : '.TopstoryItem,.SearchResult-Card,.List-item,.ContentItem') || [])].map((node) => card(node)).filter(Boolean); return { items, container: root, more: siteButton(root, /^(?:加载更多|查看更多|下一页)$/), ended: Boolean(root?.querySelector('.SearchResult-Empty,.List-end')) || (current.channel === 'popular' && items.length > 0), }; } function detail(current) { const questionTitle = document.querySelector('.QuestionHeader-title,h1.Post-Title,h1'); const answers = [...document.querySelectorAll(answerSelector)]; const matching = answers.find((item) => contentLink(item, current.item.questionId)?.id === current.detailId); const anchor = current.item.kind === 'article' ? document.querySelector(articleSelector) || document.querySelector('main') : matching || (current.item.kind === 'question' || answers.length === 1 ? answers[0] : null); if (!questionTitle || !anchor) return {}; const body = anchor.querySelector('.RichContent-inner .RichText,.Post-RichText,.RichContent-inner,.RichText.ztext'); const expandButton = anchor.querySelector('.ContentItem-expandButton') || siteButton(anchor, /^(?:展开阅读全文|阅读全文|展开阅读)$/); const commentButton = anchor.querySelector('.BottomActions-CommentBtn') || siteButton(anchor, /^(?:\d[\d,.万 ]*\s*条?\s*评论|添加评论|评论|查看(?:全部)?评论)$/); const item = { ...current.item, title: siteText(questionTitle), ...authorInfo(anchor, cardMetadata(anchor)), time: siteText(anchor.querySelector('.ContentItem-time,.Post-Time,time')), bodyHtml: zhihuReadingHtml(body, location.href), canExpandContent: Boolean(expandButton), otherAnswers: answers.filter((answer) => answer !== anchor) .map((answer) => card(answer, current.item.questionId)).filter(Boolean).slice(0, 24), }; return { item, anchor, expandButton, commentsButton: commentButton, login: Boolean(document.querySelector('.signFlowModal,.Modal .SignFlow')) }; } function replyButton(row) { return [...row.querySelectorAll('button,[role="button"]')].find((button) => (!button.closest(rowSelector) || button.closest(rowSelector) === row) && /^(?:回复|回复评论)$/.test(siteText(button.getAttribute('aria-label') || button))); } function expandReply(node) { return siteButton(node, /^(?:查看|展开|更多|加载).*(?:回复|评论)|^共\s*\d+\s*条回复$/); } function comments(detail) { const panel = detail.anchor?.querySelector('.Comments-container,.CommentsV2,[data-comment-list],.css-18ld3w0') || [...document.querySelectorAll('[role="dialog"],.Modal,.css-16zdamy')].find((candidate) => !candidate.closest('[hidden],[aria-hidden="true"]') && candidate.querySelector('.CommentContent,.CommentItemV2,[data-comment-id]')); if (!panel) return {}; const elements = new Set(); for (const body of panel.querySelectorAll('.CommentContent,[data-comment-body]')) { let row = body.closest(rowSelector); if (!row) { // Some article pages render each comment in an anonymous wrapper. for (let candidate = body.parentElement; candidate && candidate !== panel; candidate = candidate.parentElement) { if (candidate.querySelectorAll('.CommentContent').length !== 1) break; if (candidate.querySelector('a[href*="/people/"]')) { row = candidate; break; } } } if (row) elements.add(row); } const byNode = new Map(); const rows = []; for (const row of elements) { let ancestor = row.parentElement; while (ancestor && ancestor !== panel && !elements.has(ancestor)) ancestor = ancestor.parentElement; const parent = byNode.get(ancestor); const author = siteText(row.querySelector('.CommentItemV2-meta .UserLink-link,.UserLink-link,a[href*="/people/"]')); const body = siteText(row.querySelector('.CommentContent,[data-comment-body]')); if (!body) continue; const time = siteText(row.querySelector('.CommentItemV2-time,time')); const id = row.getAttribute('data-comment-id') || row.id || [parent?.id, author, time, body].join('|'); const expand = expandReply(row); const comment = { id, node: row, author, text: body, time, parentId: parent?.id || '', avatar: siteImage(row.querySelector('.Avatar,.UserLink') || row, location.href), canReply: Boolean(replyButton(row)), canExpand: Boolean(expand), replyCount: Number(siteText(expand).match(/\d+/)?.[0]) || Number(Boolean(expand)), replies: [], }; byNode.set(row, comment); if (parent) parent.replies.push(comment); else rows.push(comment); } const next = siteButton(panel, /^(?:下一页|加载更多评论|查看更多评论)$/); return { panel, rows, next, open: true, ended: /暂无评论|还没有评论/.test(siteText(panel)), login: Boolean(panel.querySelector('.SignFlow')), }; } function editor(panel, selected, prior, bound) { if (!panel) return null; const candidates = [...panel.querySelectorAll(editorSelector)].filter((node) => !node.closest('[hidden],[aria-hidden="true"]') && !node.disabled && !node.readOnly); if (!selected) return candidates.find((node) => !node.closest(rowSelector) && !/回复/.test(node.getAttribute('placeholder') || node.getAttribute('data-placeholder') || '')) || null; const author = selected.row.author; for (const node of candidates) { const hint = node.getAttribute('placeholder') || node.getAttribute('data-placeholder') || node.getAttribute('aria-label') || node.closest('.CommentEditorV2,.CommentEditor')?.querySelector('[data-placeholder]')?.getAttribute('data-placeholder') || ''; const owner = node.closest(rowSelector); if (/回复/.test(hint) && !siteReplyHint(hint, author)) continue; if (owner === selected.node || selected.node.contains(node) || (node === bound && selected.node.isConnected) || (node !== prior && siteReplyHint(hint, author))) return node; } return null; } function sendButton(node) { return siteButton(node.closest('.CommentEditorV2,.CommentEditor,form,[data-comment-editor]') || node.parentElement?.parentElement, /^(?:发布|发送|评论)$/); } function login() { const button = siteButton(document, /^(?:登录|去登录|立即登录)$/); if (!siteClick(button)) location.assign('https://www.zhihu.com/signin'); return true; } const accountAvatar = () => siteImage(document.querySelector('.AppHeader-profileAvatar,.AppHeader-profile'), location.href); return { route, feed, detail, comments, expandReply, replyButton, editor, sendButton, login, accountAvatar }; } function createUpstreamWecomPresentation(document, bridge) { const window = document.defaultView; const { applyListNavDom, bindChatPanelEvents, bindListPanelClicks, bindOrgChip, bindRailAvatarNotif, bindSearchBox, bindUserCardEvents, bindWatermarkSettings, checkForScriptUpdate, convCategoryTag, disguiseAvatarForTopic, disguiseGridAvatar, ensureEditDialog, ensureMaskAvatarToggle, formatTime, fullAvatarUrl, getThemeMode, getWatermarkSettings, groupAvatarHtml, isDarkMode, isGridMaskTopic, isGroupConversation, isMaskAvatar, isMyPost, isNav2Open, likedPosts, loadMoreList, navigateInApp, normalizeUsername, renderOrgChip, renderWatermark, replyReferenceInfo, setNav2Open, setThemeMode, syncRail, topicHref, userCardAttributes, wireComposeButton, } = bridge; const STYLE_ID = "linuxdo-wecom-theme"; const ROOT_CLASS = "wecom-im-theme"; const LOCK_CLASS = "wecom-locked"; // 仅三栏路由挂载:隐藏原生主内容 const RAIL_WIDTH = 162; // 企业微信 5.x 展开导航 const LIST_WIDTH = 304; // 会话列表 const NAV2_WIDTH = 240; // 展开栏(原生侧栏原样搬入,默认收起) const STRIP_WIDTH = 0; // 企业微信布局无窄条 const MEMBER_WIDTH = 192; // 群成员栏 const TITLEBAR_HEIGHT = 0; // 企业微信经典布局无全局顶栏 const WATERMARK_TILE_WIDTH = 300; const WATERMARK_TILE_HEIGHT = 160; const WATERMARK_MAX_LENGTH = 48; const THEME_MODE_VALUES = Object.freeze(["light", "dark", "system"]); const DEFAULT_THEME_MODE = "light"; const AVATAR_COLORS = [ "#267EF0", "#07C160", "#5B8FF9", "#8B6CFF", "#10B981", "#E6A23C", "#61758A", "#E85D5D" ]; const ICONS = { msg: ``, doc: ``, work: ``, book: ``, meet: ``, disk: ``, cal: ``, todo: ``, ding: ``, proj: ``, mail: ``, apps: ``, build: ``, more: ``, clock: ``, grid: ``, spark: ``, phone: ``, plus: ``, mute: ``, bell: ``, users: ``, win: ``, gear: ``, emoji: ``, like: ``, cut: ``, folder: ``, pic: ``, collect: ``, file: ``, bolt: ``, cam: ``, redpack: ``, dots: ``, expand: ``, search: ``, refresh: ``, external: ``, reply: ``, edit: ``, bookmark: ``, menu: ``, chevronDown: ``, chevronUp: ``, compose: ``, filter: ``, disguise: ``, aitable: ``, aimic: ``, monitor: ``, at: ``, moon: ``, sun: ``, monitorSmall: `` }; ICONS.chat = ICONS.msg; ICONS.list = ICONS.msg; ICONS.calendar = ICONS.cal; ICONS.worktable = ICONS.work; ICONS.cloud = ICONS.doc; ICONS.wiki = ICONS.doc; ICONS.task = ICONS.todo; ICONS.contacts = ICONS.book; ICONS.project = ICONS.proj; ICONS.watermark = ``; const RAW_CSS = String.raw` /* ---------- Token ---------- */ .${ROOT_CLASS} { color-scheme: light !important; --wc-blue: #1A87FF; --wc-blue-hover: #0A6FE0; --wc-blue-soft: #E8F3FF; --wc-blue-chip: #D6EBFF; --wc-title: #1A87FF; --wc-accent: #1A87FF; --wc-accent-soft: #E8F3FF; --wc-nav2-bg: #FFFFFF; --wc-nav2-border: #E6E8EB; --wc-text: #1A1D24; --wc-text-2: #4A4F5C; --wc-text-3: #8A8F99; --wc-text-4: #B0B4BE; --wc-bg: #FFFFFF; --wc-chat-bg: #F5F7FB; --wc-hover: #ECF0F7; --wc-active: #E4EAF5; --wc-bubble-other: #FFFFFF; --wc-bubble-me: #D4E5FF; --wc-border: #E6E8EB; --wc-border-strong: #D5D8DE; --wc-danger: #FF4D4F; --wc-rail-bg: #F3F4F6; --wc-strip-bg: transparent; --wc-nav: ${RAIL_WIDTH}px; --wc-nav2w: 0px; --wc-strip: ${STRIP_WIDTH}px; --wc-list: ${LIST_WIDTH}px; --wc-header-h: ${TITLEBAR_HEIGHT}px; --wc-font: "PingFang SC", "Microsoft YaHei", "Helvetica Neue", Inter, -apple-system, BlinkMacSystemFont, sans-serif; --radius: 8px; --primary: var(--wc-text); --primary-medium: var(--wc-text-2); --primary-low: var(--wc-text-3); --secondary: var(--wc-bg); --tertiary: var(--wc-accent); --header_background: #FFFFFF; --header_primary: var(--wc-text); --d-hover: var(--wc-hover); } /* 整站颜色模式:由运行时同步 html/body 与站点 stylesheet */ html.${ROOT_CLASS}, html.${ROOT_CLASS} body { color-scheme: light !important; } /* ---------- 字体与基础 ---------- */ .${ROOT_CLASS} body { font-family: var(--wc-font) !important; } /* 站点无全局 border-box:自绘面板统一盒模型,否则 padding 会加宽导致互相堆叠 */ .wecom-rail, .wecom-rail *, .wecom-strip, .wecom-strip *, .wecom-list-panel, .wecom-list-panel *, .wecom-chat-panel, .wecom-chat-panel *, .wecom-mode-fab { box-sizing: border-box; } /* ---------- 顶栏视觉隐藏(保留 DOM,供 user-menu 挂载/点击) ---------- */ .${ROOT_CLASS} .d-header-wrap, .${ROOT_CLASS} .d-header { position: fixed !important; left: 0 !important; top: 0 !important; width: 0 !important; height: 0 !important; max-width: 0 !important; max-height: 0 !important; overflow: hidden !important; opacity: 0 !important; pointer-events: none !important; margin: 0 !important; padding: 0 !important; border: none !important; clip: rect(0, 0, 0, 0) !important; z-index: -1 !important; } /* 允许脚本对用户按钮做 programmatic click */ .${ROOT_CLASS} #current-user, .${ROOT_CLASS} #toggle-current-user, .${ROOT_CLASS} .header-dropdown-toggle.current-user { pointer-events: auto !important; } .${ROOT_CLASS} #main-outlet-wrapper { padding-top: var(--wc-header-h) !important; margin-left: calc(var(--wc-nav) + var(--wc-nav2w) + var(--wc-strip)) !important; } /* ---------- 展开栏:原生侧栏原样搬入(内容与文案不变,≡ 滑出) ---------- */ .${ROOT_CLASS}.wecom-nav2-open { --wc-nav2w: ${NAV2_WIDTH}px; } html.${ROOT_CLASS} body .sidebar-wrapper { display: block !important; position: fixed; left: var(--wc-nav); top: 0; bottom: 0; width: ${NAV2_WIDTH}px !important; background-color: #FFFFFF !important; background-image: none !important; backdrop-filter: none !important; box-shadow: none !important; border-right: 1px solid var(--wc-border); z-index: 600; transform: translateX(-105%); visibility: hidden; transition: transform 0.18s ease, visibility 0.18s; /* 站点可能是深色方案:强制企业微信浅色调色板 */ --primary: var(--wc-text); --primary-medium: var(--wc-text-2); --primary-low: var(--wc-text-3); --primary-low-mid: #BBBFC4; --primary-very-low: #F0F2F5; --primary-50: #F5F6F7; --primary-100: #EBEDEF; --primary-200: #E8E9EB; --primary-300: #DEE0E3; --secondary: #FFFFFF; --tertiary: var(--wc-accent); --quaternary: var(--wc-accent); --d-hover: var(--wc-hover); --d-sidebar-background: #FFFFFF; --d-sidebar-border-color: var(--wc-border); color: var(--wc-text); } /* 可能盖住白底的子层/伪层一律透明 */ html.${ROOT_CLASS} body .sidebar-wrapper *, html.${ROOT_CLASS} body .sidebar-wrapper *::before, html.${ROOT_CLASS} body .sidebar-wrapper *::after { background-color: transparent !important; background-image: none !important; backdrop-filter: none !important; } .${ROOT_CLASS}.wecom-nav2-open .sidebar-wrapper { transform: none; visibility: visible; } /* * 锁定态把 #main-outlet-wrapper 设成 pointer-events:none, * 而 Discourse 的 .sidebar-wrapper 在其内部 → 展开后只能看不能点。 * 侧栏自身及子元素显式恢复点击。 */ .${ROOT_CLASS} .sidebar-wrapper, .${ROOT_CLASS} .sidebar-wrapper * { pointer-events: auto !important; } html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-container { height: 100%; border-right: none; } /* 侧栏内部元素统一到企业微信浅色观感 */ .${ROOT_CLASS} .sidebar-wrapper .sidebar-section-header, .${ROOT_CLASS} .sidebar-wrapper .sidebar-section-header-text { color: var(--wc-text-3) !important; } .${ROOT_CLASS} .sidebar-wrapper .sidebar-section-link { color: var(--wc-text-2) !important; border-radius: 8px; transition: background-color 0.15s; } html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-section-link:hover { background-color: var(--wc-hover) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-section-link.active { background-color: var(--wc-active) !important; color: var(--wc-accent) !important; } .${ROOT_CLASS} .sidebar-wrapper .sidebar-section-content svg, .${ROOT_CLASS} .sidebar-wrapper .sidebar-section-link-prefix { color: var(--wc-text-3); } /* 底部黑色聊天抽屉与侧栏底栏(用户栏)会破坏三栏观感,隐藏(不限于 sidebar 内部) */ .${ROOT_CLASS} .chat-drawer-container, .${ROOT_CLASS} #chat-drawer, .${ROOT_CLASS} .chat-drawer, .${ROOT_CLASS} [class*="sidebar-footer"], .${ROOT_CLASS} [id*="chat-drawer"] { display: none !important; } /* ---------- 窄图标条:假 icon(纯装饰) ---------- */ .wecom-strip { display: none !important; } .wecom-strip-item { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: var(--wc-text-2); position: relative; flex-shrink: 0; cursor: default; user-select: none; } .wecom-strip-item svg { width: 17px; height: 17px; } .wecom-strip-badge { position: absolute; top: -4px; right: -10px; min-width: 14px; height: 14px; padding: 0 4px; background: var(--wc-danger); color: #fff; font-size: 9px; line-height: 14px; text-align: center; border-radius: 7px; font-weight: 500; } /* * 原生用户菜单必须留在 .user-menu-dropdown-wrapper 内: * Discourse 用该父层判断“点击菜单内/外”,拆出子节点会让所有菜单项在 * pointerdown 阶段被误判为外部点击。打开时仅解除顶栏祖先的裁剪。 */ .${ROOT_CLASS}.wecom-notif-open .d-header-wrap, .${ROOT_CLASS}.wecom-notif-open .d-header { overflow: visible !important; opacity: 1 !important; visibility: visible !important; pointer-events: none !important; clip: auto !important; z-index: 450 !important; } .${ROOT_CLASS}.wecom-notif-open .user-menu-dropdown-wrapper { overflow: visible !important; pointer-events: none !important; visibility: visible !important; } .${ROOT_CLASS}.wecom-notif-open .d-header .contents > :not(.panel), .${ROOT_CLASS}.wecom-notif-open .d-header .panel > :not(.user-menu-dropdown-wrapper) { visibility: hidden !important; pointer-events: none !important; } /* 左侧栏头像通知:仅在 html.wecom-notif-open 时显示,避免关不掉 */ .${ROOT_CLASS} .user-menu.wecom-user-menu-float, .${ROOT_CLASS} .user-menu.revamped.menu-panel.wecom-user-menu-float, .${ROOT_CLASS} .user-menu.menu-panel.wecom-user-menu-float { display: none !important; opacity: 0 !important; visibility: hidden !important; pointer-events: none !important; } .${ROOT_CLASS}.wecom-notif-open .user-menu.wecom-user-menu-float, .${ROOT_CLASS}.wecom-notif-open .user-menu.revamped.menu-panel.wecom-user-menu-float, .${ROOT_CLASS}.wecom-notif-open .user-menu.menu-panel.wecom-user-menu-float { display: block !important; position: fixed !important; left: 8px !important; top: calc(var(--wc-header-h) + 4px) !important; right: auto !important; bottom: auto !important; width: 320px !important; max-width: min(320px, calc(100vw - 20px)) !important; max-height: calc(100vh - 28px) !important; margin: 0 !important; z-index: 450 !important; box-shadow: 0 8px 28px rgba(31, 35, 41, 0.18) !important; border-radius: 8px !important; overflow: auto !important; pointer-events: auto !important; opacity: 1 !important; visibility: visible !important; background: #fff !important; color: var(--wc-text) !important; clip: auto !important; } /* ---------- 最左:企业微信文字导航栏(浅色渐变;仅「更多」可点,展开原生侧栏) ---------- */ /* ---------- 顶部浅色 titlebar ---------- */ .wecom-titlebar { position: fixed; left: 0; right: 0; top: 0; height: var(--wc-header-h); background: linear-gradient(90deg, #D5E0F8 0%, #DCE4F9 100%); color: var(--wc-text); display: flex; align-items: center; padding: 0 10px; z-index: 500; font-family: var(--wc-font); user-select: none; gap: 8px; } /* 顶栏左侧:当前用户头像(沿用 rail-avatar 类名,复用通知菜单逻辑) */ .wecom-titlebar .me-chip { position: relative; width: 26px; height: 26px; flex-shrink: 0; } .wecom-titlebar .wecom-rail-avatar { width: 26px; height: 26px; border-radius: 6px; font-size: 11px; } .wecom-titlebar .wecom-rail-avatar-badge { top: -5px; right: -7px; min-width: 14px; height: 14px; padding: 0 3px; font-size: 9px; line-height: 14px; border-radius: 7px; } .wecom-titlebar .title-search { margin: 2px auto 0; width: min(420px, 36vw); height: 26px; border-radius: 13px; background: #EFF1FB; display: flex; align-items: center; gap: 6px; padding: 0 12px; color: var(--wc-text-3); font-size: 12px; position: relative; } .wecom-titlebar .title-search form { display: flex; align-items: center; gap: 6px; width: 100%; margin: 0; } .wecom-titlebar .title-search svg { opacity: .9; flex-shrink: 0; color: var(--wc-text-3); width: 14px; height: 14px; } .wecom-titlebar .title-search input { flex: 1; min-width: 0; border: 0; outline: none; background: transparent; color: var(--wc-text); font-size: 12px; font-family: var(--wc-font); text-align: center; line-height: 26px; padding: 0; height: 100%; } .wecom-titlebar .title-search input::placeholder { color: var(--wc-text-4); text-align: center; } .wecom-titlebar .title-actions { display: flex; align-items: center; gap: 6px; margin-left: 8px; flex-shrink: 0; } .wecom-titlebar .t-btn { width: 28px; height: 28px; border: 0; background: transparent; color: var(--wc-text-2); border-radius: 6px; cursor: pointer; display: grid; place-items: center; padding: 0; position: relative; } .wecom-titlebar .t-btn:hover { background: rgba(0,0,0,.05); } .wecom-titlebar .t-btn .dot { position: absolute; top: 4px; right: 4px; width: 6px; height: 6px; background: var(--wc-danger); border-radius: 50%; } .wecom-titlebar .t-btn.ai { width: 24px; height: 24px; border-radius: 50%; color: #fff; background: conic-gradient(from 210deg, #7C5CFF, #1A87FF, #00C56C, #FFB020, #7C5CFF); } .wecom-titlebar .t-btn.ai svg { width: 12px; height: 12px; } .wecom-titlebar .t-btn svg { width: 16px; height: 16px; } .wecom-rail { position: fixed; left: 0; top: var(--wc-header-h); bottom: 0; width: var(--wc-nav); background: linear-gradient(180deg, #D5E0F8 0%, #DCE4F9 100%); display: flex; flex-direction: column; align-items: center; padding: 6px 0 8px; z-index: 350; font-family: var(--wc-font); /* 不能 overflow:hidden:顶部组织 chip 的名称要溢出到中栏头部区 */ overflow: visible; } .wecom-rail-head { width: 100%; flex-shrink: 0; padding: 2px 8px 8px; position: relative; z-index: 360; } .wecom-rail-org-chip { display: flex; align-items: center; gap: 6px; white-space: nowrap; cursor: pointer; border-radius: 8px; padding: 2px 4px; margin-left: -4px; } .wecom-rail-org-chip:hover { background: rgba(255,255,255,.6); } .wecom-rail-org-chip:hover .wecom-rail-org-name { color: var(--wc-blue); } .wecom-rail-org-logo img { width: 100%; height: 100%; object-fit: cover; border-radius: 6px; } .wecom-rail-org-logo { width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0; background: #2F88FF; color: #fff; display: grid; place-items: center; font-size: 12px; font-weight: 700; } .wecom-rail-org-name { font-size: 13px; font-weight: 600; color: var(--wc-text); } .wecom-rail-org-chip > svg { width: 10px; height: 10px; color: var(--wc-text-3); flex-shrink: 0; } /* 头像基础样式(现挂在 titlebar 左侧,类名保留以复用通知逻辑) */ .wecom-rail-avatar { width: 36px; height: 36px; border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 13px; font-weight: 700; background: #F3A23A; cursor: pointer; } .wecom-rail-avatar img { width: 100%; height: 100%; object-fit: cover; pointer-events: none; } .wecom-rail-avatar.is-notif-pinned { box-shadow: 0 0 0 2px #fff, 0 0 0 4px var(--wc-accent); } .wecom-rail-avatar-badge { position: absolute; top: -4px; right: -6px; min-width: 16px; height: 16px; padding: 0 4px; background: var(--wc-danger); color: #fff; font-size: 10px; font-weight: 700; line-height: 16px; text-align: center; border-radius: 8px; box-shadow: 0 0 0 2px #fff; } .wecom-rail-search { display: none !important; } .wecom-rail-items { flex: 1; width: 100%; overflow: auto; display: flex; flex-direction: column; align-items: center; padding: 0 8px; } .wecom-rail-items::-webkit-scrollbar { width: 0; } .wecom-rail-item { width: 100%; border: 0; background: transparent; border-radius: 10px; display: flex; flex-direction: row; align-items: center; justify-content: flex-start; gap: 8px; padding: 9px 10px; color: var(--wc-text-2); cursor: pointer; position: relative; font-size: 16px; line-height: 1; text-align: left; } .wecom-rail-item svg { width: 20px; height: 20px; color: #5B616C; flex-shrink: 0; } .wecom-rail-item span { white-space: nowrap; } .wecom-rail-item:hover { background: rgba(255,255,255,.65); } .wecom-rail-item.active { color: var(--wc-blue); background: #FFFFFF; box-shadow: 0 1px 4px rgba(31,35,41,.06); } .wecom-rail-item.active svg { color: var(--wc-blue); } .wecom-rail-bottom { width: 100%; flex-shrink: 0; padding: 4px 8px 0; } .wecom-theme-controls { position: relative; display: flex; flex-direction: column; gap: 1px; } .wecom-theme-toggle, .wecom-theme-options { position: relative; } .wecom-theme-toggle .wecom-theme-icon, .wecom-theme-options .wecom-theme-icon { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; } .wecom-theme-options { opacity: .82; } .wecom-theme-options:hover { opacity: 1; } .wecom-theme-menu[hidden] { display: none !important; } .wecom-theme-menu { position: fixed; left: calc(var(--wc-nav) + 10px); bottom: 12px; z-index: 1200; width: 190px; padding: 7px; border: 1px solid var(--wc-border); border-radius: 10px; background: var(--wc-bg); box-shadow: 0 12px 30px rgba(31, 35, 41, .18); font-family: var(--wc-font); } .wecom-theme-menu-title { padding: 5px 8px 7px; color: var(--wc-text-3); font-size: 11px; } .wecom-theme-menu button { width: 100%; height: 34px; display: flex; align-items: center; gap: 8px; padding: 0 8px; border: 0; border-radius: 7px; background: transparent; color: var(--wc-text-2); font: 13px var(--wc-font); text-align: left; cursor: pointer; } .wecom-theme-menu button:hover { background: var(--wc-hover); color: var(--wc-text); } .wecom-theme-menu button.is-active { background: var(--wc-accent-soft); color: var(--wc-accent); font-weight: 600; } .wecom-theme-menu button svg { width: 16px; height: 16px; flex: 0 0 auto; } .wecom-theme-menu .wecom-check-update { margin-top: 6px; border-top: 1px solid var(--wc-border); border-radius: 0; } /* 更新提示沿用企微配色,不遮罩、不抢占输入焦点。 */ .wecom-update-notice { position: fixed; right: 20px; bottom: 20px; z-index: 1300; box-sizing: border-box; width: 420px; max-width: calc(100vw - 24px); padding: 16px; border: 1px solid var(--wc-border); border-radius: 10px; background: var(--wc-bg); color: var(--wc-text); box-shadow: 0 8px 32px rgba(31,35,41,.18); font: 13px/1.6 var(--wc-font); } .wecom-update-notice-title { display: flex; align-items: center; gap: 7px; font-size: 15px; font-weight: 600; } .wecom-update-notice-title svg { color: var(--wc-blue); flex-shrink: 0; } .wecom-update-notice-message { margin-top: 6px; color: var(--wc-text-2); white-space: pre-line; } .wecom-update-notice-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin-top: 12px; } .wecom-update-notice a, .wecom-update-notice button { box-sizing: border-box; margin: 0; font: inherit; text-decoration: none; cursor: pointer; border: 0; box-shadow: none; } .wecom-update-notice .wecom-update-install { display: inline-flex; align-items: center; min-height: 32px; padding: 4px 13px; background: var(--wc-blue); color: #fff; border-radius: 5px; font-weight: 600; } .wecom-update-notice .wecom-update-install:hover { background: var(--wc-blue-hover); } .wecom-update-notice .wecom-update-github { color: var(--wc-text-2); } .wecom-update-notice .wecom-update-dismiss { margin-left: auto; padding: 4px 0; background: transparent; color: var(--wc-text-3); } .wecom-update-notice :focus-visible { outline: 2px solid var(--wc-blue); outline-offset: 3px; } .wecom-update-notice [hidden] { display: none !important; } .wecom-rail-more.is-on { color: var(--wc-blue); background: #FFFFFF; box-shadow: 0 1px 4px rgba(31,35,41,.06); } .wecom-rail-more.is-on svg { color: var(--wc-blue); } /* 右边缘拖拽柄:左右拉伸 rail */ .wecom-rail-resizer { position: fixed; top: var(--wc-header-h); bottom: 0; left: calc(var(--wc-nav) - 3px); width: 6px; cursor: col-resize; z-index: 400; touch-action: none; } .wecom-rail-resizer:hover, .wecom-rail-resizer.dragging { background: rgba(26,135,255,.3); } /* 窄宽度 → 纯图标模式 */ .wecom-rail-compact .wecom-rail-item { justify-content: center; padding: 8px 0; } .wecom-rail-compact .wecom-rail-item span { display: none; } .wecom-rail-compact .wecom-rail-head { padding: 2px 0 8px; display: flex; justify-content: center; } .wecom-rail-compact .wecom-rail-org-name, .wecom-rail-compact .wecom-rail-org-chip > svg { display: none; } .wecom-rail-compact .wecom-rail-badge { left: auto; right: 8px; } .wecom-rail-badge { position: absolute; top: 3px; left: 26px; right: auto; min-width: 16px; height: 16px; padding: 0 4px; background: var(--wc-danger); color: #fff; border-radius: 8px; font-size: 10px; font-weight: 700; line-height: 16px; text-align: center; } .wecom-nav2-cat-dot { width: 10px; height: 10px; border-radius: 3px; flex-shrink: 0; margin: 0 4px; } /* ---------- 聊天 header 头像与标题行 ---------- */ .wecom-chat-head-main { display: flex; align-items: center; gap: 10px; min-width: 0; } .wecom-chat-avatar { width: 28px; height: 28px; border-radius: 6px; flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 13px; font-weight: 600; } /* ---------- 聊天头:标题行(人数 + 分类 chip) ---------- */ .wecom-chat-title-row { display: flex; align-items: center; gap: 8px; min-width: 0; } .wecom-chat-count { display: inline-flex; align-items: center; gap: 2px; font-size: 12px; color: var(--wc-text-3); font-weight: 400; flex-shrink: 0; } .wecom-chat-count svg { width: 13px; height: 13px; } .wecom-chat-chips { display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0; } .wecom-chat-chip { display: inline-flex; align-items: center; gap: 3px; height: 18px; padding: 0 5px; border-radius: 4px; font-size: 11px; line-height: 1; white-space: nowrap; color: var(--wc-blue) !important; background: var(--wc-blue-soft); border: 1px solid #C9E2FF !important; text-decoration: none !important; cursor: pointer; } .wecom-chat-chip .wecom-nav2-cat-dot { width: 8px; height: 8px; border-radius: 2px; margin: 0; } /* ---------- 隐藏原生主内容(三栏路由) ---------- */ .${ROOT_CLASS}.${LOCK_CLASS} body { overflow: hidden !important; } .${ROOT_CLASS}.${LOCK_CLASS} #main-outlet > * { visibility: hidden !important; height: 0 !important; overflow: hidden !important; margin: 0 !important; padding: 0 !important; border: 0 !important; } /* ---------- 中栏右边缘拖拽柄 ---------- */ .wecom-list-resizer { position: fixed; top: var(--wc-header-h); bottom: 0; left: calc(var(--wc-nav) + var(--wc-nav2w) + var(--wc-list) - 3px); width: 6px; cursor: col-resize; z-index: 400; touch-action: none; } .wecom-list-resizer:hover, .wecom-list-resizer.dragging { background: rgba(26,135,255,.25); } .${ROOT_CLASS}.${LOCK_CLASS}.wecom-nav2-open .wecom-list-resizer { left: calc(var(--wc-nav) + var(--wc-nav2w) + var(--wc-list) - 3px); } /* ---------- 中栏:会话列表 ---------- */ .wecom-list-panel { position: fixed; top: var(--wc-header-h); left: calc(var(--wc-nav) + var(--wc-nav2w) + var(--wc-strip)); width: var(--wc-list); bottom: 0; background: #F5F7FB; border-right: 1px solid var(--wc-border); display: flex; flex-direction: column; z-index: 200; font-family: var(--wc-font); } .wecom-list-header { display: flex; align-items: center; gap: 6px; height: 44px; padding: 0 10px; flex-shrink: 0; border-bottom: 1px solid transparent; } .wecom-list-title { display: none !important; } /* 消息/未读:分段控件胶囊 */ .wecom-list-chips { display: inline-flex; align-items: center; gap: 2px; background: #E7EAF1; border-radius: 14px; padding: 2px; flex-shrink: 0; } .wecom-chip { height: 24px; padding: 0 12px; border: 0; border-radius: 12px; background: transparent; color: var(--wc-text-2); font-size: 13px; cursor: pointer; font-family: var(--wc-font); display: inline-flex; align-items: center; gap: 3px; white-space: nowrap; flex-shrink: 0; } .wecom-chip .n { font-weight: 600; } .wecom-chip.active { background: #FFFFFF; color: var(--wc-text); font-weight: 600; box-shadow: 0 1px 3px rgba(31,35,41,.12); } .wecom-list-actions { display: flex; gap: 6px; margin-left: auto; align-items: center; } .wecom-chip-icon { width: 26px; height: 26px; border-radius: 50%; background: #E7EAF1; border: 0; display: grid; place-items: center; color: var(--wc-text-2); cursor: pointer; padding: 0; } .wecom-chip-icon:hover { background: #DCE1EA; } .wecom-chip-icon.is-on, .wecom-list-nav-toggle[aria-expanded="true"] { color: var(--wc-accent); background: var(--wc-accent-soft); } .wecom-chip-icon svg { width: 14px; height: 14px; } .wecom-list-nav-toggle[aria-expanded="true"] { color: var(--wc-accent); background: var(--wc-accent-soft); } .wecom-list-nav { display: none !important; flex-wrap: wrap; gap: 6px; padding: 10px 12px 10px; flex-shrink: 0; border-bottom: 1px solid var(--wc-border); } .wecom-list-nav.open, .wecom-list-panel.wecom-list-nav-open .wecom-list-nav { display: flex !important; } .wecom-list-nav a { display: inline-flex; align-items: center; height: 28px; padding: 0 10px; border-radius: 14px; font-size: 12px; line-height: 1; color: var(--wc-text-2) !important; text-decoration: none !important; border: 1px solid var(--wc-border) !important; background: var(--wc-bg); transition: background 0.15s, color 0.15s, border-color 0.15s; } .wecom-list-nav a:hover { background: var(--wc-hover); color: var(--wc-text) !important; } .wecom-list-nav a.active { background: var(--wc-accent-soft); color: var(--wc-accent) !important; border-color: #C2D4FF !important; font-weight: 500; } .wecom-icon-btn { width: 32px; height: 32px; border: none; border-radius: 8px; background: transparent; color: var(--wc-text-2); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; transition: background 0.15s; padding: 0; } .wecom-icon-btn:hover { background: var(--wc-hover); } .wecom-icon-btn svg { width: 18px; height: 18px; } .wecom-list-body { flex: 1; overflow-y: auto; overscroll-behavior: contain; } .wecom-list-body::-webkit-scrollbar { width: 6px; } .wecom-list-body::-webkit-scrollbar-thumb { background: var(--wc-border-strong); border-radius: 3px; } .wecom-conv { display: flex; gap: 8px; padding: 7px 10px; position: relative; text-decoration: none !important; cursor: pointer; transition: background 0.15s; border: none !important; } .wecom-conv:hover { background: var(--session-hover, var(--wc-hover)); } .wecom-conv.active { background: var(--session-active, var(--wc-active)); } .wecom-conv-avatar { width: 44px; height: 44px; border-radius: 8px; flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 15px; font-weight: 600; } /* 头像模板返回的图片通常是 96px;必须约束到头像框,否则会按原始尺寸溢出并被裁成放大的局部。 */ .wecom-conv-avatar img, .wecom-chat-avatar img { display: block; width: 100%; height: 100%; max-width: 100%; max-height: 100%; object-fit: cover; } /* 伪装文字头像:保持圆形;实心 / 空心;字数 3~5 */ .wecom-conv-avatar.is-text-avatar { box-sizing: border-box; padding: 3px; letter-spacing: 0; text-align: center; } .wecom-conv-avatar .wecom-avatar-text { line-height: 1; font-weight: 700; font-size: 13px; } .wecom-conv-avatar .wecom-avatar-text[data-len="1"] { font-size: 14px; } .wecom-conv-avatar.is-grid-mask { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); gap: 0; background: #C9E7FF; padding: 0; overflow: hidden; } .wecom-conv-avatar.is-grid-mask > span { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; color: #fff; font-size: 7px; font-weight: 700; line-height: 1; } .wecom-mask-avatar-toggle.is-on { color: var(--wc-accent); background: var(--wc-accent-soft); } .wecom-conv-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; } .wecom-conv-top { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; } .wecom-conv-avatar.is-group { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); gap: 0; background: #C9E7FF; padding: 0; overflow: hidden; } .wecom-conv-avatar.is-group img, .wecom-conv-avatar.is-group span { width: 100%; height: 100%; object-fit: cover; background: #D4E5FF; } .wecom-conv-title { display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1; } .wecom-conv-name { font-size: 14px; font-weight: 500; color: var(--wc-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; min-width: 0; } .wecom-conv-tag { display: inline-flex; align-items: center; height: 16px; padding: 0 5px; border-radius: 4px; font-size: 10px; line-height: 1; white-space: nowrap; flex-shrink: 0; color: #2F88FF; background: #E8F3FF; border: 1px solid #A8CFFF; } .wecom-conv-time { font-size: 12px; color: var(--wc-text-3); flex-shrink: 0; } .wecom-conv-bottom { display: flex; align-items: center; justify-content: space-between; gap: 8px; } .wecom-conv-msg { font-size: 13px; color: var(--wc-text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .wecom-conv-badge { position: absolute; right: 12px; bottom: 12px; min-width: 16px; height: 16px; padding: 0 4px; background: var(--wc-danger); color: #fff; font-size: 10px; font-weight: 700; line-height: 16px; text-align: center; border-radius: 8px; flex-shrink: 0; } .wecom-list-status { padding: 14px; text-align: center; font-size: 12px; color: var(--wc-text-3); } /* ---------- 右栏:聊天详情 ---------- */ .wecom-chat-panel { position: fixed; top: var(--wc-header-h); left: calc(var(--wc-nav) + var(--wc-nav2w) + var(--wc-strip) + var(--wc-list)); right: 0; bottom: 0; background: var(--wc-chat-bg); display: flex; flex-direction: column; z-index: 420; font-family: var(--wc-font); } .wecom-chat-header { height: 52px; flex-shrink: 0; background: #F5F7FB; border-bottom: 1px solid var(--wc-border); display: flex; align-items: center; justify-content: space-between; padding: 0 20px; gap: 12px; } .wecom-chat-titles { min-width: 0; } .wecom-chat-title { font-size: 16px; font-weight: 600; color: var(--wc-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .wecom-chat-sub { font-size: 12px; color: var(--wc-text-3); margin-top: 1px; } .wecom-chat-actions { display: flex; gap: 4px; flex-shrink: 0; } .wecom-chat-body { flex: 1; overflow-y: auto; padding: 20px 24px; display: flex; flex-direction: column; gap: 16px; overscroll-behavior: contain; } .wecom-chat-body::-webkit-scrollbar { width: 6px; } .wecom-chat-body::-webkit-scrollbar-thumb { background: var(--wc-border-strong); border-radius: 3px; } .wecom-msg { display: flex; gap: 10px; max-width: 78%; } .wecom-msg-other { align-self: flex-start; } .wecom-msg-me { align-self: flex-end; flex-direction: row-reverse; } .wecom-msg-avatar { width: 36px; height: 36px; border-radius: 8px; flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 14px; font-weight: 600; } .wecom-msg-avatar img { width: 100%; height: 100%; object-fit: cover; } .wecom-chat-panel [data-user-card], .wecom-member-panel [data-user-card] { cursor: pointer; } .wecom-chat-panel [data-user-card]:focus-visible, .wecom-member-panel [data-user-card]:focus-visible { outline: 2px solid var(--wc-accent); outline-offset: 2px; } .wecom-topic-bookmark.is-bookmarked { color: var(--wc-accent); background: var(--wc-accent-soft); } .wecom-topic-bookmark.is-bookmarked svg path { fill: currentColor; } .wecom-chat-panel[data-empty="1"] .wecom-topic-bookmark { display: none; } .wecom-msg-content { min-width: 0; display: flex; flex-direction: column; position: relative; } .wecom-msg-me .wecom-msg-content { align-items: flex-end; } .wecom-msg-name { font-size: 12px; color: var(--wc-text-3); margin-bottom: 4px; } .wecom-msg-me .wecom-msg-name { display: none; } .wecom-reply-reference { display: grid; grid-template-columns: 16px minmax(0, 1fr); column-gap: 6px; max-width: 420px; margin: 0 0 5px; padding: 5px 8px; color: var(--wc-text-2) !important; background: rgba(67, 137, 245, .09); border-left: 2px solid var(--wc-accent); border-radius: 3px; text-align: left; text-decoration: none !important; cursor: pointer; } .wecom-reply-reference:hover { background: rgba(67, 137, 245, .15); } .wecom-reply-reference:focus-visible { outline: 2px solid var(--wc-accent); outline-offset: 2px; } .wecom-reply-reference svg { grid-row: 1 / span 2; width: 15px; height: 15px; margin-top: 1px; color: var(--wc-accent); } .wecom-reply-reference-label { min-width: 0; overflow: hidden; color: var(--wc-accent); font-size: 11px; font-weight: 600; line-height: 16px; text-overflow: ellipsis; white-space: nowrap; } .wecom-reply-reference-preview { min-width: 0; overflow: hidden; color: var(--wc-text-3); font-size: 11px; line-height: 16px; text-overflow: ellipsis; white-space: nowrap; } .wecom-msg.is-reply-target .wecom-msg-bubble { outline: 2px solid var(--wc-accent); outline-offset: 3px; } .wecom-msg-bubble { padding: 10px 14px; font-size: 14px; line-height: 1.6; color: var(--wc-text); word-break: break-word; overflow-wrap: anywhere; } .wecom-msg-other .wecom-msg-bubble { background: var(--wc-bubble-other); border-radius: 8px; box-shadow: 0 1px 0 rgba(0,0,0,.03); } .wecom-msg-me .wecom-msg-bubble { background: var(--wc-bubble-me); border-radius: 8px; } .wecom-msg-bubble p { margin: 0 0 8px; } .wecom-msg-bubble p:last-child { margin-bottom: 0; } .wecom-msg-bubble img { max-width: 100%; border-radius: 6px; } .wecom-msg-bubble img:not(.emoji):not(.site-icon) { cursor: zoom-in; } .wecom-msg-bubble pre { background: rgba(127,127,127,0.12); padding: 8px 10px; border-radius: 6px; overflow-x: auto; font-size: 13px; } .wecom-msg-bubble code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; } .wecom-msg-bubble blockquote { margin: 0 0 8px; padding: 4px 10px; border-left: 3px solid var(--wc-accent); background: rgba(51,112,255,0.06); border-radius: 0 6px 6px 0; } .wecom-msg-bubble a { color: var(--wc-accent); } .wecom-msg-meta { font-size: 11px; color: var(--wc-text-3); margin-top: 4px; display: flex; gap: 8px; align-items: center; } .wecom-msg-time-sep { align-self: center; font-size: 12px; color: var(--wc-text-3); padding: 2px 10px; } .wecom-msg-tools { position: absolute; top: -14px; right: 0; z-index: 5; display: flex; align-items: center; gap: 2px; background: var(--wc-bg); border: 1px solid var(--wc-border); border-radius: 8px; padding: 2px; box-shadow: 0 2px 8px rgba(31, 35, 41, 0.1); opacity: 0; visibility: hidden; transition: opacity 0.15s ease; } .wecom-msg:hover .wecom-msg-tools { opacity: 1; visibility: visible; } .wecom-msg-me .wecom-msg-tools { right: auto; left: 0; } .wecom-msg-tool { width: 26px; height: 26px; display: flex; align-items: center; justify-content: center; border: none; background: transparent; cursor: pointer; border-radius: 6px; color: var(--wc-text-2); padding: 0; } .wecom-msg-tool svg { width: 15px; height: 15px; } .wecom-msg-tool:hover { background: var(--wc-hover); color: var(--wc-accent); } .wecom-msg-tool.liked, .wecom-msg-tool.bookmarked { color: var(--wc-accent); } .wecom-msg-tool.bookmarked svg path { fill: currentColor; } .wecom-chat-empty, .wecom-chat-error, .wecom-chat-loading { margin: auto; display: flex; flex-direction: column; align-items: center; gap: 10px; color: var(--wc-text-3); font-size: 14px; text-align: center; padding: 40px 20px; } .wecom-chat-empty svg, .wecom-chat-error svg { width: 56px; height: 56px; opacity: 0.5; } .wecom-empty-btn { margin-top: 6px; border: 1px solid var(--wc-border-strong); background: var(--wc-bg); color: var(--wc-text-2); border-radius: 6px; height: 32px; padding: 0 14px; font-size: 13px; cursor: pointer; font-family: var(--wc-font); } .wecom-empty-btn:hover { background: var(--wc-hover); } /* ---------- 企业微信 composer:白卡片,输入区 + 下方工具行 + 发送钮 ---------- */ .wecom-composer { background: transparent; border-top: none; padding: 4px 12px 12px; flex-shrink: 0; } .wecom-composer-card { background: #FFFFFF; border: 1px solid var(--wc-border); border-radius: 12px; cursor: pointer; transition: border-color 0.15s, box-shadow 0.15s; } .wecom-composer-card:hover { border-color: #C2D4FF; box-shadow: 0 2px 10px rgba(26,135,255,.08); } .wecom-composer-tools { display: flex; align-items: center; gap: 0; padding: 0 8px 6px; } .wecom-composer-tools .wecom-icon-btn { width: 28px; height: 28px; } .wecom-composer-tools .spacer { flex: 1; } .wecom-composer-tools .hint { font-size: 11px; color: var(--wc-text-4); margin-right: 8px; } .wecom-image-input { position: absolute !important; width: 1px !important; height: 1px !important; opacity: 0 !important; overflow: hidden !important; pointer-events: none !important; } .wecom-send-btn { height: 26px; padding: 0 14px; border: 0; border-radius: 5px; background: #C5C9D0; color: #fff; font-size: 12px; cursor: pointer; font-family: var(--wc-font); } .wecom-chat-tools { margin-left: auto; display: flex; gap: 2px; } .wecom-chat-tools .wecom-icon-btn { width: 32px; height: 32px; position: relative; } .wecom-chat-tools .dot, .wecom-composer-tools .dot { position: absolute; top: 6px; right: 6px; width: 6px; height: 6px; background: var(--wc-danger); border-radius: 50%; } .wecom-composer-tools .wecom-icon-btn { position: relative; } /* ---------- 输入区:企微外观,内容同步给后台原生 composer ---------- */ .wecom-chat-compose { position: relative; z-index: 430; flex-shrink: 0; margin: 0; min-height: 64px; height: auto; border: 0; border-radius: 0; background: transparent; color: var(--wc-text-4); display: flex; align-items: flex-start; gap: 8px; padding: 10px 14px 4px; cursor: text; font-size: 14px; font-family: var(--wc-font); transition: color 0.15s; pointer-events: auto !important; width: 100%; text-align: left; } .wecom-chat-compose:hover { color: var(--wc-text-1); } .wecom-chat-compose.busy { color: var(--wc-accent); } .wecom-chat-compose.error { color: var(--wc-danger); } .wecom-chat-compose svg { width: 16px; height: 16px; flex-shrink: 0; } .wecom-chat-panel[data-empty="1"] .wecom-composer { display: none; } /* 锁定态:原生主区不要抢走点击;原生 composer 仅作为后台提交引擎 */ .${ROOT_CLASS}.${LOCK_CLASS} #main-outlet-wrapper, .${ROOT_CLASS}.${LOCK_CLASS} #main-outlet { pointer-events: none !important; } .${ROOT_CLASS}.${LOCK_CLASS} #reply-control:not(.open):not(.fullscreen):not(.edit-title) { display: none !important; pointer-events: none !important; z-index: 0 !important; } .${ROOT_CLASS}.${LOCK_CLASS} #reply-control.open, .${ROOT_CLASS}.${LOCK_CLASS} #reply-control.edit-title, .${ROOT_CLASS}.${LOCK_CLASS} #reply-control.fullscreen { display: block !important; position: fixed !important; inset: 0 auto auto -10000px !important; width: 2px !important; min-width: 0 !important; max-width: 2px !important; height: 2px !important; min-height: 0 !important; max-height: 2px !important; overflow: hidden !important; opacity: 0 !important; visibility: hidden !important; user-select: none !important; clip-path: inset(50%) !important; pointer-events: none !important; box-shadow: none !important; } /* 原生编辑器可能把补全菜单挂到 body;IM 输入框不应被这些浮层打断。 */ .${ROOT_CLASS}.${LOCK_CLASS} .autocomplete, .${ROOT_CLASS}.${LOCK_CLASS} .autocomplete-container, .${ROOT_CLASS}.${LOCK_CLASS} .d-editor-popup, .${ROOT_CLASS}.${LOCK_CLASS} .tag-chooser { display: none !important; visibility: hidden !important; pointer-events: none !important; } /* ---------- native 模式悬浮恢复钮 ---------- */ .wecom-mode-fab { position: fixed; right: 20px; bottom: 20px; z-index: 10000; width: 44px; height: 44px; border-radius: 50%; background: #1A87FF; color: #fff; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 14px rgba(51,112,255,0.4); } .wecom-mode-fab svg { width: 22px; height: 22px; } /* ---------- 聊天图片预览 ---------- */ html.wecom-image-viewer-open, html.wecom-image-viewer-open body { overflow: hidden !important; } .wecom-image-viewer, .wecom-image-viewer * { box-sizing: border-box; } .wecom-image-viewer[hidden] { display: none !important; } .wecom-image-viewer { position: fixed; inset: 0; z-index: 2147483000; display: flex; align-items: center; justify-content: center; background: rgba(10, 18, 29, .88); backdrop-filter: blur(3px); font-family: var(--wc-font); } .wecom-image-viewer-stage { position: absolute; inset: 70px 32px 56px; display: flex; align-items: center; justify-content: center; } .wecom-image-viewer-image { display: block; max-width: 100%; max-height: 100%; border-radius: 6px; object-fit: contain; box-shadow: 0 18px 60px rgba(0, 0, 0, .42); transform: scale(var(--wecom-image-viewer-scale, 1)); transform-origin: center; transition: transform 80ms ease-out; user-select: none; -webkit-user-drag: none; will-change: transform; } .wecom-image-viewer-close { position: fixed; top: 20px; right: 24px; z-index: 2; height: 40px; display: inline-flex; align-items: center; gap: 7px; padding: 0 14px; border: 1px solid rgba(255, 255, 255, .28); border-radius: 8px; background: rgba(255, 255, 255, .13); color: #FFFFFF; font: 13px var(--wc-font); cursor: pointer; } .wecom-image-viewer-close:hover, .wecom-image-viewer-close:focus-visible { outline: none; background: rgba(255, 255, 255, .24); } .wecom-image-viewer-close b { font-size: 24px; font-weight: 300; line-height: 1; } .wecom-image-viewer-zoom { position: fixed; top: 20px; left: 24px; z-index: 2; height: 40px; display: inline-flex; align-items: center; gap: 8px; padding: 0 13px; border: 1px solid rgba(255, 255, 255, .18); border-radius: 8px; background: rgba(0, 0, 0, .28); color: rgba(255, 255, 255, .68); font-size: 12px; pointer-events: none; } .wecom-image-viewer-zoom strong { min-width: 38px; color: #FFFFFF; font-size: 13px; font-variant-numeric: tabular-nums; text-align: right; } .wecom-image-viewer-caption { position: fixed; left: 24px; right: 24px; bottom: 18px; overflow: hidden; color: rgba(255, 255, 255, .78); font-size: 12px; text-align: center; white-space: nowrap; text-overflow: ellipsis; pointer-events: none; } /* ---------- splash ---------- */ .${ROOT_CLASS} #d-splash { background: var(--wc-bg) !important; } .${ROOT_CLASS} #d-splash .preloader-image { display: none !important; } .${ROOT_CLASS} #d-splash .splash-logo-container { width: 96px !important; height: 96px !important; background-image: var(--wc-splash-logo) !important; background-size: contain !important; background-repeat: no-repeat !important; animation: none !important; } .${ROOT_CLASS} #d-splash .dots { background-color: #1A87FF !important; filter: none !important; } /* ---------- 窄屏降级 ---------- */ @media (max-width: 1280px) { .${ROOT_CLASS} { --wc-list: 250px; } } @media (max-width: 1000px) { .${ROOT_CLASS} { --wc-nav2w: 0px !important; --wc-strip: 0px !important; } .wecom-strip { display: none; } .${ROOT_CLASS}.${LOCK_CLASS} .wecom-list-panel { width: calc(100% - var(--wc-nav)); left: var(--wc-nav); } .${ROOT_CLASS}.${LOCK_CLASS}.wecom-topic-open .wecom-list-panel { display: none; } .${ROOT_CLASS}.${LOCK_CLASS}:not(.wecom-topic-open) .wecom-chat-panel { display: none; } .${ROOT_CLASS}.${LOCK_CLASS} .wecom-chat-panel { left: var(--wc-nav); } .wecom-image-viewer-stage { inset: 68px 12px 44px; } .wecom-image-viewer-close { top: 14px; right: 14px; } .wecom-image-viewer-zoom { top: 14px; left: 14px; } } `; /* 企业微信经典桌面端视觉层。交互逻辑与 Discourse 数据层保持独立。 */ const WECOM_REFINEMENTS = String.raw` .${ROOT_CLASS} { --wc-blue: #267EF0; --wc-blue-hover: #176BCE; --wc-blue-soft: #EAF3FF; --wc-blue-chip: #DCEBFF; --wc-title: #267EF0; --wc-accent: #267EF0; --wc-accent-soft: #EAF3FF; --wc-nav2-bg: #FFFFFF; --wc-nav2-border: #D9D9D9; --wc-text: #181818; --wc-text-2: #575757; --wc-text-3: #8B8B8B; --wc-text-4: #B2B2B2; --wc-bg: #FFFFFF; --wc-chat-bg: #F5F5F5; --wc-hover: #E7E7E7; --wc-active: #D8D8D8; --wc-bubble-other: #FFFFFF; --wc-bubble-me: #95EC69; --wc-border: #DEDEDE; --wc-border-strong: #CACACA; --wc-danger: #FA5151; --wc-rail-bg: #2B2D31; --wc-nav: ${RAIL_WIDTH}px; --wc-list: ${LIST_WIDTH}px; --wc-header-h: 0px; --wc-font: "Microsoft YaHei UI", "PingFang SC", "Microsoft YaHei", sans-serif; --radius: 4px; } .wecom-titlebar { display: none !important; } /* 深色工作台 rail */ .wecom-rail { top: 0; padding: 14px 0 8px; overflow: hidden; background: #2B2D31; border-right: 1px solid #202226; } .wecom-rail-head { display: flex; flex-direction: column; align-items: center; gap: 11px; width: 100%; padding: 0 0 8px; } .wecom-rail-head .me-chip { position: relative; width: 38px; height: 38px; flex: 0 0 auto; } .wecom-rail .wecom-rail-avatar { width: 38px; height: 38px; border-radius: 4px; background: #267EF0; box-shadow: none; } .wecom-rail .wecom-rail-avatar.is-notif-pinned { box-shadow: 0 0 0 2px #2B2D31, 0 0 0 4px #46C36F; } .wecom-rail .wecom-rail-avatar-badge { top: -7px; right: -9px; box-shadow: 0 0 0 2px #2B2D31; } .wecom-rail-org-chip { width: 32px; height: 32px; justify-content: center; margin: 0; padding: 0; border-radius: 5px; background: rgba(255, 255, 255, .08); } .wecom-rail-org-chip:hover { background: rgba(255, 255, 255, .14); } .wecom-rail-org-logo { width: 26px; height: 26px; border-radius: 4px; background: linear-gradient(145deg, #4294FF, #1769D2); font-size: 10px; } .wecom-rail-org-name, .wecom-rail-org-chip > svg { display: none; } .wecom-rail-items { gap: 2px; padding: 4px 5px; overflow-x: hidden; } .wecom-rail-item { height: 52px; flex: 0 0 52px; flex-direction: column; justify-content: center; gap: 3px; padding: 5px 2px; border-radius: 4px; color: #AEB2B9; font-size: 10px; line-height: 1.15; text-align: center; } .wecom-rail-item svg { width: 21px; height: 21px; color: #B9BDC4; } .wecom-rail-item:hover { background: rgba(255, 255, 255, .07); } .wecom-rail-item.active, .wecom-rail-more.is-on { color: #55CF7B; background: rgba(255, 255, 255, .08); box-shadow: none; } .wecom-rail-item.active svg, .wecom-rail-more.is-on svg { color: #55CF7B; } .wecom-rail-item.active::before { content: ""; position: absolute; left: -5px; top: 14px; width: 3px; height: 24px; border-radius: 0 2px 2px 0; background: #55CF7B; } .wecom-rail-bottom { padding: 3px 5px 0; } .wecom-rail-badge { top: 2px; left: auto; right: 3px; box-shadow: 0 0 0 2px #2B2D31; } .wecom-rail-resizer { display: none !important; } /* 通知浮层从头像右侧展开 */ .${ROOT_CLASS}.wecom-notif-open .user-menu.wecom-user-menu-float, .${ROOT_CLASS}.wecom-notif-open .user-menu.revamped.menu-panel.wecom-user-menu-float, .${ROOT_CLASS}.wecom-notif-open .user-menu.menu-panel.wecom-user-menu-float { left: 76px !important; top: 10px !important; border: 1px solid #E1E1E1 !important; border-radius: 6px !important; box-shadow: 0 10px 32px rgba(0, 0, 0, .2) !important; } /* 会话栏 */ .wecom-list-panel { top: 0; background: #F2F2F2; border-right-color: #D5D5D5; } .wecom-list-search { height: 60px; display: flex; align-items: center; gap: 8px; padding: 12px 10px 8px; flex: 0 0 60px; } .wecom-list-search form { height: 30px; min-width: 0; flex: 1; display: flex; align-items: center; gap: 7px; padding: 0 9px; border-radius: 4px; background: #E2E2E2; color: #8B8B8B; } .wecom-list-search form:focus-within { background: #FFFFFF; box-shadow: inset 0 0 0 1px #AFCDF5; } .wecom-list-search svg { width: 15px; height: 15px; flex: 0 0 auto; } .wecom-list-search input { width: 100%; height: 100%; padding: 0; border: 0; outline: 0; background: transparent; color: #202020; font: 12px var(--wc-font); } .wecom-list-search input::placeholder { color: #8C8C8C; } .wecom-list-add { width: 30px; height: 30px; display: grid; place-items: center; flex: 0 0 auto; padding: 0; border: 0; border-radius: 4px; background: #DFDFDF; color: #555; cursor: pointer; } .wecom-list-add:hover { background: #D4D4D4; } .wecom-list-add svg { width: 17px; height: 17px; } .wecom-list-header { height: 40px; padding: 0 10px; border-bottom: 1px solid #E2E2E2; } .wecom-list-chips { gap: 16px; padding: 0; background: transparent; border-radius: 0; } .wecom-chip { position: relative; height: 39px; padding: 0 2px; border-radius: 0; color: #707070; } .wecom-chip.active { color: #191919; background: transparent; box-shadow: none; } .wecom-chip.active::after { content: ""; position: absolute; left: 5px; right: 5px; bottom: 0; height: 2px; background: #267EF0; } .wecom-chip-icon { background: transparent; border-radius: 4px; } .wecom-chip-icon:hover { background: #E3E3E3; } .wecom-conv { min-height: 62px; gap: 10px; padding: 9px 11px; } .wecom-conv:hover { background: #E5E5E5; } .wecom-conv.active { background: #D5D5D5; } .wecom-conv-avatar { width: 42px; height: 42px; border-radius: 4px; } .wecom-conv-avatar.is-group, .wecom-conv-avatar.is-grid-mask { gap: 1px; padding: 1px; background: #FFFFFF; } .wecom-conv-info { justify-content: center; gap: 5px; } .wecom-conv-name { font-size: 13px; font-weight: 400; } .wecom-conv-msg, .wecom-conv-time { font-size: 11px; } .wecom-conv-tag { color: #267EF0; background: #E8F2FF; border-color: #BDD8FA; } /* 聊天区 */ .wecom-chat-panel { top: 0; background: #F5F5F5; } .wecom-chat-header { height: 62px; padding: 0 22px; background: #F5F5F5; border-bottom-color: #E2E2E2; } .wecom-chat-title { font-size: 15px; font-weight: 500; } .wecom-chat-sub { color: #999; } .wecom-chat-avatar { border-radius: 4px; } .wecom-chat-body { padding: 22px 30px; gap: 18px; } .wecom-msg { max-width: min(76%, 820px); gap: 11px; } .wecom-msg-avatar { width: 38px; height: 38px; border-radius: 4px; } .wecom-msg-name { margin-bottom: 5px; color: #999; } .wecom-msg-bubble { position: relative; padding: 9px 12px; border-radius: 4px !important; font-size: 14px; line-height: 1.62; box-shadow: none !important; } .wecom-msg-other .wecom-msg-bubble::before, .wecom-msg-me .wecom-msg-bubble::before { content: ""; position: absolute; top: 12px; width: 0; height: 0; border-top: 6px solid transparent; border-bottom: 6px solid transparent; } .wecom-msg-other .wecom-msg-bubble::before { left: -7px; border-right: 8px solid #FFFFFF; } .wecom-msg-me .wecom-msg-bubble::before { right: -7px; border-left: 8px solid #95EC69; } .wecom-msg-bubble blockquote { border-left-color: #267EF0; background: rgba(38, 126, 240, .06); } .wecom-msg-meta { color: #AAA; } .wecom-msg-tools { border-radius: 4px; } /* 企业微信底部编辑区 */ .wecom-composer { min-height: 142px; padding: 0; background: #FFFFFF; border-top: 1px solid #DFDFDF; } .wecom-composer-card { min-height: 141px; display: flex; flex-direction: column; border: 0; border-radius: 0; background: #FFFFFF; } .wecom-composer-card:hover { border: 0; box-shadow: none; } .wecom-chat-compose { order: 2; min-height: 82px; padding: 7px 18px; color: #B1B1B1; } .wecom-composer-tools { order: 1; padding: 7px 13px 0; } .wecom-send-btn { order: 3; align-self: flex-end; margin: auto 18px 12px 0; height: 28px; padding: 0 18px; color: #777; background: #F0F0F0; border: 1px solid #DEDEDE; } .wecom-mode-fab { background: #267EF0; border-radius: 6px; box-shadow: 0 5px 18px rgba(38, 126, 240, .32); } .${ROOT_CLASS} #d-splash .dots { background-color: #267EF0 !important; } @media (max-width: 1280px) { .${ROOT_CLASS} { --wc-list: 280px; } } @media (max-width: 1000px) { .${ROOT_CLASS}.${LOCK_CLASS} .wecom-chat-panel { left: var(--wc-nav); } } `; /* 企业微信 5.x:以 2026 年桌面客户端展开导航版为视觉基准。 */ const WECOM_LATEST_REFINEMENTS = String.raw` .${ROOT_CLASS} { --wc-blue: #4389F5; --wc-blue-hover: #2F78E8; --wc-blue-soft: #DCEBFF; --wc-accent: #4389F5; --wc-accent-soft: #DCEBFF; --wc-text: #172033; --wc-text-2: #526175; --wc-text-3: #8B98AA; --wc-text-4: #B5BFCC; --wc-chat-bg: #F1F4F8; --wc-hover: #E7EEF8; --wc-active: #4B8FF7; --wc-bubble-other: #E5E8ED; --wc-bubble-me: #BEE4FF; --wc-border: #D9E0E9; --wc-border-strong: #C5CFDB; --wc-rail-bg: #E3F0FF; --wc-nav: ${RAIL_WIDTH}px; --wc-list: ${LIST_WIDTH}px; --wc-members: ${MEMBER_WIDTH}px; --wc-font: "Microsoft YaHei UI", "PingFang SC", "Microsoft YaHei", sans-serif; } /* 左侧展开导航 */ .wecom-rail { top: 0; padding: 10px 0 8px; align-items: stretch; overflow: hidden; background: linear-gradient(180deg, #E7F3FF 0%, #DDEEFF 100%); border-right: 1px solid #C9D9EB; color: #47617E; } .wecom-rail-head { height: 46px; display: flex; flex-direction: row; align-items: center; gap: 8px; padding: 0 16px; flex: 0 0 46px; } .wecom-rail-head .me-chip { width: 26px; height: 26px; flex: 0 0 26px; } .wecom-rail .wecom-rail-avatar { width: 26px; height: 26px; border-radius: 4px; font-size: 10px; } .wecom-current-user-name { min-width: 0; overflow: hidden; color: #26384E; font-size: 12px; line-height: 1; white-space: nowrap; text-overflow: ellipsis; } .wecom-rail-org-chip[hidden] { display: none !important; } .wecom-rail-items { flex: 0 0 auto; width: 100%; gap: 1px; padding: 4px 12px 8px; overflow: visible; } .wecom-rail-item { width: 100%; height: 31px; min-height: 31px; flex: 0 0 31px; flex-direction: row; justify-content: flex-start; gap: 10px; padding: 0 9px; border-radius: 6px; color: #5D718A; font-size: 13px; line-height: 31px; text-align: left; } .wecom-rail-item svg { width: 16px; height: 16px; color: #7B8CA1; } .wecom-rail-item:hover { background: rgba(79, 143, 234, .09); } .wecom-rail-item.active, .wecom-rail-more.is-on { color: #2D78E7; background: #CFE4FF; box-shadow: none; } .wecom-rail-item.active svg, .wecom-rail-more.is-on svg { color: #2D78E7; } .wecom-rail-item.active::before { display: none; } .wecom-rail-badge { top: 6px; left: auto; right: 8px; height: 17px; min-width: 17px; line-height: 17px; border-radius: 9px; box-shadow: 0 0 0 2px #CFE4FF; } .wecom-rail-dot { position: absolute; right: 10px; width: 7px; height: 7px; border-radius: 50%; background: #FF574F; } .wecom-rail-groups { min-height: 0; flex: 1 1 auto; overflow-y: auto; padding: 0 12px 4px; scrollbar-width: none; } .wecom-rail-groups::-webkit-scrollbar { display: none; } .wecom-rail-group-title { height: 27px; padding: 6px 9px 0; color: #8293A8; font-size: 12px; } .wecom-rail-group-item { position: relative; width: 100%; height: 31px; display: flex; align-items: center; gap: 10px; padding: 0 9px; border: 0; border-radius: 6px; background: transparent; color: #536A84; font: 13px var(--wc-font); cursor: default; } .wecom-rail-group-item:hover { background: rgba(79, 143, 234, .08); } .wecom-rail-group-item svg { width: 16px; height: 16px; color: #7187A0; } .wecom-group-unread { margin-left: auto; color: #8595A8; font-size: 11px; font-weight: 400; } .wecom-rail-bottom { padding: 2px 12px 0; } .wecom-rail-bottom .wecom-rail-item { color: #536A84; } .wecom-rail-resizer { top: 0; display: block !important; background: transparent; } .wecom-rail-resizer:hover, .wecom-rail-resizer.dragging { background: rgba(67, 137, 245, .24); } /* 原生“更多”菜单以内联浮层挂在侧栏中,必须覆盖侧栏的透明背景重置。 */ html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-more-section-content { z-index: 1200 !important; isolation: isolate; } html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-more-section-content .fk-d-menu__inner-content, html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-more-section-content > .dropdown-menu { min-width: 210px; overflow: hidden; background-color: #FFFFFF !important; border-color: #D6DEE8 !important; box-shadow: 0 8px 24px rgba(44, 71, 105, .18) !important; } html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-more-section-content .dropdown-menu { display: flex !important; flex-direction: column !important; width: 100%; margin: 0 !important; background-color: #FFFFFF !important; } html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-more-section-content .dropdown-menu__item { position: relative !important; display: flex !important; min-height: 32px !important; flex: 0 0 auto !important; } html.${ROOT_CLASS} body .sidebar-wrapper .sidebar-more-section-content .sidebar-section-link { position: relative !important; display: flex !important; min-height: 32px !important; align-items: center !important; } .${ROOT_CLASS}.wecom-notif-open .user-menu.wecom-user-menu-float, .${ROOT_CLASS}.wecom-notif-open .user-menu.revamped.menu-panel.wecom-user-menu-float, .${ROOT_CLASS}.wecom-notif-open .user-menu.menu-panel.wecom-user-menu-float { left: calc(var(--wc-nav) + 8px) !important; top: 10px !important; } /* 会话列表 */ .wecom-list-panel { top: 0; background: #F4F7FB; border-right-color: #D6DEE8; } .wecom-list-search { height: 62px; flex: 0 0 62px; padding: 14px 16px 10px; gap: 8px; } .wecom-list-search form { height: 34px; padding: 0 11px; margin: 0 !important; border: 0 !important; border-radius: 7px; background: #E5EAF0; box-shadow: none; box-sizing: border-box; } .wecom-list-search form:focus-within { background: #FFFFFF; box-shadow: inset 0 0 0 1px #A9C9F6; } .wecom-list-search form > input[type="search"] { appearance: none !important; -webkit-appearance: none !important; display: block; min-width: 0 !important; width: 100% !important; height: 100% !important; margin: 0 !important; padding: 0 !important; border: 0 !important; border-radius: 0 !important; outline: 0 !important; background: transparent !important; box-shadow: none !important; color: #26384E !important; font-family: var(--wc-font) !important; font-size: 13px !important; font-weight: 400 !important; line-height: normal !important; } .wecom-list-search form > input[type="search"]::-webkit-search-decoration, .wecom-list-search form > input[type="search"]::-webkit-search-cancel-button { display: none !important; appearance: none !important; -webkit-appearance: none !important; } .wecom-list-add { width: 34px; height: 34px; border-radius: 7px; background: #E5EAF0; } .wecom-list-header { display: none !important; } .wecom-list-nav { position: absolute; top: 58px; left: 10px; right: 10px; z-index: 5; border: 1px solid #DCE3EC; border-radius: 8px; background: #FFFFFF; box-shadow: 0 8px 24px rgba(44, 71, 105, .16); } .wecom-conv { min-height: 62px; gap: 10px; padding: 8px 13px; border-radius: 0; } .wecom-conv:hover { background: #E8EEF6; } .wecom-conv.active { background: #4B8FF7; } .wecom-conv-avatar { width: 42px; height: 42px; border-radius: 6px; } .wecom-conv-info { justify-content: center; gap: 4px; } .wecom-conv-name { color: #1B2A3B; font-size: 13px; font-weight: 500; } .wecom-conv-msg, .wecom-conv-time { color: #8A98AA; font-size: 11px; } .wecom-conv.active .wecom-conv-name, .wecom-conv.active .wecom-conv-msg, .wecom-conv.active .wecom-conv-time { color: #FFFFFF !important; } .wecom-conv.active .wecom-conv-tag { color: #FFFFFF; border-color: rgba(255,255,255,.45); background: rgba(255,255,255,.18); } .wecom-conv-tag { color: #2C79E9; border-color: #B8D5FA; background: #E8F2FF; } .wecom-list-resizer { top: 0; } /* 聊天主区 */ .wecom-chat-panel { top: 0; right: 0; background: #F1F4F8; transition: right .16s ease; } .${ROOT_CLASS}.wecom-members-open .wecom-chat-panel { right: var(--wc-members); } .wecom-chat-header { height: 80px; padding: 0 17px; background: #FFFFFF; border-bottom-color: #DCE3EB; } .wecom-chat-avatar { display: none !important; } .wecom-chat-title { color: #111827; font-size: 17px; font-weight: 700; } .wecom-chat-sub { margin-top: 4px; color: #75849A; font-size: 11px; } .wecom-chat-title-row { gap: 7px; } .wecom-chat-count { color: #8795A7; } .wecom-chat-chip { border-radius: 3px; } .wecom-chat-tools { gap: 1px; } .wecom-chat-body { padding: 18px 17px 24px; gap: 15px; background-color: #F1F4F8; background-image: none; background-repeat: repeat; background-position: 0 0; background-size: ${WATERMARK_TILE_WIDTH}px ${WATERMARK_TILE_HEIGHT}px; } .wecom-watermark-settings.is-on { color: #2D78E7; background: #E3EFFF; } .wecom-watermark-panel[hidden] { display: none !important; } .wecom-watermark-panel { position: absolute; top: 66px; right: 16px; z-index: 500; width: 310px; padding: 16px; border: 1px solid #D6DEE8; border-radius: 10px; background: #FFFFFF; box-shadow: 0 12px 34px rgba(36, 58, 86, .18); color: #25364B; font: 13px var(--wc-font); } .wecom-watermark-head, .wecom-watermark-switch-row, .wecom-watermark-actions { display: flex; align-items: center; } .wecom-watermark-head { justify-content: space-between; margin-bottom: 14px; } .wecom-watermark-head strong { color: #172033; font-size: 15px; } .wecom-watermark-close { width: 26px; height: 26px; border: 0; border-radius: 5px; background: transparent; color: #7D8B9D; font-size: 20px; line-height: 24px; cursor: pointer; } .wecom-watermark-close:hover { background: #EEF3F8; } .wecom-watermark-switch-row { justify-content: space-between; margin-bottom: 14px; cursor: pointer; } .wecom-watermark-switch { position: relative; width: 38px; height: 22px; flex: 0 0 38px; } .wecom-watermark-switch input { position: absolute; width: 1px; height: 1px; opacity: 0; } .wecom-watermark-switch i { position: absolute; inset: 0; border-radius: 12px; background: #C5CED9; transition: background .16s ease; } .wecom-watermark-switch i::after { content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: #FFFFFF; box-shadow: 0 1px 3px rgba(35, 52, 72, .24); transition: transform .16s ease; } .wecom-watermark-switch input:checked + i { background: #4389F5; } .wecom-watermark-switch input:checked + i::after { transform: translateX(16px); } .wecom-watermark-switch input:focus-visible + i { outline: 2px solid #9CC5FF; outline-offset: 2px; } .wecom-watermark-field { display: block; } .wecom-watermark-field > span { display: block; margin-bottom: 7px; color: #536378; } .wecom-watermark-text { width: 100%; height: 36px; padding: 0 10px; border: 1px solid #C9D3DF; border-radius: 6px; outline: none; background: #FFFFFF; color: #172033; font: 13px var(--wc-font); box-sizing: border-box; } .wecom-watermark-text:focus { border-color: #4389F5; box-shadow: 0 0 0 2px rgba(67,137,245,.13); } .wecom-watermark-hint { margin-top: 7px; color: #8B98AA; font-size: 11px; line-height: 1.5; } .wecom-watermark-error { min-height: 18px; margin-top: 5px; color: #D84C4C; font-size: 11px; } .wecom-watermark-actions { justify-content: flex-end; gap: 8px; margin-top: 8px; } .wecom-watermark-actions button { min-width: 64px; height: 32px; border: 1px solid #CCD6E2; border-radius: 6px; background: #FFFFFF; color: #526175; font: 13px var(--wc-font); cursor: pointer; } .wecom-watermark-actions .wecom-watermark-save { border-color: #4389F5; background: #4389F5; color: #FFFFFF; } .wecom-watermark-actions .wecom-watermark-save:hover { background: #2F78E8; } .wecom-msg { max-width: 82%; gap: 9px; } .wecom-msg-avatar { width: 34px; height: 34px; border-radius: 5px; } .wecom-msg-name { color: #7F8EA2; font-size: 11px; } .wecom-msg-bubble { padding: 8px 11px; border-radius: 5px !important; font-size: 13px; line-height: 1.55; } .wecom-msg-other .wecom-msg-bubble { background: #E4E7EC; } .wecom-msg-me .wecom-msg-bubble { background: #BDE4FF; } .wecom-msg-other .wecom-msg-bubble::before { border-right-color: #E4E7EC; } .wecom-msg-me .wecom-msg-bubble::before { border-left-color: #BDE4FF; } .wecom-msg-meta { color: #9AA7B8; } .wecom-msg-time-sep { color: #94A2B4; } .wecom-pinned-banner { min-height: 58px; display: flex; align-items: center; gap: 9px; margin: 6px 5px 0; padding: 7px 12px; flex: 0 0 auto; border: 1px solid #BFD9FA; border-radius: 5px; background: #DDEEFF; color: #3D536D; font-size: 12px; } .wecom-pinned-avatar { width: 30px; height: 30px; display: grid; place-items: center; flex: 0 0 30px; border-radius: 4px; background: #4389F5; color: #FFFFFF; font-weight: 700; } .wecom-pinned-content { min-width: 0; display: flex; flex-direction: column; gap: 3px; } .wecom-pinned-content b { color: #38516D; font-weight: 500; } .wecom-pinned-content span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .wecom-pinned-close { margin-left: auto; border: 0; background: transparent; color: #8291A4; cursor: pointer; } .wecom-composer { min-height: 174px; padding: 0 16px 13px; background: #F1F4F8; border-top: 0; } .wecom-composer-card { min-height: 160px; position: relative; border: 1px solid #D6DEE8; border-radius: 8px; background: #FFFFFF; box-shadow: 0 1px 2px rgba(34,55,80,.03); cursor: text; } .wecom-composer-card:hover { border: 1px solid #B8D0EF; box-shadow: none; } .wecom-composer-tools { padding: 9px 10px 1px; } textarea.wecom-chat-compose { order: 3; display: block; box-sizing: border-box; min-height: 96px; max-height: 180px; padding: 8px 12px 12px; resize: none; overflow-y: auto; outline: 0; color: #1F2D3D; line-height: 1.55; cursor: text; } textarea.wecom-chat-compose::placeholder { color: #A8B0BC; opacity: 1; } textarea.wecom-chat-compose:focus { color: #1F2D3D; } .wecom-compose-status { min-width: 0; margin-left: 6px; overflow: hidden; color: #8795A8; font-size: 11px; white-space: nowrap; text-overflow: ellipsis; } .wecom-compose-status.busy { color: #4389F5; } .wecom-compose-status.error { color: #E45C5C; } .wecom-compose-status.success { color: #31A05D; } .wecom-reply-target { order: 2; min-height: 26px; margin: 4px 12px 0; padding: 4px 8px; display: flex; align-items: center; gap: 6px; border-left: 2px solid #4389F5; background: #F3F7FC; color: #65758A; font-size: 11px; } .wecom-reply-target[hidden] { display: none !important; } .wecom-reply-target span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .wecom-reply-cancel { margin-left: auto; padding: 0 2px; border: 0; background: transparent; color: #8795A8; cursor: pointer; } .wecom-send-btn { margin: 0 4px 0 8px; align-self: center; color: #A8B0BC; background: transparent; border: 0; cursor: default; } .wecom-send-btn:not(:disabled) { color: #4389F5; cursor: pointer; } .wecom-send-btn:not(:disabled):hover { background: #EEF5FF; } /* 本人消息编辑弹窗。 */ .wecom-edit-dialog, .wecom-edit-dialog * { box-sizing: border-box; } .wecom-edit-dialog[hidden] { display: none !important; } .wecom-edit-dialog { position: fixed; inset: 0; z-index: 12000; display: flex; align-items: center; justify-content: center; padding: 20px; background: rgba(24, 35, 49, .42); font-family: var(--wc-font); } .wecom-edit-dialog-card { width: min(560px, calc(100vw - 32px)); max-height: calc(100vh - 40px); display: flex; flex-direction: column; padding: 18px; border: 1px solid #D6DEE8; border-radius: 10px; background: #FFFFFF; box-shadow: 0 18px 50px rgba(30, 48, 71, .24); color: #172033; } .wecom-edit-dialog-head, .wecom-edit-dialog-actions { display: flex; align-items: center; } .wecom-edit-dialog-head { justify-content: space-between; margin-bottom: 12px; } .wecom-edit-dialog-title { font-size: 16px; font-weight: 600; } .wecom-edit-dialog-close { width: 28px; height: 28px; padding: 0; border: 0; border-radius: 5px; background: transparent; color: #7D8B9D; font-size: 21px; line-height: 26px; cursor: pointer; } .wecom-edit-dialog-close:hover { background: #EEF3F8; } .wecom-edit-input { width: 100%; min-height: 180px; max-height: 55vh; padding: 11px 12px; resize: vertical; border: 1px solid #C9D3DF; border-radius: 7px; outline: 0; background: #FFFFFF; color: #172033; font: 14px/1.6 var(--wc-font); } .wecom-edit-input:focus { border-color: #4389F5; box-shadow: 0 0 0 2px rgba(67,137,245,.13); } .wecom-edit-status { min-height: 20px; padding-top: 6px; color: #8795A8; font-size: 12px; } .wecom-edit-status.error { color: #D84C4C; } .wecom-edit-status.busy { color: #4389F5; } .wecom-edit-status.success { color: #07A35A; } .wecom-edit-dialog-actions { justify-content: flex-end; gap: 8px; } .wecom-edit-dialog-actions button { min-width: 68px; height: 32px; border: 1px solid #CCD6E2; border-radius: 6px; background: #FFFFFF; color: #526175; font: 13px var(--wc-font); cursor: pointer; } .wecom-edit-dialog-actions .wecom-edit-save { border-color: #4389F5; background: #4389F5; color: #FFFFFF; } .wecom-edit-dialog-actions .wecom-edit-save:disabled { opacity: .5; cursor: default; } /* 最终兜底:后续响应式规则也不能把后台原生编辑器带回屏幕。 */ .${ROOT_CLASS}.${LOCK_CLASS} #reply-control.open, .${ROOT_CLASS}.${LOCK_CLASS} #reply-control.edit-title, .${ROOT_CLASS}.${LOCK_CLASS} #reply-control.fullscreen { inset: 0 auto auto -10000px !important; right: auto !important; width: 2px !important; height: 2px !important; opacity: 0 !important; visibility: hidden !important; clip-path: inset(50%) !important; pointer-events: none !important; } /* 右侧群成员栏 */ .wecom-member-panel { position: fixed; top: 0; right: 0; bottom: 0; width: var(--wc-members); z-index: 421; display: flex; flex-direction: column; background: #FFFFFF; border-left: 1px solid #D8E0E9; font-family: var(--wc-font); } .wecom-member-header { height: 80px; display: flex; align-items: flex-end; justify-content: space-between; padding: 0 12px 10px; flex: 0 0 80px; border-bottom: 1px solid #E2E7ED; color: #536378; font-size: 12px; } .wecom-member-header b { font-weight: 400; } .wecom-member-actions { display: flex; gap: 8px; color: #697B92; } .wecom-member-actions svg { width: 14px; height: 14px; } .wecom-member-body { flex: 1; overflow-y: auto; padding: 8px 10px 18px; } .wecom-member-section + .wecom-member-section { margin-top: 10px; } .wecom-member-section-title { padding: 4px 0 6px; color: #D99016; font-size: 11px; } .wecom-member-section + .wecom-member-section .wecom-member-section-title { color: #42A45D; } .wecom-member-row { height: 28px; display: flex; align-items: center; gap: 7px; min-width: 0; } .wecom-member-avatar { width: 18px; height: 18px; display: grid; place-items: center; flex: 0 0 18px; overflow: hidden; border-radius: 3px; color: #FFFFFF; font-size: 8px; font-weight: 700; } .wecom-member-avatar img { width: 100%; height: 100%; object-fit: cover; } .wecom-member-name { min-width: 0; overflow: hidden; color: #25364B; font-size: 11px; white-space: nowrap; text-overflow: ellipsis; } .wecom-member-role { margin-left: auto; padding: 1px 4px; border-radius: 3px; background: #EEF2F7; color: #8C98A8; font-size: 9px; } @media (max-width: 1100px) { .wecom-member-panel { display: none; } .${ROOT_CLASS}.wecom-members-open .wecom-chat-panel { right: 0; } } @media (max-width: 1000px) { .${ROOT_CLASS} { --wc-nav: 68px !important; } .wecom-current-user-name, .wecom-rail-item > span, .wecom-rail-groups, .wecom-rail-bottom span { display: none !important; } .wecom-rail-head { justify-content: center; padding: 0; } .wecom-rail-items { padding: 4px 8px; } .wecom-rail-item { justify-content: center; padding: 0; } .wecom-watermark-panel { right: 10px; width: min(310px, calc(100vw - 96px)); } } `; /* 企业微信深色模式:使用官方深色配色表中的分层灰阶与 #338CFF 强调色。 */ const WECOM_DARK_REFINEMENTS = String.raw` .${ROOT_CLASS}.wecom-dark { color-scheme: dark !important; --wc-blue: #338CFF; --wc-blue-hover: #4D9CFF; --wc-blue-soft: rgba(51, 140, 255, .16); --wc-blue-chip: #173153; --wc-title: #338CFF; --wc-accent: #338CFF; --wc-accent-soft: rgba(51, 140, 255, .16); --wc-nav2-bg: #101011; --wc-nav2-border: #2A2C2E; --wc-text: #F7F7F7; --wc-text-2: rgba(250, 252, 255, .72); --wc-text-3: rgba(250, 252, 255, .55); --wc-text-4: rgba(250, 252, 255, .4); --wc-bg: #101011; --wc-chat-bg: #101011; --wc-hover: #272829; --wc-active: rgba(51, 140, 255, .25); --wc-bubble-other: #303031; --wc-bubble-me: #093159; --wc-border: rgba(255, 255, 255, .1); --wc-border-strong: rgba(255, 255, 255, .2); --wc-danger: #FF5962; --wc-rail-bg: #000000; --wc-surface-0: #000000; --wc-surface-1: #101011; --wc-surface-2: #181819; --wc-surface-3: #202021; --wc-surface-4: #2C2C2D; --wc-divider: #2A2C2E; --primary: #F7F7F7; --primary-medium: rgba(250, 252, 255, .72); --primary-low: rgba(250, 252, 255, .55); --secondary: #101011; --tertiary: #338CFF; --header_background: #101011; --header_primary: #F7F7F7; --d-hover: #272829; --d-sidebar-background: #101011; --d-sidebar-border-color: #2A2C2E; } html.${ROOT_CLASS}.wecom-dark, html.${ROOT_CLASS}.wecom-dark body { color-scheme: dark !important; background: var(--wc-surface-0) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark #main-outlet-wrapper, html.${ROOT_CLASS}.wecom-dark #main-outlet { background: var(--wc-surface-0) !important; color: var(--wc-text) !important; } /* 原生展开栏与通知菜单 */ html.${ROOT_CLASS}.wecom-dark body .sidebar-wrapper { background-color: var(--wc-surface-1) !important; border-right-color: var(--wc-divider) !important; color: var(--wc-text) !important; --primary: #F7F7F7; --primary-medium: rgba(250, 252, 255, .72); --primary-low: rgba(250, 252, 255, .55); --primary-low-mid: #595B5E; --primary-very-low: #1F2022; --primary-50: #161718; --primary-100: #1B1C1D; --primary-200: #2A2C2E; --primary-300: #3F4143; --secondary: #101011; --tertiary: #338CFF; --quaternary: #338CFF; --d-hover: #272829; --d-sidebar-background: #101011; --d-sidebar-border-color: #2A2C2E; } html.${ROOT_CLASS}.wecom-dark body .sidebar-wrapper .sidebar-section-link { color: rgba(250, 252, 255, .72) !important; } html.${ROOT_CLASS}.wecom-dark body .sidebar-wrapper .sidebar-section-link:hover { background-color: #272829 !important; color: #F7F7F7 !important; } html.${ROOT_CLASS}.wecom-dark body .sidebar-wrapper .sidebar-section-link.active { background-color: rgba(51, 140, 255, .2) !important; color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark body .sidebar-wrapper .sidebar-more-section-content .fk-d-menu__inner-content, html.${ROOT_CLASS}.wecom-dark body .sidebar-wrapper .sidebar-more-section-content > .dropdown-menu, html.${ROOT_CLASS}.wecom-dark body .sidebar-wrapper .sidebar-more-section-content .dropdown-menu { background-color: var(--wc-surface-3) !important; border-color: var(--wc-divider) !important; box-shadow: 0 10px 28px rgba(0, 0, 0, .45) !important; } html.${ROOT_CLASS}.wecom-dark .user-menu.wecom-user-menu-float, html.${ROOT_CLASS}.wecom-dark .user-menu.revamped.menu-panel.wecom-user-menu-float, html.${ROOT_CLASS}.wecom-dark .user-menu.menu-panel.wecom-user-menu-float { background: var(--wc-surface-3) !important; border-color: var(--wc-divider) !important; color: var(--wc-text) !important; box-shadow: 0 12px 32px rgba(0, 0, 0, .45) !important; } html.${ROOT_CLASS}.wecom-dark .user-menu.wecom-user-menu-float * { color: inherit; border-color: var(--wc-divider); } /* 工作台导航 */ html.${ROOT_CLASS}.wecom-dark .wecom-rail { background: var(--wc-surface-0) !important; border-right-color: var(--wc-divider) !important; color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-current-user-name, html.${ROOT_CLASS}.wecom-dark .wecom-current-user-name { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-avatar { background: #338CFF !important; color: #FFFFFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-avatar.is-notif-pinned { box-shadow: 0 0 0 2px var(--wc-surface-0), 0 0 0 4px #2DC252 !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-avatar-badge { box-shadow: 0 0 0 2px var(--wc-surface-0) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-org-chip { background: rgba(255, 255, 255, .05); } html.${ROOT_CLASS}.wecom-dark .wecom-rail-org-chip:hover { background: rgba(255, 255, 255, .1); } html.${ROOT_CLASS}.wecom-dark .wecom-rail-org-logo { background: linear-gradient(145deg, #4D9CFF, #235BA3); } html.${ROOT_CLASS}.wecom-dark .wecom-rail-item, html.${ROOT_CLASS}.wecom-dark .wecom-rail-group-item { color: rgba(250, 252, 255, .72) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-item svg, html.${ROOT_CLASS}.wecom-dark .wecom-rail-group-item svg { color: rgba(250, 252, 255, .55) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-item:hover, html.${ROOT_CLASS}.wecom-dark .wecom-rail-group-item:hover { background: rgba(255, 255, 255, .07) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-item.active, html.${ROOT_CLASS}.wecom-dark .wecom-rail-more.is-on { background: rgba(51, 140, 255, .2) !important; color: #338CFF !important; box-shadow: none !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-item.active svg, html.${ROOT_CLASS}.wecom-dark .wecom-rail-more.is-on svg { color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-theme-toggle.is-dark { background: rgba(51, 140, 255, .2) !important; color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-theme-toggle.is-dark svg { color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-group-title, html.${ROOT_CLASS}.wecom-dark .wecom-group-unread, html.${ROOT_CLASS}.wecom-dark .wecom-rail-bottom .wecom-rail-item { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-group-item svg, html.${ROOT_CLASS}.wecom-dark .wecom-rail-item svg { color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-badge { box-shadow: 0 0 0 2px var(--wc-surface-0) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-rail-resizer:hover, html.${ROOT_CLASS}.wecom-dark .wecom-rail-resizer.dragging, html.${ROOT_CLASS}.wecom-dark .wecom-list-resizer:hover, html.${ROOT_CLASS}.wecom-dark .wecom-list-resizer.dragging { background: rgba(51, 140, 255, .35) !important; } /* 外观切换菜单 */ html.${ROOT_CLASS}.wecom-dark .wecom-theme-menu { background: var(--wc-surface-3) !important; border-color: var(--wc-divider) !important; box-shadow: 0 14px 36px rgba(0, 0, 0, .48) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-theme-menu-title, html.${ROOT_CLASS}.wecom-dark .wecom-theme-menu button { color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-theme-menu button:hover { background: rgba(255, 255, 255, .08) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-theme-menu button.is-active { background: rgba(51, 140, 255, .2) !important; color: #338CFF !important; } /* 会话列表 */ html.${ROOT_CLASS}.wecom-dark .wecom-list-panel { background: var(--wc-surface-2) !important; border-right-color: var(--wc-divider) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-search form { background: var(--wc-surface-4) !important; color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-search form:focus-within { background: var(--wc-surface-3) !important; box-shadow: inset 0 0 0 1px rgba(51, 140, 255, .65) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-search input, html.${ROOT_CLASS}.wecom-dark .wecom-list-search form > input[type="search"] { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-search input::placeholder { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-add, html.${ROOT_CLASS}.wecom-dark .wecom-chip-icon { background: var(--wc-surface-4) !important; color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-add:hover, html.${ROOT_CLASS}.wecom-dark .wecom-chip-icon:hover { background: #3F4143 !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-chips { background: var(--wc-surface-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chip { color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chip.active { background: var(--wc-surface-4) !important; color: var(--wc-text) !important; box-shadow: 0 1px 3px rgba(0, 0, 0, .35) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-nav { background: var(--wc-surface-3) !important; border-color: var(--wc-divider) !important; box-shadow: 0 10px 28px rgba(0, 0, 0, .42) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-nav a { background: var(--wc-surface-2) !important; border-color: var(--wc-divider) !important; color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-nav a:hover { background: var(--wc-hover) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-nav a.active { background: rgba(51, 140, 255, .2) !important; border-color: rgba(51, 140, 255, .45) !important; color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv:hover { background: var(--wc-hover) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv.active { background: #3D7ACC !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv-name { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv-msg, html.${ROOT_CLASS}.wecom-dark .wecom-conv-time { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv.active .wecom-conv-name, html.${ROOT_CLASS}.wecom-dark .wecom-conv.active .wecom-conv-msg, html.${ROOT_CLASS}.wecom-dark .wecom-conv.active .wecom-conv-time { color: #FFFFFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv-tag { background: rgba(51, 140, 255, .2) !important; border-color: rgba(51, 140, 255, .45) !important; color: #80B7FF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv.active .wecom-conv-tag { background: rgba(255, 255, 255, .13) !important; border-color: rgba(255, 255, 255, .35) !important; color: #FFFFFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-conv-avatar.is-group, html.${ROOT_CLASS}.wecom-dark .wecom-conv-avatar.is-grid-mask { background: var(--wc-surface-4) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-status { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-list-body::-webkit-scrollbar-thumb, html.${ROOT_CLASS}.wecom-dark .wecom-chat-body::-webkit-scrollbar-thumb { background: #3F4143 !important; } /* 聊天区与消息气泡 */ html.${ROOT_CLASS}.wecom-dark .wecom-chat-panel { background: var(--wc-surface-1) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chat-header { background: var(--wc-surface-2) !important; border-bottom-color: var(--wc-divider) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chat-title { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chat-sub, html.${ROOT_CLASS}.wecom-dark .wecom-chat-count { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chat-chip { background: rgba(51, 140, 255, .2) !important; border-color: rgba(51, 140, 255, .45) !important; color: #80B7FF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-icon-btn { color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-icon-btn:hover { background: rgba(255, 255, 255, .08) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-topic-bookmark.is-bookmarked { background: rgba(51, 140, 255, .2) !important; color: #80B7FF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chat-body { background-color: var(--wc-surface-1) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-name, html.${ROOT_CLASS}.wecom-dark .wecom-msg-meta, html.${ROOT_CLASS}.wecom-dark .wecom-msg-time-sep { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-reply-reference { color: var(--wc-text-2) !important; background: rgba(51, 140, 255, .14) !important; border-left-color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-reply-reference:hover { background: rgba(51, 140, 255, .22) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-reply-reference-label { color: #80B7FF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-reply-reference-preview { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-bubble { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-other .wecom-msg-bubble { background: #303031 !important; box-shadow: none !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-me .wecom-msg-bubble { background: #093159 !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-other .wecom-msg-bubble::before { border-right-color: #303031 !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-me .wecom-msg-bubble::before { border-left-color: #093159 !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-bubble pre { background: rgba(255, 255, 255, .07) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-bubble blockquote { background: rgba(51, 140, 255, .12) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-bubble a { color: #80B7FF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-tool { color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-tool:hover, html.${ROOT_CLASS}.wecom-dark .wecom-msg-tool.liked, html.${ROOT_CLASS}.wecom-dark .wecom-msg-tool.bookmarked { color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-msg-tools { background: var(--wc-surface-3) !important; border-color: var(--wc-divider) !important; box-shadow: 0 4px 14px rgba(0, 0, 0, .35) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-chat-empty, html.${ROOT_CLASS}.wecom-dark .wecom-chat-error, html.${ROOT_CLASS}.wecom-dark .wecom-chat-loading { color: var(--wc-text-3) !important; } /* 置顶消息、水印与回复输入区 */ html.${ROOT_CLASS}.wecom-dark .wecom-pinned-banner { background: #19191A !important; border-color: #295794 !important; color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-pinned-content b { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-pinned-close { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-watermark-panel { background: var(--wc-surface-3) !important; border-color: var(--wc-divider) !important; color: var(--wc-text) !important; box-shadow: 0 14px 36px rgba(0, 0, 0, .5) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-watermark-head strong, html.${ROOT_CLASS}.wecom-dark .wecom-watermark-field > span { color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-watermark-close:hover { background: rgba(255, 255, 255, .08) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-watermark-text { background: var(--wc-surface-4) !important; border-color: var(--wc-divider) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-watermark-hint, html.${ROOT_CLASS}.wecom-dark .wecom-watermark-close, html.${ROOT_CLASS}.wecom-dark .wecom-watermark-actions button { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-watermark-actions button { background: var(--wc-surface-4) !important; border-color: var(--wc-divider) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-watermark-actions .wecom-watermark-save { background: #338CFF !important; border-color: #338CFF !important; color: #FFFFFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-composer { background: var(--wc-surface-1) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-composer-card { background: var(--wc-surface-2) !important; border-color: var(--wc-divider) !important; box-shadow: none !important; } html.${ROOT_CLASS}.wecom-dark .wecom-composer-card:hover { border-color: rgba(51, 140, 255, .55) !important; } html.${ROOT_CLASS}.wecom-dark textarea.wecom-chat-compose, html.${ROOT_CLASS}.wecom-dark .wecom-chat-compose { color: var(--wc-text) !important; caret-color: #338CFF; } html.${ROOT_CLASS}.wecom-dark textarea.wecom-chat-compose::placeholder { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-compose-status { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-reply-target { background: rgba(255, 255, 255, .05) !important; color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-send-btn:not(:disabled) { color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-send-btn:not(:disabled):hover { background: rgba(51, 140, 255, .14) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-composer-tools .hint { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-dialog-card { background: var(--wc-surface-3) !important; border-color: var(--wc-divider) !important; color: var(--wc-text) !important; box-shadow: 0 14px 36px rgba(0, 0, 0, .5) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-dialog-close:hover { background: rgba(255, 255, 255, .08) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-dialog-close, html.${ROOT_CLASS}.wecom-dark .wecom-edit-status, html.${ROOT_CLASS}.wecom-dark .wecom-edit-dialog-actions button { color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-status.error { color: #FF6B73 !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-status.busy { color: #338CFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-status.success { color: #21C978 !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-input, html.${ROOT_CLASS}.wecom-dark .wecom-edit-dialog-actions button { background: var(--wc-surface-4) !important; border-color: var(--wc-divider) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-edit-dialog-actions .wecom-edit-save { background: #338CFF !important; border-color: #338CFF !important; color: #FFFFFF !important; } html.${ROOT_CLASS}.wecom-dark .wecom-mode-fab { background: #338CFF !important; box-shadow: 0 5px 18px rgba(51, 140, 255, .32) !important; } /* 群成员栏 */ html.${ROOT_CLASS}.wecom-dark .wecom-member-panel { background: var(--wc-surface-2) !important; border-left-color: var(--wc-divider) !important; color: var(--wc-text) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-member-header { border-bottom-color: var(--wc-divider) !important; color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-member-actions, html.${ROOT_CLASS}.wecom-dark .wecom-member-name { color: var(--wc-text-2) !important; } html.${ROOT_CLASS}.wecom-dark .wecom-member-role { background: var(--wc-surface-4) !important; color: var(--wc-text-3) !important; } html.${ROOT_CLASS}.wecom-dark #d-splash { background: var(--wc-surface-0) !important; } html.${ROOT_CLASS}.wecom-dark #d-splash .dots { background-color: #338CFF !important; } `; const RAIL_DECO_ITEMS = [ { key: "mail", icon: "mail", label: "邮件" }, { key: "doc", icon: "doc", label: "文档" }, { key: "cal", icon: "cal", label: "日程" }, { key: "todo", icon: "todo", label: "待办" }, { key: "meet", icon: "meet", label: "会议" }, { key: "smartdoc", icon: "file", label: "智能文档", dot: true }, { key: "summary", icon: "spark", label: "智能总结" }, { key: "work", icon: "work", label: "工作台" }, { key: "book", icon: "book", label: "通讯录" }, { key: "disk", icon: "disk", label: "微盘" }, { key: "advanced", icon: "apps", label: "高级功能" } ]; const RAIL_GROUP_ITEMS = [ { key: "unread", icon: "mail", label: "未读", count: true }, { key: "at", icon: "at", label: "@我" }, { key: "single", icon: "users", label: "单聊" }, { key: "group", icon: "users", label: "群聊" }, { key: "inside", icon: "chat", label: "内部聊天" }, { key: "outside", icon: "cloud", label: "外部聊天" }, { key: "mark", icon: "collect", label: "标记" } ]; const THEME_MODE_LABELS = Object.freeze({ light: "浅色模式", dark: "深色模式", system: "跟随系统" }); function injectStyle() { let style = document.getElementById(STYLE_ID); if (!style) { style = document.createElement("style"); style.id = STYLE_ID; (document.head || document.documentElement).appendChild(style); } // 始终刷新,避免旧版 CSS(挡住回复按钮)残留 style.textContent = `${RAW_CSS}\n${WECOM_REFINEMENTS}\n${WECOM_LATEST_REFINEMENTS}\n${WECOM_DARK_REFINEMENTS}`; } function escapeHtml(text) { return String(text ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } function avatarColor(name) { let hash = 0; const s = String(name || "?"); for (let i = 0; i < s.length; i++) hash = (hash * 31 + s.charCodeAt(i)) | 0; return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length]; } function avatarLetter(name) { const s = String(name || "?").trim(); const ch = [...s][0] || "?"; return /[a-z]/i.test(ch) ? ch.toUpperCase() : ch; } function userDisplayName(user, fallback) { const name = user && String(user.name || "").trim(); if (name) return name; const uname = user && String(user.username || "").trim(); if (uname) return uname; return String(fallback || "?").trim() || "?"; } function booleanFlag(value) { return value === true || value === 1 || value === "1" || (typeof value === "string" && value.trim().toLowerCase() === "true"); } function normalizeThemeMode(mode) { return THEME_MODE_VALUES.includes(mode) ? mode : DEFAULT_THEME_MODE; } function themeModeDescription(mode) { return THEME_MODE_LABELS[normalizeThemeMode(mode)]; } function setThemeMenuOpen(open) { const menu = document.querySelector(".wecom-theme-menu"); const trigger = document.querySelector(".wecom-theme-options"); if (!menu) return; menu.hidden = !open; trigger?.setAttribute("aria-expanded", open ? "true" : "false"); } function syncThemeControls() { const mode = getThemeMode(); const dark = isDarkMode(); const toggle = document.querySelector(".wecom-theme-toggle"); if (toggle) { const label = toggle.querySelector(".wecom-theme-label"); const icon = toggle.querySelector(".wecom-theme-icon"); toggle.classList.toggle("is-dark", dark); toggle.setAttribute("aria-pressed", dark ? "true" : "false"); toggle.title = dark ? "切换到浅色模式" : "切换到深色模式"; if (label) label.textContent = dark ? "浅色模式" : "深色模式"; if (icon) icon.innerHTML = dark ? ICONS.sun : ICONS.moon; } const menu = document.querySelector(".wecom-theme-menu"); if (!menu) return; menu.querySelectorAll("button[data-theme-mode]").forEach((button) => { const active = button.dataset.themeMode === mode; button.classList.toggle("is-active", active); button.setAttribute("aria-checked", active ? "true" : "false"); }); const options = document.querySelector(".wecom-theme-options"); if (options) options.title = `外观设置(${themeModeDescription(mode)})`; } function bindThemeControls() { if (window.__wecomThemeControlsBound) return; window.__wecomThemeControlsBound = true; document.addEventListener("click", (event) => { if (!event.target.closest(".wecom-theme-controls, .wecom-theme-menu")) setThemeMenuOpen(false); }); document.addEventListener("keydown", (event) => { if (event.key === "Escape") setThemeMenuOpen(false); }); } function createThemeControls(rail) { const controls = document.createElement("div"); controls.className = "wecom-theme-controls"; controls.innerHTML = `` + ``; const bottom = rail.querySelector(".wecom-rail-bottom"); if (bottom) bottom.insertBefore(controls, bottom.firstChild); else rail.appendChild(controls); return controls; } function createThemeMenu() { const menu = document.createElement("div"); menu.className = "wecom-theme-menu"; menu.hidden = true; menu.setAttribute("role", "menu"); menu.setAttribute("aria-label", "外观模式"); menu.innerHTML = `
外观模式
` + `` + `` + `` + ``; document.body.appendChild(menu); menu.addEventListener("click", (event) => { if (event.target.closest(".wecom-check-update")) { event.preventDefault(); event.stopPropagation(); setThemeMenuOpen(false); void checkForScriptUpdate(true); return; } const option = event.target.closest("button[data-theme-mode]"); if (!option) return; event.preventDefault(); event.stopPropagation(); setThemeMode(option.dataset.themeMode); setThemeMenuOpen(false); }); return menu; } function bindThemeControlButtons(controls) { const toggle = controls.querySelector(".wecom-theme-toggle"); if (toggle && !toggle.dataset.bound) { toggle.dataset.bound = "1"; toggle.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); setThemeMode(isDarkMode() ? "light" : "dark"); }); } const options = controls.querySelector(".wecom-theme-options"); if (options && !options.dataset.bound) { options.dataset.bound = "1"; options.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); const menu = document.querySelector(".wecom-theme-menu"); setThemeMenuOpen(!!menu?.hidden); }); } } function ensureThemeControls(rail) { if (!rail || !document.body) return; const controls = rail.querySelector(".wecom-theme-controls") || createThemeControls(rail); if (!document.querySelector(".wecom-theme-menu")) createThemeMenu(); bindThemeControlButtons(controls); bindThemeControls(); syncThemeControls(); } function ensureRail() { let rail = document.querySelector(".wecom-rail"); // 旧结构重建为企业微信 5.x 展开导航 if (rail && !rail.querySelector(".wecom-rail-groups")) { rail.remove(); rail = null; } if (rail) { bindRailAvatarNotif(rail); ensureThemeControls(rail); syncRail(); return rail; } rail = document.createElement("nav"); rail.className = "wecom-rail"; rail.setAttribute("aria-label", "企业微信工作台导航"); const head = document.createElement("div"); head.className = "wecom-rail-head"; head.innerHTML = `
` + `
` + `` + `
` + `linux.do` + ``; rail.appendChild(head); const items = document.createElement("div"); items.className = "wecom-rail-items"; items.innerHTML = `` + RAIL_DECO_ITEMS.map((item) => `` ).join(""); rail.appendChild(items); const groups = document.createElement("div"); groups.className = "wecom-rail-groups"; groups.innerHTML = `
分组
` + RAIL_GROUP_ITEMS.map((item) => `` ).join(""); groups.querySelector('[data-group-key="unread"]')?.addEventListener("click", () => navigateInApp("/unseen")); rail.appendChild(groups); // 底部「更多」:展开 / 收起话题导航(原生侧栏) const bottom = document.createElement("div"); bottom.className = "wecom-rail-bottom"; const more = document.createElement("button"); more.type = "button"; more.className = "wecom-rail-item wecom-rail-more"; more.dataset.railKey = "more"; more.title = "展开话题导航"; more.setAttribute("aria-expanded", "false"); more.innerHTML = `${ICONS.build}我的企业`; more.addEventListener("click", () => setNav2Open(!isNav2Open())); bottom.appendChild(more); rail.appendChild(bottom); document.body.appendChild(rail); ensureThemeControls(rail); renderOrgChip(rail); bindOrgChip(rail); bindRailAvatarNotif(rail); setNav2Open(isNav2Open()); // 同步「更多」高亮态 syncRail(); return rail; } function ensureListPanel() { let panel = document.querySelector(".wecom-list-panel"); // 旧面板缺筛选按钮/容器时重建 if (panel && (!panel.querySelector(".wecom-list-search") || !panel.querySelector(".wecom-list-nav-toggle") || !panel.querySelector(".wecom-list-nav") || !panel.querySelector(".wecom-chip"))) { panel.remove(); panel = null; } if (panel) { bindListPanelClicks(panel); bindSearchBox(panel); ensureMaskAvatarToggle(panel); applyListNavDom(); return panel; } panel = document.createElement("div"); panel.className = "wecom-list-panel"; panel.innerHTML = `
`; document.body.appendChild(panel); bindListPanelClicks(panel); bindSearchBox(panel); ensureMaskAvatarToggle(panel); panel.querySelectorAll(".wecom-chip").forEach((chip) => { chip.addEventListener("click", () => { panel.querySelectorAll(".wecom-chip").forEach((c) => c.classList.remove("active")); chip.classList.add("active"); navigateInApp(chip.dataset.chip === "unread" ? "/unseen" : "/latest"); }); }); panel.querySelector(".wecom-list-body").addEventListener("scroll", () => { const body = panel.querySelector(".wecom-list-body"); if (body.scrollTop + body.clientHeight >= body.scrollHeight - 120) { loadMoreList(); } }); applyListNavDom(); return panel; } function ensureChatPanel() { let panel = document.querySelector(".wecom-chat-panel"); if (panel && (!panel.querySelector(".wecom-chat-compose") || !panel.querySelector(".wecom-pinned-banner") || !panel.querySelector(".wecom-watermark-panel") || !panel.querySelector(".wecom-image-input") || !panel.querySelector('[data-composer-action="emoji"]') || !panel.querySelector('[data-composer-action="pic"]') || !panel.querySelector(".wecom-topic-bookmark"))) { panel.remove(); panel = null; } if (panel) { if (!panel.dataset.composeBound) { panel.dataset.composeBound = "1"; bindChatPanelEvents(panel); } bindWatermarkSettings(panel); renderWatermark(getWatermarkSettings()); wireComposeButton(panel); bindUserCardEvents(panel); ensureEditDialog(); return panel; } panel = document.createElement("div"); panel.className = "wecom-chat-panel"; panel.dataset.empty = "1"; panel.dataset.composeBound = "1"; const toolKeys = [ ["emoji", "表情"], ["cut", "截图"], ["folder", "附件"], ["pic", "发送图片"], ["plus", "更多"] ]; const toolsHtml = toolKeys.map(([key, label]) => { const popup = key === "emoji" ? ' aria-haspopup="dialog" aria-expanded="false"' : ""; return ``; }).join(""); const headTools = ["cam", "phone", "users", "dots"].map((k) => { const dot = k === "users" ? '' : ""; return ``; }).join(""); panel.innerHTML = `
${headTools}
${toolsHtml}
`; document.body.appendChild(panel); bindChatPanelEvents(panel); bindUserCardEvents(panel); bindWatermarkSettings(panel); renderWatermark(getWatermarkSettings()); ensureEditDialog(); panel.querySelector(".wecom-pinned-close")?.addEventListener("click", () => { const banner = panel.querySelector(".wecom-pinned-banner"); if (banner) banner.style.display = "none"; }); wireComposeButton(panel); return panel; } function ensureMemberPanel() { let panel = document.querySelector(".wecom-member-panel"); if (panel) { bindUserCardEvents(panel); return panel; } panel = document.createElement("aside"); panel.className = "wecom-member-panel"; panel.innerHTML = `
群成员 · 0 ${ICONS.mail}${ICONS.dots}
`; document.body.appendChild(panel); bindUserCardEvents(panel); return panel; } function memberAvatarHtml(user) { const name = userDisplayName(user, user?.username || "?"); if (!isMaskAvatar() && user?.avatar_template) { return ``; } return `${escapeHtml(avatarLetter(name))}`; } function memberRowHtml(user, role) { const name = userDisplayName(user, user?.username || "?"); const roleHtml = role ? `${escapeHtml(role)}` : ""; return `
${memberAvatarHtml(user)}${escapeHtml(name)}${roleHtml}
`; } function topicParticipants(data, posts) { const source = [...(data?.details?.participants || []), ...(posts || [])]; const seen = new Set(); return source.filter((user) => { const key = normalizeUsername(user?.username) || String(user?.id || ""); if (!key || seen.has(key)) return false; seen.add(key); return true; }); } function renderMemberPanel(data, posts) { const panel = ensureMemberPanel(); const users = topicParticipants(data, posts); const owner = posts.find((post) => post.post_number === 1) || users[0] || null; const others = users.filter((user) => normalizeUsername(user.username) !== normalizeUsername(owner?.username)); const total = data.participant_count || users.length; panel.querySelector(".wecom-member-count").textContent = String(total); panel.querySelector(".wecom-member-body").innerHTML = `
群主/管理员
${owner ? memberRowHtml(owner, "群主") : ""}
` + `
群成员
${others.map((user) => memberRowHtml(user, "")).join("")}
`; document.documentElement.classList.add("wecom-members-open"); } function convAvatarHtml(topic, usersById) { if (isMaskAvatar()) { if (isGridMaskTopic(topic)) return disguiseGridAvatar(topic); const d = disguiseAvatarForTopic(topic); return `${d.html}`; } if (isGroupConversation(topic)) { return groupAvatarHtml(topic, usersById || {}); } const poster = (topic.posters || [])[0]; const user = poster && usersById ? usersById[poster.user_id] : null; const displayName = userDisplayName(user, topic.last_poster_username || "?"); if (user && user.avatar_template) { return ``; } return `${escapeHtml(avatarLetter(displayName))}`; } function convRowHtml(topic, usersById) { const unread = topic.unread > 0 ? topic.unread : (topic.new_posts > 0 ? topic.new_posts : 0); const replyCount = Math.max(0, (topic.posts_count || 1) - 1); const summary = topic.last_poster_username ? `[${replyCount}条] ${topic.last_poster_username}` : `${topic.posts_count || 0} 回复`; const tag = convCategoryTag(topic); return ` ${convAvatarHtml(topic, usersById)} ${escapeHtml(topic.title)} ${tag} ${escapeHtml(formatTime(topic.bumped_at || topic.last_activity_at || topic.created_at))} ${escapeHtml(summary)} ${unread ? `${unread > 99 ? "99+" : unread}` : ""} `; } function replyReferenceHtml(post) { const info = replyReferenceInfo(post); if (!info) return ""; const label = `回复 ${info.name} · #${info.number}`; const title = `${label}:${info.preview}`; return `${ICONS.reply}` + `${escapeHtml(label)}` + `${escapeHtml(info.preview)}`; } function bubbleHtml(post, myName) { const me = isMyPost(post, myName); const side = me ? "me" : "other"; const displayName = userDisplayName(post, post.username || "?"); let avatar; let avatarBg = avatarColor(displayName); if (isMaskAvatar()) { avatar = escapeHtml(avatarLetter(displayName)); } else if (post.avatar_template) { avatar = ``; avatarBg = "transparent"; } else { avatar = escapeHtml(avatarLetter(displayName)); } const liked = post.id && likedPosts.has(post.id) ? " liked" : ""; const isBookmarked = booleanFlag(post.bookmarked) || Boolean(post.bookmark_id); const bookmarkClass = isBookmarked ? " bookmarked" : ""; const bookmarkLabel = isBookmarked ? "编辑楼层书签" : "收藏本楼层"; const bookmarkButton = post.id ? `` : ""; const editButton = me && (post.id || post.post_number) ? `` : ""; return `
${avatar}
${escapeHtml(displayName)} ${replyReferenceHtml(post)}
${post.cooked || ""}
#${post.post_number} ${escapeHtml(formatTime(post.created_at))}
${bookmarkButton} ${editButton}
`; } return { injectStyle, ensureRail, ensureListPanel, ensureChatPanel, ensureMemberPanel, renderMemberPanel, convRowHtml, bubbleHtml, syncThemeControls, setThemeMenuOpen, ICONS, ROOT_CLASS, LOCK_CLASS, }; } function renderDouyinMessageCard(item) { const id = workroomEscape(item.id); const photo = item.kind === 'image'; const title = workroomEscape(item.title || (photo ? '图文' : '视频')); const cover = workroomURL(item.cover ?? item.coverUrl); if (['answer', 'question', 'article'].includes(item.kind)) { const summary = item.summary ? `${workroomEscape(item.summary)}` : ''; return ``; } const label = photo ? '查看图文' : '打开视频及评论'; const image = cover ? `` : ''; const play = photo ? '' : ''; return ``; } const WE_COM_LAYOUT_CSS = ".wecom-im-theme {\n --wc-nav: 60px;\n --wc-list: clamp(250px, 21.85vw, 310px);\n --dw-wc-header: 63px;\n --dw-wc-chat-inset: clamp(16px, 1.4vw, 22px);\n --dw-wc-divider: #e9eaec;\n --dw-wc-selection: linear-gradient(90deg, #257ef0, #5d9bff);\n --dw-wc-ink: #247bee;\n}\n\n.wecom-im-theme.wecom-dark {\n --dw-wc-divider: var(--wc-divider);\n}\n\n.wecom-rail {\n --dw-wc-rail-row: clamp(40px, 7.2vh, 50px);\n padding: 0 0 10px;\n border-right-color: var(--dw-wc-divider);\n background: linear-gradient(180deg, #d4dae4, #d7dbe3);\n}\n\n.wecom-rail-head {\n height: calc(var(--dw-wc-header) + 16px);\n flex-basis: calc(var(--dw-wc-header) + 16px);\n justify-content: center;\n padding: 28px 0 0;\n}\n\n.wecom-rail-head .me-chip {\n width: 36px;\n height: 36px;\n flex-basis: 36px;\n}\n\n.wecom-rail .wecom-rail-avatar {\n width: 36px;\n height: 36px;\n border-radius: 7px;\n background: #3c71b9;\n font-size: 16px;\n cursor: default;\n}\n.wecom-rail-avatar img[hidden], .wecom-rail-avatar span[hidden] { display: none; }\n.dw-feishu-profile-icon { display: none; }\n\n.wecom-current-user-name { display: none; }\n\n.wecom-rail-items {\n flex: 0 1 auto;\n min-height: 0;\n gap: 6px;\n padding: 6px;\n overflow: auto;\n scrollbar-width: none;\n}\n\n.wecom-rail-bottom {\n margin-top: auto;\n padding: 6px 6px 0;\n}\n\n.wecom-rail-item {\n height: var(--dw-wc-rail-row);\n min-height: var(--dw-wc-rail-row);\n flex: 0 0 var(--dw-wc-rail-row);\n flex-direction: column;\n justify-content: center;\n gap: 5px;\n padding: 3px 0;\n border-radius: 6px;\n color: #63718a;\n font-size: 11px;\n line-height: 1.25;\n text-align: center;\n}\n\n.wecom-rail-item svg { width: 20px; height: 20px; color: #7d8b9d; }\n.wecom-rail-item.active { background: #c5d1e5; box-shadow: none; }\n.wecom-rail-item.active, .wecom-rail-item.active svg { color: var(--dw-wc-ink); }\n.wecom-rail-item[aria-hidden=\"true\"] { pointer-events: none; cursor: default; }\n.wecom-rail-item[hidden] { display: none; }\n.wecom-rail-item:is([data-rail-key=\"channels\"], [data-glyph=\"mail\"], [data-glyph=\"docs\"], [data-glyph=\"calendar\"], [data-glyph=\"check\"], [data-glyph=\"meeting\"]) svg {\n width: 19px;\n height: 19px;\n padding: 2px;\n border-radius: 4px;\n background: #7d8b9d;\n color: #edf1f7;\n}\n.wecom-rail-item[data-rail-key=\"channels\"].active svg { background: var(--dw-wc-ink); color: #fff; }\n.wecom-rail-item[data-glyph=\"check\"] svg { border-radius: 50%; }\n\n.wecom-rail-bottom .wecom-rail-item {\n height: 44px;\n min-height: 44px;\n flex-basis: 44px;\n font-size: 11px;\n}\n\n.wecom-rail-badge {\n top: 4px;\n right: 6px;\n box-shadow: 0 0 0 2px #c5d1e5;\n}\n\n.wecom-rail .wecom-rail-badge:not([hidden]) { display: block !important; }\n\n.wecom-list-search,\n.wecom-chat-header,\n.wecom-member-header {\n height: var(--dw-wc-header);\n flex: 0 0 var(--dw-wc-header);\n border-bottom: 1px solid var(--dw-wc-divider);\n align-items: center;\n}\n\n.wecom-list-panel {\n background: linear-gradient(180deg, #f7f8f9, #f1f2f4 49%, #fff 89%);\n border-right-color: var(--dw-wc-divider);\n}\n\n.wecom-list-search { padding: 0 16px; }\n\n.wecom-list-search form,\n.wecom-list-add {\n height: 32px;\n background: #ecedee;\n}\n\n.wecom-list-add { width: 32px; }\n.wecom-list-search form > input[type=\"search\"] { font-size: 14px !important; }\n.wecom-list-body { padding: 1px 4px 4px; }\n.wecom-feed-pagination { padding: 12px; text-align: center; color: var(--wc-text-2); font-size: 12px; }\n.wecom-reading-card { display: grid; gap: 6px; padding: 0; border: 0; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; }\n.wecom-reading-summary { color: var(--wc-text-2); font-size: 12px; }\n.wecom-detail-media:has(.wecom-reading-body) { inline-size: min(100%, 760px); }\n.wecom-reading-body {\n padding: 12px clamp(14px, 2vw, 24px);\n border-radius: 10px;\n background: var(--wc-bubble-other);\n color: var(--wc-text);\n line-height: 1.7;\n overflow-wrap: anywhere;\n}\n.wecom-reading-body > :first-child { margin-block-start: 0; }\n.wecom-reading-body > :last-child { margin-block-end: 0; }\n.wecom-detail-work[data-douyin-reading] .wecom-detail-name { margin: 0 0 5px; }\n.wecom-reading-body img { display: block; max-width: 100%; height: auto; }\n.wecom-reading-body pre, .wecom-reading-body table { max-width: 100%; overflow-x: auto; }\n.wecom-reading-body blockquote { margin: 12px 0; padding-inline-start: 12px; border-inline-start: 2px solid var(--wc-text-2); }\n\n.wecom-conv {\n position: relative;\n min-height: 64px;\n gap: 14px;\n padding: 9px 14px 9px 12px;\n border-radius: 6px;\n}\n\n.wecom-conv::after {\n position: absolute;\n right: 12px;\n bottom: 0;\n left: 12px;\n border-bottom: 1px solid var(--dw-wc-divider);\n content: '';\n pointer-events: none;\n}\n\n.wecom-conv.active {\n background: var(--dw-wc-selection);\n box-shadow: none;\n}\n\n.wecom-conv.active::after,\n.wecom-conv:last-child::after { display: none; }\n\n.wecom-conv-avatar {\n width: 40px;\n height: 40px;\n border-radius: 6px;\n}\n\n.wecom-conv-info {\n display: grid;\n grid-template-columns: minmax(0, 1fr) auto;\n column-gap: 8px;\n row-gap: 4px;\n align-items: baseline;\n justify-content: stretch;\n}\n\n.wecom-conv-top,\n.wecom-conv-bottom { display: contents; }\n\n.wecom-conv-title { grid-area: 1 / 1; }\n.wecom-conv-name { color: #101419; font-size: 14px; font-weight: 600; }\n.wecom-conv-msg { grid-area: 2 / 1; }\n.wecom-conv-time { grid-area: 2 / 2; font-variant-numeric: tabular-nums; text-align: right; }\n.wecom-conv-msg:empty, .wecom-conv-time:empty { display: none; }\n.wecom-conv-badge { position: static; grid-area: 1 / 2; justify-self: end; }\n\n.wecom-conv-msg,\n.wecom-conv-time {\n color: #969a9e;\n font-size: 12px;\n}\n\nhtml.wecom-im-theme:not(.wecom-dark) .wecom-conv.active .wecom-conv-name { color: #fff !important; }\nhtml.wecom-im-theme:not(.wecom-dark) .wecom-conv.active :is(.wecom-conv-msg, .wecom-conv-time) { color: #bdd6ff !important; }\nhtml.wecom-im-theme.wecom-dark .wecom-conv.active { background: #244469 !important; }\n\n.wecom-chat-panel,\n.wecom-chat-body { background-color: #fff; }\n\n.wecom-chat-header { padding: 0 var(--dw-wc-chat-inset); }\n.wecom-chat-title { font-size: 18px; font-weight: 650; }\n.wecom-chat-sub { margin-top: 3px; }\n.wecom-chat-tools .dot,\n.wecom-chat-tools :is([title=\"cam\"], [title=\"phone\"], [title=\"dots\"]),\n.wecom-chat-actions :is(.wecom-topic-bookmark, .wecom-watermark-settings) { display: none; }\n.wecom-member-header { padding: 0 12px; }\n\n.wecom-chat-body {\n gap: 18px;\n padding: 18px var(--dw-wc-chat-inset) 24px;\n}\n\n.wecom-chat-body:is([data-douyin-detail], [data-douyin-group-detail]) { overscroll-behavior-y: none; }\n\n.wecom-chat-panel { --wecom-group-comments-width: clamp(270px, 29vw, 350px); }\n.wecom-chat-panel[data-douyin-group-comments-open] > .wecom-chat-body {\n margin-inline-end: var(--wecom-group-comments-width);\n}\n.wecom-group-comments {\n position: absolute;\n inset: var(--dw-wc-header) 0 0 auto;\n width: var(--wecom-group-comments-width);\n z-index: 5;\n display: flex;\n flex-direction: column;\n background: var(--wc-bg);\n border-left: 1px solid var(--dw-wc-divider);\n color: var(--wc-text);\n}\n.wecom-group-comments[hidden] { display: none; }\n.wecom-group-comments-header { display: flex; justify-content: space-between; align-items: center; padding: 8px 14px 0; }\n.wecom-group-comments-header button { font-size: 21px; }\n.wecom-group-comments-video { padding: 4px 14px 12px; color: var(--wc-text-2); font-size: 12px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n.wecom-detail-comments { display: flex; flex-direction: column; gap: inherit; }\n.wecom-group-comments .wecom-detail-comments {\n flex: 1; min-height: 0; overflow: auto; gap: 12px; overscroll-behavior: contain;\n padding: 12px; border-top: 1px solid var(--dw-wc-divider);\n}\n.wecom-group-comments .wecom-msg { max-width: 100%; }\n.wecom-group-comments .wecom-composer-card { min-height: 105px; }\n.wecom-group-comments .wecom-composer-tools { gap: 2px; }\n.wecom-group-comments .wecom-composer-tools :is(.wecom-icon-btn, .wecom-composer-decoration) { width: 27px; }\n.wecom-msg[data-douyin-group-playing] [data-douyin-card-cover] { display: none !important; }\n.wecom-msg[data-douyin-group-playing] .wecom-detail-media { width: min(360px, 33vw); max-width: 100%; margin-top: 8px; }\n\n@media (max-width: 820px) {\n .wecom-chat-panel[data-douyin-group-comments-open] > .wecom-chat-body { margin-inline-end: 0; }\n .wecom-group-comments { max-width: 92%; box-shadow: -8px 0 22px #0002; }\n .wecom-msg[data-douyin-group-playing] .wecom-detail-media { width: min(360px, 65vw); }\n}\n\n.wecom-msg { max-width: min(84%, 660px); gap: 10px; align-items: flex-start; }\n.wecom-msg[data-douyin-message-kind=\"video\"] { max-width: min(84%, 430px); }\n.wecom-msg-avatar { width: 28px; height: 28px; border-radius: 5px; }\n.wecom-detail-author { display: flex; align-items: flex-start; gap: 10px; flex: none; }\n.wecom-detail-author .wecom-msg-avatar { color: var(--wc-text-2); background: var(--wc-hover); }\n.wecom-detail-work { min-width: 0; flex: 1; }\n.wecom-detail-media { inline-size: min(100%, 560px, max(235px, 64vh)); }\n.wecom-inline-player-status {\n position: absolute;\n inset: 0;\n z-index: 1;\n display: grid;\n place-content: center;\n justify-items: center;\n gap: 9px;\n color: #d1d7df;\n background: #101318;\n font-size: 13px;\n line-height: 1.4;\n}\n.wecom-inline-player-status button {\n border: 1px solid #ffffff52;\n border-radius: 6px;\n padding: 5px 10px;\n background: #ffffff14;\n color: inherit;\n font: inherit;\n cursor: pointer;\n}\n.wecom-detail-name { display: block; margin-top: 4px; font-size: 12px; color: var(--wc-text-2); }\n.wecom-chat-actions > button[hidden] { display: none; }\n.wecom-chat-refresh[data-douyin-refresh-feed] {\n display: inline-flex;\n align-items: center;\n gap: 5px;\n width: auto;\n padding: 0 8px;\n color: var(--wc-text-2);\n font-size: 13px;\n white-space: nowrap;\n}\n.wecom-chat-actions .wecom-comments-jump {\n width: auto;\n padding: 0 8px;\n color: var(--wc-text-2);\n font-size: 13px;\n white-space: nowrap;\n}\n.wecom-comments-empty { color: var(--wc-text-2); font-size: 13px; }\n.wecom-msg-meta .wecom-msg-name { color: inherit; font-size: inherit; margin: 0; }\n.wecom-msg-meta { color: #68768a; }\n\n.wecom-msg .wecom-msg-bubble {\n padding: 9px 13px;\n border-radius: 10px !important;\n font-size: 15px;\n line-height: 1.5;\n box-shadow: none;\n}\n\n.wecom-msg-other .wecom-msg-bubble { background: #e1e1e3; }\n.wecom-msg-me .wecom-msg-bubble { background: #c9e7ff; }\n.wecom-msg .wecom-msg-bubble::before { content: none; }\n\n.wecom-msg-bubble .wecom-reply-reference {\n margin: 0 0 8px;\n padding: 5px 8px;\n border-left-color: #7397cb;\n background: transparent;\n}\n\n.wecom-msg-bubble .wecom-reply-reference-label { color: var(--wc-text-2); font-size: 12px; }\n.wecom-msg-bubble .wecom-reply-reference-preview { color: var(--wc-text-2); font-size: 12px; }\n.wecom-msg-bubble .wecom-reply-reference:hover { background: rgba(38, 77, 136, .08); }\n\n.wecom-composer {\n min-height: 0;\n padding: 0;\n border-top: 1px solid var(--dw-wc-divider);\n background: #fff;\n}\n\n.wecom-composer .wecom-composer-card,\n.wecom-composer .wecom-composer-card:hover {\n min-height: clamp(116px, 23vh, 172px);\n display: flex;\n flex-direction: column;\n border: 0;\n border-radius: 0;\n background: inherit;\n box-shadow: none;\n}\n\n.wecom-composer-tools {\n position: relative;\n z-index: 431;\n gap: 7px;\n flex-wrap: wrap;\n padding: 7px max(12px, calc(var(--dw-wc-chat-inset) - 4px)) 1px;\n}\n\n.wecom-composer-tools :is(.wecom-icon-btn, .wecom-composer-decoration) { width: 33px; height: 33px; color: var(--wc-text-2); }\n.wecom-composer-tools :is(.wecom-icon-btn, .wecom-composer-decoration) svg { width: 21px; height: 21px; }\n.wecom-composer-decoration { display: inline-flex; align-items: center; justify-content: center; }\n.wecom-composer-decoration.with-caret { width: 42px; gap: 5px; }\n.wecom-composer-decoration.with-caret::after { content: ''; border: 3px solid transparent; border-bottom: 0; border-top-color: currentColor; }\n.wecom-composer-tools .wecom-icon-btn:disabled { opacity: .42; cursor: default; }\n.wecom-composer-tools .wecom-compose-status { flex: 1; text-align: right; }\n.wecom-composer [hidden] { display: none !important; }\n.wecom-composer-emoji {\n position: absolute;\n inset: 100% auto auto var(--dw-wc-chat-inset);\n display: flex;\n gap: 3px;\n padding: 6px;\n border: 1px solid var(--dw-wc-divider);\n border-radius: 8px;\n background: var(--wc-bg);\n box-shadow: 0 4px 12px #0002;\n}\n.wecom-composer-emoji button { border: 0; border-radius: 5px; padding: 4px; background: transparent; font-size: 19px; cursor: pointer; }\n.wecom-composer-emoji button:hover { background: var(--wc-hover); }\n.wecom-composer .wecom-send-btn { margin-right: 0; }\n.wecom-composer .wecom-send-btn:not(:disabled) { color: var(--dw-wc-ink); background: #e9f0fc; border-radius: 6px; }\n.wecom-composer .wecom-send-btn:not(:disabled):hover { background: #dce9fa; }\n\n.wecom-composer textarea.wecom-chat-compose {\n flex: 1 1 auto;\n min-height: 72px;\n padding: 8px var(--dw-wc-chat-inset) 12px;\n font-size: 15px;\n outline: 0;\n}\n\n.wecom-composer .wecom-composer-card:focus-within { outline: 2px solid #7da4db; outline-offset: -2px; }\n.wecom-composer .wecom-reply-target { margin-inline: var(--dw-wc-chat-inset); }\n\n:is(.wecom-rail, .wecom-list-panel, .wecom-chat-panel) :is(button, a):focus-visible {\n outline: 2px solid var(--wc-accent);\n outline-offset: -2px;\n}\n\n@media (max-width: 1000px) {\n .wecom-im-theme { --wc-nav: 60px !important; --dw-wc-header: 58px; }\n .wecom-rail-items { padding-inline: 6px; }\n .wecom-rail .wecom-rail-item > span:not(.wecom-rail-badge) { display: inline-flex !important; }\n .wecom-chat-header { gap: 6px; }\n .wecom-chat-tools, .wecom-chat-actions { gap: 0; }\n}\n\n@media (max-width: 520px) {\n .wecom-im-theme { --dw-wc-chat-inset: 13px; }\n .wecom-chat-tools { display: none; }\n .wecom-chat-title { font-size: 16px; }\n .wecom-msg { max-width: 100%; }\n}\n"; const FEISHU_LAYOUT_CSS = "html.wecom-im-theme.dw-feishu {\n --wc-nav: clamp(142px, 13vw, 234px);\n --wc-list: clamp(292px, 36.5vw, 550px);\n --wc-font: -apple-system, BlinkMacSystemFont, \"PingFang SC\", \"Microsoft YaHei\", sans-serif;\n --wc-bg: #fafbfd;\n --wc-text: #212a38;\n --wc-text-2: #495768;\n --wc-text-3: #687789;\n --wc-accent: #4159a5;\n --wc-hover: #eef2f8;\n --wc-bubble-other: #edf1f7;\n --wc-bubble-me: #e4ebfd;\n --dw-wc-header: 62px;\n --dw-wc-divider: #dae2ed;\n --dw-wc-ink: var(--wc-accent);\n --dw-fs-frame: #e1e8f2;\n --dw-fs-rail: linear-gradient(155deg, #e9f1f8 0%, #e3ecf5 47%, #dfe5f0 100%);\n --dw-fs-rail-ink: #34465a;\n --dw-fs-rail-icon: #878d95;\n --dw-fs-rail-active: #f9fafc;\n --dw-fs-rail-active-ink: #1a1a1a;\n --dw-fs-rail-control: #d9e3ef;\n --dw-fs-rail-outline: #98abc6;\n --dw-fs-rail-avatar: #e0effd;\n --dw-fs-profile-ink: #6c89ae;\n --dw-fs-selection: #e8edfc;\n --dw-fs-strong: #334787;\n --dw-fs-gap: 6px;\n background: var(--dw-fs-frame);\n}\n\nhtml.wecom-im-theme.dw-feishu.wecom-dark {\n --wc-bg: #1c2c30;\n --wc-surface-1: var(--wc-bg);\n --wc-surface-2: #23383e;\n --wc-text: #e3efed;\n --wc-text-2: #b8cecb;\n --wc-text-3: #a5bcb9;\n --wc-accent: #7ee0c7;\n --wc-bubble-other: #2a4046;\n --wc-bubble-me: #234e47;\n --wc-divider: #395058;\n --dw-wc-divider: var(--wc-divider);\n --dw-fs-frame: #122327;\n --dw-fs-rail: #172f38;\n --dw-fs-rail-ink: #d5e8eb;\n --dw-fs-rail-icon: #b7d0d3;\n --dw-fs-rail-active: #35636a;\n --dw-fs-rail-active-ink: #f0fffc;\n --dw-fs-rail-control: #304f59;\n --dw-fs-rail-outline: #658a8f;\n --dw-fs-rail-avatar: #2c6e73;\n --dw-fs-profile-ink: #d5e8eb;\n --dw-fs-selection: #28534c;\n --dw-fs-strong: #c9f2e8;\n}\n\nhtml.wecom-im-theme.dw-feishu,\nhtml.wecom-im-theme.dw-feishu body { background: var(--dw-fs-frame) !important; }\n\n.dw-feishu :is(.wecom-rail, .wecom-list-panel, .wecom-chat-panel) {\n top: var(--dw-fs-gap);\n bottom: var(--dw-fs-gap);\n overflow: hidden;\n border: 0;\n border-radius: 13px;\n}\n\nhtml.wecom-im-theme.dw-feishu .wecom-rail {\n inset: 0 auto 0 0;\n width: calc(var(--wc-nav) - 2px);\n padding: 38px 0 12px;\n border-radius: 0 13px 13px 0;\n background: var(--dw-fs-rail) !important;\n}\n\n.dw-feishu .wecom-rail-head {\n height: 34px;\n flex-basis: 34px;\n justify-content: space-between;\n padding: 0 11px;\n}\n\n.dw-feishu .wecom-rail-head .me-chip { width: 27px; height: 27px; flex-basis: 27px; }\n.dw-feishu .wecom-rail .wecom-rail-avatar { width: 27px; height: 27px; border-radius: 50%; background: var(--dw-fs-rail-avatar) !important; }\n.dw-feishu .wecom-rail-avatar > span > span { display: none; }\n.dw-feishu .dw-feishu-profile-icon { display: block; width: 14px; height: 14px; color: var(--dw-fs-profile-ink); }\n.dw-feishu .wecom-rail-items { gap: 3.5px; padding: 2.5px 7px 0; }\n.dw-feishu .wecom-rail-bottom { display: flex; gap: 7px; padding: 0 13px; }\n\nhtml.wecom-im-theme.dw-feishu .wecom-rail-item {\n --dw-wc-rail-row: 29px;\n flex-direction: row;\n justify-content: flex-start;\n gap: 8px;\n padding: 0 8px;\n line-height: 1.15;\n font-size: 13px;\n color: var(--dw-fs-rail-ink) !important;\n text-align: start;\n}\n\nhtml.wecom-im-theme.dw-feishu .wecom-rail-item svg {\n width: 17px;\n height: 17px;\n color: var(--dw-fs-rail-icon) !important;\n padding: 0;\n background: none;\n}\n\nhtml.wecom-im-theme.dw-feishu .wecom-rail-item.active {\n color: var(--dw-fs-rail-active-ink) !important;\n background: var(--dw-fs-rail-active) !important;\n box-shadow: none;\n}\nhtml.wecom-im-theme.dw-feishu .wecom-rail-item[data-rail-key=\"chat\"].active { font-weight: 650; }\nhtml.wecom-im-theme.dw-feishu .wecom-rail-item.active svg { color: currentColor !important; }\n\n.dw-feishu .wecom-rail-badge { top: 7px; right: 8px; min-width: 17px; height: 14px; line-height: 14px; box-shadow: none; }\nhtml.wecom-im-theme.dw-feishu .wecom-rail-head .wecom-rail-item,\nhtml.wecom-im-theme.dw-feishu .wecom-rail-bottom .wecom-rail-item {\n flex: 0 0 24px;\n width: 24px;\n min-width: 24px;\n height: 24px;\n min-height: 24px;\n padding: 0;\n justify-content: center;\n border-radius: 7px;\n}\n.dw-feishu :is(.wecom-rail-head, .wecom-rail-bottom) .wecom-rail-item > span { display: none !important; }\n.dw-feishu .wecom-rail-head .wecom-rail-item svg { width: 20px; height: 20px; }\n.dw-feishu .wecom-rail-bottom .wecom-rail-item svg { width: 14px; height: 14px; }\nhtml.wecom-im-theme.dw-feishu .wecom-rail-bottom .wecom-rail-item { background: var(--dw-fs-rail-control); }\n.dw-feishu .wecom-rail-item[data-rail-key=\"appearance\"] { border: 1px solid var(--dw-fs-rail-outline); }\n\nhtml.wecom-im-theme.dw-feishu .wecom-list-panel {\n width: calc(var(--wc-list) - var(--dw-fs-gap));\n background: var(--wc-bg) !important;\n}\n\n.dw-feishu-list-heading {\n display: flex;\n align-items: center;\n flex: 0 0 44px;\n margin: 0;\n padding: 0 22px;\n border-bottom: 1px solid var(--dw-wc-divider);\n font: 650 21px/1.15 var(--wc-font);\n color: var(--wc-text);\n}\n\n.dw-feishu-list-heading::before {\n content: '';\n width: 4px;\n height: 17px;\n margin-inline-end: 10px;\n border-radius: 2px;\n background: var(--wc-accent);\n}\n.dw-feishu-list-heading[hidden], .dw-feishu-pin[hidden] { display: none; }\n.dw-feishu .dw-feishu-rail-assistant { cursor: default; }\n.dw-feishu .dw-feishu-rail-assistant:hover { background: transparent; }\n.dw-feishu .dw-feishu-assistant-avatar { border-radius: 50%; flex: none; }\nhtml.wecom-im-theme.dw-feishu .dw-feishu-rail-assistant .dw-feishu-assistant-avatar { width: 16px; height: 16px; }\n.dw-feishu-pin {\n display: grid;\n flex: none;\n align-self: flex-start;\n justify-items: center;\n gap: 3px;\n margin: 3px 14px 0;\n padding: 4px 6px 5px;\n color: var(--wc-text-2);\n font-size: 11px;\n}\n.dw-feishu-pin .dw-feishu-assistant-avatar { width: 33px; height: 33px; }\n.dw-feishu .wecom-list-search { height: 44px; flex-basis: 44px; border: 0; }\n.dw-feishu .wecom-rail .wecom-list-search { margin-top: 2px; padding: 0 7px; }\n.dw-feishu .wecom-rail .wecom-list-add { display: none; }\nhtml.wecom-im-theme.dw-feishu .wecom-rail .wecom-list-search form {\n min-width: 0;\n height: 29px;\n padding: 0 9px;\n color: var(--dw-fs-rail-ink) !important;\n background: var(--dw-fs-rail-control) !important;\n box-shadow: inset 0 0 0 1px rgb(72 95 127 / 13%);\n border-radius: 7px;\n}\nhtml.wecom-im-theme.dw-feishu .wecom-rail .wecom-list-search form :is(input, svg),\nhtml.wecom-im-theme.dw-feishu .wecom-rail .wecom-list-search form input::placeholder {\n color: var(--dw-fs-rail-ink) !important;\n}\n.dw-feishu .wecom-rail .wecom-list-search form:focus-within { outline: 2px solid var(--wc-accent); }\n.dw-feishu .dw-feishu-search-key:not([hidden]) {\n flex: none;\n padding: 1px 3px;\n border-radius: 4px;\n color: var(--dw-fs-rail-icon);\n font: 10px/1.3 var(--wc-font);\n white-space: nowrap;\n}\n.dw-feishu .wecom-list-body { padding: 8px; }\n\n.dw-feishu .wecom-conv {\n min-height: 54px;\n margin-block-end: 2px;\n padding: 7px 13px;\n border-radius: 9px;\n gap: 10px;\n transition: none;\n}\n\n.dw-feishu .wecom-conv::after { left: 58px; }\n.dw-feishu .wecom-conv-avatar { width: 34px; height: 34px; border-radius: 50%; }\n.dw-feishu .wecom-conv-info { grid-template-columns: minmax(0, 1fr) auto auto; row-gap: 4px; }\n.dw-feishu .wecom-conv-title { grid-area: 1 / 1; }\n.dw-feishu .wecom-conv-time { grid-area: 1 / 2 / 2 / 3; }\n.dw-feishu .wecom-conv-msg { grid-area: 2 / 1 / 3 / 3; }\n.dw-feishu .wecom-conv-badge { grid-area: 1 / 3 / 3 / 4; align-self: center; }\n.dw-feishu .wecom-conv-name { color: var(--wc-text); font-size: 14px; font-weight: 550; }\n.dw-feishu .wecom-conv-msg, .dw-feishu .wecom-conv-time { color: var(--wc-text-3); }\nhtml.wecom-im-theme.dw-feishu .wecom-conv.active { background: var(--dw-fs-selection) !important; }\n.dw-feishu .wecom-conv.active::before {\n position: absolute;\n inset: 12px auto 12px 0;\n width: 3px;\n border-radius: 2px;\n background: var(--wc-accent);\n content: '';\n}\nhtml.wecom-im-theme.dw-feishu .wecom-conv.active .wecom-conv-name { color: var(--dw-fs-strong) !important; }\nhtml.wecom-im-theme.dw-feishu .wecom-conv.active :is(.wecom-conv-msg, .wecom-conv-time) { color: var(--wc-text-2) !important; }\n\n.dw-feishu .wecom-chat-panel { right: var(--dw-fs-gap); }\nhtml.wecom-im-theme.dw-feishu.wecom-members-open .wecom-chat-panel { right: calc(var(--wc-members) + var(--dw-fs-gap)); }\nhtml.wecom-im-theme.dw-feishu :is(.wecom-chat-panel, .wecom-chat-header, .wecom-chat-body, .wecom-composer) {\n background: var(--wc-bg) !important;\n}\n.dw-feishu .wecom-chat-header { padding-inline: 20px; border-color: var(--dw-wc-divider); }\n.dw-feishu .wecom-chat-title { color: var(--wc-text); font-size: 18px; }\n.dw-feishu .wecom-chat-sub { color: var(--wc-text-3); }\n.dw-feishu .wecom-chat-avatar:not(:empty) {\n display: grid !important;\n place-items: center;\n width: 37px;\n height: 37px;\n border-radius: 50%;\n background: var(--dw-fs-selection);\n color: var(--dw-fs-strong);\n}\n.dw-feishu .wecom-chat-avatar img { width: 100%; height: 100%; object-fit: cover; }\n.dw-feishu .wecom-chat-avatar svg { width: 20px; height: 20px; }\nhtml.wecom-im-theme.dw-feishu .dw-feishu-group-avatar {\n display: grid;\n place-items: center;\n color: #fff;\n background: linear-gradient(135deg, #7565ec, #927eef) !important;\n}\n.dw-feishu .dw-feishu-group-avatar svg { width: 22px; height: 22px; }\n.dw-feishu .wecom-chat-body { padding-inline: clamp(16px, 2vw, 30px); }\n.dw-feishu .wecom-msg-avatar { width: 32px; height: 32px; border-radius: 50%; }\nhtml.wecom-im-theme.dw-feishu .wecom-msg-other .wecom-msg-bubble { background: var(--wc-bubble-other) !important; }\nhtml.wecom-im-theme.dw-feishu .wecom-msg-me .wecom-msg-bubble { background: var(--wc-bubble-me) !important; }\n.dw-feishu .wecom-msg .wecom-msg-bubble { padding: 10px 14px; border-radius: 4px 12px 12px !important; }\n.dw-feishu .wecom-msg-me .wecom-msg-bubble { border-radius: 12px 4px 12px 12px !important; }\n.dw-feishu .wecom-msg-meta { color: var(--wc-text-3); }\nhtml.wecom-im-theme.dw-feishu .wecom-reply-reference {\n background: var(--dw-fs-selection) !important;\n border-left-color: var(--wc-accent) !important;\n}\nhtml.wecom-im-theme.dw-feishu .wecom-reply-reference-label { color: var(--dw-fs-strong) !important; }\n\n.dw-feishu .wecom-composer { padding: 8px clamp(12px, 2vw, 26px) 14px; border: 0; }\n.dw-feishu .wecom-group-comments .wecom-composer { padding: 6px 8px 10px; }\n.dw-feishu .wecom-composer :is(.wecom-composer-card, .wecom-composer-card:hover) {\n min-height: auto;\n position: relative;\n display: grid;\n grid-template-columns: minmax(0, 1fr) repeat(5, auto);\n align-items: center;\n column-gap: 2px;\n padding: 3px 7px;\n border: 1px solid var(--dw-wc-divider);\n border-radius: 10px;\n background: var(--wc-bg);\n}\n.dw-feishu .wecom-composer .wecom-composer-card:focus-within { outline-color: var(--wc-accent); }\n.dw-feishu .wecom-composer-tools { display: contents; }\n.dw-feishu .wecom-composer-tools .wecom-composer-decoration { display: none; }\n.dw-feishu .wecom-composer-tools > button { grid-row: 2; }\n.dw-feishu .wecom-composer-tools .wecom-compose-status { grid-area: 3 / 1 / 4 / -1; text-align: start; }\n.dw-feishu .wecom-compose-status:not(:empty) { padding: 3px 8px 5px; }\n.dw-feishu .wecom-composer .wecom-reply-target {\n grid-area: 1 / 1 / 2 / -1;\n margin: 4px 3px 0;\n border-left-color: var(--wc-accent);\n background: var(--dw-fs-selection);\n color: var(--wc-text-2);\n}\n.dw-feishu .wecom-composer textarea.wecom-chat-compose {\n grid-area: 2 / 1;\n box-sizing: border-box;\n min-height: 40px;\n width: 100%;\n height: 46px;\n padding: 13px 8px 8px;\n font-size: 14px;\n line-height: 20px;\n resize: none;\n background: none;\n color: var(--wc-text);\n caret-color: var(--wc-accent);\n}\n.dw-feishu .wecom-composer textarea.wecom-chat-compose:disabled { -webkit-text-fill-color: var(--wc-text-3); }\n.dw-feishu .wecom-composer textarea.wecom-chat-compose::placeholder { color: var(--wc-text-3); }\n.dw-feishu .wecom-composer-emoji { inset: auto 8px calc(100% + 5px) auto; z-index: 431; }\n.dw-feishu .wecom-composer .wecom-send-btn { padding-inline: 10px; background: var(--wc-bubble-other); color: var(--wc-text-3); }\nhtml.wecom-im-theme.dw-feishu .wecom-composer .wecom-send-btn:not(:disabled) {\n color: var(--dw-fs-strong) !important;\n background: var(--dw-fs-selection) !important;\n}\n\n@media (max-width: 1230px) {\n .dw-feishu .wecom-chat-panel[data-douyin-group-comments-open] > .wecom-chat-body { margin-inline-end: 0; }\n .dw-feishu .wecom-group-comments { max-width: 94%; box-shadow: -6px 0 20px #0002; }\n}\n\n@media (max-width: 1100px) {\n html.wecom-im-theme.dw-feishu.wecom-members-open .wecom-chat-panel { right: var(--dw-fs-gap); }\n}\n\n@media (max-width: 1079px) {\n html.wecom-im-theme.dw-feishu { --wc-nav: 66px !important; }\n html.wecom-im-theme.dw-feishu .wecom-rail { padding-top: 8px; }\n .dw-feishu .wecom-rail-head { height: 62px; flex-basis: 62px; flex-direction: column; gap: 4px; padding: 0; }\n .dw-feishu .wecom-rail-bottom { justify-content: center; flex-wrap: wrap; gap: 3px; padding: 0 3px; }\n html.wecom-im-theme.dw-feishu .wecom-rail-item { justify-content: center; padding: 0; }\n html.wecom-im-theme.dw-feishu .wecom-rail-item > span:not(.wecom-rail-badge) { display: none !important; }\n .dw-feishu .wecom-rail .wecom-rail-badge { top: 3px; right: 2px; }\n}\n\n@media (max-width: 1000px) {\n html.wecom-im-theme.dw-feishu.wecom-locked .wecom-list-panel {\n width: calc(100% - var(--wc-nav) - var(--dw-fs-gap));\n }\n}\n\n@media (max-width: 520px) {\n html.wecom-im-theme.dw-feishu { --dw-fs-gap: 4px; --dw-wc-header: 54px; --wc-nav: 51px !important; }\n .dw-feishu .wecom-rail-head .me-chip, .dw-feishu .wecom-rail .wecom-rail-avatar { width: 29px; height: 29px; }\n .dw-feishu .wecom-chat-header { padding-inline: 8px; }\n .dw-feishu .wecom-chat-avatar:not(:empty) { width: 28px; height: 28px; }\n .dw-feishu .wecom-chat-title { font-size: 15px; }\n .dw-feishu .wecom-composer-tools button[data-composer-action=\"channels\"] { display: none; }\n .dw-feishu .wecom-composer :is(.wecom-composer-card, .wecom-composer-card:hover) { grid-template-columns: minmax(0, 1fr) repeat(4, auto); }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .dw-feishu :is(.wecom-chat-panel, .wecom-composer-card) { transition: none; }\n}\n"; // Douyin data and events for the verbatim WeCom presentation, loaded into its own document. const wecomWorkspaceGlyphs = { messages: '', conversations: '', group: '', hash: '', mail: '', docs: '', calendar: '', check: '', meeting: '', dots: '', workspace: '', profile: '', assistant: '', channelPicker: '', cloudDocs: '', table: '', camera: '', contacts: '', appGrid: '', history: '', contrast: '', original: '', face: '', scissors: '', picture: '', checklist: '', tiles: '', chatSearch: '', }; function createPristineChat(doc, actions) { const win = doc.defaultView; const site = workspaceSite(); const listeners = new win.AbortController(); const listen = (node, event, callback) => node.addEventListener(event, callback, { signal: listeners.signal }); const text = (value) => String(value ?? ''); const escape = (value) => text(value).replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', })[character]); const secureURL = (value, sameSite = false) => { if (!value) return ''; const url = workspaceSiteURL(value); return url && (!sameSite || workspaceSite(url)) ? url.href : ''; }; let model = {}; let listRows = []; let postRows = new Map(); let detailRows = new Map(); let selectedListRow; let renderedListMode; let renderedGroupAvatars; let chatMarkup = ''; let detailMarkup = ''; let mediaMarkup = ''; let bylineMarkup = ''; let listMode = 'messages'; let previousContentChannel; let membersOpen = false; let channelVisible = win.innerWidth > 1000; let conversationScroll = 0; let restoreConversationScroll = false; let commentScroll = 0; let threadRequest = ''; let detailItem; let activeDetailId = ''; let replyBranch = ''; let replyTarget; let postedReply; let sending = false; let composeScope = ''; const drafts = new Map(); const uncertainSubmissions = new Set(); const briefKey = 'douyin-content-workspace:wecom-channel-previews'; const groupKey = 'douyin-content-workspace:wecom-group'; const groupNames = site.groups; let selectedGroup = ''; try { selectedGroup = win.sessionStorage.getItem(groupKey) || ''; } catch { /* tab storage is optional */ } let detailMode = ''; let groupRow; let groupCommentsOpen = false; const briefs = readBriefs(); let lastPagination = 0; const noop = () => {}; function darkMode() { return model.colorMode === 'dark' || (model.colorMode === 'system' && win.matchMedia('(prefers-color-scheme: dark)').matches); } function showRailList(mode) { listMode = mode; channelVisible = false; update(model); actions.mediaRect?.(); } const presentation = createUpstreamWecomPresentation(doc, { applyListNavDom: noop, bindChatPanelEvents: noop, bindListPanelClicks: noop, bindOrgChip: noop, bindRailAvatarNotif: noop, bindSearchBox: noop, bindUserCardEvents: noop, bindWatermarkSettings: noop, checkForScriptUpdate: noop, convCategoryTag: () => '', disguiseAvatarForTopic: () => null, disguiseGridAvatar: () => '', ensureEditDialog: noop, ensureMaskAvatarToggle: noop, formatTime: displayTime, fullAvatarUrl: secureURL, getThemeMode: () => model.colorMode || 'light', getWatermarkSettings: () => ({ enabled: false }), groupAvatarHtml: () => '', isDarkMode: darkMode, isGridMaskTopic: () => false, isGroupConversation: () => false, isMaskAvatar: () => false, isMyPost: (post) => Boolean(post.mine), isNav2Open: () => false, likedPosts: new Set(), loadMoreList: noop, navigateInApp: (path) => showRailList(path === '/unseen' ? 'unread' : 'messages'), normalizeUsername: text, renderOrgChip: noop, renderWatermark: noop, replyReferenceInfo: (post) => post.reference, setNav2Open: noop, setThemeMode: actions.colorMode, syncRail: noop, topicHref: (topic) => topic.href || '#', userCardAttributes: () => '', wireComposeButton: noop, }); doc.documentElement.classList.add(presentation.ROOT_CLASS, presentation.LOCK_CLASS); presentation.injectStyle(); const layoutStyle = doc.createElement('style'); layoutStyle.id = 'douyin-wecom-layout'; layoutStyle.textContent = WE_COM_LAYOUT_CSS; doc.head.append(layoutStyle); const rail = presentation.ensureRail(); const railHead = rail.querySelector('.wecom-rail-head'); const railItems = rail.querySelector('.wecom-rail-items'); const railBottom = rail.querySelector('.wecom-rail-bottom'); const chatControl = railItems.querySelector('[data-rail-key="chat"]'); const unreadBadge = chatControl.querySelector('.wecom-rail-badge'); unreadBadge.style.removeProperty('display'); const channelsControl = railButton('channels', '频道', 'hash'); const railDecorations = [ ['邮件', 'mail'], ['文档', 'docs'], ['日程', 'calendar'], ['待办', 'check'], ['会议', 'meeting'], ['更多', 'dots'], ].map(([label, icon]) => decoration(label, icon, 'wecom-rail-item')); const feishuRailDecorations = [ ['云文档', 'cloudDocs'], ['多维表格', 'table'], ['视频会议', 'camera'], ['通讯录', 'contacts'], ['更多', 'appGrid'], ].map(([label, icon]) => decoration(label, icon, 'wecom-rail-item')); rail.setAttribute('aria-label', `${site.label}工作台导航`); railItems.setAttribute('role', 'group'); railItems.setAttribute('aria-label', '内容导航'); rail.querySelector('.wecom-rail-groups').remove(); const switchView = railButton('appearance', '飞书式', 'workspace'); const historyControl = railButton('history', '浏览记录', 'history'); const contrastControl = railButton('contrast', '切换浅色或深色', 'contrast'); const nativeControl = railButton('native', `切换到${site.label}原版`, 'original'); let railTheme; doc.querySelector('.wecom-theme-menu')?.remove(); const list = presentation.ensureListPanel(); const panel = presentation.ensureChatPanel(); const memberPanel = presentation.ensureMemberPanel(); const listBody = list.querySelector('.wecom-list-body'); const listFooter = doc.createElement('div'); const searchArea = list.querySelector('.wecom-list-search'); const searchBox = searchArea.querySelector('input'); const searchShortcut = doc.createElement('kbd'); searchShortcut.className = 'dw-feishu-search-key'; searchShortcut.textContent = /Mac|iPhone|iPad/i.test(win.navigator.platform) ? '⌘ K' : 'Ctrl K'; searchShortcut.setAttribute('aria-hidden', 'true'); searchShortcut.hidden = true; searchBox.after(searchShortcut); const listHeading = doc.createElement('h1'); listHeading.className = 'dw-feishu-list-heading'; listHeading.hidden = true; list.prepend(listHeading); const assistantPin = doubaoBadge('dw-feishu-pin'); listBody.before(assistantPin); const assistantRail = doubaoBadge('wecom-rail-item dw-feishu-rail-assistant'); const wideNav = win.matchMedia('(min-width: 1080px)'); const feishuStyle = doc.createElement('style'); feishuStyle.id = 'douyin-feishu-layout'; feishuStyle.textContent = FEISHU_LAYOUT_CSS; const chatBody = panel.querySelector('.wecom-chat-body'); const chatHeading = panel.querySelector('.wecom-chat-head-main'); const chatTitle = panel.querySelector('.wecom-chat-title'); const chatSubtitle = panel.querySelector('.wecom-chat-sub'); const chatAvatar = panel.querySelector('.wecom-chat-avatar'); const memberButton = panel.querySelector('.wecom-chat-tools [title="users"]'); const refresh = panel.querySelector('.wecom-chat-refresh'); const refreshText = doc.createElement('span'); refreshText.hidden = true; refresh.append(refreshText); const commentsButton = doc.createElement('button'); commentsButton.type = 'button'; commentsButton.className = 'wecom-icon-btn wecom-comments-jump'; commentsButton.hidden = true; refresh.before(commentsButton); const composer = panel.querySelector('.wecom-chat-compose'); const toolbar = panel.querySelector('.wecom-composer-tools'); const send = panel.querySelector('.wecom-send-btn'); const replyBox = panel.querySelector('.wecom-reply-target'); const status = panel.querySelector('.wecom-compose-status'); const closeDetail = doc.createElement('button'); closeDetail.type = 'button'; closeDetail.className = 'wecom-icon-btn'; closeDetail.dataset.douyinAction = 'close-detail'; closeDetail.setAttribute('aria-label', '返回会话'); closeDetail.title = '返回会话'; closeDetail.innerHTML = ''; const detailAuthor = doc.createElement('div'); detailAuthor.className = 'wecom-detail-author'; const detailAvatar = doc.createElement('span'); detailAvatar.className = 'wecom-msg-avatar'; const detailWork = doc.createElement('div'); detailWork.className = 'wecom-detail-work'; const detailName = doc.createElement('span'); detailName.className = 'wecom-detail-name'; const detailMedia = doc.createElement('div'); detailMedia.className = 'wecom-detail-media'; detailWork.append(detailMedia, detailName); detailAuthor.append(detailAvatar, detailWork); const detailComments = doc.createElement('div'); detailComments.className = 'wecom-detail-comments'; const composePanel = composer.closest('.wecom-composer'); const groupPane = doc.createElement('aside'); groupPane.className = 'wecom-group-comments'; groupPane.setAttribute('aria-label', '视频评论'); groupPane.hidden = true; const groupHeader = doc.createElement('div'); groupHeader.className = 'wecom-group-comments-header'; const groupHeading = doc.createElement('strong'); const groupVideoTitle = doc.createElement('div'); groupVideoTitle.className = 'wecom-group-comments-video'; const closeGroupPane = doc.createElement('button'); closeGroupPane.className = 'wecom-icon-btn'; closeGroupPane.type = 'button'; closeGroupPane.setAttribute('aria-label', '关闭评论'); closeGroupPane.title = '关闭评论'; closeGroupPane.textContent = '×'; groupHeader.append(groupHeading, closeGroupPane); groupPane.append(groupHeader, groupVideoTitle); panel.append(groupPane); function composerTool(key, label, icon) { const button = iconButton(label, icon); button.className = 'wecom-icon-btn'; button.dataset.composerAction = key; return button; } const emojiTool = composerTool('emoji', '插入表情', 'face'); const linkTool = composerTool('link', '插入作品链接', 'docs'); const tools = [ emojiTool, decoration('截图', 'scissors', 'wecom-composer-decoration', true), decoration('图片', 'picture', 'wecom-composer-decoration', true), linkTool, decoration('待办', 'checklist', 'wecom-composer-decoration', true), composerTool('channels', '打开频道列表', 'tiles'), composerTool('search', `搜索${site.label}`, 'chatSearch'), ]; const emojiPicker = doc.createElement('div'); emojiPicker.id = 'douyin-wecom-emoji'; emojiPicker.className = 'wecom-composer-emoji'; emojiPicker.setAttribute('role', 'group'); emojiPicker.setAttribute('aria-label', '表情'); emojiPicker.hidden = true; emojiTool.setAttribute('aria-expanded', 'false'); emojiTool.setAttribute('aria-controls', emojiPicker.id); for (const emoji of ['😀', '😂', '👍', '❤️', '👏', '🎉']) { const button = doc.createElement('button'); button.type = 'button'; button.textContent = emoji; emojiPicker.append(button); } toolbar.replaceChildren(...tools, status, send, emojiPicker); composer.placeholder = ''; composer.title = '回车发送,Shift+回车换行'; const brand = rail.querySelector('.me-chip'); brand.title = `${site.label}账号头像`; brand.setAttribute('role', 'img'); brand.setAttribute('aria-label', brand.title); rail.querySelector('.wecom-current-user-name').textContent = site.label; const railAvatar = rail.querySelector('.wecom-rail-avatar'); const accountImage = doc.createElement('img'); accountImage.alt = ''; accountImage.hidden = true; const avatarFallback = doc.createElement('span'); const avatarLetter = doc.createElement('span'); avatarLetter.textContent = site.label[0]; const profileIcon = drawIcon('profile'); profileIcon.classList.add('dw-feishu-profile-icon'); avatarFallback.append(avatarLetter, profileIcon); railAvatar.replaceChildren(avatarFallback, accountImage); listen(accountImage, 'error', () => { accountImage.hidden = true; avatarFallback.hidden = false; }); chatControl.setAttribute('aria-label', '消息'); chatControl.title = '消息'; function drawIcon(icon) { const template = doc.createElement('template'); template.innerHTML = ``; return template.content.firstElementChild; } function decoration(label, icon, className, caret = false) { const item = doc.createElement('span'); item.className = className; item.dataset.glyph = icon; item.setAttribute('aria-hidden', 'true'); item.append(drawIcon(icon)); if (caret) item.classList.add('with-caret'); if (label && className === 'wecom-rail-item') { const caption = doc.createElement('span'); caption.textContent = label; item.append(caption); } return item; } function iconButton(label, icon) { const button = doc.createElement('button'); button.type = 'button'; button.setAttribute('aria-label', label); button.dataset.glyph = icon; button.title = label; button.append(drawIcon(icon)); return button; } function railButton(key, label, icon) { const button = iconButton(label, icon); button.className = 'wecom-rail-item'; button.dataset.railKey = key; const caption = doc.createElement('span'); caption.textContent = label; button.append(caption); return button; } function doubaoBadge(className) { const badge = doc.createElement('div'); badge.className = className; badge.hidden = true; const avatar = drawIcon('assistant'); avatar.classList.add('dw-feishu-assistant-avatar'); const label = doc.createElement('span'); label.textContent = '豆包工作'; badge.append(avatar, label); return badge; } function updateAppearance() { const feishu = model.theme === 'feishu'; if (feishu && !feishuStyle.isConnected) doc.head.append(feishuStyle); doc.documentElement.classList.toggle('dw-feishu', feishu); listHeading.hidden = !feishu; assistantRail.hidden = !feishu; assistantPin.hidden = !feishu || listMode !== 'messages'; if (railTheme !== model.theme) { railTheme = model.theme; chatControl.querySelector('svg').replaceWith(drawIcon(feishu ? 'conversations' : 'messages')); channelsControl.querySelector('svg').replaceWith(drawIcon(feishu ? 'channelPicker' : 'hash')); if (feishu) { railHead.append(channelsControl); railItems.replaceChildren(chatControl, assistantRail, ...feishuRailDecorations); railBottom.replaceChildren(switchView, historyControl, contrastControl, nativeControl); } else { railItems.replaceChildren(chatControl, channelsControl, ...railDecorations); railBottom.replaceChildren(switchView); } } const label = feishu ? '企微式' : '飞书式'; if (switchView.title !== `切换到${label}`) { switchView.title = `切换到${label}`; switchView.setAttribute('aria-label', switchView.title); switchView.querySelector('span').textContent = label; } const searchHost = feishu && wideNav.matches ? rail : list; searchShortcut.hidden = searchHost !== rail; if (searchArea.parentElement === searchHost) return; const focused = doc.activeElement === searchBox; if (searchHost === rail) railItems.before(searchArea); else listHeading.after(searchArea); if (focused) searchBox.focus({ preventScroll: true }); } function updateFeishuHeader() { if (model.theme !== 'feishu') return; listHeading.textContent = listMode === 'channels' ? '频道' : listMode === 'unread' ? '未读消息' : '消息'; const group = isGroup(); const item = detailItem && !group ? (model.active?.id === detailItem.id ? model.active : detailItem) : null; const avatar = workAvatar(item); const label = chatTitle.textContent.trim(); const avatarKey = JSON.stringify([avatar, label, Boolean(item), group]); if (chatAvatar.dataset.avatarKey !== avatarKey) { chatAvatar.dataset.avatarKey = avatarKey; const contents = avatar ? `` : item ? escape(Array.from(item.author || label)[0]) : ''; chatAvatar.innerHTML = contents; chatAvatar.classList.toggle('dw-feishu-group-avatar', group); if (!item && label) chatAvatar.append(drawIcon(group ? 'group' : 'messages')); } } function syncRailNavigation() { const unread = (model.channels || []).reduce((total, channel) => total + (Number(channel.unread) || 0), 0); unreadBadge.textContent = unread > 99 ? '99+' : unread || ''; unreadBadge.hidden = !unread; unreadBadge.setAttribute('aria-hidden', 'true'); const history = listMode === 'messages' && model.route?.kind === 'history'; for (const [control, active] of [ [chatControl, listMode === 'messages' && !history], [channelsControl, listMode === 'channels'], [historyControl, history], ]) { control.classList.toggle('active', active); control.setAttribute('aria-pressed', String(active)); } const avatar = secureURL(model.accountAvatar); if ((accountImage.getAttribute('src') || '') !== avatar) { if (avatar) accountImage.src = avatar; else accountImage.removeAttribute('src'); accountImage.hidden = !avatar; avatarFallback.hidden = Boolean(avatar); } } function readBriefs() { try { return new Map(JSON.parse(win.sessionStorage.getItem(briefKey) || '[]')); } catch { return new Map(); } } function rememberBrief(channel, item) { if (!item || !['curated', 'recommend'].includes(channel?.kind)) return; const { id, title, author, avatar, cover } = item; const previous = briefs.get(channel.label); const time = item.time || (previous?.id === id ? previous.time : '') || ''; const brief = { id, title, author, avatar, cover, time }; if (JSON.stringify(previous) === JSON.stringify(brief)) return; briefs.set(channel.label, brief); try { win.sessionStorage.setItem(briefKey, JSON.stringify([...briefs])); } catch { // The current view still has the preview if tab storage is unavailable. } } function displayTime(value) { const date = text(value).match(/^\d{4}-(\d{2})-(\d{2})(?:T.*)?$/); return date ? `${Number(date[1])}/${Number(date[2])}` : text(value); } function isGroup() { return Object.hasOwn(groupNames, selectedGroup) && model.selectedChannel === selectedGroup; } function chooseGroup(id) { selectedGroup = id; try { if (id) win.sessionStorage.setItem(groupKey, id); else win.sessionStorage.removeItem(groupKey); } catch { /* the current view retains the group */ } } function buildListRows() { const channels = model.channels || []; const groups = listMode === 'messages' ? channels.filter((channel) => Object.hasOwn(groupNames, channel.id)).map((channel) => { const brief = briefs.get(channel.label); return { channel, group: true, title: groupNames[channel.id], href: channel.href, preview: [brief?.author, brief?.title].filter(Boolean).join(' · '), time: brief?.time, selected: channel.id === selectedGroup && isGroup(), }; }) : []; if (listMode === 'messages' && !model.demoMessages) { const items = model.items?.length ? model.items : model.active ? [model.active] : []; return groups.concat(items.map((item) => { const active = site.id === 'zhihu' && model.active?.id === item.id ? model.active : null; const author = active?.author || item.author; const titleFirst = site.id === 'zhihu' && !author; return { item, title: author || (titleFirst ? item.title : '作者名未显示'), preview: titleFirst ? item.summary : item.title, time: item.time, avatar: secureURL(active?.avatar) || workAvatar(item), href: item.url, selected: !isGroup() && item.id === detailItem?.id, }; })); } return groups.concat(channels.filter((channel) => listMode === 'channels' || (listMode === 'unread' ? channel.unread > 0 : channel.kind === 'demo')).map((channel) => { const brief = briefs.get(channel.label); return { channel, title: channel.label, unread: channel.unread, href: channel.href, preview: channel.preview || [brief?.author, brief?.title].filter(Boolean).join(' · '), time: brief?.time || channel.messages?.at(-1)?.time, avatar: workAvatar(brief), selected: channel.id === model.selectedChannel, }; })); } function renderList() { const rows = buildListRows(); const modeChanged = renderedListMode !== listMode; const useGroupAvatars = model.theme === 'feishu'; const contentsChanged = modeChanged || useGroupAvatars !== renderedGroupAvatars || listRows.length !== rows.length || rows.some((entry, index) => { const previous = listRows[index]; return entry.item?.id !== previous.item?.id || entry.channel?.id !== previous.channel?.id || entry.group !== previous.group || entry.title !== previous.title || entry.preview !== previous.preview || entry.time !== previous.time || entry.avatar !== previous.avatar || entry.href !== previous.href || entry.unread !== previous.unread; }); listRows = rows; renderedListMode = listMode; renderedGroupAvatars = useGroupAvatars; if (contentsChanged) { const scroll = modeChanged ? 0 : listBody.scrollTop; listBody.innerHTML = rows.map((entry, index) => { const id = index + 1; return presentation.convRowHtml({ id, title: entry.title, unread: entry.unread, created_at: entry.time, last_poster_username: entry.preview, href: secureURL(entry.href, true), posters: [{ user_id: id }], }, { [id]: { name: entry.title, avatar_template: entry.avatar } }); }).join(''); for (const row of listBody.querySelectorAll('.wecom-conv')) { const entry = rows[Number(row.dataset.topicId) - 1]; const summary = row.querySelector('.wecom-conv-msg'); summary.textContent = entry.preview; summary.title = entry.preview; row.querySelector('.wecom-conv-time').title = entry.time || ''; if (entry.item) row.dataset.douyinMidItem = entry.item.id; else row.dataset.channelId = entry.channel.id; if (entry.group) { row.dataset.douyinGroup = entry.channel.id; if (useGroupAvatars) { const avatar = row.querySelector('.wecom-conv-avatar'); avatar.classList.add('dw-feishu-group-avatar'); avatar.replaceChildren(drawIcon('group')); } } } listBody.scrollTop = scroll; } const footer = listMode === 'messages' ? feedPagination() : ''; if (footer !== listFooter.innerHTML) listFooter.innerHTML = footer; if (footer && listFooter.parentElement !== listBody) listBody.append(listFooter); else if (!footer) listFooter.remove(); const index = rows.findIndex((entry) => entry.selected); const selection = index < 0 ? null : listBody.querySelector(`.wecom-conv[data-topic-id="${index + 1}"]`); if (selection === selectedListRow) return; selectedListRow?.classList.remove('active'); selectedListRow?.removeAttribute('aria-current'); selection?.classList.add('active'); selection?.setAttribute('aria-current', 'true'); selectedListRow = selection; } function detailAction(action, label) { return ``; } function feedPagination() { if (!model.items?.length || model.nativeGate) return ''; let content; if (model.route?.kind === 'recommend' && model.canStep) { content = detailAction('next-recommendation', '加载下一条推荐'); } else if (['curated', 'search'].includes(model.route?.kind)) { if (model.feedState === 'ended') content = '已看到底'; else if (model.feedState === 'loading') content = '正在加载更多…'; else if (model.canLoadMore) { content = detailAction('load-feed', model.feedState === 'retry' ? '加载超时,点此重试' : '加载更多'); } } return content ? `
${content}
` : ''; } function workAvatar(item) { return secureURL(item?.avatar || item?.avatarUrl) || secureURL(item?.cover || item?.coverUrl); } function appendPost(rows, record, kind, content, parent) { const number = rows.length + 1; const caption = record.author || record.name || ''; const reference = parent ? { number: parent.number, name: parent.record.author || '抖音', preview: parent.record.text || parent.record.title, href: `#post_${parent.number}`, } : null; const post = { id: number, post_number: number, name: caption, username: caption, avatar_template: kind === 'video' ? workAvatar(record) : secureURL(record.avatar ?? record.avatarUrl), created_at: record.time, cooked: content, mine: Boolean(record.mine), reference, }; const row = { number, record, kind, post }; rows.push(row); return row; } function appendComments(rows, comments, parent, includeReplies) { for (const comment of comments || []) { const image = secureURL(comment.media); const body = `

${escape(comment.text)}

` + (image ? `` : ''); const replies = Math.max(Number(comment.replyCount) || 0, comment.replies?.length || 0); const more = replies || comment.canExpand ? `

${detailAction('expand-replies', replies ? `查看 ${replies} 条回复` : '查看更多回复')}

` : ''; const row = appendPost(rows, comment, 'comment', body + more, parent); if (includeReplies) appendComments(rows, comment.replies, row, true); } } function findComment(comments, id) { for (const comment of comments || []) { if (comment.id === id) return comment; const child = findComment(comment.replies, id); if (child) return child; } return undefined; } function decorateMessage(message, row) { message.dataset.douyinMessageKind = row.kind; const meta = message.querySelector('.wecom-msg-meta'); meta.firstElementChild?.remove(); if (!row.post.created_at) meta.firstElementChild?.remove(); if (!row.post.mine) meta.prepend(message.querySelector('.wecom-msg-name')); if (!meta.childElementCount) meta.remove(); const quote = message.querySelector('.wecom-reply-reference'); if (quote) { quote.querySelector('.wecom-reply-reference-label').textContent = row.post.reference.name; message.querySelector('.wecom-msg-bubble').prepend(quote); } const tools = message.querySelector('.wecom-msg-tools'); const reply = tools.querySelector('[data-action="reply"]'); if (row.kind === 'demo') { tools.remove(); return; } tools.replaceChildren(reply); if (row.kind === 'video') { reply.dataset.douyinAction = 'open-comments'; reply.title = '查看评论'; reply.setAttribute('aria-label', '查看评论'); } } function renderChat(selectedChannel) { const rows = []; for (const message of model.demoMessages || []) appendPost(rows, message, 'demo', `

${escape(message.text)}

`); for (const item of model.items || []) { appendPost(rows, item, 'video', renderDouyinMessageCard(item)); } const opened = isGroup() ? detailItem || model.active : model.active; if (opened && !(model.items || []).some((item) => item.id === opened.id)) { appendPost(rows, opened, 'video', renderDouyinMessageCard(opened)); } postRows = new Map(rows.map((row) => [row.number, row])); const footer = model.nativeGate ? `

${escape(model.nativeGate.message)} ${detailAction('login', '登录')}

` : rows.length ? feedPagination() : `
${model.loading ? '正在加载会话…' : '暂无可显示的内容'}
`; const markup = rows.map((row) => presentation.bubbleHtml(row.post, '')).join('') + footer; if (markup !== chatMarkup) { const scroll = restoreConversationScroll ? conversationScroll : chatBody.scrollTop; const kept = preserveGroupPlayer(markup, rows); if (!kept) chatBody.innerHTML = markup; chatMarkup = markup; for (const message of chatBody.querySelectorAll('.wecom-msg')) { if (message === kept) continue; decorateMessage(message, postRows.get(Number(message.dataset.postNumber))); } chatBody.scrollTop = scroll; } if (restoreConversationScroll) chatBody.scrollTop = conversationScroll; restoreConversationScroll = false; panel.dataset.empty = rows.length || model.nativeGate ? '0' : '1'; chatTitle.textContent = isGroup() ? groupNames[selectedGroup] : selectedChannel?.label || ''; chatSubtitle.textContent = model.route?.query || ''; showMembers(membersOpen && rows.length > 0); if (!memberPanel.hidden) { const posts = rows.map((row) => row.post).filter((post) => post.name && post.name !== '我'); presentation.renderMemberPanel({}, posts); } } function preserveGroupPlayer(markup, rows) { if (detailMode !== 'group' || groupRow?.parentElement !== chatBody || groupRow.dataset.douyinGroupPlaying !== detailItem?.id) return null; const selected = rows.find(({ record, kind }) => kind === 'video' && record.id === detailItem.id); if (!selected) return null; const template = doc.createElement('template'); template.innerHTML = markup; const replacement = template.content.querySelector(`[data-post-number="${selected.number}"]`); if (!replacement) return null; for (const node of [...chatBody.children]) if (node !== groupRow) node.remove(); let before = groupRow; for (const node of [...template.content.children]) { if (node === replacement) before = null; else chatBody.insertBefore(node, before); } groupRow.dataset.postNumber = String(selected.number); return groupRow; } function showMembers(show) { memberPanel.hidden = !show; if (show) memberPanel.style.removeProperty('display'); else { memberPanel.style.display = 'none'; doc.documentElement.classList.remove('wecom-members-open'); } } function setGroupComments(open) { groupCommentsOpen = open; groupPane.hidden = !open; panel.toggleAttribute('data-douyin-group-comments-open', open); const host = open ? groupPane : panel; if (composePanel.parentElement !== host) host.append(composePanel); } function mountDetail(group) { const mode = group ? 'group' : 'single'; if (detailMode === mode) return; if (detailMode) unmountDetail(); detailMode = mode; conversationScroll = chatBody.scrollTop; membersOpen = false; showMembers(false); memberButton.disabled = true; commentsButton.hidden = false; refresh.hidden = true; panel.dataset.empty = '0'; chatHeading.prepend(closeDetail); if (group) { chatBody.dataset.douyinGroupDetail = ''; groupPane.append(detailComments); setGroupComments(true); return; } chatBody.dataset.douyinDetail = ''; chatBody.replaceChildren(detailAuthor, detailComments); chatBody.scrollTop = 0; } function unmountDetail() { if (!detailMode) return; const group = detailMode === 'group'; detailMode = ''; if (group) { setGroupComments(false); delete chatBody.dataset.douyinGroupDetail; if (groupRow) delete groupRow.dataset.douyinGroupPlaying; groupRow = undefined; detailWork.prepend(detailMedia); } delete chatBody.dataset.douyinDetail; delete chatBody.dataset.douyinRepliesFor; memberButton.disabled = false; commentsButton.hidden = true; refresh.hidden = false; closeDetail.remove(); detailAvatar.replaceChildren(); detailName.textContent = ''; detailMedia.replaceChildren(); detailComments.replaceChildren(); if (!group) { chatBody.replaceChildren(); chatMarkup = ''; } restoreConversationScroll = true; detailRows.clear(); detailMarkup = ''; mediaMarkup = ''; bylineMarkup = ''; } function renderDetail() { const reading = ['answer', 'article', 'question'].includes(detailItem.kind); const group = isGroup() && !reading; mountDetail(group); let movedRow; if (group) { renderChat((model.channels || []).find((channel) => channel.id === model.selectedChannel)); const row = [...chatBody.querySelectorAll('[data-item-id]')] .find((card) => card.dataset.itemId === detailItem.id)?.closest('.wecom-msg'); if (row && row !== groupRow) { if (groupRow) delete groupRow.dataset.douyinGroupPlaying; groupRow = row; groupRow.dataset.douyinGroupPlaying = detailItem.id; groupRow.querySelector('.wecom-msg-bubble').append(detailMedia); movedRow = groupRow; } } const active = model.active?.id === detailItem.id; const cornerStyle = 'display:block;width:100%;height:auto;border-radius:8px'; const cover = secureURL(detailItem.cover ?? detailItem.coverUrl); const author = (active && model.active.author) || detailItem.author || site.label; const avatar = (active && secureURL(model.active.avatar)) || workAvatar(detailItem); const authorMarkup = avatar ? `` : escape(Array.from(author)[0]); if (authorMarkup !== bylineMarkup) { detailAvatar.innerHTML = authorMarkup; bylineMarkup = authorMarkup; } detailName.textContent = author; const wasReading = detailWork.hasAttribute('data-douyin-reading'); if (reading !== wasReading) { detailWork.toggleAttribute('data-douyin-reading', reading); if (reading) detailMedia.before(detailName); else detailMedia.after(detailName); } const media = reading ? renderReading(active ? model.active : detailItem) : getVideoItem() ? '
' : active && model.previewReady && model.mediaKind === 'image' ? `` : cover ? `${escape(detailItem.title)}` : ''; if (media !== mediaMarkup) { detailMedia.innerHTML = media; mediaMarkup = media; } detailMedia.hidden = !media; movedRow?.scrollIntoView({ block: 'nearest' }); const comments = active ? model.comments || [] : []; commentsButton.textContent = comments.length ? `评论 ${comments.length}` : '评论'; const branch = replyBranch && findComment(comments, replyBranch); if (branch) chatBody.dataset.douyinRepliesFor = branch.id; else delete chatBody.dataset.douyinRepliesFor; if (group) { groupHeading.textContent = branch ? '楼中楼' : commentsButton.textContent; groupVideoTitle.textContent = detailItem.title || '视频评论'; } else { chatTitle.textContent = detailItem.title || (reading ? '内容详情' : '视频详情'); chatSubtitle.textContent = branch ? '楼中楼回复' : reading ? '文章与回答' : '视频详情'; } const rows = []; appendComments(rows, branch ? [branch] : comments, null, Boolean(branch)); detailRows = new Map(rows.map((row) => [row.number, row])); const body = rows.map((row) => presentation.bubbleHtml(row.post, '')).join(''); const back = branch ? detailAction('all-comments', '返回全部评论') : ''; const title = branch || group ? '' : '
评论
'; const login = active && (model.previewError || (model.canLogin && !model.canCompose)) ? detailAction('login', `登录${site.label}`) : ''; const original = active && model.canOpenOriginalComments && !model.commentsOpen ? detailAction('original-comments', `在${site.label}查看评论`) : ''; const more = !branch && active && model.commentsOpen && model.canLoadMoreComments ? detailAction('more-comments', '加载更多评论') : ''; const emptyText = !active || model.commentsState === 'closed' || model.commentsState === 'loading' ? '正在加载评论…' : model.commentsState === 'empty' ? '暂无评论' : '评论暂未加载出来'; const empty = !branch && !rows.length && !login && !original ? `
${emptyText}
` : ''; const retry = active && !rows.length && model.canRetryComments ? detailAction('retry-comments', '重试加载评论') : ''; const markup = back + title + body + login + original + more + empty + retry; if (markup !== detailMarkup) { detailComments.innerHTML = markup; detailMarkup = markup; for (const node of detailComments.querySelectorAll('.wecom-msg')) { const row = detailRows.get(Number(node.dataset.postNumber)); node.dataset.commentId = row.record.id; decorateMessage(node, row); } } } function renderReading(item) { const body = item.bodyHtml || (item.summary ? `

${escape(item.summary)}

` : ''); const expand = item.canExpandContent ? detailAction('expand-content', '展开全文') : ''; const other = (item.otherAnswers || []).map((answer) => { const href = secureURL(answer.url, true); return href ? `
  • ${escape(answer.author || '知乎回答')}
  • ` : ''; }).join(''); return `
    ${body}${expand}${other ? `

    其他回答

      ${other}
    ` : ''}
    `; } function canSend() { return Boolean(canCompose() && composer.value.trim() && !sending && !uncertainSubmissions.has(submissionKey())); } function canCompose() { return Boolean(model.demoMessages || (model.canCompose && detailItem?.id === model.active?.id)); } function submissionKey() { return JSON.stringify([composeScope, replyTarget?.id || '', composer.value.trim()]); } function syncDraft() { const nextScope = model.demoMessages ? `demo:${model.selectedChannel}` : model.active?.id || ''; if (nextScope !== composeScope) { toggleEmoji(false); if (composeScope) drafts.set(composeScope, { text: composer.value, replyTarget }); const draft = drafts.get(nextScope); composeScope = nextScope; composer.value = draft?.text || ''; replyTarget = draft?.replyTarget; status.textContent = ''; } replyBox.hidden = !replyTarget; replyBox.querySelector('span').textContent = replyTarget ? `回复 ${replyTarget.author || '评论'}` : ''; composer.disabled = !canCompose(); composer.placeholder = model.theme === 'feishu' ? model.demoMessages ? '发送消息…' : detailItem ? '写评论…' : '打开一条内容后参与讨论' : ''; send.disabled = !canSend(); send.hidden = model.theme !== 'feishu' && !composer.value.trim(); emojiTool.disabled = composer.disabled; linkTool.disabled = composer.disabled || !secureURL(detailItem?.url, true); if (composer.disabled) toggleEmoji(false); } function toggleEmoji(open) { emojiPicker.hidden = !open; emojiTool.setAttribute('aria-expanded', String(open)); } function insertDraft(value) { if (composer.disabled || !value) return; composer.setRangeText(value, composer.selectionStart, composer.selectionEnd, 'end'); syncDraft(); composer.focus(); } async function submit() { if (!canSend()) return; const value = composer.value.trim(); const scope = composeScope; const key = submissionKey(); sending = true; status.textContent = `正在等待${site.label}确认…`; syncDraft(); try { const result = await actions.send?.(value, replyTarget); if (result?.pending) uncertainSubmissions.add(key); if (scope === composeScope) { status.textContent = result === true || result?.ok ? '' : (result?.message || '暂未确认发送'); if ((result === true || result?.ok) && submissionKey() === key) { postedReply = result?.posted; composer.value = ''; replyTarget = undefined; } } } catch { if (scope === composeScope) status.textContent = '暂时无法发送,草稿已保留。'; } finally { sending = false; syncDraft(); } } function resetDetail() { detailItem = undefined; activeDetailId = ''; replyBranch = ''; threadRequest = ''; commentScroll = 0; unmountDetail(); } function selectVideo(item) { detailItem = item; replyBranch = ''; commentScroll = 0; if (chatBody.hasAttribute('data-douyin-detail')) chatBody.scrollTop = 0; if (detailMode === 'group') detailComments.scrollTop = 0; } function openVideo(item) { if (!item) return; channelVisible = true; if (detailItem?.id !== item.id) { selectVideo(item); activeDetailId = ''; } if (isGroup() && detailMode === 'group' && !groupCommentsOpen) setGroupComments(true); threadRequest = item.id; update(model); actions.mediaRect?.(); actions.open?.(item); } function update(nextModel) { const channelChanged = model.selectedChannel && model.selectedChannel !== nextModel.selectedChannel; model = nextModel; if (channelChanged || (!model.active && activeDetailId) || model.demoMessages) resetDetail(); if (channelChanged) { restoreConversationScroll = false; chatBody.scrollTop = 0; } if (model.active && !model.demoMessages && (!detailItem || activeDetailId || detailItem.id === model.active.id)) { if (detailItem?.id !== model.active.id) { selectVideo(model.active); threadRequest = model.active.id; } activeDetailId = model.active.id; } if (model.status) status.textContent = model.status; const selectedChannel = (model.channels || []).find((channel) => channel.id === model.selectedChannel); rememberBrief(selectedChannel, model.items?.[0]); doc.documentElement.classList.toggle('wecom-dark', darkMode()); doc.body.classList.toggle('wecom-dark', darkMode()); doc.documentElement.classList.toggle('wecom-topic-open', channelVisible); updateAppearance(); syncRailNavigation(); renderList(); const refreshRecommendations = model.canRefreshFeed && !detailItem; refresh.toggleAttribute('data-douyin-refresh-feed', Boolean(refreshRecommendations)); refreshText.hidden = !refreshRecommendations; refresh.disabled = Boolean(refreshRecommendations && model.feedRefreshState === 'loading'); refreshText.textContent = refresh.disabled ? '正在换…' : '换一换'; refresh.title = refreshRecommendations ? model.feedRefreshState === 'retry' ? '暂未刷出新推荐,点击重试' : refreshText.textContent : '刷新本话题'; const confirmed = model.confirmedReplies?.find((reply) => reply.videoId === composeScope && uncertainSubmissions.has(reply.key)); if (confirmed) { uncertainSubmissions.delete(confirmed.key); if (submissionKey() === confirmed.key) { status.textContent = ''; composer.value = ''; replyTarget = undefined; postedReply = confirmed; } } const showPosted = postedReply && detailItem?.id === postedReply.videoId && findComment(model.comments || [], postedReply.commentId); if (showPosted && postedReply.threadId) replyBranch = postedReply.threadId; if (detailItem) renderDetail(); else renderChat(selectedChannel); updateFeishuHeader(); if (showPosted) { [...detailComments.querySelectorAll('[data-comment-id]')] .find((node) => node.dataset.commentId === postedReply.commentId)?.scrollIntoView({ block: 'nearest' }); postedReply = undefined; } syncDraft(); if (threadRequest && threadRequest === model.active?.id) { if (model.commentsOpen) threadRequest = ''; else if (model.canOpenComments) { threadRequest = ''; actions.openComments?.(); } } } function getMediaElement() { return detailMedia.querySelector('[data-douyin-media]'); } function getVideoItem() { if (!detailItem) return null; if (model.active?.id === detailItem.id && (model.previewError || model.mediaKind === 'image')) return null; const url = secureURL(detailItem.url, true); return detailItem.kind === 'video' && url && new URL(url).origin === location.origin && workspaceContent(url)?.id === detailItem.id ? detailItem : null; } function loadMoreNearEnd(scroller) { if (scroller === chatBody && detailMode === 'single') return; if (scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - 120) return; loadFeed(false); } function loadFeed(explicit) { if (model.nativeGate || (!explicit && Date.now() - lastPagination < 650)) return; const recommendation = model.route?.kind === 'recommend' && model.canStep; if (recommendation) { if (!explicit && detailItem) return; } else if (!model.canLoadMore || model.feedState === 'loading' || (!explicit && model.feedState === 'retry')) return; lastPagination = Date.now(); if (recommendation) actions.step?.(1); else actions.more?.(); } listen(listBody, 'click', (event) => { if (event.target.closest('[data-douyin-action="load-feed"], [data-douyin-action="next-recommendation"]')) { event.preventDefault(); loadFeed(true); return; } const row = event.target.closest('.wecom-conv'); if (!row) return; event.preventDefault(); const entry = listRows[Number(row.dataset.topicId) - 1]; if (!entry) return; channelVisible = true; doc.documentElement.classList.add('wecom-topic-open'); if (entry.item) { if (isGroup()) { replyBranch = ''; commentScroll = 0; } chooseGroup(''); openVideo(entry.item); } else { chooseGroup(entry.group ? entry.channel.id : ''); if (entry.channel.kind === 'history' && model.route?.kind !== 'history') previousContentChannel = model.selectedChannel; listMode = 'messages'; if (entry.group && entry.channel.id === model.selectedChannel && model.route?.kind === entry.channel.kind) { if (detailItem) hideVideoDetail(); else update(model); return; } update(model); actions.channel?.(entry.channel); } }); listen(listBody, 'scroll', () => { if (listMode === 'messages') loadMoreNearEnd(listBody); }); listen(listBody, 'wheel', (event) => { if (listMode === 'messages' && event.deltaY > 0) loadMoreNearEnd(listBody); }); listen(searchBox.form, 'submit', (event) => { event.preventDefault(); actions.search?.(searchBox.value); }); listen(composer, 'input', syncDraft); listen(composer, 'keydown', (event) => { if (event.key !== 'Enter' || event.isComposing || event.shiftKey) return; event.preventDefault(); void submit(); }); listen(send, 'click', () => { void submit(); }); listen(toolbar, 'click', (event) => { const action = event.target.closest('[data-composer-action]')?.dataset.composerAction; switch (action) { case 'emoji': toggleEmoji(emojiPicker.hidden); if (!emojiPicker.hidden) emojiPicker.firstElementChild.focus(); break; case 'link': insertDraft(secureURL(detailItem?.url, true)); break; case 'channels': showRailList('channels'); break; case 'search': focusSearch(); break; } }); listen(emojiPicker, 'click', (event) => { const button = event.target.closest('button'); if (!button) return; toggleEmoji(false); insertDraft(button.textContent); }); listen(doc, 'click', (event) => { if (!toolbar.contains(event.target) && !emojiPicker.hidden) toggleEmoji(false); }); listen(emojiPicker, 'keydown', (event) => { if (event.key !== 'Escape') return; toggleEmoji(false); emojiTool.focus(); }); listen(replyBox, 'click', (event) => { if (!event.target.closest('.wecom-reply-cancel')) return; replyTarget = undefined; syncDraft(); composer.focus(); }); listen(chatBody, 'scroll', () => { actions.mediaRect?.(); loadMoreNearEnd(chatBody); }); listen(chatBody, 'wheel', (event) => { if (event.deltaY > 0) loadMoreNearEnd(chatBody); }); function handleBubbleAction(event, scope, rows) { const control = event.target.closest('[data-douyin-action], [data-action], [data-reply-post-number]'); const row = rows.get(Number(event.target.closest('.wecom-msg')?.dataset.postNumber)); if (!control) { if (row?.kind === 'comment' && event.target.closest('.wecom-msg-bubble') && !win.getSelection()?.toString()) { selectReply(row.record); } return; } event.preventDefault(); if (control.dataset.replyPostNumber) { scope.querySelector(`[data-post-number="${Number(control.dataset.replyPostNumber)}"]`)?.scrollIntoView({ block: 'nearest' }); return; } switch (control.dataset.douyinAction) { case 'open-video': case 'open-comments': openVideo(row?.record || model.active); break; case 'next-recommendation': case 'load-feed': loadFeed(true); break; case 'all-comments': replyBranch = ''; renderDetail(); (detailMode === 'group' ? detailComments : chatBody).scrollTop = commentScroll; break; case 'expand-replies': if (row?.kind === 'comment') { const scroller = detailMode === 'group' ? detailComments : chatBody; if (!replyBranch) commentScroll = scroller.scrollTop; replyBranch = row.record.id; if (row.record.canExpand) actions.expandReplies?.(row.record); renderDetail(); if (scroller === detailComments) scroller.scrollTop = 0; else detailComments.scrollIntoView({ block: 'start' }); } break; case 'more-comments': actions.moreComments?.(); break; case 'expand-content': actions.expandContent?.(); break; case 'retry-comments': actions.openComments?.(true); break; case 'original-comments': actions.originalComments?.(); break; case 'login': actions.login?.(); break; default: if (control.dataset.action === 'reply' && row?.kind === 'comment') selectReply(row.record); } } function selectReply(comment) { if (comment.canReply === false) return; replyTarget = comment; syncDraft(); composer.focus(); } function hideVideoDetail() { const closedItemId = detailItem?.id; if (!closedItemId) return; resetDetail(); renderChat((model.channels || []).find((channel) => channel.id === model.selectedChannel)); syncDraft(); const opener = [...chatBody.querySelectorAll('[data-douyin-action="open-video"]')] .find((card) => card.dataset.itemId === closedItemId); opener?.focus({ preventScroll: true }); actions.close?.(); actions.mediaRect?.(); } listen(chatBody, 'click', (event) => { if (!detailComments.contains(event.target)) handleBubbleAction(event, chatBody, postRows); }); listen(detailComments, 'click', (event) => handleBubbleAction(event, detailComments, detailRows)); listen(closeDetail, 'click', hideVideoDetail); function hideGroupComments() { setGroupComments(false); commentsButton.focus({ preventScroll: true }); actions.mediaRect?.(); } listen(closeGroupPane, 'click', hideGroupComments); listen(groupPane, 'keydown', (event) => { if (event.key === 'Escape') hideGroupComments(); }); listen(doc, 'keydown', (event) => { if (!model.canStep || model.route?.kind !== 'recommend' || event.altKey || event.ctrlKey || event.metaKey || event.isComposing || event.target.closest?.('input,textarea,button,a,[contenteditable]')) return; if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return; event.preventDefault(); actions.step?.(event.key === 'ArrowUp' ? -1 : 1); }); listen(panel.querySelector('.wecom-chat-native'), 'click', () => actions.theme?.('native')); listen(commentsButton, 'click', () => { if (!model.commentsOpen && model.canOpenComments) actions.openComments?.(); if (detailMode === 'group') { setGroupComments(true); actions.mediaRect?.(); } else detailComments.scrollIntoView({ block: 'start' }); }); listen(refresh, 'click', () => { if (model.canRefreshFeed && !detailItem) { actions.refreshFeed?.(); lastPagination = Date.now(); listBody.scrollTop = 0; chatBody.scrollTop = 0; } else if (model.active) actions.openComments?.(); else actions.more?.(); }); listen(memberButton, 'click', () => { membersOpen = !membersOpen; update(model); actions.mediaRect?.(); }); function focusSearch() { if (listMode !== 'messages' || searchArea.parentElement !== rail) showRailList('messages'); searchBox.focus(); } listen(chatControl, 'click', () => { showRailList('messages'); if (model.route?.kind !== 'history') return; const channels = model.channels || []; const channel = channels.find(({ id }) => id === previousContentChannel) || channels.find(({ kind }) => kind === 'curated'); actions.channel?.(channel); }); listen(channelsControl, 'click', () => showRailList('channels')); listen(switchView, 'click', () => actions.theme?.(model.theme === 'feishu' ? 'wecom' : 'feishu')); listen(historyControl, 'click', () => { const channel = (model.channels || []).find(({ kind }) => kind === 'history'); if (!channel || model.selectedChannel === channel.id) return; previousContentChannel = model.selectedChannel; chooseGroup(''); listMode = 'messages'; channelVisible = true; actions.channel?.(channel); }); listen(contrastControl, 'click', () => actions.colorMode?.(darkMode() ? 'light' : 'dark')); listen(nativeControl, 'click', () => actions.theme?.('native')); listen(wideNav, 'change', updateAppearance); // Preserve the upstream list button and its dimensions, but take search through Douyin. listen(searchArea.querySelector('.wecom-list-add'), 'click', () => searchBox.focus()); return { update, getMediaElement, getVideoItem, focusSearch, destroy: () => listeners.abort(), }; } const INLINE_DOUYIN_CSS = ` html[data-dw-inline-page] body { overflow: hidden !important; background: #101318 !important; } html[data-dw-inline-page] [data-dw-inline-path] { overflow: visible !important; contain: none !important; transform: none !important; } html[data-dw-inline-page] [data-dw-inline-path] > :not( [data-dw-inline-path], [data-dw-inline-player], :has([id^="login-full-panel-"], #douyin_login_comp_flat_panel_title), [id^="login-full-panel-"], #douyin_login_comp_flat_panel_title ) { visibility: hidden !important; opacity: 0 !important; pointer-events: none !important; } html[data-dw-inline-page] :is([data-dw-native-comments], #comment-input-container) :is([contenteditable="true"], textarea, input) { visibility: visible !important; } html[data-dw-inline-page] [data-dw-inline-player] { position: fixed !important; inset: 0 !important; width: 100vw !important; height: 100vh !important; max-width: none !important; max-height: none !important; min-height: 0 !important; margin: 0 !important; transform: none !important; visibility: visible !important; overflow: hidden !important; background: #101318 !important; z-index: 2147482990 !important; } html[data-dw-inline-page] [data-dw-inline-player] :is(xg-video-container, .xg-video-container) { inset: 0 !important; width: 100% !important; height: 100% !important; } html[data-dw-inline-page] [data-dw-inline-player] video { width: 100% !important; height: 100% !important; inset: 0 !important; margin: 0 !important; object-fit: contain !important; } html[data-dw-inline-page] [data-dw-inline-player] :is( xg-top-bar, xg-left-bar, xg-right-bar, #video-info-wrap, #videoSideCard, #videoSideBar, [data-e2e="video-share-container"], .xgplayer-page-full-screen ) { display: none !important; } html[data-dw-inline-page] [data-dw-inline-player] :is(xg-controls,.xgplayer-controls) { z-index: 2147482991 !important; } html[data-dw-inline-page] [data-dw-inline-fullscreen-button] { position: absolute; inset: auto 6px 6px auto; z-index: 2147482992; display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0; border-radius: 4px; color: white; background: #101318b3; cursor: pointer; } html[data-dw-inline-page] [data-dw-inline-fullscreen-button][hidden] { display: none !important; } html[data-dw-inline-page] [data-dw-inline-player]:has([data-dw-inline-fullscreen-button]:not([hidden])) :is(xg-right-grid, .xg-right-grid) { margin-inline-end: 32px; } html[data-dw-inline-page] [data-dw-inline-fullscreen-button]:focus-visible { outline: 2px solid #90baff; } `; const INLINE_LOADING_TIMEOUT = 12000; const INLINE_BILIBILI_CSS = ` html[data-dw-inline-page], html[data-dw-inline-page] > body[data-dw-inline-path] { overflow: hidden !important; } /* Keep the site's player anchor visible when its document scrolls to load comments. */ html[data-dw-inline-page] #playerWrap[data-dw-inline-path] { position: fixed !important; inset: 0 !important; width: 100% !important; height: 100% !important; min-width: 0 !important; max-width: none !important; margin: 0 !important; } html[data-dw-inline-page] [data-dw-native-comments] { visibility: visible !important; } html[data-dw-inline-page] [data-dw-inline-player] :is(.bpx-player-container, .bpx-player-primary-area, .bpx-player-video-area, .bpx-player-video-perch, .bpx-player-video-wrap) { width: 100% !important; height: 100% !important; min-width: 0 !important; min-height: 0 !important; max-width: none !important; max-height: none !important; margin: 0 !important; } html[data-dw-inline-page] [data-dw-inline-player] .bpx-player-container[data-screen="mini"] { position: absolute !important; inset: 0 !important; transform: none !important; border-radius: 0 !important; box-shadow: none !important; } html[data-dw-inline-page] [data-dw-inline-player] .bpx-player-container[data-screen="mini"] .bpx-player-control-wrap { display: block !important; position: absolute !important; inset: auto 0 0 !important; } html[data-dw-inline-page] [data-dw-inline-player] .bpx-player-container[data-screen="mini"]:is(:hover, :focus-within) .bpx-player-control-bottom { transform: none !important; opacity: 1 !important; visibility: visible !important; pointer-events: auto !important; } html[data-dw-inline-page] [data-dw-inline-player] :is(video, bwp-video) { object-fit: contain !important; } html[data-dw-inline-page] [data-dw-inline-player] :is(.bpx-player-sending-area, .bpx-player-top-wrap, .bpx-player-extra-area, .bpx-player-mini-warp) { display: none !important; } `; function createInlineWorkspaceMedia(onChange) { let mounted; let saved; function snapshot(video) { if (!video) return null; return { time: video.currentTime, paused: video.paused, muted: video.muted, volume: video.volume, rate: video.playbackRate }; } function restore(video, state) { if (!video || !state) return; video.muted = state.muted; video.volume = state.volume; video.playbackRate = state.rate; if (Number.isFinite(state.time) && (state.time === 0 || video.readyState >= 1)) video.currentTime = state.time; if (state.paused) video.pause(); else video.play().catch(() => {}); } function watchBackground(entry, video) { if (entry.background === video) return; entry.background?.removeEventListener('play', entry.pauseBackground); entry.background = video; entry.backgroundWasPlaying = Boolean(video && !video.paused); video?.addEventListener('play', entry.pauseBackground); video?.pause(); } function unmount(resumeNative = false) { if (!mounted) return; const entry = mounted; mounted = undefined; const background = entry.background; const playback = snapshot(entry.video) || entry.restore || (resumeNative && snapshot(background)); if (playback && !entry.video && !entry.restore && (entry.backgroundWasPlaying || entry.autoplay)) playback.paused = false; if (playback) saved = { id: entry.id, playback, source: resumeNative ? entry.background : undefined }; entry.abort.abort(); entry.comments?.destroy(); clearTimeout(entry.loadingTimer); clearTimeout(entry.documentTimer); entry.stopDocument?.(); watchBackground(entry, undefined); entry.frame.remove(); entry.status.remove(); if (resumeNative) restore(background, playback); } function fail(entry) { if (mounted !== entry || entry.unavailable) return; entry.unavailable = true; entry.status.style.display = 'grid'; entry.message.textContent = '播放器暂未就绪'; entry.retry.hidden = false; if (entry.original) entry.original.hidden = false; } function load(entry) { entry.stopDocument?.(); entry.comments?.destroy(); entry.comments = undefined; entry.previousDocument = entry.frame.contentDocument; entry.document = undefined; entry.video?.pause(); entry.video = undefined; entry.unavailable = false; entry.message.textContent = '正在加载抖音播放器…'; entry.retry.hidden = true; if (entry.original) entry.original.hidden = true; entry.status.style.display = 'grid'; clearTimeout(entry.loadingTimer); clearTimeout(entry.documentTimer); entry.loadingTimer = setTimeout(() => { clearTimeout(entry.documentTimer); fail(entry); }, INLINE_LOADING_TIMEOUT); entry.frame.src = entry.url; function watchDocument() { if (connectDocument(entry, entry.frame.contentDocument)) return; entry.documentTimer = setTimeout(watchDocument, 80); } entry.documentTimer = setTimeout(watchDocument, 80); } function connectDocument(entry, doc) { if (mounted !== entry || doc === entry.previousDocument || !doc?.head || !doc.body) return false; const work = workspaceContent(doc.location?.href); if (work?.id !== entry.id || doc.location.origin !== location.origin) return false; clearTimeout(entry.documentTimer); if (entry.document === doc) return true; entry.previousDocument = undefined; entry.document = doc; try { prepareDocument(entry, doc); } catch { fail(entry); } onChange(); return true; } function prepareDocument(entry, doc) { entry.stopDocument?.(); const style = doc.createElement('style'); const bili = entry.site.id === 'bilibili'; const nativePlayerSelector = bili ? '#bilibili-player,#bofqi,.bpx-player-container' : '.basePlayerContainer, .xgplayer, .douyin-player, [data-e2e="player-container"]'; style.textContent = INLINE_DOUYIN_CSS + (bili ? INLINE_BILIBILI_CSS : ''); let path = []; let player; let fullscreenButton; let scheduled = 0; const events = new AbortController(); const listen = (target, name, handler, options) => target.addEventListener(name, handler, { ...options, signal: events.signal }); function syncFullscreenButton() { if (!player || player.matches('video')) return; const native = player.querySelector(bili ? '.bpx-player-ctrl-full,.bilibili-player-video-btn-fullscreen' : '.xgplayer-fullscreen, xg-fullscreen, [data-e2e="video-player-fullscreen"], button[aria-label="全屏"]:not([data-dw-inline-fullscreen-button])'); const area = player.getBoundingClientRect(); const bounds = native?.getBoundingClientRect(); const x = bounds && bounds.left + bounds.width / 2; const y = bounds && bounds.top + bounds.height / 2; const nativeVisible = bounds && bounds.width > 0 && bounds.height > 0 && x > area.left && x < area.right && y > area.top && y < area.bottom && !native.matches('[disabled], [aria-disabled="true"]') && doc.defaultView.getComputedStyle(native).visibility === 'visible'; if (!fullscreenButton && nativeVisible) return; if (!fullscreenButton) { fullscreenButton = doc.createElement('button'); fullscreenButton.type = 'button'; fullscreenButton.setAttribute('data-dw-inline-fullscreen-button', ''); listen(fullscreenButton, 'click', (event) => { event.stopPropagation(); const transition = doc.fullscreenElement ? doc.exitFullscreen() : player.requestFullscreen(); transition.catch(() => { fullscreenButton.setAttribute('aria-label', '浏览器未允许全屏'); }); }); } if (fullscreenButton.parentElement !== player) player.append(fullscreenButton); if (fullscreenButton.hidden !== Boolean(nativeVisible)) fullscreenButton.hidden = Boolean(nativeVisible); const full = Boolean(doc.fullscreenElement); const label = full ? '退出全屏' : '全屏'; if (fullscreenButton.getAttribute('aria-label') !== label) { fullscreenButton.setAttribute('aria-label', label); const icon = full ? 'M4 9h5V4m6 0v5h5m0 6h-5v5m-6 0v-5H4' : 'M9 4H4v5m16 0V4h-5m5 11v5h-5m-6 0H4v-5'; fullscreenButton.innerHTML = ``; } } function readPlayer() { scheduled = 0; if (player && !player.isConnected) { doc.documentElement.removeAttribute('data-dw-inline-page'); for (const node of path) node.removeAttribute('data-dw-inline-path'); path = []; player = undefined; entry.video = undefined; } const item = /^\d+$/.test(entry.id) ? doc.querySelector( `.sliderVideo.video_${entry.id}, [data-e2e="video-detail"][data-aweme-id="${entry.id}"]`, ) : null; const active = item || doc.querySelector('[data-e2e="feed-active-video"], .swiper-slide-active'); const scope = (bili && doc.querySelector(nativePlayerSelector)) || active || doc; const candidates = [...scope.querySelectorAll(active || bili ? 'video' : '.basePlayerContainer video, .xgplayer video, .douyin-player video, [data-e2e="player-container"] video, video[controls]')].filter((video) => { const owner = video.closest('[data-aweme-id], [data-video-id], .sliderVideo'); const ownerId = owner?.dataset.awemeId || owner?.dataset.videoId || owner?.getAttribute('class')?.match(/\bvideo_(\d+)\b/)?.[1]; return !/^\d+$/.test(ownerId) || ownerId === entry.id; }); const video = candidates.find((node) => !node.error && node.readyState >= 2) || candidates.find((node) => !node.error && (node.currentSrc || node.getAttribute('src'))) || (candidates.length === 1 && !candidates[0].error ? candidates[0] : null); if (!video && (!candidates.length || candidates.some((node) => !node.error))) return; if (!video) { fail(entry); return; } const current = (bili && doc.querySelector('#bilibili-player,#bofqi')) || video.closest(nativePlayerSelector) || video; if (current !== player) { for (const node of path) node.removeAttribute('data-dw-inline-path'); player?.removeAttribute('data-dw-inline-player'); if (!style.isConnected) doc.head.append(style); player = current; path = []; doc.body.setAttribute('data-dw-inline-path', ''); for (let node = player.parentElement; node && node !== doc.body; node = node.parentElement) { node.setAttribute('data-dw-inline-path', ''); path.push(node); } player.setAttribute('data-dw-inline-player', ''); // The outer loading panel already covers the iframe. Keep Douyin visible to its own startup code. doc.documentElement.setAttribute('data-dw-inline-page', ''); } entry.video = video; syncFullscreenButton(); if (video.readyState >= 2) { entry.unavailable = false; clearTimeout(entry.loadingTimer); } if (!entry.unavailable) entry.status.style.display = 'none'; if (entry.restore && video.readyState >= 1) { restore(video, entry.restore); entry.restore = undefined; } if (entry.autoplay && video.readyState >= 1) { entry.autoplay = false; video.play().catch(() => {}); } } function schedule() { if (!scheduled) scheduled = requestAnimationFrame(readPlayer); } const observer = new MutationObserver(schedule); const layoutAttributes = bili ? ['data-e2e', 'src', 'class', 'hidden', 'data-screen'] : ['data-e2e', 'src', 'class', 'hidden']; observer.observe(doc, { childList: true, subtree: true, attributes: true, attributeFilter: layoutAttributes }); listen(doc.defaultView, 'resize', schedule); listen(doc, 'fullscreenchange', schedule); listen(doc, 'loadeddata', schedule, { capture: true }); listen(doc, 'loadedmetadata', schedule, { capture: true }); listen(doc, 'canplay', schedule, { capture: true }); listen(doc, 'DOMContentLoaded', schedule); listen(doc, 'error', schedule, { capture: true }); listen(doc, 'wheel', (event) => { if (doc.fullscreenElement || !event.cancelable || event.ctrlKey || event.metaKey || event.shiftKey || Math.abs(event.deltaY) <= Math.abs(event.deltaX) || event.target.closest?.('.xgplayer-volume, [role="slider"]')) return; const scroll = entry.slot.closest('.wecom-chat-body'); if (!scroll) return; const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? scroll.clientHeight : 1; scroll.scrollTop += event.deltaY * unit; event.preventDefault(); event.stopPropagation(); }, { capture: true, passive: false }); entry.stopDocument = () => { observer.disconnect(); if (scheduled) cancelAnimationFrame(scheduled); events.abort(); }; readPlayer(); } function mount(slot, item, background) { if (!slot || !item?.url) { unmount(); return true; } if (mounted?.slot === slot && mounted.id === item.id && mounted.frame.isConnected) { watchBackground(mounted, background); return true; } unmount(); const url = new URL(item.url, location.origin); const site = workspaceSite(url); if (!site || url.origin !== location.origin || workspaceContent(url.href)?.id !== item.id) return true; const doc = slot.ownerDocument; const frame = doc.createElement('iframe'); frame.dataset.dwInlineDouyin = item.id; frame.title = `${site.label}原生播放器`; frame.allow = 'autoplay; fullscreen'; frame.allowFullscreen = true; frame.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;border:0'; const status = doc.createElement('div'); status.className = 'wecom-inline-player-status'; const message = doc.createElement('span'); message.setAttribute('role', 'status'); const retry = doc.createElement('button'); retry.type = 'button'; retry.textContent = '重试播放'; status.append(message, retry); let original; if (site.id === 'bilibili') { original = doc.createElement('a'); original.href = url.href; original.target = '_top'; original.textContent = '打开 B 站原页'; status.append(original); } const playback = saved?.id === item.id ? (saved.source === background && background ? snapshot(background) : saved.playback) : undefined; const entry = { id: item.id, site, url: url.href, slot, frame, status, message, retry, original, abort: new AbortController(), restore: playback }; entry.pauseBackground = (event) => { entry.backgroundWasPlaying = true; event.currentTarget.pause(); }; mounted = entry; watchBackground(entry, background); retry.addEventListener('click', () => load(entry), { signal: entry.abort.signal }); frame.addEventListener('load', () => connectDocument(entry, frame.contentDocument), { signal: entry.abort.signal }); load(entry); slot.append(frame, status); return true; } function play() { if (!mounted) return; if (mounted.video?.readyState >= 1) mounted.video.play().catch(() => {}); else mounted.autoplay = true; } function commentAdapter(id) { if (!mounted) return null; if (mounted.id !== id) { mounted.comments?.destroy(); mounted.comments = undefined; return null; } if (!mounted.document?.defaultView) return null; if (!mounted.comments) { mounted.comments = createWorkspaceAdapter(mounted.site, onChange, mounted.document.defaultView); mounted.comments.start(); } return mounted.comments; } return { mount, unmount, play, commentAdapter }; } function createPristineWorkspaceView(actions) { const host = document.createElement('div'); host.id = 'douyin-workspace'; host.setAttribute('data-dw-workspace', ''); host.style.cssText = 'position:fixed;inset:0;z-index:2147483000;pointer-events:none'; let surface; let model; let mediaFrame = 0; let observedMedia; const observer = new ResizeObserver(schedulePosition); const inlineMedia = createInlineWorkspaceMedia(actions.mediaChanged); function schedulePosition() { if (mediaFrame) return; mediaFrame = requestAnimationFrame(() => { mediaFrame = 0; if (!host.hidden) actions.mediaRect(); }); } function clearOpening() { surface?.frame.style.removeProperty('clip-path'); } function openSurface() { const frame = document.createElement('iframe'); frame.allow = 'autoplay; fullscreen'; frame.allowFullscreen = true; frame.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;border:0;pointer-events:auto'; host.append(frame); const doc = frame.contentDocument; let view; try { doc.open(); doc.write(''); doc.close(); view = createPristineChat(doc, actions); } catch (error) { frame.remove(); throw error; } observer.observe(frame); doc.addEventListener('scroll', schedulePosition, { passive: true, capture: true }); doc.addEventListener('click', schedulePosition, { passive: true }); doc.addEventListener('transitionend', schedulePosition); doc.addEventListener('keydown', (event) => { if (model?.theme === 'feishu' && (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && !event.repeat && !event.isComposing && event.key.toLowerCase() === 'k') { event.preventDefault(); view.focusSearch(); return; } if (!event.altKey || !event.shiftKey || event.repeat || event.isComposing) return; const target = event.target; if (target?.closest?.('input,textarea,[contenteditable]')) return; const mode = { KeyW: 'native', Digit1: 'wecom', Digit2: 'feishu' }[event.code]; if (!mode) return; event.preventDefault(); actions.theme(mode); }); return { frame, doc, view }; } function setVisible(visible) { if (!visible) { inlineMedia.unmount(true); clearOpening(); } host.hidden = !visible; } function update(nextModel) { model = nextModel; setVisible(true); if (host.dataset.theme !== model.theme) host.dataset.theme = model.theme; surface ||= openSurface(); if (surface.frame.dataset.dwSourceView !== model.theme) { surface.frame.dataset.dwSourceView = model.theme; surface.frame.title = `${WORKSPACE_THEME_LABELS[model.theme]}会话视图`; } surface.view.update(model); const media = surface.view.getMediaElement(); if (media !== observedMedia) { if (observedMedia) observer.unobserve(observedMedia); observedMedia = media; if (media) observer.observe(media); } } function getMediaRect() { if (!surface || model?.mediaKind !== 'image') return null; const { frame, doc, view } = surface; const media = view.getMediaElement(); if (!model?.previewReady || host.hidden || !media?.isConnected) { clearOpening(); return null; } const bounds = media.getBoundingClientRect(); const outer = frame.getBoundingClientRect(); let visible = { left: Math.max(bounds.left, 0), top: Math.max(bounds.top, 0), right: Math.min(bounds.right, outer.width), bottom: Math.min(bounds.bottom, outer.height), }; const getStyle = (element) => doc.defaultView.getComputedStyle(element); for (let node = media; node && node !== doc.body; node = node.parentElement) { const style = getStyle(node); if (style.visibility === 'hidden' || style.display === 'none' || Number(style.opacity) === 0) { clearOpening(); return null; } if (node === media) continue; const box = node.getBoundingClientRect(); if (/^(auto|scroll|hidden|clip)$/.test(style.overflowX)) { visible.left = Math.max(visible.left, box.left); visible.right = Math.min(visible.right, box.right); } if (/^(auto|scroll|hidden|clip)$/.test(style.overflowY)) { visible.top = Math.max(visible.top, box.top); visible.bottom = Math.min(visible.bottom, box.bottom); } } if (visible.right <= visible.left || visible.bottom <= visible.top || bounds.width < 32 || bounds.height < 32) { clearOpening(); return null; } // Native photo albums remain in the parent document. const { left, top, right, bottom } = visible; const hole = `${left}px ${top}px, ${right}px ${top}px, ${right}px ${bottom}px, ${left}px ${bottom}px, ${left}px ${top}px`; frame.style.clipPath = `polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ${hole})`; return { left: outer.left + bounds.left, top: outer.top + bounds.top, right: outer.left + bounds.right, bottom: outer.top + bounds.bottom, width: bounds.width, height: bounds.height, radius: getStyle(media).borderRadius, clip: { left: left - bounds.left, top: top - bounds.top, right: bounds.right - right, bottom: bounds.bottom - bottom, }, }; } function updateInlineMedia(background) { const item = surface?.view.getVideoItem(); if (!item) { inlineMedia.unmount(); return false; } clearOpening(); return inlineMedia.mount(surface.view.getMediaElement(), item, model.nativePlayerId === item.id ? background : undefined); } function playInlineMedia() { inlineMedia.play(); } function isInlineFullscreen(element) { if (!surface || element !== surface.frame) return false; return Boolean(surface.doc.fullscreenElement?.hasAttribute('data-dw-inline-douyin')); } function scrollMedia(delta, mode) { const scroller = surface?.view.getMediaElement()?.closest('.wecom-chat-body'); if (!scroller) return false; const unit = mode === 1 ? 16 : mode === 2 ? scroller.clientHeight : 1; scroller.scrollTop += delta * unit; return true; } return { host, update, setVisible, getMediaRect, updateInlineMedia, inlineCommentAdapter: inlineMedia.commentAdapter, playInlineMedia, isInlineFullscreen, scrollMedia, clearOpening, focusSearch: () => surface?.view.focusSearch?.(), destroy() { inlineMedia.unmount(); if (mediaFrame) cancelAnimationFrame(mediaFrame); observer.disconnect(); surface?.view.destroy?.(); host.remove(); }, }; } const WORKSPACE_SETTING_PREFIX = 'douyin-content-workspace.v1.'; function readWorkspaceSetting(key, fallback) { try { if (typeof GM_getValue === 'function') return GM_getValue(WORKSPACE_SETTING_PREFIX + key, fallback); const value = localStorage.getItem(WORKSPACE_SETTING_PREFIX + key); return value === null ? fallback : JSON.parse(value); } catch { return fallback; } } function holdWorkspaceStartup() { if (!USE_PRISTINE_VIEWS || window.top !== window.self) return; const site = workspaceSite()?.id; const supported = site === 'douyin' ? douyinRoute(new URL(location.href)).kind !== 'other' : site === 'bilibili' ? bilibiliRoute(location).kind !== 'other' : site === 'zhihu' && (workspaceContent(location.href) || (location.hostname === 'www.zhihu.com' && /^\/(?:hot\/?|search\/?)?$/.test(location.pathname))); if (!supported || readWorkspaceSetting('theme', 'wecom') === 'native') return; let root; let opacity; let priority; const observer = new MutationObserver(attach); const timeout = setTimeout(reveal, 12000); function attach() { root = document.documentElement; if (!root) return; opacity = root.style.getPropertyValue('opacity'); priority = root.style.getPropertyPriority('opacity'); root.style.setProperty('opacity', '0', 'important'); observer.disconnect(); } function reveal() { clearTimeout(timeout); observer.disconnect(); if (root?.style.getPropertyValue('opacity') === '0' && root.style.getPropertyPriority('opacity') === 'important') { root.style.setProperty('opacity', opacity, priority); } } if (document.documentElement) attach(); else observer.observe(document, { childList: true }); return reveal; } function startDouyinWorkspace() { const site = workspaceSite(); if (!site || window.top !== window.self || (!USE_PRISTINE_VIEWS && site.id !== 'douyin')) return; const siteChannels = USE_PRISTINE_VIEWS ? WORKSPACE_SITES.filter(({ id }) => id !== site.id) .map(({ id, label, home }) => ({ id: `site:${id}`, kind: 'site', label, href: home })) : []; const themeLabels = site.id === 'douyin' ? WORKSPACE_THEME_LABELS : { ...WORKSPACE_THEME_LABELS, native: `${site.label}原版` }; const themes = new Set(Object.keys(themeLabels)); const colorModes = new Set(['system', 'light', 'dark']); const root = document.documentElement; const recentChannel = { id: 'local:recent', kind: 'history', label: '浏览记录', preview: '回看最近打开的内容' }; const demos = [ { id: 'local:review', kind: 'demo', label: '内容评审群', avatarText: '评', unread: 2, messages: [ { id: 'review-1', author: '许宁', text: '我把这周的候选素材过了一遍,留了三条。', time: '10:08' }, { id: 'review-2', author: '林舟', text: '先过第一条吧,看一下前五秒的节奏。', time: '10:12' }, ], }, { id: 'local:lin', kind: 'demo', label: '林舟', avatarText: '林', unread: 1, messages: [ { id: 'lin-1', author: '林舟', text: '下午开会之前,方便把你挑出来的参考发一下吗?', time: '11:26' }, { id: 'lin-2', author: '我', mine: true, text: '好,我看完两条就整理。', time: '11:28' }, { id: 'lin-3', author: '林舟', text: '收到,先发链接就行。', time: '11:29' }, ], }, ]; function writeSetting(key, value) { try { if (typeof GM_setValue === 'function') GM_setValue(WORKSPACE_SETTING_PREFIX + key, value); else localStorage.setItem(WORKSPACE_SETTING_PREFIX + key, JSON.stringify(value)); } catch { // The current tab can still use preferences when persistent storage is unavailable. } } function readArray(key) { const value = readWorkspaceSetting(key, []); return Array.isArray(value) ? value : []; } const savedTheme = readWorkspaceSetting('theme', 'wecom'); const savedColorMode = readWorkspaceSetting('color', 'system'); let theme = themes.has(savedTheme) ? savedTheme : 'wecom'; let colorMode = colorModes.has(savedColorMode) ? savedColorMode : 'system'; const savedOfficeTheme = readWorkspaceSetting('officeTheme', 'wecom'); let lastOfficeTheme = theme !== 'native' ? theme : savedOfficeTheme; if (!themes.has(lastOfficeTheme) || lastOfficeTheme === 'native') lastOfficeTheme = 'wecom'; if (theme !== savedTheme) writeSetting('theme', theme); if (lastOfficeTheme !== savedOfficeTheme) writeSetting('officeTheme', lastOfficeTheme); let view; let resumeButton; let localChannel; let localOriginRoute; let dismissedRecommendation; let recommendationOpen = false; let quietVideo; let temporaryNative = false; let scheduledFrame = 0; let openFrame = 0; let openTimer = 0; let placementFrame = 0; let placedPlayer; let layoutPath = []; let compactPath = []; let placementTarget; let status; let statusTimer; let lastModel; let pendingVideo; let commentSource; let replySource; let waitForNativeCommentsUntil = 0; let commentFallbackTimer; let adapterRunning = false; let failed = false; const recentKey = site.id === 'douyin' ? 'recent' : `recent:${site.id}`; let recent = readArray(recentKey).filter((item) => item && item.id && workUrl(item.url)); const readDemos = new Set(readArray('readDemos')); const storedDemoReplies = readWorkspaceSetting('demoReplies', {}); const demoReplies = storedDemoReplies && typeof storedDemoReplies === 'object' ? storedDemoReplies : {}; const adapter = createWorkspaceAdapter(site, scheduleRender); const readAdapter = USE_PRISTINE_VIEWS ? adapter.getSnapshot : adapter.read; function workUrl(candidate) { if (!candidate || typeof candidate !== 'string') return ''; const url = workspaceSiteURL(candidate, location.origin); return url && site.hosts.includes(url.hostname) ? url.href : ''; } function remember(item) { const url = workUrl(item?.url); if (!item?.id || !url || !item.title) return; const previous = recent.find((entry) => entry.id === item.id); const time = item.time || previous?.time || ''; const avatar = item.avatar || previous?.avatar || ''; const author = item.author || previous?.author || ''; if (recent[0] === previous && previous?.title === item.title && (previous.time || '') === time && (previous.avatar || '') === avatar && (previous.author || '') === author) return; const { id, title, cover, duration, kind } = item; recent = [{ id, title, author, avatar, cover, duration, kind, time, url }, ...recent.filter((entry) => entry.id !== id)].slice(0, 80); writeSetting(recentKey, recent); } function notify(message) { if (!message) return; status = message; clearTimeout(statusTimer); statusTimer = setTimeout(() => { status = undefined; scheduleRender(); }, 4400); scheduleRender(); } function stopTrackingPlayer() { if (placementFrame) cancelAnimationFrame(placementFrame); placementFrame = 0; placementTarget = undefined; } function clearCompactPlayer() { placedPlayer?.removeAttribute('data-dw-player-compact'); for (const element of compactPath) element.removeAttribute('data-dw-player-track'); compactPath = []; } function clearPlacement() { stopTrackingPlayer(); clearCompactPlayer(); if (placedPlayer) { placedPlayer.removeAttribute('data-dw-player-placed'); placedPlayer.removeAttribute('data-dw-player-suppressed'); for (const name of ['left', 'top', 'width', 'height', 'radius', 'clip']) { placedPlayer.style.removeProperty(`--dw-player-${name}`); } placedPlayer = undefined; } for (const element of layoutPath) element.removeAttribute('data-dw-layout-path'); layoutPath = []; } function isolatedPath(player) { const path = []; let parent = player.parentElement; while (parent && parent !== document.body) { path.push(parent); parent = parent.parentElement; } return path; } function setCompactPlayer(player) { const compact = usesMessageCards() && lastModel.mediaKind !== 'image' && (player.matches('video') || Boolean(player.querySelector('video'))); if (!compact) { clearCompactPlayer(); return; } if (player.hasAttribute('data-dw-player-compact')) return; player.setAttribute('data-dw-player-compact', ''); const boundary = layoutPath.findIndex((element) => element.matches('[data-dw-native-active], [data-dw-native-detail]')); compactPath = layoutPath.slice(0, boundary >= 0 ? boundary + 1 : 1); for (const element of compactPath) element.setAttribute('data-dw-player-track', ''); } function alignPlayer() { if (!placedPlayer?.isConnected || !placementTarget) return; const box = placedPlayer.getBoundingClientRect(); const style = placedPlayer.style; const dx = placementTarget.left - box.left; const dy = placementTarget.top - box.top; if (Math.abs(dx) >= 0.5) style.setProperty('--dw-player-left', `${(parseFloat(style.getPropertyValue('--dw-player-left')) || 0) + dx}px`); if (Math.abs(dy) >= 0.5) style.setProperty('--dw-player-top', `${(parseFloat(style.getPropertyValue('--dw-player-top')) || 0) + dy}px`); } function trackPlayer() { placementFrame = 0; if (!placementTarget || !placedPlayer?.isConnected) return; // Douyin can move a containing block of its native player without a resize // event. Keep its viewport coordinates tied to the workbench's media slot. alignPlayer(); placementFrame = requestAnimationFrame(trackPlayer); } function positionPlayer() { if (view?.host.isConnected && !view.host.hidden && view.updateInlineMedia?.(getMarkedVideo())) { clearPlacement(); return; } if (!view?.host.isConnected || view.host.hidden || !lastModel?.previewReady || root.hasAttribute('data-dw-fullscreen')) { view?.clearOpening?.(); clearPlacement(); return; } const player = document.querySelector('[data-dw-native-player]:not([data-dw-native-player="inactive"])'); if (!player) { view.clearOpening?.(); clearPlacement(); return; } if (player !== placedPlayer || (player.hasAttribute('data-dw-player-placed') && (layoutPath[0] ?? document.body) !== player.parentElement)) { clearPlacement(); placedPlayer = player; } const rect = view.getMediaRect(); const clip = rect && [ Math.max(0, rect.clip?.top || 0, -rect.top), Math.max(0, rect.clip?.right || 0, rect.right - innerWidth), Math.max(0, rect.clip?.bottom || 0, rect.bottom - innerHeight), Math.max(0, rect.clip?.left || 0, -rect.left), ]; if (!rect || rect.width < 32 || rect.height < 32 || clip[1] + clip[3] >= rect.width || clip[0] + clip[2] >= rect.height) { // The original element continues playback at its last geometry offscreen. stopTrackingPlayer(); clearCompactPlayer(); player.setAttribute('data-dw-player-suppressed', ''); return; } if (!player.hasAttribute('data-dw-player-placed')) { layoutPath = isolatedPath(player); for (const element of layoutPath) element.setAttribute('data-dw-layout-path', ''); player.setAttribute('data-dw-player-placed', ''); } player.removeAttribute('data-dw-player-suppressed'); setCompactPlayer(player); placementTarget = rect; const style = player.style; style.setProperty('--dw-player-width', `${rect.width}px`); style.setProperty('--dw-player-height', `${rect.height}px`); style.setProperty('--dw-player-radius', rect.radius || '12px'); style.setProperty('--dw-player-clip', clip.some(Boolean) ? `inset(${clip.map((inset) => `${inset}px`).join(' ')})` : 'none'); alignPlayer(); if (!placementFrame) placementFrame = requestAnimationFrame(trackPlayer); } function renderResumeButton(label) { if (!resumeButton) { resumeButton = document.createElement('button'); resumeButton.id = 'douyin-workspace-resume'; resumeButton.type = 'button'; resumeButton.addEventListener('click', () => setTheme(lastOfficeTheme)); } resumeButton.textContent = label; if (!resumeButton.isConnected) document.body.append(resumeButton); } function showNative(showResume, label = '开启内容工作台') { cancelScheduledOpen(); clearTimeout(commentFallbackTimer); waitForNativeCommentsUntil = 0; pendingVideo = undefined; commentSource = undefined; keepRecommendationQuiet(); root.removeAttribute('data-dw-mode'); clearPlacement(); if (view?.setVisible) view.setVisible(false); else view?.host.remove(); if (showResume) renderResumeButton(label); else resumeButton?.remove(); } function beginAdapter() { if (adapterRunning) return; adapterRunning = true; try { adapter.start(); } catch (error) { failed = true; stopAdapter(); console.error('[摸鱼伪装] 初始化失败', error); } } function stopAdapter() { if (!adapterRunning) return; adapterRunning = false; adapter.stop(); } function setTheme(value) { if (!themes.has(value)) return; failed = false; theme = value; temporaryNative = false; writeSetting('theme', value); if (value === 'native') stopAdapter(); else { lastOfficeTheme = value; writeSetting('officeTheme', value); beginAdapter(); } render(); } function setColorMode(value) { if (!colorModes.has(value)) return; colorMode = value; writeSetting('color', value); render(); } function routeKey(route) { return [route?.kind, route?.channel, route?.query].join('|'); } function isRecommendationFeed(route) { return route.kind === 'recommend' && !route.detailId; } function usesMessageCards() { return USE_PRISTINE_VIEWS && theme !== 'native'; } function getMarkedVideo() { const player = document.querySelector('[data-dw-native-player]:not([data-dw-native-player="inactive"])'); return player?.matches('video') ? player : player?.querySelector('video'); } function pauseRecommendation(event) { event.currentTarget.pause(); } function keepRecommendationQuiet(video) { if (quietVideo === video) return; quietVideo?.removeEventListener('play', pauseRecommendation); quietVideo = video; video?.addEventListener('play', pauseRecommendation); video?.pause(); } function addDemoReply(text) { const thread = demos.find(({ id }) => id === localChannel?.id); if (!thread || !text.trim()) return; const key = thread.id; const previous = Array.isArray(demoReplies[key]) ? demoReplies[key] : []; const time = new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit' }).format(new Date()); demoReplies[key] = [...previous, { id: `demo-${Date.now()}`, author: '我', mine: true, text, time }].slice(-100); writeSetting('demoReplies', demoReplies); render(); return { ok: true }; } function runAction(action, failure) { try { const result = action(); if (result === false && failure) notify(failure); else if (result?.then) result.catch(() => notify(failure || '抖音页面暂时没有响应。')); scheduleRender(); return result; } catch (error) { console.warn('[摸鱼伪装]', error); notify(failure || '抖音页面暂时没有响应。'); return false; } } function originalLogin() { const dialog = readAdapter().nativeLogin; temporaryNative = true; showNative(true, '返回内容工作台'); if (!dialog) adapter.login?.(); } function originalComments() { const target = workUrl(lastModel?.active?.url || adapter.commentPage?.()); if (!target) return notify('暂时找不到这条内容的原站详情。'); if (new URL(target).origin === location.origin && new URL(target).pathname === location.pathname && (site.id !== 'douyin' || !location.search)) { temporaryNative = true; showNative(true, '返回内容工作台'); if (site.id === 'douyin') { document.querySelector('[data-e2e="comment-list"], #comment-input-container')?.scrollIntoView({ block: 'start' }); } else adapter.revealComments?.(); return; } location.assign(target); } function cancelScheduledOpen() { if (openFrame) cancelAnimationFrame(openFrame); clearTimeout(openTimer); openFrame = 0; openTimer = 0; } function openItem(item) { localChannel = undefined; const snapshot = readAdapter(); const inRecommendation = isRecommendationFeed(snapshot.route); const fromCard = usesMessageCards() && inRecommendation; const resume = inRecommendation && (dismissedRecommendation === item.id || (fromCard && snapshot.active?.id === item.id)); dismissedRecommendation = undefined; if (resume) { pendingVideo = undefined; if (fromCard) recommendationOpen = true; keepRecommendationQuiet(); render(); if (fromCard && view?.playInlineMedia) view.playInlineMedia(); else getMarkedVideo()?.play().catch(() => notify('点击原生播放按钮继续观看。')); return; } const url = workUrl(item.url); const inPlace = USE_PRISTINE_VIEWS && item.kind === 'video' && url && new URL(url).origin === location.origin && workspaceContent(url)?.id === item.id; pendingVideo = inPlace ? item : undefined; clearTimeout(commentFallbackTimer); waitForNativeCommentsUntil = inPlace ? Date.now() + 900 : 0; if (inPlace) commentFallbackTimer = setTimeout(scheduleRender, 900); if (USE_PRISTINE_VIEWS && snapshot.active?.id === item.id) return scheduleRender(); runAction(() => adapter.open(item, Boolean(inPlace)), '暂时无法打开这条内容。'); } const actions = { theme: setTheme, colorMode: setColorMode, mediaRect: positionPlayer, mediaChanged: scheduleRender, channel(channel) { if (!channel) return; cancelScheduledOpen(); pendingVideo = undefined; recommendationOpen = false; if (channel.kind === 'site') { const target = WORKSPACE_SITES.find(({ id }) => `site:${id}` === channel.id); if (target) location.assign(target.home); return; } if (channel.kind === 'demo' || channel.kind === 'history') { adapter.pause(); localChannel = channel; localOriginRoute = routeKey(readAdapter().route); if (channel.kind === 'demo') { readDemos.add(channel.id); writeSetting('readDemos', [...readDemos]); } render(); return; } localChannel = undefined; runAction(() => adapter.navigate(channel), '暂时无法打开这个分区。'); }, open(item) { if (!item) return; if (!USE_PRISTINE_VIEWS) return openItem(item); cancelScheduledOpen(); // Paint the new conversation before activating the background Douyin detail for comments. openFrame = requestAnimationFrame(() => { openFrame = 0; openTimer = setTimeout(() => { openTimer = 0; openItem(item); }, 0); }); }, close() { cancelScheduledOpen(); pendingVideo = undefined; runAction(() => { const snapshot = readAdapter(); adapter.pause(); if (isRecommendationFeed(snapshot.route)) { recommendationOpen = false; dismissedRecommendation = snapshot.active?.id; return true; } return adapter.close(); }); }, search(value) { const query = typeof value === 'string' ? value.trim().slice(0, 100) : ''; if (!query) return; cancelScheduledOpen(); pendingVideo = undefined; localChannel = undefined; runAction(() => adapter.search(query), '暂时无法打开站内搜索。'); }, more() { if (!localChannel) runAction(() => adapter.more()); }, refreshFeed() { if (!localChannel) runAction(() => adapter.refreshFeed?.(), 'B 站推荐暂时无法刷新。'); }, step(direction) { cancelScheduledOpen(); pendingVideo = undefined; dismissedRecommendation = undefined; runAction(() => adapter.step(direction < 0 ? -1 : 1), '这一页暂时没有更多可以切换的内容。'); }, openComments(retry = false) { runAction(() => (commentSource || adapter).openComments(retry), '暂时无法打开评论,可以查看原视频页。'); }, expandContent() { runAction(() => adapter.expandContent?.(), '请打开原网页查看完整内容。'); }, expandReplies(comment) { runAction(() => (commentSource || adapter).expandComment(comment?.id ?? comment), '暂时无法展开这条回复。'); }, moreComments() { runAction(() => (commentSource || adapter).moreComments(), '评论暂时没有更多内容。'); }, async send(text, replyTo) { if (localChannel?.kind === 'demo') return addDemoReply(text); const source = commentSource || adapter; replySource = source; try { const result = await source.reply(text, replyTo?.id ?? replyTo); if (result === true || result?.ok) return { ok: true, posted: result?.posted }; return { ok: false, pending: result?.pending, message: result?.message || result?.reason || '原站暂未确认发送,草稿已保留。', }; } catch { return { ok: false, message: '暂时无法发送,草稿已保留。' }; } finally { if (replySource === source) replySource = undefined; scheduleRender(); } }, originalComments, revealComments() { runAction(() => adapter.revealComments?.()); temporaryNative = true; showNative(true, '返回内容工作台'); document.querySelector('#comment-input-container, [data-e2e="comment-list"]')?.scrollIntoView({ block: 'center' }); }, login: originalLogin, }; function scheduleRender() { if (!scheduledFrame) scheduledFrame = requestAnimationFrame(render); } function render() { if (scheduledFrame) cancelAnimationFrame(scheduledFrame); scheduledFrame = 0; if (!document.body) return; if (theme === 'native' || temporaryNative || failed) { showNative(true, temporaryNative || failed ? '返回内容工作台' : '开启内容工作台'); return; } try { const snapshot = readAdapter(); if (snapshot.compatible === false) { showNative(false); return; } if (localChannel && routeKey(snapshot.route) !== localOriginRoute) localChannel = undefined; const inRecommendation = isRecommendationFeed(snapshot.route); if (!inRecommendation) recommendationOpen = false; const recommendationList = usesMessageCards() && inRecommendation && !recommendationOpen; keepRecommendationQuiet(recommendationList ? getMarkedVideo() : undefined); const visibleDemos = demos.map((thread) => ({ ...thread, unread: readDemos.has(thread.id) ? 0 : thread.unread, preview: (demoReplies[thread.id]?.at?.(-1) || thread.messages.at(-1)).text, })); const thread = visibleDemos.find(({ id }) => id === localChannel?.id); const isLocal = Boolean(localChannel); const items = localChannel?.kind === 'history' ? recent : thread ? [] : (snapshot.items || []); if (snapshot.route.kind !== 'recommend' || snapshot.active?.id !== dismissedRecommendation) { dismissedRecommendation = undefined; } if (pendingVideo?.id === snapshot.active?.id && snapshot.nativeDetail) pendingVideo = undefined; const active = isLocal || dismissedRecommendation || (recommendationList && !pendingVideo) ? null : pendingVideo || snapshot.active; const matchedOuter = active && snapshot.active?.id === active.id; const sendingInline = active && replySource && replySource !== adapter && replySource.getSnapshot().active?.id === active.id; const currentInline = active && commentSource !== adapter ? commentSource?.getSnapshot() : null; const trackingInline = currentInline?.active?.id === active?.id && active && (commentSource.hasPendingReply(active.id) || currentInline.confirmedReplies.length); const allowInline = sendingInline || trackingInline || (Date.now() >= waitForNativeCommentsUntil && (!matchedOuter || !snapshot.commentsOpen || snapshot.commentsState === 'unavailable')); const inlineAdapter = view?.inlineCommentAdapter?.( active?.kind === 'video' && allowInline ? active.id : null, ); const embedded = inlineAdapter?.getSnapshot(); const matchedInline = active && embedded?.active?.id === active.id; const useInline = matchedInline && (sendingInline || trackingInline || embedded.commentsOpen || !matchedOuter || !snapshot.canOpenComments); commentSource = useInline ? inlineAdapter : matchedOuter ? adapter : undefined; const discussion = useInline ? embedded : matchedOuter ? snapshot : {}; remember(active); const savedProfiles = USE_PRISTINE_VIEWS || theme === 'wecom' ? new Map(recent.map((item) => [item.id, item])) : null; const selectedChannel = localChannel?.id || snapshot.selectedChannel || snapshot.route?.channel; const model = { ...snapshot, theme, colorMode, channels: [...(snapshot.channels || []), ...siteChannels, recentChannel, ...visibleDemos], selectedChannel, route: isLocal ? { ...snapshot.route, kind: localChannel.kind, channel: selectedChannel } : snapshot.route, items: savedProfiles ? items.map((item) => { const saved = savedProfiles.get(item.id); if (!saved) return item; return { ...item, avatar: item.avatar || saved.avatar, author: item.author || (site.id === 'zhihu' && saved.author) || '' }; }) : items, active, nativePlayerId: snapshot.active?.id, comments: discussion.comments || [], confirmedReplies: discussion.confirmedReplies || [], canLoadMore: !isLocal && snapshot.canLoadMore, canRefreshFeed: !isLocal && snapshot.canRefreshFeed, canCompose: Boolean(discussion.canCompose), canOpenComments: Boolean(discussion.canOpenComments), canRetryComments: Boolean(discussion.canRetryComments), canLoadMoreComments: Boolean(discussion.canLoadMoreComments), commentsOpen: Boolean(discussion.commentsOpen), commentsState: discussion.commentsState || 'loading', canStep: !isLocal && snapshot.canStep, canOpenOriginalComments: Boolean(active && workUrl(active.url || adapter.commentPage?.())), canRevealComments: Boolean(matchedOuter && (snapshot.commentsOpen || snapshot.commentsState === 'closed')), canLogin: !isLocal && (snapshot.nativeLogin || discussion.commentsState === 'login'), nativeGate: !isLocal && snapshot.nativeGate ? { message: site.id === 'douyin' ? snapshot.route.kind === 'search' ? '登录抖音后可查看搜索结果。' : '当前内容需要登录抖音。' : `登录${site.label}后可查看当前内容。`, } : undefined, demoMessages: thread && [...thread.messages, ...(Array.isArray(demoReplies[thread.id]) ? demoReplies[thread.id] : [])], previewReady: Boolean(matchedOuter && snapshot.nativeDetail && !snapshot.nativeLogin), previewError: matchedOuter && snapshot.nativeLogin ? site.id === 'douyin' ? '抖音打开了登录窗口,可从下方跳回原站登录。' : `请在${site.label}登录后继续。` : undefined, loading: !isLocal && snapshot.loading, status, }; if (!view) view = USE_PRISTINE_VIEWS ? createPristineWorkspaceView(actions) : createWorkspaceView(actions); resumeButton?.remove(); if (!view.host.isConnected) document.body.append(view.host); root.setAttribute('data-dw-mode', theme); lastModel = model; view.update(model); positionPlayer(); } catch (error) { failed = true; stopAdapter(); showNative(true, '返回内容工作台'); console.error('[摸鱼伪装] 页面适配失败', error); } } function onFullscreen() { root.toggleAttribute('data-dw-fullscreen', Boolean(document.fullscreenElement)); root.toggleAttribute('data-dw-inline-fullscreen', Boolean(view?.isInlineFullscreen?.(document.fullscreenElement))); positionPlayer(); } function onPlayerWheel(event) { if (!event.cancelable || !placementTarget || !placedPlayer?.contains(event.target) || root.hasAttribute('data-dw-fullscreen') || event.ctrlKey || event.metaKey || event.shiftKey || Math.abs(event.deltaY) <= Math.abs(event.deltaX) || event.target.closest?.('.xgplayer-volume, [role="slider"]')) return; const deltaMode = event.deltaMode; if (!view?.scrollMedia?.(event.deltaY, deltaMode)) return; event.preventDefault(); event.stopPropagation(); positionPlayer(); } if (typeof GM_addStyle === 'function') GM_addStyle(NATIVE_CSS); else { const sheet = document.createElement('style'); sheet.textContent = NATIVE_CSS; (document.head || root).append(sheet); } if (typeof GM_registerMenuCommand === 'function') { for (const mode of themes) GM_registerMenuCommand(`切换到${themeLabels[mode]}`, () => setTheme(mode)); for (const [mode, label] of [['system', '跟随系统'], ['light', '浅色'], ['dark', '深色']]) { GM_registerMenuCommand(`外观 · ${label}`, () => setColorMode(mode)); } } window.addEventListener('resize', positionPlayer, { passive: true }); document.addEventListener('fullscreenchange', onFullscreen); document.addEventListener('wheel', onPlayerWheel, { capture: true, passive: false }); document.addEventListener('keydown', (event) => { if (!event.altKey || !event.shiftKey || event.repeat || event.isComposing) return; const target = event.composedPath()[0]; if (target instanceof Element && target.closest('input, textarea, [contenteditable]')) return; const mode = event.code === 'KeyW' ? (theme === 'native' || temporaryNative ? lastOfficeTheme : 'native') : USE_PRISTINE_VIEWS ? { Digit1: 'wecom', Digit2: 'feishu' }[event.code] : undefined; if (!mode) return; event.preventDefault(); setTheme(mode); }); window.addEventListener('pageshow', scheduleRender); if (theme !== 'native') beginAdapter(); render(); } const revealWorkspace = holdWorkspaceStartup(); function startWorkspace() { // Startup mounts the workspace in this task. Restore visibility before the // adapters measure native controls so login dialogs remain detectable. revealWorkspace?.(); startDouyinWorkspace(); } if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', startWorkspace, { once: true }); else startWorkspace(); })();