Skip to content

rewrite data viewer frontend with vanilla JS - #17382

Merged
kevinushey merged 61 commits into
mainfrom
feature/data-viewer-rewrite
May 5, 2026
Merged

kevinushey merged 61 commits into
mainfrom
feature/data-viewer-rewrite

Conversation

@kevinushey

@kevinushey kevinushey commented Apr 9, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Addresses #17539.

Summary

  • Replace jQuery + DataTables + Scroller plugin with a custom vanilla JS grid implementation (~2600 lines replacing ~19600 lines of vendored code)
  • Add column summary sidebar with sparkline histograms for numeric columns
  • Add virtual scrolling with row caching and async prefetch
  • Add sticky column headers and pinnable columns with reordering
  • Add custom scrollbars positioned below the header and after pinned columns
  • Add auto-sized column widths based on content measurement
  • Bump default max display columns from 50 to 200
  • Sort indicators and pin icons use mask-image for automatic dark theme support
  • Fix latchable toolbar button border shift in themeStyles.css
  • No backend or GWT protocol changes -- preserves full window.* API contract

Test plan

  • View(mtcars) -- verify row names display, sort, filter, column resize, sticky header
  • View(iris) -- verify factor column filters, sidebar sparklines
  • View(ggplot2::diamonds) -- verify virtual scrolling with 53,940 rows
  • View(as.data.frame(matrix(rnorm(100000), nrow=100, ncol=1000))) -- verify wide dataset with column pagination
  • Pin a column -- verify it moves to the left and sticks during horizontal scroll
  • Toggle sidebar -- verify column summaries with histograms
  • Switch between light and dark themes -- verify all elements theme correctly
  • Test filter UI: numeric range (histogram brush), factor dropdown, text search, boolean
  • Test data import preview (Import Dataset dialog)
  • Test nested viewer links -- click a data.frame or list cell
  • Verify custom scrollbars appear/hide correctly, drag and track-click work

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.
@kevinushey kevinushey added this to the Globemaster Allium milestone Apr 9, 2026
@posit-snyk-bot

posit-snyk-bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 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.
@gtritchie

This comment was marked as resolved.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assorted feedback to ponder and cherish while putting on your belt and suspenders.

kevinushey added 2 commits May 4, 2026 14:12
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].
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Current state. I've moved the Summary widget to the right; the UI felt cluttered having it on the left.

Screenshot 2026-05-04 at 3 50 24 PM

kevinushey added 5 commits May 4, 2026 16:28
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).
@gtritchie

Copy link
Copy Markdown
Member

Review summary (pass 2 — accessibility focus)

Five parallel review passes (accessibility, code quality, tests, error handling, comments). Critical findings spot-verified against the source.

Critical (recommend addressing before merge)

# Finding Location
C1 Accessibility regression vs. the prior DataTables viewer. DataViewer.js (3466 lines) has zero aria-* attributes, zero role= assignments, and one tabindex. Sortable headers not keyboard-operable; pin/sidebar/filter UI mouse-only; drill-in icon has no alt text; virtual-scroll size not exposed via aria-rowcount. Detail below. DataViewer.js, DataViewer.css, gridviewer.html
C2 Embedded NUL byte in columnFingerprint separator — names.join("\x00") instead of names.join(" "). Verified via od -c. Almost certainly a typo; violates the project ASCII-only policy and serializes � into localStorage. DataViewer.js:3005
C3 Unchecked r::json::jsonValueFromObject return — same silent-failure pattern that the surface silent failures commit fixed, repeated one branch lower in the same try block. Returns success with stale result on encoding failure. DataViewer.cpp:978
C4 col_type_r wire change breaks Data Import default-type detection. typeof(val) -> class(val)[[1]] means Date columns now report "Date" (was "double"); the consumer's switch() has no "Date" / "POSIXct" arm and falls through to "text". The PR's own comment flags it as wire-visible. SessionDataViewer.R:296 consumed by SessionDataImportV2.R:211-222
C5 escapeHtml has no test coverage despite two recent commits adjusting it (escape ', formatting). The exact regression those commits fixed could silently come back. DataViewer.js:246-261

Accessibility detail

The grid is essentially non-accessible today. Specific blocking gaps:

  • Headers: no role="columnheader", no aria-sort, no keyboard activation (<th> has click-only handler, no Enter/Space; th:focus { outline: none } removes the only feedback). DataViewer.js:683-738, DataViewer.css:134.
  • Pin/unpin: <span class="pin-icon"> with opacity:0 until hover, no tabindex, no role, no key handler, no accessible name beyond title. DataViewer.js:632-643.
  • Filter popup: not a role="dialog", no focus trap, never moves focus in or restores on close. Histogram brush is mouse-only with no slider/numeric-input alternative. DataViewer.js:1138-1436, hist.js.
  • Sidebar: toggle, expand button, column entries are bare <div>s — no buttons, no aria-expanded, no headings/landmarks. SR users can't find the column summary at all. DataViewer.js:2060-2223.
  • Drill-in viewer link: <img> with no alt. DataViewer.js:558-571.
  • Errors not announced: #errorWrapper has no role="alert" / aria-live. DataViewer.js:271-277.
  • Virtual scroll size invisible to AT: missing aria-rowcount means SRs report ~100 rows for a 100k-row dataset.
  • No aria-activedescendant as keyboard nav moves between cells — cell-focus indicator is visual-only.

Bright spot: viewport tabindex="0" plus arrow / Home / End / PageUp / PgDn / Ctrl-Home / Ctrl-End / Ctrl-C is genuinely good for sighted keyboard users — but invisible to assistive tech.

Important

  • updateSpacerHeight is a tombstone no-op kept "so call sites compile." Project rule: Replace, don't deprecate — delete it and its three call sites (DataViewer.js:1545-1547, calls at 444, 2836, 2907).
  • applyTransform (every filter type, every search) has no test — the string-based "type|value" and range "a_b" parsers are the riskiest server-side surface (SessionDataViewer.R:750-879).
  • Virtual scrolling never exercised in tests — mtcars has 32 rows, virtualization needs >200; eviction LRU and prefetch chunking ship untested.
  • Column-summary RPC error path untested — the explicit reason for the surface-silent-failures commit could regress unnoticed (DataViewer.cpp:957-980).
  • JSNI iframe-method guards in DataTable.java (if (frame && frame.foo) frame.foo()) silently no-op when the iframe fails to load. Three new entry points (toggleSidebar, onDismiss, setSidebarStateCallback) compound the issue — consider a Debug.logException in the else branch (DataTable.java:467-501).
  • #rsGridData_info ("Showing 1 to 30 of 1,234") has no aria-live — filter count change is invisible to AT (DataViewer.js:1549-1615).
  • Custom scrollbars hide native scrollbar; thumb at opacity 0.25/0.5 of --grid-fg over near-same-color background almost certainly fails 3:1 (DataViewer.css:937-996).
  • Animations don't respect prefers-reduced-motion (column-flash 1s, sidebar spin, fade transitions).
  • Three new functions exceed the project's 100-line cap: renderVisibleRows (~146), initGrid (~125), initSidebar (~163).
  • View() end-to-end has no BRAT test for empty / single-row / all-NA / 200+-column frames (unit tests cover summarizeColumn only).
  • Active-cell focus cleared on sort/filter/pin without re-establishment — keyboard users get silently dumped to the top of the table mid-task.

Minor

  • SummaryIcon.png (and _2x) is shipped but the JSNI replaces the rendered <img> with inline SVG — drop one or the other.
  • DataViewer.js:994 empty catch (e) {} lacks the /* leave as-is */ comment its three siblings have.
  • copyActiveCell returns true after a failed execCommand("copy"), mis-signalling success.
  • Single-line "what" comments at DataViewer.js:81-105 mostly restate the variable name.
  • 10px sidebar expand button and 11px clear-filter icon are below WCAG 2.5.8 (24x24) target size.
  • <th> missing scope="col".
  • Resize handle is mouse-only — acceptable, but worth a follow-up.
  • Selection / search-match highlight are color-only signals.

Strengths

  • Comment quality is unusually high — comments explain why, not what; no non-ASCII; no dead TODOs.
  • The surface silent failures commit does the right thing: fetchRows.catch -> showError, sidebar errors render explicit messages, gridDataFetch normalizes 502/HTML bodies.
  • escapeHtml is comprehensive (< > & " '); no XSS sites found at innerHTML callsites.
  • Schema/prefs/i18n consistency for the new data_viewer_show_summary pref is correct across all six wiring locations; French translations present for every new English string.
  • Listener cleanup is correct (sidebar scroll fix, custom scrollbars, AbortController on summary fetches with proper ref-count).
  • drawCounter staleness check correctly discards races past AbortController.
  • Row-cache hysteresis (ROW_CACHE_LIMIT/TARGET) bounds memory.
  • summarizeColumn is well-tested, including the factor-truncation trade-off with non-alphabetical levels.
  • window.* public API contract is preserved; GWT host backward-compat intact.
  • NEWS.md and Allman/3-space C++ style match conventions.

Recommended action plan

  1. Address the accessibility critical (C1). At minimum: grid roles + aria-rowcount, sortable-header keyboard + aria-sort, sidebar/pin/filter trigger keyboard + roles, drill-in icon alt, role="alert" on errors. The rest can ship as a tracked follow-up but a public release shouldn't regress AT users.
  2. Fix the NUL byte (C2) — one-character change.
  3. Fix the jsonValueFromObject return check (C3) — mirror the pattern just above it.
  4. Fix the Data Import switch arms (C4) — add "Date", "POSIXct", "POSIXlt" cases to SessionDataImportV2.R:211-222, or revert the class(val)[[1]] change.
  5. Add tests for escapeHtml (C5) and applyTransform; one BRAT test on a 50k-row frame to actually exercise virtualization.
  6. Sweep Important items in the same pass; defer Minor to a follow-up.

The rewrite is high-quality in most respects — comment quality, listener hygiene, schema/i18n consistency, and security-sensitive rendering are all good. The a11y regression and the four small-but-real bugs are what gate merge.

kevinushey added 4 commits May 5, 2026 10:05
Critical:
- Replace NUL byte in columnFingerprint separator with a space.
- Surface failed jsonValueFromObject conversions instead of returning
  success with a stale result.
- Add Date/POSIXct/POSIXlt arms to the Data Import column-type switch
  so the col_type_r wire change keeps mapping date columns to date.
- Cover escapeHtml via two BRAT tests on the rendered DOM.

Accessibility (minimum scope):
- role=grid + aria-rowcount on the table; role=row/aria-rowindex on
  rows; role=gridcell on cells; scope=col on headers.
- Sortable headers are tab-reachable, activate on Enter/Space, set
  aria-sort, and gain a :focus-visible outline.
- Pin icon becomes a button with aria-pressed, aria-label and
  keyboard activation.
- Sidebar toggle, expand buttons and column-entry headers expose
  role/aria-expanded and keyboard activation.
- Drill-in icon gets alt=\"\" with the link carrying the accessible
  name; error wrapper gets role=alert; info bar gets aria-live.
- prefers-reduced-motion clamps animations and transitions.

Other:
- Remove updateSpacerHeight no-op and its three call sites.
- Log via Debug.log when a JSNI iframe method is expected but
  missing, instead of silently no-opping.
- Empty catch blocks now carry intent comments; copyActiveCell
  returns the actual execCommand result.
- Drop SummaryIcon PNG; the inline SVG (theme-aware, DPR-sharp)
  is the only icon path.
.viewerLink is absolutely positioned at right:0; for that to land on
the cell edge it needs a positioned ancestor. .largeCell provides
position: relative for long string values, but short list cells (e.g.
"a") have neither .largeCell nor any other positioned ancestor, so the
icon escaped to a distant ancestor and showed up in the wrong spot.
renderCellContents and createHeader set cell/header text via
td.textContent and span.textContent, so the browser's text encoding
handles XSS safety; entity encoding only kicks in for <, >, and &
(quotes are valid as plain text content). The previous tests asserted
that " and ' came back as &quot; and &#39; through innerHTML, which
they don't on this code path.

Reframe both tests around the observable security property: no
user-supplied content escapes into the DOM as a real element, and
textContent round-trips the original string. Keep the &lt;/&gt;/&amp;
checks so a regression that bypasses textContent would still trip the
test.
@kevinushey
kevinushey merged commit 32e66b2 into main May 5, 2026
8 checks passed
@kevinushey
kevinushey deleted the feature/data-viewer-rewrite branch May 5, 2026 20:16
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.

4 participants