Allow programmatically setting st.dataframe selections#13594
Allow programmatically setting st.dataframe selections#13594lukasmasuch merged 34 commits intodevelopfrom
st.dataframe selections#13594Conversation
✅ 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. |
✅ PR preview is ready!
|
st.dataframe state
st.dataframe statest.dataframe selections
- Fix Python test `StArrowTableAPITest::test_table` to use `new_element.table` and `proto.arrow_data.data` matching the new `TableProto` structure - Fix TypeScript type errors in `useWidgetState.test.ts` by replacing undefined `ArrowProto` references with the already-imported `DataframeProto` Co-authored-by: Cursor <[email protected]>
📉 Frontend coverage change detectedThe frontend unit test (vitest) coverage has decreased by 0.0100%
✅ Coverage change is within normal range. |
The `text_content()` method returns `str | None`, but `to_have_text()` expects a non-None value. Adding an assert narrows the type. Co-authored-by: Cursor <[email protected]>
st.dataframe selectionsst.dataframe selections
There was a problem hiding this comment.
Pull request overview
Enables programmatic control of st.dataframe selection by allowing users to write a selection-state object into st.session_state[key], which is then validated on the backend and applied on the frontend.
Changes:
- Add
selection_stateto the Dataframe protobuf to carry backend-driven selection state to the frontend. - Add backend validation (
_validate_selection_state) and send validated selection JSON to the frontend when session state changes. - Add frontend support to apply programmatic selections, avoid feedback loops, and extend unit + e2e coverage.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| proto/streamlit/proto/Dataframe.proto | Adds selection_state field to transport programmatic selection state to the frontend. |
| lib/streamlit/elements/arrow.py | Validates session-state selection payloads and forwards programmatic selection state to the frontend; allows session-state writes for this widget. |
| lib/tests/streamlit/elements/arrow_dataframe_test.py | Removes the “no session_state writes” expectation and adds focused unit tests for selection-state validation. |
| frontend/lib/src/components/widgets/DataFrame/hooks/useWidgetState.ts | Adds parsing helper + programmatic selection retrieval/sync behavior. |
| frontend/lib/src/components/widgets/DataFrame/hooks/useWidgetState.test.ts | Adds unit tests covering programmatic selection parsing + widget manager syncing. |
| frontend/lib/src/components/widgets/DataFrame/hooks/useSelectionHandler.ts | Adds an option to skip syncing selection updates to widget state (used to avoid programmatic feedback loops). |
| frontend/lib/src/components/widgets/DataFrame/DataFrame.tsx | Applies programmatic selection state from the element and prevents redundant backend syncs. |
| e2e_playwright/st_dataframe_selections.py | Adds an app section demonstrating programmatic selection set/clear via session state. |
| e2e_playwright/st_dataframe_selections_test.py | Adds e2e coverage for programmatic selection and improves a fragment rerun assertion. |
frontend/lib/src/components/widgets/DataFrame/hooks/useWidgetState.ts
Outdated
Show resolved
Hide resolved
SummaryAdds programmatic dataframe selection via Session State, including backend validation, a new proto field, frontend application logic, and expanded unit/e2e coverage for selection behavior. Code QualityThe overall structure is clean and consistent with existing patterns, but programmatic row selections are applied using raw row indices without accounting for sorted views. Since selection state is synced using original row indices, a sorted grid can highlight the wrong rows after a programmatic update. selectionState.selection?.rows?.forEach(row => {
rowSelection = rowSelection.add(row)
}) selectionState.selection.rows = newSelection.rows
.toArray()
.map(row => getOriginalIndex(row))Test CoverageGood breadth across Python validation, TS hooks, and e2e coverage for programmatic selection. However, a new e2e test uses # The selection uses a debounce of 150ms; the React effect that applies the
# programmatic selection to the grid's visual state runs after DOM commit,
# so we need a brief wait before the manual click.
app.wait_for_timeout(250)Backwards CompatibilityAdding an optional proto field is backwards compatible; existing selection behavior is preserved for users who don’t set programmatic selection state. Security & RiskNo direct security concerns. Main regression risk is incorrect row highlighting when programmatic selection occurs while a dataframe is sorted, which can cause user confusion and incorrect downstream logic. AccessibilityNo new UI elements or interaction patterns were introduced; accessibility impact appears neutral. Recommendations
VerdictCHANGES_REQUESTED: Please address the e2e wait strategy and the sorted-row mapping issue before merge. This is an automated AI review using |
SummaryThis PR adds the ability to programmatically set
Code QualityBackend ( The
Frontend (
Frontend (
Proto (
Test refactor (
Test CoveragePython unit tests ( Frontend unit tests ( Frontend unit tests ( E2E tests (
Minor note on E2E flakiness: The The existing fragment test fix ( Backwards CompatibilityThis PR is fully backward compatible:
Security & Risk
AccessibilityNo new interactive UI elements are introduced. The programmatic selection applies the same visual highlighting (checkmarks, column highlights) that user-initiated selections use, so existing accessibility properties of glide-data-grid are preserved. The toolbar "Clear selection" button continues to work correctly with programmatically set selections. Recommendations
VerdictAPPROVED: This is a well-designed, thoroughly tested, and backward-compatible feature addition. The validation logic is defensive, the frontend follows established patterns, test coverage is comprehensive across all layers, and the PR addresses a clear user need (issue #10128). The minor recommendations above are suggestions for polish, not blockers. This is an automated AI review using |
|
I think it's a good idea to support setting the value via session state, but I was wondering whether we should also include a parameter for it to make it more discoverable and align with how to set the default value for other widgets. E.g. |
Co-authored-by: Cursor <[email protected]>
I added |
SummaryThis PR adds programmatic selection support for
The implementation spans the full stack: a new Code QualityBoth reviewers agreed the code is well-structured, follows existing codebase patterns, and cleanly separates backend/frontend responsibilities. Backend highlights:
Frontend highlights:
Minor issue — boolean acceptance as row indices (non-blocking):
Test CoverageBoth reviewers agreed coverage is thorough across all layers:
Minor gap: No test asserts that boolean row/cell indices are rejected (relates to the non-blocking issue above). Backwards CompatibilityBoth reviewers agreed there are no breaking changes:
Security & RiskBoth reviewers agreed security posture is sound:
AccessibilityBoth reviewers agreed there are no accessibility regressions. The feature drives the same visual selection state that users already set via mouse/keyboard — no new interactive elements or ARIA attributes are introduced. Reviewer Agreement & Disagreements
Recommendations
VerdictAPPROVED: This is a well-designed, thoroughly tested feature with robust input validation, proper frontend integration, and no backwards compatibility concerns. The boolean-as-int edge case raised by one reviewer is technically valid but non-blocking — it's an unlikely user scenario with benign behavior that can be addressed as a follow-up. Consolidated review by 📋 Review by `gpt-5.3-codex-high`SummaryThis PR introduces programmatic selection support for Code QualityOverall structure is solid: the selection-mode normalization split is cleaner, backend/frontend responsibilities are well separated, and the one-shot frontend handling for One correctness issue needs to be fixed before merge:
Test CoverageCoverage is strong and well-targeted:
Gap:
Backwards CompatibilityThe API change is additive ( Security & RiskNo major security issue identified. Main regression risk is selection-state correctness from loosely-typed Python inputs; the bool-as-int acceptance is the key remaining risk. AccessibilityNo material accessibility regressions observed in the changed frontend logic. The changes are primarily state-handling and selection synchronization, not new interactive controls or semantics. Recommendations
VerdictCHANGES REQUESTED: The feature is close, but boolean values being accepted as row indices is a correctness bug that should be fixed before merge. This is an automated AI review by 📋 Review by `opus-4.6-thinking`SummaryThis PR adds the ability to programmatically set
The implementation spans the full stack: a new Code QualityThe code is well-structured and follows existing patterns in the codebase. Backend (
Frontend (
Frontend (
Minor observations:
Test CoverageTest coverage is thorough across all layers: Python unit tests (27+ tests):
TypeScript unit tests (14+ tests):
E2E tests:
The Backwards CompatibilityNo breaking changes:
Security & Risk
AccessibilityNo new accessibility concerns:
Recommendations
VerdictAPPROVED: A well-designed, thoroughly tested feature that adds programmatic dataframe selection via session state and a This is an automated AI review by |
SummaryThis PR adds the ability to programmatically set
Changes span the full stack: protobuf schema (two new optional fields), Python backend (validation + serialization), React frontend (one-shot programmatic selection consumption), and comprehensive tests (Python unit, TypeScript unit, E2E, typing, and snapshot tests). Code QualityAll three reviewers agreed the code is well-structured and follows existing codebase patterns. Specific strengths noted across reviews:
Minor concerns (non-blocking):
Test CoverageAll three reviewers agreed test coverage is excellent. Highlights:
Gap noted by Backwards CompatibilityAll three reviewers agreed the changes are fully backwards compatible:
Security & RiskAll three reviewers agreed there are no security concerns. The validation logic is robust — type checks, range checks, column existence checks, and deduplication are applied defensively. Invalid entries are silently filtered. The one-shot signal pattern prevents stale state re-application. AccessibilityAll three reviewers agreed there are no accessibility regressions. No new interactive UI elements are introduced; programmatic selections update the same Reviewer Agreement & Disagreement
Key disagreement: Recommendations
VerdictAPPROVED: The majority of reviewers (2/3) approve, and the single concern raised by This is a consolidated AI review by 📋 Review by `gemini-3.1-pro`SummaryThis PR introduces the ability to programmatically set the Code QualityThe code is well-structured and follows the established patterns in the Streamlit codebase.
Test CoverageThe changes are thoroughly tested across the stack:
Backwards CompatibilityThe changes are fully backwards compatible. The new Security & RiskNo security concerns identified. The backend validates all programmatic selections against the actual dataframe dimensions and column names, preventing invalid indices or names from causing issues or crashes in the frontend. AccessibilityNo new UI elements were added, so there are no new accessibility concerns. The changes maintain the existing accessibility features of the dataframe component. RecommendationsThe implementation is solid, well-tested, and ready to be merged. I have no further recommendations. VerdictAPPROVED: The PR is well-implemented, thoroughly tested, and follows the project's best practices. This is an automated AI review by 📋 Review by `gpt-5.3-codex-high`SummaryThis PR introduces programmatic Code QualityOne functional issue needs to be addressed before merge:
Test CoverageCoverage is strong overall:
Gap:
Backwards CompatibilityFor existing string-column dataframes, behavior is largely backward compatible and aligns with the new feature intent. Security & RiskNo direct security vulnerabilities are apparent in these changes. AccessibilityNo accessibility regressions identified in this PR. The frontend changes are state-management and selection-sync logic; they do not introduce new interactive controls or semantic markup changes. Recommendations
VerdictCHANGES REQUESTED: The feature implementation is close, but programmatic column/cell selection is currently incorrect for valid dataframes with non-string column labels. This is an automated AI review by 📋 Review by `opus-4.6-thinking`SummaryThis PR adds the ability to programmatically set
Key changes span all layers of the stack:
Code QualityThe code is well-structured and follows existing patterns in the codebase. Strengths:
Minor concerns:
Test CoverageTest coverage is excellent and follows all relevant AGENTS.md guidelines: Python unit tests (
Frontend unit tests (
Frontend unit tests (
E2E tests (
Backwards CompatibilityThis change is fully backwards compatible:
Security & Risk
Accessibility
Recommendations
VerdictAPPROVED: This is a well-implemented, thoroughly tested feature that enables programmatic control of This is an automated AI review by |
Describe your changes
Allow programmatically setting the
st.dataframeselection state via session state, and add a newselection_defaultparameter for specifying initial selections.selectionStateproto fieldselection_defaultparameter provides initial selection on first render without overriding subsequent user selectionssingle-cellmode (multi-cell ranges require rectangular range info that can't be reconstructed)GitHub Issue Link (if applicable)
st.dataframe#10128Testing Plan
lib/tests/streamlit/elements/arrow_dataframe_test.py— 27+ new tests for_validate_selection_stateand integration tests forselection_defaultuseWidgetState.test.ts— 14+ new tests forgetProgrammaticSelectionStateand selection default loading;useSelectionHandler.test.ts— consolidated withit.eache2e_playwright/st_dataframe_selections_test.py— Tests for programmatic row/column/cell selection, clearing, and selection defaultsContribution License Agreement
By submitting this pull request you agree that all contributions to this project are made under the Apache 2.0 license.