"""HTML representation for PyVista objects in Jupyter notebooks. Uses pure HTML/CSS with checkbox-driven expand/collapse. The only JavaScript is a minimal ``navigator.clipboard.writeText`` call for copy-to-clipboard buttons. Works in Jupyter Notebook, JupyterLab, VS Code, Colab, and nbviewer. """ from __future__ import annotations from functools import lru_cache from html import escape from importlib.resources import files as _resources_files from typing import TYPE_CHECKING import uuid if TYPE_CHECKING: from collections.abc import Sequence @lru_cache(None) def _load_css() -> str: """Load the CSS stylesheet (cached).""" return ( _resources_files('pyvista.core.static').joinpath('style.css').read_text(encoding='utf-8') ) @lru_cache(None) def _load_pyvista_logo() -> str: """Load the PyVista brand mark SVG (cached).""" return ( _resources_files('pyvista.core.static') .joinpath('pyvista_logo.svg') .read_text(encoding='utf-8') ) _MESH_TYPE_ICONS: dict[str, str] = { 'PolyData': 'polydata.svg', 'UnstructuredGrid': 'unstructured.svg', 'ImageData': 'imagedata.svg', 'RectilinearGrid': 'rectilinear.svg', 'StructuredGrid': 'structured.svg', 'MultiBlock': 'multiblock.svg', } @lru_cache(None) def _load_mesh_icon(mesh_type: str) -> str | None: """Load a mesh-type SVG icon, or ``None`` if unavailable.""" filename = _MESH_TYPE_ICONS.get(mesh_type) if filename is None: return None icon_dir = _resources_files('pyvista.core.static').joinpath('mesh_icons') return icon_dir.joinpath(filename).read_text(encoding='utf-8') def collapsible_section( header: str, *, inline_details: str = '', details: str = '', n_items: int | None = None, enabled: bool = True, collapsed: bool = False, ) -> str: """Build an expand/collapse section using a hidden checkbox. Parameters ---------- header : str Section label (e.g. ``'Point Data:'``). inline_details : str Content shown when collapsed. details : str Content shown when expanded. n_items : int, optional Item count displayed in parentheses. A value of ``0`` disables the section. enabled : bool Whether the section is expandable. collapsed : bool Whether the section starts collapsed. Returns ------- str HTML fragment for the section. """ data_id = 'section-' + str(uuid.uuid4()) has_items = n_items is not None and n_items > 0 n_items_span = '' if n_items is None else f' ({n_items})' enabled_attr = '' if enabled and has_items else ' disabled' collapsed_attr = '' if collapsed or not has_items else ' checked' tip = " title='Expand/collapse section'" if enabled_attr == '' else '' html = ( f"" f"' f"
{inline_details}
" ) if details: html += f"
{details}
" return html def _badge(label: str, css_class: str) -> str: """Return a small colored badge ````.""" return f" {escape(label)}" def _copy_btn(text: str) -> str: """Return a small copy-to-clipboard button. Uses a ``data-copy`` attribute to hold the text and reads it via ``this.dataset.copy`` in the ``onclick`` handler. This avoids XSS risks from inline string interpolation: HTML entities in the attribute value are decoded safely by the browser before reaching the JavaScript API. """ return ( f"' ) def _summarize_array( name: str, ncomp: int, dtype: str, *, badges: str = '', is_active: bool = False, shape: str = '', range_str: str = '', ) -> str: """Format a single data-array row for the grid layout.""" safe_name = escape(name) dims_str = escape(shape) if shape else f'{ncomp} comp' if ncomp > 1 else 'scalar' active_cls = ' pv-var-name-active' if is_active else '' copy = _copy_btn(name) return ( f"
{safe_name}{copy}
" f"
{dims_str}
" f"
{escape(dtype)}
" f"
{escape(range_str)}
" f"
{badges}
" ) def _array_badges( name: str, *, active_scalars: str | None = None, active_vectors: str | None = None, active_normals: str | None = None, active_tcoords: str | None = None, ) -> str: """Return concatenated badge HTML for an array.""" badges = '' if name == active_scalars: badges += _badge('active', 'pv-badge-active') if name == active_vectors: badges += _badge('vectors', 'pv-badge-vectors') if name == active_normals: badges += _badge('normals', 'pv-badge-normals') if name == active_tcoords: badges += _badge('tcoords', 'pv-badge-tcoords') return badges def _data_array_section( title: str, arrays: list[tuple[str, int, str, str, str]], *, active_scalars: str | None = None, active_vectors: str | None = None, active_normals: str | None = None, active_tcoords: str | None = None, collapsed: bool = False, ) -> str: """Build a collapsible section for a set of data arrays. Parameters ---------- title : str Section title (e.g. ``'Point Data'``). arrays : list[tuple[str, int, str, str, str]] Each tuple is ``(name, n_components, dtype_str, shape_str, range_str)``. When ``shape_str`` is non-empty it is shown instead of the default ``'scalar'`` / ``'N comp'`` label. ``range_str`` is displayed as the data range (e.g. ``'[-0.5, 0.5]'``). active_scalars : str, optional Name of the active scalars array. active_vectors : str, optional Name of the active vectors array. active_normals : str, optional Name of the active normals array. active_tcoords : str, optional Name of the active texture coordinates array. collapsed : bool Whether the section starts collapsed. Returns ------- str HTML fragment for the section. """ li_parts: list[str] = [] for name, ncomp, dtype, shape_str, range_str in arrays: badges = _array_badges( name, active_scalars=active_scalars, active_vectors=active_vectors, active_normals=active_normals, active_tcoords=active_tcoords, ) row = _summarize_array( name, ncomp, dtype, badges=badges, is_active=(name == active_scalars), shape=shape_str, range_str=range_str, ) li_parts.append(f"
  • {row}
  • ") items_li = ''.join(li_parts) details = f"" # Show active scalar name inline when collapsed inline = '' if active_scalars and any(name == active_scalars for name, _, _, _, _ in arrays): inline = f'{escape(active_scalars)}{_badge("active", "pv-badge-active")}' return collapsible_section( f'{title}:', inline_details=inline, details=details, n_items=len(arrays), collapsed=collapsed, ) def _metadata_html( rows: list[tuple[str, list[tuple[str, str]], str]], ) -> str: """Build always-visible metadata rows. Parameters ---------- rows : list[tuple[str, list[tuple[str, str]], str]] Each entry is ``(row_label, [(key, value), ...], copy_text)``. If ``copy_text`` is non-empty, a clipboard button is shown. Returns ------- str HTML ``
    `` fragment. """ row_parts: list[str] = [] for label, items, copy_text in rows: entries = ''.join( f"" f"{escape(k)} {escape(v)}" f'' for k, v in items ) copy_html = _copy_btn(copy_text) if copy_text else '' row_parts.append( f"
    " f"{escape(label)}" f'{copy_html}{entries}' f'
    ' ) return f"" def _fmt_memory(kib: int) -> str: """Format kibibytes into a human-readable string.""" if kib < 1024: return f'{kib} KiB' mib = kib / 1024 if mib < 1024: return f'{mib:.1f} MiB' gib = mib / 1024 return f'{gib:.2f} GiB' def _children_section( title: str, children: list[tuple[str, str, str]], ) -> str: """Build a collapsible section listing child blocks/partitions. Parameters ---------- title : str Section title (e.g. ``'Blocks'``). children : list[tuple[str, str, str]] Each tuple is ``(name, type_name, detail_str)``. Returns ------- str HTML fragment for the section. """ items_li = ''.join( f"
  • {escape(name)}" f"{escape(ctype)}" f"{escape(detail)}
  • " for name, ctype, detail in children ) details = f"" return collapsible_section( f'{title}:', details=details, n_items=len(children), collapsed=False, ) def _sections_html(sections: list[str]) -> str: """Wrap sections into a ``