Repository navigation
rewrite data viewer frontend with vanilla JS - #17382
Merged
Merged
Conversation
Replace the jQuery/DataTables-based grid viewer with a custom vanilla JS implementation. Adds a column summary sidebar with sparkline histograms, virtual scrolling, sticky headers, pinnable columns, and auto-sized column widths. Removes ~180KB of vendored jQuery/DataTables/Scroller dependencies. No backend or GWT protocol changes required. - New DataViewer.js: virtual scroll engine, cell rendering, filter UI, column resize, sort, sidebar, pin columns, full window.* API compat - New DataViewer.css: CSS custom properties from ThemeColorExtractor for automatic light/dark theme support - Rewritten gridviewer.html with sidebar + grid panel layout - Deleted dtviewer.js, dtstyles.css, datatables/ directory - Fix latchable toolbar button border shift in themeStyles.css
- Fix fetch loop skipping block boundaries when render window straddles two FETCH_SIZE blocks — iterate block-aligned boundaries instead - Fix height mismatch from skipped uncached rows — bottom spacer now absorbs the deficit so total height stays correct - Fix spacer row picking up alternating row stripe background by boosting CSS specificity of spacer-row rules - Move pin icon to left of column label to avoid sort indicator conflict - Account for pin icon width in auto-size column measurement
… border - Sort indicators use mask-image for dark theme support - Row names data cells get "first-child" class for GridViewerStyles theming - Remove extra left border on pinned first column - Pin icon moved to left of column label - Pin icon uses Material Symbols "keep" icon with mask-image theming - Account for pin icon width in auto-size column measurement - Latchable toolbar buttons use transparent border (themeStyles.css)
Hide native scrollbars and render custom scrollbar divs that start below the sticky header (vertical) and after the pinned columns (horizontal). Supports thumb drag, track click-and-drag, auto-hide after inactivity, hover-to-show, and theme-aware colors via CSS custom properties.
The new vanilla JS rendering pipeline handles wide datasets efficiently without jQuery/DataTables overhead, so the conservative 50-column default can be safely increased.
Contributor
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
- Skip renderVisibleRows when render window unchanged (early exit) - Use textContent fast path for plain cells, avoiding innerHTML parsing - Batch all layout reads before writes in updateCustomScrollbars - Coalesce scrollbar updates to one per frame via requestAnimationFrame - Cache layout values at drag start in scrollbar thumb handler - Suppress updateInfoBar during scrollbar drag, use cached scrollTop - Return totalWidth from getPinnedOffsets to avoid redundant reads - Add CSS contain: layout style on scrollbar elements
Instead of destroying and rebuilding all ~26,000 DOM elements on every scroll tick, only add/remove rows at the edges of the render window. Persistent spacer <tr> elements are created once and their heights updated in place. A Map tracks rendered row elements for O(1) lookup. Force rebuilds (sort, filter, pin, fetch) still do full teardown. Typical vertical scrolling now touches ~5% of rows per frame.
Bump BUFFER_ROWS from 50 to 200 and FETCH_SIZE from 200 to 500. With incremental row recycling, the larger buffer is cheap to maintain and lets users scroll several pages before new rows need rendering.
- Exclude row names column from hover highlight and alternating stripes - Increase hover highlight contrast for dark themes via color-mix - Add horizontal overscroll so last columns can sit next to pinned ones
…labels - Add "Columns" toggle button to the GWT toolbar next to "Filter" - Add hover tooltips on histogram bars showing range + count + percentage - Add NA count to column metadata (col_na_count from backend) - Display NA percentage in sidebar footer for each column - Use class() instead of typeof() for col_type_r so factors show as <fct>/<ord> instead of <int> - Add total_rows to rownames metadata for NA percentage calculation - Flash-highlight column header when clicking a sidebar entry
- Add .rs.summarizeColumn R function with type-specific stats (numeric: min/max/mean/median/sd, character: lengths, factor: all levels with counts in levels() order, logical: TRUE/FALSE, date: min/max) - Add show=column_summary endpoint in DataViewer.cpp - Lazy-fetch stats on expand — no computation until user clicks - Inline expand/collapse toggle (▸/▾) in sidebar column header - Factor levels preserve defined ordering instead of sorting by frequency - Show "Unique" count for numeric and character but not factor columns
- Rename "Columns" to "Summary" toolbar button with Material Symbols area_chart icon - Move Summary button to the left of Filter - Show sidebar by default on open (start latched) - Re-run autoSizeColumns on first tab activate if initial sizing happened while hidden (fixes undersized columns after page reload) - Fix missing table variable reference in autoSizeColumns
- Replace GWT ToolbarButton with custom HTML widget using inline SVG bar chart icon for reliable alignment - Remove latching behavior — plain toggle button - Rename sidebar title from "Columns" to "Summary" - Show spinner in sidebar header during stats fetch with 200ms grace period and 1s fade-in to avoid flashing on fast loads - Fix missing table variable in autoSizeColumns - Re-run auto-sizing on first tab activate if initial sizing was hidden
Subtle repeating diagonal stripes on the padding rows give a visual cue that data is pending/loading, rather than showing blank space.
- preserve filter UI when toggling pinned columns by reordering existing <th> elements rather than recreating them in rebuildHeaders - tighten autoSizeColumns chrome constants to match actual CSS, drop the viewport-fill distribution, and use data-col-idx so widths stay correct after pinning - lock the cursor and disable pointer-events on grid descendants during a column resize so hover behavior on the pin icon does not interrupt the drag
Row names styling:
- drop bold weight on row name data cells (header still bold via th rule)
- add 4px horizontal padding so the values aren't flush to the cell edge
Bugs:
- scrollToColumn now uses getHeaderCell so sidebar clicks still land on the
right column when columns are pinned
- didResize is set only when the cursor actually moves during a drag and
reset via setTimeout(0) after mouseup, so a single click after resizing
no longer gets eaten before sort can fire
- guard the rownames JSON.parse in renderCellContents
- drop dead code in buildRow (rowData[0] ternary, no-op clazz override)
- log a console.warn when fetchColumnSummary fails instead of silent catch
- rewire drawCounter as a staleness token bumped on invalidateCache, so
responses for a request that started before an invalidate are discarded
- remove the document mouseleave listener that ended a column resize when
the cursor crossed the iframe boundary
Performance:
- cache getPinnedOffsets and invalidate it explicitly on autoSize, manual
resize, pin toggle, and grid destroy; previously each scroll tick paid
N offsetWidth reads
- build the force-rebuild row batch into a DocumentFragment
- RAF-throttle onScroll so virtual scroll renders happen during the scroll
- measure text widths via a 2d canvas instead of a hidden DOM element
- only emit the overscroll paddingRight when content exceeds the viewport,
and recompute on iframe resize via the existing window resize handler
Maintainability:
- consolidate transient state reset into resetGridState
- share a small gridDataFetch helper across fetchRows/Columns/ColumnSummary
- have renderCellContents write directly into the td instead of returning
a {text} xor {html} record
- gather the assorted ms timings into a single TIMING object
Per-object UI state (pinned columns, sidebar visibility, manual column widths, sort, and column filter values) is now saved to localStorage keyed by env+obj and restored on bootstrap. State is loaded before headers are built and before the first row fetch, so pinning order, sort indicators, and filter params show up in the initial render. A pre-existing bug surfaced by this work: autoSizeColumns ignored manualWidths, so a manual resize was silently overwritten on the next pin toggle or refresh. autoSizeColumns now uses manualWidths[colIdx] when present. Also: the sidebar's border-right was leaving a 1px gap when the panel was collapsed; moved the border to the .expanded rule so it's only drawn while the panel is open.
Two issues kept the localStorage persistence from taking effect: - stateKey required a non-empty env, but RStudio's data viewer URL passes env= (empty) for objects from the global env. Save and load were both skipped. Now keyed on obj only, with a "_" sentinel for empty env. - initSidebar conditionally added the "expanded" class but never removed it, so on in-page bootstraps a previous expanded panel persisted even when saved state said the sidebar should be collapsed. Use classList.toggle so the panel reflects sidebarVisible authoritatively. Also: drop the 200ms debounce on saveState. localStorage.setItem is synchronous and inexpensive, and the debounce window meant a quick toggle-then-refresh could lose the save before it landed.
Wires an onDismiss path from DataEditingTarget through the widget chain into the iframe's window.onDismiss, which removes the localStorage entry for the current object. Only fires when dismissType == DISMISS_TYPE_CLOSE so moving the tab between source columns preserves state.
Bugs / correctness: - endResize unconditionally clears body.col-resizing so a teardown that cleared resizingColIdx first can't leave global pointer-events: none active; resetGridState also clears the class defensively - mousemove falls back to evt.buttons === 0 detection plus a window blur fallback so a mouseup-outside-iframe scenario can't leave a drag stuck - applySavedState now allows pinned column index 0 (matters when rowNumbers is false) - saveState only fires at end of drag (in endResize), not on every mousemove, fixing a localStorage write storm on the resize hot path - state keys are encoded with encodeURIComponent so colons or empty env values can't collide - rebuildHeaders removes any leftover headers whose columns are no longer in the visible column set - autoSizeColumns returns early when the viewport has no layout instead of applying widths measured against a 0-height viewport - scroll/resize/scrollend listeners and the scrollbar-update RAF id are now stored at module scope so destroyGrid removes them across bootstrap cycles - updateCustomScrollbars is called after the sidebar transition completes - scrollbar track sizes are clamped to >= 0 so an oversized header or pinned region can't produce negative geometry - setHeaderUIVisible(false) removes only injected UI nodes (marked with a class) rather than blindly removing th.lastChild, which was at risk of removing the permanent .resizer - the renderVisibleRows force-rebuild path stops at the first cache miss so cached rows downstream of a gap can't render at the wrong vertical position when fetch blocks resolve out of order - restored the .largeCell class on long-text cells so they ellipsis-clip rather than wrap - spacer-row hover styling outranks the odd-row hover stripe - fetchColumnSummary invokes its callback with an error sentinel on failure so the sidebar can render an error state instead of staying on a "Loading..." spinner - sidebar-summary spinner uses a refcount so concurrent expansions don't hide the spinner while other fetches are still in flight - factor summaries cap at 50 levels so a high-cardinality factor doesn't bloat the response and DOM UI / theming: - summary toolbar SVG icon uses currentColor so it adapts to the theme - the i18n label text is set via DOM API instead of HTML concatenation - consolidated repeated color-mix expressions into --grid-row-hover-bg / --grid-row-stripe-bg / --grid-row-active-bg Other: - histogram-bin tooltip is built with DOM nodes rather than innerHTML - parseInt(bin, 10) instead of an unspecified radix - updated SessionHelp.R comment that still referenced the old 50-column default
- fetchColumnSummary now invokes the callback with null on AbortError so the caller can balance any pending-fetch bookkeeping (the sidebar spinner refcount was leaking when a fetch was aborted, leaving the spinner stuck visible) - the sidebar expand callback decrements pendingSummaryFetches before checking data, and treats data === null as "aborted; allow retry" (loaded stays false) - remove the hardcoded color:#888 from the summary toolbar SVG so fill='currentColor' actually inherits the toolbar's text color and adapts to the active theme
New boolean user pref (default true) that controls whether the data viewer's Summary side panel is open when an object is first opened. The value is threaded through the gridviewer.html URL as show_summary= and parsed in DataViewer.js. Saved per-object state (in localStorage) still wins, so a user who toggles the panel off for a specific object keeps that override regardless of the pref. Generated via scripts/generate-prefs.R: adds the pref to the schema and regenerates the C++ / R / GWT accessors and the en i18n keys.
The client-side autoSizeColumns previously sampled at most 100 of the
first 500 cached rows to estimate column widths, which gave bad widths
for columns whose content widens beyond the sample (notably the row-
names column on large data frames — its widest value is at the bottom).
The server now sends a per-column col_max_chars hint when it can be
computed cheaply without formatting the whole column:
- integer / integer-valued numeric : max(nchar) of range()
- character : max(nchar)
- factor : max(nchar) of levels()
- logical : 5 ("FALSE")
- Date / POSIXt : 10 / 19 (fixed format width)
- rownames : nchar of max rowname
For column types whose accurate display width would require expensive
format() calls (real-valued doubles, integer64, complex, list cells),
the field is omitted and the client falls back to its existing row
sampling.
To bound the per-column work for very wide tables we only emit the
hint when ncol(x) <= 200; above that the client samples as before.
The client measures a representative reference string at module load
to derive an avgCharWidth, then translates the hint into pixels via
avgCharWidth × N + chrome. Sampling still runs alongside (as an
upper-bound update) so cell content with unusually wide glyphs can
still grow the column.
The previous code called rownames(x) and then is.numeric(rn) to detect default rownames — but rownames() always returns a character vector, so the cheap branch was unreachable and we always paid for the full materialization plus an O(n) nchar scan. On large data frames that's a real regression for what should be metadata-only work. Now read attr(x, "row.names") directly and detect the compact form c(NA_integer_, -n) used for automatic rownames in O(1). Explicit integer rownames are bounded via range(); explicit character rownames fall back to a cheap nchar scan.
This comment was marked as resolved.
This comment was marked as resolved.
gtritchie
requested changes
May 4, 2026
gtritchie
left a comment
Member
There was a problem hiding this comment.
Assorted feedback to ponder and cherish while putting on your belt and suspenders.
Address review feedback on PR #17382: gridDataFetch normalizes non-JSON error bodies, column-summary expand handler retries on error, setOffsetAndMaxColumns clamps maxDisplayColumns even when newMax<=0, saved state carries a column-name fingerprint and is dropped on mismatch, .rs.summarizeColumn wraps each statistic in tryCatch, localStorage write failures emit a one-shot warning, plus comment polish and consolidation of module-scoped vars at the top of DataViewer.js. Bug fixes: filter UI duplication after applying a filter and toggling (distinct marker classes per injected UI, idempotent show path, and classList add/remove instead of `className=` so the marker isn't clobbered); custom scrollbars refresh after pin toggle; numeric filter header now shows the active range "[15, 30]" or value "[15]" instead of placeholder "[...]". Sidebar trial: sidebar moved to the right side with a slightly stronger border. Summary button converted to LatchingToolbarButton with the inline bar-chart SVG (currentColor for theme adaptation); latched state mirrors sidebar visibility via a JS->Java callback. Right-side toolbar layout: [search] | [summary] | [refresh] [options].
Collaborator
Author
Cell selection + keyboard navigation in the iframe: click a cell or focus the viewport (now tabindex=0) to begin; arrows / Home / End / PageUp / PageDown move the active cell, Ctrl-Home and Ctrl-End jump to top-left and bottom-right, Ctrl/Cmd-C copies the rendered cell text via navigator.clipboard.writeText (with execCommand fallback). The selection clears on sort, filter, search, pin toggle, and column pagination -- anything that changes row or column identity. Sparkline tooltip clipping fix: anchor below the bar (top: 100%) and drop overflow:hidden from .sidebar-col so both the "Range" and "Count" lines render fully instead of the top line being clipped by the parent's overflow. Whole-number numeric columns whose distinct integer range is <= 12 now bin one-per-value, so a 1-5 Likert column shows five distinct bars rather than Sturges' default smearing; gaps in the range render as zero-height bars. JS coerces breaks (sent as strings to preserve double precision) to Number before arithmetic, surfaces single-integer bins in the tooltip as "Value: N" instead of "Range: 0.5 to 1.5", and formats integer bin edges (including 0) without a trailing decimal. Summary toolbar icon: swap the first and last bar heights so the silhouette reads low / high / medium.
Reformat the data viewer rewrite entry into three single-line bullets linking to #17539: the user-visible feature additions (pinnable columns, Summary sidebar, keyboard nav, clipboard copy), the new data_viewer_show_summary preference, and the raised data_viewer_max_columns default. Drops the "rewrote frontend" framing and the jQuery DataTables note as internal-only.
No current call site emits user data into a single-quoted attribute,
but adding ' to the escape map covers the future copy-paste case where
someone writes attr='${escapeHtml(x)}'. One-line defensive change with
no impact on existing output (current sites all flow into HTML element
content or double-quoted attributes).

Intent
Addresses #17539.
Summary
Test plan
View(mtcars)-- verify row names display, sort, filter, column resize, sticky headerView(iris)-- verify factor column filters, sidebar sparklinesView(ggplot2::diamonds)-- verify virtual scrolling with 53,940 rowsView(as.data.frame(matrix(rnorm(100000), nrow=100, ncol=1000)))-- verify wide dataset with column pagination