holoviz/panel · #9139
feat(CodeEditor): add line markers and style the read-only tooltip
examples/reference/widgets/CodeEditor.ipynb30 + / 0 −
@@ -24,6 +24,7 @@ " - **themes**\n", " - basic **completion** support via `ctrl+space` (using only static analysis of the code)\n", " - **annotations**\n",+ " - line **markers**\n", " - **readonly** mode\n", "\n", "#### Parameters:\n",@@ -39,6 +40,12 @@ "* **``indent``** (int): Number of spaces to use for default indentation.\n", "* **``keyboard_accessible``** (boolean): Whether Tab moves the focus out of the editor instead of indenting. Escape leaves the text and Tab then moves on; a keyboard user tabbing in reaches the gutter first, then the content, and presses Enter to edit.\n", "* **``language``** (str): A string declaring which language to use for code syntax highlighting (default: 'text')\n",+ "* **``markers``** (list): list of markers highlighting ranges of rows, replaced as a whole when set. Markers stay at the rows they were set on and do not follow edits, so recompute and set them when the text changes. A marker is a dict with the following keys:\n",+ " - `'start_row'`: first row of the marker (zero-based)\n",+ " - `'end_row'`: last row of the marker, inclusive (default: `start_row`)\n",+ " - `'class'`: CSS class of the highlight (default: `'pn-ace-marker'`); `None` marks only the gutter\n",+ " - `'gutter_class'`: CSS class added to the gutter cell of each marked row\n",+ " - `'type'`: `'fullLine'` (default), `'screenLine'` or `'text'`; a text marker spans `'start_column'` to `'end_column'`\n", "* **``on_keyup``** (bool): Whether to update the value on every key press or only upon loss of focus / hotkeys.\n", "* **``print_margin``** (boolean): Whether to show a print margin in the editor\n", "* **``soft_tabs``** (boolean): Whether to use spaces instead of tabs for indentation.\n",@@ -165,6 +172,29 @@ "]" ] },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "Markers highlight ranges of rows, for example lines that just changed. The default `pn-ace-marker` class gives a subtle background; custom classes are styled through `stylesheets` (a full-line marker needs `position: absolute`), and a `gutter_class` decorates the gutter cells of the marked rows:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "editor.stylesheets = [\"\"\"\n",+ ".changed { position: absolute; background: rgba(46, 125, 50, 0.16); }\n",+ ".ace_gutter-cell.changed-row { box-shadow: inset 3px 0 0 #2e7d32; }\n",+ "\"\"\"]\n",+ "editor.markers = [\n",+ " dict(start_row=0),\n",+ " {'start_row': 2, 'end_row': 3, 'class': 'changed', 'gutter_class': 'changed-row'},\n",+ "]"+ ]+ }, { "cell_type": "markdown", "metadata": {},panel/models/ace.py2 + / 0 −
@@ -62,6 +62,8 @@ def __js_skip__(cls): language = String(default='') + markers = List(Dict(String, Any), default=[])+ on_keyup = Bool(default=True) print_margin = Bool(default=False)panel/models/ace.ts75 + / 5 −
@@ -1,5 +1,6 @@ import type * as p from "@bokehjs/core/properties" import {div} from "@bokehjs/core/dom"+import type {StyleSheetLike} from "@bokehjs/core/dom" import {HTMLBox, HTMLBoxView} from "./layout" import type {Ace} from "ace-code"@@ -8,6 +9,18 @@ declare const ace: typeof AceCode import {ID} from "./util" +import ace_css from "styles/models/ace.css"++type Marker = {+ start_row: number+ end_row?: number+ start_column?: number+ end_column?: number+ class?: string | null+ gutter_class?: string | null+ type?: "fullLine" | "screenLine" | "text"+}+ declare type ModeList = { getModeForPath(path: string): {mode: string} }@@ -19,24 +32,29 @@ export class AcePlotView extends HTMLBoxView { protected _langTools: unknown protected _modelist: ModeList protected _container: HTMLDivElement+ protected _marker_ids: number[] = []+ protected _gutter_marks: [number, string][] = [] override connect_signals(): void { super.connect_signals() - const {code, theme, language, filename, print_margin, annotations, soft_tabs, indent, readonly, keyboard_accessible, soft_wrap} = this.model.properties+ const {code, theme, language, filename, print_margin, annotations, markers, soft_tabs, indent, readonly, keyboard_accessible, soft_wrap} = this.model.properties this.on_change(code, () => this._update_code_from_model()) this.on_change(theme, () => this._update_theme()) this.on_change(language, () => this._update_language()) this.on_change(filename, () => this._update_filename()) this.on_change(print_margin, () => this._update_print_margin()) this.on_change(annotations, () => this._add_annotations())+ this.on_change(markers, () => this._update_markers()) this.on_change(indent, () => this._editor.setOptions({tabSize: this.model.indent})) this.on_change(soft_tabs, () => this._editor.setOptions({useSoftTabs: this.model.soft_tabs})) this.on_change(keyboard_accessible, () => this._editor.setOptions({enableKeyboardAccessibility: this.model.keyboard_accessible})) this.on_change(soft_wrap, () => this._editor.setOptions({wrap: this.model.soft_wrap}))- this.on_change(readonly, () => {- this._editor.setReadOnly(this.model.readonly)- })+ this.on_change(readonly, () => this._update_readonly())+ }++ override stylesheets(): StyleSheetLike[] {+ return [...super.stylesheets(), ace_css] } override render(): void {@@ -68,7 +86,10 @@ export class AcePlotView extends HTMLBoxView { this._update_theme() this._update_filename() this._update_language()- this._editor.setReadOnly(this.model.readonly)+ this._update_readonly()+ this._marker_ids = []+ this._gutter_marks = []+ this._update_markers() this._editor.setShowPrintMargin(this.model.print_margin) const {on_keyup} = this.model this._editor.on("change", () => {@@ -119,6 +140,53 @@ export class AcePlotView extends HTMLBoxView { } } + _update_readonly(): void {+ this._editor.setReadOnly(this.model.readonly)+ // Ace creates the "Editing is disabled" tooltip on document.body, outside+ // the shadow root holding Ace's CSS, unless the editor already has one.+ // It drops the tooltip whenever read-only is turned off, so attach a new+ // one to the shadow root each time it is turned on.+ const editor = this._editor as any+ if (this.model.readonly && editor.hoverTooltip == null) {+ const {HoverTooltip} = (ace as any).require("ace/tooltip")+ editor.hoverTooltip = new HoverTooltip(this.shadow_el)+ }+ }++ _update_markers(): void {+ const session = this._editor.session+ for (const id of this._marker_ids) {+ session.removeMarker(id)+ }+ for (const [row, cls] of this._gutter_marks) {+ session.removeGutterDecoration(row, cls)+ }+ this._marker_ids = []+ this._gutter_marks = []+ const {Range} = (ace as any).require("ace/range")+ for (const marker of this.model.markers as Marker[]) {+ const start = marker.start_row+ if (typeof start !== "number") {+ continue+ }+ const end = marker.end_row ?? start+ const cls = marker.class === undefined ? "pn-ace-marker" : marker.class+ if (cls != null && cls !== "") {+ const type = marker.type ?? "fullLine"+ const range = type === "text"+ ? new Range(start, marker.start_column ?? 0, end, marker.end_column ?? Infinity)+ : new Range(start, 0, end, Infinity)+ this._marker_ids.push(session.addMarker(range, cls, type, false))+ }+ if (marker.gutter_class != null && marker.gutter_class !== "") {+ for (let row = start; row <= end; row++) {+ session.addGutterDecoration(row, marker.gutter_class)+ this._gutter_marks.push([row, marker.gutter_class])+ }+ }+ }+ }+ _update_print_margin(): void { this._editor.setShowPrintMargin(this.model.print_margin) }@@ -179,6 +247,7 @@ export namespace AcePlot { code_input: p.Property<string> on_keyup: p.Property<boolean> language: p.Property<string>+ markers: p.Property<any[]> filename: p.Property<string | null> indent: p.Property<number> keyboard_accessible: p.Property<boolean>@@ -213,6 +282,7 @@ export class AcePlot extends HTMLBox { indent: [ Int, 4 ], keyboard_accessible: [ Bool, false ], language: [ Str, "" ],+ markers: [ List(Any), [] ], on_keyup: [ Bool, true ], print_margin: [ Bool, false ], theme: [ Str, "github_light_default" ],panel/styles/models/ace.lessadded4 + / 0 −
@@ -0,0 +1,4 @@+.ace_marker-layer .pn-ace-marker {+ position: absolute;+ background: rgba(255, 213, 79, 0.3);+}panel/tests/ui/widgets/test_codeeditor.py70 + / 0 −
@@ -399,3 +399,73 @@ def test_code_editor_soft_wrap(page): editor.soft_wrap = False wait_until(lambda: _ace_screen_rows(page) == 1, page)+++def test_code_editor_markers(page):+ code = "a: 1\nb: 2\nc: 3\nd: 4\n"+ editor = CodeEditor(value=code, language="yaml", markers=[+ {"start_row": 0, "end_row": 1, "gutter_class": "pn-test-changed"},+ ], stylesheets=[".pn-test-changed { box-shadow: inset 3px 0 0 rgb(0, 128, 0); }"])+ serve_component(page, editor)++ marker = page.locator(".ace_marker-layer .pn-ace-marker")+ expect(marker).to_have_count(1)+ expect(marker).to_have_css("position", "absolute")+ expect(marker).to_have_css("background-color", "rgba(255, 213, 79, 0.3)")+ gutter = page.locator(".ace_gutter-cell.pn-test-changed")+ expect(gutter).to_have_count(2)+ expect(gutter.first).to_have_css("box-shadow", "rgb(0, 128, 0) 3px 0px 0px 0px inset")++ editor.markers = [+ {"start_row": 2, "class": "pn-test-only", "gutter_class": "pn-test-only-row"},+ {"start_row": 3, "class": None, "gutter_class": "pn-test-changed"},+ ]+ expect(page.locator(".ace_marker-layer .pn-ace-marker")).to_have_count(0)+ expect(page.locator(".ace_marker-layer .pn-test-only")).to_have_count(1)+ expect(page.locator(".ace_gutter-cell.pn-test-only-row")).to_have_text("3")+ expect(page.locator(".ace_gutter-cell.pn-test-changed")).to_have_text("4")++ editor.markers = []+ expect(page.locator(".ace_marker-layer .pn-test-only")).to_have_count(0)+ expect(page.locator(".ace_gutter-cell.pn-test-only-row")).to_have_count(0)+ expect(page.locator(".ace_gutter-cell.pn-test-changed")).to_have_count(0)+++def test_code_editor_text_marker(page):+ editor = CodeEditor(value="hello world", markers=[+ {"start_row": 0, "start_column": 6, "end_column": 11, "type": "text", "class": "pn-test-word"},+ ], stylesheets=[".pn-test-word { position: absolute; background: red; }"])+ serve_component(page, editor)++ marker = page.locator(".ace_marker-layer .pn-test-word")+ expect(marker).to_have_count(1)+ line = page.locator(".ace_line").first.bounding_box()+ box = marker.bounding_box()+ assert box["width"] < line["width"] / 2+++def _assert_readonly_tooltip(page):+ page.locator(".ace_content").click()+ page.keyboard.type("x")+ tooltip = page.locator(".ace_tooltip", has_text="Editing is disabled")+ expect(tooltip).to_be_visible()+ expect(tooltip).to_have_text("Editing is disabled")+ expect(tooltip).to_have_css("position", "fixed")+ expect(tooltip).not_to_have_css("background-color", "rgba(0, 0, 0, 0)")+ expect(tooltip).to_have_css("z-index", "999999")+ assert tooltip.evaluate("el => el.getRootNode() !== document")+++def test_code_editor_readonly_tooltip_styled(page):+ editor = CodeEditor(value="print('Hello')", readonly=True)+ serve_component(page, editor)++ _assert_readonly_tooltip(page)+ assert editor.value == "print('Hello')"++ editor.readonly = False+ expect(page.locator(".ace_tooltip", has_text="Editing is disabled")).to_have_count(0)++ editor.readonly = True+ page.mouse.click(0, 0)+ _assert_readonly_tooltip(page)panel/tests/widgets/test_codeeditor.py37 + / 0 −
@@ -1,5 +1,7 @@ from unittest.mock import patch +import pytest+ from panel import config from panel.widgets import CodeEditor @@ -48,3 +50,38 @@ def test_code_editor_theme(): with patch('panel.config._config.theme', new_callable=lambda: "dark"): assert CodeEditor(value="My theme is appropriate", theme="chrome").theme == "chrome"+++def test_ace_markers(document, comm):+ markers = [{"start_row": 0, "end_row": 1, "gutter_class": "changed"}]+ editor = CodeEditor(value="a\nb\nc", markers=markers)+ model = editor.get_root(document, comm=comm)+ assert model.markers == markers++ editor.markers = [{"start_row": 2, "class": "only"}]+ assert model.markers == [{"start_row": 2, "class": "only"}]++ editor.markers = []+ assert model.markers == []+++@pytest.mark.parametrize("marker", [+ {"end_row": 1},+ {"start_row": "1"},+ {"start_row": -1},+ {"start_row": True},+ {"start_row": 0, "end_row": False},+ {"start_row": 2, "end_row": 1},+ {"start_row": 0, "type": "block"},+])+def test_ace_markers_invalid(marker):+ with pytest.raises(ValueError):+ CodeEditor(markers=[marker])+++def test_ace_markers_invalid_not_stored():+ markers = [{"start_row": 1}]+ editor = CodeEditor(markers=markers)+ with pytest.raises(ValueError):+ editor.markers = [{"start_row": -1}]+ assert editor.markers == markerspanel/widgets/codeeditor.py42 + / 0 −
@@ -14,6 +14,35 @@ from ..util import lazy_load from .base import Widget +_MARKER_TYPES = ('fullLine', 'screenLine', 'text')+++def _is_row(value: t.Any) -> bool:+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0+++class _Markers(param.List):+ """A list of CodeEditor markers, validated before it is stored."""++ def _validate(self, val):+ super()._validate(val)+ for marker in val or []:+ start = marker.get('start_row')+ if not _is_row(start):+ raise ValueError(+ f"CodeEditor markers require a non-negative integer 'start_row', got {marker!r}."+ )+ end = marker.get('end_row', start)+ if not _is_row(end) or end < start:+ raise ValueError(+ f"CodeEditor marker 'end_row' must be an integer >= 'start_row', got {marker!r}."+ )+ if marker.get('type', 'fullLine') not in _MARKER_TYPES:+ raise ValueError(+ f"CodeEditor marker 'type' must be one of {_MARKER_TYPES}, got {marker!r}."+ )++ if t.TYPE_CHECKING: from collections.abc import Mapping @@ -47,6 +76,19 @@ class CodeEditor(Widget): The editor is entered with Enter and left with Escape, so a keyboard user is not trapped in it.""") + markers: list[dict[str, t.Any]] = _Markers(default=[], item_type=dict, doc="""+ List of markers highlighting ranges of rows. Each marker is a dict+ with a zero-based ``start_row``, an optional inclusive ``end_row``+ (defaults to ``start_row``), an optional CSS ``class`` for the+ highlight (defaults to ``pn-ace-marker``, set it to ``None`` to only+ mark the gutter), an optional ``gutter_class`` added to the gutter+ cell of every marked row, and an optional ``type``: ``'fullLine'``+ (default), ``'screenLine'`` or ``'text'``, where a text marker spans+ ``start_column`` to ``end_column``. Setting the parameter replaces+ all previous markers. Markers stay at the rows they were set on and+ do not follow edits, so recompute and set them when the text+ changes.""") # type: ignore[assignment, ty:invalid-assignment]+ on_keyup = param.Boolean(default=True, doc=""" Whether to update the value on every key press or only upon loss of focus / hotkeys.""")