Skip to content

swapDoc, refresh and onResize (Refs #39, Refs #40) - #91

Draft
DJAscendance wants to merge 12 commits into
masterfrom
feat/swap-doc-refresh
Draft

DJAscendance wants to merge 12 commits into
masterfrom
feat/swap-doc-refresh

Conversation

@DJAscendance

@DJAscendance DJAscendance commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Refs #39
Refs #40

Ledger rows: 481 swapDoc, 480 refresh, 418 onResize.

Base: 7d917785a1b65259b238f35a3fad98343d8a6d02 (master, merged in); parent PR head ac0238af964e2cfd1d36b7568b2227dcd86f3a3c
Head: 5ee41bf7dfbe0684c885a175941224129bfe97ad

Integration: Stacked on #90 (ac0238a); merge in order #81, #83, #86, #89, #90, #91, #92. Until the PR below it merges, this PR's diff against master includes that PR.

What this adds

  • Editor::swap_doc(doc) -> Result<Doc, CmError> (methods.js:423). It does what CM5 does, in this order:

    • old.cm = null, then attaches the new document.
    • attachDoc's work: the highlight state starts over for the new document (modeGen + 1), the mode is loaded from doc.modeOption, the line heights are dropped, findMaxLine runs, the view is reset, and the whole document is registered as changed.
    • clearCaches.
    • Scrolls to the new document's own scrollLeft/scrollTop. Each document keeps the position it was shown at (Doc::scroll_pos).
    • swapDoc fires delayed with the old document. As in CM5's finishOperation, it fires before the redraw's update.

    A document that already has an editor returns CmError::DocInUse, and nothing changes.

  • Editor::refresh() (methods.js:411, a methodOp), in this order: a whole-document regChange, forceUpdate, clearCaches, scrollToCoords(scrollLeft, scrollTop), updateGutterSpace, estimateLineHeights, then the immediate refresh event (Editor::on_refresh). set_metrics(m) now stores the metrics and runs refresh(); cm-web's WebEditor::refresh already calls it.

  • Editor::on_resize(width, height, metrics) (global_events.js:39). When the host re-measured different metrics, it drops the measurement caches, then runs setSize. No refresh event.

  • cm-core changes:

    • Doc::set_mode_option, scroll_pos and set_scroll_pos.
    • Doc::has_editor is now public.
    • The editor writes doc.modeOption in the constructor and in set_mode, as CM5's mode option handler does.

Upstream refs (pinned 4ca3d05)

src/edit/methods.js:411-435; src/edit/global_events.js:39-45; src/display/mode_state.js; src/util/operation_group.js:32-41; test/doc_test.js:228-265.

Tests and evidence

  • crates/cm-view/tests/swap_refresh.rs:
    • Ports doc_test.js swapDoc, docKeepsScroll, copyDoc and docKeepsMode. docKeepsMode uses text/x-rustsrc in place of markdown.
    • swap_doc_event_in_use_and_state: event order, DocInUse, view, longest line and highlighting.
    • refresh_event_and_redraw: also covers set_metrics changing geometry.
    • on_resize_applies_metrics_and_size
  • Strict, on the top of the stack (Cursor drawing: showCursorWhenSelecting, cursorHeight, fat cursor, overwriteToggle (Refs #51) #92 0b167ad, which contains this PR and every PR below it): cargo test --workspace --no-fail-fast gave 834 passed, 0 failed, 0 ignored. The same under xvfb-run -a: 834 passed, 0 failed. tools/web-test.sh: all 5 browser profiles passed 63/63.
  • cm-web code is not changed.

Known differences

  • refresh always re-estimates line heights. CM5 skips this when the text height did not change and lines do not wrap; skipping only saves work.
  • swapDoc has no state.selectingText/input.reset equivalent, because those are DOM/input state.
  • onResize: the native window still maps a resize to set_size and does not re-measure on a scale-factor change, because its font size is fixed at creation. Row 418 stays PARTIAL.

Coverage change

  • 481: NOT_PORTED → PORTED
  • 480: PARTIAL → PORTED
  • 418: PARTIAL → PARTIAL

After the merge, swap_doc also recomputes has_widgets for the new document and keeps addModeClass. New test: swap_doc_line_widget_heights.

CI: pending (Actions cannot start: billing)

)

cursorCoords/charCoords/coordsChar/lineAtHeight/heightAtLine method forms
(cursor_coords_in, char_coords_in, coords_char_in, line_at_height_in,
height_at_line_in) with page and window modes over a host-supplied
window origin and page scroll, start=null/true/false, clipPos, LineHandle
arguments, includeWidgets (no widgets yet) and the end-of-document
adjustment; intoCoordSystem/fromCoordSystem ported with CM5's div
(viewOffset) semantics. The port's internal document-y frame is now
CoordSys::Doc. Checked against a CM5 recording (cm5-coord-systems.json).
… (Refs #54)

get_scroll_info() returns CM5's {left, top, height, width, clientHeight,
clientWidth}; scroll_into_view_target takes null (cursor plus
cursorScrollMargin), a line number, a position, a range, a coordinate box
or a box range (scrollToCoordsRange); scroll_rect_into_view is the
immediate, thresholded scrollIntoView(cm, rect) helper. Checked against a
CM5 recording (cm5-scroll-api.json), including scrollTo and scrollIntoView
inside one operation.
NamedListeners (one copy-on-write list per event name) and cm_core::Emitter
port on/off/getHandlers/signal/hasHandler for string-named and custom
events on any object; the editor, documents, line handles and markers get
a named table beside their typed lists. Editor::signal_dom_event and
on_dom_event port signalDOMEvent; key_down, key_press, mouse_down, paste
and maybeScrollWindow (scrollCursorIntoView) signal before handling, and a
handler that calls prevent_default or sets codemirror_ignore pre-empts
the editor.
… reset (Refs #50)

The editor keeps the blink: restart_blink on focus (also when already
focused), after an operation that changed the selection and after a
handled key; cursor_blink_visible / next_blink_in follow the
cursorBlinkRate option (> 0 blinks, 0 shows, < 0 hides). Blurring stops
the blink and schedules onBlur's 150 ms display.shift reset, run by the
host through run_timers / next_timer_in. The native window draws and
wakes from these instead of its fixed 530 ms timer.
…t hooks, autofocus, phrase (Refs #41)

set_option/get_option map CM5 option names onto EditorOptions, run each
option's handler in an operation (mode, indentUnit, tabSize, lineWrapping,
the gutter options, resetModeState options, undoDepth, viewportMargin) and
fire optionChange. define_option adds custom options with handlers run on
init (CodeMirror.Init) unless notOnInit; the constructor ends with
finishInit, the defineInitHook hooks and autofocus's 20 ms onFocus timer.
line_number_for applies lineNumberFormatter; phrase reads the phrases
option. Stacked on feat/focus-blink (run_timers).
swap_doc detaches the old document, attaches the new one, keeps each
document's scroll position, loads doc.modeOption, resets the highlight
state, line heights and longest line, scrolls to the new document's
position and fires swapDoc delayed. refresh() is the methodOp of
methods.js:411 with the immediate refresh event; set_metrics runs it.
on_resize applies re-measured metrics and setSize. Doc gains
set_mode_option, scroll_pos and set_scroll_pos; the editor writes
doc.modeOption when the mode is set.
into_coord_system honors include_widgets as CM5 does: without it the box
moves below the widgets above the line (widgetTopHeight), before the
"line" early return; master's into_coords path is the include_widgets =
false case. Exports keep both sides' items. New test
into_coord_system_include_widgets.
Keep both listener sets (gutter/line-widget events and named events).
… uses lineNumberFor

Keep both sides' options fields, listeners and README sections. The
native renderer, cm-web's frame and the line-number width now format
numbers through line_number_for (lineNumberFor: lineNumberFormatter(i +
firstLineNumber), without subtracting doc.first, as update_line.js:114
and line_numbers.js:34 do). Render number buffers are keyed by text.
New test line_number_formatter_sizes_gutter.
Keep both listener sets. Use master's reg_change_all(first, size). swap_doc
also recomputes has_widgets for the new document and carries addModeClass
into the fresh highlight state. New test swap_doc_line_widget_heights.
@github-actions

Copy link
Copy Markdown

MiniMax-M3.1-Flash QA

Findings

[High] Repeated blur calls postpone the shift reset indefinitely

File: crates/cm-view/src/editor.rs

set_focused(false) currently schedules the 150 ms timeout even when the editor was already blurred:

if focused != self.focused {
    // focus/blur events
}

if focused {
    self.restart_blink();
} else {
    self.blink_start = None;
    self.blur_shift_at = Some(cm_core::clock::now() + 150.0);
}

Consequently, repeatedly calling set_focused(false) before the timeout keeps replacing blur_shift_at, so display.shift can remain stuck indefinitely. CM5 schedules that timeout as part of the blur transition; a repeated blur should not restart it.

Please schedule the blur timeout only when transitioning from focused to blurred, for example:

if focused != self.focused {
    self.focused = focused;
    // Fire focus/blur handlers.

    if !focused {
        self.blur_shift_at = Some(cm_core::clock::now() + 150.0);
    }
}

if focused {
    self.restart_blink();
} else {
    self.blink_start = None;
}

Add a regression test that calls set_focused(false) repeatedly and verifies that display.shift is still reset 150 ms after the first blur.


[Medium] Formatted line-number positioning uses character count rather than rendered width

File: crates/cm-view/src/render.rs

The renderer positions line-number labels using:

let digits = n.chars().count() as f32;

This is incorrect for a user-provided lineNumberFormatter. A formatter can return Unicode text whose rendered width differs from its number of Unicode scalar values—for example, combining characters, emoji, or full-width characters. The label buffer already contains the actual rendered geometry, so positioning should use that geometry rather than chars().count().

This also disagrees with Editor::last_line_number_chars, which correctly uses UTF-16 code-unit count:

self.line_number_for(last).encode_utf16().count()

Please derive the right-aligned position from the rendered buffer width (or use the same canonical text-width helper used by measurement), and add a formatter test containing non-ASCII or combining characters.


[Medium] setOption("mode", ...) cannot represent a mode specification object

File: crates/cm-view/src/options.rs

The editor already supports cm_modes::Spec::Obj, and get_field("mode") converts an object mode to its name string. However, set_option accepts only OptionValue::Null and OptionValue::Str for "mode":

let spec = match &value {
    OptionValue::Null => Spec::Null,
    OptionValue::Str(s) => Spec::Str(s.clone()),
    _ => return Err(OptionError::Type(name.to_string())),
};

This prevents callers from restoring an object-form mode through the generic options API and makes get_option/set_option asymmetric. Either add an object-mode representation to OptionValue and preserve it, or explicitly document and test that object modes are unsupported by set_option. If CM5 compatibility is intended, preserving the full mode specification is preferable.


[Low] The public into_coord_system exposes an internal-only coordinate system without enough context

File: crates/cm-view/src/editor.rs

CoordSys::Doc is introduced as an internal renderer/measurement frame, but it is now part of the public enum and into_coord_system is public. Its relationship to "div" is subtle:

  • "div" is relative to the current rendered range.
  • "doc" is relative to the document and effectively uses view_offset == 0.

Callers can easily combine these systems incorrectly, especially because cursor_coords and char_coords accept the public CoordSys directly. Consider either:

  • keeping Doc internal and exposing separate public/internal methods, or
  • clearly documenting in the enum-level documentation that Doc is a port-specific coordinate system and is not a CM5 coordinate mode.

The current per-variant documentation is useful, but the distinction between public CM5-compatible modes and the internal renderer mode should be more prominent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant