re_dataframe_ui 0.33.0

Rich table widget over DataFusion.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Test grid view mode of the `DataFusionTableWidget`.

mod common;

use std::sync::Arc;

use arrow::array::{BooleanArray, Float64Array, RecordBatch, StringArray};
use arrow::datatypes::{DataType, Field, Schema};
use datafusion::prelude::SessionContext;
use egui::accesskit::Role;
use egui_kittest::SnapshotResults;
use egui_kittest::kittest::Queryable as _;
use re_dataframe_ui::DataFusionTableWidget;
use re_test_context::TestContext;
use re_viewer_context::AsyncRuntimeHandle;

use common::run_async_harness;

/// Basic grid view rendering in dark and light theme.
#[tokio::test(flavor = "multi_thread")] // `multi_thread` required because `ConnectionRegistryHandle::credentials` uses `block_in_place`.
async fn test_grid_view() {
    let (session_context, table_ref) = setup_test_table(false);
    let mut snapshot_results = SnapshotResults::new();

    for (theme, suffix) in [(egui::Theme::Dark, "dark"), (egui::Theme::Light, "light")] {
        let mut test_context = TestContext::new();
        test_context
            .app_options
            .experimental
            .table_cards_and_blueprints = true;
        let runtime_handle =
            AsyncRuntimeHandle::from_current_tokio_runtime_or_wasmbindgen().unwrap();

        let mut harness = test_context
            .setup_kittest_for_rendering_ui([800.0, 600.0])
            .with_theme(theme)
            .build_ui(|ui| {
                test_context.run_recording(&ui.ctx().clone(), |ctx| {
                    DataFusionTableWidget::new(Arc::clone(&session_context), table_ref)
                        .title("Grid view test")
                        .show(
                            ctx,
                            &runtime_handle,
                            ui,
                            &mut test_context.view_states.lock(),
                        );
                });
            });

        run_async_harness(&mut harness).await;

        // Switch to grid mode.
        harness.get_by_label("Grid view").click();
        run_async_harness(&mut harness).await;

        harness.snapshot(format!("grid_view_basic_{suffix}"));
        snapshot_results.extend_harness(&mut harness);
    }
}

/// Test that the grid reflows when rendered at different widths.
#[tokio::test(flavor = "multi_thread")] // `multi_thread` required because `ConnectionRegistryHandle::credentials` uses `block_in_place`.
async fn test_grid_view_resize() {
    let (session_context, table_ref) = setup_test_table(false);
    let mut snapshot_results = SnapshotResults::new();

    for (width, suffix) in [(400.0, "narrow"), (1200.0, "wide")] {
        let mut test_context = TestContext::new();
        test_context
            .app_options
            .experimental
            .table_cards_and_blueprints = true;
        let runtime_handle =
            AsyncRuntimeHandle::from_current_tokio_runtime_or_wasmbindgen().unwrap();

        let mut harness = test_context
            .setup_kittest_for_rendering_ui([width, 600.0])
            .build_ui(|ui| {
                test_context.run_recording(&ui.ctx().clone(), |ctx| {
                    DataFusionTableWidget::new(Arc::clone(&session_context), table_ref)
                        .title("Grid resize test")
                        .show(
                            ctx,
                            &runtime_handle,
                            ui,
                            &mut test_context.view_states.lock(),
                        );
                });
            });

        run_async_harness(&mut harness).await;

        // Switch to grid mode.
        harness.get_by_label("Grid view").click();
        run_async_harness(&mut harness).await;

        harness.snapshot(format!("grid_view_resize_{suffix}"));
        snapshot_results.extend_harness(&mut harness);
    }
}

/// Test flag toggle interaction in dark and light theme (in-memory only).
///
/// Verifies that flag buttons appear and clicking toggles the visual state.
/// Server-side persistence of flag changes is tested in
/// `re_integration_test::tests::grid_view_flagging`.
#[tokio::test(flavor = "multi_thread")] // `multi_thread` required because `ConnectionRegistryHandle::credentials` uses `block_in_place`.
async fn test_grid_view_flagging() {
    let (session_context, table_ref) = setup_test_table(true);
    let mut snapshot_results = SnapshotResults::new();

    // Fake remote URI — flagging requires remote_table + table index to be enabled.
    let remote_uri: re_uri::EntryUri =
        "rerun+http://localhost:1234/entry/00000000000000000000000000000001"
            .parse()
            .unwrap();

    for (theme, suffix) in [(egui::Theme::Dark, "dark"), (egui::Theme::Light, "light")] {
        let mut test_context = TestContext::new();
        test_context
            .app_options
            .experimental
            .table_cards_and_blueprints = true;
        let runtime_handle =
            AsyncRuntimeHandle::from_current_tokio_runtime_or_wasmbindgen().unwrap();

        let mut harness = test_context
            .setup_kittest_for_rendering_ui([800.0, 600.0])
            .with_theme(theme)
            .build_ui(|ui| {
                test_context.run_recording(&ui.ctx().clone(), |ctx| {
                    DataFusionTableWidget::new(Arc::clone(&session_context), table_ref)
                        .title("Flag test")
                        .remote_table(remote_uri.clone())
                        .show(
                            ctx,
                            &runtime_handle,
                            ui,
                            &mut test_context.view_states.lock(),
                        );
                });
            });

        run_async_harness(&mut harness).await;
        harness.get_by_label("Grid view").click();
        run_async_harness(&mut harness).await;
        harness.snapshot(format!("grid_view_flagging_{suffix}"));

        // Toggle the first flag.
        harness
            .query_all_by_role_and_label(Role::CheckBox, "Flag")
            .next()
            .expect("Expected at least one flag button.")
            .click();
        run_async_harness(&mut harness).await;
        harness.snapshot(format!("grid_view_flagging_toggled_{suffix}"));

        snapshot_results.extend_harness(&mut harness);
    }
}

/// Test grid view with non-uniform card heights to exercise virtualized layout.
///
/// Creates 30 rows with varying content lengths — some with long multi-word notes
/// that wrap, some with short or missing values — so cards end up at different heights.
#[tokio::test(flavor = "multi_thread")] // `multi_thread` required because `ConnectionRegistryHandle::credentials` uses `block_in_place`.
async fn test_grid_view_non_uniform_cards() {
    let (session_context, table_ref) = setup_non_uniform_table();
    let mut test_context = TestContext::new();
    test_context
        .app_options
        .experimental
        .table_cards_and_blueprints = true;
    let runtime_handle = AsyncRuntimeHandle::from_current_tokio_runtime_or_wasmbindgen().unwrap();

    let mut harness = test_context
        .setup_kittest_for_rendering_ui([800.0, 600.0])
        .build_ui(|ui| {
            test_context.run_recording(&ui.ctx().clone(), |ctx| {
                DataFusionTableWidget::new(Arc::clone(&session_context), table_ref)
                    .title("Non-uniform cards")
                    .show(
                        ctx,
                        &runtime_handle,
                        ui,
                        &mut test_context.view_states.lock(),
                    );
            });
        });

    run_async_harness(&mut harness).await;

    // Switch to grid mode.
    harness.get_by_label("Grid view").click();
    run_async_harness(&mut harness).await;

    harness.snapshot("grid_view_non_uniform_cards");
}

// ---

/// Sets up a test table.
///
/// When `with_flagging` is true, the schema is configured for flagging:
/// - `id` column gets `rerun:is_table_index` metadata (required for upsert)
/// - Schema gets `rerun:flag_column` metadata pointing at the `flagged` column
fn setup_test_table(with_flagging: bool) -> (Arc<SessionContext>, &'static str) {
    let mut id_field = Field::new("id", DataType::Int64, false);
    let mut flagged_field = Field::new("flagged", DataType::Boolean, true);

    if with_flagging {
        id_field = id_field.with_metadata(
            [(
                re_sorbet::metadata::SORBET_IS_TABLE_INDEX.to_owned(),
                "true".to_owned(),
            )]
            .into(),
        );
        flagged_field = flagged_field.with_metadata(
            [(
                re_dataframe_ui::experimental_field_metadata::IS_FLAG_COLUMN.to_owned(),
                "true".to_owned(),
            )]
            .into(),
        );
    }

    let schema = Arc::new(Schema::new_with_metadata(
        vec![
            id_field,
            Field::new("score", DataType::Float64, false),
            Field::new("category", DataType::Utf8, false),
            Field::new("name", DataType::Utf8, false),
            flagged_field,
            Field::new("notes", DataType::Utf8, true),
        ],
        Default::default(),
    ));
    let batch = RecordBatch::try_new_with_options(
        schema.clone(),
        vec![
            Arc::new(arrow::array::Int64Array::from(vec![1, 2, 3, 4, 5])),
            Arc::new(Float64Array::from(vec![95.0, 82.5, 91.0, 88.0, 76.5])),
            Arc::new(StringArray::from(vec![
                "robotics", "vision", "robotics", "spatial", "vision",
            ])),
            Arc::new(StringArray::from(vec![
                "Alice", "Bob", "Charlie", "Diana", "Eve",
            ])),
            Arc::new(BooleanArray::from(vec![
                Some(true),
                Some(false),
                Some(false),
                Some(true),
                Some(false),
            ])),
            Arc::new(StringArray::from(vec![
                Some("top performer"),
                None,
                Some("needs review"),
                Some("promoted"),
                None,
            ])),
        ],
        &Default::default(),
    )
    .expect("Failed to create a record batch");

    let session_context = Arc::new(SessionContext::new());
    let table_ref = "test_table";
    session_context
        .register_batch(table_ref, batch)
        .expect("Failed to register the table");

    (session_context, table_ref)
}

/// Sets up a table with 30 rows of wildly varying content lengths.
///
/// Rows differ in: name length, number of nullable fields that are present,
/// description length (from absent to multi-sentence paragraphs), and tag count.
/// This produces cards with very different heights to stress the virtualized
/// layout's height caching and row assignment.
fn setup_non_uniform_table() -> (Arc<SessionContext>, &'static str) {
    let ids: Vec<i64> = (1..=20).collect();
    let n = ids.len();
    let scores: Vec<f64> = (0..n).map(|i| 50.0 + (i as f64 * 1.7) % 50.0).collect();

    let categories: Vec<&str> = (0..n)
        .map(|i| match i % 5 {
            0 => "robotics",
            1 => "computer-vision",
            2 => "spatial-computing",
            3 => "motion-planning",
            _ => "multi-modal-perception",
        })
        .collect();

    let names: Vec<&str> = [
        "Al",
        "Bob",
        "Charlie Chaplin",
        "Di",
        "Eve",
        "Ferdinand von Zeppelin III",
        "G",
        "Hank",
        "Iris Apfel-Strudel",
        "Jo",
        "Kai",
        "Luna Moonbeam Stargazer the Magnificent",
        "Mo",
        "Nia",
        "Olaf",
        "Pippi Longstocking",
        "Q",
        "Raj",
        "Sue",
        "Tiberius Maximus Aurelius",
    ]
    .into();

    // Descriptions vary from None to very long paragraphs.
    let descriptions: Vec<Option<&str>> = (0..n)
        .map(|i| match i % 8 {
            0 => Some(
                "Top performer in the quarterly assessment with outstanding marks across \
                 all evaluation criteria and team collaboration metrics. Recommended for \
                 leadership track. Has consistently demonstrated excellence in cross-functional \
                 projects spanning multiple divisions.",
            ),
            1 | 3 | 5 => None,
            2 => Some("OK"),
            4 => Some(
                "Needs review: flagged by automated pipeline for anomalous sensor readings \
                 during the third calibration pass. Investigate before clearing. The anomaly \
                 pattern matches a known firmware regression in batch 7B units.",
            ),
            6 => Some(
                "Extended field trial participant. Deployed for 847 hours across arctic, \
                 desert, and underwater environments. All subsystems nominal except minor \
                 thermal drift in IMU cluster B which self-corrected after 72h acclimatization. \
                 Full telemetry archive available in dataset DS-2024-0891. Recommend continued \
                 deployment with monthly check-ins.",
            ),
            _ => Some("No issues found."),
        })
        .collect();

    // Tags: some rows have none, some have short tags, some long comma-separated lists.
    let tags: Vec<Option<&str>> = (0..n)
        .map(|i| match i % 6 {
            0 => Some("priority, review-needed, Q4-2024"),
            1 | 4 => None,
            2 => Some("stable"),
            3 => Some("arctic, underwater, extreme-conditions, long-duration, telemetry, thermal-drift, imu"),
            _ => Some("regression, firmware, batch-7B, calibration, sensor-anomaly, high-priority"),
        })
        .collect();

    // Location: mix of present/absent with varying lengths.
    let locations: Vec<Option<&str>> = (0..n)
        .map(|i| match i % 5 {
            0 => Some("Building 4, Lab 2A"),
            1 => Some("Remote — Svalbard Arctic Station, Sector 7G, Cold Storage Unit #12"),
            2 | 4 => None,
            _ => Some("HQ"),
        })
        .collect();

    // Status: short field, always present but varying.
    let statuses: Vec<&str> = (0..n)
        .map(|i| match i % 4 {
            0 => "active",
            1 => "inactive",
            2 => "pending-review",
            _ => "deployed",
        })
        .collect();

    let schema = Arc::new(Schema::new_with_metadata(
        vec![
            Field::new("id", DataType::Int64, false),
            Field::new("name", DataType::Utf8, false),
            Field::new("score", DataType::Float64, false),
            Field::new("category", DataType::Utf8, false),
            Field::new("status", DataType::Utf8, false),
            Field::new("description", DataType::Utf8, true),
            Field::new("tags", DataType::Utf8, true),
            Field::new("location", DataType::Utf8, true),
        ],
        Default::default(),
    ));

    let batch = RecordBatch::try_new_with_options(
        schema,
        vec![
            Arc::new(arrow::array::Int64Array::from(ids)),
            Arc::new(StringArray::from(names)),
            Arc::new(Float64Array::from(scores)),
            Arc::new(StringArray::from(categories)),
            Arc::new(StringArray::from(statuses)),
            Arc::new(StringArray::from(descriptions)),
            Arc::new(StringArray::from(tags)),
            Arc::new(StringArray::from(locations)),
        ],
        &Default::default(),
    )
    .expect("Failed to create a record batch");

    let session_context = Arc::new(SessionContext::new());
    let table_ref = "non_uniform_table";
    session_context
        .register_batch(table_ref, batch)
        .expect("Failed to register the table");

    (session_context, table_ref)
}