| 1 |
"""HTML representation for PyVista objects in Jupyter notebooks. |
| 2 |
|
| 3 |
Uses pure HTML/CSS with checkbox-driven expand/collapse. The only |
| 4 |
JavaScript is a minimal ``navigator.clipboard.writeText`` call for |
| 5 |
copy-to-clipboard buttons. |
| 6 |
Works in Jupyter Notebook, JupyterLab, VS Code, Colab, and nbviewer. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
from functools import lru_cache |
| 12 |
from html import escape |
| 13 |
from importlib.resources import files as _resources_files |
| 14 |
from typing import TYPE_CHECKING |
| 15 |
import uuid |
| 16 |
|
| 17 |
if TYPE_CHECKING: |
| 18 |
from collections.abc import Sequence |
| 19 |
|
| 20 |
|
| 21 |
@lru_cache(None) |
| 22 |
def _load_css() -> str: |
| 23 |
"""Load the CSS stylesheet (cached).""" |
| 24 |
return ( |
| 25 |
_resources_files('pyvista.core.static').joinpath('style.css').read_text(encoding='utf-8') |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
@lru_cache(None) |
| 30 |
def _load_pyvista_logo() -> str: |
| 31 |
"""Load the PyVista brand mark SVG (cached).""" |
| 32 |
return ( |
| 33 |
_resources_files('pyvista.core.static') |
| 34 |
.joinpath('pyvista_logo.svg') |
| 35 |
.read_text(encoding='utf-8') |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
_MESH_TYPE_ICONS: dict[str, str] = { |
| 40 |
'PolyData': 'polydata.svg', |
| 41 |
'UnstructuredGrid': 'unstructured.svg', |
| 42 |
'ImageData': 'imagedata.svg', |
| 43 |
'RectilinearGrid': 'rectilinear.svg', |
| 44 |
'StructuredGrid': 'structured.svg', |
| 45 |
'MultiBlock': 'multiblock.svg', |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
@lru_cache(None) |
| 50 |
def _load_mesh_icon(mesh_type: str) -> str | None: |
| 51 |
"""Load a mesh-type SVG icon, or ``None`` if unavailable.""" |
| 52 |
filename = _MESH_TYPE_ICONS.get(mesh_type) |
| 53 |
if filename is None: |
| 54 |
return None |
| 55 |
icon_dir = _resources_files('pyvista.core.static').joinpath('mesh_icons') |
| 56 |
return icon_dir.joinpath(filename).read_text(encoding='utf-8') |
| 57 |
|
| 58 |
|
| 59 |
def collapsible_section( |
| 60 |
header: str, |
| 61 |
*, |
| 62 |
inline_details: str = '', |
| 63 |
details: str = '', |
| 64 |
n_items: int | None = None, |
| 65 |
enabled: bool = True, |
| 66 |
collapsed: bool = False, |
| 67 |
) -> str: |
| 68 |
"""Build an expand/collapse section using a hidden checkbox. |
| 69 |
|
| 70 |
Parameters |
| 71 |
---------- |
| 72 |
header : str |
| 73 |
Section label (e.g. ``'Point Data:'``). |
| 74 |
inline_details : str |
| 75 |
Content shown when collapsed. |
| 76 |
details : str |
| 77 |
Content shown when expanded. |
| 78 |
n_items : int, optional |
| 79 |
Item count displayed in parentheses. A value of ``0`` |
| 80 |
disables the section. |
| 81 |
enabled : bool |
| 82 |
Whether the section is expandable. |
| 83 |
collapsed : bool |
| 84 |
Whether the section starts collapsed. |
| 85 |
|
| 86 |
Returns |
| 87 |
------- |
| 88 |
str |
| 89 |
HTML fragment for the section. |
| 90 |
|
| 91 |
""" |
| 92 |
data_id = 'section-' + str(uuid.uuid4()) |
| 93 |
|
| 94 |
has_items = n_items is not None and n_items > 0 |
| 95 |
n_items_span = '' if n_items is None else f' <span>({n_items})</span>' |
| 96 |
enabled_attr = '' if enabled and has_items else ' disabled' |
| 97 |
collapsed_attr = '' if collapsed or not has_items else ' checked' |
| 98 |
tip = " title='Expand/collapse section'" if enabled_attr == '' else '' |
| 99 |
|
| 100 |
html = ( |
| 101 |
f"<input id='{data_id}' class='pv-section-summary-in'" |
| 102 |
f" type='checkbox'{enabled_attr}{collapsed_attr} />" |
| 103 |
f"<label for='{data_id}' class='pv-section-summary'{tip}>" |
| 104 |
f'{header}{n_items_span}</label>' |
| 105 |
f"<div class='pv-section-inline-details'>{inline_details}</div>" |
| 106 |
) |
| 107 |
if details: |
| 108 |
html += f"<div class='pv-section-details'>{details}</div>" |
| 109 |
return html |
| 110 |
|
| 111 |
|
| 112 |
def _badge(label: str, css_class: str) -> str: |
| 113 |
"""Return a small colored badge ``<span>``.""" |
| 114 |
return f" <span class='pv-badge {css_class}'>{escape(label)}</span>" |
| 115 |
|
| 116 |
|
| 117 |
def _copy_btn(text: str) -> str: |
| 118 |
"""Return a small copy-to-clipboard button. |
| 119 |
|
| 120 |
Uses a ``data-copy`` attribute to hold the text and reads it via |
| 121 |
``this.dataset.copy`` in the ``onclick`` handler. This avoids |
| 122 |
XSS risks from inline string interpolation: HTML entities in the |
| 123 |
attribute value are decoded safely by the browser before reaching |
| 124 |
the JavaScript API. |
| 125 |
""" |
| 126 |
return ( |
| 127 |
f"<button class='pv-copy-btn' title='Copy to clipboard'" |
| 128 |
f" data-copy='{escape(text)}'" |
| 129 |
f''' onclick="navigator.clipboard.writeText(this.dataset.copy)"''' |
| 130 |
f'>\u29c9</button>' |
| 131 |
) |
| 132 |
|
| 133 |
|
| 134 |
def _summarize_array( |
| 135 |
name: str, |
| 136 |
ncomp: int, |
| 137 |
dtype: str, |
| 138 |
*, |
| 139 |
badges: str = '', |
| 140 |
is_active: bool = False, |
| 141 |
shape: str = '', |
| 142 |
range_str: str = '', |
| 143 |
) -> str: |
| 144 |
"""Format a single data-array row for the grid layout.""" |
| 145 |
safe_name = escape(name) |
| 146 |
dims_str = escape(shape) if shape else f'{ncomp} comp' if ncomp > 1 else 'scalar' |
| 147 |
active_cls = ' pv-var-name-active' if is_active else '' |
| 148 |
copy = _copy_btn(name) |
| 149 |
|
| 150 |
return ( |
| 151 |
f"<div class='pv-var-name{active_cls}'><span>{safe_name}</span>{copy}</div>" |
| 152 |
f"<div class='pv-var-dims'>{dims_str}</div>" |
| 153 |
f"<div class='pv-var-dtype'>{escape(dtype)}</div>" |
| 154 |
f"<div class='pv-var-range'>{escape(range_str)}</div>" |
| 155 |
f"<div class='pv-var-badges'>{badges}</div>" |
| 156 |
) |
| 157 |
|
| 158 |
|
| 159 |
def _array_badges( |
| 160 |
name: str, |
| 161 |
*, |
| 162 |
active_scalars: str | None = None, |
| 163 |
active_vectors: str | None = None, |
| 164 |
active_normals: str | None = None, |
| 165 |
active_tcoords: str | None = None, |
| 166 |
) -> str: |
| 167 |
"""Return concatenated badge HTML for an array.""" |
| 168 |
badges = '' |
| 169 |
if name == active_scalars: |
| 170 |
badges += _badge('active', 'pv-badge-active') |
| 171 |
if name == active_vectors: |
| 172 |
badges += _badge('vectors', 'pv-badge-vectors') |
| 173 |
if name == active_normals: |
| 174 |
badges += _badge('normals', 'pv-badge-normals') |
| 175 |
if name == active_tcoords: |
| 176 |
badges += _badge('tcoords', 'pv-badge-tcoords') |
| 177 |
return badges |
| 178 |
|
| 179 |
|
| 180 |
def _data_array_section( |
| 181 |
title: str, |
| 182 |
arrays: list[tuple[str, int, str, str, str]], |
| 183 |
*, |
| 184 |
active_scalars: str | None = None, |
| 185 |
active_vectors: str | None = None, |
| 186 |
active_normals: str | None = None, |
| 187 |
active_tcoords: str | None = None, |
| 188 |
collapsed: bool = False, |
| 189 |
) -> str: |
| 190 |
"""Build a collapsible section for a set of data arrays. |
| 191 |
|
| 192 |
Parameters |
| 193 |
---------- |
| 194 |
title : str |
| 195 |
Section title (e.g. ``'Point Data'``). |
| 196 |
arrays : list[tuple[str, int, str, str, str]] |
| 197 |
Each tuple is ``(name, n_components, dtype_str, shape_str, |
| 198 |
range_str)``. When ``shape_str`` is non-empty it is shown |
| 199 |
instead of the default ``'scalar'`` / ``'N comp'`` label. |
| 200 |
``range_str`` is displayed as the data range (e.g. |
| 201 |
``'[-0.5, 0.5]'``). |
| 202 |
active_scalars : str, optional |
| 203 |
Name of the active scalars array. |
| 204 |
active_vectors : str, optional |
| 205 |
Name of the active vectors array. |
| 206 |
active_normals : str, optional |
| 207 |
Name of the active normals array. |
| 208 |
active_tcoords : str, optional |
| 209 |
Name of the active texture coordinates array. |
| 210 |
collapsed : bool |
| 211 |
Whether the section starts collapsed. |
| 212 |
|
| 213 |
Returns |
| 214 |
------- |
| 215 |
str |
| 216 |
HTML fragment for the section. |
| 217 |
|
| 218 |
""" |
| 219 |
li_parts: list[str] = [] |
| 220 |
for name, ncomp, dtype, shape_str, range_str in arrays: |
| 221 |
badges = _array_badges( |
| 222 |
name, |
| 223 |
active_scalars=active_scalars, |
| 224 |
active_vectors=active_vectors, |
| 225 |
active_normals=active_normals, |
| 226 |
active_tcoords=active_tcoords, |
| 227 |
) |
| 228 |
row = _summarize_array( |
| 229 |
name, |
| 230 |
ncomp, |
| 231 |
dtype, |
| 232 |
badges=badges, |
| 233 |
is_active=(name == active_scalars), |
| 234 |
shape=shape_str, |
| 235 |
range_str=range_str, |
| 236 |
) |
| 237 |
li_parts.append(f"<li class='pv-var-item'>{row}</li>") |
| 238 |
|
| 239 |
items_li = ''.join(li_parts) |
| 240 |
details = f"<ul class='pv-var-list'>{items_li}</ul>" |
| 241 |
|
| 242 |
# Show active scalar name inline when collapsed |
| 243 |
inline = '' |
| 244 |
if active_scalars and any(name == active_scalars for name, _, _, _, _ in arrays): |
| 245 |
inline = f'{escape(active_scalars)}{_badge("active", "pv-badge-active")}' |
| 246 |
|
| 247 |
return collapsible_section( |
| 248 |
f'{title}:', |
| 249 |
inline_details=inline, |
| 250 |
details=details, |
| 251 |
n_items=len(arrays), |
| 252 |
collapsed=collapsed, |
| 253 |
) |
| 254 |
|
| 255 |
|
| 256 |
def _metadata_html( |
| 257 |
rows: list[tuple[str, list[tuple[str, str]], str]], |
| 258 |
) -> str: |
| 259 |
"""Build always-visible metadata rows. |
| 260 |
|
| 261 |
Parameters |
| 262 |
---------- |
| 263 |
rows : list[tuple[str, list[tuple[str, str]], str]] |
| 264 |
Each entry is ``(row_label, [(key, value), ...], copy_text)``. |
| 265 |
If ``copy_text`` is non-empty, a clipboard button is shown. |
| 266 |
|
| 267 |
Returns |
| 268 |
------- |
| 269 |
str |
| 270 |
HTML ``<div>`` fragment. |
| 271 |
|
| 272 |
""" |
| 273 |
row_parts: list[str] = [] |
| 274 |
for label, items, copy_text in rows: |
| 275 |
entries = ''.join( |
| 276 |
f"<span class='pv-meta-entry'>" |
| 277 |
f"<span class='pv-meta-label'>{escape(k)}</span> {escape(v)}" |
| 278 |
f'</span>' |
| 279 |
for k, v in items |
| 280 |
) |
| 281 |
copy_html = _copy_btn(copy_text) if copy_text else '' |
| 282 |
row_parts.append( |
| 283 |
f"<div class='pv-meta-row pv-copyable'>" |
| 284 |
f"<span class='pv-meta-row-label'>{escape(label)}</span>" |
| 285 |
f'{copy_html}{entries}' |
| 286 |
f'</div>' |
| 287 |
) |
| 288 |
return f"<div class='pv-metadata'>{''.join(row_parts)}</div>" |
| 289 |
|
| 290 |
|
| 291 |
def _fmt_memory(kib: int) -> str: |
| 292 |
"""Format kibibytes into a human-readable string.""" |
| 293 |
if kib < 1024: |
| 294 |
return f'{kib} KiB' |
| 295 |
mib = kib / 1024 |
| 296 |
if mib < 1024: |
| 297 |
return f'{mib:.1f} MiB' |
| 298 |
gib = mib / 1024 |
| 299 |
return f'{gib:.2f} GiB' |
| 300 |
|
| 301 |
|
| 302 |
def _children_section( |
| 303 |
title: str, |
| 304 |
children: list[tuple[str, str, str]], |
| 305 |
) -> str: |
| 306 |
"""Build a collapsible section listing child blocks/partitions. |
| 307 |
|
| 308 |
Parameters |
| 309 |
---------- |
| 310 |
title : str |
| 311 |
Section title (e.g. ``'Blocks'``). |
| 312 |
children : list[tuple[str, str, str]] |
| 313 |
Each tuple is ``(name, type_name, detail_str)``. |
| 314 |
|
| 315 |
Returns |
| 316 |
------- |
| 317 |
str |
| 318 |
HTML fragment for the section. |
| 319 |
|
| 320 |
""" |
| 321 |
items_li = ''.join( |
| 322 |
f"<li><span class='pv-child-name'>{escape(name)}</span>" |
| 323 |
f"<span class='pv-child-type'>{escape(ctype)}</span>" |
| 324 |
f"<span class='pv-child-detail'>{escape(detail)}</span></li>" |
| 325 |
for name, ctype, detail in children |
| 326 |
) |
| 327 |
details = f"<ul class='pv-children-list'>{items_li}</ul>" |
| 328 |
return collapsible_section( |
| 329 |
f'{title}:', |
| 330 |
details=details, |
| 331 |
n_items=len(children), |
| 332 |
collapsed=False, |
| 333 |
) |
| 334 |
|
| 335 |
|
| 336 |
def _sections_html(sections: list[str]) -> str: |
| 337 |
"""Wrap sections into a ``<ul>`` CSS grid.""" |
| 338 |
items = ''.join(f"<li class='pv-section-item'>{s}</li>" for s in sections) |
| 339 |
return f"<ul class='pv-sections'>{items}</ul>" |
| 340 |
|
| 341 |
|
| 342 |
def build_repr_html( |
| 343 |
obj_type: str, |
| 344 |
mesh_type: str, |
| 345 |
*, |
| 346 |
header_badges: Sequence[str] = (), |
| 347 |
metadata: Sequence[tuple[str, list[tuple[str, str]], str]] = (), |
| 348 |
sections: Sequence[str] = (), |
| 349 |
text_repr: str = '', |
| 350 |
) -> str: |
| 351 |
"""Assemble a complete HTML repr with header, metadata, sections, and fallback. |
| 352 |
|
| 353 |
Parameters |
| 354 |
---------- |
| 355 |
obj_type : str |
| 356 |
Display name (e.g. ``'PolyData'``). |
| 357 |
mesh_type : str |
| 358 |
Key for mesh icon lookup (e.g. ``'PolyData'``). |
| 359 |
header_badges : Sequence[str] |
| 360 |
Labels shown as small badges in the header (e.g. memory size). |
| 361 |
metadata : Sequence[tuple[str, list[tuple[str, str]], str]] |
| 362 |
Always-visible key-value rows rendered between the header and |
| 363 |
collapsible sections. Each entry is |
| 364 |
``(row_label, [(key, val), ...], copy_text)``. |
| 365 |
sections : Sequence[str] |
| 366 |
List of collapsible-section HTML fragments. |
| 367 |
text_repr : str |
| 368 |
Plain-text fallback for non-HTML environments. |
| 369 |
|
| 370 |
Returns |
| 371 |
------- |
| 372 |
str |
| 373 |
Complete HTML string. |
| 374 |
|
| 375 |
""" |
| 376 |
css = _load_css() |
| 377 |
|
| 378 |
# Mesh icon |
| 379 |
icon_svg = _load_mesh_icon(mesh_type) or _load_mesh_icon('ImageData') or '' |
| 380 |
icon_html = f"<span class='pv-logo'>{icon_svg}</span>" |
| 381 |
|
| 382 |
# PyVista brand logo (top-right) |
| 383 |
pv_logo = _load_pyvista_logo() |
| 384 |
pv_logo_html = f"<span class='pv-brand-logo'>{pv_logo}</span>" |
| 385 |
|
| 386 |
# Header badges |
| 387 |
badges_html = ''.join( |
| 388 |
f" <span class='pv-header-badge'>{escape(b)}</span>" for b in header_badges |
| 389 |
) |
| 390 |
|
| 391 |
header = ( |
| 392 |
"<div class='pv-header'>" |
| 393 |
f'{icon_html}' |
| 394 |
"<div class='pv-header-text'>" |
| 395 |
f"<div class='pv-obj-type'>{escape(obj_type)}{badges_html}</div>" |
| 396 |
'</div>' |
| 397 |
f'{pv_logo_html}' |
| 398 |
'</div>' |
| 399 |
) |
| 400 |
|
| 401 |
meta_html = _metadata_html(list(metadata)) if metadata else '' |
| 402 |
text_fallback = escape(text_repr) |
| 403 |
|
| 404 |
return ( |
| 405 |
'<div>' |
| 406 |
f'<style>{css}</style>' |
| 407 |
f"<pre class='pv-text-repr-fallback'>{text_fallback}</pre>" |
| 408 |
"<div class='pv-wrap' style='display:none'>" |
| 409 |
f'{header}' |
| 410 |
f'{meta_html}' |
| 411 |
f'{_sections_html(list(sections))}' |
| 412 |
'</div>' |
| 413 |
'</div>' |
| 414 |
) |