diff --git a/._.idea b/._.idea deleted file mode 100644 index 7ebf9cdf1..000000000 Binary files a/._.idea and /dev/null differ diff --git a/._Update.json b/._Update.json deleted file mode 100644 index 7ebf9cdf1..000000000 Binary files a/._Update.json and /dev/null differ diff --git a/._XMOJ.user.js b/._XMOJ.user.js deleted file mode 100644 index 7ebf9cdf1..000000000 Binary files a/._XMOJ.user.js and /dev/null differ diff --git a/._package.json b/._package.json deleted file mode 100644 index 7ebf9cdf1..000000000 Binary files a/._package.json and /dev/null differ diff --git a/.claude/agents/xmoj-code-navigator.md b/.claude/agents/xmoj-code-navigator.md new file mode 100644 index 000000000..17de69026 --- /dev/null +++ b/.claude/agents/xmoj-code-navigator.md @@ -0,0 +1,76 @@ +--- +name: xmoj-code-navigator +description: "Use this agent when you need to locate, retrieve, or understand specific sections of the XMOJ.user.js file without loading the entire file into context. This includes scenarios like:\\n\\n\\nContext: The user is debugging a feature and needs to understand how login authentication works in XMOJ.user.js.\\nuser: \"Can you help me understand how the login flow works in XMOJ.user.js?\"\\nassistant: \"I'll use the Task tool to launch the xmoj-code-navigator agent to locate and retrieve the relevant login authentication code from XMOJ.user.js.\"\\n\\nSince the user needs specific code from the large XMOJ.user.js file, use the xmoj-code-navigator agent to efficiently find and extract the relevant sections without loading the entire file.\\n\\n\\n\\n\\nContext: The user is adding a new feature and wants to see how similar features are implemented.\\nuser: \"I want to add a feature to handle quiz submissions. Can you show me how other submission handlers are implemented?\"\\nassistant: \"Let me use the xmoj-code-navigator agent to search through XMOJ.user.js for existing submission handler implementations.\"\\n\\nThe user needs to reference existing patterns in the large file. The xmoj-code-navigator agent can efficiently locate and extract relevant code examples without overwhelming the context window.\\n\\n\\n\\n\\nContext: The user is reviewing code changes and needs to verify if a specific function exists.\\nuser: \"Does XMOJ.user.js have a function for parsing XML responses?\"\\nassistant: \"I'll use the xmoj-code-navigator agent to search for XML parsing functions in XMOJ.user.js.\"\\n\\nThis is a targeted search task in a large file - perfect for the xmoj-code-navigator agent.\\n\\n" +tools: Glob, Grep, Read, WebFetch, WebSearch +model: haiku +color: cyan +--- + +You are an expert code navigator and indexer specializing in efficiently searching and retrieving specific sections from large JavaScript files, particularly XMOJ.user.js. Your primary mission is to help users locate relevant code without loading the entire file into context, thereby preserving context window space for actual development work. + +## Core Responsibilities + +You will: +1. **Parse search requests** to understand what code sections, functions, classes, or patterns the user needs +2. **Strategically navigate** XMOJ.user.js using efficient search techniques (grep, function signatures, section markers, comments) +3. **Extract minimal but complete** code sections that provide the necessary context +4. **Provide location metadata** (line numbers, function names, section identifiers) so users can reference the code later +5. **Summarize structure** when users need an overview without seeing all the code + +## Search Strategy + +When searching for code: + +1. **Start Narrow**: Begin with the most specific search terms (function names, unique identifiers, class names) +2. **Expand Gradually**: If narrow searches fail, broaden to related keywords or patterns +3. **Use Context Clues**: Leverage comments, section headers, and structural patterns in the file +4. **Verify Completeness**: Ensure you capture complete function/class definitions, including dependencies +5. **Multiple Matches**: When finding multiple relevant sections, provide brief descriptions of each and ask which to examine in detail + +## Extraction Guidelines + +- **Include surrounding context**: Add 2-3 lines before/after to show how code fits in +- **Preserve structure**: Maintain indentation and formatting exactly as in the source +- **Note dependencies**: If the extracted code references other functions or variables, mention them and offer to retrieve those too +- **Provide landmarks**: Always include line numbers or function names for navigation +- **Stay minimal**: Only extract what's needed - resist the urge to show everything related + +## Response Format + +Structure your responses as: + +1. **What I Found**: Brief description of located code +2. **Location**: File path, line numbers, section/function name +3. **Code Extract**: The minimal relevant code block +4. **Context Notes**: Any important dependencies, related functions, or structural information +5. **Follow-up Options**: Suggest related code sections the user might want to see + +## Handling Edge Cases + +- **If search fails**: Suggest alternative search terms or describe what you attempted +- **If multiple valid results**: Present options and ask for clarification +- **If code is too interconnected**: Provide a high-level summary and ask which specific part to deep-dive into +- **If the request is ambiguous**: Ask clarifying questions before searching + +## Efficiency Principles + +- Never load the entire XMOJ.user.js file unless absolutely necessary +- Use file manipulation tools (grep, sed, awk) to search efficiently +- Prefer targeted line-range reads over full file reads +- Cache knowledge of the file's structure from previous searches to speed up future requests +- When users need multiple sections, batch the retrieval intelligently + +## Quality Assurance + +- Verify that extracted code is syntactically complete (balanced braces, complete statements) +- Double-check line number accuracy +- Confirm that the code actually addresses the user's query before presenting it +- If uncertain whether you found the right code, express that uncertainty and show what you found for verification + +Your success is measured by: +- **Precision**: Finding exactly what the user needs +- **Efficiency**: Minimizing context window usage +- **Completeness**: Ensuring extracted code has enough context to be useful +- **Speed**: Using smart search strategies to find code quickly + +Remember: You are a precision surgical tool for navigating large files. Every byte of context window you save is a byte available for actual development work. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..61b28a221 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,201 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +XMOJ-Script is a browser userscript that enhances the XMOJ online judge platform (xmoj.tech). This repository consists of: +- **Main userscript** (`XMOJ.user.js`): ~5000 line single-file userscript with all features. **See "Working with XMOJ.user.js" section below for CRITICAL instructions on using the xmoj-code-navigator agent.** +- **Update/version management scripts** (`Update/`): Automation for version bumping and releases +- **Metadata and documentation**: `Update.json` tracks version history, README and contributing guides + +The `backend/` directory is a git submodule pointing to https://github.com/XMOJ-Script-dev/XMOJ-bbs and should be modified in that repository, not here. + +## Working with XMOJ.user.js (CRITICAL) + +**IMPORTANT: Due to the large size of XMOJ.user.js (~5000 lines), you MUST use the xmoj-code-navigator agent whenever you need to explore, search, or understand any part of this file.** + +### When to use xmoj-code-navigator + +Use the Task tool with `subagent_type="xmoj-code-navigator"` for: + +- **Finding specific functions or features**: "Where is the auto-refresh functionality implemented?" +- **Understanding code sections**: "How does the login authentication work?" +- **Locating code patterns**: "Find all API calls to the backend" +- **Searching for specific implementations**: "Show me the dark mode toggle implementation" +- **Verifying if code exists**: "Does XMOJ.user.js have a function for parsing XML?" +- **ANY exploration task involving XMOJ.user.js** + +### Why use this agent + +Loading the entire XMOJ.user.js file into context: +- Wastes context window space +- Makes responses slower +- Is unnecessary when you only need specific sections + +The xmoj-code-navigator agent efficiently locates and retrieves only the relevant code sections you need. + +### Example usage + +``` +Instead of: Read tool on XMOJ.user.js (loads entire 5000 lines) +Use: Task tool with xmoj-code-navigator agent to find specific sections +``` + +**Exception**: Only use Read tool on XMOJ.user.js when: +- You need to edit a specific line number you already know +- You're making targeted edits and already know the exact location +- You need to verify a small, specific section (use offset and limit parameters) + +## Development Workflow + +### Branch Structure and PR Requirements + +- `master`: Production branch - **DO NOT make PRs directly to master** +- `dev`: Development branch - **ALL PRs must be based on and target this branch** +- `extern-contrib`: External contributors must submit PRs to this branch + +**CRITICAL: All pull requests must:** +1. Be based on the `dev` branch (branch off from `dev`) +2. Target the `dev` branch (not `master`) +3. Merge latest `dev` into your branch before submitting to resolve conflicts + +The workflow is: `dev` → (when ready) → `master` for releases. Direct PRs to `master` are not accepted. +You should follow the PR template that can be found [here](https://raw.githubusercontent.com/XMOJ-Script-dev/.github/refs/heads/main/.github/PULL_REQUEST_TEMPLATE.md). + +### Version Management (CRITICAL - Fully Automated) + +Version updates are **fully automated** via GitHub Actions. When a PR to `dev` modifies `XMOJ.user.js`: + +1. The `UpdateVersion` workflow runs `Update/UpdateVersion.js` which automatically: + - Bumps patch version in `package.json` + - Updates `@version` in `XMOJ.user.js` metadata block + - Adds/updates entry in `Update.json` with PR number, title, and timestamp + - Commits changes back to the PR branch with `github-actions[bot]` + +2. Version sync is enforced between: + - `package.json` → `"version": "x.y.z"` + - `XMOJ.user.js` → `// @version x.y.z` (in metadata block) + - `Update.json` → `UpdateHistory["x.y.z"]` (JSON key) + +**Never manually edit version numbers** - the automation handles this based on PR metadata. + +### Release Notes in PRs + +To add release notes to a PR that will appear in the release, include an HTML comment block in the PR description: + +```markdown + +``` + +The `UpdateVersion.js` script extracts this and adds it to `Update.json` as the `Notes` field. + +### Bypassing Automation + +To prevent CI from touching your PR (e.g., during merge conflicts or debugging), add `//!ci-no-touch` anywhere in `Update.json`. The automation will remove it and exit without making other changes. + +### Release Process + +- **Pre-release**: Push to `dev` triggers a pre-release with `"Prerelease": true` in Update.json +- **Release**: Merge `dev` to `master` triggers a production release +- Releases are created by `Update/GetVersion.js` reading the version from XMOJ.user.js +- Both workflows deploy to Cloudflare Pages and GitHub Pages + +## Code Structure + +### Main Userscript (`XMOJ.user.js`) + +A single-file userscript (~5000 lines) organized as: + +1. **Metadata block** (lines 1-50): Userscript headers + - `@name`, `@version`, `@description`, `@author` + - `@match` patterns for xmoj.tech and 116.62.212.172 + - `@require` declarations for external libraries (CryptoJS, CodeMirror, FileSaver, marked, DOMPurify) + - `@grant` permissions for GM APIs + +2. **Main script body**: Direct DOM manipulation and feature injection + - Page detection and routing based on URL patterns + - UI enhancements using Bootstrap classes + - Feature implementations (auto-refresh, code checking, test data fetching, dark mode, etc.) + - API calls to backend at `api.xmoj-bbs.tech` / `api.xmoj-bbs.me` + +Key classes/functions: +- `compareVersions()` (line 112): Version comparison logic +- `NavbarStyler` class (line 589): Navigation bar styling +- `replaceMarkdownImages()` (line 715): Markdown image processing + +### Update Scripts (`Update/`) + +Node.js scripts run by GitHub Actions (not for local development): + +- **`UpdateVersion.js`**: Automated version bumping for PRs to `dev` + - Reads PR number, title, body from command line args + - Uses `gh` CLI to check out PR branch + - Parses `` blocks from PR body + - Updates version in all three locations + - Pushes changes back to PR branch + +- **`GetVersion.js`**: Extracts current version from XMOJ.user.js for release workflows + +- **`UpdateToRelease.js`**: Changes `"Prerelease": false` when promoting to production + +- **`AutoLabel.js`**: Auto-labels PRs based on content + +These scripts directly manipulate `Update.json` and `XMOJ.user.js` using Node.js fs module. + +## Coding Standards + +### Style Guidelines (from CONTRIBUTING.md) + +- **Variables**: camelCase +- **Functions**: PascalCase +- **Classes**: TitleCase +- **Line endings**: Unix (LF) +- **Do NOT run code formatters** - maintain original formatting +- **Use Bootstrap classes** instead of custom CSS +- **No external libraries** without permission (script already includes many via `@require`) + +### Development Principles + +- **Stability before features**: Bug fixes take priority +- Respect the original code style, even if inconsistent +- New features require prior discussion in an issue +- Before submitting PRs, merge `dev` into your branch and resolve conflicts + +## Testing + +No automated test suite exists. Manual testing workflow: + +1. Install the userscript in Tampermonkey/ScriptCat/Violentmonkey +2. Navigate to xmoj.tech (or 116.62.212.172) +3. Test features on relevant pages: + - Problem lists + - Problem detail pages + - Status/submission pages + - Contest pages + - User profiles + +Observe browser console for errors and verify UI enhancements appear correctly. + +## Common Issues + +### Version Sync Errors + +If you see "XMOJ.user.js and Update.json have different patch versions": +- The automation keeps these in sync normally +- If manually editing (not recommended), update both files +- Use `//!ci-no-touch` if you need to bypass automation temporarily + +### PR Requirements + +- **All PRs must be based on and target `dev` branch, not `master`** +- Only PRs from the same repository (not forks) trigger auto-versioning +- PRs must modify `XMOJ.user.js` to trigger version bumps +- Must merge `dev` into your branch before submitting +- External contributors must target `extern-contrib` branch + +### Single-File Architecture + +The entire userscript is intentionally in one file - do not split into modules. Userscript managers load it as a single file, with external dependencies via `@require` headers in the metadata block. diff --git a/Update.json b/Update.json index 1c7bd178f..fbf81e36c 100644 --- a/Update.json +++ b/Update.json @@ -3288,6 +3288,66 @@ } ], "Notes": "No release notes were provided for this release." + }, + "2.7.3": { + "UpdateDate": 1770816092957, + "Prerelease": true, + "UpdateContents": [ + { + "PR": 905, + "Description": "Add WebSocket notification system for real-time BBS and mail mentions" + } + ], + "Notes": "Adds WebSocket-based real-time notification system for BBS mentions and mail notifications. Notifications now arrive within 1-2 seconds instead of requiring page focus. Includes automatic reconnection with exponential backoff and fallback to polling when WebSocket is unavailable." + }, + "2.7.4": { + "UpdateDate": 1771211196807, + "Prerelease": true, + "UpdateContents": [ + { + "PR": 906, + "Description": "Add toggleable Minimalist Monochrome UI" + } + ], + "Notes": "Added a new toggleable \"极简黑白界面风格\" (Minimalist Monochrome UI) setting under Beautify options. Features serif typography, zero border-radius, line-based visual structure, and automatic dark mode support with charcoal tones." + }, + "3.0.0": { + "UpdateDate": 1771211353041, + "Prerelease": true, + "UpdateContents": [ + { + "PR": 906, + "Description": "Add toggleable Minimalist Monochrome UI" + } + ], + "Notes": "Added a new toggleable \"极简黑白界面风格\" (Minimalist Monochrome UI) setting under Beautify options. Features serif typography, zero border-radius, line-based visual structure, and automatic dark mode support with charcoal tones." + }, + "3.1.0": { + "UpdateDate": 1771254908784, + "Prerelease": false, + "UpdateContents": [ + { + "PR": 895, + "Description": "Update to release 2.7.0" + }, + { + "PR": 896, + "Description": "Update to release 2.7.0" + }, + { + "PR": 905, + "Description": "Add WebSocket notification system for real-time BBS and mail mentions" + }, + { + "PR": 906, + "Description": "Add toggleable Minimalist Monochrome UI" + }, + { + "PR": 906, + "Description": "Add toggleable Minimalist Monochrome UI" + } + ], + "Notes": "v3 显然需要在新年第一天发布(" } } } \ No newline at end of file diff --git a/Update/UpdateVersion.js b/Update/UpdateVersion.js index 840ec2b8b..cd744cd87 100644 --- a/Update/UpdateVersion.js +++ b/Update/UpdateVersion.js @@ -7,6 +7,14 @@ process.env.GITHUB_TOKEN = GithubToken; execSync("gh pr checkout " + PRNumber); console.info("PR #" + PRNumber + " has been checked out."); +// Check if the last commit was made by github-actions[bot] +const lastCommitAuthor = execSync("git log -1 --pretty=format:'%an'").toString().trim(); +console.log("Last commit author: " + lastCommitAuthor); +if (lastCommitAuthor === "github-actions[bot]") { + console.log("Last commit was made by github-actions[bot]. Skipping to prevent infinite loop."); + process.exit(0); +} + const JSONFileName = "./Update.json"; const JSFileName = "./XMOJ.user.js"; var JSONFileContent = readFileSync(JSONFileName, "utf8"); diff --git a/XMOJ.user.js b/XMOJ.user.js index 035aa0e00..aba3fd3d5 100644 --- a/XMOJ.user.js +++ b/XMOJ.user.js @@ -1,6 +1,6 @@ // ==UserScript== // @name XMOJ -// @version 2.7.2 +// @version 3.1.0 // @description XMOJ增强脚本 // @author @XMOJ-Script-dev, @langningchen and the community // @namespace https://github/langningchen @@ -533,6 +533,287 @@ let RequestAPI = (Action, Data, CallBack) => { } }; +// WebSocket Notification System +let NotificationSocket = null; +let NotificationSocketReconnectAttempts = 0; +let NotificationSocketReconnectDelay = 1000; +let NotificationSocketPingInterval = null; +let NotificationSocketReconnectTimer = null; + +function GetPHPSESSID() { + let Session = ""; + let Temp = document.cookie.split(";"); + for (let i = 0; i < Temp.length; i++) { + if (Temp[i].includes("PHPSESSID")) { + Session = Temp[i].split("=")[1]; + break; + } + } + return Session; +} + +function ConnectNotificationSocket() { + try { + // Clear any pending reconnection timer to prevent duplicate connections + if (NotificationSocketReconnectTimer) { + clearTimeout(NotificationSocketReconnectTimer); + NotificationSocketReconnectTimer = null; + } + + let Session = GetPHPSESSID(); + if (Session === "") { + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: PHPSESSID not available, skipping connection"); + } + return; + } + + let wsUrl = (UtilityEnabled("SuperDebug") ? "ws://127.0.0.1:8787" : "wss://api.xmoj-bbs.me") + "/ws/notifications?SessionID=" + Session; + + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: Connecting to", wsUrl); + } + + NotificationSocket = new WebSocket(wsUrl); + + NotificationSocket.onopen = () => { + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: Connected successfully"); + } + NotificationSocketReconnectAttempts = 0; + NotificationSocketReconnectDelay = 1000; + + // Start ping keepalive + if (NotificationSocketPingInterval) { + clearInterval(NotificationSocketPingInterval); + } + NotificationSocketPingInterval = setInterval(() => { + if (NotificationSocket && NotificationSocket.readyState === WebSocket.OPEN) { + NotificationSocket.send(JSON.stringify({ type: 'ping' })); + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: Sent ping"); + } + } else { + clearInterval(NotificationSocketPingInterval); + } + }, 30000); + }; + + NotificationSocket.onmessage = (event) => { + HandleNotificationMessage(event); + }; + + NotificationSocket.onerror = (error) => { + if (UtilityEnabled("DebugMode")) { + console.error("WebSocket: Error", error); + } + }; + + NotificationSocket.onclose = (event) => { + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: Connection closed", event.code, event.reason); + } + if (NotificationSocketPingInterval) { + clearInterval(NotificationSocketPingInterval); + } + ReconnectNotificationSocket(); + }; + } catch (e) { + console.error("WebSocket: Failed to connect", e); + ReconnectNotificationSocket(); + } +} + +function ReconnectNotificationSocket() { + const delay = Math.min(NotificationSocketReconnectDelay * Math.pow(2, NotificationSocketReconnectAttempts), 30000); + NotificationSocketReconnectAttempts++; + + if (UtilityEnabled("DebugMode")) { + console.log(`WebSocket: Reconnecting in ${delay}ms (attempt ${NotificationSocketReconnectAttempts})`); + } + + NotificationSocketReconnectTimer = setTimeout(() => { + ConnectNotificationSocket(); + }, delay); +} + +function HandleNotificationMessage(event) { + try { + const notification = JSON.parse(event.data); + + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: Received message", notification); + } + + if (notification.type === 'connected') { + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: Server confirmed connection at timestamp", notification.timestamp); + } + } else if (notification.type === 'bbs_mention') { + // Backend now provides all data needed for immediate display + CreateAndShowBBSMentionToast(notification.data); + } else if (notification.type === 'mail_mention') { + // Backend now provides all data needed for immediate display + CreateAndShowMailMentionToast(notification.data); + } else if (notification.type === 'pong') { + if (UtilityEnabled("DebugMode")) { + console.log("WebSocket: Received pong"); + } + } + } catch (e) { + console.error("WebSocket: Failed to handle message", e); + } +} + +function CreateAndShowBBSMentionToast(mention) { + let ToastContainer = document.querySelector(".toast-container"); + if (!ToastContainer) return; + + let Toast = document.createElement("div"); + Toast.classList.add("toast"); + Toast.setAttribute("role", "alert"); + let ToastHeader = document.createElement("div"); + ToastHeader.classList.add("toast-header"); + let ToastTitle = document.createElement("strong"); + ToastTitle.classList.add("me-auto"); + ToastTitle.innerHTML = "提醒:有人@你"; + ToastHeader.appendChild(ToastTitle); + let ToastTime = document.createElement("small"); + ToastTime.classList.add("text-body-secondary"); + ToastTime.innerHTML = GetRelativeTime(mention.MentionTime); + ToastHeader.appendChild(ToastTime); + let ToastCloseButton = document.createElement("button"); + ToastCloseButton.type = "button"; + ToastCloseButton.classList.add("btn-close"); + ToastCloseButton.setAttribute("data-bs-dismiss", "toast"); + ToastHeader.appendChild(ToastCloseButton); + Toast.appendChild(ToastHeader); + let ToastBody = document.createElement("div"); + ToastBody.classList.add("toast-body"); + ToastBody.innerHTML = "讨论" + escapeHTML(mention.PostTitle) + "有新回复"; + let ToastFooter = document.createElement("div"); + ToastFooter.classList.add("mt-2", "pt-2", "border-top"); + let ToastDismissButton = document.createElement("button"); + ToastDismissButton.type = "button"; + ToastDismissButton.classList.add("btn", "btn-secondary", "btn-sm", "me-2"); + ToastDismissButton.innerText = "忽略"; + ToastDismissButton.addEventListener("click", () => { + RequestAPI("ReadBBSMention", { + "MentionID": Number(mention.MentionID) + }, () => { + }); + Toast.remove(); + }); + ToastFooter.appendChild(ToastDismissButton); + let ToastViewButton = document.createElement("button"); + ToastViewButton.type = "button"; + ToastViewButton.classList.add("btn", "btn-primary", "btn-sm"); + ToastViewButton.innerText = "查看"; + ToastViewButton.addEventListener("click", () => { + open("https://www.xmoj.tech/discuss3/thread.php?tid=" + mention.PostID + '&page=' + mention.PageNumber, "_blank"); + RequestAPI("ReadBBSMention", { + "MentionID": Number(mention.MentionID) + }, () => { + }); + }); + ToastFooter.appendChild(ToastViewButton); + ToastBody.appendChild(ToastFooter); + Toast.appendChild(ToastBody); + ToastContainer.appendChild(Toast); + new bootstrap.Toast(Toast).show(); +} + +function CreateAndShowMailMentionToast(mention) { + let ToastContainer = document.querySelector(".toast-container"); + if (!ToastContainer) return; + + let Toast = document.createElement("div"); + Toast.classList.add("toast"); + Toast.setAttribute("role", "alert"); + let ToastHeader = document.createElement("div"); + ToastHeader.classList.add("toast-header"); + let ToastTitle = document.createElement("strong"); + ToastTitle.classList.add("me-auto"); + ToastTitle.innerHTML = "提醒:有新消息"; + ToastHeader.appendChild(ToastTitle); + let ToastTime = document.createElement("small"); + ToastTime.classList.add("text-body-secondary"); + ToastTime.innerHTML = GetRelativeTime(mention.MentionTime); + ToastHeader.appendChild(ToastTime); + let ToastCloseButton = document.createElement("button"); + ToastCloseButton.type = "button"; + ToastCloseButton.classList.add("btn-close"); + ToastCloseButton.setAttribute("data-bs-dismiss", "toast"); + ToastHeader.appendChild(ToastCloseButton); + Toast.appendChild(ToastHeader); + let ToastBody = document.createElement("div"); + ToastBody.classList.add("toast-body"); + let ToastUser = document.createElement("span"); + GetUsernameHTML(ToastUser, mention.FromUserID); + ToastBody.appendChild(ToastUser); + ToastBody.appendChild(document.createTextNode(" 给你发了一封短消息")); + let ToastFooter = document.createElement("div"); + ToastFooter.classList.add("mt-2", "pt-2", "border-top"); + let ToastDismissButton = document.createElement("button"); + ToastDismissButton.type = "button"; + ToastDismissButton.classList.add("btn", "btn-secondary", "btn-sm", "me-2"); + ToastDismissButton.setAttribute("data-bs-dismiss", "toast"); + ToastDismissButton.innerText = "忽略"; + ToastDismissButton.addEventListener("click", () => { + RequestAPI("ReadMailMention", { + "MentionID": Number(mention.MentionID) + }, () => { + }); + }); + ToastFooter.appendChild(ToastDismissButton); + let ToastViewButton = document.createElement("button"); + ToastViewButton.type = "button"; + ToastViewButton.classList.add("btn", "btn-primary", "btn-sm"); + ToastViewButton.innerText = "查看"; + ToastViewButton.addEventListener("click", () => { + open("https://www.xmoj.tech/mail.php?to_user=" + mention.FromUserID, "_blank"); + RequestAPI("ReadMailMention", { + "MentionID": Number(mention.MentionID) + }, () => { + }); + }); + ToastFooter.appendChild(ToastViewButton); + ToastBody.appendChild(ToastFooter); + Toast.appendChild(ToastBody); + ToastContainer.appendChild(Toast); + new bootstrap.Toast(Toast).show(); +} + +function PollNotifications() { + // Clear toast container once before fetching to prevent race condition + if (UtilityEnabled("BBSPopup") || UtilityEnabled("MessagePopup")) { + let ToastContainer = document.querySelector(".toast-container"); + if (ToastContainer) { + ToastContainer.innerHTML = ""; + } + } + if (UtilityEnabled("BBSPopup")) { + RequestAPI("GetBBSMentionList", {}, (Response) => { + if (Response.Success) { + let MentionList = Response.Data.MentionList; + for (let i = 0; i < MentionList.length; i++) { + CreateAndShowBBSMentionToast(MentionList[i]); + } + } + }); + } + if (UtilityEnabled("MessagePopup")) { + RequestAPI("GetMailMentionList", {}, (Response) => { + if (Response.Success) { + let MentionList = Response.Data.MentionList; + for (let i = 0; i < MentionList.length; i++) { + CreateAndShowMailMentionToast(MentionList[i]); + } + } + }); + } +} + GM_registerMenuCommand("清除缓存", () => { let Temp = []; for (let i = 0; i < localStorage.length; i++) { @@ -620,15 +901,28 @@ class NavbarStyler { try { let n = this.navbar; n.classList.add('fixed-top', 'container', 'ml-auto'); - Object.assign(n.style, { - position: 'fixed', - borderRadius: '28px', - boxShadow: '0 4px 8px rgba(0, 0, 0, 0.5)', - margin: '16px auto', - backgroundColor: 'rgba(255, 255, 255, 0)', - opacity: '0.75', - zIndex: '1000' - }); + if (UtilityEnabled("MonochromeUI")) { + Object.assign(n.style, { + position: 'fixed', + borderRadius: '0', + boxShadow: '0 4px 8px rgba(0, 0, 0, 0.5)', + margin: '0', + maxWidth: '100%', + backgroundColor: 'rgba(255, 255, 255, 0)', + opacity: '0.75', + zIndex: '1000' + }); + } else { + Object.assign(n.style, { + position: 'fixed', + borderRadius: '28px', + boxShadow: '0 4px 8px rgba(0, 0, 0, 0.5)', + margin: '16px auto', + backgroundColor: 'rgba(255, 255, 255, 0)', + opacity: '0.75', + zIndex: '1000' + }); + } } catch (e) { console.error(e); if (UtilityEnabled("DebugMode")) { @@ -645,7 +939,11 @@ class NavbarStyler { document.body.appendChild(overlay); let style = document.createElement('style'); - style.textContent = ` + style.textContent = UtilityEnabled("MonochromeUI") ? ` + #blur-overlay { + display: none !important; + } + ` : ` #blur-overlay { position: fixed; backdrop-filter: blur(4px); @@ -786,6 +1084,32 @@ async function main() { } else { document.querySelector("html").setAttribute("data-bs-theme", "light"); } + if (UtilityEnabled("MonochromeUI")) { + let fontLink = document.createElement("link"); + fontLink.rel = "stylesheet"; + fontLink.href = "https://fonts.loli.net/css2?family=Playfair+Display:wght@400;700&family=Source+Serif+4:wght@400;600;700&family=JetBrains+Mono:wght@400;500&display=swap"; + document.head.appendChild(fontLink); + let earlyStyle = document.createElement("style"); + earlyStyle.textContent = ` + :root { + --mono-black: #000; --mono-white: #fff; + --mono-gray-100: #f5f5f5; --mono-gray-300: #d4d4d4; + --mono-font-heading: 'Playfair Display', Georgia, serif; + --mono-font-body: 'Source Serif 4', 'Source Serif Pro', Georgia, serif; + } + [data-bs-theme='dark'] { + --mono-black: #e5e5e5; --mono-white: #1a1a1a; + --mono-gray-100: #222; --mono-gray-300: #404040; + } + * { border-radius: 0 !important; box-shadow: none !important; } + body { font-family: var(--mono-font-body) !important; background-color: var(--mono-white) !important; color: var(--mono-black) !important; } + h1,h2,h3,h4,h5,h6 { font-family: var(--mono-font-heading) !important; } + .table thead th { background-color: var(--mono-black) !important; color: var(--mono-white) !important; } + .card { border: 2px solid var(--mono-black) !important; } + .card-header { background-color: var(--mono-black) !important; color: var(--mono-white) !important; } + `; + document.head.appendChild(earlyStyle); + } var resources = [{ type: 'link', href: 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css', @@ -859,6 +1183,382 @@ async function main() { } let Style = document.createElement("style"); document.body.appendChild(Style); + if (UtilityEnabled("MonochromeUI")) { + Style.innerHTML = ` + /* Fonts loaded via to avoid layout shift */ + + :root { + --mono-black: #000; + --mono-white: #fff; + --mono-gray-100: #f5f5f5; + --mono-gray-200: #e5e5e5; + --mono-gray-300: #d4d4d4; + --mono-gray-400: #a3a3a3; + --mono-gray-500: #737373; + --mono-border: 2px solid var(--mono-black); + --mono-border-thin: 1px solid var(--mono-gray-300); + --mono-font-heading: 'Playfair Display', Georgia, serif; + --mono-font-body: 'Source Serif 4', 'Source Serif Pro', Georgia, serif; + --mono-font-mono: 'JetBrains Mono', 'Consolas', monospace; + --mono-transition: 100ms ease; + } + + [data-bs-theme='dark'] { + --mono-black: #e5e5e5; + --mono-white: #1a1a1a; + --mono-gray-100: #222; + --mono-gray-200: #2a2a2a; + --mono-gray-300: #404040; + --mono-gray-400: #737373; + --mono-gray-500: #a3a3a3; + } + + * { + border-radius: 0 !important; + box-shadow: none !important; + } + + body { + font-family: var(--mono-font-body) !important; + color: var(--mono-black) !important; + background-color: var(--mono-white) !important; + } + + h1, h2, h3, h4, h5, h6 { + font-family: var(--mono-font-heading) !important; + font-weight: 700 !important; + } + + code, pre, .CodeMirror, kbd, samp { + font-family: var(--mono-font-mono) !important; + } + + a { + color: var(--mono-black) !important; + text-decoration: none !important; + transition: var(--mono-transition) !important; + } + .container a:not(.nav-link):not(.btn):not(.dropdown-item):not(.list-group-item):not(.page-link) { + border-bottom: 1px solid var(--mono-gray-400) !important; + padding-bottom: 1px !important; + } + .container a:not(.nav-link):not(.btn):not(.dropdown-item):not(.list-group-item):not(.page-link):hover { + border-bottom-color: var(--mono-black) !important; + } + + blockquote { + border-left: 4px solid var(--mono-black) !important; + padding: 0.5em 1em; + } + + /* Navbar */ + .navbar, nav.navbar { + border-bottom: 4px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + opacity: 1 !important; + } + .navbar .nav-link { + color: var(--mono-black) !important; + text-decoration: none !important; + font-family: var(--mono-font-body) !important; + text-transform: uppercase !important; + letter-spacing: 0.05em !important; + font-size: 0.85rem !important; + } + .navbar .nav-link:hover, .navbar .nav-link.active { + background-color: var(--mono-black) !important; + color: var(--mono-white) !important; + } + + /* Buttons */ + .btn { + border: 2px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + text-transform: uppercase !important; + letter-spacing: 0.1em !important; + font-family: var(--mono-font-body) !important; + font-weight: 600 !important; + transition: var(--mono-transition) !important; + } + .btn:hover, .btn:focus, .btn:active, .btn.active { + background-color: var(--mono-black) !important; + color: var(--mono-white) !important; + border-color: var(--mono-black) !important; + } + .btn-primary { + border: 2px solid var(--mono-black) !important; + background-color: var(--mono-black) !important; + color: var(--mono-white) !important; + } + .btn-primary:hover { + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + } + .btn-secondary { + border: 2px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + } + .btn-secondary:hover { + background-color: var(--mono-black) !important; + color: var(--mono-white) !important; + } + .btn-success { + background-color: var(--mono-white) !important; + border: 2px solid #52c41a !important; + color: #52c41a !important; + } + .btn-danger { + background-color: var(--mono-white) !important; + border: 2px solid #fe4c61 !important; + color: #fe4c61 !important; + } + .btn-warning { + background-color: var(--mono-white) !important; + border: 2px solid #ffa900 !important; + color: #ffa900 !important; + } + .btn-info { + background-color: var(--mono-white) !important; + border: 2px solid #0dcaf0 !important; + color: #0dcaf0 !important; + } + + /* Cards */ + .card { + border: 2px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + } + .card-header { + background-color: var(--mono-black) !important; + color: var(--mono-white) !important; + border-bottom: none !important; + font-family: var(--mono-font-heading) !important; + } + .card-header * { + color: var(--mono-white) !important; + } + .card-body { + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + } + .card-footer { + border-top: 1px solid var(--mono-gray-300) !important; + background-color: var(--mono-white) !important; + } + + /* Modals */ + .modal-content { + border: 4px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + } + .modal-header { + border-bottom: 1px solid var(--mono-gray-300) !important; + background-color: var(--mono-white) !important; + } + .modal-footer { + border-top: 1px solid var(--mono-gray-300) !important; + background-color: var(--mono-white) !important; + } + .modal-title { + font-family: var(--mono-font-heading) !important; + } + + /* Toasts */ + .toast { + border: 2px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + } + .toast-header { + background-color: var(--mono-gray-100) !important; + color: var(--mono-black) !important; + border-bottom: 1px solid var(--mono-gray-300) !important; + } + + /* Tables */ + .table { + border-color: var(--mono-gray-300) !important; + } + thead th, th.header, th.headerSortUp, th.headerSortDown { + background-color: var(--mono-black) !important; + background-image: none !important; + color: var(--mono-white) !important; + border-bottom: none !important; + font-family: var(--mono-font-heading) !important; + text-transform: uppercase !important; + letter-spacing: 0.05em !important; + font-size: 0.85rem !important; + } + td, th { + border-color: var(--mono-gray-300) !important; + text-align: center !important; + } + .table-striped > tbody > tr:nth-of-type(odd) > * { + background-color: var(--mono-gray-100) !important; + } + table { + margin-top: 16px !important; + } + + /* List groups */ + .list-group-item { + border: none !important; + border-bottom: 1px solid var(--mono-gray-300) !important; + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + } + .list-group-item-success { + border-left: 4px solid #52c41a !important; + } + .list-group-item-warning { + border-left: 4px solid #ffa900 !important; + } + .list-group-item-danger { + border-left: 4px solid #fe4c61 !important; + } + + /* Dropdowns */ + .dropdown-menu { + border: 2px solid var(--mono-black) !important; + padding: 0 !important; + background-color: var(--mono-white) !important; + } + .dropdown-item { + border-bottom: 1px solid var(--mono-gray-200) !important; + color: var(--mono-black) !important; + transition: var(--mono-transition) !important; + text-decoration: none !important; + } + .dropdown-item:last-child { + border-bottom: none !important; + } + .dropdown-item:hover, .dropdown-item:focus { + background-color: var(--mono-black) !important; + color: var(--mono-white) !important; + } + + /* Forms */ + .form-control, .form-select { + border: 2px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + font-family: var(--mono-font-body) !important; + } + .form-control:focus, .form-select:focus { + outline: 2px solid var(--mono-black) !important; + outline-offset: 2px !important; + border-color: var(--mono-black) !important; + } + + /* Alerts */ + .alert { + border: 2px solid var(--mono-black) !important; + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + } + .alert-primary { + border-left: 8px solid var(--mono-black) !important; + } + + /* Status indicators */ + .status_y { + background-color: #52c41a !important; + color: #fff !important; + border-color: #52c41a !important; + } + .status_n { + background-color: #fe4c61 !important; + color: #fff !important; + border-color: #fe4c61 !important; + } + .status_w { + background-color: #ffa900 !important; + color: #fff !important; + border-color: #ffa900 !important; + } + + .test-case:hover { + border: 2px solid var(--mono-black) !important; + } + + .software_list { + width: unset !important; + } + .software_item { + margin: 5px 10px !important; + background-color: var(--mono-gray-100) !important; + border: 1px solid var(--mono-gray-300) !important; + } + .software_item img { + width: 50px !important; + height: 50px !important; + object-fit: contain !important; + } + .item-txt { + color: var(--mono-black) !important; + } + .cnt-row { + justify-content: inherit; + align-items: stretch; + width: 100% !important; + padding: 1rem 0; + } + .cnt-row-head { + padding: 0.8em 1em; + background-color: var(--mono-black); + color: var(--mono-white); + width: 100%; + font-family: var(--mono-font-heading); + } + .cnt-row-head * { + color: var(--mono-white) !important; + } + .cnt-row-body { + padding: 1em; + border: 2px solid var(--mono-black); + border-top: none; + } + + /* Scrollbar */ + ::-webkit-scrollbar { + width: 8px; + height: 8px; + } + ::-webkit-scrollbar-track { + background: var(--mono-white); + } + ::-webkit-scrollbar-thumb { + background: var(--mono-black); + } + + /* Copy button in inverted headers */ + .cnt-row-head .copy-btn, .card-header .copy-btn { + border-color: var(--mono-white) !important; + color: var(--mono-white) !important; + background-color: transparent !important; + } + .cnt-row-head .copy-btn:hover, .card-header .copy-btn:hover { + background-color: var(--mono-white) !important; + color: var(--mono-black) !important; + } + + /* Problem switcher responsive */ + @media (max-width: 768px) { + .problem-switcher-container { + display: none !important; + } + } + + /* Contain images */ + img { + max-width: 100% !important; + height: auto !important; + } + + /* Hide blur overlay */ + #blur-overlay { display: none !important; }`; + } else { Style.innerHTML = ` nav { border-bottom-left-radius: 5px; @@ -915,9 +1615,10 @@ async function main() { border-top: none; border-radius: 0 0 0.3rem 0.3rem; }`; + } if (UtilityEnabled("AddAnimation")) { Style.innerHTML += `.status, .test-case { - transition: 0.5s !important; + transition: ${UtilityEnabled("MonochromeUI") ? "100ms ease" : "0.5s"} !important; }`; } if (UtilityEnabled("AddColorText")) { @@ -1041,7 +1742,7 @@ async function main() { Array.from(PopupUL.children).forEach(item => { item.style.opacity = 0; item.style.transform = 'translateY(-16px)'; - item.style.transition = 'transform 0.3s ease, opacity 0.5s ease'; + item.style.transition = UtilityEnabled("MonochromeUI") ? 'transform 100ms ease, opacity 100ms ease' : 'transform 0.3s ease, opacity 0.5s ease'; }); let showDropdownItems = () => { PopupUL.style.display = 'block'; @@ -1052,7 +1753,7 @@ async function main() { item._timeout = setTimeout(() => { item.style.opacity = 1; item.style.transform = 'translateY(2px)'; - }, index * 36); + }, index * (UtilityEnabled("MonochromeUI") ? 20 : 36)); }); }; let hideDropdownItems = () => { @@ -1063,7 +1764,7 @@ async function main() { }); setTimeout(() => { PopupUL.style.display = 'none'; - }, 100); + }, UtilityEnabled("MonochromeUI") ? 80 : 100); }; let toggleDropdownItems = () => { if (PopupUL.style.display === 'block') { @@ -1232,135 +1933,31 @@ async function main() { let ToastContainer = document.createElement("div"); ToastContainer.classList.add("toast-container", "position-fixed", "bottom-0", "end-0", "p-3"); document.body.appendChild(ToastContainer); + // Initialize WebSocket notification system + if (CurrentUsername && (UtilityEnabled("BBSPopup") || UtilityEnabled("MessagePopup"))) { + ConnectNotificationSocket(); + } + + // Fallback polling when WebSocket is not connected addEventListener("focus", () => { - if (UtilityEnabled("BBSPopup")) { - RequestAPI("GetBBSMentionList", {}, (Response) => { - if (Response.Success) { - ToastContainer.innerHTML = ""; - let MentionList = Response.Data.MentionList; - for (let i = 0; i < MentionList.length; i++) { - let Toast = document.createElement("div"); - Toast.classList.add("toast"); - Toast.setAttribute("role", "alert"); - let ToastHeader = document.createElement("div"); - ToastHeader.classList.add("toast-header"); - let ToastTitle = document.createElement("strong"); - ToastTitle.classList.add("me-auto"); - ToastTitle.innerHTML = "提醒:有人@你"; - ToastHeader.appendChild(ToastTitle); - let ToastTime = document.createElement("small"); - ToastTime.classList.add("text-body-secondary"); - ToastTime.innerHTML = GetRelativeTime(MentionList[i].MentionTime); - ToastHeader.appendChild(ToastTime); - let ToastCloseButton = document.createElement("button"); - ToastCloseButton.type = "button"; - ToastCloseButton.classList.add("btn-close"); - ToastCloseButton.setAttribute("data-bs-dismiss", "toast"); - ToastHeader.appendChild(ToastCloseButton); - Toast.appendChild(ToastHeader); - let ToastBody = document.createElement("div"); - ToastBody.classList.add("toast-body"); - ToastBody.innerHTML = "讨论" + MentionList[i].PostTitle + "有新回复"; - let ToastFooter = document.createElement("div"); - ToastFooter.classList.add("mt-2", "pt-2", "border-top"); - let ToastDismissButton = document.createElement("button"); - ToastDismissButton.type = "button"; - ToastDismissButton.classList.add("btn", "btn-secondary", "btn-sm", "me-2"); - ToastDismissButton.innerText = "忽略"; - ToastDismissButton.addEventListener("click", () => { - RequestAPI("ReadBBSMention", { - "MentionID": Number(MentionList[i].MentionID) - }, () => { - }); - Toast.remove(); - }); - ToastFooter.appendChild(ToastDismissButton); - let ToastViewButton = document.createElement("button"); - ToastViewButton.type = "button"; - ToastViewButton.classList.add("btn", "btn-primary", "btn-sm"); - ToastViewButton.innerText = "查看"; - ToastViewButton.addEventListener("click", () => { - open("https://www.xmoj.tech/discuss3/thread.php?tid=" + MentionList[i].PostID + '&page=' + MentionList[i].PageNumber, "_blank"); - RequestAPI("ReadBBSMention", { - "MentionID": Number(MentionList[i].MentionID) - }, () => { - }); - }); - ToastFooter.appendChild(ToastViewButton); - ToastBody.appendChild(ToastFooter); - Toast.appendChild(ToastBody); - ToastContainer.appendChild(Toast); - new bootstrap.Toast(Toast).show(); - } - } - }); + if (!NotificationSocket || NotificationSocket.readyState !== WebSocket.OPEN) { + PollNotifications(); } - if (UtilityEnabled("MessagePopup")) { - RequestAPI("GetMailMentionList", {}, async (Response) => { - if (Response.Success) { - if (!UtilityEnabled("BBSPopup")) { - ToastContainer.innerHTML = ""; - } - let MentionList = Response.Data.MentionList; - for (let i = 0; i < MentionList.length; i++) { - let Toast = document.createElement("div"); - Toast.classList.add("toast"); - Toast.setAttribute("role", "alert"); - let ToastHeader = document.createElement("div"); - ToastHeader.classList.add("toast-header"); - let ToastTitle = document.createElement("strong"); - ToastTitle.classList.add("me-auto"); - ToastTitle.innerHTML = "提醒:有新消息"; - ToastHeader.appendChild(ToastTitle); - let ToastTime = document.createElement("small"); - ToastTime.classList.add("text-body-secondary"); - ToastTime.innerHTML = GetRelativeTime(MentionList[i].MentionTime); - ToastHeader.appendChild(ToastTime); - let ToastCloseButton = document.createElement("button"); - ToastCloseButton.type = "button"; - ToastCloseButton.classList.add("btn-close"); - ToastCloseButton.setAttribute("data-bs-dismiss", "toast"); - ToastHeader.appendChild(ToastCloseButton); - Toast.appendChild(ToastHeader); - let ToastBody = document.createElement("div"); - ToastBody.classList.add("toast-body"); - let ToastUser = document.createElement("span"); - GetUsernameHTML(ToastUser, MentionList[i].FromUserID); - ToastBody.appendChild(ToastUser); - ToastBody.innerHTML += " 给你发了一封短消息"; - let ToastFooter = document.createElement("div"); - ToastFooter.classList.add("mt-2", "pt-2", "border-top"); - let ToastDismissButton = document.createElement("button"); - ToastDismissButton.type = "button"; - ToastDismissButton.classList.add("btn", "btn-secondary", "btn-sm", "me-2"); - ToastDismissButton.setAttribute("data-bs-dismiss", "toast"); - ToastDismissButton.innerText = "忽略"; - ToastDismissButton.addEventListener("click", () => { - RequestAPI("ReadMailMention", { - "MentionID": Number(MentionList[i].MentionID) - }, () => { - }); - }); - ToastFooter.appendChild(ToastDismissButton); - let ToastViewButton = document.createElement("button"); - ToastViewButton.type = "button"; - ToastViewButton.classList.add("btn", "btn-primary", "btn-sm"); - ToastViewButton.innerText = "查看"; - ToastViewButton.addEventListener("click", () => { - open("https://www.xmoj.tech/mail.php?to_user=" + MentionList[i].FromUserID, "_blank"); - RequestAPI("ReadMailMention", { - "MentionID": Number(MentionList[i].MentionID) - }, () => { - }); - }); - ToastFooter.appendChild(ToastViewButton); - ToastBody.appendChild(ToastFooter); - Toast.appendChild(ToastBody); - ToastContainer.appendChild(Toast); - new bootstrap.Toast(Toast).show(); - } - } - }); + }); + + // Periodic fallback polling every 60 seconds when WebSocket is down + setInterval(() => { + if (!NotificationSocket || NotificationSocket.readyState !== WebSocket.OPEN) { + PollNotifications(); + } + }, 60000); + + // Handle tab visibility changes - reconnect if connection dropped + document.addEventListener('visibilitychange', () => { + if (!document.hidden && NotificationSocket && + NotificationSocket.readyState !== WebSocket.OPEN && + NotificationSocket.readyState !== WebSocket.CONNECTING) { + ConnectNotificationSocket(); } }); dispatchEvent(new Event("focus")); @@ -1495,7 +2092,9 @@ async function main() { }, {"ID": "RemoveUseless", "Type": "D", "Name": "删去无法使用的功能*"}, { "ID": "ReplaceXM", "Type": "F", - "Name": "将网站中所有“小明”和“我”关键字替换为“高老师”,所有“小红”替换为“徐师娘”,所有“小粉”替换为“彩虹”,所有“下海”、“海上”替换为“上海” (此功能默认关闭)" + "Name": "将网站中所有\"小明\"和\"我\"关键字替换为\"高老师\",所有\"小红\"替换为\"徐师娘\",所有\"小粉\"替换为\"彩虹\",所有\"下海\"、\"海上\"替换为\"上海\" (此功能默认关闭)" + }, { + "ID": "MonochromeUI", "Type": "F", "Name": "极简黑白界面风格" }] }, { "ID": "AutoLogin", "Type": "A", "Name": "在需要登录的界面自动跳转到登录界面" @@ -1688,6 +2287,7 @@ async function main() { } let problemSwitcher = document.createElement("div"); + problemSwitcher.classList.add("problem-switcher-container"); problemSwitcher.style.position = "fixed"; problemSwitcher.style.top = "50%"; problemSwitcher.style.left = "0"; @@ -1695,12 +2295,13 @@ async function main() { problemSwitcher.style.maxHeight = "80vh"; problemSwitcher.style.overflowY = "auto"; if (document.querySelector("html").getAttribute("data-bs-theme") == "dark") { - problemSwitcher.style.backgroundColor = "rgba(0, 0, 0, 0.8)"; + problemSwitcher.style.backgroundColor = UtilityEnabled("MonochromeUI") ? "#000" : "rgba(0, 0, 0, 0.8)"; } else { - problemSwitcher.style.backgroundColor = "rgba(255, 255, 255, 0.8)"; + problemSwitcher.style.backgroundColor = UtilityEnabled("MonochromeUI") ? "#FFF" : "rgba(255, 255, 255, 0.8)"; } problemSwitcher.style.padding = "10px"; - problemSwitcher.style.borderRadius = "0 10px 10px 0"; + problemSwitcher.style.borderRadius = UtilityEnabled("MonochromeUI") ? "0" : "0 10px 10px 0"; + if (UtilityEnabled("MonochromeUI")) problemSwitcher.style.borderRight = "4px solid"; problemSwitcher.style.display = "flex"; problemSwitcher.style.flexDirection = "column"; @@ -1947,7 +2548,7 @@ async function main() { ImproveACRateButton.innerText = "提高正确率"; ImproveACRateButton.disabled = true; let ACProblems = []; - await fetch("https://www.xmoj.tech/userinfo.php?user=" + CurrentUsername) + fetch("https://www.xmoj.tech/userinfo.php?user=" + CurrentUsername) .then((Response) => { return Response.text(); }).then((Response) => { @@ -2040,13 +2641,13 @@ async function main() { } if (UtilityEnabled("RefreshSolution")) { - let StdList; - await new Promise((Resolve) => { + let StdList = null; + let StdListReady = new Promise((Resolve) => { RequestAPI("GetStdList", {}, async (Result) => { if (Result.Success) { StdList = Result.Data.StdList; - Resolve(); } + Resolve(); }) }); @@ -2059,7 +2660,7 @@ async function main() { Points[SolutionID] = Rows[i].cells[2].children[1].innerText; Rows[i].cells[2].children[1].remove(); } - Rows[i].cells[2].innerHTML += ""; + Rows[i].cells[2].innerHTML += UtilityEnabled("MonochromeUI") ? "" : ""; setTimeout(() => { RefreshResult(SolutionID); }, 0); @@ -2078,7 +2679,7 @@ async function main() { .then((Response) => { return Response.text(); }) - .then((Response) => { + .then(async (Response) => { let PID = 0; if (SearchParams.get("cid") === null) { PID = localStorage.getItem("UserScript-Solution-" + SolutionID + "-Problem"); @@ -2101,25 +2702,29 @@ async function main() { setTimeout(() => { RefreshResult(SolutionID) }, 500); - TempHTML += ""; + TempHTML += UtilityEnabled("MonochromeUI") ? "" : ""; } else if (ResponseData[0] == 4 && UtilityEnabled("UploadStd")) { + await StdListReady; + if (!StdList) { /* skip upload if list fetch failed */ } + else { if (SearchParams.get("cid") == null) CurrentRow.cells[1].innerText; let Std = StdList.find((Element) => { return Element == Number(PID); }); if (Std != undefined) { - TempHTML += "✅"; + TempHTML += UtilityEnabled("MonochromeUI") ? "[STD]" : "✅"; } else { RequestAPI("UploadStd", { "ProblemID": Number(PID), }, (Result) => { if (Result.Success) { - CurrentRow.cells[2].innerHTML += "🆗"; + CurrentRow.cells[2].innerHTML += UtilityEnabled("MonochromeUI") ? "[OK]" : "🆗"; } else { - CurrentRow.cells[2].innerHTML += "⚠️"; + CurrentRow.cells[2].innerHTML += UtilityEnabled("MonochromeUI") ? "[ERR]" : "⚠️"; } }); } + } } CurrentRow.cells[2].innerHTML = TempHTML; }); @@ -2577,7 +3182,7 @@ async function main() { }) })(); CodeMirrorElement.setSize("100%", "auto"); - CodeMirrorElement.getWrapperElement().style.border = "1px solid #ddd"; + CodeMirrorElement.getWrapperElement().style.border = UtilityEnabled("MonochromeUI") ? "2px solid var(--mono-black)" : "1px solid #ddd"; if (SearchParams.get("sid") !== null) { await fetch("https://www.xmoj.tech/getsource.php?id=" + SearchParams.get("sid")) diff --git a/package.json b/package.json index d558b7acf..3f59d6be3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "xmoj-script", - "version": "2.7.2", + "version": "3.1.0", "description": "an improvement script for xmoj.tech", "main": "AddonScript.js", "scripts": {