Skip to content

Add secure flag to cookies when SSL is enabled - #888

Merged
jjallaire merged 2 commits into
masterfrom
feature/secure-cookies
Nov 10, 2016
Merged

jjallaire merged 2 commits into
masterfrom
feature/secure-cookies

Conversation

@jmcphers

@jmcphers jmcphers commented Nov 9, 2016

Copy link
Copy Markdown
Member

This change adds the Secure flag to cookies when SSL is enabled. This flag simply tells the browser to never transmit the cookie over vanilla HTTP, following the OWASP guidance.

));
false, // can't be HTTP only since it's read by client script
// secure if delivered via SSL
options().getOverlayOption("ssl-enabled") == "1"));

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.

There is a call to get overlay options as Boolean which would be more convenient here

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.

I'm wrong about this. It's actually the session that has an accessor not server:

bool Options::getBoolOverlayOption(const std::string& name)
{
std::string optionValue = getOverlayOption(name);
return boost::algorithm::trim_copy(optionValue) == "1";
}
. I'll go ahead and merge this.

@jjallaire
jjallaire merged commit 1fe0711 into master Nov 10, 2016
@valerie-rstudio
valerie-rstudio deleted the feature/secure-cookies branch January 21, 2022 17:45
kevinushey added a commit that referenced this pull request May 1, 2026
- 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
kevinushey added a commit that referenced this pull request May 5, 2026
* rewrite data viewer frontend with vanilla JS

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 virtual scroll spacer visibility and other polish

- 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

* polish: sort icon theming, row names styling, pin icon, filter button 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)

* add custom scrollbars with proper positioning

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.

* bump default data viewer max columns from 50 to 200

The new vanilla JS rendering pipeline handles wide datasets efficiently
without jQuery/DataTables overhead, so the conservative 50-column
default can be safely increased.

* optimize scroll performance: eliminate layout thrashing

- 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

* implement incremental row recycling in renderVisibleRows

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.

* increase virtual scroll buffer to ~8 pages

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.

* polish: row hover styling, horizontal overscroll, dark theme contrast

- 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

* enhance sidebar: toolbar toggle, histogram tooltips, NA counts, type 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 expandable column summary stats in sidebar

- 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 sidebar to Summary, add area_chart icon, show by default

- 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

* polish summary button, spinner, and sidebar title

- 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

* add diagonal zebra stripes to virtual scroll spacer rows

Subtle repeating diagonal stripes on the padding rows give a visual
cue that data is pending/loading, rather than showing blank space.

* fix data viewer column UI interactions

- 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

* clean up data viewer code and behavior

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

* persist data viewer ui state to localStorage

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.

* make data viewer state save reliably

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.

* clear data viewer saved state when the tab is closed

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.

* address open data viewer code review findings

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

* fix sidebar spinner refcount on aborted summary fetches

- 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

* add data_viewer_show_summary preference

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.

* add server-side col_max_chars hint for column auto-sizing

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.

* fix data viewer rowname width hint to avoid materializing rownames

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.

* use .row_names_info() to detect automatic data viewer rownames

Cleaner than inspecting the attr(x, "row.names") shape ourselves —
.row_names_info(x, 1L) returns a signed row count (negative for the
compact auto form, positive for explicit rownames), so the auto-
rowname path is now a one-liner that doesn't touch the rownames
vector at all. Explicit rownames still take the same range()/nchar
path as before.

* clamp data viewer 'showing X to Y' range to fully visible rows

The status bar previously used Math.floor for the first row and
Math.ceil for the row count, so partially-visible rows at top or
bottom were counted, leading to an off-by-one for the end row when
the last visible row was only partially in the viewport. Switch to
ceil for first and floor for last (against scrollTop+viewportH) so
only rows that are entirely within the viewport are reported.

If the viewport is shorter than a row, fall back to showing the
single in-view row rather than an empty range.

* use 50% visibility threshold for data viewer 'showing X to Y' range

Replace strict ceil/floor with round on both boundary positions so a
row counts as in view once at least half of it is visible. A row
that's mostly scrolled away (less than half visible) is excluded; a
row that's mostly visible still counts.

* fix data viewer 'showing X to Y' edge cases

Two issues with the recent 50% threshold change:

- A row that's exactly 50% visible at the top was excluded, because
  Math.round in JS rounds half away from zero. Use
  ceil((scrollTop + H/2) / H) instead, which is round-half-down and
  keeps the equality case in range. The bottom edge is fine — its
  half-up rounding correctly includes the equality case.

- At max scroll on a viewport shorter than a row, first could exceed
  activeRows and produce an out-of-bounds range like "11 to 11 of 10".
  Clamp first to [1, activeRows] before clamping last.

* account for sticky thead and hscrollbar in 'showing X to Y'

The viewport's clientHeight is not the same as the area where data rows
are actually visible: the sticky <thead> overlays the top of the
viewport, and when horizontal scroll is active the custom horizontal
scrollbar overlays the bottom 10px. The previous math used the full
clientHeight, so the last-row computation could include a row that was
actually obscured under the thead or hscrollbar — visible as an off-by-
one at the end of the displayed range.

(Note: the info bar isn't part of this — it's a flex sibling of the
viewport, not an absolute overlay, so clientHeight already excludes it.)

Compute an effective body-visible height (clientHeight - headerH -
hscrollbar) and use that in the round-based bottom-edge calculation.
The top-edge formula is unchanged since the sticky header doesn't
shift the relationship between scrollTop and the topmost visible row.

* add NEWS entry for data viewer rewrite

* add gear menu to data viewer toolbar

The new gear button sits next to the Summary toggle in the toolbar
and opens a popup of data viewer options. Initially it has one item:
a CheckableMenuItem bound to the data_viewer_show_summary user pref
("Show Summary panel by default"). Toggling persists the pref via
writeUserPrefs so the new default applies on the next View() call.

This is also a place to hang any future per-user data viewer options
without growing the toolbar with one button per setting.

Icon is an inline gear SVG (Material Symbols "settings" path) using
fill='currentColor' so it adapts to the active theme.

* move data viewer gear menu to the right of the search widget

Previous placement put it next to the Summary toggle on the left, which
got crowded. Move it to the right, after the search widget, with a
separator between them. The right panel adds widgets left-to-right so
the order is [search] | [gear], matching where the user expects an
"options" affordance to live in a toolbar.

* follow refresh + dropdown convention for data viewer toolbar

Replace the standalone gear icon with the same pattern other panes use
(Environment, Files, Plots): a Refresh button followed by a NoText
ToolbarMenuButton whose dropdown arrow opens a popup of related
options. The data_viewer_show_summary toggle moves into that menu;
clicking the refresh button calls the iframe's refreshData().

* use the standard refresh icon for the data viewer toolbar

Drop the inline SVG and use a regular ToolbarButton with the same
refresh artwork the other panes use (copied from the refreshEnvironment
command icon, bundled into DataViewerResources alongside FilterIcon /
SummaryIcon). Also pick up the .refreshToolbarButton theme style for
consistent sizing/treatment with EnvironmentPane, FilesPane, etc.

* add floating custom scrollbar to data viewer Summary sidebar

Factored the existing grid scrollbar code into a generic
attachCustomScrollbar(viewport, host, axis, options) helper, then used
it for the sidebar in addition to the grid:

- Each instance owns its own DOM, drag/track-click handlers, and
  activity-based fade timer (separate, per the sidebar UX request).
- options.getInsets() gives a callback for grid-specific offsets
  (sticky header height for the vertical bar, pinned column width
  for the horizontal bar). The sidebar bar uses it to start below
  the Summary toggle.
- options.onDragEnd lets the grid re-render its info bar on drag
  release.
- Module-scope scrollbarDragging variable replaced by an
  anyScrollbarDragging() helper that consults all live bars.

Sidebar wiring: attachSidebarScrollbar() runs after initSidebar
populates the content list; the scrollbar refreshes on stats-panel
expand/collapse (content height changes) and is destroyed in
destroyGrid alongside the grid scrollbars. Native scrollbar on
#sidebarContent is hidden via scrollbar-width:none and the webkit
shadow-pseudo. #sidebarPanel gets position:relative so the absolute
bar anchors inside it.

* fix data viewer info-bar zero-rows + gear menu pref scope

Three review-fix items:

- updateInfoBar now handles activeRows === 0 (filter matched nothing
  while totalRows > 0): use a 0/0 range instead of clamping to 1/1, and
  always include the "(filtered from N total)" suffix when filteredRows
  is below totalRows. The previous clamping produced an invalid
  "Showing 1 to 1 of 0 entries".

- The "Show Summary panel by default" gear menu item now reads via
  getGlobalValue() to match the setGlobalValue() write path, so when a
  project layer overrides the pref the UI reflects (and mutates) the
  same user-layer value rather than reading the merged value and
  writing the user one.

- The options menu refreshes the show-summary item's checked state in
  getDynamicPopupMenu so a pref change made elsewhere (global Options,
  another open viewer) is visible the next time the menu is opened,
  not stuck on whatever state was current the last time the user
  toggled it locally.

* fix sidebar scroll listener leak and grid bar info-bar overrun

Two follow-up fixes from the floating-scrollbar refactor:

- attachSidebarScrollbar now tracks the scroll listener it adds and
  removes the previous one before re-attaching; destroyCustomScrollbars
  removes it too. The listener also no-ops when sidebarScrollbar_ has
  been nulled, so it can't throw if it fires after teardown.

- The grid vertical scrollbar's bottom inset now includes the
  rsGridData_info bar's height. The new attachCustomScrollbar sizes
  bars from host.offsetHeight, but the grid's host (#gridPanel)
  contains both the scrollable viewport and the 25px info bar below
  it; without this the vertical bar extended over the info bar area.

* fix non-ASCII em-dashes in SessionDataViewer.R comments

Two em-dashes snuck into the rownames-info comments while I was
explaining the .row_names_info path. Replaced with -- per the
project's ASCII-only rule for R sources, restoring test-linter.R.

* address data viewer review feedback

- guard renderCellContents against null/undefined cell values by coercing
  data to a string before search/highlight code paths
- replace the javascript: viewer-link href with a real click handler so
  rowData[0] is never concatenated into an executable URL
- tighten escapeHtml: handle null/undefined explicitly, coerce non-strings
  via String(), drop the !html shortcut and the space->nbsp substitution
- show the parsed row name in the tooltip instead of the JSON-encoded form
- accept scientific notation (1e10, -2.5e-7) in the numeric filter input
- reset lastScrollTop/Left in resetGridState so onActivate can't restore
  a stale position after refresh
- drop the dead dismissOnClick parameter from invokeFilterPopup and
  document the light-dismiss semantics
- log swallowed exceptions in DataTable.onDismiss instead of silently
  discarding them
- strip non-ASCII characters (em-dashes) from JS/CSS/Java comments and
  the user-facing formatStatValue placeholder
- clean up two duplicate NEWS entries and note the data_viewer_max_columns
  default bump (50 -> 200)

* update data-viewer BRAT test for new link href

The viewer-link href changed from `javascript:window.listViewerCallback(...)`
to `#` (with a click handler) as part of the review-feedback fix that
removed the user-data-into-javascript-URL concatenation. Drop the
implementation-specific href assertion; the subsequent click + tab-title
check is what verifies the user-facing behavior.

* disable overscroll bounce on data viewer scrollers

The grid viewport and the Summary sidebar both have known, finite scroll
extents, so the rubber-band/bounce effect doesn't add useful affordance --
the scroll-end is already obvious. Suppressing it also prevents scroll
chaining out of the iframe into the IDE chrome.

Applies to both #gridViewport (table) and #sidebarContent (Summary panel).

* address remaining data viewer review items

- Hoist scroll/scrollbar/scrollend/resize listeners to module scope so
  addEventListener stays idempotent if two bootstrap() calls overlap;
  drops the bookkeeping vars that previously only tracked the most
  recent anonymous handler. Same treatment for the sidebar scroll
  listener.
- Bail out of the renderVisibleRows incremental path when buildRow
  returns null mid-window. The previous "silently skip and adjust the
  spacer" fix-up left rows at incorrect vertical offsets during fast
  scroll with slow fetches; now the function clears the spacers and
  re-enters via the full-rebuild branch, which uses the existing
  contiguous-prefix rule.
- Add a soft size cap (ROW_CACHE_LIMIT = 20000, target = 15000) on
  rowCache with distance-based eviction. Keeps memory bounded for users
  scrolling end-to-end through very large datasets.
- localStorage hygiene: removeItem on version mismatch and JSON parse
  errors instead of leaving stale entries indefinitely.
- Rename the renderVisibleRows force parameter to forceRebuild and add
  a function-header comment explaining the two execution paths.
- Drop dead variables: n_valid and col_class in summarizeColumn,
  and the parsed-but-unused current variable in createFactorFilterUI.
- summarizeColumn factor branch now sorts levels by count descending
  before truncation, so top_levels actually contains the most frequent
  levels rather than the alphabetically-first ones.

* preserve R level order in factor column summary

Sorting by count descending makes truncation more useful for high-
cardinality factors but loses the encoded level order, which matters
for ordered factors and any deliberate ordering. Revert to the level
order that R provides; document the level cap behavior in the comment.

* document the factor-truncation trade-off in summarizeColumn

Spell out why we keep R's level order (preserves ordered-factor and
explicit level-order semantics) and the consequence for high-cardinality
factors (truncation drops the alphabetically-late levels rather than
the least frequent), with options for future revisiting.

* surface silent failures in data viewer + add summarizeColumn tests

- DataViewer.cpp: when the .rs.summarizeColumn R call returns a non-
  throwing Error, log it and respond with {error: ...} instead of an
  empty body. Without this the sidebar spinner stops on a blank panel
  with no user-visible indication of what went wrong.
- fetchRows: the catch's "Ignore non-JSON errors" branch was swallowing
  network failures, 500s with HTML bodies, and CORS rejections, leaving
  the table frozen on Loading. Mirror fetchColumns and surface every
  non-abort failure via showError.
- renderColumnStats: when the response carries no type-specific fields
  (unsupported column type, all-NA column), show a fallback message
  instead of an empty container. Add a small CSS class for it.
- Add R unit tests for .rs.summarizeColumn covering each branch
  (numeric, character, factor, logical, Date, POSIXct, unsupported),
  out-of-range indices, all-NA columns, zero-row data frames, factor
  level-order preservation, and >50-level truncation.

* BRAT tests

* add rstudioapi

* data viewer: review feedback and sidebar UX trial

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].

* data viewer: keyboard nav, copy, integer histograms, tooltip fix

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.

* news: split data viewer entry into linked bullets

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.

* data viewer: also escape single quotes in escapeHtml

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).

* data viewer: format escapeHtml replacements one per line

* data viewer: address review feedback on accessibility and bugs

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.

* data viewer: anchor list-cell viewer icon to its cell

.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.

* data viewer: nudge list-cell viewer icon 2px off the right edge

* data viewer: fix escapeHtml tests to match the actual render path

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.
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.

2 participants