Skip to content

Use Monaco Editor and save code in submitpage.php when edit the content#989

Merged
def-WA2025 merged 50 commits into
devfrom
def-WA2025/monaco-editor-and-save-code
Jun 12, 2026
Merged

Use Monaco Editor and save code in submitpage.php when edit the content#989
def-WA2025 merged 50 commits into
devfrom
def-WA2025/monaco-editor-and-save-code

Conversation

@def-WA2025

@def-WA2025 def-WA2025 commented May 30, 2026

Copy link
Copy Markdown
Member

What does this PR aim to accomplish?:

Use Monaco Editor and save code in submitpage.php when edit the content.

How does this PR accomplish the above?:

Editor -> Monaco

Save code in localStorage.


By submitting this pull request, I confirm the following:

  1. I have read and understood the contributor's guide, as well as this entire template. I understand which branch to base my commits and Pull Requests against.
  2. I have commented on my proposed changes within the code.
  3. I have tested my changes.
  4. I am willing to help maintain this change if there are issues with it later.
  5. It is compatible with the GNU General Public License v3.0
  6. I have squashed any insignificant commits. (git rebase)
  7. I have checked that another pull request for this purpose does not exist.
  8. I have considered and confirmed that this submission will be valuable to others.
  9. I accept that this submission may not be used, and the pull request can be closed at the will of the maintainer.
  10. I give this submission freely and claim no ownership to its content.
  11. I have verified that my changes work correctly in both the new UI and the old/classic UI.

  • I have read the above and my PR is ready for review. Check this box to confirm

Summary by Sourcery

Replace the legacy CodeMirror integration with a Monaco-based editor abstraction and apply it to the submission page, including autosave and graceful fallbacks.

New Features:

  • Integrate Monaco editor loading and initialization utilities with a CodeMirror-compatible shim API.
  • Use Monaco as the primary code editor on the submission page, including keyboard shortcuts and local code persistence per problem or contest.
  • Show a small read-only Monaco code snippet (or text fallback) for generated freopen helper code in the error message area.

Bug Fixes:

  • Harden editor sizing by providing a fixed minimum height fallback when automatic Monaco layout calculation fails.

Enhancements:

  • Refine the submission page header structure for clearer dynamic rendering of problem or contest identifiers.

Build:

  • Bump script and package version numbers to 3.5.2.

Summary by Sourcery

Replace the legacy CodeMirror integration with a Monaco-based editor abstraction and apply it to the submission page, including autosave and safer error/standard-solution displays.

New Features:

  • Introduce a Monaco editor loader and CodeMirror-compatible shim used throughout the script.
  • Use a Monaco-based editor on the submission page with per-problem local storage and keyboard shortcuts, falling back to a textarea if Monaco fails to load.
  • Render a small read-only Monaco (or text) snippet for generated freopen helper code inside the error area.

Bug Fixes:

  • Prevent CE info and standard-solution pages from breaking when the underlying page shows access-denied or missing-problem messages, and clean up any transient error snippet editors between submissions.

Enhancements:

  • Refine the submission page header layout for clearer problem and contest identification and make editor sizing more robust, including viewport-fitting behavior.
  • Align dark-mode themes across Monaco- and CodeMirror-based views by using the Monaco dark theme name where applicable.

Build:

  • Bump userscript and package versions to 3.5.2 and update metadata for the new editor support.

@sourcery-ai

sourcery-ai Bot commented May 30, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Replace the legacy CodeMirror-based submission editor with a Monaco-backed abstraction, use it on submitpage.php with autosave and fallbacks, and adjust several read-only code views and headers while bumping versions to 3.5.2.

Sequence diagram for Monaco-backed submission editor initialization and autosave

sequenceDiagram
    actor User
    participant Browser
    participant main
    participant createMonacoEditor
    participant ensureMonaco
    participant monaco_editor as monaco.editor
    participant localStorage

    User->>Browser: Open /submitpage.php
    Browser->>main: execute()
    main->>main: Build _submitPageHeader DOM
    main->>main: Define getSubmitStorageKey()
    main->>createMonacoEditor: createMonacoEditor('MonacoEditor', editorOptions)
    activate createMonacoEditor
    createMonacoEditor->>ensureMonaco: ensureMonaco()
    activate ensureMonaco
    ensureMonaco->>Browser: load loader.js via MonacoCDN
    ensureMonaco->>Browser: require(['vs/editor/editor.main'])
    ensureMonaco-->>createMonacoEditor: monaco available
    deactivate ensureMonaco

    createMonacoEditor->>monaco_editor: monaco.editor.create(innerHost, options)
    createMonacoEditor->>localStorage: getItem(localStorageKey)
    localStorage-->>createMonacoEditor: saved code or null
    createMonacoEditor-->>main: CodeMirrorElement (Monaco adapter)
    deactivate createMonacoEditor

    main->>monaco_editor: addCommand(Ctrl+Enter, Submit.click)
    main->>monaco_editor: addCommand(Ctrl+Space, triggerSuggest)
    main->>Browser: remove loadEditor placeholder

    loop onDidChangeModelContent
        monaco_editor-->>createMonacoEditor: content changed
        createMonacoEditor->>localStorage: setItem(localStorageKey, editor.getValue())
    end

    alt Monaco initialization fails
        createMonacoEditor--x main: throw Error
        main->>Browser: hide MonacoEditor
        main->>Browser: show CodeInput textarea
        main->>localStorage: getItem(getSubmitStorageKey())
        main->>Browser: attach keydown Ctrl+Enter -> Submit.click
        loop textarea input
            Browser->>localStorage: setItem(fallbackKey, textarea.value)
        end
    end
Loading

File-Level Changes

Change Details Files
Introduce a Monaco editor loader and CodeMirror-compatible shim to centralize editor creation and support diff views.
  • Add MonacoCDN constant and ensureMonaco loader that configures AMD require and loads vs/editor/editor.main from CDN with timeout handling.
  • Implement createMonacoEditor helper that instantiates Monaco editors with viewport-fitting height logic, theme selection, localStorage persistence, and a thin adapter API (get/setValue, setSize, focus, navigation helpers, dispose).
  • Wrap the Monaco editor in a window.CodeMirror shim supporting fromTextArea and MergeView, including loading placeholders, textarea replacement, diff editor creation, and mode-to-language mapping.
XMOJ.user.js
Replace the submitpage.php CodeMirror usage with Monaco-based editor integration, including autosave, keyboard shortcuts, and textarea fallback.
  • Refactor submit page header rendering to use DOM construction for problem/contest labels instead of string concatenation.
  • Render a MonacoEditor container plus hidden textarea, then asynchronously create a Monaco editor with automatic layout, dark/light theme, per-problem/contest localStorage key, and viewport-fitting height.
  • Hook Ctrl+Enter and Ctrl+Space commands in Monaco to trigger submit and suggestions, and style the editor wrapper border according to the MonochromeUI setting.
  • On Monaco load failure, fall back to a visible textarea with similar autosave behavior, dynamic height calculation, and Ctrl+Enter submit shortcut, while exposing a minimal CodeMirrorElement-like interface.
XMOJ.user.js
Enhance error message handling on the submit page with Monaco-based freopen snippets and cleanup of transient editors.
  • Add _xmoj_disposeErrorMessageEditors helper to dispose transient Monaco editors and clear associated hosts in the error message area.
  • Call _xmoj_disposeErrorMessageEditors before setting various ErrorMessage contents (contest ended, submit failure, IO filename hint, commented freopen, empty source, compile error) to avoid orphaned editors.
  • Replace the CodeMirror-based freopen snippet with a compact Monaco read-only editor when monaco is available, falling back to a simple pre block otherwise, and track instances in window._xmoj_temp_error_editors.
XMOJ.user.js
Align themes and behavior of read-only CodeMirror viewers and improve problem_std.php and ceinfo.php rendering.
  • Switch CodeMirror theme mappings from "darcula" to Monaco-compatible dark theme key "vs-dark" in multiple read-only views (diff MergeView, apply patch, code viewer pages, etc.).
  • Guard ceinfo.php rendering to skip transforming the page when the jumbotron reports "I am sorry, You could not view this message!".
  • Guard problem_std.php rendering to skip when "No such Problem!", then rebuild the page with one CodeMirror viewer per
     standard solution block and remove an obsolete loading overlay element if present.
XMOJ.user.js
Bump project version metadata to 3.5.2.
  • Update userscript @Version header from 3.5.1 to 3.5.2.
  • Update npm package version in package.json from 3.5.1 to 3.5.2.
  • Update Update.json version metadata accordingly.
XMOJ.user.js
package.json
Update.json

Assessment against linked issues

Issue Objective Addressed Explanation
#967 Use Monaco Editor as the code editor on the submission page (/submitpage.php) instead of the existing editor.
#967 Persist code entered on the submission page locally (e.g., via localStorage) so that it is not lost on refresh.

Possibly linked issues

  • #: The PR introduces Monaco on the submit page with localStorage autosave, exactly fulfilling the requested feature.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@hendragon-bot hendragon-bot Bot added the user-script This issue or pull request is related to the main user script label May 30, 2026
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 30, 2026

Copy link
Copy Markdown

Deploying xmoj-script-dev-channel with  Cloudflare Pages  Cloudflare Pages

Latest commit: 317d4af
Status: ✅  Deploy successful!
Preview URL: https://5fb59fb4.xmoj-script-dev-channel.pages.dev
Branch Preview URL: https://def-wa2025-monaco-editor-and.xmoj-script-dev-channel.pages.dev

View logs

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 security issues, 1 other issue, and left some high level feedback:

Security issues:

  • User controlled data in methods like innerHTML, outerHTML or document.write is an anti-pattern that can lead to XSS vulnerabilities (link)
  • User controlled data in a document.querySelector("body > div > div.mt-3").innerHTML is an anti-pattern that can lead to XSS vulnerabilities (link)

General comments:

  • On submitpage.php the hidden #CodeInput textarea is no longer bound to the editor as it was with CodeMirror.fromTextArea; make sure you copy the Monaco editor content back into #CodeInput (e.g., in the submit handler) so the backend still receives the code.
  • In the freopen snippet error block you always append an empty div (codeHost) to #ErrorMessage and, in the fallback path, also append a
     directly to #ErrorMessage; consider either rendering the fallback 
     inside codeHost or skipping codeHost creation when Monaco is unavailable to avoid redundant markup.
  • The CodeMirror shim exposes _monacoEditor and callers reach into that to add commands; consider exposing a small public API (e.g., addCommand/triggerSuggest) on the adapter instead of using the private _monacoEditor field to keep the abstraction boundary cleaner.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- On submitpage.php the hidden #CodeInput textarea is no longer bound to the editor as it was with CodeMirror.fromTextArea; make sure you copy the Monaco editor content back into #CodeInput (e.g., in the submit handler) so the backend still receives the code.
- In the freopen snippet error block you always append an empty div (codeHost) to #ErrorMessage and, in the fallback path, also append a <pre> directly to #ErrorMessage; consider either rendering the fallback <pre> inside codeHost or skipping codeHost creation when Monaco is unavailable to avoid redundant markup.
- The CodeMirror shim exposes _monacoEditor and callers reach into that to add commands; consider exposing a small public API (e.g., addCommand/triggerSuggest) on the adapter instead of using the private _monacoEditor field to keep the abstraction boundary cleaner.

## Individual Comments

### Comment 1
<location path="XMOJ.user.js" line_range="374-383" />
<code_context>
+    shim.MergeView = function(container, options) {
</code_context>
<issue_to_address>
**suggestion (bug_risk):** MergeView hardcodes the language to C++, ignoring any mode/language passed in options.

The shim currently instantiates both models with language `'cpp'` and ignores `options.mode` (or any language option), which changes behavior compared to the CodeMirror-based MergeView for non-C++ content. Please derive the Monaco language from the provided mode (similar to `shim`/`createMonacoEditor`, mapping known CodeMirror modes and defaulting to C++) so other languages still get appropriate syntax handling.
</issue_to_address>

### Comment 2
<location path="XMOJ.user.js" line_range="3633-3638" />
<code_context>
                    document.querySelector("body > div > div.mt-3").innerHTML = `<center class="mb-3">` + `<h3>提交代码</h3>` + (SearchParams.get("id") != null ? `题目<span class="blue">${Number(SearchParams.get("id"))}</span>` : `比赛<span class="blue">${Number(SearchParams.get("cid")) + `</span>&emsp;题目<span class="blue">` + String.fromCharCode(65 + parseInt(SearchParams.get("pid")))}</span>`) + `</center>
    <div id="MonacoEditor" style="width:100%; height:400px;"></div>
    <textarea id="CodeInput" style="display:none"></textarea>
    <center class="mt-3">
        <input id="enable_O2" name="enable_O2" type="checkbox"><label for="enable_O2">打开O2开关</label>
        <br>
        <input id="Submit" class="btn btn-info mt-2" type="button" value="提交">
        <div id="ErrorElement" class="mt-2" style="display: none; text-align: left; padding: 10px;">
            <div id="ErrorMessage" style="white-space: pre; background-color: rgba(0, 0, 0, 0.1); padding: 10px; border-radius: 5px;"></div>
            <button id="PassCheck" class="btn btn-outline-secondary mt-2" style="display: none">强制提交</button>
        </div>
    </center>`;
</code_context>
<issue_to_address>
**security (javascript.browser.security.insecure-document-method):** User controlled data in methods like `innerHTML`, `outerHTML` or `document.write` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

### Comment 3
<location path="XMOJ.user.js" line_range="3633-3638" />
<code_context>
                    document.querySelector("body > div > div.mt-3").innerHTML = `<center class="mb-3">` + `<h3>提交代码</h3>` + (SearchParams.get("id") != null ? `题目<span class="blue">${Number(SearchParams.get("id"))}</span>` : `比赛<span class="blue">${Number(SearchParams.get("cid")) + `</span>&emsp;题目<span class="blue">` + String.fromCharCode(65 + parseInt(SearchParams.get("pid")))}</span>`) + `</center>
    <div id="MonacoEditor" style="width:100%; height:400px;"></div>
    <textarea id="CodeInput" style="display:none"></textarea>
    <center class="mt-3">
        <input id="enable_O2" name="enable_O2" type="checkbox"><label for="enable_O2">打开O2开关</label>
        <br>
        <input id="Submit" class="btn btn-info mt-2" type="button" value="提交">
        <div id="ErrorElement" class="mt-2" style="display: none; text-align: left; padding: 10px;">
            <div id="ErrorMessage" style="white-space: pre; background-color: rgba(0, 0, 0, 0.1); padding: 10px; border-radius: 5px;"></div>
            <button id="PassCheck" class="btn btn-outline-secondary mt-2" style="display: none">强制提交</button>
        </div>
    </center>`;
</code_context>
<issue_to_address>
**security (javascript.browser.security.insecure-innerhtml):** User controlled data in a `document.querySelector("body > div > div.mt-3").innerHTML` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread XMOJ.user.js Outdated
Comment thread XMOJ.user.js Outdated
Comment thread XMOJ.user.js Outdated

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New security issues found

Comment thread XMOJ.user.js Outdated
Comment thread XMOJ.user.js Outdated
cubic-dev-ai[bot]

This comment was marked as off-topic.

cubic-dev-ai[bot]

This comment was marked as outdated.

PythonSmall-Q

This comment was marked as outdated.

@PythonSmall-Q

Copy link
Copy Markdown
Member

@copilot fix all

This comment was marked as off-topic.

PythonSmall-Q and others added 2 commits May 31, 2026 16:20
Signed-off-by: Shan Wenxiao <seanoj_noreply@yeah.net>
Copilot AI changed the title Use Monaco Editor and save code in submitpage.php when edit the content. Fix always-false typeof h === 'number' check in Monaco adapter setSize May 31, 2026
@PythonSmall-Q PythonSmall-Q changed the title Fix always-false typeof h === 'number' check in Monaco adapter setSize Use Monaco Editor and save code in submitpage.php when edit the content May 31, 2026
@PythonSmall-Q

Copy link
Copy Markdown
Member

@sourcery-ai review

def-WA2025 and others added 4 commits June 6, 2026 22:30
Removed the creation of a custom style element for Monaco editor. Added error handling for disposing transient Monaco editors in various functions.

Signed-off-by: zsTree <wa2025666@gmail.com>
Signed-off-by: zsTree <wa2025666@gmail.com>
@def-WA2025

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • In createMonacoEditor, applyAutoFit references the editor const before it’s initialized (via typeof editor !== 'undefined'), which will hit the temporal dead zone and can throw a ReferenceError; consider passing the editor instance into applyAutoFit or closing over it only after initialization instead of touching it inside the pre‑init calls.
  • The CodeMirror.fromTextArea shim replaces the original <textarea> with a div without copying over attributes like id, name, or classes, which may break selectors or CSS that rely on the original element identity; consider preserving key attributes on the replacement container.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `createMonacoEditor`, `applyAutoFit` references the `editor` const before it’s initialized (via `typeof editor !== 'undefined'`), which will hit the temporal dead zone and can throw a `ReferenceError`; consider passing the editor instance into `applyAutoFit` or closing over it only after initialization instead of touching it inside the pre‑init calls.
- The `CodeMirror.fromTextArea` shim replaces the original `<textarea>` with a div without copying over attributes like `id`, `name`, or classes, which may break selectors or CSS that rely on the original element identity; consider preserving key attributes on the replacement container.

## Individual Comments

### Comment 1
<location path="XMOJ.user.js" line_range="5244" />
<code_context>
-                                }).setSize("100%", "auto");
+                                }).setSize("100%", "730px");
                             }
+                            document.getElementById("overlay").remove();
                         });
                 } else if (location.pathname == "/mail.php") {
</code_context>
<issue_to_address>
**issue (bug_risk):** Removing the `overlay` element without a null check can throw if it is missing.

If `document.getElementById('overlay')` returns `null`, calling `.remove()` will throw and stop the handler. Consider guarding the call, e.g.:

```js
const overlay = document.getElementById('overlay');
if (overlay && overlay.remove) overlay.remove();
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread XMOJ.user.js Outdated
@def-WA2025

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The logic for computing available viewport height from the header (in createMonacoEditor, the diff editor shim, and the textarea fallback) is duplicated with slightly different implementations; consider extracting a shared helper to keep sizing behavior consistent and easier to maintain.
  • The Monaco loader currently hardcodes a specific CDN URL and version; it would be more flexible to centralize this configuration (e.g., at the top-level or behind a small config object) so it can be updated or overridden without touching multiple call sites.
  • In the CodeMirror shim, placeholderAdapter methods are reassigned asynchronously after Monaco loads, which can be subtle and race-prone; consider returning a Promise-resolved adapter or exposing an explicit ready Promise to make consumer code more robust and predictable.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The logic for computing available viewport height from the header (in `createMonacoEditor`, the diff editor shim, and the textarea fallback) is duplicated with slightly different implementations; consider extracting a shared helper to keep sizing behavior consistent and easier to maintain.
- The Monaco loader currently hardcodes a specific CDN URL and version; it would be more flexible to centralize this configuration (e.g., at the top-level or behind a small config object) so it can be updated or overridden without touching multiple call sites.
- In the CodeMirror shim, `placeholderAdapter` methods are reassigned asynchronously after Monaco loads, which can be subtle and race-prone; consider returning a Promise-resolved adapter or exposing an explicit `ready` Promise to make consumer code more robust and predictable.

## Individual Comments

### Comment 1
<location path="XMOJ.user.js" line_range="5255" />
<code_context>
-                                }).setSize("100%", "auto");
+                                }).setSize("100%", "730px");
                             }
+                            document.getElementById("overlay").remove();
                         });
                 } else if (location.pathname == "/mail.php") {
</code_context>
<issue_to_address>
**issue:** Make overlay removal resilient if the element is missing

Accessing `#overlay` unconditionally can throw if it isn’t rendered on this page or has already been removed, which can break the `problem_std.php` flow. Consider guarding the call:

```js
const overlay = document.getElementById('overlay');
if (overlay && overlay.remove) overlay.remove();
```

This preserves current behavior when the overlay exists while preventing runtime errors when it doesn’t.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread XMOJ.user.js Outdated

@PythonSmall-Q PythonSmall-Q left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2026-06-07.154701.mp4

重交页面逻辑错误,不应该保留

多用cdnjs

Comment thread XMOJ.user.js Outdated
@PythonSmall-Q

PythonSmall-Q commented Jun 10, 2026 via email

Copy link
Copy Markdown
Member

@def-WA2025

Copy link
Copy Markdown
Member Author

https://s4.zstatic.net/npm/monaco-editor@0.55.1/min/vs/loader.js

I think it faster than cloudflare cdnjs

Signed-off-by: zsTree <wa2025666@gmail.com>
github-actions Bot and others added 3 commits June 11, 2026 15:55
Removed unused localStorage fallback logic for submission key.

Signed-off-by: zsTree <wa2025666@gmail.com>
@def-WA2025

Copy link
Copy Markdown
Member Author

I used Cloudflare cdnjs now

@def-WA2025

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@def-WA2025 def-WA2025 requested a review from PythonSmall-Q June 11, 2026 16:01

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • There are many broad try { ... } catch (e) {} blocks that fully swallow errors (especially around Monaco loading and layout); consider at least logging or gating these behind a debug flag so failures are diagnosable without overwhelming the console in normal use.
  • The ensureMonaco loader assumes a global require/AMD environment and hardcodes the Monaco CDN/version; it may be more robust to guard against conflicting require implementations and to centralize the CDN/version into a single configuration spot or feature flag so it can be updated or overridden more easily.
  • The auto-fit height computation for the Monaco hosts relies on locating a header/nav element and can return null if the DOM structure is unexpected; it may be safer to provide a consistent minimum height fallback (not just in the Math.max call) when the header cannot be found or getBoundingClientRect fails, to avoid very small or zero-height editors on atypical layouts.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- There are many broad `try { ... } catch (e) {}` blocks that fully swallow errors (especially around Monaco loading and layout); consider at least logging or gating these behind a debug flag so failures are diagnosable without overwhelming the console in normal use.
- The `ensureMonaco` loader assumes a global `require`/AMD environment and hardcodes the Monaco CDN/version; it may be more robust to guard against conflicting `require` implementations and to centralize the CDN/version into a single configuration spot or feature flag so it can be updated or overridden more easily.
- The auto-fit height computation for the Monaco hosts relies on locating a header/nav element and can return `null` if the DOM structure is unexpected; it may be safer to provide a consistent minimum height fallback (not just in the `Math.max` call) when the header cannot be found or `getBoundingClientRect` fails, to avoid very small or zero-height editors on atypical layouts.

## Individual Comments

### Comment 1
<location path="XMOJ.user.js" line_range="5241-5250" />
<code_context>
+                            if (!ParsedDocument.getElementsByClassName("jumbotron")[0].innerHTML.includes('No such Problem!')) {
</code_context>
<issue_to_address>
**issue:** Similarly guard against missing `.jumbotron` element on `problem_std.php`

This repeats the CE info pattern: `getElementsByClassName("jumbotron")[0].innerHTML` is used without confirming the element exists, so a missing/renamed `.jumbotron` will throw and break the standard solution view. Please first store the element, check it’s non-null, then access `.innerHTML` so minor HTML changes don’t cause runtime errors.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread XMOJ.user.js

@PythonSmall-Q PythonSmall-Q left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you wish, you may add console output of debug data

def-WA2025 and others added 2 commits June 13, 2026 00:38
Enhanced error handling by adding console error logging and user alerts in DebugMode for various operations.

Signed-off-by: zsTree <wa2025666@gmail.com>
@def-WA2025 def-WA2025 merged commit 1ca8d17 into dev Jun 12, 2026
6 checks passed
@def-WA2025 def-WA2025 deleted the def-WA2025/monaco-editor-and-save-code branch June 12, 2026 16:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL user-script This issue or pull request is related to the main user script

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] 提交时使用 Monaco Editor 编辑器

4 participants