From 84c39d4479a3eb3cebb2725934eb1d0d22c8e9bc Mon Sep 17 00:00:00 2001 From: Andrew Stein Date: Fri, 20 Nov 2026 09:10:27 -0500 Subject: [PATCH 1/4] Move formatting to Rust icu4x Signed-off-by: Andrew Stein --- Cargo.lock | 633 ++++++++++++- Cargo.toml | 32 +- .../viewer-charts/src/ts/axis/numeric-axis.ts | 2 +- .../charts/candlestick/candlestick-build.ts | 2 +- .../viewer-charts/src/ts/charts/chart-base.ts | 124 ++- .../charts/common/category-axis-resolver.ts | 67 +- .../src/ts/charts/heatmap/heatmap-build.ts | 2 +- .../src/ts/charts/heatmap/heatmap-interact.ts | 2 +- .../src/ts/charts/series/series-build.ts | 2 +- .../src/ts/data/last-group-by-split.ts | 2 +- packages/viewer-charts/src/ts/layout/ticks.ts | 98 ++- .../src/ts/plugin/format-defaults.ts | 2 +- packages/viewer-charts/src/ts/plugin_utils.ts | 26 + .../viewer-charts/src/ts/theme/gradient.ts | 227 +---- .../src/ts/worker/renderer.worker.ts | 2 + .../viewer-datagrid/src/css/regular_table.css | 64 -- .../src/ts/custom_elements/datagrid.ts | 48 +- .../src/ts/data_listener/format_cell.ts | 83 +- .../src/ts/data_listener/formatter_cache.ts | 104 --- .../src/ts/data_listener/index.ts | 21 +- .../viewer-datagrid/src/ts/get_cell_config.ts | 3 +- .../viewer-datagrid/src/ts/model/create.ts | 115 +-- .../viewer-datagrid/src/ts/model/index.ts | 2 +- .../src/ts/plugin/column_config_schema.ts | 179 +--- .../src/ts/plugin/plugin_config_schema.ts | 41 +- .../viewer-datagrid/src/ts/plugin/restore.ts | 92 +- .../viewer-datagrid/src/ts/plugin_utils.ts | 18 +- .../src/ts/style_handlers/body.ts | 22 +- packages/viewer-datagrid/src/ts/types.ts | 185 +--- rust/perspective-client/Cargo.toml | 5 - rust/perspective-client/src/rust/client.rs | 13 +- rust/perspective-client/src/rust/utils/mod.rs | 5 - rust/perspective-js/Cargo.toml | 7 +- rust/perspective-js/build.mjs | 2 +- rust/perspective-js/src/rust/typed_array.rs | 43 +- .../src/rust/utils/trace_allocator.rs | 7 +- rust/perspective-migrate/src/plugins/mod.rs | 1 + rust/perspective-python/Cargo.toml | 1 - rust/perspective-viewer/Cargo.toml | 23 +- rust/perspective-viewer/build.mjs | 13 +- rust/perspective-viewer/package.json | 5 - .../src/css/plugin-selector.css | 11 + .../column_selector/config_selector.rs | 19 + .../rust/components/datetime_column_style.rs | 43 +- .../src/rust/config/number_string_format.rs | 4 +- .../src/rust/config/plugin_static_config.rs | 15 + .../src/rust/custom_elements/viewer.rs | 1 + .../src/rust/format/baked_data.rs | 260 ++++++ .../src/rust/format/datetime.rs | 832 ++++++++++++++++++ .../src/rust/format/digits.rs | 140 +++ .../src/rust/format/locale_data.rs | 70 ++ .../perspective-viewer/src/rust/format/mod.rs | 159 ++++ .../src/rust/format/number.rs | 510 +++++++++++ .../src/rust/format/spec.rs | 196 +++++ rust/perspective-viewer/src/rust/lib.rs | 79 +- .../src/rust/plugin_utils.rs | 731 +++++++++++++++ .../src/rust/plugin_utils/resolve.rs | 402 +++++++++ rust/perspective-viewer/src/rust/renderer.rs | 4 +- .../rust/session/column_defaults_update.rs | 16 + .../src/rust/utils/custom_element.rs | 27 +- .../src/rust/utils/number_format.rs | 38 +- .../src/svg/mega-menu-icons-summary.svg | 17 + rust/perspective-viewer/src/themes/icons.css | 1 + rust/perspective-viewer/src/themes/intl.css | 6 +- .../perspective-viewer/src/themes/intl/ar.css | 6 +- .../perspective-viewer/src/themes/intl/de.css | 6 +- .../perspective-viewer/src/themes/intl/es.css | 6 +- .../perspective-viewer/src/themes/intl/fr.css | 6 +- .../perspective-viewer/src/themes/intl/ja.css | 6 +- .../perspective-viewer/src/themes/intl/pt.css | 6 +- .../perspective-viewer/src/themes/intl/zh.css | 6 +- rust/perspective-viewer/src/ts/bootstrap.ts | 3 +- .../src/ts/column-format.ts | 252 ------ rust/perspective-viewer/src/ts/extensions.ts | 16 + .../src/ts/perspective-viewer.ts | 8 +- .../src/ts/plugin_utils/cell_style.ts | 27 + .../ts/plugin_utils/cell_style}/boolean.ts | 13 +- .../ts/plugin_utils/cell_style}/cell_flash.ts | 8 +- .../ts/plugin_utils/cell_style}/datetime.ts | 11 +- .../ts/plugin_utils/cell_style}/numeric.ts | 14 +- .../src/ts/plugin_utils/cell_style/pulse.css | 76 ++ .../src/ts/plugin_utils/cell_style}/string.ts | 12 +- .../src/ts/plugin_utils/cell_style/types.ts | 47 + .../src/ts/plugin_utils/color.ts | 240 +---- .../src/ts/plugin_utils/column_style.ts | 238 +++++ .../src/ts/plugin_utils/css.d.ts | 16 + .../src/ts/plugin_utils/format.ts | 84 ++ .../src/ts/plugin_utils/index.ts | 70 ++ .../src/ts/plugin_utils}/meta_columns.ts | 0 .../src/ts/plugin_utils/native.ts | 68 ++ .../src/ts/plugin_utils/schema.ts | 240 +++++ .../src/ts/plugin_utils/theme_style.ts | 126 +++ .../settings_panel/status_bar_menus.spec.ts | 52 -- .../custom_elements_manifest.spec.ts | 7 +- rust/perspective-viewer/tools.mjs | 41 +- 95 files changed, 5778 insertions(+), 1839 deletions(-) create mode 100644 packages/viewer-charts/src/ts/plugin_utils.ts delete mode 100644 packages/viewer-datagrid/src/ts/data_listener/formatter_cache.ts rename rust/perspective-client/src/rust/utils/talc_allocator.rs => packages/viewer-datagrid/src/ts/plugin_utils.ts (83%) create mode 100644 rust/perspective-viewer/src/rust/format/baked_data.rs create mode 100644 rust/perspective-viewer/src/rust/format/datetime.rs create mode 100644 rust/perspective-viewer/src/rust/format/digits.rs create mode 100644 rust/perspective-viewer/src/rust/format/locale_data.rs create mode 100644 rust/perspective-viewer/src/rust/format/mod.rs create mode 100644 rust/perspective-viewer/src/rust/format/number.rs create mode 100644 rust/perspective-viewer/src/rust/format/spec.rs create mode 100644 rust/perspective-viewer/src/rust/plugin_utils.rs create mode 100644 rust/perspective-viewer/src/rust/plugin_utils/resolve.rs create mode 100644 rust/perspective-viewer/src/svg/mega-menu-icons-summary.svg delete mode 100644 rust/perspective-viewer/src/ts/column-format.ts create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/cell_style.ts rename {packages/viewer-datagrid/src/ts/style_handlers/table_cell => rust/perspective-viewer/src/ts/plugin_utils/cell_style}/boolean.ts (91%) rename {packages/viewer-datagrid/src/ts/style_handlers/table_cell => rust/perspective-viewer/src/ts/plugin_utils/cell_style}/cell_flash.ts (95%) rename {packages/viewer-datagrid/src/ts/style_handlers/table_cell => rust/perspective-viewer/src/ts/plugin_utils/cell_style}/datetime.ts (94%) rename {packages/viewer-datagrid/src/ts/style_handlers/table_cell => rust/perspective-viewer/src/ts/plugin_utils/cell_style}/numeric.ts (96%) create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/cell_style/pulse.css rename {packages/viewer-datagrid/src/ts/style_handlers/table_cell => rust/perspective-viewer/src/ts/plugin_utils/cell_style}/string.ts (96%) create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/cell_style/types.ts rename packages/viewer-datagrid/src/ts/color_utils.ts => rust/perspective-viewer/src/ts/plugin_utils/color.ts (63%) create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/column_style.ts create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/css.d.ts create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/format.ts create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/index.ts rename {packages/viewer-datagrid/src/ts/model => rust/perspective-viewer/src/ts/plugin_utils}/meta_columns.ts (100%) create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/native.ts create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/schema.ts create mode 100644 rust/perspective-viewer/src/ts/plugin_utils/theme_style.ts diff --git a/Cargo.lock b/Cargo.lock index f8adcb5ed3..56e44c2530 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -348,6 +348,16 @@ version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + [[package]] name = "camino" version = "1.2.1" @@ -565,6 +575,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -732,6 +751,17 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "dtoa" version = "1.0.11" @@ -772,7 +802,7 @@ dependencies = [ "anstream", "anstyle", "env_filter", - "jiff", + "jiff 0.2.18", "log", ] @@ -827,6 +857,18 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "ryu", + "smallvec", + "writeable", +] + [[package]] name = "fixedbitset" version = "0.4.2" @@ -1406,6 +1448,352 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_calendar" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a68ffb801cc7acb8dcae62da7c692c47934698d2dd4f479ddee1eb442763dea1" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_provider", + "ixdtf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_calendar_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "514da54e79efa36b5976232d5b3d1d8ee1b47b19ab658f1b1ebe39221696c2d8" + +[[package]] +name = "icu_casemap" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a6f143e9349267b80ae071a6ec25d4797c45756d8b2671a8b24b7b25b81ab94" +dependencies = [ + "icu_casemap_data", + "icu_collections", + "icu_locale_core", + "icu_properties", + "icu_provider", + "potential_utf", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_casemap_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71a5c321208537711696af55bc2ab5dad939e4f6e0aef92dd6a2555deceedf3a" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "serde", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_datetime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c338aa7ebff734470e216a4196fa84b123a366cc786c445741b6f5647412c3c" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_calendar", + "icu_datetime_data", + "icu_decimal", + "icu_locale_core", + "icu_locale_fallback", + "icu_pattern", + "icu_plurals", + "icu_provider", + "icu_time", + "potential_utf", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_datetime_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bddb757c2df1635453c4e8cb2d4ba7ad026e904893f29699315826c0951bbd9" + +[[package]] +name = "icu_decimal" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1150ad5e272740670464934ee76facda43ef2e11f85c27b7ba76ccb33edf2d05" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_decimal_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_pattern", + "icu_plurals", + "icu_provider", + "serde", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_decimal_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5595ab78370d48abd24a062f3db115d5108dd0b65634352036cae532aebb0df8" + +[[package]] +name = "icu_experimental" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64423d9f65806f0a864c4d1f156a46b910cba98b6cf6a764f3297f671423b7ec" +dependencies = [ + "displaydoc", + "either", + "fixed_decimal", + "icu_casemap", + "icu_collections", + "icu_decimal", + "icu_experimental_data", + "icu_list", + "icu_locale", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_pattern", + "icu_plurals", + "icu_properties", + "icu_provider", + "litemap", + "num-bigint", + "num-rational", + "num-traits", + "potential_utf", + "smallvec", + "tinystr", + "writeable", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_experimental_data" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3028e254d20c6c04d2ff4f59f13cce34e3f147dfcc3a80b82441256c22181722" + +[[package]] +name = "icu_list" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b7401916042e00e2ff603d4a1dd4767772ec361d341a03e549ed2879b56591" +dependencies = [ + "icu_list_data", + "icu_locale_fallback", + "icu_provider", + "regex-automata", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_list_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22b55746bcc43fb7397bc6590980c78a4981d62c04bd7a0db1e3cbc1d2d63457" + +[[package]] +name = "icu_locale" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe8fa57bcddc15cb921582ee5259c5b77da39f946f188ca5213fad24d9241236" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64014dac577a11d8d2cee48517c73c1984bd72ab11031e934269bd3cefb2ad9" + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_pattern" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc43ce0e76ee8cb0482dc6e2dbb9b76278e8038f45daabf2a2877577e2ceb18f" +dependencies = [ + "displaydoc", + "either", + "serde", + "writeable", + "yoke", + "zerovec", +] + +[[package]] +name = "icu_plurals" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef046647b445acf95ce0f8083fa292467d3df649959fa9a20f3f8abfd957c5d" +dependencies = [ + "fixed_decimal", + "icu_locale_fallback", + "icu_plurals_data", + "icu_provider", + "zerovec", +] + +[[package]] +name = "icu_plurals_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43ff7df2c1a1d41588a6ddcba354d513d4a3e10eec22c06fe56d13c12a848ea" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "serde", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_time" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17d45ee651f21433b1c6352311f2ad9b5253c26be0e25d9a0869cb8247b8cfde" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar", + "icu_locale_core", + "icu_provider", + "icu_time_data", + "ixdtf", + "serde", + "writeable", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_time_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6d7d711f44237fa9300406ab6e521148594056862343370b5df265a0d15c088" + [[package]] name = "id-arena" version = "2.2.1" @@ -1496,19 +1884,49 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "ixdtf" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4754a1731458af0443709c9667302793d3f63cc90ec4ba4c8259f2b9515478e5" + [[package]] name = "jiff" version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67e8da4c49d6d9909fe03361f9b620f58898859f5c7aded68351e85e71ecf50" dependencies = [ - "jiff-static", + "jiff-static 0.2.18", "log", "portable-atomic", "portable-atomic-util", "serde_core", ] +[[package]] +name = "jiff" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5d126d72eb017f10b302e73bdeca446bea405ee449af4d9e7866d6b082d83e" +dependencies = [ + "jiff-core", + "jiff-static 1.0.1", + "jiff-tzdb", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + [[package]] name = "jiff-static" version = "0.2.18" @@ -1520,6 +1938,24 @@ dependencies = [ "syn 2.0.111", ] +[[package]] +name = "jiff-static" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0127e9bde3c6130d6169e7d8d68676e4be69c4bf7573c308b6f960a5089c428" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + [[package]] name = "js-sys" version = "0.3.85" @@ -1625,6 +2061,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "lock_api" version = "0.4.14" @@ -1640,22 +2082,6 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" -[[package]] -name = "macro_rules_attribute" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520" -dependencies = [ - "macro_rules_attribute-proc_macro", - "paste", -] - -[[package]] -name = "macro_rules_attribute-proc_macro" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30" - [[package]] name = "matchers" version = "0.2.0" @@ -1791,6 +2217,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1968,7 +2405,6 @@ dependencies = [ "serde", "serde_bytes", "serde_json", - "talc", "thiserror 1.0.69", "tracing", "ts-rs", @@ -2030,7 +2466,6 @@ dependencies = [ "extend", "futures", "indexmap 2.14.0", - "macro_rules_attribute", "perspective-client", "perspective-migrate", "perspective-server", @@ -2077,12 +2512,21 @@ dependencies = [ "console_error_panic_hook", "derivative", "extend", + "fixed_decimal", "futures", "glob", + "icu_calendar", + "icu_datetime", + "icu_decimal", + "icu_experimental", + "icu_locale_core", + "icu_plurals", + "icu_provider", + "icu_time", "itertools 0.14.0", + "jiff 1.0.1", "js-sys", "lightningcss", - "macro_rules_attribute", "nom", "perspective-client", "perspective-js", @@ -2098,6 +2542,7 @@ dependencies = [ "wasm-bindgen-derive", "wasm-bindgen-futures", "web-sys", + "writeable", "yew", ] @@ -2227,6 +2672,17 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -3026,6 +3482,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -3033,12 +3500,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" [[package]] -name = "talc" -version = "4.4.3" +name = "synstructure" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3ae828aa394de34c7de08f522d1b86bd1c182c668d27da69caadda00590f26d" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ - "lock_api", + "proc-macro2", + "quote", + "syn 3.0.10", ] [[package]] @@ -3133,6 +3602,17 @@ dependencies = [ "crunchy", ] +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + [[package]] name = "tinyvec" version = "1.11.0" @@ -3483,12 +3963,27 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "uuid" version = "1.22.0" @@ -3885,6 +4380,15 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +dependencies = [ + "either", +] + [[package]] name = "wyz" version = "0.5.1" @@ -3954,6 +4458,29 @@ dependencies = [ "syn 2.0.111", ] +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.31" @@ -3974,6 +4501,62 @@ dependencies = [ "syn 2.0.111", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 4d5741b820..9955fe4b55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,7 @@ members = [ [profile.dev] panic = "abort" -opt-level = "s" +opt-level = 2 [profile.release] panic = "abort" @@ -45,16 +45,42 @@ codegen-units = 1 lto = true strip = true +# The crates `perspective-viewer`'s number and datetime formatters spend their +# time in, optimized for speed under an otherwise size-optimized profile. +[profile.release.package] +calendrical_calculations = { opt-level = 3 } +core_maths = { opt-level = 3 } +fixed_decimal = { opt-level = 3 } +icu_calendar = { opt-level = 3 } +icu_datetime = { opt-level = 3 } +icu_decimal = { opt-level = 3 } +icu_experimental = { opt-level = 3 } +icu_locale_core = { opt-level = 3 } +icu_pattern = { opt-level = 3 } +icu_plurals = { opt-level = 3 } +icu_provider = { opt-level = 3 } +icu_time = { opt-level = 3 } +libm = { opt-level = 3 } +litemap = { opt-level = 3 } +potential_utf = { opt-level = 3 } +ryu = { opt-level = 3 } +smallvec = { opt-level = 3 } +tinystr = { opt-level = 3 } +writeable = { opt-level = 3 } +yoke = { opt-level = 3 } +zerofrom = { opt-level = 3 } +zerotrie = { opt-level = 3 } +zerovec = { opt-level = 3 } + [profile.fast] inherits = "release" -opt-level = 1 +opt-level = "s" codegen-units = 256 lto = "off" incremental = true # These are only respected when `cargo` is invoked from the project root [patch.crates-io] -# simd-adler32 = { git = "https://github.com/mcountryman/simd-adler32.git", rev = "b279034d9eb554c3e5e0af523db044f08d8297ba" } protobuf-src = { git = "https://github.com/carlocorradini/rust-protobuf-native.git", rev = "1aba500e469f8bdc384a0fe9e69c189fda72e059" } perspective-client = { path = "rust/perspective-client" } perspective-server = { path = "rust/perspective-server" } diff --git a/packages/viewer-charts/src/ts/axis/numeric-axis.ts b/packages/viewer-charts/src/ts/axis/numeric-axis.ts index 4f64ed0206..d7eb7dc49b 100644 --- a/packages/viewer-charts/src/ts/axis/numeric-axis.ts +++ b/packages/viewer-charts/src/ts/axis/numeric-axis.ts @@ -21,7 +21,7 @@ import { drawYTickColumn, } from "./axis-primitives.ts"; import type { Theme } from "../theme/theme.ts"; -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import type { DateFormatModifiers } from "@perspective-dev/viewer"; export interface AxisDomain { min: number; diff --git a/packages/viewer-charts/src/ts/charts/candlestick/candlestick-build.ts b/packages/viewer-charts/src/ts/charts/candlestick/candlestick-build.ts index 17e3663052..fa139f8817 100644 --- a/packages/viewer-charts/src/ts/charts/candlestick/candlestick-build.ts +++ b/packages/viewer-charts/src/ts/charts/candlestick/candlestick-build.ts @@ -10,7 +10,7 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import type { DateFormatModifiers } from "@perspective-dev/viewer"; import type { ColumnDataMap } from "../../data/view-reader.ts"; import { buildSplitGroups } from "../../data/split-groups.ts"; import type { CategoricalLevel } from "../../axis/categorical-axis.ts"; diff --git a/packages/viewer-charts/src/ts/charts/chart-base.ts b/packages/viewer-charts/src/ts/charts/chart-base.ts index f0b1100100..186e249db2 100644 --- a/packages/viewer-charts/src/ts/charts/chart-base.ts +++ b/packages/viewer-charts/src/ts/charts/chart-base.ts @@ -11,17 +11,12 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import type { View } from "@perspective-dev/client"; -import { - createNumberFormatter, - createDatetimeFormatter, - createDateFormatter, - dateFormatModifiers, - hasDateFormatShape, - sourceColumn, - type NumberFormatConfig, - type DateFormatConfig, - type DateFormatModifiers, -} from "@perspective-dev/viewer/column-format"; +import type { + DateFormatConfig, + DateFormatModifiers, + NumberFormatConfig, +} from "@perspective-dev/viewer"; +import { plugin_utils } from "../plugin_utils.ts"; import type { ColumnDataMap } from "../data/view-reader.ts"; import { LazyRowFetcher } from "../data/lazy-row.ts"; import { @@ -65,27 +60,41 @@ import { requestRender as scheduleRender } from "../render/scheduler.ts"; * Fallback formatter applied to numeric tooltip / legend values when the * column has no `number_format` configured. */ -const DEFAULT_VALUE_FORMATTER: (v: number) => string = ((): (( - v: number, -) => string) => { - const intl = createNumberFormatter( - "float", - undefined, - CHART_NUMBER_DEFAULTS, - ); - return (v) => intl.format(v); -})(); +let DEFAULT_VALUE_FORMATTER: ((v: number) => string) | undefined; + +function default_value_formatter(): (v: number) => string { + if (DEFAULT_VALUE_FORMATTER === undefined) { + const formatter = plugin_utils().formatter( + "float", + undefined, + CHART_NUMBER_DEFAULTS, + )!; + + DEFAULT_VALUE_FORMATTER = (v) => formatter.format(v); + } + + return DEFAULT_VALUE_FORMATTER; +} /** * Fallback formatter for datetime tooltip / legend values when the * column has no `date_format` configured. */ -const DEFAULT_DATETIME_FORMATTER: (v: number) => string = ((): (( - v: number, -) => string) => { - const intl = createDatetimeFormatter(undefined, CHART_DATETIME_DEFAULTS); - return (v) => intl.format(v); -})(); +let DEFAULT_DATETIME_FORMATTER: ((v: number) => string) | undefined; + +function default_datetime_formatter(): (v: number) => string { + if (DEFAULT_DATETIME_FORMATTER === undefined) { + const formatter = plugin_utils().formatter( + "datetime", + undefined, + CHART_DATETIME_DEFAULTS, + )!; + + DEFAULT_DATETIME_FORMATTER = (v) => formatter.format(v); + } + + return DEFAULT_DATETIME_FORMATTER; +} /** * Base class for WebGL chart implementations. Owns the common lifecycle @@ -214,7 +223,7 @@ export abstract class AbstractChart implements ChartImplementation { /** * Pre-compiled per-column value formatters, keyed by the **source** * column name (synthetic split-by paths are normalized via - * `sourceColumn`). Rebuilt by `setColumnsConfig` from the active + * `source_column`). Rebuilt by `setColumnsConfig` from the active * plugin's `column_config_schema` output, then consulted by axis / * tooltip / legend paths via {@link getColumnFormatter}. * @@ -480,6 +489,7 @@ export abstract class AbstractChart implements ChartImplementation { * can arrive in any order. Idempotent. */ private _rebuildColumnFormatters(): void { + const utils = plugin_utils(); this._columnFormatters = new Map(); this._columnDateModifiers = new Map(); this._columnValueFormatters = new Map(); @@ -500,15 +510,18 @@ export abstract class AbstractChart implements ChartImplementation { | DateFormatConfig | undefined; - const modifiers = dateFormatModifiers(dateFormat); + const modifiers = utils.date_format_modifiers(dateFormat); if (type === "datetime" && modifiers && !fmt) { this._columnDateModifiers.set(name, modifiers); - const intl = createDatetimeFormatter( + const formatter = utils.formatter( + "datetime", dateFormat, CHART_DATETIME_DEFAULTS, - ); + )!; - this._columnValueFormatters.set(name, (v) => intl.format(v)); + this._columnValueFormatters.set(name, (v) => + formatter.format(v), + ); } } } @@ -521,6 +534,7 @@ export abstract class AbstractChart implements ChartImplementation { return undefined; } + const utils = plugin_utils(); if (type === "integer" || type === "float") { const numberFormat = cfg.number_format as | NumberFormatConfig @@ -529,35 +543,43 @@ export abstract class AbstractChart implements ChartImplementation { return undefined; } - const intl = createNumberFormatter( + const formatter = utils.formatter( type, numberFormat, CHART_NUMBER_DEFAULTS, - ); - return (v) => intl.format(v); + )!; + + return (v) => formatter.format(v); } if (type === "datetime") { const dateFormat = cfg.date_format as DateFormatConfig | undefined; - if (!hasDateFormatShape(dateFormat)) { + if (!utils.has_date_format_shape(dateFormat)) { return undefined; } - const intl = createDatetimeFormatter( + const formatter = utils.formatter( + "datetime", dateFormat, CHART_DATETIME_DEFAULTS, - ); - return (v) => intl.format(v); + )!; + + return (v) => formatter.format(v); } if (type === "date") { const dateFormat = cfg.date_format as DateFormatConfig | undefined; - if (!hasDateFormatShape(dateFormat)) { + if (!utils.has_date_format_shape(dateFormat)) { return undefined; } - const intl = createDateFormatter(dateFormat, CHART_DATE_DEFAULTS); - return (v) => intl.format(v); + const formatter = utils.formatter( + "date", + dateFormat, + CHART_DATE_DEFAULTS, + )!; + + return (v) => formatter.format(v); } return undefined; @@ -593,7 +615,7 @@ export abstract class AbstractChart implements ChartImplementation { ): ((v: number) => string) | undefined { if (columnName) { const formatter = this._columnFormatters.get( - sourceColumn(columnName), + plugin_utils().source_column(columnName), ); if (formatter) { return formatter; @@ -605,7 +627,9 @@ export abstract class AbstractChart implements ChartImplementation { } const valueFormatter = columnName - ? this._columnValueFormatters.get(sourceColumn(columnName)) + ? this._columnValueFormatters.get( + plugin_utils().source_column(columnName), + ) : undefined; if (valueFormatter) { @@ -616,16 +640,18 @@ export abstract class AbstractChart implements ChartImplementation { // key group_by source columns (their post-aggregate form is // `__ROW_PATH_N__`); fall back to `_groupByTypes` so date / // datetime group_by axes don't get formatted as numbers. - const sourceName = columnName ? sourceColumn(columnName) : undefined; + const sourceName = columnName + ? plugin_utils().source_column(columnName) + : undefined; const type = sourceName ? (this._columnTypes[sourceName] ?? this._groupByTypes[sourceName]) : undefined; if (type === "date" || type === "datetime") { - return DEFAULT_DATETIME_FORMATTER; + return default_datetime_formatter(); } - return DEFAULT_VALUE_FORMATTER; + return default_value_formatter(); } /** @@ -636,7 +662,9 @@ export abstract class AbstractChart implements ChartImplementation { columnName: string | null | undefined, ): DateFormatModifiers | undefined { return columnName - ? this._columnDateModifiers.get(sourceColumn(columnName)) + ? this._columnDateModifiers.get( + plugin_utils().source_column(columnName), + ) : undefined; } diff --git a/packages/viewer-charts/src/ts/charts/common/category-axis-resolver.ts b/packages/viewer-charts/src/ts/charts/common/category-axis-resolver.ts index 197ee1b3ba..12117f48d0 100644 --- a/packages/viewer-charts/src/ts/charts/common/category-axis-resolver.ts +++ b/packages/viewer-charts/src/ts/charts/common/category-axis-resolver.ts @@ -16,8 +16,12 @@ import type { CategoricalLevel, } from "../../axis/categorical-axis.ts"; import { buildGroupRuns } from "../../axis/categorical-axis-core.ts"; -import { formatTickValue, formatDateTickValue } from "../../layout/ticks.ts"; -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import { + formatTickValue, + formatDateTickValue, + formatDateTickValues, +} from "../../layout/ticks.ts"; +import type { DateFormatModifiers } from "@perspective-dev/viewer"; export interface CategoryAxisResult { /** @@ -225,6 +229,29 @@ export function formatLevelValue( return String(value); } +/** {@link formatLevelValue} over every one of `values`, all of them valid. */ +function formatLevelValues( + values: number[], + levelType: string, + dateModifiers?: DateFormatModifiers, +): string[] { + if (levelType !== "date" && levelType !== "datetime") { + return values.map((v) => + formatLevelValue(v, true, levelType, dateModifiers), + ); + } + + const present = values.map((v) => v != null && !Number.isNaN(v)); + const labels = formatDateTickValues( + values.filter((_, i) => present[i]), + undefined, + levelType === "datetime" ? dateModifiers : undefined, + ); + + let next = 0; + return present.map((ok) => (ok ? labels[next++] : "")); +} + /** * Synthesize a `(indices, dictionary)` pair from a non-string row-path * column so the rest of the categorical axis machinery (label @@ -246,29 +273,39 @@ export function synthesizeStringLevel( seen.set("", 0); const valueIdx = new Map(); - + const distinct: number[] = []; for (let r = 0; r < numRows; r++) { const isValid = valid ? !!((valid[r >> 3] >> (r & 7)) & 1) : true; if (!isValid) { - indices[r] = 0; + indices[r] = -1; continue; } const v = values[r] as number; - let dictIdx = valueIdx.get(v); - if (dictIdx === undefined) { - const label = formatLevelValue(v, true, levelType, dateModifiers); - dictIdx = seen.get(label); - if (dictIdx === undefined) { - dictIdx = dictionary.length; - dictionary.push(label); - seen.set(label, dictIdx); - } + let slot = valueIdx.get(v); + if (slot === undefined) { + slot = distinct.length; + distinct.push(v); + valueIdx.set(v, slot); + } - valueIdx.set(v, dictIdx); + indices[r] = slot; + } + + const labels = formatLevelValues(distinct, levelType, dateModifiers); + const dictIdx = labels.map((label) => { + let idx = seen.get(label); + if (idx === undefined) { + idx = dictionary.length; + dictionary.push(label); + seen.set(label, idx); } - indices[r] = dictIdx; + return idx; + }); + + for (let r = 0; r < numRows; r++) { + indices[r] = indices[r] < 0 ? 0 : dictIdx[indices[r]]; } return { indices, dictionary }; diff --git a/packages/viewer-charts/src/ts/charts/heatmap/heatmap-build.ts b/packages/viewer-charts/src/ts/charts/heatmap/heatmap-build.ts index 3bdd8f5edd..f27a42dc63 100644 --- a/packages/viewer-charts/src/ts/charts/heatmap/heatmap-build.ts +++ b/packages/viewer-charts/src/ts/charts/heatmap/heatmap-build.ts @@ -10,7 +10,7 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import type { DateFormatModifiers } from "@perspective-dev/viewer"; import type { ColumnDataMap } from "../../data/view-reader.ts"; import type { CategoricalLevel } from "../../axis/categorical-axis.ts"; import { buildGroupRuns } from "../../axis/categorical-axis-core.ts"; diff --git a/packages/viewer-charts/src/ts/charts/heatmap/heatmap-interact.ts b/packages/viewer-charts/src/ts/charts/heatmap/heatmap-interact.ts index 051b425ee1..8aea0ac798 100644 --- a/packages/viewer-charts/src/ts/charts/heatmap/heatmap-interact.ts +++ b/packages/viewer-charts/src/ts/charts/heatmap/heatmap-interact.ts @@ -10,7 +10,7 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import type { DateFormatModifiers } from "@perspective-dev/viewer"; import type { HeatmapChart } from "./heatmap.ts"; import type { HeatmapCell } from "./heatmap-build.ts"; import { renderCanvasTooltip } from "../../interaction/tooltip-controller.ts"; diff --git a/packages/viewer-charts/src/ts/charts/series/series-build.ts b/packages/viewer-charts/src/ts/charts/series/series-build.ts index 9969ca10e0..6313ddc8ff 100644 --- a/packages/viewer-charts/src/ts/charts/series/series-build.ts +++ b/packages/viewer-charts/src/ts/charts/series/series-build.ts @@ -10,7 +10,7 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import type { DateFormatModifiers } from "@perspective-dev/viewer"; import type { ColumnDataMap } from "../../data/view-reader.ts"; import { buildSplitGroups } from "../../data/split-groups.ts"; import type { diff --git a/packages/viewer-charts/src/ts/data/last-group-by-split.ts b/packages/viewer-charts/src/ts/data/last-group-by-split.ts index 2b8899c5b7..5ba271c0ed 100644 --- a/packages/viewer-charts/src/ts/data/last-group-by-split.ts +++ b/packages/viewer-charts/src/ts/data/last-group-by-split.ts @@ -12,7 +12,7 @@ import type { ColumnData, ColumnDataMap } from "./view-reader"; import { formatLevelValue } from "../charts/common/category-axis-resolver"; -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import type { DateFormatModifiers } from "@perspective-dev/viewer"; export interface LastGroupBySplit { columns: ColumnDataMap; diff --git a/packages/viewer-charts/src/ts/layout/ticks.ts b/packages/viewer-charts/src/ts/layout/ticks.ts index 2cbf09287b..fe87fc55a6 100644 --- a/packages/viewer-charts/src/ts/layout/ticks.ts +++ b/packages/viewer-charts/src/ts/layout/ticks.ts @@ -10,7 +10,12 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import type { DateFormatModifiers } from "@perspective-dev/viewer/column-format"; +import type { + DateFormatConfig, + DateFormatModifiers, + Formatter, +} from "@perspective-dev/viewer"; +import { plugin_utils } from "../plugin_utils.ts"; function niceNum(value: number, round: boolean): number { const exp = Math.floor(Math.log10(value)); @@ -127,53 +132,42 @@ export function formatTickValue(val: number): string { } /** - * Cached `Intl.DateTimeFormat` per option shape. `Date.prototype. - * toLocale*` constructs a fresh `DateTimeFormat` (plus its ICU - * backing) on EVERY call — ~30µs each — which turned per-row label - * synthesis over large pivots into a multi-second stall. A cached - * formatter's `format()` is ~1µs. Keyed by precision tier and date options; the - * default locale is fixed for the lifetime of the worker, so entries - * never invalidate. + * Cached formatter per option shape, as building one parses its options. + * Keyed by precision tier and date options; the locale is fixed for the + * lifetime of the worker, so entries never invalidate. */ -const DATE_FORMAT_CACHE = new Map(); +const DATE_FORMAT_CACHE = new Map(); function cachedDateFormat( tier: string, - options: Intl.DateTimeFormatOptions, + options: DateFormatConfig, modifiers?: DateFormatModifiers, -): Intl.DateTimeFormat { +): Formatter { const key = `${tier}|${modifiers?.timeZone ?? ""}|${modifiers?.hour12 ?? ""}`; let fmt = DATE_FORMAT_CACHE.get(key); if (!fmt) { - fmt = new Intl.DateTimeFormat(undefined, { ...options, ...modifiers }); + fmt = plugin_utils().formatter("datetime", { + ...options, + ...modifiers, + })!; + DATE_FORMAT_CACHE.set(key, fmt); } return fmt; } -/** - * Format a timestamp (ms since epoch) as a human-readable date/time label. - * Adapts precision based on the tick spacing. - */ -export function formatDateTickValue( - val: number, +/** The formatter whose precision suits ticks `stepMs` apart, date-only without a step. */ +function dateTickFormatter( stepMs?: number, modifiers?: DateFormatModifiers, -): string { - const d = new Date(val); - if (isNaN(d.getTime())) { - return formatTickValue(val); - } - - // If step is provided, choose precision based on tick interval +): Formatter { if (stepMs !== undefined && stepMs > 0) { const DAY = 86_400_000; const HOUR = 3_600_000; const MINUTE = 60_000; if (stepMs >= DAY * 28) { - // Monthly or longer — show year-month return cachedDateFormat( "ym", { @@ -181,11 +175,10 @@ export function formatDateTickValue( month: "short", }, modifiers, - ).format(d); + ); } if (stepMs >= DAY) { - // Daily — show month and day return cachedDateFormat( "md", { @@ -193,11 +186,10 @@ export function formatDateTickValue( day: "numeric", }, modifiers, - ).format(d); + ); } if (stepMs >= HOUR) { - // Hourly return cachedDateFormat( "mdh", { @@ -206,11 +198,10 @@ export function formatDateTickValue( hour: "numeric", }, modifiers, - ).format(d); + ); } if (stepMs >= MINUTE) { - // Minutes return cachedDateFormat( "hm", { @@ -218,10 +209,9 @@ export function formatDateTickValue( minute: "2-digit", }, modifiers, - ).format(d); + ); } - // Sub-minute return cachedDateFormat( "hms", { @@ -230,10 +220,9 @@ export function formatDateTickValue( second: "2-digit", }, modifiers, - ).format(d); + ); } - // Default: show date only return cachedDateFormat( "ymd", { @@ -242,5 +231,40 @@ export function formatDateTickValue( day: "numeric", }, modifiers, - ).format(d); + ); +} + +/** + * Format a timestamp (ms since epoch) as a human-readable date/time label. + * Adapts precision based on the tick spacing. + */ +export function formatDateTickValue( + val: number, + stepMs?: number, + modifiers?: DateFormatModifiers, +): string { + if (isNaN(new Date(val).getTime())) { + return formatTickValue(val); + } + + return dateTickFormatter(stepMs, modifiers).format(val); +} + +/** {@link formatDateTickValue} over every one of `vals` in one call. */ +export function formatDateTickValues( + vals: number[], + stepMs?: number, + modifiers?: DateFormatModifiers, +): string[] { + const out = dateTickFormatter(stepMs, modifiers).format_strings( + new Float64Array(vals), + ); + + for (let i = 0; i < vals.length; i++) { + if (isNaN(new Date(vals[i]).getTime())) { + out[i] = formatTickValue(vals[i]); + } + } + + return out; } diff --git a/packages/viewer-charts/src/ts/plugin/format-defaults.ts b/packages/viewer-charts/src/ts/plugin/format-defaults.ts index f486ea38b6..a4122bc620 100644 --- a/packages/viewer-charts/src/ts/plugin/format-defaults.ts +++ b/packages/viewer-charts/src/ts/plugin/format-defaults.ts @@ -13,7 +13,7 @@ import type { DateFormatConfig, NumberFormatConfig, -} from "@perspective-dev/viewer/column-format"; +} from "@perspective-dev/viewer"; /** * The chart plugin's default per-column formats, declared to the viewer in diff --git a/packages/viewer-charts/src/ts/plugin_utils.ts b/packages/viewer-charts/src/ts/plugin_utils.ts new file mode 100644 index 0000000000..f889c505dc --- /dev/null +++ b/packages/viewer-charts/src/ts/plugin_utils.ts @@ -0,0 +1,26 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { NativeUtils } from "@perspective-dev/viewer"; + +let UTILS: NativeUtils | undefined; + +/** Supply the viewer's wasm module as the shared plugin code where no `` class exists, as in a `Worker`. */ +export function bind_plugin_utils(utils: NativeUtils): void { + UTILS = utils; +} + +/** The part of the code `` shares with its plugins that also runs in a `Worker`. */ +export function plugin_utils(): NativeUtils { + UTILS ??= customElements.get("perspective-viewer").plugin_utils; + return UTILS; +} diff --git a/packages/viewer-charts/src/ts/theme/gradient.ts b/packages/viewer-charts/src/ts/theme/gradient.ts index 398dab6348..824bc34e1a 100644 --- a/packages/viewer-charts/src/ts/theme/gradient.ts +++ b/packages/viewer-charts/src/ts/theme/gradient.ts @@ -11,6 +11,7 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import { parseCSSColorToVec3, vec3ToHexColor } from "../utils/css.ts"; +import { plugin_utils } from "../plugin_utils.ts"; /** * A single stop on a parsed CSS gradient. `offset` ∈ [0, 1]. @@ -185,134 +186,10 @@ export function parseCssGradient( export function parseCssColorStrict( src: string, ): [number, number, number] | null { - const s = src.trim(); - if (s.startsWith("#")) { - const hex = s.slice(1); - if (!/^[0-9a-f]+$/i.test(hex)) { - return null; - } - - if (hex.length === 3 || hex.length === 4) { - return [ - parseInt(hex[0] + hex[0], 16) / 255, - parseInt(hex[1] + hex[1], 16) / 255, - parseInt(hex[2] + hex[2], 16) / 255, - ]; - } - - if (hex.length === 6 || hex.length === 8) { - return [ - parseInt(hex.slice(0, 2), 16) / 255, - parseInt(hex.slice(2, 4), 16) / 255, - parseInt(hex.slice(4, 6), 16) / 255, - ]; - } - - return null; - } - - const m = s.match(/^rgba?\(([^)]*)\)$/i); - if (!m) { - return null; - } - - const tokens = m[1] - .split("/")[0] - .split(/[\s,]+/) - .filter((x) => x.length > 0); - if (tokens.length < 3 || tokens.length > 4) { - return null; - } - - const channel = (token: string): number | null => { - const pct = token.endsWith("%"); - const n = parseFloat(pct ? token.slice(0, -1) : token); - if (!isFinite(n)) { - return null; - } - - const v = pct ? (n / 100) * 255 : n; - return Math.max(0, Math.min(255, Math.round(v))) / 255; - }; - - const r = channel(tokens[0]); - const g = channel(tokens[1]); - const b = channel(tokens[2]); - return r === null || g === null || b === null ? null : [r, g, b]; -} - -/** - * The shared `linear-gradient(...)` tokenizer of the viewer's CSS-valued - * config grammar. - */ -export function tokenizeLinearGradient( - src: string, -): Array<[[number, number, number], number | null]> | null { - const m = src.trim().match(/^linear-gradient\s*\((.*)\)$/is); - if (!m) { - return null; - } - - const body = m[1]; - const parts: string[] = []; - let depth = 0; - let start = 0; - for (let i = 0; i < body.length; i++) { - const ch = body[i]; - if (ch === "(") { - depth++; - } else if (ch === ")") { - depth--; - } else if (ch === "," && depth === 0) { - parts.push(body.substring(start, i)); - start = i + 1; - } - } - - parts.push(body.substring(start)); - const out: Array<[[number, number, number], number | null]> = []; - for (let i = 0; i < parts.length; i++) { - const piece = parts[i].trim(); - if (!piece) { - return null; - } - - const lower = piece.toLowerCase(); - if ( - i === 0 && - (lower.startsWith("to ") || - /^[-\d.]+(deg|rad|grad|turn)$/.test(lower)) - ) { - continue; - } - - const posMatch = piece.match(/\s([^\s)]+)$/); - let color = piece; - let offset: number | null = null; - if (posMatch) { - const tail = posMatch[1]; - if (tail.endsWith("%")) { - const n = parseFloat(tail.slice(0, -1)); - if (!isFinite(n)) { - return null; - } - - color = piece.substring(0, posMatch.index).trim(); - offset = n / 100; - } else if (/^[-\d.]/.test(tail)) { - return null; - } - } - - const rgb = parseCssColorStrict(color); - if (!rgb) { - return null; - } - - out.push([rgb, offset]); - } - - return out; + const rgb = plugin_utils().parse_css_color(src); + return rgb === undefined + ? null + : [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255]; } /** @@ -321,48 +198,13 @@ export function tokenizeLinearGradient( * on malformed input. */ export function parseCssGradientStrict(src: string): GradientStop[] | null { - const entries = tokenizeLinearGradient(src); - if (!entries || entries.length < 2) { - return null; - } - - const offsets: Array = entries.map(([, p]) => p); - const last = offsets.length - 1; - if (offsets[0] === null) { - offsets[0] = 0; - } - - if (offsets[last] === null) { - offsets[last] = 1; - } - - for (let i = 1; i < last; i++) { - if (offsets[i] !== null) { - continue; - } - - let j = i + 1; - while (offsets[j] === null) { - j++; - } - - const before = offsets[i - 1]!; - const after = offsets[j]!; - const span = j - (i - 1); - for (let k = i; k < j; k++) { - offsets[k] = before + ((k - (i - 1)) / span) * (after - before); - } - - i = j - 1; - } - - const stops: GradientStop[] = entries.map(([rgb], i) => ({ - offset: Math.max(0, Math.min(1, offsets[i]!)), - color: [rgb[0], rgb[1], rgb[2], 1], - })); - - stops.sort((a, b) => a.offset - b.offset); - return stops; + const stops = plugin_utils().parse_css_gradient(src); + return ( + stops?.map(({ rgb, offset }) => ({ + offset, + color: [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255, 1], + })) ?? null + ); } /** @@ -372,26 +214,10 @@ export function parseCssGradientStrict(src: string): GradientStop[] | null { export function parseCssColorList( src: string, ): Array<[number, number, number]> | null { - const entries = tokenizeLinearGradient(src); - if (!entries || entries.length === 0) { - return null; - } - - const out: Array<[number, number, number]> = []; - for (const [rgb, offset] of entries) { - if (offset !== null) { - return null; - } - - out.push(rgb); - } - - return out; -} - -function formatPercent(offset: number): string { - const rounded = Math.round(Math.max(0, Math.min(1, offset)) * 1000) / 10; - return `${rounded}%`; + const colors = plugin_utils().parse_css_palette(src); + return ( + colors?.map((rgb) => [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255]) ?? null + ); } /** @@ -399,15 +225,16 @@ function formatPercent(offset: number): string { * right, #rrggbb P%, …)`, sorted, positions at 0.1% resolution. */ export function stopsToCss(stops: GradientStop[]): string { - const body = [...stops] - .sort((a, b) => a.offset - b.offset) - .map( - (stop) => - `${vec3ToHexColor([stop.color[0], stop.color[1], stop.color[2]])} ${formatPercent(stop.offset)}`, - ) - .join(", "); - - return `linear-gradient(to right, ${body})`; + return plugin_utils().css_gradient( + stops.map((stop) => ({ + color: vec3ToHexColor([ + stop.color[0], + stop.color[1], + stop.color[2], + ]), + offset: stop.offset, + })), + ); } /** @@ -415,7 +242,7 @@ export function stopsToCss(stops: GradientStop[]): string { * with bare `#rrggbb` entries and no positions. */ export function colorsToCss(colors: Array<[number, number, number]>): string { - return `linear-gradient(to right, ${colors.map(vec3ToHexColor).join(", ")})`; + return plugin_utils().css_palette(colors.map(vec3ToHexColor)); } /** diff --git a/packages/viewer-charts/src/ts/worker/renderer.worker.ts b/packages/viewer-charts/src/ts/worker/renderer.worker.ts index eede65a145..3241babeef 100644 --- a/packages/viewer-charts/src/ts/worker/renderer.worker.ts +++ b/packages/viewer-charts/src/ts/worker/renderer.worker.ts @@ -38,6 +38,7 @@ import { viewToColumnDataMap } from "../data/view-reader.ts"; import { TILE_SOURCES, type TileSourceSpec } from "../map/tile-source.ts"; import { loadFontDeduped } from "./font-loader.ts"; import { installSessionHost } from "./session-host.ts"; +import { bind_plugin_utils } from "../plugin_utils.ts"; import { deferIfDraining, unregister } from "../render/scheduler.ts"; /** @@ -853,6 +854,7 @@ async function bootstrapWorker( )) as typeof wasm_module_type; await module.initSync({ module: msg.clientWasm }); + bind_plugin_utils(module); // Register every `@font-face` the host found in its document so // Canvas2D `ctx.font` lookups inside this worker resolve correctly. diff --git a/packages/viewer-datagrid/src/css/regular_table.css b/packages/viewer-datagrid/src/css/regular_table.css index a43937b0cf..716a8ffb2c 100644 --- a/packages/viewer-datagrid/src/css/regular_table.css +++ b/packages/viewer-datagrid/src/css/regular_table.css @@ -568,67 +568,3 @@ regular-table table tbody tr:hover:not(:first-child):after { regular-table table tbody tr:hover + tr:after { border-top: 1px solid var(--psp-datagrid--hover--border-color); } - -@keyframes pulse_pos { - 0% { - background-color: var( - --pulse--background-color-start, - rgba(0, 128, 255, 0.5) - ); - } - - 100% { - background-color: var( - --pulse--background-color-end, - rgba(0, 128, 255, 0) - ); - } -} - -@keyframes pulse_pos2 { - 0% { - background-color: var( - --pulse--background-color-start, - rgba(0, 128, 255, 0.5) - ); - } - - 100% { - background-color: var( - --pulse--background-color-end, - rgba(0, 128, 255, 0) - ); - } -} - -@keyframes pulse_neg { - 0% { - background-color: var( - --pulse--background-color-start, - rgba(255, 25, 0, 0.5) - ); - } - - 100% { - background-color: var( - --pulse--background-color-end, - rgba(255, 25, 0, 0) - ); - } -} - -@keyframes pulse_neg2 { - 0% { - background-color: var( - --pulse--background-color-start, - rgba(255, 25, 0, 0.5) - ); - } - - 100% { - background-color: var( - --pulse--background-color-end, - rgba(255, 25, 0, 0) - ); - } -} diff --git a/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts b/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts index 474223d6da..00a43e8f3e 100644 --- a/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts +++ b/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts @@ -12,7 +12,6 @@ import { PRIVATE_PLUGIN_SYMBOL, - readThemeStyle, reconcile_column_widths, width_config_delta, } from "../model/index.ts"; @@ -22,15 +21,14 @@ import { save } from "../plugin/save.ts"; import { hit_test } from "../plugin/hit_test.ts"; import { command_scopes_changed } from "../commands.ts"; import { draw } from "../plugin/draw.ts"; -import column_config_schema, { - ColumnConfigSchema, -} from "../plugin/column_config_schema.ts"; +import column_config_schema from "../plugin/column_config_schema.ts"; import plugin_config_schema from "../plugin/plugin_config_schema.ts"; import datagridStyles from "../../../dist/css/perspective-viewer-datagrid.css"; -import { format_raw } from "../data_listener/format_cell.ts"; +import { plugin_utils } from "../plugin_utils.ts"; import type { ColumnWindow, View, ViewWindow } from "@perspective-dev/client"; import type { + ColumnConfigSchema, HTMLPerspectiveViewerElement, IPerspectiveViewerPlugin, PerspectiveHitTest, @@ -49,7 +47,6 @@ import type { } from "../types.ts"; import { RegularTableElement } from "regular-table"; import type { CellScalar } from "regular-table/dist/esm/types.js"; -import { isMetaColumn } from "../model/meta_columns.ts"; /** * The custom element class for this plugin. The interface methods for this @@ -148,7 +145,9 @@ export class HTMLPerspectiveViewerDatagridPluginElement const Elem = HTMLPerspectiveViewerDatagridPluginElement; if (!Elem._sheet) { Elem._sheet = new CSSStyleSheet(); - Elem._sheet.replaceSync(datagridStyles); + Elem._sheet.replaceSync( + plugin_utils().cell_style.css + datagridStyles, + ); } const shadow = this.attachShadow({ mode: "open" }); @@ -205,6 +204,7 @@ export class HTMLPerspectiveViewerDatagridPluginElement // loaded by default. priority: 1, can_render_column_styles: true, + renders_text: true, }; } @@ -274,8 +274,9 @@ export class HTMLPerspectiveViewerDatagridPluginElement >, ]); + const utils = plugin_utils(); const keys = Object.keys(json as Record).filter( - (x) => !isMetaColumn(x), + (x) => !utils.column_style.isMetaColumn(x), ); const names = area[area.length - 1] ?? []; @@ -293,19 +294,33 @@ export class HTMLPerspectiveViewerDatagridPluginElement const formatters = keys.map((_, cidx) => { const name = String(names[cidx] ?? ""); - return format_raw( + return utils.format.format_raw( this.model!._schema[name], pluginConfig?.[name] || {}, ); }); + const columns = keys.map( + (key) => (json as Record)[key], + ); + + const texts = formatters.map( + (formatter, cidx) => + formatter && + formatter.format_strings( + new Float64Array(columns[cidx] as number[]), + ), + ); + let out = ""; for (let ridx = 0; ridx < nrows; ridx++) { for (let cidx = 0; cidx < keys.length; cidx++) { - const col = (json as Record)[keys[cidx]]; + const col = columns[cidx]; const formatter = formatters[cidx]; - if (formatter) { - out += formatter.format(col[ridx]) + "\t"; + if (formatter && ridx < col.length) { + out += texts[cidx]![ridx] + "\t"; + } else if (formatter) { + out += formatter.format(col[ridx] as number) + "\t"; } else { out += col[ridx] + "\t"; } @@ -404,11 +419,18 @@ export class HTMLPerspectiveViewerDatagridPluginElement return; } - Object.assign(this.model, readThemeStyle(this.regular_table)); + Object.assign( + this.model, + plugin_utils().theme_style.readThemeStyle(this.regular_table), + ); sync_wrap_lines.call(this); } delete(): void { + plugin_utils().format.free_formatters( + (this.regular_table as any)[PRIVATE_PLUGIN_SYMBOL] ?? {}, + ); + this.disconnectedCallback(); this._toolbar = undefined; if ((this.regular_table as any).table_model) { diff --git a/packages/viewer-datagrid/src/ts/data_listener/format_cell.ts b/packages/viewer-datagrid/src/ts/data_listener/format_cell.ts index 308ee7ac8f..1924e9d7cf 100644 --- a/packages/viewer-datagrid/src/ts/data_listener/format_cell.ts +++ b/packages/viewer-datagrid/src/ts/data_listener/format_cell.ts @@ -10,22 +10,37 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import { FormatterCache, Formatter } from "./formatter_cache.ts"; +import { plugin_utils } from "../plugin_utils.ts"; import type { - ColumnConfig, DatagridModel, ResolvedColumnsConfig, ResolvedColumnStyle, } from "../types.ts"; import type { ColumnType } from "@perspective-dev/client"; -const FORMAT_CACHE = new FormatterCache(); +/** The type of column `title`, by the table's schema first when `use_table_schema`. */ +function column_type( + model: DatagridModel, + title: string, + use_table_schema: boolean, +): ColumnType { + return ((use_table_schema && model._table_schema[title]) || + model._schema[title] || + model._window_schema?.[title] || + "string") as ColumnType; +} -export function format_raw( +/** Whether cells of `type` styled by `plugin` draw a bar in place of text. */ +function is_bar( type: ColumnType, - value: Pick, -): Formatter | false | undefined { - return FORMAT_CACHE.get(type, value); + plugin: ResolvedColumnStyle, + use_table_schema: boolean, +): boolean { + return ( + (type === "integer" || type === "float") && + !use_table_schema && + (plugin.fg_mode === "bar" || plugin.fg_mode === "label-bar") + ); } /** @@ -42,18 +57,9 @@ export function format_cell( return null; } - const type: ColumnType = ((use_table_schema && this._table_schema[title]) || - this._schema[title] || - this._window_schema?.[title] || - "string") as ColumnType; + const type = column_type(this, title, use_table_schema); const plugin: ResolvedColumnStyle = plugins[title] || {}; - const is_numeric = type === "integer" || type === "float"; - - if ( - is_numeric && - !use_table_schema && - (plugin.fg_mode === "bar" || plugin.fg_mode === "label-bar") - ) { + if (is_bar(type, plugin, use_table_schema)) { return ""; } else if (plugin?.link === true && type === "string") { const anchor = document.createElement("a"); @@ -66,7 +72,44 @@ export function format_cell( // column type falling back to `"string"`), a raw non-string value // must not leak into consumers that expect text - see the // `{ toString }` wrapper in `format_tree_header.ts`. - const formatter = FORMAT_CACHE.get(type, plugin); - return formatter ? formatter.format(val) : String(val); + const formatter = plugin_utils().format.format_raw(type, plugin); + return formatter ? formatter.format(val as number) : String(val); + } +} + +/** + * Format every cell of `column` as `format_cell` does, in one call to the + * column's formatter when it has one. + */ +export function format_column( + this: DatagridModel, + title: string, + column: unknown[], + plugins: ResolvedColumnsConfig = {}, +): (string | HTMLElement | null)[] { + const type = column_type(this, title, false); + const plugin: ResolvedColumnStyle = plugins[title] || {}; + const formatter = is_bar(type, plugin, false) + ? undefined + : plugin_utils().format.format_raw(type, plugin); + + if (formatter === undefined) { + return column.map((x) => format_cell.call(this, title, x, plugins)); + } + + const values: number[] = []; + for (let i = 0; i < column.length; i++) { + if (column[i] !== null) { + values.push(column[i] as number); + } } + + const texts = formatter.format_strings(new Float64Array(values)); + const out = new Array(column.length); + let next = 0; + for (let i = 0; i < column.length; i++) { + out[i] = column[i] === null ? null : texts[next++]; + } + + return out; } diff --git a/packages/viewer-datagrid/src/ts/data_listener/formatter_cache.ts b/packages/viewer-datagrid/src/ts/data_listener/formatter_cache.ts deleted file mode 100644 index 98a0e61cd9..0000000000 --- a/packages/viewer-datagrid/src/ts/data_listener/formatter_cache.ts +++ /dev/null @@ -1,104 +0,0 @@ -// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ -// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ -// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ -// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ -// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ -// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ -// ┃ Copyright (c) 2017, the Perspective Authors. ┃ -// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ -// ┃ This file is part of the Perspective library, distributed under the terms ┃ -// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ -// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ - -import type { ColumnType } from "@perspective-dev/client"; -import { - createDateFormatter, - createDatetimeFormatter, - createNumberFormatter, -} from "@perspective-dev/viewer/column-format"; -import type { ColumnConfig } from "../types.ts"; - -export interface Formatter { - format(val: unknown): string; -} - -class BooleanFormatter implements Formatter { - format(val: unknown): string { - return val ? "true" : "false"; - } -} - -// PluginConfig is a subset of ColumnConfig with the formatting properties -type PluginConfig = Pick; - -export class FormatterCache { - private _formatters: Map; - - constructor() { - this._formatters = new Map(); - } - - private create_datetime_formatter( - _type: ColumnType, - plugin: PluginConfig, - ): Intl.DateTimeFormat { - return createDatetimeFormatter(plugin.date_format); - } - - private create_date_formatter( - _type: ColumnType, - plugin: PluginConfig, - ): Intl.DateTimeFormat { - return createDateFormatter(plugin.date_format); - } - - private create_number_formatter( - type: ColumnType, - plugin: PluginConfig, - ): Intl.NumberFormat { - return createNumberFormatter(type, plugin.number_format); - } - - private create_boolean_formatter( - _type: ColumnType, - _plugin: PluginConfig, - ): Formatter { - return new BooleanFormatter(); - } - - get(type: ColumnType, plugin: PluginConfig): Formatter | false | undefined { - const formatter_key = JSON.stringify([ - type, - plugin.date_format ?? null, - plugin.number_format ?? null, - ]); - - if (!this._formatters.has(formatter_key)) { - if (type === "date") { - this._formatters.set( - formatter_key, - this.create_date_formatter(type, plugin), - ); - } else if (type === "datetime") { - this._formatters.set( - formatter_key, - this.create_datetime_formatter(type, plugin), - ); - } else if (type === "integer" || type === "float") { - this._formatters.set( - formatter_key, - this.create_number_formatter(type, plugin), - ); - } else if (type === "boolean") { - this._formatters.set( - formatter_key, - this.create_boolean_formatter(type, plugin), - ); - } else { - this._formatters.set(formatter_key, false); - } - } - - return this._formatters.get(formatter_key); - } -} diff --git a/packages/viewer-datagrid/src/ts/data_listener/index.ts b/packages/viewer-datagrid/src/ts/data_listener/index.ts index d394ef8720..c66fb7fda1 100644 --- a/packages/viewer-datagrid/src/ts/data_listener/index.ts +++ b/packages/viewer-datagrid/src/ts/data_listener/index.ts @@ -11,7 +11,7 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import { PRIVATE_PLUGIN_SYMBOL } from "../types.ts"; -import { isMetaColumn } from "../model/meta_columns.ts"; +import { plugin_utils } from "../plugin_utils.ts"; import { reconcile_column_widths } from "../model/column_overrides.ts"; import { column_name, @@ -19,7 +19,7 @@ import { write_area, write_flat_area, } from "../model/column_path_area.ts"; -import { format_cell } from "./format_cell.ts"; +import { format_column } from "./format_cell.ts"; import { COMMAND_COLUMN_PATH, build_frame, @@ -146,6 +146,7 @@ export function createDataListener( // `__ID__` (the previous filter) misses the per-level // form and the virtual server's columns leak into the // visible grid. + const { isMetaColumn } = plugin_utils().column_style; const new_col_paths = y.filter((x) => !isMetaColumn(x)); let changed_cols = false; @@ -377,18 +378,20 @@ export function createDataListener( this._config.group_by.length, ); + const formatted = format_column.call( + this, + name, + column, + columns_config, + ); + data.push( - column.map((x, i) => { + column.map((_, i) => { if ((columns?.__ROW_PATH__?.[i]?.length ?? 0) < agg_depth) { return ""; } - const cell = format_cell.call( - this, - name, - x, - columns_config, - ) as string | HTMLElement; + const cell = formatted[i] as string | HTMLElement; const content = wrap ? wrap_cell(cell) : cell; if (!cell_results || i >= n_fetched) { diff --git a/packages/viewer-datagrid/src/ts/get_cell_config.ts b/packages/viewer-datagrid/src/ts/get_cell_config.ts index dc4bb13e50..3a7c46dca5 100644 --- a/packages/viewer-datagrid/src/ts/get_cell_config.ts +++ b/packages/viewer-datagrid/src/ts/get_cell_config.ts @@ -12,7 +12,7 @@ import type { View, ViewConfig, Filter, Scalar } from "@perspective-dev/client"; import type { CellConfigResult } from "./types.ts"; -import { isMetaColumn } from "./model/meta_columns.ts"; +import { plugin_utils } from "./plugin_utils.ts"; interface ModelWithViewAndConfig { _view: View; @@ -54,6 +54,7 @@ export default async function getCellConfig( // `__ROW_PATH__` sidecar, so the previous `+1` skip (which // assumed exactly one leading meta column) lands on a meta key // when group_by has multiple levels. + const { isMetaColumn } = plugin_utils().column_style; const user_keys = Object.keys(r[0]).filter((k) => !isMetaColumn(k)); const column_paths = col_idx === undefined ? undefined : user_keys[col_idx]; const result: CellConfigResult = { diff --git a/packages/viewer-datagrid/src/ts/model/create.ts b/packages/viewer-datagrid/src/ts/model/create.ts index a9beaba318..f6243f8263 100644 --- a/packages/viewer-datagrid/src/ts/model/create.ts +++ b/packages/viewer-datagrid/src/ts/model/create.ts @@ -11,13 +11,7 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import { createDataListener } from "../data_listener/index.ts"; -import { - blend, - make_color_record, - parseColor, - rgbToHex, - type RGB, -} from "../color_utils.ts"; +import { plugin_utils } from "../plugin_utils.ts"; import type { ColumnType, Table, @@ -102,111 +96,6 @@ function nestedArraysChanged(a: T[][], b: T[][]): boolean { return false; } -const UNSET_COLOR = "rgba(0, 0, 0, 0)"; - -function get_rule(regular: HTMLElement, tag: string, def: string): string { - const color = window.getComputedStyle(regular).getPropertyValue(tag).trim(); - if (color.length > 0 && color !== UNSET_COLOR) { - return color; - } else { - return def; - } -} - -export type ThemeStyle = Pick< - DatagridModel, - | "_theme" - | "_plugin_background" - | "_color" - | "_pos_fg_color" - | "_neg_fg_color" - | "_pos_bg_color" - | "_neg_bg_color" - | "_default_bg_color_stops" - | "_series_palette" ->; - -function read_series_palette(regular: HTMLElement, accent: string): string[] { - const walk = (prefix: string): string[] => { - const out: string[] = []; - for (let i = 1; ; i++) { - const raw = get_rule(regular, `${prefix}${i}--color`, ""); - if (!raw) { - break; - } - - out.push(rgbToHex(parseColor(raw))); - } - - return out; - }; - - const own = walk("--psp-datagrid--series-"); - if (own.length > 0) { - return own; - } - - const charts = walk("--psp-charts--series-"); - return charts.length > 0 ? charts : [rgbToHex(parseColor(accent))]; -} - -/** - * Read the theme-derived style values off `regular`'s computed style, the - * single source for the color/theme fields cached on `DatagridModel`. - */ -export function readThemeStyle(regular: HTMLElement): ThemeStyle { - const _theme = get_rule(regular, "--psp-theme-name", ""); - const _plugin_background = parseColor( - get_rule(regular, "--psp--background-color", "#FFFFFF"), - ); - - const _pos_fg_color = make_color_record( - get_rule(regular, "--psp-datagrid--pos-cell--color", "#338DCD"), - ); - - const _neg_fg_color = make_color_record( - get_rule(regular, "--psp-datagrid--neg-cell--color", "#FF5942"), - ); - - const _pos_bg_color = make_color_record( - blend(_pos_fg_color[0], _plugin_background), - ); - - const _neg_bg_color = make_color_record( - blend(_neg_fg_color[0], _plugin_background), - ); - - const _color = make_color_record( - get_rule(regular, "--psp-active--color", "#ff0000"), - ); - - const _series_palette = read_series_palette(regular, _color[0]); - - const _default_bg_color_stops = [ - { - rgb: [_neg_bg_color[1], _neg_bg_color[2], _neg_bg_color[3]] as RGB, - offset: 0, - }, - { rgb: _plugin_background as RGB, offset: 0.5 }, - { - rgb: [_pos_bg_color[1], _pos_bg_color[2], _pos_bg_color[3]] as RGB, - offset: 1, - }, - ]; - - return { - _theme, - _plugin_background, - _color, - _pos_fg_color, - _neg_fg_color, - _pos_bg_color, - _neg_bg_color, - _default_bg_color_stops, - _series_palette, - }; -} - export async function createModel( this: DatagridPluginElement, regular: RegularTable, @@ -215,7 +104,7 @@ export async function createModel( extend: Partial = {}, ): Promise { const config = (await view.get_config()) as ViewConfig; - const style = readThemeStyle(regular); + const style = plugin_utils().theme_style.readThemeStyle(regular); if (this?.model?._config) { const old = this.model._config; const group_by_changed = arraysChanged(old.group_by, config.group_by); diff --git a/packages/viewer-datagrid/src/ts/model/index.ts b/packages/viewer-datagrid/src/ts/model/index.ts index 227430f8fa..a901880a31 100644 --- a/packages/viewer-datagrid/src/ts/model/index.ts +++ b/packages/viewer-datagrid/src/ts/model/index.ts @@ -11,7 +11,7 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ export { PRIVATE_PLUGIN_SYMBOL } from "../types.ts"; -export { createModel, readThemeStyle } from "./create.ts"; +export { createModel } from "./create.ts"; export { toggle_edit_mode, toggle_scroll_lock } from "./toolbar.ts"; export { reconcile_column_widths, diff --git a/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts b/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts index a991404890..035844a426 100644 --- a/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts +++ b/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts @@ -11,22 +11,14 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import type { ColumnType } from "@perspective-dev/client"; -import { colorsToCss, rgbToHex, stopsToCss } from "../color_utils.ts"; -import { readThemeStyle } from "../model/create.ts"; -import { measure_px, parse_align } from "./plugin_config_schema.ts"; +import type { ColumnConfigSchema, ControlSpec } from "@perspective-dev/viewer"; +import { plugin_utils } from "../plugin_utils.ts"; +import { measure_px } from "./plugin_config_schema.ts"; import { positive_px } from "./restore.ts"; -import { - bg_modes_for, - default_bg_mode, - default_fg_mode, - fg_modes_for, - parse_bg_mode, - parse_fg_mode, - type BgMode, - type ColumnConfig, - type ColumnRole, - type DatagridPluginElement, - type FgMode, +import type { + ColumnConfig, + ColumnRole, + DatagridPluginElement, } from "../types.ts"; interface ViewerConfigLike { @@ -35,30 +27,10 @@ interface ViewerConfigLike { group_rollup_mode?: string; } -type ControlSpec = Record & { kind: string }; - -export interface ColumnConfigSchema { - fields: ControlSpec[]; -} - /** * Plugin schema for the Datagrid column-settings sidebar. Returns the * controls the viewer should render in the Style tab for a given column. */ -/** - * A column's `date_format` / `number_format` controls, which are the only ones - * that apply to a value rendered as a pivot label rather than a cell. - */ -function format_fields(type: ColumnType): ControlSpec[] { - if (type === "integer" || type === "float") { - return [{ kind: "NumberFormat" }]; - } else if (type === "date" || type === "datetime") { - return [{ kind: "DatetimeFormat" }]; - } - - return []; -} - export default function column_config_schema( this: DatagridPluginElement, type: ColumnType, @@ -69,8 +41,9 @@ export default function column_config_schema( plugin_config?: Record | null, role?: ColumnRole, ): ColumnConfigSchema { + const { schema, theme_style } = plugin_utils(); if (role === "group_by" || role === "split_by") { - return { fields: format_fields(type) }; + return { fields: schema.format_fields(type) }; } const grid = @@ -91,7 +64,7 @@ export default function column_config_schema( font_size: positive_px(plugin_config.font_size), bold: plugin_config.bold === true, italic: plugin_config.italic === true, - align: parse_align(plugin_config.align), + align: schema.parse_align(plugin_config.align), word_wrap: plugin_config.word_wrap === true, }; @@ -159,28 +132,17 @@ export default function column_config_schema( ], }); - const fg_modes = fg_modes_for(type); - const bg_modes = bg_modes_for(type); - if (fg_modes.length > 0 || bg_modes.length > 0) { - const fg_mode = - parse_fg_mode(type, current_value?.fg_mode) ?? - default_fg_mode(type); - - const bg_mode = - parse_bg_mode(type, current_value?.bg_mode) ?? - default_bg_mode(type); + const colors = schema.color_group( + type, + current_value, + () => this.model ?? theme_style.readThemeStyle(this.regular_table), + ); - const color_fields: ControlSpec[] = [ - mode_spec("fg_mode", fg_modes, default_fg_mode(type)), - ...value_specs.call(this, type, "fg", fg_mode), - mode_spec("bg_mode", bg_modes, default_bg_mode(type)), - ...value_specs.call(this, type, "bg", bg_mode), - ]; - - fields.push({ kind: "Group", key: "color", fields: color_fields }); + if (colors !== undefined) { + fields.push(colors); } - fields.push(...format_fields(type)); + fields.push(...schema.format_fields(type)); if (type === "string") { fields.push({ kind: "Bool", @@ -191,108 +153,3 @@ export default function column_config_schema( return { fields }; } - -const MODE_LABELS: Record = { - disabled: "Disabled", - color: "Color", - bar: "Bar", - "label-bar": "Gradient", - gradient: "Gradient", - pulse: "Pulse", - series: "Series", -}; - -/** The `Enum` control for `fg_mode` / `bg_mode` over a type's modes. */ -function mode_spec( - key: "fg_mode" | "bg_mode", - modes: readonly (FgMode | BgMode)[], - default_mode: FgMode | BgMode, -): ControlSpec { - return { - kind: "Enum", - key: key satisfies keyof ColumnConfig, - default: default_mode, - variants: modes.map((value) => ({ value, label: MODE_LABELS[value] })), - }; -} - -/** - * The controls a foreground or background `mode` gates in for a column of - * `type`: the `fg_color` / `bg_color` value control in the grammar the - * (type, mode) pair reads - gradient stops for numbers, a color for - * string / datetime `"color"`, a palette for string `"series"` - plus the - * numeric scale extent. Nothing for `"disabled"`. - */ -function value_specs( - this: DatagridPluginElement, - type: ColumnType, - side: "fg" | "bg", - mode: FgMode | BgMode, -): ControlSpec[] { - if (mode === "disabled") { - return []; - } - - const theme = this.model ?? readThemeStyle(this.regular_table); - - const key = `${side}_color` satisfies keyof ColumnConfig; - if (type === "integer" || type === "float") { - const pos = theme[`_pos_${side}_color`][0]; - const neg = theme[`_neg_${side}_color`][0]; - const stops: ControlSpec = - mode === "gradient" || mode === "pulse" - ? { - kind: "GradientStops", - key, - default: stopsToCss([ - { color: neg, offset: 0 }, - { - color: rgbToHex( - theme._plugin_background as [ - number, - number, - number, - ], - ), - offset: 0.5, - }, - { color: pos, offset: 1 }, - ]), - } - : { - kind: "GradientStops", - key, - default: stopsToCss([ - { color: neg, offset: 0 }, - { color: pos, offset: 1 }, - ]), - discrete: true, - }; - - const scaled = - mode === "bar" || mode === "label-bar" || mode === "gradient"; - - return scaled - ? [ - stops, - { - kind: "Number", - key: `${side}_gradient` satisfies keyof ColumnConfig, - include: true, - default: 0, - default_stat: "abs_max", - }, - ] - : [stops]; - } else if (mode === "series") { - return [ - { - kind: "Palette", - key, - default: colorsToCss(theme._series_palette), - }, - ]; - } else { - return [{ kind: "Color", key, default: theme._color[0] }]; - } -} diff --git a/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts b/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts index e7a91941b7..da43ab0e33 100644 --- a/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts +++ b/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts @@ -10,30 +10,17 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import { mixRgb, parseColor, rgbToHex } from "../color_utils.ts"; +import type { ColumnConfigSchema } from "@perspective-dev/viewer"; +import { plugin_utils } from "../plugin_utils.ts"; import type { - Align, CommandColumn, DatagridPluginConfig, DatagridPluginElement, } from "../types.ts"; -import type { ColumnConfigSchema } from "./column_config_schema.ts"; import { is_command_scope } from "../commands.ts"; type ControlSpec = Record & { kind: string }; -export const ALIGNS: readonly Align[] = [ - "top-left", - "top", - "top-right", - "left", - "center", - "right", - "bottom-left", - "bottom", - "bottom-right", -]; - export const COMMAND_COLUMNS: readonly CommandColumn[] = [ "none", "left", @@ -48,29 +35,6 @@ export function parse_command_column(raw: unknown): CommandColumn { : "left"; } -/** An `align` value from a token, or `undefined` for anything else. */ -export function parse_align(raw: unknown): Align | undefined { - return ALIGNS.includes(raw as Align) ? (raw as Align) : undefined; -} - -/** CSS generic font families, which are never quoted when applied. */ -export const GENERIC_FONT_FAMILIES: readonly string[] = [ - "inherit", - "monospace", - "sans-serif", - "serif", - "system-ui", -]; - -/** The CSS `font-family` value for a `font_family` config value. */ -export function css_font_family(family: string): string { - if (GENERIC_FONT_FAMILIES.includes(family)) { - return family; - } - - return `"${family.replace(/["\\]/g, "\\$&")}"`; -} - /** Line height of a wrapped cell's block, as a multiple of its font size. */ export const WRAP_LINE_HEIGHT = 1.2; @@ -106,6 +70,7 @@ const UNSET_COLOR = "rgba(0, 0, 0, 0)"; * into background when the theme defines none. */ export function default_zebra_color(elem: Element): string { + const { mixRgb, parseColor, rgbToHex } = plugin_utils().color; const style = window.getComputedStyle(elem); const read = (name: string) => { const raw = style.getPropertyValue(name).trim(); diff --git a/packages/viewer-datagrid/src/ts/plugin/restore.ts b/packages/viewer-datagrid/src/ts/plugin/restore.ts index 334ca69423..b0857fda52 100644 --- a/packages/viewer-datagrid/src/ts/plugin/restore.ts +++ b/packages/viewer-datagrid/src/ts/plugin/restore.ts @@ -17,26 +17,15 @@ import { } from "../model/toolbar.ts"; import { PRIVATE_PLUGIN_SYMBOL } from "../model/index.ts"; import { - css_font_family, measure_px, - parse_align, parse_command_column, wrap_lines, } from "./plugin_config_schema.ts"; -import { - make_color_record, - parseCssColorList, - parseCssGradientStops, - rgbToHex, - type GradientStopRgb, -} from "../color_utils.ts"; +import { plugin_utils } from "../plugin_utils.ts"; import type { - ColumnConfig, - ColorRecord, ColumnsConfig, DatagridPluginElement, EditMode, - ResolvedColumnStyle, ResolvedColumnsConfig, } from "../types.ts"; @@ -117,6 +106,7 @@ function restore_grid_style( token: RestoreToken, columns: ColumnsConfig, ): boolean { + const { schema } = plugin_utils(); const font_before = [this._font_family, this._font_size]; const row_height_before = this._row_height; const column_font_before = column_font_state(this._columns_config); @@ -141,7 +131,7 @@ function restore_grid_style( this._command_cells = token.command_cells !== false; this._bold = token.bold === true; this._italic = token.italic === true; - this._align = parse_align(token.align); + this._align = schema.parse_align(token.align); this._row_height = positive_px(token.row_height); this._zebra_rows = Math.max( @@ -158,7 +148,9 @@ function restore_grid_style( set_grid_font( grid, "font-family", - this._font_family ? css_font_family(this._font_family) : undefined, + this._font_family + ? schema.css_font_family(this._font_family) + : undefined, ); set_grid_font( @@ -208,71 +200,6 @@ function restore_grid_style( ); } -/** - * Every parsed form of one `fg_color` / `bg_color` string. Column types - * are unknown here (`restore()` may run before the model exists), so each - * reader runs and the style handlers pick the form their mode needs. - */ -interface ParsedColor { - color?: ColorRecord; - stops?: GradientStopRgb[]; - palette?: string[]; -} - -function parse_color_value(raw: unknown): ParsedColor { - if (typeof raw !== "string") { - return {}; - } - - const stops = parseCssGradientStops(raw) ?? undefined; - const palette = parseCssColorList(raw)?.map(rgbToHex) ?? undefined; - return { - color: is_single_color(raw) ? make_color_record(raw) : undefined, - stops, - palette, - }; -} - -/** A bare CSS color, as opposed to a `linear-gradient(…)` list. */ -function is_single_color(raw: string): boolean { - return !raw.trim().toLowerCase().startsWith("linear-gradient("); -} - -function end_records( - stops: GradientStopRgb[] | undefined, -): [neg: ColorRecord | undefined, pos: ColorRecord | undefined] { - if (!stops) { - return [undefined, undefined]; - } - - return [ - make_color_record(rgbToHex(stops[0].rgb)), - make_color_record(rgbToHex(stops[stops.length - 1].rgb)), - ]; -} - -/** `config` with its color strings parsed into every form a handler reads. */ -function resolve_column_style(config: ColumnConfig): ResolvedColumnStyle { - const { fg_color, bg_color, ...rest } = config; - const fg = parse_color_value(fg_color); - const bg = parse_color_value(bg_color); - const [neg_fg_color, pos_fg_color] = end_records(fg.stops); - const [neg_bg_color, pos_bg_color] = end_records(bg.stops); - return { - ...rest, - fg_color: fg.color, - bg_color: bg.color, - fg_stops: fg.stops, - bg_stops: bg.stops, - pos_fg_color, - neg_fg_color, - pos_bg_color, - neg_bg_color, - fg_palette: fg.palette, - bg_palette: bg.palette, - }; -} - export function restore( this: DatagridPluginElement, token: RestoreToken, @@ -294,9 +221,10 @@ export function restore( } this._columns_config = structuredClone(columns); + const utils = plugin_utils(); const styles: ResolvedColumnsConfig = {}; for (const [col_name, controls] of Object.entries(columns)) { - styles[col_name] = resolve_column_style(controls); + styles[col_name] = utils.column_style.resolve_column_style(controls); } // `echo = false`: this `restore()` IS the host delivering the config — @@ -327,5 +255,9 @@ export function restore( }); } + utils.format.free_formatters( + (this.regular_table as any)[PRIVATE_PLUGIN_SYMBOL] ?? {}, + ); + (this.regular_table as any)[PRIVATE_PLUGIN_SYMBOL] = styles; } diff --git a/rust/perspective-client/src/rust/utils/talc_allocator.rs b/packages/viewer-datagrid/src/ts/plugin_utils.ts similarity index 83% rename from rust/perspective-client/src/rust/utils/talc_allocator.rs rename to packages/viewer-datagrid/src/ts/plugin_utils.ts index 3bcca323e6..099201c543 100644 --- a/rust/perspective-client/src/rust/utils/talc_allocator.rs +++ b/packages/viewer-datagrid/src/ts/plugin_utils.ts @@ -10,16 +10,12 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -#[global_allocator] -static TALC: talc::TalckWasm = unsafe { talc::TalckWasm::new_global() }; +import type { PluginUtils } from "@perspective-dev/viewer"; -pub fn get_used() -> (usize, usize) { - return { - let counters = TALC.lock(); - ( - counters.get_counters().allocated_bytes, - (counters.get_counters().available_bytes + counters.get_counters().allocated_bytes) - as usize, - ) - }; +let UTILS: PluginUtils | undefined; + +/** The code `` shares with its plugins. */ +export function plugin_utils(): PluginUtils { + UTILS ??= customElements.get("perspective-viewer").plugin_utils; + return UTILS; } diff --git a/packages/viewer-datagrid/src/ts/style_handlers/body.ts b/packages/viewer-datagrid/src/ts/style_handlers/body.ts index fba94d4a86..95932b6825 100644 --- a/packages/viewer-datagrid/src/ts/style_handlers/body.ts +++ b/packages/viewer-datagrid/src/ts/style_handlers/body.ts @@ -20,16 +20,8 @@ import { get_psp_type, } from "../types.ts"; import type { ColumnType } from "@perspective-dev/client"; -import { - css_font_family, - measure_px, - wrap_lines, -} from "../plugin/plugin_config_schema.ts"; - -import { cell_style_numeric } from "./table_cell/numeric.ts"; -import { cell_style_string } from "./table_cell/string.ts"; -import { cell_style_datetime } from "./table_cell/datetime.ts"; -import { cell_style_boolean } from "./table_cell/boolean.ts"; +import { measure_px, wrap_lines } from "../plugin/plugin_config_schema.ts"; +import { plugin_utils } from "../plugin_utils.ts"; import { cell_style_row_header } from "./table_cell/row_header.ts"; import { is_type_text_editable } from "../event_handlers/edit_focus.ts"; import { @@ -148,6 +140,16 @@ export function applyBodyCellStyles( model._config.group_rollup_mode === "flat", ); + const { + cell_style: { + cell_style_boolean, + cell_style_datetime, + cell_style_numeric, + cell_style_string, + }, + schema: { css_font_family }, + } = plugin_utils(); + const is_rollup_mode = model._config.group_rollup_mode === "rollup"; const n_split_by = model._config.split_by.length; const group_by_len = model._config.group_by.length; diff --git a/packages/viewer-datagrid/src/ts/types.ts b/packages/viewer-datagrid/src/ts/types.ts index 0f68c369b2..67f942513e 100644 --- a/packages/viewer-datagrid/src/ts/types.ts +++ b/packages/viewer-datagrid/src/ts/types.ts @@ -22,9 +22,15 @@ import type { } from "@perspective-dev/client"; import type { + Align, + BgMode, + ColorRecord, DateFormatConfig, + FgMode, + GradientStopRgb, HTMLPerspectiveViewerElement, NumberFormatConfig, + Resolved, ViewerConfig, } from "@perspective-dev/viewer"; @@ -34,7 +40,6 @@ import type { CellScalar, DataResponse, } from "regular-table/dist/esm/types.js"; -import type { GradientStopRgb } from "./color_utils.ts"; // Re-export types from regular-table for use throughout the codebase export type { RegularTableElement as RegularTable }; @@ -56,12 +61,6 @@ export function get_psp_type( // Edit mode for the datagrid -/** - * Where in the `ViewConfig` a column being configured appears, which is a - * different axis from its plugin column slot. - */ -export type ColumnRole = "column" | "group_by" | "split_by"; - /** * Datagrid cell interaction mode (`plugin_config.edit_mode`): * `"READ_ONLY"` (default), `"EDIT"` (cells editable, writing back to the @@ -76,17 +75,6 @@ export type EditMode = | "SELECT_REGION" | "SELECT_ROW_TREE"; -// Color record for styling - tuple returned by make_color_record -export type ColorRecord = [ - string, // hex color - number, // red - number, // green - number, // blue - string, // gradient - string, // rgba solid - string, // rgba transparent -]; - export type SortTerm = [string, SortDir]; // Selection state for mouse-based region selection @@ -112,120 +100,6 @@ export interface SelectedPosition { content?: string; } -/** - * A cell of the 3×3 alignment grid: corners `"top-left"` etc., edges - * `"top"`/`"left"`/`"right"`/`"bottom"`, or `"center"`. - */ -export type Align = - | "top-left" - | "top" - | "top-right" - | "left" - | "center" - | "right" - | "bottom-left" - | "bottom" - | "bottom-right"; - -/** Foreground treatments of an integer / float column. */ -export const NUMBER_FG_MODES = [ - "disabled", - "color", - "bar", - "label-bar", -] as const; - -/** Background treatments of an integer / float column. */ -export const NUMBER_BG_MODES = [ - "disabled", - "color", - "gradient", - "pulse", -] as const; - -/** Foreground and background treatments of a string column. */ -export const STRING_MODES = ["disabled", "color", "series"] as const; - -/** Foreground and background treatments of a date / datetime column. */ -export const DATETIME_MODES = ["disabled", "color"] as const; - -export type NumberFgMode = (typeof NUMBER_FG_MODES)[number]; -export type NumberBgMode = (typeof NUMBER_BG_MODES)[number]; -export type StringMode = (typeof STRING_MODES)[number]; -export type DatetimeMode = (typeof DATETIME_MODES)[number]; - -/** - * Every foreground treatment some column type accepts. The subset a given - * column accepts is `fg_modes_for(type)`; `column_config_schema()` - * advertises exactly that subset, and the viewer rejects any other value. - */ -export type FgMode = NumberFgMode | StringMode | DatetimeMode; - -/** Every background treatment some column type accepts, as {@link FgMode}. */ -export type BgMode = NumberBgMode | StringMode | DatetimeMode; - -/** The `fg_mode` values a column of `type` accepts, empty for boolean. */ -export function fg_modes_for(type: ColumnType): readonly FgMode[] { - switch (type) { - case "integer": - case "float": - return NUMBER_FG_MODES; - case "string": - return STRING_MODES; - case "date": - case "datetime": - return DATETIME_MODES; - default: - return []; - } -} - -/** The `bg_mode` values a column of `type` accepts, empty for boolean. */ -export function bg_modes_for(type: ColumnType): readonly BgMode[] { - switch (type) { - case "integer": - case "float": - return NUMBER_BG_MODES; - case "string": - return STRING_MODES; - case "date": - case "datetime": - return DATETIME_MODES; - default: - return []; - } -} - -/** The `fg_mode` an omitted key stands for: colored text for numbers. */ -export function default_fg_mode(type: ColumnType): FgMode { - return type === "integer" || type === "float" ? "color" : "disabled"; -} - -/** The `bg_mode` an omitted key stands for. */ -export function default_bg_mode(_type: ColumnType): BgMode { - return "disabled"; -} - -/** `raw` as an `fg_mode` a column of `type` accepts, else `undefined`. */ -export function parse_fg_mode( - type: ColumnType, - raw: unknown, -): FgMode | undefined { - return (fg_modes_for(type) as readonly unknown[]).includes(raw) - ? (raw as FgMode) - : undefined; -} - -/** `raw` as a `bg_mode` a column of `type` accepts, else `undefined`. */ -export function parse_bg_mode( - type: ColumnType, - raw: unknown, -): BgMode | undefined { - return (bg_modes_for(type) as readonly unknown[]).includes(raw) - ? (raw as BgMode) - : undefined; -} - /** * Datagrid per-column style configuration - one value of the * `columns_config` map of a `ViewerConfigUpdate` when the Datagrid plugin @@ -343,43 +217,21 @@ export interface ColumnConfig { number_format?: NumberFormatConfig; } -// The format-object types are the VIEWER's exported contract - its -// `createNumberFormatter` / `createDatetimeFormatter` consume them and its -// style editors write them - so they are imported, not redefined. export type { - NumberFormatConfig, + Align, + BgMode, + CellStyleModel, + ColorRecord, + ColumnRole, DateFormatConfig, + FgMode, + NumberFormatConfig, } from "@perspective-dev/viewer"; export type ColumnsConfig = Record; -/** - * A column's {@link ColumnConfig} with its `fg_color` / `bg_color` strings - * parsed once at `restore()`. Column types are not known at restore time, - * so every reader runs and each parsed form is present when its grammar - * matched; the per-type cell style handlers pick the form their mode - * needs. - */ -export interface ResolvedColumnStyle - extends Omit { - /** `fg_color` as a single color (string / datetime `"color"` mode). */ - fg_color?: ColorRecord; - bg_color?: ColorRecord; - - /** `fg_color` as gradient stops (numeric columns), t-ordered. */ - fg_stops?: GradientStopRgb[]; - bg_stops?: GradientStopRgb[]; - - /** End colors of `fg_stops` / `bg_stops`: the last stop is positive. */ - pos_fg_color?: ColorRecord; - neg_fg_color?: ColorRecord; - pos_bg_color?: ColorRecord; - neg_bg_color?: ColorRecord; - - /** `fg_color` as a palette (string `"series"` mode), `#rrggbb` each. */ - fg_palette?: string[]; - bg_palette?: string[]; -} +/** A column's {@link ColumnConfig} with its color strings parsed at `restore()`. */ +export type ResolvedColumnStyle = Resolved; /** What `restore()` stores under {@link PRIVATE_PLUGIN_SYMBOL}. */ export type ResolvedColumnsConfig = Record; @@ -624,13 +476,6 @@ export interface ProjectedWidth { px: number | undefined; } -// Formatter cache types -export interface FormatterCacheEntry { - format(value: unknown): string; -} - -export type FormatterCache = Map; - // Cell config result from getCellConfig export interface CellConfigResult { row: Record; diff --git a/rust/perspective-client/Cargo.toml b/rust/perspective-client/Cargo.toml index bcc3132b94..187c68fcbb 100644 --- a/rust/perspective-client/Cargo.toml +++ b/rust/perspective-client/Cargo.toml @@ -51,10 +51,6 @@ protobuf-src = ["dep:protobuf-src"] # to skip metadata generation. This currently only affects docs. omit_metadata = [] -# Should `talc` be used as a global allocator? Allows enhanced runtime metrics -# via `Client::system_info`. -talc-allocator = ["talc"] - [lib] crate-type = ["rlib"] path = "src/rust/lib.rs" @@ -86,7 +82,6 @@ rand = { version = ">=0.9,<1" } serde = { version = "1.0", features = ["derive"] } serde_bytes = { version = "0.11" } serde_json = { version = "1.0.107", features = ["raw_value", "preserve_order"] } -talc = { version = "4.4.3", features = ["counters"], optional = true } thiserror = { version = "1.0.55" } tracing = { version = "0.1.36" } diff --git a/rust/perspective-client/src/rust/client.rs b/rust/perspective-client/src/rust/client.rs index 06ddba61ab..46558a8824 100644 --- a/rust/perspective-client/src/rust/client.rs +++ b/rust/perspective-client/src/rust/client.rs @@ -923,23 +923,14 @@ impl Client { #[cfg(target_family = "wasm")] let timestamp = None; - #[cfg(feature = "talc-allocator")] - let (client_used, client_heap) = { - let (client_used, client_heap) = crate::utils::get_used(); - (Some(client_used as u64), Some(client_heap as u64)) - }; - - #[cfg(not(feature = "talc-allocator"))] - let (client_used, client_heap) = (None, None); - let info = SystemInfo { heap_size: resp.heap_size, used_size: resp.used_size, cpu_time: resp.cpu_time, cpu_time_epoch: resp.cpu_time_epoch, timestamp, - client_heap, - client_used, + client_heap: None, + client_used: None, }; Ok(info) diff --git a/rust/perspective-client/src/rust/utils/mod.rs b/rust/perspective-client/src/rust/utils/mod.rs index 5b73e3d363..645ee38a42 100644 --- a/rust/perspective-client/src/rust/utils/mod.rs +++ b/rust/perspective-client/src/rust/utils/mod.rs @@ -16,9 +16,6 @@ mod clone; mod logging; mod rand_sequence; -#[cfg(feature = "talc-allocator")] -mod talc_allocator; - #[cfg(test)] mod tests; @@ -27,8 +24,6 @@ use std::time::SystemTimeError; use rand::prelude::*; use rand::rngs::StdRng; -#[cfg(feature = "talc-allocator")] -pub(crate) use talc_allocator::get_used; use thiserror::*; use crate::proto; diff --git a/rust/perspective-js/Cargo.toml b/rust/perspective-js/Cargo.toml index fde426fb70..8906fd239d 100644 --- a/rust/perspective-js/Cargo.toml +++ b/rust/perspective-js/Cargo.toml @@ -48,13 +48,8 @@ external-cpp = [ "perspective-client/protobuf-src", ] -# Should `talc` be used as a global allocator? Allows enhanced runtime metrics -# via `Client::system_info`. Mutually exclusive to `trace-allocator` -talc-allocator = ["perspective-client/talc-allocator"] - # Should global allocation be traced? Allows enhanced runtime metrics via -# `Client::system_info`. Mutually exclusive to `talc-allocator`, which does -# not requires a `wasm_bindgen` call to get available heap size. +# `Client::system_info`. trace-allocator = [] [dependencies] diff --git a/rust/perspective-js/build.mjs b/rust/perspective-js/build.mjs index 009b3ce362..f9e8c9ebd5 100644 --- a/rust/perspective-js/build.mjs +++ b/rust/perspective-js/build.mjs @@ -130,7 +130,7 @@ function get_host() { async function build_rust() { const release_flag = IS_DEBUG ? "" : IS_FAST ? "--fast" : "--release"; execSync( - `PSP_ROOT_DIR=../.. cargo bundle --target=${get_host()} -- perspective_js ${release_flag} --features="export-init,talc-allocator"`, + `PSP_ROOT_DIR=../.. cargo bundle --target=${get_host()} -- perspective_js ${release_flag} --features="export-init,trace-allocator"`, INHERIT, ); diff --git a/rust/perspective-js/src/rust/typed_array.rs b/rust/perspective-js/src/rust/typed_array.rs index a7e1ccb42f..ffa308223c 100644 --- a/rust/perspective-js/src/rust/typed_array.rs +++ b/rust/perspective-js/src/rust/typed_array.rs @@ -28,6 +28,22 @@ unsafe extern "C" { pub type JsTypedArrayWindow; } +#[wasm_bindgen(inline_js = " + export function split_strings(text, ends) { + const out = new Array(ends.length); + let start = 0; + for (let i = 0; i < ends.length; i++) { + out[i] = text.substring(start, ends[i]); + start = ends[i]; + } + + return out; + } +")] +extern "C" { + fn split_strings(text: &str, ends: &Uint32Array) -> Array; +} + /// Calls `callback` with zero-copy JS views of `columns`, awaiting a returned /// `Promise` before the views are released. pub(crate) async fn call_with_typed_arrays( @@ -75,13 +91,26 @@ fn values_view(values: &TypedArrayValues) -> JsValue { } } +/// The strings of a dictionary column as a JS `Array`, passed to JS as one +/// string and split there to avoid decoding each separately. fn dictionary(values: &TypedArrayValues) -> JsValue { - match values { - TypedArrayValues::Dictionary { values, .. } => values - .iter() - .map(|value| JsValue::from_str(value)) - .collect::() - .into(), - _ => JsValue::NULL, + let TypedArrayValues::Dictionary { values, .. } = values else { + return JsValue::NULL; + }; + + let mut text = String::with_capacity(values.iter().map(String::len).sum()); + let mut ends = Vec::with_capacity(values.len()); + let mut end = 0; + for value in values { + text.push_str(value); + end += if value.is_ascii() { + value.len() as u32 + } else { + value.encode_utf16().count() as u32 + }; + + ends.push(end); } + + split_strings(&text, &Uint32Array::from(ends.as_slice())).into() } diff --git a/rust/perspective-js/src/rust/utils/trace_allocator.rs b/rust/perspective-js/src/rust/utils/trace_allocator.rs index b4b3a72a7b..a8e839ae54 100644 --- a/rust/perspective-js/src/rust/utils/trace_allocator.rs +++ b/rust/perspective-js/src/rust/utils/trace_allocator.rs @@ -10,8 +10,8 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -//! A wrapper around the default allocator which counts allocations, useful for -//! instrumenting the `Client` as an alternative to switching to `talc`. +//! A wrapper around the default allocator which counts allocations, for the +//! `Client`'s heap metrics in `Client::system_info`. //! //! Lifted from https://stackoverflow.com/questions/78246635/how-do-i-log-wasm-heap-memory-usage-from-rust //! or as its popular to refer to these days, "AI". @@ -93,6 +93,3 @@ pub(crate) fn get_used() -> (usize, usize) { (ALLOCATOR.allocated_now(), client_heap as usize) } - -#[cfg(all(feature = "talc-allocator", feature = "trace-allocator"))] -compile_error!("Cannot enable both `talc-allocator` and `trace-allocator` features"); diff --git a/rust/perspective-migrate/src/plugins/mod.rs b/rust/perspective-migrate/src/plugins/mod.rs index 9c01bb43b2..b514a05a8d 100644 --- a/rust/perspective-migrate/src/plugins/mod.rs +++ b/rust/perspective-migrate/src/plugins/mod.rs @@ -22,6 +22,7 @@ use crate::step::StepCx; pub(crate) const REGISTRATION_ORDER: &[&str] = &[ "Datagrid", + "Summary", "X Bar", "Y Bar", "Y Line", diff --git a/rust/perspective-python/Cargo.toml b/rust/perspective-python/Cargo.toml index d76054ac00..2430eb5bd2 100644 --- a/rust/perspective-python/Cargo.toml +++ b/rust/perspective-python/Cargo.toml @@ -62,7 +62,6 @@ perspective-migrate = { version = "~5.9.4" } perspective-server = { version = "~5.9.4" } bytes = "1.10.1" chrono = "0.4" -macro_rules_attribute = "0.2.2" async-lock = "2.5.0" pollster = "0.3.0" extend = "1.1.2" diff --git a/rust/perspective-viewer/Cargo.toml b/rust/perspective-viewer/Cargo.toml index 380b31f87d..97b0eed380 100644 --- a/rust/perspective-viewer/Cargo.toml +++ b/rust/perspective-viewer/Cargo.toml @@ -35,9 +35,12 @@ path = "src/rust/lib.rs" [features] external-bootstrap = [] + +# Look up time zone rules and time zone, currency and unit names in linked +# locale data rather than in the browser, for builds that run outside one. +bundled-locale-data = ["dep:jiff"] metadata = [] default = ["llm-agent"] -talc-allocator = ["perspective-js/talc-allocator"] trace-allocator = ["perspective-js/trace-allocator"] llm-agent = [] @@ -67,6 +70,22 @@ derivative = "2.2.0" # Easy way to define & implement a singleton trait (type extension) extend = "1.1.2" +# Locale-aware number and date formatting, pinned as parts are pre-stable +fixed_decimal = { version = "=0.7.3", features = ["ryu"] } +icu_calendar = { version = "=2.4.0" } +icu_datetime = { version = "=2.4.0" } +icu_decimal = { version = "=2.4.0", features = ["alloc", "unstable"] } +icu_experimental = { version = "=0.7.0" } +icu_locale_core = { version = "=2.4.0", features = ["alloc"] } +icu_plurals = { version = "=2.4.0" } +icu_provider = { version = "=2.4.0" } +icu_time = { version = "=2.4.0" } +jiff = { version = "=1.0.1", optional = true, default-features = false, features = [ + "std", + "tzdb-bundle-always", +] } +writeable = { version = "=0.6.4" } + # General async tools futures = "0.3.31" @@ -76,8 +95,6 @@ itertools = "0.14.0" # JavaScript stdlib bindings js-sys = "0.3.85" -macro_rules_attribute = "0.2.2" - # Parse ExprTK for syntax highlighting. nom = "7.1.1" diff --git a/rust/perspective-viewer/build.mjs b/rust/perspective-viewer/build.mjs index 774bb1942f..19c90b2d59 100644 --- a/rust/perspective-viewer/build.mjs +++ b/rust/perspective-viewer/build.mjs @@ -83,6 +83,7 @@ export async function build_all() { { entryPoints: ["src/ts/perspective-viewer.ts"], format: "esm", + loader: { ".css": "text" }, minify: false, minifySyntax: !process.env.PSP_DEBUG, minifyIdentifiers: !process.env.PSP_DEBUG, @@ -99,12 +100,12 @@ export async function build_all() { }), ], }, - // Dependency-free leaf modules, published as the `./select-detail` - // and `./column-format` subpath exports. Plugin packages import these - // instead of the package root, which would link the entire viewer and - // its wasm asset into a plugin's standalone `dist/cdn` bundle. + // A dependency-free leaf module, published as the `./select-detail` + // subpath export. Plugin packages import this instead of the package + // root, which would link the entire viewer and its wasm asset into a + // plugin's standalone `dist/cdn` bundle. { - entryPoints: ["src/ts/select-detail.ts", "src/ts/column-format.ts"], + entryPoints: ["src/ts/select-detail.ts"], format: "esm", outdir: "dist/esm", }, @@ -120,7 +121,7 @@ export async function build_all() { { entryPoints: ["src/ts/perspective-viewer.cdn.ts"], format: "esm", - loader: { ".wasm": "file" }, + loader: { ".wasm": "file", ".css": "text" }, outfile: "dist/cdn/perspective-viewer.js", plugins: [ WorkerPlugin({ diff --git a/rust/perspective-viewer/package.json b/rust/perspective-viewer/package.json index f877c1e809..abd54602bd 100644 --- a/rust/perspective-viewer/package.json +++ b/rust/perspective-viewer/package.json @@ -43,11 +43,6 @@ "import": "./dist/esm/select-detail.js", "default": "./dist/esm/select-detail.js" }, - "./column-format": { - "types": "./dist/esm/column-format.d.ts", - "import": "./dist/esm/column-format.js", - "default": "./dist/esm/column-format.js" - }, "./themes": "./dist/css/themes.css", "./themes/*.css": "./dist/css/*.css", "./themes/intl/*.css": "./dist/css/intl/*.css", diff --git a/rust/perspective-viewer/src/css/plugin-selector.css b/rust/perspective-viewer/src/css/plugin-selector.css index 83748e4321..e9ab61d641 100644 --- a/rust/perspective-viewer/src/css/plugin-selector.css +++ b/rust/perspective-viewer/src/css/plugin-selector.css @@ -283,6 +283,17 @@ visibility: hidden; } } + + .plugin-select-item[data-plugin="Summary"] > .icon { + -webkit-mask-image: var( + --psp-plugin-selector--summary--content + ); + mask-image: var(--psp-plugin-selector--summary--content); + &:before { + content: var(--psp-plugin-selector--summary--content); + visibility: hidden; + } + } } #plugin_selector { diff --git a/rust/perspective-viewer/src/rust/components/column_selector/config_selector.rs b/rust/perspective-viewer/src/rust/components/column_selector/config_selector.rs index 92aef2d5ed..88cbb3473c 100644 --- a/rust/perspective-viewer/src/rust/components/column_selector/config_selector.rs +++ b/rust/perspective-viewer/src/rust/components/column_selector/config_selector.rs @@ -87,6 +87,19 @@ impl PartialEq for ConfigSelectorProps { } } +/// Whether the active plugin can draw a `group_by` at all. +fn accepts_group_by(props: &ConfigSelectorProps) -> bool { + let rollup_features = props + .metadata + .get_features() + .map(|x| x.get_group_rollup_modes()) + .unwrap_or_default(); + + props + .plugin_static_config + .accepts_group_by(&rollup_features) +} + #[derive(Debug)] pub enum ConfigSelectorMsg { DragOver(usize, DragTarget), @@ -272,6 +285,11 @@ impl Component for ConfigSelector { false }, ConfigSelectorMsg::Close(..) => false, + ConfigSelectorMsg::Drop(_, DragTarget::GroupBy, ..) + if !accepts_group_by(ctx.props()) => + { + false + }, ConfigSelectorMsg::Drop(column, action, effect, index) if action != DragTarget::Active && !action.is_staged() => { @@ -675,6 +693,7 @@ impl Component for ConfigSelector { name="group_by" role_label={plugin_roles.0.clone()} disabled={config.group_rollup_mode == GroupRollupMode::Total} + is_invalid={!accepts_group_by(ctx.props())} parent={ctx.link().clone()} column_dropdown={column_dropdown.clone()} exclude={config.group_by.iter().cloned().collect::>()} diff --git a/rust/perspective-viewer/src/rust/components/datetime_column_style.rs b/rust/perspective-viewer/src/rust/components/datetime_column_style.rs index 1623fb7233..c519a47a70 100644 --- a/rust/perspective-viewer/src/rust/components/datetime_column_style.rs +++ b/rust/perspective-viewer/src/rust/components/datetime_column_style.rs @@ -18,9 +18,6 @@ use std::rc::Rc; use std::sync::LazyLock; use derivative::Derivative; -use perspective_js::json; -use perspective_js::utils::global::navigator; -use wasm_bindgen::prelude::*; use yew::prelude::*; use crate::components::datetime_column_style::custom::DatetimeStyleCustom; @@ -288,47 +285,17 @@ fn inherited_time_zone(format: &DatetimeFormat) -> String { format .time_zone .clone() - .unwrap_or_else(|| (*USER_TIMEZONE).clone()) + .unwrap_or_else(|| crate::plugin_utils::local_time_zone().to_owned()) } fn inherited_hour12(format: &DatetimeFormat) -> bool { format.hour12.unwrap_or(*USER_HOUR12) } -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_name = supportedValuesOf, js_namespace = Intl)] - pub fn supported_values_of(s: &JsValue) -> js_sys::Array; -} - thread_local! { - static ALL_TIMEZONES: LazyLock>> = LazyLock::new(|| { - Rc::new( - supported_values_of(&JsValue::from("timeZone")) - .iter() - .map(|x| x.as_string().unwrap()) - .collect(), - ) - }); + static ALL_TIMEZONES: LazyLock>> = + LazyLock::new(|| Rc::new(crate::plugin_utils::time_zones())); } -static USER_TIMEZONE: LazyLock = LazyLock::new(|| { - js_sys::Reflect::get( - &js_sys::Intl::DateTimeFormat::new(&navigator().languages(), &json!({})).resolved_options(), - &JsValue::from("timeZone"), - ) - .unwrap() - .as_string() - .unwrap() -}); - -static USER_HOUR12: LazyLock = LazyLock::new(|| { - js_sys::Reflect::get( - &js_sys::Intl::DateTimeFormat::new(&navigator().languages(), &json!({"hour": "numeric"})) - .resolved_options(), - &JsValue::from("hour12"), - ) - .ok() - .and_then(|x| x.as_bool()) - .unwrap_or(true) -}); +static USER_HOUR12: LazyLock = + LazyLock::new(|| crate::format::prefers_hour12(crate::plugin_utils::languages())); diff --git a/rust/perspective-viewer/src/rust/config/number_string_format.rs b/rust/perspective-viewer/src/rust/config/number_string_format.rs index a56df1839e..d5f6041e8d 100644 --- a/rust/perspective-viewer/src/rust/config/number_string_format.rs +++ b/rust/perspective-viewer/src/rust/config/number_string_format.rs @@ -181,12 +181,12 @@ pub enum SignDisplay { /// A numeric column's `number_format` (`columns_config` value) — /// `Intl.NumberFormat`-shaped options, written by the Style tab's number -/// format editor and read by `createNumberFormatter`. The `style` and +/// format editor and read by `plugin_utils.formatter()`. The `style` and /// `notation` families ([`NumberFormatStyle`] / [`Notation`]) are serde- /// FLATTENED into this object but `#[ts(skip)]`'d (ts-rs cannot flatten /// `Option`) — the package's `NumberFormatConfig` re-composes the /// full wire type as `CustomNumberFormatConfig & Partial -/// & Partial` (see `column-format.ts`). +/// & Partial` (see `plugin_utils/native.ts`). #[derive(Serialize, Deserialize, Debug, Default, PartialEq, Clone, TS)] #[serde(rename_all = "camelCase")] pub struct CustomNumberFormatConfig { diff --git a/rust/perspective-viewer/src/rust/config/plugin_static_config.rs b/rust/perspective-viewer/src/rust/config/plugin_static_config.rs index 06cb8dc33a..7a5363ebf4 100644 --- a/rust/perspective-viewer/src/rust/config/plugin_static_config.rs +++ b/rust/perspective-viewer/src/rust/config/plugin_static_config.rs @@ -162,6 +162,14 @@ pub struct PluginStaticConfig { #[ts(as = "Option<_>")] #[ts(optional)] pub connects_row_order: bool, + + /// `true` when this plugin's `render()` resolves to text rather than an + /// image, which makes the copy and export menus offer `.txt` in place of + /// `.png`. + #[serde(default)] + #[ts(as = "Option<_>")] + #[ts(optional)] + pub renders_text: bool, } impl PluginStaticConfig { @@ -204,6 +212,13 @@ impl PluginStaticConfig { .unwrap_or_default() } + /// Whether this plugin accepts a `group_rollup_mode` other than `total`, + /// the one mode a `group_by` cannot have. + pub fn accepts_group_by(&self, rollup_features: &[GroupRollupMode]) -> bool { + let modes = self.get_group_rollups(rollup_features); + modes.is_empty() || modes.iter().any(|x| *x != GroupRollupMode::Total) + } + pub fn get_split_rollups(&self, rollup_features: &[SplitRollupMode]) -> Vec { self.split_rollup_modes .clone() diff --git a/rust/perspective-viewer/src/rust/custom_elements/viewer.rs b/rust/perspective-viewer/src/rust/custom_elements/viewer.rs index 341977689e..7b318372aa 100644 --- a/rust/perspective-viewer/src/rust/custom_elements/viewer.rs +++ b/rust/perspective-viewer/src/rust/custom_elements/viewer.rs @@ -236,6 +236,7 @@ impl CustomElementMetadata for PerspectiveViewerElement { "getColumnConfigDefaults", ] .as_slice(); + const STATIC_GETTERS: &'static [&'static str] = ["plugin_utils"].as_slice(); } impl PerspectiveViewerElement { diff --git a/rust/perspective-viewer/src/rust/format/baked_data.rs b/rust/perspective-viewer/src/rust/format/baked_data.rs new file mode 100644 index 0000000000..7f5605db68 --- /dev/null +++ b/rust/perspective-viewer/src/rust/format/baked_data.rs @@ -0,0 +1,260 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +use fixed_decimal::{Decimal, FloatPrecision, SignedRoundingMode, UnsignedRoundingMode}; +use icu_datetime::fieldsets::builder::{FieldSetBuilder, ZoneStyle}; +use icu_datetime::fieldsets::enums::ZoneFieldSet; +use icu_datetime::input::{TimeZone, UtcOffset}; +use icu_datetime::{DateTimeFormatterPreferences, NoCalendarFormatter}; +use icu_decimal::DecimalFormatter; +use icu_experimental::dimension::currency::CurrencyType; +use icu_experimental::dimension::currency::formatter::{ + CurrencyFormatter, CurrencyFormatterPreferences, +}; +use icu_experimental::dimension::provider::currency::symbols::{ + CurrencySymbolWidth, CurrencySymbolsV1, +}; +use icu_experimental::dimension::provider::units::categorized_display_names::*; +use icu_experimental::dimension::provider::units::display_names::UnitsDisplayNames; +use icu_experimental::provider::Baked; +use icu_locale_core::Locale; +use icu_locale_core::preferences::LocalePreferences; +use icu_plurals::PluralRules; +use icu_provider::marker::ErasedMarker; +use icu_provider::prelude::*; +use icu_time::zone::ZoneNameTimestamp; +use writeable::Writeable; + +use super::locale_data::{CurrencySymbol, LocaleData, NameKind, OffsetSpan}; +use super::number::currency_digits; +use super::spec::UnitDisplay; + +type UnitNames = DataPayload>>; + +/// Looks up time zone rules and localized names in the data linked into +/// this binary. +pub struct BakedData; + +#[optimize(speed)] +fn load_unit_names(preferences: LocalePreferences, attributes: &str) -> Option<(UnitNames, bool)> +where + M: DataMarker>, + Baked: DataProvider, +{ + let attributes = DataMarkerAttributes::try_from_str(attributes).ok()?; + let locale = M::make_locale(preferences); + let mut metadata = DataRequestMetadata::default(); + metadata.silent = true; + let response = DataProvider::::load(&Baked, DataRequest { + id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale), + metadata, + }) + .ok()?; + + let is_root = response + .metadata + .locale + .as_ref() + .is_some_and(|x| x.is_unknown()); + + Some((response.payload.cast(), is_root)) +} + +/// The localized names of `unit`, preferring any the locale itself defines +/// over the root abbreviation. +#[optimize(speed)] +fn unit_names( + preferences: LocalePreferences, + unit: &str, + display: UnitDisplay, +) -> Option { + let width = match display { + UnitDisplay::Short => "short", + UnitDisplay::Narrow => "narrow", + UnitDisplay::Long => "long", + }; + + let attributes = format!("{width}-{unit}"); + let mut root = None; + macro_rules! find { + ($($marker:ident),*) => {$( + match load_unit_names::<$marker>(preferences, &attributes) { + Some((names, false)) => return Some(names), + Some((names, true)) => root = root.or(Some(names)), + None => {}, + } + )*}; + } + + find!( + UnitsNamesAreaCoreV1, + UnitsNamesAreaExtendedV1, + UnitsNamesAreaOutlierV1, + UnitsNamesDurationCoreV1, + UnitsNamesDurationExtendedV1, + UnitsNamesDurationOutlierV1, + UnitsNamesLengthCoreV1, + UnitsNamesLengthExtendedV1, + UnitsNamesLengthOutlierV1, + UnitsNamesMassCoreV1, + UnitsNamesMassExtendedV1, + UnitsNamesMassOutlierV1, + UnitsNamesVolumeCoreV1, + UnitsNamesVolumeExtendedV1, + UnitsNamesVolumeOutlierV1 + ); + + root +} + +/// `value` with exactly `fraction_digits` fraction digits. +#[optimize(speed)] +fn decimal(value: f64, fraction_digits: i16) -> Option { + let mut decimal = Decimal::try_from_f64(value, FloatPrecision::RoundTrip).ok()?; + decimal.round_with_mode( + -fraction_digits, + SignedRoundingMode::Unsigned(UnsignedRoundingMode::HalfExpand), + ); + + decimal.absolute.pad_end(-fraction_digits); + Some(decimal) +} + +impl LocaleData for BakedData { + #[optimize(speed)] + fn time_zones(&self) -> Vec { + jiff::tz::db() + .available() + .map(|x| x.as_str().to_owned()) + .collect() + } + + #[optimize(speed)] + fn utc_offset(&self, zone: &str, epoch_ms: i64) -> Option { + let zone = jiff::tz::TimeZone::get(zone).ok()?; + let instant = jiff::Timestamp::from_millisecond(epoch_ms).ok()?; + let after = instant + .checked_add(jiff::SignedDuration::from_nanos(1)) + .unwrap_or(instant); + + Some(OffsetSpan { + offset: zone.to_offset(instant).seconds(), + start: zone + .preceding(after) + .next() + .map_or(i64::MIN, |x| x.timestamp().as_millisecond()), + end: zone + .following(instant) + .next() + .map_or(i64::MAX, |x| x.timestamp().as_millisecond()), + }) + } + + #[optimize(speed)] + fn currency_symbol(&self, locale: &str, code: &str, narrow: bool) -> Option { + let locale = Locale::try_from_str(locale).ok()?; + let currency: CurrencyType = code.parse().ok()?; + let preferences: CurrencyFormatterPreferences = (&locale).into(); + let data_locale = CurrencySymbolsV1::make_locale(preferences.locale_preferences); + let width = if narrow { + CurrencySymbolWidth::Narrow + } else { + CurrencySymbolWidth::Short + }; + + let mut metadata = DataRequestMetadata::default(); + metadata.silent = true; + let response = DataProvider::::load(&Baked, DataRequest { + id: DataIdentifierBorrowed::for_marker_attributes_and_locale( + CurrencySymbolsV1::make_attributes(currency, width, &mut Default::default()), + &data_locale, + ), + metadata, + }) + .ok()?; + + let symbol = response.payload.get(); + Some(CurrencySymbol { + text: symbol.as_str().to_owned(), + starts_with_letter: symbol.starts_with_letter(), + ends_with_letter: symbol.ends_with_letter(), + }) + } + + #[optimize(speed)] + fn zone_name(&self, locale: &str, zone: &str, epoch_ms: f64, long: bool) -> Option { + let locale = Locale::try_from_str(locale).ok()?; + let instant = jiff::Timestamp::from_millisecond(epoch_ms.trunc() as i64).ok()?; + let offset = jiff::tz::TimeZone::get(zone) + .ok()? + .to_offset(instant) + .seconds(); + let info = TimeZone::from_iana_id(zone) + .with_offset(UtcOffset::try_from_seconds(offset).ok()) + .with_zone_name_timestamp(ZoneNameTimestamp::from_epoch_seconds(instant.as_second())); + + let mut builder = FieldSetBuilder::new(); + builder.zone_style = Some(if long { + ZoneStyle::SpecificLong + } else { + ZoneStyle::SpecificShort + }); + + let field_set: ZoneFieldSet = builder.build_zone().ok()?; + let formatter = + NoCalendarFormatter::try_new(DateTimeFormatterPreferences::from(&locale), field_set) + .ok()?; + + Some(formatter.format(&info).to_string()) + } + + #[optimize(speed)] + fn pattern( + &self, + locale: &str, + kind: &NameKind, + value: f64, + fraction_digits: u8, + ) -> Option { + let locale = Locale::try_from_str(locale).ok()?; + match kind { + NameKind::Unit { unit, display } => { + let names = unit_names((&locale).into(), unit, *display)?; + let plurals = PluralRules::try_new_cardinal((&locale).into()).ok()?; + let decimal = decimal(value, i16::from(fraction_digits))?; + Some( + names + .get() + .get((&decimal).into(), &plurals) + .interpolate(("{0}",)) + .write_to_string() + .into_owned(), + ) + }, + NameKind::Currency(code) => { + let currency: CurrencyType = code.parse().ok()?; + let preferences: CurrencyFormatterPreferences = (&locale).into(); + let named = CurrencyFormatter::try_new_name(preferences, currency).ok()?; + let number = + DecimalFormatter::try_new((&preferences).into(), Default::default()).ok()?; + let decimal = decimal(value, i16::from(currency_digits(code)))?; + let text = named + .format_fixed_decimal(&decimal) + .write_to_string() + .into_owned(); + let digits = number.format(&decimal).write_to_string().into_owned(); + text.contains(&digits) + .then(|| text.replacen(&digits, "{0}", 1)) + }, + } + } +} diff --git a/rust/perspective-viewer/src/rust/format/datetime.rs b/rust/perspective-viewer/src/rust/format/datetime.rs new file mode 100644 index 0000000000..0f1d7e0226 --- /dev/null +++ b/rust/perspective-viewer/src/rust/format/datetime.rs @@ -0,0 +1,832 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +use std::cell::RefCell; +use std::collections::{BTreeMap, HashMap}; +use std::ops::Bound; +use std::rc::Rc; + +use icu_calendar::Gregorian; +use icu_datetime::fieldsets::builder::{DateFields, FieldSetBuilder}; +use icu_datetime::fieldsets::enums::{CompositeDateTimeFieldSet, TimeFieldSet}; +use icu_datetime::input::{DateTime, UtcOffset, ZonedDateTime}; +use icu_datetime::options::{Length, SubsecondDigits, TimePrecision}; +use icu_datetime::pattern::{DateTimePattern, FixedCalendarDateTimeNames}; +use icu_datetime::preferences::HourCycle; +use icu_datetime::provider::fields::{self, FieldLength, FieldSymbol}; +use icu_datetime::provider::pattern::{GenericPatternItem, PatternItem, runtime}; +use icu_datetime::provider::semantic_skeletons::DatetimePatternsGlueV1; +use icu_datetime::{DateTimeFormatterPreferences, FixedCalendarDateTimeFormatter}; +use icu_locale_core::Locale; +use icu_provider::prelude::*; +use writeable::{TryWriteable, Writeable}; + +use super::locale; +use super::locale_data::{LocaleData, OffsetSpan}; +use super::spec::{DatetimeSpec, MonthWidth, NumericWidth, PresetLength, TextWidth}; + +/// The latest and earliest instants a JavaScript `Date` can hold, in +/// milliseconds. +const MAX_EPOCH_MS: f64 = 8.64e15; + +/// What a value that is not an instant renders as. +const INVALID: &str = "-"; + +/// The space CLDR puts before a day period, which browsers show as a plain +/// space. +const NARROW_NO_BREAK_SPACE: char = '\u{202f}'; + +/// The names of every time zone that has only ever been UTC. +const UTC_ZONES: [&str; 18] = [ + "UTC", + "Etc/UTC", + "Etc/UCT", + "UCT", + "Etc/Universal", + "Universal", + "Etc/Zulu", + "Zulu", + "GMT", + "Etc/GMT", + "Etc/GMT0", + "Etc/GMT+0", + "Etc/GMT-0", + "GMT0", + "GMT+0", + "GMT-0", + "Etc/Greenwich", + "Greenwich", +]; + +type Formatter = FixedCalendarDateTimeFormatter; + +type Names = FixedCalendarDateTimeNames; + +/// A pattern a part's formatter resolves to, with the names and pattern it +/// is rewritten to when the widths change it. +struct Rewrite { + source: DateTimePattern, + rewritten: Option<(Names, DateTimePattern)>, +} + +/// An instant, its time zone's UTC offset at it, and its local date and +/// time there. +struct Moment { + epoch_ms: f64, + offset: i32, + local: DateTime, +} + +/// The UTC offsets of a time zone, by instant. +enum Offsets { + /// A zone that has only ever had this offset. + Fixed(i32), + + /// Disjoint spans with their offsets, keyed by their starts. + Spans(RefCell>), +} + +/// Per-field widths a field set cannot carry, applied by rewriting the +/// pattern it resolves to. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +struct Widths { + weekday: Option, + year: Option, + month: Option, + day: Option, + hour: Option, +} + +/// Which name of the time zone follows the time. +#[derive(Clone, Copy, PartialEq, Eq)] +enum ZoneName { + Short, + Long, +} + +enum Plan { + /// A date part and/or a time part, joined by the locale's pattern for + /// doing so, the time followed by its zone's name. + Parts { + date: Option>, + time: Option>, + zone: Option, + glue: DataPayload, + widths: Widths, + }, + + /// A minute and/or second with no hour, which no field set covers. + TimePattern { + names: FixedCalendarDateTimeNames<(), TimeFieldSet>, + pattern: DateTimePattern, + }, +} + +#[optimize(speed)] +fn error(err: impl core::fmt::Display) -> String { + err.to_string() +} + +#[optimize(speed)] +fn formatter( + preferences: DateTimeFormatterPreferences, + builder: FieldSetBuilder, +) -> Result { + let field_set = builder.build_composite_datetime().map_err(error)?; + Formatter::try_new(preferences, field_set).map_err(error) +} + +#[optimize(speed)] +fn time_formatter( + preferences: DateTimeFormatterPreferences, + precision: TimePrecision, +) -> Result { + let mut builder = FieldSetBuilder::new(); + builder.time_precision = Some(precision); + formatter(preferences, builder) +} + +#[optimize(speed)] +fn is_numeric(length: FieldLength) -> bool { + matches!(length, FieldLength::One | FieldLength::Two) +} + +/// Whether the month of `pattern` is spelled out rather than numeric, if it +/// has one. +#[optimize(speed)] +fn month_is_text(pattern: &runtime::Pattern) -> Option { + pattern.items.iter().find_map(|item| match item { + PatternItem::Field(field) if matches!(field.symbol, FieldSymbol::Month(_)) => { + Some(!is_numeric(field.length)) + }, + _ => None, + }) +} + +/// `pattern` with the widths of `widths` applied to its fields, or `None` +/// when it has them already. +#[optimize(speed)] +fn rewrite_widths(pattern: &runtime::Pattern, widths: &Widths) -> Option { + use FieldLength::{Five, Four, One, Six, Three, Two}; + let numeric_length = |x: NumericWidth| match x { + NumericWidth::TwoDigit => Two, + NumericWidth::Numeric => One, + }; + + let mut changed = false; + let items = pattern + .items + .iter() + .map(|item| { + let PatternItem::Field(mut field) = item else { + return item; + }; + + let numeric = is_numeric(field.length); + let length = match field.symbol { + FieldSymbol::Year(fields::Year::Calendar) if numeric => { + widths.year.map(numeric_length) + }, + FieldSymbol::Day(fields::Day::DayOfMonth) if numeric => { + widths.day.map(numeric_length) + }, + FieldSymbol::Hour(_) if numeric => widths.hour.map(numeric_length), + FieldSymbol::Month(_) => match (widths.month, numeric) { + (Some(MonthWidth::Numeric), true) => Some(One), + (Some(MonthWidth::TwoDigit), true) => Some(Two), + (Some(MonthWidth::Short), false) => Some(Three), + (Some(MonthWidth::Long), false) => Some(Four), + (Some(MonthWidth::Narrow), false) => Some(Five), + _ => None, + }, + FieldSymbol::Weekday(kind) if !numeric || kind == fields::Weekday::Format => { + match widths.weekday { + Some(TextWidth::Short) if matches!(field.length, Four | Five | Six) => { + Some(Three) + }, + Some(TextWidth::Long) => Some(Four), + Some(TextWidth::Narrow) => Some(Five), + _ => None, + } + }, + _ => None, + }; + + if let Some(length) = length { + changed |= length != field.length; + field.length = length; + } + + PatternItem::Field(field) + }) + .collect::>(); + + changed.then(|| DateTimePattern::from(runtime::Pattern::from(items))) +} + +#[optimize(speed)] +fn try_write(value: T, out: &mut String) -> Result<(), String> { + match value.try_write_to(out) { + Ok(_) => Ok(()), + Err(err) => Err(err.to_string()), + } +} + +/// The UTC offset in seconds of `zone` when it names a time zone that has +/// only ever had one. +#[optimize(speed)] +fn fixed_offset(zone: &str) -> Option { + if UTC_ZONES.iter().any(|x| x.eq_ignore_ascii_case(zone)) { + return Some(0); + } + + const PREFIX: &str = "Etc/GMT"; + let rest = zone + .get(..PREFIX.len()) + .filter(|x| x.eq_ignore_ascii_case(PREFIX)) + .map(|_| &zone[PREFIX.len()..])?; + + let (sign, hours) = match rest.split_at_checked(1)? { + ("+", hours) => (-1, hours), + ("-", hours) => (1, hours), + _ => return None, + }; + + let canonical = matches!(hours.len(), 1 | 2) + && hours.bytes().all(|x| x.is_ascii_digit()) + && !hours.starts_with('0'); + + let hours: i32 = hours.parse().ok().filter(|_| canonical)?; + (hours <= if sign < 0 { 12 } else { 14 }).then_some(sign * hours * 3600) +} + +/// Add `span`, found for `instant`, to `spans`, trimmed to the gap around +/// `instant` and merged with a neighbour it touches at the same offset. +#[optimize(speed)] +fn insert_span(spans: &mut BTreeMap, span: OffsetSpan, instant: i64) { + let previous = spans.range(..=instant).next_back().map(|(_, x)| *x); + let next = spans + .range((Bound::Excluded(instant), Bound::Unbounded)) + .next() + .map(|(_, x)| *x); + + let mut span = OffsetSpan { + offset: span.offset, + start: span + .start + .min(instant) + .max(previous.map_or(i64::MIN, |x| x.end)), + end: span + .end + .max(instant + 1) + .min(next.map_or(i64::MAX, |x| x.start)), + }; + + if let Some(previous) = previous.filter(|x| x.end == span.start && x.offset == span.offset) { + spans.remove(&previous.start); + span.start = previous.start; + } + + if let Some(next) = next.filter(|x| x.start == span.end && x.offset == span.offset) { + spans.remove(&next.start); + span.end = next.end; + } + + spans.insert(span.start, span); +} + +/// The local date and time of the instant `epoch_ms` at `offset` seconds +/// from UTC. +#[optimize(speed)] +fn local(epoch_ms: i64, offset: i32) -> Result, String> { + let offset = + UtcOffset::try_from_seconds(offset).map_err(|_| "UTC offset out of range".to_owned())?; + + let local = ZonedDateTime::from_epoch_milliseconds_and_utc_offset(epoch_ms, offset); + Ok(DateTime { + date: local.date.to_calendar(Gregorian), + time: local.time, + }) +} + +/// `offset` seconds from UTC as `GMT`, `GMT-5` or `GMT+5:30`. +#[optimize(speed)] +fn offset_name(offset: i32) -> String { + if offset == 0 { + return "GMT".to_owned(); + } + + let sign = if offset < 0 { '-' } else { '+' }; + let minutes = offset.unsigned_abs() / 60; + match minutes % 60 { + 0 => format!("GMT{sign}{}", minutes / 60), + rest => format!("GMT{sign}{}:{rest:02}", minutes / 60), + } +} + +/// The smallest field set with every date field `spec` asks for, if it asks +/// for any. +#[optimize(speed)] +fn date_fields(spec: &DatetimeSpec) -> Option { + Some( + match ( + spec.weekday.is_some(), + spec.year.is_some(), + spec.month.is_some(), + spec.day.is_some(), + ) { + (false, false, false, false) => return None, + (false, true, false, false) => DateFields::Y, + (false, false, true, false) => DateFields::M, + (false, true, true, false) => DateFields::YM, + (false, false, false, true) => DateFields::D, + (false, false, true, true) => DateFields::MD, + (false, true, _, true) => DateFields::YMD, + (true, false, false, false) => DateFields::E, + (true, false, false, true) => DateFields::DE, + (true, false, true, _) => DateFields::MDE, + (true, true, ..) => DateFields::YMDE, + }, + ) +} + +/// The formatter for the date `fields`, of whichever length resolves to a +/// month in the form `widths` asks for. +#[optimize(speed)] +fn date_formatter( + preferences: DateTimeFormatterPreferences, + fields: DateFields, + widths: &Widths, + sample: &DateTime, +) -> Result { + let lengths: &[Length] = match (widths.month, widths.weekday) { + (Some(MonthWidth::Numeric | MonthWidth::TwoDigit), _) => &[Length::Short], + (_, Some(TextWidth::Long)) | (Some(MonthWidth::Long), None) => { + &[Length::Long, Length::Medium] + }, + _ => &[Length::Medium, Length::Long], + }; + + let wants_text = widths + .month + .map(|x| !matches!(x, MonthWidth::Numeric | MonthWidth::TwoDigit)); + + let mut fallback = None; + for (index, length) in lengths.iter().enumerate() { + let mut builder = FieldSetBuilder::new(); + builder.date_fields = Some(fields); + builder.length = Some(*length); + let formatter = formatter(preferences, builder)?; + let pattern: runtime::Pattern = formatter.format(sample).pattern().into(); + let matches = match (wants_text, month_is_text(&pattern)) { + (Some(want), Some(have)) => want == have, + _ => true, + }; + + if matches || lengths.len() == 1 { + return Ok(formatter); + } + + if index == 0 || *length == Length::Long { + fallback = Some(formatter); + } + } + + fallback.ok_or_else(|| "No date format".to_owned()) +} + +#[optimize(speed)] +fn glue( + preferences: DateTimeFormatterPreferences, + attributes: &str, +) -> Result, String> { + let locale = DatetimePatternsGlueV1::INFO.make_locale(preferences.locale_preferences); + let response: DataResponse = icu_datetime::provider::Baked + .load(DataRequest { + id: DataIdentifierBorrowed::for_marker_attributes_and_locale( + DataMarkerAttributes::try_from_str(attributes) + .map_err(|_| "Unknown date and time joiner".to_owned())?, + &locale, + ), + ..Default::default() + }) + .map_err(error)?; + + Ok(response.payload) +} + +/// The plan for a `dateStyle` and/or `timeStyle`. +#[optimize(speed)] +fn preset_plan( + preferences: DateTimeFormatterPreferences, + date_style: Option, + time_style: Option, +) -> Result { + let date = date_style + .map(|style| { + let (fields, length) = match style { + PresetLength::Full => (DateFields::YMDE, Length::Long), + PresetLength::Long => (DateFields::YMD, Length::Long), + PresetLength::Medium => (DateFields::YMD, Length::Medium), + PresetLength::Short => (DateFields::YMD, Length::Short), + }; + + let mut builder = FieldSetBuilder::new(); + builder.date_fields = Some(fields); + builder.length = Some(length); + formatter(preferences, builder).map(Box::new) + }) + .transpose()?; + + let time = time_style + .map(|style| { + let precision = match style { + PresetLength::Short => TimePrecision::Minute, + _ => TimePrecision::Second, + }; + + time_formatter(preferences, precision).map(Box::new) + }) + .transpose()?; + + let zone = match time_style { + Some(PresetLength::Full) => Some(ZoneName::Long), + Some(PresetLength::Long) => Some(ZoneName::Short), + _ => None, + }; + + let attributes = match date_style { + Some(PresetLength::Full | PresetLength::Long) => "ldt", + Some(PresetLength::Medium) => "mdt", + _ => "sdt", + }; + + Ok(Plan::Parts { + date, + time, + zone, + glue: glue(preferences, attributes)?, + widths: Widths::default(), + }) +} + +#[optimize(speed)] +fn plan( + spec: &DatetimeSpec, + preferences: DateTimeFormatterPreferences, + sample: &DateTime, +) -> Result { + if spec.date_style.is_some() || spec.time_style.is_some() { + return preset_plan(preferences, spec.date_style, spec.time_style); + } + + let subsecond = match spec.fractional_second_digits { + None => None, + Some(1) => Some(SubsecondDigits::S1), + Some(2) => Some(SubsecondDigits::S2), + Some(_) => Some(SubsecondDigits::S3), + }; + + let has_time = spec.hour.is_some() + || spec.minute.is_some() + || spec.second.is_some() + || subsecond.is_some(); + + let precision = + spec.hour.map( + |_| match (subsecond, spec.second.is_some(), spec.minute.is_some()) { + (Some(digits), ..) => TimePrecision::Subsecond(digits), + (None, true, _) => TimePrecision::Second, + (None, false, true) => TimePrecision::Minute, + (None, false, false) => TimePrecision::Hour, + }, + ); + + let (fields, widths) = match date_fields(spec) { + None if !has_time => (Some(DateFields::YMD), Widths { + year: Some(NumericWidth::Numeric), + month: Some(MonthWidth::Numeric), + day: Some(NumericWidth::Numeric), + ..Widths::default() + }), + fields => (fields, Widths { + weekday: spec.weekday, + year: spec.year, + month: spec.month, + day: spec.day, + hour: match (spec.hour, precision) { + (Some(NumericWidth::Numeric), Some(TimePrecision::Hour)) => None, + (hour, _) => hour, + }, + }), + }; + + let time = if let Some(precision) = precision { + Some(Box::new(time_formatter(preferences, precision)?)) + } else if !has_time { + None + } else if fields.is_some() { + return Err("`minute` and `second` need an `hour` beside date fields".to_owned()); + } else { + let mut pattern = match ( + spec.minute.is_some(), + spec.second.is_some() || subsecond.is_some(), + ) { + (true, true) => "mm:ss", + (true, false) => "m", + (false, _) => "s", + } + .to_owned(); + + if let Some(digits) = spec.fractional_second_digits { + pattern.push('.'); + pattern.push_str(&"S".repeat(usize::from(digits.clamp(1, 3)))); + } + + let pattern = DateTimePattern::try_from_pattern_str(&pattern).map_err(error)?; + let mut names = FixedCalendarDateTimeNames::try_new(preferences).map_err(error)?; + names.include_for_pattern(&pattern).map_err(error)?; + return Ok(Plan::TimePattern { names, pattern }); + }; + + let date = fields + .map(|fields| date_formatter(preferences, fields, &widths, sample).map(Box::new)) + .transpose()?; + + let attributes = match widths.month { + Some(MonthWidth::Long) => "ldt", + Some(MonthWidth::Short) => "mdt", + _ => "sdt", + }; + + Ok(Plan::Parts { + date, + time, + zone: None, + glue: glue(preferences, attributes)?, + widths, + }) +} + +/// Renders instants by one [`DatetimeSpec`] in one locale, in the Gregorian +/// calendar. +pub struct DatetimeRenderer { + zone_id: String, + locale: String, + preferences: DateTimeFormatterPreferences, + plan: Plan, + names: Rc, + offsets: Offsets, + + /// Every pattern the plan's formatters have resolved to. + rewrites: RefCell>, + + /// The zone's name at each UTC offset it has been shown at. + zone_names: RefCell>, +} + +impl DatetimeRenderer { + #[optimize(speed)] + pub fn new( + spec: &DatetimeSpec, + locales: &[String], + names: Rc, + ) -> Result { + let locale: Locale = locale(locales); + let mut preferences = DateTimeFormatterPreferences::from(&locale); + match spec.hour12 { + Some(true) => preferences.hour_cycle = Some(HourCycle::Clock12), + Some(false) => preferences.hour_cycle = Some(HourCycle::Clock24), + None => {}, + } + + let offsets = match fixed_offset(&spec.time_zone) { + Some(offset) => Offsets::Fixed(offset), + None => { + let span = names + .utc_offset(&spec.time_zone, 0) + .ok_or_else(|| format!("Unknown time zone `{}`", spec.time_zone))?; + + let mut spans = BTreeMap::new(); + insert_span(&mut spans, span, 0); + Offsets::Spans(RefCell::new(spans)) + }, + }; + + Ok(Self { + plan: plan(spec, preferences, &local(0, 0)?)?, + zone_id: spec.time_zone.clone(), + locale: locale.to_string(), + preferences, + names, + offsets, + rewrites: RefCell::default(), + zone_names: RefCell::default(), + }) + } + + /// The zone's UTC offset in seconds at the instant `epoch_ms`. + #[optimize(speed)] + fn offset(&self, epoch_ms: i64) -> Result { + let spans = match &self.offsets { + Offsets::Fixed(offset) => return Ok(*offset), + Offsets::Spans(spans) => spans, + }; + + let found = spans + .borrow() + .range(..=epoch_ms) + .next_back() + .map(|(_, x)| *x) + .filter(|x| epoch_ms < x.end); + + if let Some(span) = found { + return Ok(span.offset); + } + + let span = self + .names + .utc_offset(&self.zone_id, epoch_ms) + .ok_or_else(|| format!("Unknown time zone `{}`", self.zone_id))?; + + insert_span(&mut spans.borrow_mut(), span, epoch_ms); + Ok(span.offset) + } + + /// Append `input` rendered by `formatter` with `widths` applied. + #[optimize(speed)] + fn write_part( + &self, + formatter: &Formatter, + widths: &Widths, + input: &DateTime, + out: &mut String, + ) -> Result<(), String> { + let formatted = formatter.format(input); + if *widths == Widths::default() { + return formatted.write_to(out).map_err(error); + } + + let source = formatted.pattern(); + let mut rewrites = self.rewrites.borrow_mut(); + let index = match rewrites.iter().position(|x| x.source == source) { + Some(index) => index, + None => { + let pattern: runtime::Pattern = formatted.pattern().into(); + let rewritten = match rewrite_widths(&pattern, widths) { + None => None, + Some(pattern) => { + let mut names = Names::try_new(self.preferences).map_err(error)?; + names.include_for_pattern(&pattern).map_err(error)?; + Some((names, pattern)) + }, + }; + + rewrites.push(Rewrite { source, rewritten }); + rewrites.len() - 1 + }, + }; + + match &rewrites[index].rewritten { + None => formatted.write_to(out).map_err(error), + Some((names, pattern)) => { + try_write(names.with_pattern_unchecked(pattern).format(input), out) + }, + } + } + + /// Append the time part of `input`, followed by the zone's name when + /// `zone` asks for one. + #[optimize(speed)] + fn write_time( + &self, + time: &Formatter, + zone: Option, + widths: &Widths, + moment: &Moment, + out: &mut String, + ) -> Result<(), String> { + self.write_part(time, widths, &moment.local, out)?; + if let Some(zone) = zone { + out.push(' '); + self.write_zone_name(moment, zone == ZoneName::Long, out); + } + + Ok(()) + } + + #[optimize(speed)] + fn write_zone_name(&self, moment: &Moment, long: bool, out: &mut String) { + let mut cache = self.zone_names.borrow_mut(); + let name = cache.entry(moment.offset).or_insert_with(|| { + self.names + .zone_name(&self.locale, &self.zone_id, moment.epoch_ms, long) + .unwrap_or_else(|| offset_name(moment.offset)) + }); + + out.push_str(name); + } + + #[optimize(speed)] + fn try_write(&self, epoch_ms: f64, out: &mut String) -> Result<(), String> { + let instant = epoch_ms.trunc() as i64; + let offset = self.offset(instant)?; + let moment = Moment { + epoch_ms, + offset, + local: local(instant, offset)?, + }; + + match &self.plan { + Plan::Parts { + date, + time, + zone, + glue, + widths, + } => match (date, time) { + (Some(date), Some(time)) => { + for item in glue.get().pattern.items.iter() { + match item { + GenericPatternItem::Placeholder(0) => { + self.write_time(time, *zone, widths, &moment, out)? + }, + GenericPatternItem::Placeholder(1) => { + self.write_part(date, widths, &moment.local, out)? + }, + GenericPatternItem::Placeholder(_) => {}, + GenericPatternItem::Literal(x) => out.push(x), + } + } + + Ok(()) + }, + (Some(date), None) => self.write_part(date, widths, &moment.local, out), + (None, Some(time)) => self.write_time(time, *zone, widths, &moment, out), + (None, None) => Ok(()), + }, + Plan::TimePattern { names, pattern } => try_write( + names + .with_pattern_unchecked(pattern) + .format(&moment.local.time), + out, + ), + } + } + + /// Append the text of the instant `epoch_ms` to `out`. + #[optimize(speed)] + pub fn write(&self, epoch_ms: f64, out: &mut String) { + let start = out.len(); + let written = if epoch_ms.is_finite() && epoch_ms.abs() <= MAX_EPOCH_MS { + self.try_write(epoch_ms, out) + } else { + Err(String::new()) + }; + + if written.is_err() { + out.truncate(start); + out.push_str(INVALID); + return; + } + + let mut from = start; + while let Some(found) = out[from..].find(NARROW_NO_BREAK_SPACE) { + let at = from + found; + out.replace_range(at..at + NARROW_NO_BREAK_SPACE.len_utf8(), " "); + from = at + 1; + } + } +} + +/// Whether the first of `locales` shows hours on a 12-hour clock by default. +#[optimize(speed)] +pub fn prefers_hour12(locales: &[String]) -> bool { + let preferences = DateTimeFormatterPreferences::from(&locale(locales)); + let (Ok(formatter), Ok(sample)) = ( + time_formatter(preferences, TimePrecision::Hour), + local(0, 0), + ) else { + return false; + }; + + let pattern: runtime::Pattern = formatter.format(&sample).pattern().into(); + pattern.items.iter().any(|item| { + matches!( + item, + PatternItem::Field(field) if matches!( + field.symbol, + FieldSymbol::Hour(fields::Hour::H11 | fields::Hour::H12) + ) + ) + }) +} diff --git a/rust/perspective-viewer/src/rust/format/digits.rs b/rust/perspective-viewer/src/rust/format/digits.rs new file mode 100644 index 0000000000..bb0fa3d291 --- /dev/null +++ b/rust/perspective-viewer/src/rust/format/digits.rs @@ -0,0 +1,140 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +use fixed_decimal::{ + Decimal, RoundingIncrement, SignDisplay, SignedRoundingMode, UnsignedRoundingMode, +}; + +use super::spec; + +#[optimize(speed)] +fn rounding_mode(mode: spec::RoundingMode) -> SignedRoundingMode { + match mode { + spec::RoundingMode::Ceil => SignedRoundingMode::Ceil, + spec::RoundingMode::Floor => SignedRoundingMode::Floor, + spec::RoundingMode::Expand => SignedRoundingMode::Unsigned(UnsignedRoundingMode::Expand), + spec::RoundingMode::Trunc => SignedRoundingMode::Unsigned(UnsignedRoundingMode::Trunc), + spec::RoundingMode::HalfCeil => SignedRoundingMode::HalfCeil, + spec::RoundingMode::HalfFloor => SignedRoundingMode::HalfFloor, + spec::RoundingMode::HalfExpand => { + SignedRoundingMode::Unsigned(UnsignedRoundingMode::HalfExpand) + }, + spec::RoundingMode::HalfTrunc => { + SignedRoundingMode::Unsigned(UnsignedRoundingMode::HalfTrunc) + }, + spec::RoundingMode::HalfEven => { + SignedRoundingMode::Unsigned(UnsignedRoundingMode::HalfEven) + }, + } +} + +/// `increment` as a power of ten to shift the rounding position by and the +/// multiple left over. +#[optimize(speed)] +fn split_increment(increment: u16) -> (i16, RoundingIncrement) { + let mut multiple = increment; + let mut shift = 0; + while multiple >= 10 && multiple % 10 == 0 { + multiple /= 10; + shift += 1; + } + + let multiple = match multiple { + 2 => RoundingIncrement::MultiplesOf2, + 5 => RoundingIncrement::MultiplesOf5, + 25 => RoundingIncrement::MultiplesOf25, + _ => RoundingIncrement::MultiplesOf1, + }; + + (shift, multiple) +} + +/// Round `decimal` to `max` fraction digits, keeping at least `min`, and +/// return the magnitude it was rounded at. +#[optimize(speed)] +fn round_fraction(decimal: &mut Decimal, (min, max): spec::Digits, spec: &spec::NumberSpec) -> i16 { + let (shift, increment) = split_increment(spec.rounding_increment); + let position = shift - i16::from(max); + decimal.round_with_mode_and_increment(position, rounding_mode(spec.rounding_mode), increment); + decimal.absolute.trim_end(); + decimal.absolute.pad_end(-i16::from(min)); + position +} + +/// Round `decimal` to `max` significant digits, keeping at least `min`, and +/// return the magnitude it was rounded at. +#[optimize(speed)] +fn round_significant( + decimal: &mut Decimal, + (min, max): spec::Digits, + spec: &spec::NumberSpec, +) -> i16 { + let position = decimal.absolute.nonzero_magnitude_start() - i16::from(max) + 1; + decimal.round_with_mode(position, rounding_mode(spec.rounding_mode)); + decimal.absolute.trim_end(); + decimal + .absolute + .pad_end(decimal.absolute.nonzero_magnitude_start() - i16::from(min) + 1); + + position +} + +/// Round `decimal` as `spec.rounding` describes. +#[optimize(speed)] +pub fn round(decimal: &mut Decimal, spec: &spec::NumberSpec) { + match spec.rounding { + spec::Rounding::FractionDigits(fraction) => { + round_fraction(decimal, fraction, spec); + }, + spec::Rounding::SignificantDigits(significant) => { + round_significant(decimal, significant, spec); + }, + spec::Rounding::MorePrecision { + fraction, + significant, + } + | spec::Rounding::LessPrecision { + fraction, + significant, + } => { + let mut by_fraction = decimal.clone(); + let fraction_position = round_fraction(&mut by_fraction, fraction, spec); + let significant_position = round_significant(decimal, significant, spec); + let more = matches!(spec.rounding, spec::Rounding::MorePrecision { .. }); + if more != (significant_position <= fraction_position) { + *decimal = by_fraction; + } + }, + } +} + +/// Apply the digit padding, trailing zero and sign rules of `spec` to an +/// already rounded `decimal`. +#[optimize(speed)] +pub fn finish(decimal: &mut Decimal, spec: &spec::NumberSpec) { + decimal.absolute.trim_start(); + decimal + .absolute + .pad_start(i16::from(spec.minimum_integer_digits)); + + if spec.trailing_zero_display == spec::TrailingZeroDisplay::StripIfInteger { + decimal.absolute.trim_end_if_integer(); + } + + decimal.apply_sign_display(match spec.sign_display { + spec::SignDisplay::Auto => SignDisplay::Auto, + spec::SignDisplay::Always => SignDisplay::Always, + spec::SignDisplay::ExceptZero => SignDisplay::ExceptZero, + spec::SignDisplay::Negative => SignDisplay::Negative, + spec::SignDisplay::Never => SignDisplay::Never, + }); +} diff --git a/rust/perspective-viewer/src/rust/format/locale_data.rs b/rust/perspective-viewer/src/rust/format/locale_data.rs new file mode 100644 index 0000000000..e17204f6ab --- /dev/null +++ b/rust/perspective-viewer/src/rust/format/locale_data.rs @@ -0,0 +1,70 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +/// What a number is measured in, when it is shown with a localized name. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum NameKind { + /// A currency by its ISO 4217 code, by its long name. + Currency(String), + + /// A unit by its `Intl.NumberFormat` identifier. + Unit { + unit: String, + display: super::spec::UnitDisplay, + }, +} + +/// A currency's symbol, and whether each of its ends counts as a letter, +/// which sets it apart by a space from a number written beside that end. +pub struct CurrencySymbol { + pub text: String, + pub starts_with_letter: bool, + pub ends_with_letter: bool, +} + +/// A UTC offset in seconds and the instants from `start` up to but not +/// including `end`, in milliseconds since the epoch, that share it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OffsetSpan { + pub offset: i32, + pub start: i64, + pub end: i64, +} + +/// Time zone rules and localized names a formatter looks up from outside +/// itself, so that the data behind them need not be linked into it. +pub trait LocaleData { + /// The IANA name of every time zone a formatter may be given. + fn time_zones(&self) -> Vec; + + /// The UTC offset of the time zone `zone` at the instant `epoch_ms` and + /// the span around it that shares it, or `None` when `zone` is not a + /// known time zone. + fn utc_offset(&self, zone: &str, epoch_ms: i64) -> Option; + + /// The name of the time zone `zone` at the instant `epoch_ms`, long or + /// short, in `locale`. + fn zone_name(&self, locale: &str, zone: &str, epoch_ms: f64, long: bool) -> Option; + + /// The symbol of the currency `code` in `locale`, narrow or not. + fn currency_symbol(&self, locale: &str, code: &str, narrow: bool) -> Option; + + /// The text of `value` shown with `fraction_digits` fraction digits as + /// `kind` in `locale`, with the number replaced by `{0}`. + fn pattern( + &self, + locale: &str, + kind: &NameKind, + value: f64, + fraction_digits: u8, + ) -> Option; +} diff --git a/rust/perspective-viewer/src/rust/format/mod.rs b/rust/perspective-viewer/src/rust/format/mod.rs new file mode 100644 index 0000000000..afa7c2829f --- /dev/null +++ b/rust/perspective-viewer/src/rust/format/mod.rs @@ -0,0 +1,159 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +#[cfg(feature = "bundled-locale-data")] +mod baked_data; +mod datetime; +mod digits; +mod locale_data; +mod number; +pub mod spec; + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::{Rc, Weak}; + +#[cfg(feature = "bundled-locale-data")] +pub use baked_data::BakedData; +pub use datetime::prefers_hour12; +use icu_locale_core::Locale; +pub use locale_data::{CurrencySymbol, LocaleData, NameKind, OffsetSpan}; +pub use number::currency_digits; +use spec::FormatSpec; + +/// The first of `locales` that is a well-formed language tag, else the root +/// locale. +#[optimize(speed)] +fn locale(locales: &[String]) -> Locale { + locales + .iter() + .find_map(|x| Locale::try_from_str(x).ok()) + .unwrap_or(Locale::UNKNOWN) +} + +/// A column of formatted values: the texts concatenated, and the end of each +/// one as an offset in UTF-16 code units. +pub struct FormattedColumn { + pub text: String, + pub ends: Vec, +} + +enum Renderer { + Number(Box), + Datetime(Box), + Boolean, +} + +type Key = (FormatSpec, Vec); + +struct Shared { + key: Key, + renderer: Renderer, +} + +thread_local! { + static FORMATTERS: RefCell>> = RefCell::default(); +} + +/// Formats values by one [`FormatSpec`] for one locale list, sharing its +/// renderer with every other `Formatter` built from the same two, which +/// should therefore always be given the same [`LocaleData`]. +pub struct Formatter(Rc); + +impl Drop for Formatter { + #[optimize(speed)] + fn drop(&mut self) { + if Rc::strong_count(&self.0) == 1 { + let _ = FORMATTERS.try_with(|x| x.borrow_mut().remove(&self.0.key)); + } + } +} + +impl Formatter { + /// A formatter for `spec` in the first of `locales` with data, or an + /// error naming what `spec` asks for that cannot be rendered. + #[optimize(speed)] + pub fn new( + spec: &FormatSpec, + locales: &[String], + names: &Rc, + ) -> Result { + let key = (spec.clone(), locales.to_vec()); + let shared = FORMATTERS.with_borrow(|x| x.get(&key).and_then(Weak::upgrade)); + if let Some(shared) = shared { + return Ok(Self(shared)); + } + + let renderer = + match spec { + FormatSpec::Number(spec) => Renderer::Number(Box::new( + number::NumberRenderer::new(spec, locales, names.clone())?, + )), + FormatSpec::Datetime(spec) => Renderer::Datetime(Box::new( + datetime::DatetimeRenderer::new(spec, locales, names.clone())?, + )), + FormatSpec::Boolean => Renderer::Boolean, + }; + + let shared = Rc::new(Shared { + key: key.clone(), + renderer, + }); + + FORMATTERS.with_borrow_mut(|x| x.insert(key, Rc::downgrade(&shared))); + Ok(Self(shared)) + } + + /// Append the text of `value` to `out`. + #[optimize(speed)] + pub fn write(&self, value: f64, out: &mut String) { + match &self.0.renderer { + Renderer::Number(x) => x.write(value, out), + Renderer::Datetime(x) => x.write(value, out), + Renderer::Boolean => out.push_str(if value != 0. && !value.is_nan() { + "true" + } else { + "false" + }), + } + } + + /// The text of `value`. + #[optimize(speed)] + pub fn format(&self, value: f64) -> String { + let mut out = String::new(); + self.write(value, &mut out); + out + } + + /// The text of every one of `values`. + #[optimize(speed)] + pub fn format_column(&self, values: &[f64]) -> FormattedColumn { + let mut text = String::new(); + let mut ends = Vec::with_capacity(values.len()); + let mut end = 0; + for value in values { + let start = text.len(); + self.write(*value, &mut text); + let written = &text[start..]; + end += if written.is_ascii() { + written.len() as u32 + } else { + written.encode_utf16().count() as u32 + }; + + ends.push(end); + } + + FormattedColumn { text, ends } + } +} diff --git a/rust/perspective-viewer/src/rust/format/number.rs b/rust/perspective-viewer/src/rust/format/number.rs new file mode 100644 index 0000000000..32f64092f1 --- /dev/null +++ b/rust/perspective-viewer/src/rust/format/number.rs @@ -0,0 +1,510 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use fixed_decimal::{Decimal, FloatPrecision, Sign}; +use icu_decimal::options::{DecimalFormatterOptions, GroupingStrategy}; +use icu_decimal::preferences::CompactDecimalFormatterPreferences; +use icu_decimal::provider::{DecimalDigitsV1, DecimalSymbolsV1}; +use icu_decimal::{CompactDecimalFormatter, DecimalFormatter, DecimalFormatterPreferences}; +use icu_experimental::dimension::currency::CurrencyType; +use icu_experimental::dimension::currency::formatter::CurrencyFormatterPreferences; +use icu_experimental::dimension::provider::currency::essentials::CurrencyEssentialsV1; +use icu_experimental::dimension::provider::currency::fractions::CurrencyFractionsV1; +use icu_experimental::dimension::provider::currency::symbols::CurrencyDecimalSymbolsV1; +use icu_experimental::dimension::provider::percent::DecimalPercentV1; +use icu_experimental::provider::Baked; +use icu_locale_core::Locale; +use icu_plurals::{PluralCategory, PluralRules}; +use icu_provider::prelude::*; +use writeable::Writeable; + +use super::locale_data::{CurrencySymbol, LocaleData, NameKind}; +use super::spec::{self, NumberSpec}; +use super::{digits, locale}; + +/// Decimal symbols with the per-currency overrides some locales carry. +struct CurrencySymbolsProvider(CurrencyType); + +impl DataProvider for CurrencySymbolsProvider { + #[optimize(speed)] + fn load(&self, request: DataRequest) -> Result, DataError> { + let mut metadata = request.metadata; + metadata.silent = true; + let overridden = DataProvider::::load(&Baked, DataRequest { + id: DataIdentifierBorrowed::for_marker_attributes_and_locale( + CurrencyDecimalSymbolsV1::make_attributes( + DecimalSymbolsV1::parse_attributes(request.id.marker_attributes), + self.0, + &mut Default::default(), + ), + request.id.locale, + ), + metadata, + }) + .allow_identifier_not_found()?; + + match overridden { + Some(response) => Ok(response.cast()), + None => icu_decimal::provider::Baked.load(request), + } + } +} + +impl DataProvider for CurrencySymbolsProvider { + #[optimize(speed)] + fn load(&self, request: DataRequest) -> Result, DataError> { + icu_decimal::provider::Baked.load(request) + } +} + +/// What a number's digits are wrapped in. +enum Decoration { + Plain, + Percent(DataPayload), + Currency { + essentials: DataPayload, + symbols: DataPayload, + text: String, + starts_with_letter: bool, + ends_with_letter: bool, + accounting: bool, + }, + + /// A currency or unit by its localized name, looked up per plural + /// category. + Named { + kind: NameKind, + plurals: PluralRules, + + /// The pattern used when no name is found, `{0}` standing for the + /// number. + fallback: String, + patterns: RefCell>, + }, +} + +/// The symbols of units whose names are commonly missing from locale data, as +/// `(identifier, symbol, narrow symbol, spaced)`. +const UNIT_SYMBOLS: [(&str, &str, &str, bool); 15] = [ + ("bit", "bit", "bit", true), + ("byte", "byte", "B", true), + ("kilobit", "kb", "kb", true), + ("kilobyte", "kB", "kB", true), + ("megabit", "Mb", "Mb", true), + ("megabyte", "MB", "MB", true), + ("gigabit", "Gb", "Gb", true), + ("gigabyte", "GB", "GB", true), + ("terabit", "Tb", "Tb", true), + ("terabyte", "TB", "TB", true), + ("petabyte", "PB", "PB", true), + ("celsius", "\u{b0}C", "\u{b0}C", false), + ("fahrenheit", "\u{b0}F", "\u{b0}F", false), + ("degree", "deg", "\u{b0}", true), + ("percent", "%", "%", false), +]; + +#[optimize(speed)] +fn data_error(err: DataError) -> String { + err.to_string() +} + +impl Decoration { + #[optimize(speed)] + fn new(spec: &NumberSpec, locale: &Locale, names: &dyn LocaleData) -> Result { + match &spec.style { + spec::NumberStyle::Decimal => Ok(Self::Plain), + spec::NumberStyle::Percent => { + let data_locale = DecimalPercentV1::make_locale(locale.into()); + let response: DataResponse = Baked + .load(DataRequest { + id: DataIdentifierBorrowed::for_locale(&data_locale), + ..Default::default() + }) + .map_err(data_error)?; + + Ok(Self::Percent(response.payload)) + }, + spec::NumberStyle::Currency { + code, + display, + sign, + } => { + let currency: CurrencyType = code + .parse() + .map_err(|_| format!("Unknown currency `{code}`"))?; + + let preferences: CurrencyFormatterPreferences = locale.into(); + let narrow = match display { + spec::CurrencyDisplay::Symbol => Some(false), + spec::CurrencyDisplay::NarrowSymbol => Some(true), + spec::CurrencyDisplay::Code => None, + spec::CurrencyDisplay::Name => { + return Self::named( + NameKind::Currency(code.clone()), + locale, + format!("{{0}} {}", currency.iso_code()), + ); + }, + }; + + let data_locale = CurrencyEssentialsV1::make_locale(preferences.locale_preferences); + let essentials: DataResponse = Baked + .load(DataRequest { + id: DataIdentifierBorrowed::for_locale(&data_locale), + ..Default::default() + }) + .map_err(data_error)?; + + let decimal_preferences: DecimalFormatterPreferences = (&preferences).into(); + let symbols: DataResponse = CurrencySymbolsProvider(currency) + .load(DataRequest { + id: DataIdentifierBorrowed::for_locale(&DecimalSymbolsV1::make_locale( + decimal_preferences.locale_preferences, + )), + ..Default::default() + }) + .map_err(data_error)?; + + let symbol = narrow + .and_then(|narrow| names.currency_symbol(&locale.to_string(), code, narrow)) + .unwrap_or_else(|| CurrencySymbol { + text: currency.iso_code().to_string(), + starts_with_letter: true, + ends_with_letter: true, + }); + + Ok(Self::Currency { + essentials: essentials.payload, + symbols: symbols.payload, + text: symbol.text, + starts_with_letter: symbol.starts_with_letter, + ends_with_letter: symbol.ends_with_letter, + accounting: *sign == spec::CurrencySign::Accounting, + }) + }, + spec::NumberStyle::Unit { unit, display } => { + let fallback = match UNIT_SYMBOLS.iter().find(|x| x.0 == unit) { + Some((_, _, narrow, _)) if *display == spec::UnitDisplay::Narrow => { + format!("{{0}}{narrow}") + }, + Some((_, symbol, _, true)) => format!("{{0}} {symbol}"), + Some((_, symbol, _, false)) => format!("{{0}}{symbol}"), + None => format!("{{0}} {unit}"), + }; + + Self::named( + NameKind::Unit { + unit: unit.clone(), + display: *display, + }, + locale, + fallback, + ) + }, + } + } + + #[optimize(speed)] + fn named(kind: NameKind, locale: &Locale, fallback: String) -> Result { + Ok(Self::Named { + kind, + plurals: PluralRules::try_new_cardinal(locale.into()).map_err(data_error)?, + fallback, + patterns: RefCell::default(), + }) + } +} + +/// Renders numbers by one [`NumberSpec`] in one locale. +pub struct NumberRenderer { + spec: NumberSpec, + number: DecimalFormatter, + compact: Option, + decoration: Decoration, + locale: String, + names: Rc, +} + +impl NumberRenderer { + #[optimize(speed)] + pub fn new( + spec: &NumberSpec, + locales: &[String], + names: Rc, + ) -> Result { + let locale = locale(locales); + let grouping = match spec.grouping { + spec::Grouping::Always => GroupingStrategy::Always, + spec::Grouping::Auto => GroupingStrategy::Auto, + spec::Grouping::Min2 => GroupingStrategy::Min2, + spec::Grouping::Never => GroupingStrategy::Never, + }; + + let options: DecimalFormatterOptions = grouping.into(); + let decoration = Decoration::new(spec, &locale, &*names)?; + let number = match (&decoration, &spec.style) { + (Decoration::Currency { .. }, spec::NumberStyle::Currency { code, .. }) => { + let currency: CurrencyType = code + .parse() + .map_err(|_| format!("Unknown currency `{code}`"))?; + + let preferences: CurrencyFormatterPreferences = (&locale).into(); + DecimalFormatter::try_new_unstable( + &CurrencySymbolsProvider(currency), + (&preferences).into(), + options, + ) + }, + _ => DecimalFormatter::try_new((&locale).into(), options), + } + .map_err(data_error)?; + + let compact = match spec.notation { + spec::Notation::Compact(display) => { + let preferences: CompactDecimalFormatterPreferences = (&locale).into(); + let options = grouping.into(); + Some( + match display { + spec::CompactDisplay::Short => { + CompactDecimalFormatter::try_new_short(preferences, options) + }, + spec::CompactDisplay::Long => { + CompactDecimalFormatter::try_new_long(preferences, options) + }, + } + .map_err(data_error)?, + ) + }, + _ => None, + }; + + Ok(Self { + spec: spec.clone(), + number, + compact, + decoration, + locale: locale.to_string(), + names, + }) + } + + /// The power of ten a number whose leading digit has `magnitude` is + /// divided by before its digits are shown. + #[optimize(speed)] + fn exponent_for(&self, magnitude: i16) -> i16 { + match (&self.spec.notation, &self.compact) { + (spec::Notation::Scientific, _) => magnitude, + (spec::Notation::Engineering, _) => magnitude.div_euclid(3) * 3, + (spec::Notation::Compact(_), Some(compact)) => { + i16::from(compact.compact_exponent_for_magnitude(magnitude)) + }, + _ => 0, + } + } + + /// Round `decimal` in place, first dividing it by the power of ten its + /// notation calls for, and return that power. + #[optimize(speed)] + fn scale(&self, decimal: &mut Decimal) -> i16 { + if self.spec.notation == spec::Notation::Standard || decimal.absolute.is_zero() { + digits::round(decimal, &self.spec); + return 0; + } + + let magnitude = decimal.absolute.nonzero_magnitude_start(); + let scaled = |exponent: i16| { + let mut scaled = decimal.clone(); + scaled.multiply_pow10(-exponent); + digits::round(&mut scaled, &self.spec); + scaled + }; + + let mut exponent = self.exponent_for(magnitude); + let mut rounded = scaled(exponent); + if !rounded.absolute.is_zero() + && rounded.absolute.nonzero_magnitude_start() != magnitude - exponent + { + exponent = self.exponent_for(magnitude + 1); + rounded = scaled(exponent); + } + + *decimal = rounded; + exponent + } + + /// Append the digits of `decimal` in this renderer's notation. + #[optimize(speed)] + fn write_number(&self, decimal: &Decimal, exponent: i16, out: &mut String) { + let _ = match (&self.spec.notation, &self.compact) { + (spec::Notation::Scientific | spec::Notation::Engineering, _) => self + .number + .format(decimal) + .write_to(out) + .map(|_| out.push('E')) + .and_then(|_| self.number.format(&Decimal::from(exponent)).write_to(out)), + (spec::Notation::Compact(_), Some(compact)) => { + match compact.format_with_exponent(decimal, exponent.clamp(0, 255) as u8) { + Ok(formatted) => formatted.write_to(out), + Err(_) => self.number.format(decimal).write_to(out), + } + }, + _ => self.number.format(decimal).write_to(out), + }; + } + + /// Append the text of `value` to `out`. + #[optimize(speed)] + pub fn write(&self, value: f64, out: &mut String) { + let Ok(mut decimal) = Decimal::try_from_f64(value, FloatPrecision::RoundTrip) else { + out.push_str(if value.is_nan() { + "NaN" + } else if value > 0. { + "\u{221e}" + } else { + "-\u{221e}" + }); + + return; + }; + + if self.spec.style == spec::NumberStyle::Percent { + decimal.multiply_pow10(2); + } + + let exponent = self.scale(&mut decimal); + digits::finish(&mut decimal, &self.spec); + let unsigned = || { + let mut number = String::new(); + let absolute = decimal.clone().with_sign(Sign::None); + self.write_number(&absolute, exponent, &mut number); + number + }; + + let _ = match &self.decoration { + Decoration::Plain => { + self.write_number(&decimal, exponent, out); + Ok(()) + }, + Decoration::Percent(essentials) => { + let essentials = essentials.get(); + let number = unsigned(); + match decimal.sign() { + Sign::Negative => essentials + .signed_pattern + .interpolate((number.as_str(), &*essentials.minus_sign)) + .write_to(out), + Sign::Positive => essentials + .signed_pattern + .interpolate((number.as_str(), &*essentials.plus_sign)) + .write_to(out), + Sign::None => essentials + .unsigned_pattern + .interpolate([number.as_str()]) + .write_to(out), + } + }, + Decoration::Currency { + essentials, + symbols, + text, + starts_with_letter, + ends_with_letter, + accounting, + } => { + let essentials = essentials.get(); + let (starts, ends) = (*starts_with_letter, *ends_with_letter); + let number = unsigned(); + let negative = match (decimal.sign(), accounting) { + (Sign::Negative, true) => essentials.get_negative_accounting(starts, ends), + (Sign::Negative, false) => essentials.get_negative(starts, ends), + _ => None, + }; + + match negative { + Some(pattern) => pattern + .interpolate((number.as_str(), text.as_str())) + .write_to(out), + None => { + let strings = &symbols.get().strings; + let (prefix, suffix) = match decimal.sign() { + Sign::None => ("", ""), + Sign::Negative => { + (strings.minus_sign_prefix(), strings.minus_sign_suffix()) + }, + Sign::Positive => { + (strings.plus_sign_prefix(), strings.plus_sign_suffix()) + }, + }; + + let pattern = if *accounting { + essentials.get_positive_accounting(starts, ends) + } else { + essentials.get_positive(starts, ends) + }; + + out.push_str(prefix); + let written = pattern + .interpolate((number.as_str(), text.as_str())) + .write_to(out); + + out.push_str(suffix); + written + }, + } + }, + Decoration::Named { + kind, + plurals, + fallback, + patterns, + } => { + let mut number = String::new(); + self.write_number(&decimal, exponent, &mut number); + let mut patterns = patterns.borrow_mut(); + let pattern = patterns + .entry(plurals.category_for(&decimal)) + .or_insert_with(|| { + let absolute = decimal.absolute.to_string().parse().unwrap_or(0.); + let fraction_digits = + (-decimal.absolute.magnitude_range().start()).clamp(0, 255) as u8; + + self.names + .pattern(&self.locale, kind, absolute, fraction_digits) + .unwrap_or_else(|| fallback.clone()) + }); + + out.push_str(&pattern.replacen("{0}", &number, 1)); + Ok(()) + }, + }; + } +} + +/// The number of fraction digits amounts in the currency `code` are shown +/// with, `2` when it is not known. +#[optimize(speed)] +pub fn currency_digits(code: &str) -> u8 { + let Ok(currency) = code.parse::() else { + return 2; + }; + + let fractions: Result, DataError> = + Baked.load(Default::default()); + + fractions + .map(|x| x.payload.get().resolve(currency).digits) + .unwrap_or(2) +} diff --git a/rust/perspective-viewer/src/rust/format/spec.rs b/rust/perspective-viewer/src/rust/format/spec.rs new file mode 100644 index 0000000000..94062041a3 --- /dev/null +++ b/rust/perspective-viewer/src/rust/format/spec.rs @@ -0,0 +1,196 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +/// How a number is presented: plain, as a percentage, as money or with a +/// unit of measure. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum NumberStyle { + Decimal, + Percent, + Currency { + code: String, + display: CurrencyDisplay, + sign: CurrencySign, + }, + Unit { + unit: String, + display: UnitDisplay, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CurrencyDisplay { + Code, + Symbol, + NarrowSymbol, + Name, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CurrencySign { + Standard, + Accounting, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum UnitDisplay { + Short, + Narrow, + Long, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Notation { + Standard, + Scientific, + Engineering, + Compact(CompactDisplay), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CompactDisplay { + Short, + Long, +} + +/// A `(minimum, maximum)` digit count. +pub type Digits = (u8, u8); + +/// Which digits of a number survive rounding. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Rounding { + FractionDigits(Digits), + SignificantDigits(Digits), + + /// Whichever of the two keeps more digits. + MorePrecision { + fraction: Digits, + significant: Digits, + }, + + /// Whichever of the two keeps fewer digits. + LessPrecision { + fraction: Digits, + significant: Digits, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum RoundingMode { + Ceil, + Floor, + Expand, + Trunc, + HalfCeil, + HalfFloor, + HalfExpand, + HalfTrunc, + HalfEven, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum TrailingZeroDisplay { + Auto, + StripIfInteger, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Grouping { + Always, + Auto, + Min2, + Never, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum SignDisplay { + Auto, + Always, + ExceptZero, + Negative, + Never, +} + +/// A fully resolved number format, with no defaults left to apply. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct NumberSpec { + pub style: NumberStyle, + pub notation: Notation, + pub minimum_integer_digits: u8, + pub rounding: Rounding, + + /// The multiple of the last fraction digit to round to, `1` for none. + pub rounding_increment: u16, + pub rounding_mode: RoundingMode, + pub trailing_zero_display: TrailingZeroDisplay, + pub grouping: Grouping, + pub sign_display: SignDisplay, +} + +/// The length of a date or time preset. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PresetLength { + Full, + Long, + Medium, + Short, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum TextWidth { + Narrow, + Short, + Long, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum NumericWidth { + Numeric, + TwoDigit, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MonthWidth { + Numeric, + TwoDigit, + Narrow, + Short, + Long, +} + +/// A fully resolved datetime format: either presets or per-part fields, in a +/// named time zone. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct DatetimeSpec { + pub date_style: Option, + pub time_style: Option, + pub weekday: Option, + pub year: Option, + pub month: Option, + pub day: Option, + pub hour: Option, + pub minute: Option, + pub second: Option, + pub fractional_second_digits: Option, + pub hour12: Option, + + /// An IANA time zone name. + pub time_zone: String, +} + +/// What a [`super::Formatter`] renders. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum FormatSpec { + Number(NumberSpec), + Datetime(DatetimeSpec), + Boolean, +} diff --git a/rust/perspective-viewer/src/rust/lib.rs b/rust/perspective-viewer/src/rust/lib.rs index 9c3499b8ba..0e2e09627b 100644 --- a/rust/perspective-viewer/src/rust/lib.rs +++ b/rust/perspective-viewer/src/rust/lib.rs @@ -36,7 +36,9 @@ pub mod custom_elements; mod custom_events; mod derived; pub mod exprtk; +mod format; mod js; +mod plugin_utils; mod presentation; mod root; @@ -51,10 +53,6 @@ pub mod ui; pub mod utils; mod workspace; -#[macro_use] -extern crate macro_rules_attribute; -extern crate alloc; - use std::cell::RefCell; use perspective_js::utils::*; @@ -125,6 +123,10 @@ export type ExportData = | Record | ViewerConfig; +import type {CustomNumberFormatConfig} from "../ts-rs/CustomNumberFormatConfig.d.ts"; +import type {NumberFormatStyle} from "../ts-rs/NumberFormatStyle.d.ts"; +import type {Notation} from "../ts-rs/Notation.d.ts"; +import type {DatetimeFormat} from "../ts-rs/DatetimeFormat.d.ts"; import type {GetTableOptions} from "../ts-rs/GetTableOptions.d.ts"; import type {PanelOptions} from "../ts-rs/PanelOptions.d.ts"; import type {RestoreOptions} from "../ts-rs/RestoreOptions.d.ts"; @@ -149,6 +151,68 @@ import type {CommandSchemaOptions} from "../ts-rs/CommandSchemaOptions.d.ts"; import type {PerspectiveHit} from "../ts-rs/PerspectiveHit.d.ts"; import type {PerspectiveHitRef} from "../ts-rs/PerspectiveHitRef.d.ts"; +/** A column of formatted values: one string and the UTF-16 end offset of each value in it. */ +export interface FormattedColumn { + text: string; + ends: Uint32Array; +} + +/** + * A numeric column's `number_format`, as the Style tab writes it: the ts-rs + * `CustomNumberFormatConfig` with its flattened `style` and `notation` + * families, which ts-rs cannot flatten and exports separately. + */ +export type NumberFormatConfig = CustomNumberFormatConfig & + Partial & + Partial; + +/** A datetime column's `date_format`, a subset of `Intl.DateTimeFormatOptions`. */ +export type DateFormatConfig = DatetimeFormat; + +/** The `date_format` options that apply individually rather than as one group. */ +export type DateFormatModifiers = Pick; + +/** + * A formatter for the values of a column of `column_type`, or `undefined` for + * a type whose values are not formatted, given the column's `number_format` + * or `date_format` and the calling plugin's default for the same key. + * + * @example + * ```javascript + * const formatter = viewer.plugin_utils.formatter("float", { style: "percent" }); + * console.log(formatter.format(0.25)); + * ``` + */ +export function formatter( + column_type: ColumnType, + format?: NumberFormatConfig | DateFormatConfig, + defaults?: NumberFormatConfig | DateFormatConfig, +): Formatter | undefined; + +/** + * Whether the `date_format` `format` sets any of the keys that apply as one + * group (a preset or any date or time part), rather than only `timeZone` or + * `hour12`. + */ +export function has_date_format_shape(format?: DateFormatConfig): boolean; + +/** + * The keys of the `date_format` `format` that apply individually, `timeZone` + * and `hour12`, or `undefined` when it sets neither. + */ +export function date_format_modifiers( + format?: DateFormatConfig, +): DateFormatModifiers | undefined; + +/** A color's red, green and blue channels, each in `[0, 255]`. */ +export type RGB = [number, number, number]; + +/** One stop of a color scale: a color at `offset` in `[0, 1]`. */ +export interface GradientStopRgb { + rgb: RGB; + offset: number; +} + /** A surface a command schema is evaluated for. */ export type PerspectiveCommandLocation = CommandLocation; @@ -335,9 +399,14 @@ pub fn getColumnConfigDefaults() -> ApiResult { /// preserve backwards-compatible synchronous API). #[cfg(not(feature = "external-bootstrap"))] #[wasm_bindgen(js_name = "init")] -pub fn js_init(module: js_sys::WebAssembly::Module, url: web_sys::Url) { +pub fn js_init( + module: js_sys::WebAssembly::Module, + url: web_sys::Url, + #[wasm_bindgen(unchecked_param_type = "unknown")] plugin_utils: JsValue, +) { console_error_panic_hook::set_once(); perspective_js::utils::set_global_logging(); + crate::plugin_utils::set_plugin_utils(plugin_utils); define_web_components!("export * as psp from '../../perspective-viewer.js'"); MODULE.with_borrow_mut(|f| { *f = Some((module, url)); diff --git a/rust/perspective-viewer/src/rust/plugin_utils.rs b/rust/perspective-viewer/src/rust/plugin_utils.rs new file mode 100644 index 0000000000..5af10248b8 --- /dev/null +++ b/rust/perspective-viewer/src/rust/plugin_utils.rs @@ -0,0 +1,731 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +mod resolve; + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::LazyLock; + +use perspective_js::utils::*; +use wasm_bindgen::prelude::*; + +use crate::config::{CustomNumberFormatConfig, DatetimeFormat}; +use crate::format; +use crate::format::spec::{FormatSpec, UnitDisplay}; +use crate::format::{CurrencySymbol, LocaleData, NameKind, OffsetSpan}; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "FormattedColumn")] + pub type JsFormattedColumn; +} + +#[wasm_bindgen(inline_js = " + export function split_column(text, ends) { + const out = new Array(ends.length); + let start = 0; + for (let i = 0; i < ends.length; i++) { + out[i] = text.substring(start, ends[i]); + start = ends[i]; + } + + return out; + } + + export function long_offset(format, epoch_ms) { + try { + for (const part of format.formatToParts(epoch_ms)) { + if (part.type === \"timeZoneName\") { + return part.value; + } + } + } catch { + return undefined; + } + } + + export function temporal_offset(zone, epoch_ms, out) { + try { + const time = Temporal.Instant.fromEpochMilliseconds(epoch_ms).toZonedDateTimeISO(zone); + const previous = time.add({ nanoseconds: 1 }).getTimeZoneTransition(\"previous\"); + const next = time.getTimeZoneTransition(\"next\"); + out[0] = time.offsetNanoseconds / 1e9; + out[1] = previous === null ? -Infinity : previous.epochMilliseconds; + out[2] = next === null ? Infinity : next.epochMilliseconds; + return true; + } catch { + return false; + } + } +")] +extern "C" { + fn split_column(text: &str, ends: &js_sys::Uint32Array) -> js_sys::Array; + fn long_offset(format: &JsValue, epoch_ms: f64) -> Option; + fn temporal_offset(zone: &str, epoch_ms: f64, out: &mut [f64]) -> bool; +} + +struct SessionLocale { + languages: Vec, + time_zone: String, +} + +fn property(object: &JsValue, name: &str) -> Option { + js_sys::Reflect::get(object, &JsValue::from(name)) + .ok() + .filter(|x| !x.is_undefined()) +} + +static SESSION_LOCALE: LazyLock = LazyLock::new(|| { + let languages = property(&js_sys::global(), "navigator") + .and_then(|x| property(&x, "languages")) + .and_then(|x| x.dyn_into::().ok()) + .map(|x| x.iter().filter_map(|x| x.as_string()).collect()) + .unwrap_or_default(); + + let options = js_sys::Intl::DateTimeFormat::new(&js_sys::Array::new(), &js_sys::Object::new()) + .resolved_options(); + + let time_zone = property(&options, "timeZone") + .and_then(|x| x.as_string()) + .unwrap_or_else(|| "UTC".to_owned()); + + SessionLocale { + languages, + time_zone, + } +}); + +/// The browser's language preferences, most preferred first. +pub fn languages() -> &'static [String] { + &SESSION_LOCALE.languages +} + +/// The IANA name of the browser's time zone. +pub fn local_time_zone() -> &'static str { + &SESSION_LOCALE.time_zone +} + +/// `Intl.` for `locale` with `options`, or `None` when it +/// rejects them. +fn intl(constructor: &str, locale: &str, options: &[(&str, JsValue)]) -> Option { + let intl = property(&js_sys::global(), "Intl")?; + let constructor: js_sys::Function = property(&intl, constructor)?.dyn_into().ok()?; + let bag = js_sys::Object::new(); + for (key, value) in options { + js_sys::Reflect::set(&bag, &JsValue::from(*key), value).ok()?; + } + + let locales = js_sys::Array::of1(&JsValue::from(locale)); + js_sys::Reflect::construct(&constructor, &js_sys::Array::of2(&locales, &bag)).ok() +} + +/// The parts `formatter`'s `formatToParts` splits `value` into, as +/// `(type, value)`. +fn format_to_parts(formatter: &JsValue, value: &JsValue) -> Option> { + let format: js_sys::Function = property(formatter, "formatToParts")?.dyn_into().ok()?; + let parts: js_sys::Array = format.call1(formatter, value).ok()?.dyn_into().ok()?; + parts + .iter() + .map(|part| { + Some(( + property(&part, "type")?.as_string()?, + property(&part, "value")?.as_string()?, + )) + }) + .collect() +} + +/// `Intl.` for `locale` with `options`, applied by its +/// `formatToParts` to `value`. +fn intl_parts( + constructor: &str, + locale: &str, + options: &[(&str, JsValue)], + value: &JsValue, +) -> Option> { + format_to_parts(&intl(constructor, locale, options)?, value) +} + +/// The seconds east of UTC of a `longOffset` time zone name such as `GMT`, +/// `GMT-05:00` or `GMT+05:30:00`. +fn parse_long_offset(name: &str) -> Option { + let offset = name.strip_prefix("GMT")?; + if offset.is_empty() { + return Some(0); + } + + let mut chars = offset.chars(); + let sign = match chars.next()? { + '+' => 1, + '-' | '\u{2212}' => -1, + _ => return None, + }; + + let mut seconds = 0; + let mut fields = 0; + for (field, scale) in chars.as_str().split(':').zip([3600, 60, 1]) { + seconds += field.parse::().ok()? * scale; + fields += 1; + } + + (fields > 0).then_some(sign * seconds) +} + +/// Looks up time zone rules and localized names with the browser's `Intl`, +/// so that the data behind them is not linked into this binary. +struct BrowserData { + /// Whether the browser has `Temporal`, whose time zones report their + /// transitions. + temporal: bool, + + /// The `Intl.DateTimeFormat` naming each time zone by its UTC offset, or + /// `None` for a name the browser does not know. + offset_formats: RefCell>>, +} + +impl BrowserData { + fn new() -> Self { + Self { + temporal: property(&js_sys::global(), "Temporal").is_some(), + offset_formats: RefCell::default(), + } + } + + /// The UTC offset in seconds of `zone` at the instant `epoch_ms`, by + /// `Intl`. + fn intl_offset(&self, zone: &str, epoch_ms: i64) -> Option { + let mut formats = self.offset_formats.borrow_mut(); + if !formats.contains_key(zone) { + let format = intl("DateTimeFormat", "en-US", &[ + ("timeZone", JsValue::from(zone)), + ("timeZoneName", JsValue::from("longOffset")), + ]); + + formats.insert(zone.to_owned(), format); + } + + parse_long_offset(&long_offset(formats.get(zone)?.as_ref()?, epoch_ms as f64)?) + } + + /// The span between the transitions of `zone` around the instant + /// `epoch_ms`, by `Temporal`. + fn temporal_span(&self, zone: &str, epoch_ms: i64) -> Option { + let mut out = [0.; 3]; + (self.temporal && temporal_offset(zone, epoch_ms as f64, &mut out)).then(|| OffsetSpan { + offset: out[0].round() as i32, + start: out[1] as i64, + end: out[2] as i64, + }) + } +} + +/// The lengths in milliseconds of the blocks of time `BrowserData` takes to +/// share one UTC offset when its ends do, without `Temporal`. +const OFFSET_BLOCKS_MS: [i64; 2] = [86_400_000, 3_600_000]; + +/// The latest and earliest instants a JavaScript `Date` can hold, in +/// milliseconds. +const MAX_EPOCH_MS: i64 = 8_640_000_000_000_000; + +impl LocaleData for BrowserData { + fn time_zones(&self) -> Vec { + property(&js_sys::global(), "Intl") + .and_then(|intl| { + let supported: js_sys::Function = + property(&intl, "supportedValuesOf")?.dyn_into().ok()?; + supported + .call1(&intl, &JsValue::from("timeZone")) + .ok()? + .dyn_into::() + .ok() + }) + .map(|x| x.iter().filter_map(|x| x.as_string()).collect()) + .unwrap_or_default() + } + + fn utc_offset(&self, zone: &str, epoch_ms: i64) -> Option { + if let Some(span) = self.temporal_span(zone, epoch_ms) { + return Some(span); + } + + for block in OFFSET_BLOCKS_MS { + let start = epoch_ms.div_euclid(block) * block; + let first = start.max(-MAX_EPOCH_MS); + let last = (start + block - 1).min(MAX_EPOCH_MS); + let offset = self.intl_offset(zone, first)?; + if offset == self.intl_offset(zone, last)? { + return Some(OffsetSpan { + offset, + start, + end: start + block, + }); + } + } + + Some(OffsetSpan { + offset: self.intl_offset(zone, epoch_ms)?, + start: epoch_ms, + end: epoch_ms + 1, + }) + } + + /// The symbol's ends both count as letters when `Intl` spaces it from the + /// number beside it, as only the end beside the number is ever consulted. + fn currency_symbol(&self, locale: &str, code: &str, narrow: bool) -> Option { + let parts = intl_parts( + "NumberFormat", + locale, + &[ + ("style", JsValue::from("currency")), + ("currency", JsValue::from(code)), + ( + "currencyDisplay", + JsValue::from(if narrow { "narrowSymbol" } else { "symbol" }), + ), + ], + &JsValue::from(1), + )?; + + let symbol = parts.iter().position(|(kind, _)| kind == "currency")?; + let number = parts.iter().position(|(kind, _)| kind == "integer")?; + let spaced = parts[symbol.min(number) + 1..symbol.max(number)] + .iter() + .any(|(kind, value)| kind == "literal" && value.chars().any(char::is_whitespace)); + + Some(CurrencySymbol { + text: parts[symbol].1.clone(), + starts_with_letter: spaced, + ends_with_letter: spaced, + }) + } + + fn zone_name(&self, locale: &str, zone: &str, epoch_ms: f64, long: bool) -> Option { + let parts = intl_parts( + "DateTimeFormat", + locale, + &[ + ("timeZone", JsValue::from(zone)), + ( + "timeZoneName", + JsValue::from(if long { "long" } else { "short" }), + ), + ], + &js_sys::Date::new(&JsValue::from(epoch_ms)), + )?; + + parts + .into_iter() + .find_map(|(kind, value)| (kind == "timeZoneName").then_some(value)) + } + + fn pattern( + &self, + locale: &str, + kind: &NameKind, + value: f64, + fraction_digits: u8, + ) -> Option { + let digits = JsValue::from(fraction_digits.min(100)); + let mut options = vec![ + ("minimumFractionDigits", digits.clone()), + ("maximumFractionDigits", digits), + ]; + + match kind { + NameKind::Currency(code) => options.extend([ + ("style", JsValue::from("currency")), + ("currency", JsValue::from(code)), + ("currencyDisplay", JsValue::from("name")), + ]), + NameKind::Unit { unit, display } => options.extend([ + ("style", JsValue::from("unit")), + ("unit", JsValue::from(unit)), + ( + "unitDisplay", + JsValue::from(match display { + UnitDisplay::Short => "short", + UnitDisplay::Narrow => "narrow", + UnitDisplay::Long => "long", + }), + ), + ]), + } + + let parts = intl_parts("NumberFormat", locale, &options, &JsValue::from(value))?; + let mut pattern = String::new(); + let mut placed = false; + for (kind, value) in &parts { + if matches!(kind.as_str(), "integer" | "group" | "decimal" | "fraction") { + if !placed { + pattern.push_str("{0}"); + placed = true; + } + } else { + pattern.push_str(value); + } + } + + (!parts.is_empty()).then_some(pattern) + } +} + +thread_local! { + static LOCALE_DATA: Rc = if cfg!(feature = "bundled-locale-data") { + baked_data() + } else { + Rc::new(BrowserData::new()) + }; +} + +#[cfg(feature = "bundled-locale-data")] +fn baked_data() -> Rc { + Rc::new(format::BakedData) +} + +#[cfg(not(feature = "bundled-locale-data"))] +fn baked_data() -> Rc { + Rc::new(BrowserData::new()) +} + +/// The IANA name of every time zone a datetime format may name. +pub fn time_zones() -> Vec { + LOCALE_DATA.with(|x| x.time_zones()) +} + +fn optional(value: JsValue) -> ApiResult> { + if value.is_undefined() || value.is_null() { + Ok(None) + } else { + let value: serde_json::Value = value.into_serde_ext()?; + Ok(Some(serde_json::from_value(value)?)) + } +} + +/// The [`FormatSpec`] of a column of `column_type` given its format and the +/// calling plugin's default, or `None` for a type whose values are not +/// formatted. +fn format_spec( + column_type: &str, + format: JsValue, + defaults: JsValue, +) -> ApiResult> { + let spec = match column_type { + "integer" | "float" => FormatSpec::Number(resolve::number_spec( + column_type == "float", + optional::(format)?.as_ref(), + optional::(defaults)?.as_ref(), + format::currency_digits, + )?), + "datetime" => FormatSpec::Datetime(resolve::datetime_spec( + optional::(format)?.as_ref(), + optional::(defaults)?.as_ref(), + local_time_zone(), + )?), + "date" => FormatSpec::Datetime(resolve::date_spec( + optional::(format)?.as_ref(), + optional::(defaults)?.as_ref(), + )?), + "boolean" => FormatSpec::Boolean, + _ => return Ok(None), + }; + + Ok(Some(spec)) +} + +/// A handle to a formatter for one column type and format, from +/// [`formatter`]. +#[wasm_bindgen] +pub struct Formatter(format::Formatter); + +#[wasm_bindgen] +impl Formatter { + /// The text of `value`. + /// + /// # JavaScript Examples + /// + /// ```javascript + /// const formatter = viewer.plugin_utils.formatter("float"); + /// console.log(formatter.format(1234.5)); + /// ``` + pub fn format(&self, value: f64) -> String { + self.0.format(value) + } + + /// The text of every one of `values`, concatenated, with the end offset + /// of each. + /// + /// # JavaScript Examples + /// + /// ```javascript + /// const { text, ends } = formatter.format_column(new Float64Array([1, 2.5])); + /// console.log(text.substring(0, ends[0]), text.substring(ends[0], ends[1])); + /// ``` + pub fn format_column(&self, values: &[f64]) -> JsFormattedColumn { + let format::FormattedColumn { text, ends } = self.0.format_column(values); + let column = js_sys::Object::new(); + let _ = js_sys::Reflect::set(&column, &JsValue::from("text"), &JsValue::from(text)); + let _ = js_sys::Reflect::set( + &column, + &JsValue::from("ends"), + &js_sys::Uint32Array::from(ends.as_slice()), + ); + + column.unchecked_into() + } + + /// The text of every one of `values`, one string per value. + /// + /// # JavaScript Examples + /// + /// ```javascript + /// const [a, b] = formatter.format_strings(new Float64Array([1, 2.5])); + /// ``` + #[wasm_bindgen(unchecked_return_type = "string[]")] + pub fn format_strings(&self, values: &[f64]) -> js_sys::Array { + let format::FormattedColumn { text, ends } = self.0.format_column(values); + split_column(&text, &js_sys::Uint32Array::from(ends.as_slice())) + } +} + +impl Formatter { + /// A formatter for values of `spec` in the browser's languages. + pub fn new(spec: &FormatSpec) -> ApiResult { + let names = LOCALE_DATA.with(Rc::clone); + Ok(Self(format::Formatter::new(spec, languages(), &names)?)) + } + + /// The formatter of an integer column with no `number_format`. + pub fn integer() -> ApiResult { + let spec = resolve::number_spec(false, None, None, format::currency_digits)?; + Self::new(&FormatSpec::Number(spec)) + } +} + +/// A formatter for the values of a column of `column_type`, or `undefined` +/// for a type whose values are not formatted, given the column's +/// `number_format` or `date_format` and the calling plugin's default for the +/// same key. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// const formatter = viewer.plugin_utils.formatter("float", { style: "percent" }); +/// console.log(formatter.format(0.25)); +/// ``` +#[wasm_bindgen(skip_typescript)] +pub fn formatter( + column_type: String, + format: Option, + defaults: Option, +) -> ApiResult { + let format = format.unwrap_or(JsValue::UNDEFINED); + let defaults = defaults.unwrap_or(JsValue::UNDEFINED); + Ok(match format_spec(&column_type, format, defaults)? { + Some(spec) => Formatter::new(&spec)?.into(), + None => JsValue::UNDEFINED, + }) +} + +/// The source column name of a `split_by` column path, its last `|` +/// separated segment. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// console.log(viewer.plugin_utils.source_column("East|Sales")); +/// ``` +#[wasm_bindgen] +pub fn source_column(path: String) -> String { + match path.rsplit_once('|') { + Some((_, name)) => name.to_owned(), + None => path, + } +} + +/// Whether the `date_format` `format` sets any of the keys that apply as one +/// group (a preset or any date or time part), rather than only `timeZone` or +/// `hour12`. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// viewer.plugin_utils.has_date_format_shape({ dateStyle: "short" }); // true +/// viewer.plugin_utils.has_date_format_shape({ timeZone: "UTC" }); // false +/// ``` +#[wasm_bindgen(skip_typescript)] +pub fn has_date_format_shape(format: Option) -> ApiResult { + let format = optional::(format.unwrap_or(JsValue::UNDEFINED))?; + Ok(format.is_some_and(|x| x.has_shape())) +} + +/// The keys of the `date_format` `format` that apply individually, +/// `timeZone` and `hour12`, or `undefined` when it sets neither. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// const modifiers = viewer.plugin_utils.date_format_modifiers({ +/// dateStyle: "short", +/// timeZone: "UTC", +/// }); +/// ``` +#[wasm_bindgen(skip_typescript)] +pub fn date_format_modifiers(format: Option) -> ApiResult { + let modifiers = optional::(format.unwrap_or(JsValue::UNDEFINED))? + .map(|x| DatetimeFormat { + time_zone: x.time_zone, + hour12: x.hour12, + ..DatetimeFormat::default() + }) + .filter(|x| x.time_zone.is_some() || x.hour12.is_some()); + + Ok(to_js(&modifiers)) +} + +/// The channels of a `#rrggbb` color. +fn hex_rgb(hex: &str) -> Option<[u8; 3]> { + let channel = |at: usize| u8::from_str_radix(hex.get(at..at + 2)?, 16).ok(); + Some([channel(1)?, channel(3)?, channel(5)?]) +} + +#[derive(serde::Deserialize, serde::Serialize)] +struct GradientStopRgb { + rgb: [u8; 3], + offset: f64, +} + +fn to_js(value: &Option) -> JsValue { + JsValue::from_serde_ext(value).unwrap_or(JsValue::UNDEFINED) +} + +/// The channels of a color literal of the viewer's config grammar (`#rgb`, +/// `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` or `rgba()`, alpha ignored), or +/// `undefined` for anything else. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// const [r, g, b] = viewer.plugin_utils.parse_css_color("rgb(255, 0, 0)"); +/// ``` +#[wasm_bindgen(unchecked_return_type = "RGB | undefined")] +pub fn parse_css_color(src: &str) -> JsValue { + to_js( + &crate::utils::normalize_css_color(src) + .ok() + .and_then(|x| hex_rgb(&x)), + ) +} + +/// The stops of a gradient value of the viewer's config grammar, a +/// `linear-gradient()` of at least two color literals with optional `%` +/// positions, sorted with every position resolved, or `undefined` for +/// anything else, including a `var()` reference. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// const stops = viewer.plugin_utils.parse_css_gradient( +/// "linear-gradient(to right, #000, #fff 80%)", +/// ); +/// ``` +#[wasm_bindgen(unchecked_return_type = "GradientStopRgb[] | undefined")] +pub fn parse_css_gradient(src: &str) -> JsValue { + let stops: Option> = match crate::utils::CssGradient::parse(src) { + Ok(crate::utils::CssGradient::Literal(stops)) => stops + .iter() + .map(|stop| { + Some(GradientStopRgb { + rgb: hex_rgb(&stop.color)?, + offset: stop.offset, + }) + }) + .collect(), + _ => None, + }; + + to_js(&stops) +} + +/// The colors of a palette value of the viewer's config grammar, a +/// `linear-gradient()` of color literals with no positions, or `undefined` +/// for anything else, including a `var()` reference. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// const colors = viewer.plugin_utils.parse_css_palette( +/// "linear-gradient(to right, #f00, #0f0)", +/// ); +/// ``` +#[wasm_bindgen(unchecked_return_type = "RGB[] | undefined")] +pub fn parse_css_palette(src: &str) -> JsValue { + let colors = match crate::utils::CssPalette::parse(src) { + Ok(crate::utils::CssPalette::Literal(colors)) => colors + .iter() + .map(|x| hex_rgb(x)) + .collect::>>(), + _ => None, + }; + + to_js(&colors) +} + +/// The viewer's canonical gradient value for `stops`, sorted with every +/// position explicit to 0.1%. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// const css = viewer.plugin_utils.css_gradient([ +/// { color: "#000000", offset: 0 }, +/// { color: "#ffffff", offset: 1 }, +/// ]); +/// ``` +#[wasm_bindgen] +pub fn css_gradient( + #[wasm_bindgen(unchecked_param_type = "Array<{ color: string; offset: number }>")] + stops: JsValue, +) -> ApiResult { + let stops: Vec = stops.into_serde_ext()?; + Ok(crate::utils::gradient_to_css(&stops)) +} + +/// The viewer's canonical palette value for `colors`, with no positions. +/// +/// # JavaScript Examples +/// +/// ```javascript +/// const css = viewer.plugin_utils.css_palette(["#ff0000", "#00ff00"]); +/// ``` +#[wasm_bindgen] +pub fn css_palette(colors: Vec) -> String { + crate::utils::palette_to_css(&colors) +} + +thread_local! { + static PLUGIN_UTILS: RefCell = const { RefCell::new(JsValue::UNDEFINED) }; +} + +/// Keep `utils`, the object the TypeScript bootstrap builds from this +/// module's exports and its own helpers, as the element's `plugin_utils`. +pub fn set_plugin_utils(utils: JsValue) { + PLUGIN_UTILS.set(utils); +} + +/// The object kept by [`set_plugin_utils`], backing the element's static +/// `plugin_utils`. +#[wasm_bindgen(skip_typescript)] +pub fn plugin_utils() -> JsValue { + PLUGIN_UTILS.with_borrow(Clone::clone) +} diff --git a/rust/perspective-viewer/src/rust/plugin_utils/resolve.rs b/rust/perspective-viewer/src/rust/plugin_utils/resolve.rs new file mode 100644 index 0000000000..6bf1e078cd --- /dev/null +++ b/rust/perspective-viewer/src/rust/plugin_utils/resolve.rs @@ -0,0 +1,402 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +use crate::config::*; +use crate::format::spec; + +const MAX_FRACTION_DIGITS: f64 = 100.; +const MAX_SIGNIFICANT_DIGITS: f64 = 21.; +const ROUNDING_INCREMENTS: [u16; 15] = [ + 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000, +]; + +/// The `number_format` a float or integer column renders with when neither it +/// nor its plugin declares one. +fn legacy_number_format(is_float: bool) -> CustomNumberFormatConfig { + if is_float { + CustomNumberFormatConfig { + _style: Some(NumberFormatStyle::Decimal), + minimum_fraction_digits: Some(2.), + maximum_fraction_digits: Some(2.), + ..CustomNumberFormatConfig::default() + } + } else { + CustomNumberFormatConfig::default() + } +} + +/// `upper` layered over `base`, where `style`, `notation`, the fraction digit +/// pair and the significant digit pair are each taken whole from whichever +/// sets any part of them. +fn merge_number_format( + base: &CustomNumberFormatConfig, + upper: &CustomNumberFormatConfig, +) -> CustomNumberFormatConfig { + let fraction = + if upper.minimum_fraction_digits.is_some() || upper.maximum_fraction_digits.is_some() { + upper + } else { + base + }; + + let significant = if upper.minimum_significant_digits.is_some() + || upper.maximum_significant_digits.is_some() + { + upper + } else { + base + }; + + CustomNumberFormatConfig { + _style: upper._style.clone().or_else(|| base._style.clone()), + minimum_integer_digits: upper.minimum_integer_digits.or(base.minimum_integer_digits), + minimum_fraction_digits: fraction.minimum_fraction_digits, + maximum_fraction_digits: fraction.maximum_fraction_digits, + minimum_significant_digits: significant.minimum_significant_digits, + maximum_significant_digits: significant.maximum_significant_digits, + rounding_priority: upper.rounding_priority.or(base.rounding_priority), + rounding_increment: upper.rounding_increment.or(base.rounding_increment), + rounding_mode: upper.rounding_mode.or(base.rounding_mode), + trailing_zero_display: upper.trailing_zero_display.or(base.trailing_zero_display), + _notation: upper._notation.clone().or_else(|| base._notation.clone()), + use_grouping: upper.use_grouping.or(base.use_grouping), + sign_display: upper.sign_display.or(base.sign_display), + } +} + +/// `value` as a whole digit count within `min..=max`. +fn digits(name: &str, value: f64, min: f64, max: f64) -> Result { + let value = value.floor(); + if value.is_nan() || value < min || value > max { + Err(format!("`{name}` must be between {min} and {max}")) + } else { + Ok(value as u8) + } +} + +fn number_style(style: NumberFormatStyle) -> spec::NumberStyle { + match style { + NumberFormatStyle::Decimal => spec::NumberStyle::Decimal, + NumberFormatStyle::Percent => spec::NumberStyle::Percent, + NumberFormatStyle::Currency(currency) => spec::NumberStyle::Currency { + code: currency.currency.to_string(), + display: match currency.currency_display.unwrap_or_default() { + CurrencyDisplay::Code => spec::CurrencyDisplay::Code, + CurrencyDisplay::Symbol => spec::CurrencyDisplay::Symbol, + CurrencyDisplay::NarrowSymbol => spec::CurrencyDisplay::NarrowSymbol, + CurrencyDisplay::Name => spec::CurrencyDisplay::Name, + }, + sign: match currency.currency_sign.unwrap_or_default() { + CurrencySign::Standard => spec::CurrencySign::Standard, + CurrencySign::Accounting => spec::CurrencySign::Accounting, + }, + }, + NumberFormatStyle::Unit(unit) => spec::NumberStyle::Unit { + unit: serde_json::to_value(unit.unit) + .ok() + .and_then(|x| x.as_str().map(str::to_owned)) + .unwrap_or_default(), + display: match unit.unit_display.unwrap_or_default() { + UnitDisplay::Short => spec::UnitDisplay::Short, + UnitDisplay::Narrow => spec::UnitDisplay::Narrow, + UnitDisplay::Long => spec::UnitDisplay::Long, + }, + }, + } +} + +/// The format a column of the given numeric type renders with: `format` +/// layered over `defaults`, then completed by the `Intl.NumberFormat` +/// defaulting rules. +pub fn number_spec( + is_float: bool, + format: Option<&CustomNumberFormatConfig>, + defaults: Option<&CustomNumberFormatConfig>, + currency_digits: impl Fn(&str) -> u8, +) -> Result { + let base = defaults + .cloned() + .unwrap_or_else(|| legacy_number_format(is_float)); + + let merged = match format { + Some(format) => merge_number_format(&base, format), + None => base, + }; + + let style = number_style(merged._style.clone().unwrap_or_default()); + let notation = match merged._notation.clone().unwrap_or_default() { + Notation::Standard => spec::Notation::Standard, + Notation::Scientific => spec::Notation::Scientific, + Notation::Engineering => spec::Notation::Engineering, + Notation::Compact(CompactDisplay::Short) => { + spec::Notation::Compact(spec::CompactDisplay::Short) + }, + Notation::Compact(CompactDisplay::Long) => { + spec::Notation::Compact(spec::CompactDisplay::Long) + }, + }; + + let rounding_increment = match merged.rounding_increment { + None => 1, + Some(x) => ROUNDING_INCREMENTS + .into_iter() + .find(|y| f64::from(*y) == x) + .ok_or_else(|| format!("`roundingIncrement` {x} is not supported"))?, + }; + + let (default_min_fraction, default_max_fraction) = match (&style, notation) { + (spec::NumberStyle::Currency { code, .. }, spec::Notation::Standard) => { + let digits = currency_digits(code); + (digits, digits) + }, + (spec::NumberStyle::Percent, _) => (0, 0), + _ if rounding_increment != 1 => (0, 0), + _ => (0, 3), + }; + + let minimum_integer_digits = match merged.minimum_integer_digits { + None => 1, + Some(x) => digits("minimumIntegerDigits", x, 1., MAX_SIGNIFICANT_DIGITS)?, + }; + + let priority = merged.rounding_priority.unwrap_or_default(); + let has_significant = + merged.minimum_significant_digits.is_some() || merged.maximum_significant_digits.is_some(); + + let has_fraction = + merged.minimum_fraction_digits.is_some() || merged.maximum_fraction_digits.is_some(); + + let is_compact = matches!(notation, spec::Notation::Compact(_)); + let (need_significant, need_fraction) = match priority { + RoundingPriority::Auto => ( + has_significant, + !(has_significant || !has_fraction && is_compact), + ), + _ => (true, true), + }; + + let significant = if has_significant { + let min = match merged.minimum_significant_digits { + None => 1, + Some(x) => digits("minimumSignificantDigits", x, 1., MAX_SIGNIFICANT_DIGITS)?, + }; + + let max = match merged.maximum_significant_digits { + None => MAX_SIGNIFICANT_DIGITS as u8, + Some(x) => digits( + "maximumSignificantDigits", + x, + f64::from(min), + MAX_SIGNIFICANT_DIGITS, + )?, + }; + + (min, max) + } else { + (1, MAX_SIGNIFICANT_DIGITS as u8) + }; + + let fraction = if has_fraction { + let min = merged + .minimum_fraction_digits + .map(|x| digits("minimumFractionDigits", x, 0., MAX_FRACTION_DIGITS)) + .transpose()?; + + let max = merged + .maximum_fraction_digits + .map(|x| digits("maximumFractionDigits", x, 0., MAX_FRACTION_DIGITS)) + .transpose()?; + + match (min, max) { + (Some(min), Some(max)) if min > max => { + return Err(format!( + "`minimumFractionDigits` {min} exceeds `maximumFractionDigits` {max}" + )); + }, + (Some(min), Some(max)) => (min, max), + (Some(min), None) => (min, default_max_fraction.max(min)), + (None, Some(max)) => (default_min_fraction.min(max), max), + (None, None) => (default_min_fraction, default_max_fraction), + } + } else { + (default_min_fraction, default_max_fraction) + }; + + let rounding = if !need_significant && !need_fraction { + spec::Rounding::MorePrecision { + fraction: (0, 0), + significant: (1, 2), + } + } else { + match priority { + RoundingPriority::MorePrecision => spec::Rounding::MorePrecision { + fraction, + significant, + }, + RoundingPriority::LessPrecision => spec::Rounding::LessPrecision { + fraction, + significant, + }, + RoundingPriority::Auto if has_significant => { + spec::Rounding::SignificantDigits(significant) + }, + RoundingPriority::Auto => spec::Rounding::FractionDigits(fraction), + } + }; + + if rounding_increment != 1 { + match rounding { + spec::Rounding::FractionDigits((min, max)) if min == max => {}, + spec::Rounding::FractionDigits(_) => { + return Err( + "`roundingIncrement` needs equal `minimumFractionDigits` and \ + `maximumFractionDigits`" + .to_owned(), + ); + }, + _ => { + return Err( + "`roundingIncrement` cannot be combined with significant digits or a \ + `roundingPriority`" + .to_owned(), + ); + }, + } + } + + Ok(spec::NumberSpec { + style, + notation, + minimum_integer_digits, + rounding, + rounding_increment, + rounding_mode: match merged.rounding_mode.unwrap_or_default() { + RoundingMode::Ceil => spec::RoundingMode::Ceil, + RoundingMode::Floor => spec::RoundingMode::Floor, + RoundingMode::Expand => spec::RoundingMode::Expand, + RoundingMode::Trunc => spec::RoundingMode::Trunc, + RoundingMode::HalfCeil => spec::RoundingMode::HalfCeil, + RoundingMode::HalfFloor => spec::RoundingMode::HalfFloor, + RoundingMode::HalfExpand => spec::RoundingMode::HalfExpand, + RoundingMode::HalfTrunc => spec::RoundingMode::HalfTrunc, + RoundingMode::HalfEven => spec::RoundingMode::HalfEven, + }, + trailing_zero_display: match merged.trailing_zero_display.unwrap_or_default() { + TrailingZeroDisplay::Auto => spec::TrailingZeroDisplay::Auto, + TrailingZeroDisplay::StripIfInteger => spec::TrailingZeroDisplay::StripIfInteger, + }, + grouping: match merged.use_grouping { + None if is_compact => spec::Grouping::Min2, + None | Some(UseGrouping::Auto) => spec::Grouping::Auto, + Some(UseGrouping::Always | UseGrouping::False(true)) => spec::Grouping::Always, + Some(UseGrouping::Min2) => spec::Grouping::Min2, + Some(UseGrouping::False(false)) => spec::Grouping::Never, + }, + sign_display: match merged.sign_display.unwrap_or_default() { + SignDisplay::Auto => spec::SignDisplay::Auto, + SignDisplay::Always => spec::SignDisplay::Always, + SignDisplay::ExceptZero => spec::SignDisplay::ExceptZero, + SignDisplay::Negative => spec::SignDisplay::Negative, + SignDisplay::Never => spec::SignDisplay::Never, + }, + }) +} + +fn preset(length: SimpleDatetimeFormat) -> spec::PresetLength { + match length { + SimpleDatetimeFormat::Full => spec::PresetLength::Full, + SimpleDatetimeFormat::Long => spec::PresetLength::Long, + SimpleDatetimeFormat::Medium => spec::PresetLength::Medium, + SimpleDatetimeFormat::Short => spec::PresetLength::Short, + } +} + +fn numeric(part: DatetimeNumericPart) -> spec::NumericWidth { + match part { + DatetimeNumericPart::Numeric => spec::NumericWidth::Numeric, + DatetimeNumericPart::TwoDigit => spec::NumericWidth::TwoDigit, + } +} + +/// `format` layered over `defaults` and then `base` by the `date_format` +/// group rule. +fn layer_date_format( + base: DatetimeFormat, + format: Option<&DatetimeFormat>, + defaults: Option<&DatetimeFormat>, +) -> Result { + let mut resolved = base; + for layer in [defaults, format].into_iter().flatten() { + layer.validate()?; + resolved = resolved.overlay(layer); + } + + Ok(resolved) +} + +/// The format a `datetime` column renders with, in `local_zone` unless the +/// format names a time zone. +pub fn datetime_spec( + format: Option<&DatetimeFormat>, + defaults: Option<&DatetimeFormat>, + local_zone: &str, +) -> Result { + let resolved = layer_date_format(DatetimeFormat::base(true), format, defaults)?; + Ok(spec::DatetimeSpec { + date_style: resolved.date_style.map(preset), + time_style: resolved.time_style.map(preset), + weekday: resolved.weekday.map(|x| match x { + DatetimeTextPart::Long => spec::TextWidth::Long, + DatetimeTextPart::Short => spec::TextWidth::Short, + DatetimeTextPart::Narrow => spec::TextWidth::Narrow, + }), + year: resolved.year.map(numeric), + month: resolved.month.map(|x| match x { + DatetimeMonthPart::Numeric => spec::MonthWidth::Numeric, + DatetimeMonthPart::TwoDigit => spec::MonthWidth::TwoDigit, + DatetimeMonthPart::Long => spec::MonthWidth::Long, + DatetimeMonthPart::Short => spec::MonthWidth::Short, + DatetimeMonthPart::Narrow => spec::MonthWidth::Narrow, + }), + day: resolved.day.map(numeric), + hour: resolved.hour.map(numeric), + minute: resolved.minute.map(numeric), + second: resolved.second.map(numeric), + fractional_second_digits: resolved.fractional_second_digits.map(|x| x.get()), + hour12: resolved.hour12, + time_zone: resolved.time_zone.unwrap_or_else(|| local_zone.to_owned()), + }) +} + +/// The format a `date` column renders with: a date preset alone, in UTC. +pub fn date_spec( + format: Option<&DatetimeFormat>, + defaults: Option<&DatetimeFormat>, +) -> Result { + let resolved = layer_date_format(DatetimeFormat::base(false), format, defaults)?; + Ok(spec::DatetimeSpec { + date_style: Some(preset( + resolved.date_style.unwrap_or(SimpleDatetimeFormat::Short), + )), + time_style: None, + weekday: None, + year: None, + month: None, + day: None, + hour: None, + minute: None, + second: None, + fractional_second_digits: None, + hour12: None, + time_zone: "UTC".to_owned(), + }) +} diff --git a/rust/perspective-viewer/src/rust/renderer.rs b/rust/perspective-viewer/src/rust/renderer.rs index 4e4772b5c0..a505a53be2 100644 --- a/rust/perspective-viewer/src/rust/renderer.rs +++ b/rust/perspective-viewer/src/rust/renderer.rs @@ -463,7 +463,7 @@ impl Renderer { } pub fn is_chart(&self) -> bool { - self.metadata().name.as_str() != "Datagrid" + !self.metadata().renders_text } /// Whether the active plugin opts into per-column style controls. @@ -830,7 +830,7 @@ impl Renderer { if has_plugin { let config = self.metadata(); let plugin_name = Some(config.name.clone()); - let is_chart = config.name.as_str() != "Datagrid"; + let is_chart = !config.renders_text; let available_plugins = self .get_all_plugin_configs() .into_iter() diff --git a/rust/perspective-viewer/src/rust/session/column_defaults_update.rs b/rust/perspective-viewer/src/rust/session/column_defaults_update.rs index 3d84db8227..b574d8922d 100644 --- a/rust/perspective-viewer/src/rust/session/column_defaults_update.rs +++ b/rust/perspective-viewer/src/rust/session/column_defaults_update.rs @@ -59,6 +59,22 @@ pub impl ViewConfigUpdate { ); } + let flips_to_rollup = self.group_rollup_mode.unwrap_or(current.group_rollup_mode) + == GroupRollupMode::Total + && self.group_by.as_ref().is_some_and(|x| !x.is_empty()); + + if flips_to_rollup + && !group_rollups.is_empty() + && !group_rollups.contains(&GroupRollupMode::Rollup) + { + match group_rollups.iter().find(|x| **x != GroupRollupMode::Total) { + Some(mode) => self.group_rollup_mode = Some(*mode), + None => self.group_by = None, + } + + tracing::debug!("`group_by` needs a rollup mode the plugin does not accept"); + } + let split_rollup_features = metadata .get_features() .map(|x| x.get_split_rollup_modes()) diff --git a/rust/perspective-viewer/src/rust/utils/custom_element.rs b/rust/perspective-viewer/src/rust/utils/custom_element.rs index a3e204f826..ea59242678 100644 --- a/rust/perspective-viewer/src/rust/utils/custom_element.rs +++ b/rust/perspective-viewer/src/rust/utils/custom_element.rs @@ -15,7 +15,7 @@ use wasm_bindgen::prelude::*; #[wasm_bindgen(inline_js = r#" - export function bootstrap(psp, name, clsname, statics) { + export function bootstrap(psp, name, clsname, statics, static_getters) { if (customElements.get(name)) { console.warn(`Custom element "${name}" is already registered; skipping duplicate registration (Perspective was loaded more than once on this page).`); return; @@ -55,12 +55,26 @@ use wasm_bindgen::prelude::*; }); } + for (const key of static_getters) { + Object.defineProperty(x, key, { + get: function() { + return psp[key].call(psp); + } + }); + } + customElements.define(name, x); } "#)] extern "C" { #[wasm_bindgen(js_name = "bootstrap")] - fn js_bootstrap(psp: &JsValue, name: &str, cls: &str, statics: js_sys::Array) -> JsValue; + fn js_bootstrap( + psp: &JsValue, + name: &str, + cls: &str, + statics: js_sys::Array, + static_getters: js_sys::Array, + ) -> JsValue; } /// A trait which allows the [`define_web_component`] method to create a @@ -75,6 +89,10 @@ pub trait CustomElementMetadata { /// element. const STATICS: &'static [&'static str] = [].as_slice(); + /// [optional] The names of the module functions which should be static + /// getters on the element. + const STATIC_GETTERS: &'static [&'static str] = [].as_slice(); + /// [optional] The name of the Rust struct. const TYPE_NAME: &'static str = std::any::type_name::(); @@ -95,5 +113,10 @@ pub fn define_web_component(module: &JsValue) { T::CUSTOM_ELEMENT_NAME, T::struct_name(), T::STATICS.iter().cloned().map(JsValue::from).collect(), + T::STATIC_GETTERS + .iter() + .cloned() + .map(JsValue::from) + .collect(), ); } diff --git a/rust/perspective-viewer/src/rust/utils/number_format.rs b/rust/perspective-viewer/src/rust/utils/number_format.rs index ee58e22612..86e7adeadd 100644 --- a/rust/perspective-viewer/src/rust/utils/number_format.rs +++ b/rust/perspective-viewer/src/rust/utils/number_format.rs @@ -10,40 +10,20 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -use std::sync::LazyLock; +use crate::plugin_utils::Formatter; -use js_sys::Intl; -use perspective_js::json; -use perspective_js::utils::global::navigator; -use wasm_bindgen::JsValue; - -struct UnsafeNumberFormat(Intl::NumberFormat); - -// JavaScript does not allow threading, but we do not have a non-threadsafe -// way to conveniently make lazy static caches of JavaScript ref values. -unsafe impl Send for UnsafeNumberFormat {} -unsafe impl Sync for UnsafeNumberFormat {} - -static NUMBER_FORMAT: LazyLock = LazyLock::new(|| { - let locale = navigator().languages(); - let opts = json!({}); - let number_format = Intl::NumberFormat::new(&locale, &opts); - UnsafeNumberFormat(number_format) -}); - -impl UnsafeNumberFormat {} +thread_local! { + static NUMBER_FORMAT: Option = Formatter::integer().ok(); +} /// Trait for the [`u32::to_formatted_string`] method. #[extend::ext] pub impl u32 { - /// Format integers consistenly using the Browser's native `NumberFormat`. + /// Format integers consistently, in the browser's locale. fn to_formatted_string(&self) -> String { - NUMBER_FORMAT - .0 - .format() - .call1(&NUMBER_FORMAT.0, &JsValue::from_f64(*self as f64)) - .unwrap() - .as_string() - .unwrap() + NUMBER_FORMAT.with(|x| match x { + Some(formatter) => formatter.format(f64::from(*self)), + None => self.to_string(), + }) } } diff --git a/rust/perspective-viewer/src/svg/mega-menu-icons-summary.svg b/rust/perspective-viewer/src/svg/mega-menu-icons-summary.svg new file mode 100644 index 0000000000..a9193ab738 --- /dev/null +++ b/rust/perspective-viewer/src/svg/mega-menu-icons-summary.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + diff --git a/rust/perspective-viewer/src/themes/icons.css b/rust/perspective-viewer/src/themes/icons.css index a22c3972dd..f76d08fd42 100644 --- a/rust/perspective-viewer/src/themes/icons.css +++ b/rust/perspective-viewer/src/themes/icons.css @@ -92,6 +92,7 @@ perspective-viewer-tab { --psp-plugin-selector--y-line--content: url(../svg/mega-menu-icons-y-line.svg); --psp-plugin-selector--y-scatter--content: url(../svg/mega-menu-icons-y-scatter.svg); --psp-plugin-selector--datagrid--content: url(../svg/mega-menu-icons-datagrid.svg); + --psp-plugin-selector--summary--content: url(../svg/mega-menu-icons-summary.svg); /* Datagrid */ /* `regular-table` icons */ diff --git a/rust/perspective-viewer/src/themes/intl.css b/rust/perspective-viewer/src/themes/intl.css index 121a1b0ce2..1a05713701 100644 --- a/rust/perspective-viewer/src/themes/intl.css +++ b/rust/perspective-viewer/src/themes/intl.css @@ -23,6 +23,7 @@ perspective-viewer { /* Plugin names */ --psp-plugin-name--datagrid--content: "Datagrid"; + --psp-plugin-name--summary--content: "Summary"; --psp-plugin-name--treemap--content: "Treemap"; --psp-plugin-name--sunburst--content: "Sunburst"; --psp-plugin-name--heatmap--content: "Heatmap"; @@ -59,7 +60,6 @@ perspective-viewer { --psp-label--copy-button--content: "Copy"; --psp-label--export-button--content: "Export"; --psp-label--reset-button--content: "Reset"; - --psp-label--new-panel-button--content: "New"; --psp-label--new-from-table--content: "New from Table"; --psp-label--new-from-panel--content: "New from Panel"; --psp-label--apply-button--content: "Apply"; @@ -155,6 +155,7 @@ perspective-viewer { --psp-label--role--facets--content: "Facets"; --psp-label--role--row-groups--content: "Row Groups"; --psp-label--role--column-groups--content: "Column Groups"; + --psp-label--role--breakdown--content: "Breakdown"; /* Window editor */ --psp-label--window-source--content: "Column"; @@ -184,6 +185,9 @@ perspective-viewer { --psp-label--row-height--content: "Row height"; --psp-label--zebra-rows--content: "Zebra rows"; --psp-label--zebra-color--content: "Zebra color"; + --psp-label--label-position--content: "Label position"; + --psp-label--value-fit--content: "Value size"; + --psp-label--breakdown--content: "Breakdown"; --psp-label--chart-type--content: "Glyph type"; /* Plugin settings — viewer-charts */ diff --git a/rust/perspective-viewer/src/themes/intl/ar.css b/rust/perspective-viewer/src/themes/intl/ar.css index dc45d10b4c..060f8c4f77 100644 --- a/rust/perspective-viewer/src/themes/intl/ar.css +++ b/rust/perspective-viewer/src/themes/intl/ar.css @@ -21,6 +21,7 @@ perspective-viewer { --psp-label--untitled--content: "بدون عنوان"; --psp-plugin-name--datagrid--content: "شبكة البيانات"; + --psp-plugin-name--summary--content: "ملخص"; --psp-plugin-name--treemap--content: "خريطة شجرية"; --psp-plugin-name--sunburst--content: "مخطط شمسي"; --psp-plugin-name--heatmap--content: "خريطة حرارية"; @@ -55,7 +56,6 @@ perspective-viewer { --psp-label--copy-button--content: "نسخ"; --psp-label--export-button--content: "تصدير"; --psp-label--reset-button--content: "إعادة تعيين"; - --psp-label--new-panel-button--content: "جديد"; --psp-label--new-from-table--content: "جديد من جدول"; --psp-label--new-from-panel--content: "جديد من لوحة"; --psp-label--apply-button--content: "تطبيق"; @@ -147,6 +147,7 @@ perspective-viewer { --psp-label--role--facets--content: "الأوجه"; --psp-label--role--row-groups--content: "مجموعات الصفوف"; --psp-label--role--column-groups--content: "مجموعات الأعمدة"; + --psp-label--role--breakdown--content: "تفصيل"; --psp-label--window-source--content: "العمود"; --psp-label--window-order-by--content: "ترتيب حسب"; @@ -174,6 +175,9 @@ perspective-viewer { --psp-label--row-height--content: "ارتفاع الصف"; --psp-label--zebra-rows--content: "صفوف متناوبة"; --psp-label--zebra-color--content: "لون التناوب"; + --psp-label--label-position--content: "موضع التسمية"; + --psp-label--value-fit--content: "حجم القيمة"; + --psp-label--breakdown--content: "تفصيل"; --psp-label--chart-type--content: "نوع الشكل"; --psp-label--auto-alt-y-axis--content: "محور Y تلقائي"; diff --git a/rust/perspective-viewer/src/themes/intl/de.css b/rust/perspective-viewer/src/themes/intl/de.css index 65a4028ef6..cd78b73f47 100644 --- a/rust/perspective-viewer/src/themes/intl/de.css +++ b/rust/perspective-viewer/src/themes/intl/de.css @@ -23,6 +23,7 @@ perspective-viewer { /* Plugin names */ --psp-plugin-name--datagrid--content: "Datengitter"; + --psp-plugin-name--summary--content: "Zusammenfassung"; --psp-plugin-name--treemap--content: "Treemap"; --psp-plugin-name--sunburst--content: "Sunburst"; --psp-plugin-name--heatmap--content: "Heatmap"; @@ -59,7 +60,6 @@ perspective-viewer { --psp-label--copy-button--content: "Kopieren"; --psp-label--export-button--content: "Exportieren"; --psp-label--reset-button--content: "Zurücksetzen"; - --psp-label--new-panel-button--content: "Neu"; --psp-label--new-from-table--content: "Neu aus Tabelle"; --psp-label--new-from-panel--content: "Neu aus Panel"; --psp-label--apply-button--content: "Anwenden"; @@ -150,6 +150,7 @@ perspective-viewer { --psp-label--role--facets--content: "Facetten"; --psp-label--role--row-groups--content: "Zeilengruppen"; --psp-label--role--column-groups--content: "Spaltengruppen"; + --psp-label--role--breakdown--content: "Aufschlüsselung"; /* Plugin settings */ --psp-label--edit-mode--content: "Bearbeitungsmodus"; @@ -171,6 +172,9 @@ perspective-viewer { --psp-label--row-height--content: "Zeilenhöhe"; --psp-label--zebra-rows--content: "Zebra-Zeilen"; --psp-label--zebra-color--content: "Zebra-Farbe"; + --psp-label--label-position--content: "Beschriftungsposition"; + --psp-label--value-fit--content: "Wertgröße"; + --psp-label--breakdown--content: "Aufschlüsselung"; --psp-label--chart-type--content: "Glyphentyp"; /* Plugin settings — viewer-charts */ diff --git a/rust/perspective-viewer/src/themes/intl/es.css b/rust/perspective-viewer/src/themes/intl/es.css index cf02e2db9c..a1d778baae 100644 --- a/rust/perspective-viewer/src/themes/intl/es.css +++ b/rust/perspective-viewer/src/themes/intl/es.css @@ -23,6 +23,7 @@ perspective-viewer { /* Plugin names */ --psp-plugin-name--datagrid--content: "Cuadrícula de datos"; + --psp-plugin-name--summary--content: "Resumen"; --psp-plugin-name--treemap--content: "Mapa de árbol"; --psp-plugin-name--sunburst--content: "Sunburst"; --psp-plugin-name--heatmap--content: "Mapa de calor"; @@ -59,7 +60,6 @@ perspective-viewer { --psp-label--copy-button--content: "Copiar"; --psp-label--export-button--content: "Exportar"; --psp-label--reset-button--content: "Restablecer"; - --psp-label--new-panel-button--content: "Nuevo"; --psp-label--new-from-table--content: "Nuevo desde tabla"; --psp-label--new-from-panel--content: "Nuevo desde panel"; --psp-label--apply-button--content: "Aplicar"; @@ -150,6 +150,7 @@ perspective-viewer { --psp-label--role--facets--content: "Facetas"; --psp-label--role--row-groups--content: "Grupos de filas"; --psp-label--role--column-groups--content: "Grupos de columnas"; + --psp-label--role--breakdown--content: "Desglose"; /* Plugin settings */ --psp-label--edit-mode--content: "Modo de edición"; @@ -171,6 +172,9 @@ perspective-viewer { --psp-label--row-height--content: "Altura de fila"; --psp-label--zebra-rows--content: "Filas cebra"; --psp-label--zebra-color--content: "Color cebra"; + --psp-label--label-position--content: "Posición de etiqueta"; + --psp-label--value-fit--content: "Tamaño del valor"; + --psp-label--breakdown--content: "Desglose"; --psp-label--chart-type--content: "Tipo de glifo"; /* Plugin settings — viewer-charts */ diff --git a/rust/perspective-viewer/src/themes/intl/fr.css b/rust/perspective-viewer/src/themes/intl/fr.css index 62b1c6a20a..5341b3c4b0 100644 --- a/rust/perspective-viewer/src/themes/intl/fr.css +++ b/rust/perspective-viewer/src/themes/intl/fr.css @@ -23,6 +23,7 @@ perspective-viewer { /* Plugin names */ --psp-plugin-name--datagrid--content: "Grille de données"; + --psp-plugin-name--summary--content: "Résumé"; --psp-plugin-name--treemap--content: "Treemap"; --psp-plugin-name--sunburst--content: "Sunburst"; --psp-plugin-name--heatmap--content: "Carte de chaleur"; @@ -59,7 +60,6 @@ perspective-viewer { --psp-label--copy-button--content: "Copier"; --psp-label--export-button--content: "Exporter"; --psp-label--reset-button--content: "Réinitialiser"; - --psp-label--new-panel-button--content: "Nouveau"; --psp-label--new-from-table--content: "Nouveau depuis une table"; --psp-label--new-from-panel--content: "Nouveau depuis un panneau"; --psp-label--apply-button--content: "Appliquer"; @@ -150,6 +150,7 @@ perspective-viewer { --psp-label--role--facets--content: "Facettes"; --psp-label--role--row-groups--content: "Groupes de lignes"; --psp-label--role--column-groups--content: "Groupes de colonnes"; + --psp-label--role--breakdown--content: "Répartition"; /* Plugin settings */ --psp-label--edit-mode--content: "Mode édition"; @@ -171,6 +172,9 @@ perspective-viewer { --psp-label--row-height--content: "Hauteur de ligne"; --psp-label--zebra-rows--content: "Lignes zébrées"; --psp-label--zebra-color--content: "Couleur zébrée"; + --psp-label--label-position--content: "Position du libellé"; + --psp-label--value-fit--content: "Taille de la valeur"; + --psp-label--breakdown--content: "Répartition"; --psp-label--chart-type--content: "Type de glyphe"; /* Plugin settings — viewer-charts */ diff --git a/rust/perspective-viewer/src/themes/intl/ja.css b/rust/perspective-viewer/src/themes/intl/ja.css index 72d9667d6f..1785dea567 100644 --- a/rust/perspective-viewer/src/themes/intl/ja.css +++ b/rust/perspective-viewer/src/themes/intl/ja.css @@ -23,6 +23,7 @@ perspective-viewer { /* Plugin names */ --psp-plugin-name--datagrid--content: "データグリッド"; + --psp-plugin-name--summary--content: "サマリー"; --psp-plugin-name--treemap--content: "ツリーマップ"; --psp-plugin-name--sunburst--content: "サンバースト"; --psp-plugin-name--heatmap--content: "ヒートマップ"; @@ -60,7 +61,6 @@ perspective-viewer { --psp-label--copy-button--content: "コピー"; --psp-label--export-button--content: "エクスポート"; --psp-label--reset-button--content: "リセット"; - --psp-label--new-panel-button--content: "新規"; --psp-label--new-from-table--content: "テーブルから新規"; --psp-label--new-from-panel--content: "パネルから新規"; --psp-label--apply-button--content: "適用"; @@ -150,6 +150,7 @@ perspective-viewer { --psp-label--role--facets--content: "ファセット"; --psp-label--role--row-groups--content: "行グループ"; --psp-label--role--column-groups--content: "列グループ"; + --psp-label--role--breakdown--content: "内訳"; /* Plugin settings */ --psp-label--edit-mode--content: "編集モード"; @@ -171,6 +172,9 @@ perspective-viewer { --psp-label--row-height--content: "行の高さ"; --psp-label--zebra-rows--content: "縞模様の行数"; --psp-label--zebra-color--content: "縞模様の色"; + --psp-label--label-position--content: "ラベル位置"; + --psp-label--value-fit--content: "値のサイズ"; + --psp-label--breakdown--content: "内訳"; --psp-label--chart-type--content: "グリフの種類"; /* Plugin settings — viewer-charts */ diff --git a/rust/perspective-viewer/src/themes/intl/pt.css b/rust/perspective-viewer/src/themes/intl/pt.css index 4936f6b187..9881f4a398 100644 --- a/rust/perspective-viewer/src/themes/intl/pt.css +++ b/rust/perspective-viewer/src/themes/intl/pt.css @@ -23,6 +23,7 @@ perspective-viewer { /* Plugin names */ --psp-plugin-name--datagrid--content: "Grade de dados"; + --psp-plugin-name--summary--content: "Resumo"; --psp-plugin-name--treemap--content: "Mapa de árvore"; --psp-plugin-name--sunburst--content: "Sunburst"; --psp-plugin-name--heatmap--content: "Mapa de calor"; @@ -59,7 +60,6 @@ perspective-viewer { --psp-label--copy-button--content: "Copiar"; --psp-label--export-button--content: "Exportar"; --psp-label--reset-button--content: "Redefinir"; - --psp-label--new-panel-button--content: "Novo"; --psp-label--new-from-table--content: "Novo a partir de tabela"; --psp-label--new-from-panel--content: "Novo a partir de painel"; --psp-label--apply-button--content: "Aplicar"; @@ -150,6 +150,7 @@ perspective-viewer { --psp-label--role--facets--content: "Facetas"; --psp-label--role--row-groups--content: "Grupos de linhas"; --psp-label--role--column-groups--content: "Grupos de colunas"; + --psp-label--role--breakdown--content: "Detalhamento"; /* Plugin settings */ --psp-label--edit-mode--content: "Modo de edição"; @@ -171,6 +172,9 @@ perspective-viewer { --psp-label--row-height--content: "Altura da linha"; --psp-label--zebra-rows--content: "Linhas zebradas"; --psp-label--zebra-color--content: "Cor zebrada"; + --psp-label--label-position--content: "Posição do rótulo"; + --psp-label--value-fit--content: "Tamanho do valor"; + --psp-label--breakdown--content: "Detalhamento"; --psp-label--chart-type--content: "Tipo de glifo"; /* Plugin settings — viewer-charts */ diff --git a/rust/perspective-viewer/src/themes/intl/zh.css b/rust/perspective-viewer/src/themes/intl/zh.css index 811dc93ba1..cef450b531 100644 --- a/rust/perspective-viewer/src/themes/intl/zh.css +++ b/rust/perspective-viewer/src/themes/intl/zh.css @@ -23,6 +23,7 @@ perspective-viewer { /* Plugin names */ --psp-plugin-name--datagrid--content: "数据网格"; + --psp-plugin-name--summary--content: "摘要"; --psp-plugin-name--treemap--content: "树形图"; --psp-plugin-name--sunburst--content: "旭日图"; --psp-plugin-name--heatmap--content: "热力图"; @@ -59,7 +60,6 @@ perspective-viewer { --psp-label--copy-button--content: "复制"; --psp-label--export-button--content: "导出"; --psp-label--reset-button--content: "重置"; - --psp-label--new-panel-button--content: "新建"; --psp-label--new-from-table--content: "从表新建"; --psp-label--new-from-panel--content: "从面板新建"; --psp-label--apply-button--content: "应用"; @@ -150,6 +150,7 @@ perspective-viewer { --psp-label--role--facets--content: "分面"; --psp-label--role--row-groups--content: "行分组"; --psp-label--role--column-groups--content: "列分组"; + --psp-label--role--breakdown--content: "细分"; /* Plugin settings */ --psp-label--edit-mode--content: "编辑模式"; @@ -171,6 +172,9 @@ perspective-viewer { --psp-label--row-height--content: "行高"; --psp-label--zebra-rows--content: "斑马行"; --psp-label--zebra-color--content: "斑马色"; + --psp-label--label-position--content: "标签位置"; + --psp-label--value-fit--content: "数值大小"; + --psp-label--breakdown--content: "细分"; --psp-label--chart-type--content: "图元类型"; /* Plugin settings — viewer-charts */ diff --git a/rust/perspective-viewer/src/ts/bootstrap.ts b/rust/perspective-viewer/src/ts/bootstrap.ts index 747988b00f..abbd973031 100644 --- a/rust/perspective-viewer/src/ts/bootstrap.ts +++ b/rust/perspective-viewer/src/ts/bootstrap.ts @@ -27,6 +27,7 @@ import type { // @ts-ignore import * as worker_url from "./perspective-viewer.worker.ts"; +import { create_plugin_utils } from "./plugin_utils/index.ts"; export type { InitOptions, @@ -79,7 +80,7 @@ provide_viewer_runtime(async (wasm) => { ]); await glue.default({ module_or_path: module }); - await glue.init(module, url); + await glue.init(module, url, create_plugin_utils(glue)); return { glue: glue as ClientRuntime["glue"], module }; }); diff --git a/rust/perspective-viewer/src/ts/column-format.ts b/rust/perspective-viewer/src/ts/column-format.ts deleted file mode 100644 index 448ce6178e..0000000000 --- a/rust/perspective-viewer/src/ts/column-format.ts +++ /dev/null @@ -1,252 +0,0 @@ -// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ -// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ -// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ -// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ -// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ -// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ -// ┃ Copyright (c) 2017, the Perspective Authors. ┃ -// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ -// ┃ This file is part of the Perspective library, distributed under the terms ┃ -// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ -// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ - -/** - * Cross-package helpers for per-column value formatting. Used by both - * `viewer-datagrid` (cell formatting) and `viewer-charts` (axis ticks, - * tooltips, legends) so a column's `number_format` / `date_format` - * configuration produces identical output across plugins. - * - * The format configs mirror the `Intl.NumberFormatOptions` / - * `Intl.DateTimeFormatOptions` shapes one-for-one — they're written - * straight into the respective constructors. - */ - -import type { CustomNumberFormatConfig } from "../../dist/ts-rs/CustomNumberFormatConfig.d.ts"; -import type { NumberFormatStyle } from "../../dist/ts-rs/NumberFormatStyle.d.ts"; -import type { Notation } from "../../dist/ts-rs/Notation.d.ts"; -import type { DatetimeFormat } from "../../dist/ts-rs/DatetimeFormat.d.ts"; - -/** - * A numeric column's `number_format` (`columns_config` value), exactly as - * the Style tab's editor WRITES it — the ts-rs projection of the Rust - * `CustomNumberFormatConfig`, re-composed with its serde-flattened - * `style` and `notation` families (ts-rs cannot flatten `Option`, - * so the Rust type `#[ts(skip)]`s them and they export separately). - */ -export type NumberFormatConfig = CustomNumberFormatConfig & - Partial & - Partial; - -/** - * A datetime column's `date_format` (`columns_config` value), a subset of - * `Intl.DateTimeFormatOptions`. - */ -export type DateFormatConfig = DatetimeFormat; - -/** The `date_format` keys that apply as one group. */ -export const DATE_FORMAT_SHAPE_KEYS = [ - "dateStyle", - "timeStyle", - "weekday", - "year", - "month", - "day", - "hour", - "minute", - "second", - "fractionalSecondDigits", -] as const satisfies readonly (keyof DateFormatConfig)[]; - -/** The `date_format` keys that apply individually. */ -export const DATE_FORMAT_MODIFIER_KEYS = [ - "timeZone", - "hour12", -] as const satisfies readonly (keyof DateFormatConfig)[]; - -/** Whether `cfg` sets any of the `date_format` keys that apply as one group. */ -export function hasDateFormatShape( - cfg: DateFormatConfig | undefined, -): cfg is DateFormatConfig { - return DATE_FORMAT_SHAPE_KEYS.some((key) => cfg?.[key] !== undefined); -} - -/** The `date_format` options that apply individually. */ -export type DateFormatModifiers = Pick< - Intl.DateTimeFormatOptions, - "timeZone" | "hour12" ->; - -/** The `date_format` keys of `cfg` that apply individually, if it sets any. */ -export function dateFormatModifiers( - cfg: DateFormatConfig | undefined, -): DateFormatModifiers | undefined { - const out: DateFormatModifiers = {}; - if (cfg?.timeZone !== undefined) { - out.timeZone = cfg.timeZone; - } - - if (cfg?.hour12 !== undefined) { - out.hour12 = cfg.hour12; - } - - return Object.keys(out).length > 0 ? out : undefined; -} - -/** - * Default `Intl.NumberFormatOptions` applied when a numeric column has no - * `number_format` configured. Float columns get two fractional digits to - * match the legacy datagrid behavior; integer columns get an empty - * options bag (locale-default integer rendering). - */ -const NUMERIC_LEGACY_DEFAULTS: Record = { - float: { - style: "decimal", - minimumFractionDigits: 2, - maximumFractionDigits: 2, - }, -}; - -/** - * The viewer's own `date_format` for a datetime column, below every plugin - * and override layer. - */ -const DATETIME_BASE: DateFormatConfig = { - dateStyle: "short", - timeStyle: "medium", -}; - -const DATE_BASE: DateFormatConfig & { dateStyle: "short" } = { - dateStyle: "short", -}; - -const NUMBER_FORMAT_GROUPS: readonly (readonly string[])[] = [ - [ - "style", - "currency", - "currencyDisplay", - "currencySign", - "unit", - "unitDisplay", - ], - ["notation", "compactDisplay"], - ["minimumFractionDigits", "maximumFractionDigits"], - ["minimumSignificantDigits", "maximumSignificantDigits"], -]; - -function mergeNumberOptions( - base: Intl.NumberFormatOptions, - cfg?: NumberFormatConfig, -): Intl.NumberFormatOptions { - const explicit: Record = {}; - for (const [k, v] of Object.entries(cfg ?? {})) { - if (v !== undefined && v !== null) { - explicit[k] = v; - } - } - - const merged: Record = { ...base }; - for (const group of NUMBER_FORMAT_GROUPS) { - if (group.some((key) => key in explicit)) { - for (const key of group) { - delete merged[key]; - } - } - } - - return Object.assign(merged, explicit) as Intl.NumberFormatOptions; -} - -/** - * `defaults` is the calling plugin's declared default format, filling in - * the fields `cfg` leaves unset. - */ -export function createNumberFormatter( - type: string, - cfg?: NumberFormatConfig, - defaults?: NumberFormatConfig, -): Intl.NumberFormat { - // ts-rs renders serde-absent keys as `T | null`; the wire never - // carries an explicit `null` (`skip_serializing_if`), and - // `Intl.NumberFormat` treats both absent and `undefined` the same, so - // the cast is presentation-only. - const base = ((defaults as Intl.NumberFormatOptions | undefined) ?? - NUMERIC_LEGACY_DEFAULTS[type] ?? - {}) as Intl.NumberFormatOptions; - - const opts = cfg ? mergeNumberOptions(base, cfg) : base; - return new Intl.NumberFormat(navigator.languages as string[], opts); -} - -/** - * `cfg` layered over `defaults`, then over `base`, by the `date_format` - * group rule, as `Intl.DateTimeFormat` options. - */ -export function resolveDateFormat( - cfg: DateFormatConfig | undefined, - defaults: DateFormatConfig | undefined, - base: DateFormatConfig, -): Intl.DateTimeFormatOptions { - const layers = [cfg, defaults, base]; - const shape: DateFormatConfig = layers.find(hasDateFormatShape) ?? {}; - const opts: DateFormatConfig = {}; - const copy = ( - key: K, - from: DateFormatConfig | undefined, - ) => { - if (from !== undefined && from[key] !== undefined) { - opts[key] = from[key]; - } - }; - - for (const key of DATE_FORMAT_SHAPE_KEYS) { - copy(key, shape); - } - - for (const key of DATE_FORMAT_MODIFIER_KEYS) { - copy( - key, - layers.find((layer) => layer?.[key] !== undefined), - ); - } - - return opts; -} - -/** - * `defaults` is the calling plugin's declared default `date_format`, which - * `cfg` overrides by the `date_format` group rule. - */ -export function createDatetimeFormatter( - cfg?: DateFormatConfig, - defaults?: DateFormatConfig, -): Intl.DateTimeFormat { - return new Intl.DateTimeFormat( - navigator.languages as string[], - resolveDateFormat(cfg, defaults, DATETIME_BASE), - ); -} - -/** - * `defaults` follows the same contract as [`createDatetimeFormatter`]; - * only `dateStyle` applies, in UTC. - */ -export function createDateFormatter( - cfg?: DateFormatConfig, - defaults?: DateFormatConfig, -): Intl.DateTimeFormat { - const { dateStyle } = resolveDateFormat(cfg, defaults, DATE_BASE); - return new Intl.DateTimeFormat(navigator.languages as string[], { - timeZone: "utc", - dateStyle: dateStyle ?? DATE_BASE.dateStyle, - }); -} - -/** - * Recover the source column name from a synthetic split-by path. Split - * pivoting produces paths of the form `|...|`; - * per-column config (formatters, aggregate styling, …) is always keyed - * on the trailing source column. - */ -export function sourceColumn(path: string): string { - return path.split("|").at(-1) ?? path; -} diff --git a/rust/perspective-viewer/src/ts/extensions.ts b/rust/perspective-viewer/src/ts/extensions.ts index 25de357ea8..49fd00e19a 100644 --- a/rust/perspective-viewer/src/ts/extensions.ts +++ b/rust/perspective-viewer/src/ts/extensions.ts @@ -21,6 +21,7 @@ import type { ColumnType, ViewWindow, Filter } from "@perspective-dev/client"; import type { ConfigDefaultsOptions } from "../../dist/ts-rs/ConfigDefaultsOptions.d.ts"; import type { ColumnConfigDefaultsOptions } from "../../dist/ts-rs/ColumnConfigDefaultsOptions.d.ts"; import type { PerspectiveSelectDetail } from "./select-detail.ts"; +import type { PluginUtils } from "./plugin_utils/index.ts"; export { PerspectiveSelectDetail } from "./select-detail.ts"; export type { @@ -255,6 +256,21 @@ export interface PerspectiveViewerElementExt { defaults: Record; }>; + /** + * The code `` shares with its plugins: value + * formatting, color parsing, theme reading, cell styling and settings + * schema helpers. + * + * @category Plugin + * @example + * ```javascript + * const { plugin_utils } = customElements.get("perspective-viewer"); + * const formatter = plugin_utils.formatter("float", { style: "percent" }); + * console.log(formatter.format(0.25)); + * ``` + */ + readonly plugin_utils: PluginUtils; + get_wasm_module(): WebAssembly.Module; get_worker_url(): URL; diff --git a/rust/perspective-viewer/src/ts/perspective-viewer.ts b/rust/perspective-viewer/src/ts/perspective-viewer.ts index 02b12b8039..eca21235c7 100644 --- a/rust/perspective-viewer/src/ts/perspective-viewer.ts +++ b/rust/perspective-viewer/src/ts/perspective-viewer.ts @@ -40,13 +40,7 @@ export { HTMLPerspectiveViewerPluginElement } from "./plugin.ts"; export { providers } from "./providers.ts"; export type { AgentProviderPreset } from "./providers.ts"; -export { - createNumberFormatter, - createDatetimeFormatter, - createDateFormatter, - sourceColumn, -} from "./column-format.ts"; -export type { NumberFormatConfig, DateFormatConfig } from "./column-format.ts"; +export type * from "./plugin_utils/index.ts"; export type * from "./extensions.ts"; export { PerspectiveSelectDetail } from "./select-detail.ts"; diff --git a/rust/perspective-viewer/src/ts/plugin_utils/cell_style.ts b/rust/perspective-viewer/src/ts/plugin_utils/cell_style.ts new file mode 100644 index 0000000000..bc477fd22d --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style.ts @@ -0,0 +1,27 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import pulse from "./cell_style/pulse.css"; + +export { cell_style_boolean } from "./cell_style/boolean.ts"; +export { cell_style_datetime } from "./cell_style/datetime.ts"; +export { cell_style_numeric } from "./cell_style/numeric.ts"; +export { cell_style_string } from "./cell_style/string.ts"; +export { style_cell_flash } from "./cell_style/cell_flash.ts"; +export type { + CellFlashMeta, + CellStyleMeta, + CellStyleModel, +} from "./cell_style/types.ts"; + +/** The `@keyframes` the `"pulse"` background mode animates with, as CSS text. */ +export const css: string = pulse; diff --git a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/boolean.ts b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/boolean.ts similarity index 91% rename from packages/viewer-datagrid/src/ts/style_handlers/table_cell/boolean.ts rename to rust/perspective-viewer/src/ts/plugin_utils/cell_style/boolean.ts index 3cf336469f..3980fb5e0e 100644 --- a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/boolean.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/boolean.ts @@ -10,18 +10,15 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import { CellMetadata } from "regular-table/dist/esm/types.js"; -import type { - DatagridModel, - ResolvedColumnStyle, - ColorRecord, -} from "../../types.ts"; +import type { ColorRecord } from "../color.ts"; +import type { ResolvedColumnStyle } from "../column_style.ts"; +import type { CellStyleMeta, CellStyleModel } from "./types.ts"; export function cell_style_boolean( - model: DatagridModel, + model: CellStyleModel, _plugin: ResolvedColumnStyle | undefined, td: HTMLElement, - metadata: CellMetadata, + metadata: CellStyleMeta, ): void { // @ts-ignore if (metadata._is_hidden_by_aggregate_depth) { diff --git a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/cell_flash.ts b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/cell_flash.ts similarity index 95% rename from packages/viewer-datagrid/src/ts/style_handlers/table_cell/cell_flash.ts rename to rust/perspective-viewer/src/ts/plugin_utils/cell_style/cell_flash.ts index ae4d5b05ea..492325b7d2 100644 --- a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/cell_flash.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/cell_flash.ts @@ -10,12 +10,12 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import { CellMetadataBody } from "regular-table/dist/esm/types.js"; -import type { DatagridModel, ColorRecord } from "../../types.ts"; +import type { ColorRecord } from "../color.ts"; +import type { CellFlashMeta, CellStyleModel } from "./types.ts"; export function style_cell_flash( - model: DatagridModel, - metadata: CellMetadataBody, + model: CellStyleModel, + metadata: CellFlashMeta, td: HTMLElement, [, , , , , pos_s, pos_e]: ColorRecord, [, , , , , neg_s, neg_e]: ColorRecord, diff --git a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/datetime.ts b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/datetime.ts similarity index 94% rename from packages/viewer-datagrid/src/ts/style_handlers/table_cell/datetime.ts rename to rust/perspective-viewer/src/ts/plugin_utils/cell_style/datetime.ts index 616019039f..6be4053499 100644 --- a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/datetime.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/datetime.ts @@ -9,25 +9,24 @@ // ┃ This file is part of the Perspective library, distributed under the terms ┃ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import { CellMetadata } from "regular-table/dist/esm/types.js"; import { rgbaToRgb, infer_foreground_from_background, type RGB, -} from "../../color_utils.ts"; +} from "../color.ts"; import { parse_bg_mode, parse_fg_mode, - type DatagridModel, type ResolvedColumnStyle, -} from "../../types.ts"; +} from "../column_style.ts"; +import type { CellStyleMeta, CellStyleModel } from "./types.ts"; /** Apply a datetime column's foreground and background modes independently. */ export function cell_style_datetime( - model: DatagridModel, + model: CellStyleModel, plugin: ResolvedColumnStyle | undefined, td: HTMLElement, - metadata: CellMetadata, + metadata: CellStyleMeta, ): void { const fg_mode = parse_fg_mode("datetime", plugin?.fg_mode) ?? "disabled"; const bg_mode = parse_bg_mode("datetime", plugin?.bg_mode) ?? "disabled"; diff --git a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/numeric.ts b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/numeric.ts similarity index 96% rename from packages/viewer-datagrid/src/ts/style_handlers/table_cell/numeric.ts rename to rust/perspective-viewer/src/ts/plugin_utils/cell_style/numeric.ts index c301a9042e..bd05ffba59 100644 --- a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/numeric.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/numeric.ts @@ -10,20 +10,20 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import { style_cell_flash } from "./cell_flash.ts"; -import { format_raw } from "../../data_listener/format_cell.ts"; +import { format_raw } from "../format.ts"; import { infer_foreground_from_background, rgbaToRgb, rgbToHex, sampleGradientRgb, -} from "../../color_utils.ts"; +} from "../color.ts"; +import type { ColorRecord } from "../color.ts"; import { parse_bg_mode, parse_fg_mode, - type ColorRecord, - type DatagridModel, type ResolvedColumnStyle, -} from "../../types.ts"; +} from "../column_style.ts"; +import type { CellStyleModel } from "./types.ts"; import type { ColumnType } from "@perspective-dev/client"; const MAX_BAR_WIDTH_PCT = 1; @@ -82,7 +82,7 @@ function style_cell_bar( } } -function neutral_record(model: DatagridModel): ColorRecord { +function neutral_record(model: CellStyleModel): ColorRecord { return [ "", model._plugin_background[0], @@ -95,7 +95,7 @@ function neutral_record(model: DatagridModel): ColorRecord { } export function cell_style_numeric( - model: DatagridModel, + model: CellStyleModel, plugin: ResolvedColumnStyle | undefined, type: ColumnType | undefined, td: HTMLElement, diff --git a/rust/perspective-viewer/src/ts/plugin_utils/cell_style/pulse.css b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/pulse.css new file mode 100644 index 0000000000..7116e6bba2 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/pulse.css @@ -0,0 +1,76 @@ +/* ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ + * ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ + * ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ + * ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ + * ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ + * ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ + * ┃ Copyright (c) 2017, the Perspective Authors. ┃ + * ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ + * ┃ This file is part of the Perspective library, distributed under the terms ┃ + * ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ + * ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + */ + +@keyframes pulse_pos { + 0% { + background-color: var( + --pulse--background-color-start, + rgba(0, 128, 255, 0.5) + ); + } + + 100% { + background-color: var( + --pulse--background-color-end, + rgba(0, 128, 255, 0) + ); + } +} + +@keyframes pulse_pos2 { + 0% { + background-color: var( + --pulse--background-color-start, + rgba(0, 128, 255, 0.5) + ); + } + + 100% { + background-color: var( + --pulse--background-color-end, + rgba(0, 128, 255, 0) + ); + } +} + +@keyframes pulse_neg { + 0% { + background-color: var( + --pulse--background-color-start, + rgba(255, 25, 0, 0.5) + ); + } + + 100% { + background-color: var( + --pulse--background-color-end, + rgba(255, 25, 0, 0) + ); + } +} + +@keyframes pulse_neg2 { + 0% { + background-color: var( + --pulse--background-color-start, + rgba(255, 25, 0, 0.5) + ); + } + + 100% { + background-color: var( + --pulse--background-color-end, + rgba(255, 25, 0, 0) + ); + } +} diff --git a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/string.ts b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/string.ts similarity index 96% rename from packages/viewer-datagrid/src/ts/style_handlers/table_cell/string.ts rename to rust/perspective-viewer/src/ts/plugin_utils/cell_style/string.ts index c0b4913dab..66365fa37e 100644 --- a/packages/viewer-datagrid/src/ts/style_handlers/table_cell/string.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/string.ts @@ -14,13 +14,13 @@ import { parseColor, rgbaToRgb, type RGB, -} from "../../color_utils.ts"; +} from "../color.ts"; import { parse_bg_mode, parse_fg_mode, - type DatagridModel, type ResolvedColumnStyle, -} from "../../types.ts"; +} from "../column_style.ts"; +import type { CellStyleModel } from "./types.ts"; interface CellMetaWithExtras { _is_hidden_by_aggregate_depth?: boolean; @@ -33,7 +33,7 @@ interface CellMetaWithExtras { * distinct values in encounter order. */ function series_seed( - model: DatagridModel, + model: CellStyleModel, column_name: string, value: string, ): number { @@ -53,7 +53,7 @@ function series_seed( } function series_color( - model: DatagridModel, + model: CellStyleModel, palette_colors: string[] | undefined, seed: number, ): string { @@ -67,7 +67,7 @@ function series_color( /** Apply a string column's foreground and background modes independently. */ export function cell_style_string( - model: DatagridModel, + model: CellStyleModel, plugin: ResolvedColumnStyle | undefined, td: HTMLElement, metadata: CellMetaWithExtras, diff --git a/rust/perspective-viewer/src/ts/plugin_utils/cell_style/types.ts b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/types.ts new file mode 100644 index 0000000000..e73b8c68e5 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/cell_style/types.ts @@ -0,0 +1,47 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { ColorRecord, GradientStopRgb } from "../color.ts"; + +/** The model fields the body cell style handlers read. */ +export interface CellStyleModel { + _plugin_background: number[]; + _color: ColorRecord; + _pos_fg_color: ColorRecord; + _neg_fg_color: ColorRecord; + _pos_bg_color: ColorRecord; + _neg_bg_color: ColorRecord; + _default_bg_color_stops: GradientStopRgb[]; + _series_palette: string[]; + _series_color_map: Map>; + _series_color_seed: Map; + _ids: unknown[][]; + _column_paths: string[]; + _is_old_viewport?: boolean; + last_meta?: unknown[][]; + last_reverse_ids?: Map; + last_reverse_columns?: Map; + _config: { split_by: string[] }; +} + +/** The cell metadata fields the date, datetime and boolean handlers read. */ +export interface CellStyleMeta { + _is_hidden_by_aggregate_depth?: boolean; + user?: unknown; +} + +/** The cell metadata fields the pulse handler reads. */ +export interface CellFlashMeta { + x: number; + dy?: number; + user?: unknown; +} diff --git a/packages/viewer-datagrid/src/ts/color_utils.ts b/rust/perspective-viewer/src/ts/plugin_utils/color.ts similarity index 63% rename from packages/viewer-datagrid/src/ts/color_utils.ts rename to rust/perspective-viewer/src/ts/plugin_utils/color.ts index 46ce5bc11b..4b3e3a8611 100644 --- a/packages/viewer-datagrid/src/ts/color_utils.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/color.ts @@ -10,10 +10,23 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -import type { ColorRecord } from "./types.ts"; - -/** 8-bit sRGB color as `[r, g, b]` with each channel in `[0, 255]`. */ -export type RGB = [number, number, number]; +import type { + GradientStopRgb, + RGB, +} from "../../../dist/wasm/perspective-viewer.js"; + +export type { GradientStopRgb, RGB }; + +/** A color and the strings derived from it, as `make_color_record` builds them. */ +export type ColorRecord = [ + string, // hex color + number, // red + number, // green + number, // blue + string, // gradient + string, // rgba solid + string, // rgba transparent +]; /** HSL color as `[h, s, l]` with `h` in degrees `[0, 360)` and `s`, `l` in `[0, 1]`. */ export type HSL = [number, number, number]; @@ -101,15 +114,6 @@ export function rgbToHex([r, g, b]: RGB): string { return `#${toHex(r)}${toHex(g)}${toHex(b)}`; } -/** - * One stop of a resolved color scale: an `RGB` triple at - * `offset` ∈ [0, 1]. - */ -export interface GradientStopRgb { - rgb: RGB; - offset: number; -} - /** * Piecewise-linear color sample over `stops` (sorted by offset) at * `t` ∈ [0, 1], clamped to the first/last stop outside their offsets. @@ -255,216 +259,6 @@ export function infer_foreground_from_background([r, g, b]: [ : "#ffffff"; } -/** - * A color literal — `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` or - * `rgba()` — or `null` for anything else. - */ -export function parseColorStrict(input: string): RGB | null { - const s = input.trim(); - if (s.startsWith("#")) { - return /^#[0-9a-f]+$/i.test(s) ? parse_hex(s) : null; - } - - const m = s.match(/^rgba?\(([^)]*)\)$/i); - if (!m) { - return null; - } - - const tokens = m[1] - .split("/")[0] - .split(/[\s,]+/) - .filter((x) => x.length > 0); - if (tokens.length < 3 || tokens.length > 4) { - return null; - } - - const channel = (token: string): number | null => { - const pct = token.endsWith("%"); - const n = parseFloat(pct ? token.slice(0, -1) : token); - if (!isFinite(n)) { - return null; - } - - return Math.max( - 0, - Math.min(255, Math.round(pct ? (n / 100) * 255 : n)), - ); - }; - - const r = channel(tokens[0]); - const g = channel(tokens[1]); - const b = channel(tokens[2]); - return r === null || g === null || b === null ? null : [r, g, b]; -} - -/** - * The shared `linear-gradient(...)` tokenizer of the viewer's CSS-valued - * config grammar. - */ -export function tokenizeLinearGradient( - src: string, -): Array<[RGB, number | null]> | null { - const m = src.trim().match(/^linear-gradient\s*\((.*)\)$/is); - if (!m) { - return null; - } - - const body = m[1]; - const parts: string[] = []; - let depth = 0; - let start = 0; - for (let i = 0; i < body.length; i++) { - const ch = body[i]; - if (ch === "(") { - depth++; - } else if (ch === ")") { - depth--; - } else if (ch === "," && depth === 0) { - parts.push(body.substring(start, i)); - start = i + 1; - } - } - - parts.push(body.substring(start)); - const out: Array<[RGB, number | null]> = []; - for (let i = 0; i < parts.length; i++) { - const piece = parts[i].trim(); - if (!piece) { - return null; - } - - const lower = piece.toLowerCase(); - if ( - i === 0 && - (lower.startsWith("to ") || - /^[-\d.]+(deg|rad|grad|turn)$/.test(lower)) - ) { - continue; - } - - const posMatch = piece.match(/\s([^\s)]+)$/); - let color = piece; - let offset: number | null = null; - if (posMatch) { - const tail = posMatch[1]; - if (tail.endsWith("%")) { - const n = parseFloat(tail.slice(0, -1)); - if (!isFinite(n)) { - return null; - } - - color = piece.substring(0, posMatch.index).trim(); - offset = n / 100; - } else if (/^[-\d.]/.test(tail)) { - return null; - } - } - - const rgb = parseColorStrict(color); - if (!rgb) { - return null; - } - - out.push([rgb, offset]); - } - - return out; -} - -/** - * Strict gradient reader (numeric `fg_color`/`bg_color`): ≥ 2 stops, positions - * optional, clamped to `[0, 1]` and sorted, or `null` on malformed - * input. - */ -export function parseCssGradientStops(src: string): GradientStopRgb[] | null { - const entries = tokenizeLinearGradient(src); - if (!entries || entries.length < 2) { - return null; - } - - const offsets: Array = entries.map(([, p]) => p); - const last = offsets.length - 1; - if (offsets[0] === null) { - offsets[0] = 0; - } - - if (offsets[last] === null) { - offsets[last] = 1; - } - - for (let i = 1; i < last; i++) { - if (offsets[i] !== null) { - continue; - } - - let j = i + 1; - while (offsets[j] === null) { - j++; - } - - const before = offsets[i - 1]!; - const after = offsets[j]!; - const span = j - (i - 1); - for (let k = i; k < j; k++) { - offsets[k] = before + ((k - (i - 1)) / span) * (after - before); - } - - i = j - 1; - } - - const stops: GradientStopRgb[] = entries.map(([rgb], i) => ({ - rgb, - offset: Math.max(0, Math.min(1, offsets[i]!)), - })); - - stops.sort((a, b) => a.offset - b.offset); - return stops; -} - -/** - * Strict palette reader (string `series` `fg_color`/`bg_color`): ≥ 1 colors - * with no positions, or - * `null` on malformed input. - */ -export function parseCssColorList(src: string): RGB[] | null { - const entries = tokenizeLinearGradient(src); - if (!entries || entries.length === 0) { - return null; - } - - const out: RGB[] = []; - for (const [rgb, offset] of entries) { - if (offset !== null) { - return null; - } - - out.push(rgb); - } - - return out; -} - -/** The viewer's canonical gradient string: `linear-gradient(to right, #rrggbb P%, …)`, sorted, 0.1% positions. */ -export function stopsToCss( - stops: Array<{ color: string; offset: number }>, -): string { - const body = [...stops] - .sort((a, b) => a.offset - b.offset) - .map((stop) => { - const pct = - Math.round(Math.max(0, Math.min(1, stop.offset)) * 1000) / 10; - return `${stop.color} ${pct}%`; - }) - .join(", "); - - return `linear-gradient(to right, ${body})`; -} - -/** The viewer's canonical palette string: `linear-gradient(to right, #rrggbb, …)` — no positions. */ -export function colorsToCss(colors: string[]): string { - return `linear-gradient(to right, ${colors.join(", ")})`; -} - /** Build a CSS `linear-gradient` that fans `rgb` ±15° in hue, used as the negative-value swatch in column color pickers. */ function make_gradient(rgb: RGB): string { const [h, s, l] = rgbToHsl(rgb); diff --git a/rust/perspective-viewer/src/ts/plugin_utils/column_style.ts b/rust/perspective-viewer/src/ts/plugin_utils/column_style.ts new file mode 100644 index 0000000000..646a3e07e8 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/column_style.ts @@ -0,0 +1,238 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { ColumnType } from "@perspective-dev/client"; +import { + make_color_record, + rgbToHex, + type ColorRecord, + type GradientStopRgb, +} from "./color.ts"; +import { + native, + type DateFormatConfig, + type NumberFormatConfig, +} from "./native.ts"; + +export { isMetaColumn } from "./meta_columns.ts"; + +/** Foreground treatments of an integer / float column. */ +export const NUMBER_FG_MODES = [ + "disabled", + "color", + "bar", + "label-bar", +] as const; + +/** Background treatments of an integer / float column. */ +export const NUMBER_BG_MODES = [ + "disabled", + "color", + "gradient", + "pulse", +] as const; + +/** Foreground and background treatments of a string column. */ +export const STRING_MODES = ["disabled", "color", "series"] as const; + +/** Foreground and background treatments of a date / datetime column. */ +export const DATETIME_MODES = ["disabled", "color"] as const; + +export type NumberFgMode = (typeof NUMBER_FG_MODES)[number]; +export type NumberBgMode = (typeof NUMBER_BG_MODES)[number]; +export type StringMode = (typeof STRING_MODES)[number]; +export type DatetimeMode = (typeof DATETIME_MODES)[number]; + +/** + * Every foreground treatment some column type accepts. The subset a given + * column accepts is `fg_modes_for(type)`; `column_config_schema()` + * advertises exactly that subset, and the viewer rejects any other value. + */ +export type FgMode = NumberFgMode | StringMode | DatetimeMode; + +/** Every background treatment some column type accepts, as {@link FgMode}. */ +export type BgMode = NumberBgMode | StringMode | DatetimeMode; + +/** The `fg_mode` values a column of `type` accepts, empty for boolean. */ +export function fg_modes_for(type: ColumnType): readonly FgMode[] { + switch (type) { + case "integer": + case "float": + return NUMBER_FG_MODES; + case "string": + return STRING_MODES; + case "date": + case "datetime": + return DATETIME_MODES; + default: + return []; + } +} + +/** The `bg_mode` values a column of `type` accepts, empty for boolean. */ +export function bg_modes_for(type: ColumnType): readonly BgMode[] { + switch (type) { + case "integer": + case "float": + return NUMBER_BG_MODES; + case "string": + return STRING_MODES; + case "date": + case "datetime": + return DATETIME_MODES; + default: + return []; + } +} + +/** The `fg_mode` an omitted key stands for: colored text for numbers. */ +export function default_fg_mode(type: ColumnType): FgMode { + return type === "integer" || type === "float" ? "color" : "disabled"; +} + +/** The `bg_mode` an omitted key stands for. */ +export function default_bg_mode(_type: ColumnType): BgMode { + return "disabled"; +} + +/** `raw` as an `fg_mode` a column of `type` accepts, else `undefined`. */ +export function parse_fg_mode( + type: ColumnType, + raw: unknown, +): FgMode | undefined { + return (fg_modes_for(type) as readonly unknown[]).includes(raw) + ? (raw as FgMode) + : undefined; +} + +/** `raw` as a `bg_mode` a column of `type` accepts, else `undefined`. */ +export function parse_bg_mode( + type: ColumnType, + raw: unknown, +): BgMode | undefined { + return (bg_modes_for(type) as readonly unknown[]).includes(raw) + ? (raw as BgMode) + : undefined; +} + +/** The `columns_config` keys the cell style handlers and formatters read. */ +export interface ColumnStyleConfig { + fg_mode?: FgMode; + bg_mode?: BgMode; + fg_color?: string; + bg_color?: string; + fg_gradient?: number; + bg_gradient?: number; + link?: boolean; + date_format?: DateFormatConfig; + number_format?: NumberFormatConfig; +} + +/** The parsed forms of a column's `fg_color` / `bg_color` strings. */ +export interface ResolvedColors { + /** `fg_color` as a single color (string / datetime `"color"` mode). */ + fg_color?: ColorRecord; + bg_color?: ColorRecord; + + /** `fg_color` as gradient stops (numeric columns), t-ordered. */ + fg_stops?: GradientStopRgb[]; + bg_stops?: GradientStopRgb[]; + + /** End colors of `fg_stops` / `bg_stops`: the last stop is positive. */ + pos_fg_color?: ColorRecord; + neg_fg_color?: ColorRecord; + pos_bg_color?: ColorRecord; + neg_bg_color?: ColorRecord; + + /** `fg_color` as a palette (string `"series"` mode), `#rrggbb` each. */ + fg_palette?: string[]; + bg_palette?: string[]; +} + +/** `T` with its `fg_color` / `bg_color` strings replaced by their parsed forms. */ +export type Resolved = Omit & ResolvedColors; + +/** + * A column's {@link ColumnStyleConfig} with its `fg_color` / `bg_color` + * strings parsed once at `restore()`. Column types are not known at restore + * time, so every reader runs and each parsed form is present when its + * grammar matched; the per-type cell style handlers pick the form their + * mode needs. + */ +export type ResolvedColumnStyle = Resolved; + +/** + * Every parsed form of one `fg_color` / `bg_color` string. Column types + * are unknown here (`restore()` may run before the model exists), so each + * reader runs and the style handlers pick the form their mode needs. + */ +interface ParsedColor { + color?: ColorRecord; + stops?: GradientStopRgb[]; + palette?: string[]; +} + +function parse_color_value(raw: unknown): ParsedColor { + if (typeof raw !== "string") { + return {}; + } + + const stops = native().parse_css_gradient(raw); + const palette = native().parse_css_palette(raw)?.map(rgbToHex); + return { + color: is_single_color(raw) ? make_color_record(raw) : undefined, + stops, + palette, + }; +} + +/** A bare CSS color, as opposed to a `linear-gradient(…)` list. */ +function is_single_color(raw: string): boolean { + return !raw.trim().toLowerCase().startsWith("linear-gradient("); +} + +function end_records( + stops: GradientStopRgb[] | undefined, +): [neg: ColorRecord | undefined, pos: ColorRecord | undefined] { + if (!stops) { + return [undefined, undefined]; + } + + return [ + make_color_record(rgbToHex(stops[0].rgb)), + make_color_record(rgbToHex(stops[stops.length - 1].rgb)), + ]; +} + +/** `config` with its color strings parsed into every form a handler reads. */ +export function resolve_column_style< + T extends { fg_color?: string; bg_color?: string }, +>(config: T): Resolved { + const { fg_color, bg_color, ...rest } = config; + const fg = parse_color_value(fg_color); + const bg = parse_color_value(bg_color); + const [neg_fg_color, pos_fg_color] = end_records(fg.stops); + const [neg_bg_color, pos_bg_color] = end_records(bg.stops); + return { + ...rest, + fg_color: fg.color, + bg_color: bg.color, + fg_stops: fg.stops, + bg_stops: bg.stops, + pos_fg_color, + neg_fg_color, + pos_bg_color, + neg_bg_color, + fg_palette: fg.palette, + bg_palette: bg.palette, + }; +} diff --git a/rust/perspective-viewer/src/ts/plugin_utils/css.d.ts b/rust/perspective-viewer/src/ts/plugin_utils/css.d.ts new file mode 100644 index 0000000000..93758fda71 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/css.d.ts @@ -0,0 +1,16 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +declare module "*.css" { + const text: string; + export default text; +} diff --git a/rust/perspective-viewer/src/ts/plugin_utils/format.ts b/rust/perspective-viewer/src/ts/plugin_utils/format.ts new file mode 100644 index 0000000000..865974b4e9 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/format.ts @@ -0,0 +1,84 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { ColumnType } from "@perspective-dev/client"; +import { + native, + type DateFormatConfig, + type Formatter, + type NumberFormatConfig, +} from "./native.ts"; + +type FormatConfig = { + date_format?: DateFormatConfig; + number_format?: NumberFormatConfig; +}; + +const DEFAULT_FORMATTERS = new Map(); + +const STYLE_FORMATTERS = new WeakMap< + object, + Map +>(); + +function format_of( + type: ColumnType, + style: FormatConfig, +): NumberFormatConfig | DateFormatConfig | undefined { + if (type === "integer" || type === "float") { + return style.number_format; + } else if (type === "date" || type === "datetime") { + return style.date_format; + } + + return undefined; +} + +/** + * The formatter of a column of `type` styled by `style`, created on first + * use and kept for the life of the `style` object. + */ +export function format_raw( + type: ColumnType, + style: FormatConfig, +): Formatter | undefined { + const format = format_of(type, style); + let formatters = DEFAULT_FORMATTERS; + if (format !== undefined) { + let own = STYLE_FORMATTERS.get(style); + if (own === undefined) { + own = new Map(); + STYLE_FORMATTERS.set(style, own); + } + + formatters = own; + } + + if (!formatters.has(type)) { + formatters.set(type, native().formatter(type, format)); + } + + return formatters.get(type); +} + +/** Release every formatter `format_raw` created for the style objects in `styles`. */ +export function free_formatters(styles: Record): void { + for (const style of Object.values(styles)) { + const formatters = STYLE_FORMATTERS.get(style); + if (formatters !== undefined) { + STYLE_FORMATTERS.delete(style); + for (const formatter of formatters.values()) { + formatter?.free(); + } + } + } +} diff --git a/rust/perspective-viewer/src/ts/plugin_utils/index.ts b/rust/perspective-viewer/src/ts/plugin_utils/index.ts new file mode 100644 index 0000000000..ea7c4fa4c1 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/index.ts @@ -0,0 +1,70 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import * as cell_style from "./cell_style.ts"; +import * as color from "./color.ts"; +import * as column_style from "./column_style.ts"; +import * as format from "./format.ts"; +import { bind_native, pick_native, type NativeUtils } from "./native.ts"; +import * as schema from "./schema.ts"; +import * as theme_style from "./theme_style.ts"; + +export type * from "./cell_style.ts"; +export type * from "./color.ts"; +export type * from "./column_style.ts"; +export type * from "./format.ts"; +export type { + DateFormatConfig, + DateFormatModifiers, + FormattedColumn, + Formatter, + NativeUtils, + NumberFormatConfig, +} from "./native.ts"; +export type * from "./schema.ts"; +export type * from "./theme_style.ts"; + +/** The code `` shares with its plugins, as the element class's static `plugin_utils`. */ +export interface PluginUtils extends NativeUtils { + /** Formatter handles kept per column style. */ + format: typeof format; + + /** CSS color parsing, conversion and gradient sampling. */ + color: typeof color; + + /** The `fg_mode` / `bg_mode` vocabulary and `columns_config` color parsing. */ + column_style: typeof column_style; + + /** The theme colors read from an element's computed style. */ + theme_style: typeof theme_style; + + /** The per-type handlers which style one rendered cell. */ + cell_style: typeof cell_style; + + /** The `column_config_schema()` controls plugins share. */ + schema: typeof schema; +} + +/** The `plugin_utils` of the viewer whose wasm module is `module`. */ +export function create_plugin_utils(module: NativeUtils): PluginUtils { + const native = pick_native(module); + bind_native(native); + return Object.freeze({ + ...native, + format, + cell_style, + color, + column_style, + schema, + theme_style, + }); +} diff --git a/packages/viewer-datagrid/src/ts/model/meta_columns.ts b/rust/perspective-viewer/src/ts/plugin_utils/meta_columns.ts similarity index 100% rename from packages/viewer-datagrid/src/ts/model/meta_columns.ts rename to rust/perspective-viewer/src/ts/plugin_utils/meta_columns.ts diff --git a/rust/perspective-viewer/src/ts/plugin_utils/native.ts b/rust/perspective-viewer/src/ts/plugin_utils/native.ts new file mode 100644 index 0000000000..e5af6656b6 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/native.ts @@ -0,0 +1,68 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type * as wasm_module from "../../../dist/wasm/perspective-viewer.js"; + +export type { + DateFormatConfig, + DateFormatModifiers, + FormattedColumn, + Formatter, + NumberFormatConfig, +} from "../../../dist/wasm/perspective-viewer.js"; + +/** + * The members of `plugin_utils` implemented in the viewer's WebAssembly, + * which a `Worker` reaches as the exports of the viewer's wasm module. + */ +export type NativeUtils = Pick< + typeof wasm_module, + | "formatter" + | "source_column" + | "parse_css_color" + | "parse_css_gradient" + | "parse_css_palette" + | "css_gradient" + | "css_palette" + | "has_date_format_shape" + | "date_format_modifiers" +>; + +/** The names of the members of {@link NativeUtils}. */ +const NATIVE_UTILS = [ + "formatter", + "source_column", + "parse_css_color", + "parse_css_gradient", + "parse_css_palette", + "css_gradient", + "css_palette", + "has_date_format_shape", + "date_format_modifiers", +] as const satisfies readonly (keyof NativeUtils)[]; + +let NATIVE: NativeUtils | undefined; + +/** The members of {@link NativeUtils} in `module`, the viewer's wasm module. */ +export function pick_native(module: NativeUtils): NativeUtils { + return Object.fromEntries( + NATIVE_UTILS.map((name) => [name, module[name]]), + ) as NativeUtils; +} + +export function bind_native(native: NativeUtils): void { + NATIVE = native; +} + +export function native(): NativeUtils { + return NATIVE!; +} diff --git a/rust/perspective-viewer/src/ts/plugin_utils/schema.ts b/rust/perspective-viewer/src/ts/plugin_utils/schema.ts new file mode 100644 index 0000000000..aabaab9f11 --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/schema.ts @@ -0,0 +1,240 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { ColumnType } from "@perspective-dev/client"; +import { rgbToHex } from "./color.ts"; +import { native } from "./native.ts"; +import { + bg_modes_for, + default_bg_mode, + default_fg_mode, + fg_modes_for, + parse_bg_mode, + parse_fg_mode, + type BgMode, + type ColumnStyleConfig, + type FgMode, +} from "./column_style.ts"; +import type { ThemeStyle } from "./theme_style.ts"; + +/** + * Where in the `ViewConfig` a column being configured appears, which is a + * different axis from its plugin column slot. + */ +export type ColumnRole = "column" | "group_by" | "split_by"; + +/** + * A cell of the 3×3 alignment grid: corners `"top-left"` etc., edges + * `"top"`/`"left"`/`"right"`/`"bottom"`, or `"center"`. + */ +export type Align = + | "top-left" + | "top" + | "top-right" + | "left" + | "center" + | "right" + | "bottom-left" + | "bottom" + | "bottom-right"; + +export const ALIGNS: readonly Align[] = [ + "top-left", + "top", + "top-right", + "left", + "center", + "right", + "bottom-left", + "bottom", + "bottom-right", +]; + +/** An `align` value from a token, or `undefined` for anything else. */ +export function parse_align(raw: unknown): Align | undefined { + return ALIGNS.includes(raw as Align) ? (raw as Align) : undefined; +} + +/** CSS generic font families, which are never quoted when applied. */ +export const GENERIC_FONT_FAMILIES: readonly string[] = [ + "inherit", + "monospace", + "sans-serif", + "serif", + "system-ui", +]; + +/** The CSS `font-family` value for a `font_family` config value. */ +export function css_font_family(family: string): string { + if (GENERIC_FONT_FAMILIES.includes(family)) { + return family; + } + + return `"${family.replace(/["\\]/g, "\\$&")}"`; +} + +export type ControlSpec = Record & { kind: string }; + +export interface ColumnConfigSchema { + fields: ControlSpec[]; +} + +/** + * A column's `date_format` / `number_format` controls, which are the only ones + * that apply to a value rendered as a pivot label rather than a cell. + */ +export function format_fields(type: ColumnType): ControlSpec[] { + if (type === "integer" || type === "float") { + return [{ kind: "NumberFormat" }]; + } else if (type === "date" || type === "datetime") { + return [{ kind: "DatetimeFormat" }]; + } + + return []; +} + +/** + * The `"color"` group of a column of `type`: its `fg_mode` / `bg_mode` + * selectors and the value controls `current_value`'s modes gate in, or + * `undefined` for a type with no modes. + */ +export function color_group( + type: ColumnType, + current_value: Record | null, + theme: () => ThemeStyle, +): ControlSpec | undefined { + const fg_modes = fg_modes_for(type); + const bg_modes = bg_modes_for(type); + if (fg_modes.length === 0 && bg_modes.length === 0) { + return undefined; + } + + const fg_mode = + parse_fg_mode(type, current_value?.fg_mode) ?? default_fg_mode(type); + + const bg_mode = + parse_bg_mode(type, current_value?.bg_mode) ?? default_bg_mode(type); + + const color_fields: ControlSpec[] = [ + mode_spec("fg_mode", fg_modes, default_fg_mode(type)), + ...value_specs(type, "fg", fg_mode, theme), + mode_spec("bg_mode", bg_modes, default_bg_mode(type)), + ...value_specs(type, "bg", bg_mode, theme), + ]; + + return { kind: "Group", key: "color", fields: color_fields }; +} + +const MODE_LABELS: Record = { + disabled: "Disabled", + color: "Color", + bar: "Bar", + "label-bar": "Gradient", + gradient: "Gradient", + pulse: "Pulse", + series: "Series", +}; + +/** The `Enum` control for `fg_mode` / `bg_mode` over a type's modes. */ +function mode_spec( + key: "fg_mode" | "bg_mode", + modes: readonly (FgMode | BgMode)[], + default_mode: FgMode | BgMode, +): ControlSpec { + return { + kind: "Enum", + key: key satisfies keyof ColumnStyleConfig, + default: default_mode, + variants: modes.map((value) => ({ value, label: MODE_LABELS[value] })), + }; +} + +/** + * The controls a foreground or background `mode` gates in for a column of + * `type`: the `fg_color` / `bg_color` value control in the grammar the + * (type, mode) pair reads - gradient stops for numbers, a color for + * string / datetime `"color"`, a palette for string `"series"` - plus the + * numeric scale extent. Nothing for `"disabled"`. + */ +function value_specs( + type: ColumnType, + side: "fg" | "bg", + mode: FgMode | BgMode, + read_theme: () => ThemeStyle, +): ControlSpec[] { + if (mode === "disabled") { + return []; + } + + const theme = read_theme(); + + const key = `${side}_color` satisfies keyof ColumnStyleConfig; + if (type === "integer" || type === "float") { + const pos = theme[`_pos_${side}_color`][0]; + const neg = theme[`_neg_${side}_color`][0]; + const stops: ControlSpec = + mode === "gradient" || mode === "pulse" + ? { + kind: "GradientStops", + key, + default: native().css_gradient([ + { color: neg, offset: 0 }, + { + color: rgbToHex( + theme._plugin_background as [ + number, + number, + number, + ], + ), + offset: 0.5, + }, + { color: pos, offset: 1 }, + ]), + } + : { + kind: "GradientStops", + key, + default: native().css_gradient([ + { color: neg, offset: 0 }, + { color: pos, offset: 1 }, + ]), + discrete: true, + }; + + const scaled = + mode === "bar" || mode === "label-bar" || mode === "gradient"; + + return scaled + ? [ + stops, + { + kind: "Number", + key: `${side}_gradient` satisfies keyof ColumnStyleConfig, + include: true, + default: 0, + default_stat: "abs_max", + }, + ] + : [stops]; + } else if (mode === "series") { + return [ + { + kind: "Palette", + key, + default: native().css_palette(theme._series_palette), + }, + ]; + } else { + return [{ kind: "Color", key, default: theme._color[0] }]; + } +} diff --git a/rust/perspective-viewer/src/ts/plugin_utils/theme_style.ts b/rust/perspective-viewer/src/ts/plugin_utils/theme_style.ts new file mode 100644 index 0000000000..bfc2ae2abd --- /dev/null +++ b/rust/perspective-viewer/src/ts/plugin_utils/theme_style.ts @@ -0,0 +1,126 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { + blend, + make_color_record, + parseColor, + rgbToHex, + type ColorRecord, + type GradientStopRgb, + type RGB, +} from "./color.ts"; + +const UNSET_COLOR = "rgba(0, 0, 0, 0)"; + +function get_rule(regular: HTMLElement, tag: string, def: string): string { + const color = window.getComputedStyle(regular).getPropertyValue(tag).trim(); + if (color.length > 0 && color !== UNSET_COLOR) { + return color; + } else { + return def; + } +} + +/** The theme-derived colors the cell style handlers and settings schema read. */ +export interface ThemeStyle { + _theme: string; + _plugin_background: number[]; + _color: ColorRecord; + _pos_fg_color: ColorRecord; + _neg_fg_color: ColorRecord; + _pos_bg_color: ColorRecord; + _neg_bg_color: ColorRecord; + _default_bg_color_stops: GradientStopRgb[]; + _series_palette: string[]; +} + +function read_series_palette(regular: HTMLElement, accent: string): string[] { + const walk = (prefix: string): string[] => { + const out: string[] = []; + for (let i = 1; ; i++) { + const raw = get_rule(regular, `${prefix}${i}--color`, ""); + if (!raw) { + break; + } + + out.push(rgbToHex(parseColor(raw))); + } + + return out; + }; + + const own = walk("--psp-datagrid--series-"); + if (own.length > 0) { + return own; + } + + const charts = walk("--psp-charts--series-"); + return charts.length > 0 ? charts : [rgbToHex(parseColor(accent))]; +} + +/** + * Read the theme-derived style values off `regular`'s computed style, the + * single source for the color/theme fields cached on `DatagridModel`. + */ +export function readThemeStyle(regular: HTMLElement): ThemeStyle { + const _theme = get_rule(regular, "--psp-theme-name", ""); + const _plugin_background = parseColor( + get_rule(regular, "--psp--background-color", "#FFFFFF"), + ); + + const _pos_fg_color = make_color_record( + get_rule(regular, "--psp-datagrid--pos-cell--color", "#338DCD"), + ); + + const _neg_fg_color = make_color_record( + get_rule(regular, "--psp-datagrid--neg-cell--color", "#FF5942"), + ); + + const _pos_bg_color = make_color_record( + blend(_pos_fg_color[0], _plugin_background), + ); + + const _neg_bg_color = make_color_record( + blend(_neg_fg_color[0], _plugin_background), + ); + + const _color = make_color_record( + get_rule(regular, "--psp-active--color", "#ff0000"), + ); + + const _series_palette = read_series_palette(regular, _color[0]); + + const _default_bg_color_stops = [ + { + rgb: [_neg_bg_color[1], _neg_bg_color[2], _neg_bg_color[3]] as RGB, + offset: 0, + }, + { rgb: _plugin_background as RGB, offset: 0.5 }, + { + rgb: [_pos_bg_color[1], _pos_bg_color[2], _pos_bg_color[3]] as RGB, + offset: 1, + }, + ]; + + return { + _theme, + _plugin_background, + _color, + _pos_fg_color, + _neg_fg_color, + _pos_bg_color, + _neg_bg_color, + _default_bg_color_stops, + _series_palette, + }; +} diff --git a/rust/perspective-viewer/test/js/settings_panel/status_bar_menus.spec.ts b/rust/perspective-viewer/test/js/settings_panel/status_bar_menus.spec.ts index f105e7ae74..cff6a6a003 100644 --- a/rust/perspective-viewer/test/js/settings_panel/status_bar_menus.spec.ts +++ b/rust/perspective-viewer/test/js/settings_panel/status_bar_menus.spec.ts @@ -86,20 +86,6 @@ test.describe("Status bar export and copy menus", () => { await expect(menu).toHaveCount(0); }); - test("export and copy still open after the New menu was used", async ({ - page, - }) => { - const viewer = page.locator("perspective-viewer"); - await viewer.locator("#status_bar #new_panel").click(); - await expect(page.locator("perspective-new-panel-menu")).toBeVisible(); - await page.keyboard.press("Escape"); - await viewer.locator("#status_bar #copy").click(); - await expect(page.locator("perspective-copy-menu")).toBeVisible(); - await page.keyboard.press("Escape"); - await viewer.locator("#status_bar #export").click(); - await expect(page.locator("perspective-export-menu")).toBeVisible(); - }); - test("resizing the window closes the export menu", async ({ page }) => { const viewer = page.locator("perspective-viewer"); await viewer.locator("#status_bar #export").click(); @@ -121,42 +107,4 @@ test.describe("Status bar export and copy menus", () => { await page.evaluate(() => window.scrollTo(0, 100)); await expect(menu).toHaveCount(0); }); - - test("scrolling the height-limited New menu's own list keeps it open", async ({ - page, - }) => { - await page.evaluate(async () => { - const worker = window["__TEST_WORKER__"]; - await Promise.all( - Array.from({ length: 300 }, (_, i) => - worker.table({ x: [1] }, { name: `t_${i}` }), - ), - ); - }); - - const viewer = page.locator("perspective-viewer"); - await viewer.locator("#status_bar #new_panel").click(); - const menu = page.locator("perspective-new-panel-menu"); - await menu - .locator(".dropdown-menu-item", { hasText: "t_299" }) - .waitFor({ state: "attached" }); - - await expect - .poll(() => menu.evaluate((el: HTMLElement) => el.style.maxHeight)) - .not.toBe(""); - - await menu.evaluate((el) => { - el.scrollTop = 200; - }); - - await page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(resolve)), - ), - ); - - await expect(menu).toBeVisible(); - expect(await menu.evaluate((el) => el.scrollTop)).toBeGreaterThan(0); - }); }); diff --git a/rust/perspective-viewer/test/js/viewer_api/custom_elements_manifest.spec.ts b/rust/perspective-viewer/test/js/viewer_api/custom_elements_manifest.spec.ts index 1a790e22a0..e92c52956f 100644 --- a/rust/perspective-viewer/test/js/viewer_api/custom_elements_manifest.spec.ts +++ b/rust/perspective-viewer/test/js/viewer_api/custom_elements_manifest.spec.ts @@ -113,7 +113,12 @@ test.describe("Custom elements manifest", () => { .filter(visible) .sort(), statics: Object.getOwnPropertyNames(cls) - .filter((x) => typeof cls[x] === "function") + .filter( + (x) => + typeof cls[x] === "function" || + Object.getOwnPropertyDescriptor(cls, x)?.get !== + undefined, + ) .filter(visible) .sort(), }; diff --git a/rust/perspective-viewer/tools.mjs b/rust/perspective-viewer/tools.mjs index 79456b5ba0..103814fd08 100644 --- a/rust/perspective-viewer/tools.mjs +++ b/rust/perspective-viewer/tools.mjs @@ -77,11 +77,26 @@ const DOCS_DTS_FILES = [ prefix: "Datagrid Plugin", scope: [ "type EditMode", - "type Align", "interface ColumnConfig", "interface DatagridPluginConfig", ], }, + { + file: "./src/ts/plugin_utils/schema.ts", + prefix: "Plugin Config", + scope: ["type Align"], + }, + { + file: "../../packages/viewer-summary/src/ts/types.ts", + prefix: "Summary Plugin", + scope: [ + "type LabelPosition", + "type ValueFit", + "type Breakdown", + "interface ColumnConfig", + "interface SummaryPluginConfig", + ], + }, { file: "../../packages/viewer-charts/src/ts/charts/chart.ts", prefix: "Charts Plugin", @@ -955,6 +970,30 @@ function cemKnownTypes() { known.set(name, "@perspective-dev/viewer"); } + const plugin_utils = "./src/ts/plugin_utils"; + const exported = [ + ...fs + .readFileSync(path.join(plugin_utils, "index.ts"), "utf8") + .matchAll(/export type \* from "\.\/(\w+)\.ts";/g), + ].map((x) => path.join(plugin_utils, `${x[1]}.ts`)); + + for (const file of [path.join(plugin_utils, "index.ts"), ...exported]) { + const text = fs.readFileSync(file, "utf8"); + for (const [, name] of text.matchAll( + /^export (?:interface|type|class) (\w+)/gm, + )) { + known.set(name, "@perspective-dev/viewer"); + } + + for (const [, names] of text.matchAll(/^export type \{([^}]*)\}/gm)) { + for (const name of names.split(",")) { + if (name.trim()) { + known.set(name.trim(), "@perspective-dev/viewer"); + } + } + } + } + return known; } From 3ebdf5c9204b65831f2db8a09a53ed63ccb382d3 Mon Sep 17 00:00:00 2001 From: Andrew Stein Date: Sat, 21 Nov 2026 12:03:24 -0500 Subject: [PATCH 2/4] Add `date` and `datetime` to `max by` and `min by` aggregates Signed-off-by: Andrew Stein --- .../view/config/grouping_and_pivots.md | 30 +++++-- .../perspective-js/test/js/aggregates.spec.js | 82 +++++++++++++++++++ .../test/js/get_features.spec.js | 14 ++++ .../cpp/perspective/src/cpp/server.cpp | 28 ++++--- 4 files changed, 134 insertions(+), 20 deletions(-) diff --git a/docs/md/explanation/view/config/grouping_and_pivots.md b/docs/md/explanation/view/config/grouping_and_pivots.md index 301841b3ec..dc3c2f8c3b 100644 --- a/docs/md/explanation/view/config/grouping_and_pivots.md +++ b/docs/md/explanation/view/config/grouping_and_pivots.md @@ -256,7 +256,7 @@ accumulate as `integer`, `float` columns as `float`. | Aggregate | Description | Result type | | --- | --- | --- | | `min`, `max` | Smallest and largest of the group's current values | input type | -| `min by`, `max by` | The value from the row at which a **second column**, supplied as an argument, is smallest or largest | input type | +| `min by`, `max by` | The value from the row at which a **second column**, supplied as an argument, is smallest or largest; the argument may be an `integer`, `float`, `date` or `datetime` column | input type | | `high`, `low` | High and low _water mark_ — the largest and smallest value this `View` has ever observed for the group, which never moves back when rows are updated or removed | input type | | `high minus low` | `max - min` of the group's current values, i.e. its range. Despite the name this uses `min`/`max`, not the water marks | input type | | `median`, `q1`, `q3` | The value at the 50%, 25% and 75% position of the group's values; on `float` columns an exact split averages the two adjacent values | input type | @@ -266,13 +266,24 @@ accumulate as `integer`, `float` columns as `float`. | Aggregate | Description | Result type | | --- | --- | --- | | `first` | Value from the group's earliest row | input type | -| `last by index` | Value from the group's latest row | input type | +| `last by index` | Value from the group's latest row, out of every row in the group | input type | | `last minus first` | `last by index` minus `first` | input type | -| `last` | Value from the group's most recently _updated_ row | input type | - -"Earliest" and "latest" are by the `Table`'s `index` column, or by row order -when the `Table` is unindexed. This is not the same as `last`, which tracks -update recency rather than position. +| `last` | On leaf rows, the same as `last by index`. On parent rows, the `last` of the group's most recently _created_ leaf group | input type | + +"Earliest" and "latest" are by the `Table`'s `index` — compared column by +column for a multi-column `index` — or by insertion order when the `Table` is +unindexed. On an indexed `Table`, an `update()` that overwrites an existing row +does not make that row the latest; neither `last` nor `last by index` tracks +update recency. + +`last` differs from `last by index` only on parent rows, including the total +row. Rather than reading every row in the group, it takes the latest row of +whichever leaf group (deepest `group_by` level) was created most recently. The +groups created by one `update()`, or by the initial load, are created in +ascending order of their `group_by` values. For the unindexed rows +`{x: 1, z: true}`, `{x: 2, z: false}`, `{x: 3, z: true}`, `{x: 4, z: false}` +grouped by `z`, the total row's `last by index` is `4` but its `last` is `3`, +because the `true` group sorts after, and so was created after, `false`. ### Cardinality and identity @@ -335,7 +346,10 @@ column's underlying numeric representation — not a date. ### Argument-taking aggregates `weighted mean`, `min by` and `max by` each read a second column, and are -written as a `[name, [argument]]` pair rather than a bare string: +written as a `[name, [argument]]` pair rather than a bare string. The argument +to `weighted mean` must be numeric; the argument to `min by` and `max by` may +also be a `date` or `datetime` column, e.g. `["max by", ["timestamp"]]` for +each group's most recent value:
diff --git a/rust/perspective-js/test/js/aggregates.spec.js b/rust/perspective-js/test/js/aggregates.spec.js index f4ed02db34..ec475ca621 100644 --- a/rust/perspective-js/test/js/aggregates.spec.js +++ b/rust/perspective-js/test/js/aggregates.spec.js @@ -952,6 +952,88 @@ const std = (nums) => { await table.delete(); }); + test("max_by and min_by with a date argument", async () => { + const table = await perspective.table({ + b: "integer", + c: "string", + e: "string", + d: "date", + }); + + await table.update({ + b: [0, 1, 0, 1, 0, 1], + c: ["a", "b", "c", "d", "e", "f"], + e: ["a", "b", "c", "d", "e", "f"], + d: [ + new Date(2024, 0, 1), + new Date(2023, 11, 31), + new Date(2023, 1, 28), + new Date(2024, 2, 15), + new Date(2022, 10, 30), + new Date(2023, 0, 31), + ], + }); + + const view = await table.view({ + columns: ["c", "e"], + aggregates: { + c: ["max by", ["d"]], + e: ["min by", ["d"]], + }, + group_by: ["b"], + }); + + expect(await view.to_columns()).toEqual({ + __ROW_PATH__: [[], [0], [1]], + c: ["d", "a", "d"], + e: ["e", "e", "f"], + }); + + await view.delete(); + await table.delete(); + }); + + test("max_by and min_by with a datetime argument", async () => { + const table = await perspective.table({ + b: "integer", + c: "float", + e: "float", + t: "datetime", + }); + + await table.update({ + b: [0, 1, 0, 1, 0, 1], + c: [1.5, 2.5, 3.5, 4.5, 5.5, 6.5], + e: [1.5, 2.5, 3.5, 4.5, 5.5, 6.5], + t: [ + new Date(Date.UTC(2024, 0, 1, 0, 0, 1)), + new Date(Date.UTC(2023, 11, 31, 23, 59, 59)), + new Date(Date.UTC(2024, 0, 1, 0, 0, 0)), + new Date(Date.UTC(2024, 0, 1, 12, 0, 0)), + new Date(Date.UTC(2023, 5, 15, 8, 30, 0)), + new Date(Date.UTC(2023, 11, 31, 23, 59, 58)), + ], + }); + + const view = await table.view({ + columns: ["c", "e"], + aggregates: { + c: ["max by", ["t"]], + e: ["min by", ["t"]], + }, + group_by: ["b"], + }); + + expect(await view.to_columns()).toEqual({ + __ROW_PATH__: [[], [0], [1]], + c: [4.5, 1.5, 4.5], + e: [5.5, 5.5, 6.5], + }); + + await view.delete(); + await table.delete(); + }); + test("max_by with empty filter", async () => { const data = { a: [1, 2, 3, 4, 5, 6, 7, 8], diff --git a/rust/perspective-js/test/js/get_features.spec.js b/rust/perspective-js/test/js/get_features.spec.js index f969bdce10..fb16bfc22c 100644 --- a/rust/perspective-js/test/js/get_features.spec.js +++ b/rust/perspective-js/test/js/get_features.spec.js @@ -26,3 +26,17 @@ test("get_features() reports the native engine's features", async () => { expect(Object.keys(features.aggregates)).toContain("integer"); await table.delete(); }); + +test("get_features() accepts float, date and datetime arguments to min by and max by", async () => { + const table = await perspective.table({ x: [1, 2, 3] }); + const features = await table.get_features(); + for (const type of ["string", "integer", "float"]) { + for (const agg of ["min by", "max by"]) { + for (const arg of ["float", "date", "datetime"]) { + expect(features.aggregates[type]).toContainEqual([agg, [arg]]); + } + } + } + + await table.delete(); +}); diff --git a/rust/perspective-server/cpp/perspective/src/cpp/server.cpp b/rust/perspective-server/cpp/perspective/src/cpp/server.cpp index 7836b3b1ce..cc8a49bb05 100644 --- a/rust/perspective-server/cpp/perspective/src/cpp/server.cpp +++ b/rust/perspective-server/cpp/perspective/src/cpp/server.cpp @@ -2378,6 +2378,20 @@ ProtoServer::_handle_request(std::uint32_t client_id, Request&& req) { (*features->mutable_filter_ops())[proto::ColumnType::BOOLEAN] = opts2; + const auto add_extrema_by = + [](proto::GetFeaturesResp_AggregateOptions& opts) { + for (const auto by_type : + {proto::ColumnType::FLOAT, + proto::ColumnType::DATE, + proto::ColumnType::DATETIME}) { + for (const auto* name : {"min by", "max by"}) { + auto* agg = opts.add_aggregates(); + agg->set_name(name); + agg->add_args(by_type); + } + } + }; + proto::GetFeaturesResp_AggregateOptions string_opts; string_opts.add_aggregates()->set_name("count"); string_opts.add_aggregates()->set_name("any"); @@ -2392,12 +2406,7 @@ ProtoServer::_handle_request(std::uint32_t client_id, Request&& req) { string_opts.add_aggregates()->set_name("q1"); string_opts.add_aggregates()->set_name("q3"); string_opts.add_aggregates()->set_name("unique"); - auto args1 = string_opts.add_aggregates(); - args1->set_name("min by"); - args1->add_args(proto::ColumnType::FLOAT); - auto args2 = string_opts.add_aggregates(); - args2->set_name("max by"); - args2->add_args(proto::ColumnType::FLOAT); + add_extrema_by(string_opts); (*features->mutable_aggregates())[proto::ColumnType::STRING] = string_opts; @@ -2450,12 +2459,7 @@ ProtoServer::_handle_request(std::uint32_t client_id, Request&& req) { auto args3 = number_opts.add_aggregates(); args3->set_name("weighted mean"); args3->add_args(proto::ColumnType::FLOAT); - auto args4 = number_opts.add_aggregates(); - args4->set_name("min by"); - args4->add_args(proto::ColumnType::FLOAT); - auto args5 = number_opts.add_aggregates(); - args5->set_name("max by"); - args5->add_args(proto::ColumnType::FLOAT); + add_extrema_by(number_opts); (*features->mutable_aggregates())[proto::ColumnType::INTEGER] = number_opts; From 84440c6db9ce3f71b0e494d42e0a7b0db2abf720 Mon Sep 17 00:00:00 2001 From: Andrew Stein Date: Sat, 21 Nov 2026 12:03:01 -0500 Subject: [PATCH 3/4] Add batch columns buttons, swap edit row default Signed-off-by: Andrew Stein --- Cargo.toml | 2 - packages/viewer-charts/src/ts/layout/ticks.ts | 9 +- .../viewer-datagrid/src/css/regular_table.css | 36 ++- .../viewer-datagrid/src/css/row-hover.css | 16 +- .../src/ts/custom_elements/datagrid.ts | 2 +- .../viewer-datagrid/src/ts/model/create.ts | 2 +- .../src/ts/plugin/column_config_schema.ts | 14 +- .../src/ts/plugin/plugin_config_schema.ts | 2 +- .../viewer-datagrid/src/ts/plugin/restore.ts | 7 +- .../viewer-datagrid/src/ts/plugin/save.ts | 2 +- .../src/ts/style_handlers/body.ts | 15 +- packages/viewer-datagrid/src/ts/types.ts | 2 +- .../test/js/activation.spec.ts | 2 + .../test/js/column_config_validation.spec.ts | 1 + .../test/js/column_list_buttons.spec.ts | 66 +++++ .../test/js/column_settings.spec.ts | 14 + .../js/column_settings_activation.spec.ts | 139 ++++++++++ .../test/js/column_style.spec.ts | 5 + .../test/js/command_buttons.spec.ts | 2 +- .../js/context_menu_column_settings.spec.ts | 245 ++++++++++++++++++ .../test/js/control_groups.spec.ts | 1 + .../test/js/header_recycling.spec.ts | 1 + .../test/js/plugin_config_options.spec.ts | 26 +- .../viewer-datagrid/test/js/restyle.spec.ts | 1 + rust/perspective-viewer/Cargo.toml | 4 - .../src/css/column-selector.css | 38 +++ .../src/rust/components/column_selector.rs | 115 ++++++++ .../column_selector/active_column.rs | 19 ++ .../src/rust/components/main_panel.rs | 12 +- .../rust/components/main_panel/reconcile.rs | 1 - .../src/rust/components/main_panel/render.rs | 2 + .../src/rust/components/main_panel/update.rs | 36 +-- .../src/rust/components/panel_menu.rs | 116 ++++++--- .../src/rust/components/viewer.rs | 5 +- .../src/rust/components/viewer/msg.rs | 6 +- .../src/rust/components/viewer/panels.rs | 8 + .../src/rust/components/viewer/render.rs | 10 + .../src/rust/components/viewer/settings.rs | 72 +++-- .../src/rust/custom_elements/viewer.rs | 11 +- .../src/rust/queries/resolve_commands.rs | 28 +- rust/perspective-viewer/src/rust/workspace.rs | 5 + rust/perspective-viewer/src/themes/intl.css | 1 + .../perspective-viewer/src/themes/intl/ar.css | 1 + .../perspective-viewer/src/themes/intl/de.css | 1 + .../perspective-viewer/src/themes/intl/es.css | 1 + .../perspective-viewer/src/themes/intl/fr.css | 1 + .../perspective-viewer/src/themes/intl/ja.css | 1 + .../perspective-viewer/src/themes/intl/pt.css | 1 + .../perspective-viewer/src/themes/intl/zh.css | 1 + .../src/ts/plugin_utils/column_style.ts | 27 +- .../src/ts/plugin_utils/meta_columns.ts | 30 +-- .../src/ts/plugin_utils/schema.ts | 27 +- .../multi_panel/context_menu_commands.spec.ts | 27 +- .../context_menu_commands_plugin.spec.ts | 8 +- .../multi_panel/context_menu_viewer.spec.ts | 54 ++++ .../add_all_named_columns.spec.ts | 66 +++++ .../settings_panel/alignment_control.spec.ts | 41 +++ .../js/viewer_config/localization.spec.ts | 1 + rust/perspective-viewer/tools.mjs | 2 +- 59 files changed, 1155 insertions(+), 236 deletions(-) create mode 100644 packages/viewer-datagrid/test/js/column_list_buttons.spec.ts create mode 100644 packages/viewer-datagrid/test/js/column_settings_activation.spec.ts create mode 100644 packages/viewer-datagrid/test/js/context_menu_column_settings.spec.ts create mode 100644 rust/perspective-viewer/test/js/settings_panel/add_all_named_columns.spec.ts diff --git a/Cargo.toml b/Cargo.toml index 9955fe4b55..416c86a6f6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,8 +45,6 @@ codegen-units = 1 lto = true strip = true -# The crates `perspective-viewer`'s number and datetime formatters spend their -# time in, optimized for speed under an otherwise size-optimized profile. [profile.release.package] calendrical_calculations = { opt-level = 3 } core_maths = { opt-level = 3 } diff --git a/packages/viewer-charts/src/ts/layout/ticks.ts b/packages/viewer-charts/src/ts/layout/ticks.ts index fe87fc55a6..9c102b801e 100644 --- a/packages/viewer-charts/src/ts/layout/ticks.ts +++ b/packages/viewer-charts/src/ts/layout/ticks.ts @@ -132,9 +132,8 @@ export function formatTickValue(val: number): string { } /** - * Cached formatter per option shape, as building one parses its options. - * Keyed by precision tier and date options; the locale is fixed for the - * lifetime of the worker, so entries never invalidate. + * Formatters by precision tier and date modifiers, never invalidated as the + * worker's locale is fixed. */ const DATE_FORMAT_CACHE = new Map(); @@ -235,8 +234,8 @@ function dateTickFormatter( } /** - * Format a timestamp (ms since epoch) as a human-readable date/time label. - * Adapts precision based on the tick spacing. + * Format a timestamp (ms since epoch) as a date/time label whose precision + * suits the tick spacing. */ export function formatDateTickValue( val: number, diff --git a/packages/viewer-datagrid/src/css/regular_table.css b/packages/viewer-datagrid/src/css/regular_table.css index 716a8ffb2c..c654928bd1 100644 --- a/packages/viewer-datagrid/src/css/regular_table.css +++ b/packages/viewer-datagrid/src/css/regular_table.css @@ -39,7 +39,6 @@ perspective-viewer, .psp-menu-enabled { padding: 0 6px; font-size: 8px; - border-radius: 3px 3px 0 0; } .psp-menu-enabled:hover, @@ -47,9 +46,22 @@ perspective-viewer, color: var(--psp--background-color); background-color: var(--psp--color); border-bottom-color: var(--psp--color); + box-shadow: 5px 0px 0px var(--psp-box-shadow--color); cursor: pointer; } + tr:not([id]), + tr#psp-column-titles { + th.psp-menu-open { + border-radius: 3px 3px 0 0; + box-shadow: + inset -1px 0px 0px var(--psp--color), + inset 1px 0px 0px var(--psp--color), + inset 0px 1px 0px var(--psp--color), + 10px 5px 0px -5px var(--psp-box-shadow--color); + } + } + tr:not(.rt-autosize) th.psp-menu-open { &:before { background-repeat: no-repeat; @@ -69,8 +81,9 @@ perspective-viewer, td.psp-menu-open { box-shadow: - inset -2px 0px 0px var(--psp--color), - inset 2px 0px 0px var(--psp--color); + inset -1px 0px 0px var(--psp--color), + inset 1px 0px 0px var(--psp--color), + 5px 0px 0px var(--psp-box-shadow--color); } tr:first-child td.psp-menu-open { @@ -79,9 +92,10 @@ perspective-viewer, tr:last-child td.psp-menu-open { box-shadow: - inset -2px 0px 0px var(--psp--color), - inset 2px 0px 0px var(--psp--color), - inset 0px -2px 0px var(--psp--color); + inset -1px 0px 0px var(--psp--color), + inset 1px 0px 0px var(--psp--color), + inset 0px -1px 0px var(--psp--color), + 5px 0px 0px var(--psp-box-shadow--color); } regular-table table tbody td, @@ -484,16 +498,18 @@ regular-table tbody tr:hover { td.psp-select-region.psp-menu-open { &:not(.psp-select-region-inactive) { box-shadow: - inset -2px 0px 0px var(--psp--background-color), - inset 2px 0px 0px var(--psp--background-color); + inset -1px 0px 0px var(--psp--background-color), + inset 1px 0px 0px var(--psp--background-color), + 5px 0px 0px var(--psp-box-shadow--color); } } } :host([settings]) td.psp-select-region.psp-menu-open { box-shadow: - inset -2px 0px 0px var(--psp--background-color), - inset 2px 0px 0px var(--psp--background-color); + inset -1px 0px 0px var(--psp--background-color), + inset 1px 0px 0px var(--psp--background-color), + 5px 0px 0px var(--psp-box-shadow--color); } /* This is a design/architecture bug. When the datagrid draws during a sidepanel */ diff --git a/packages/viewer-datagrid/src/css/row-hover.css b/packages/viewer-datagrid/src/css/row-hover.css index b3a6a9262b..20cb6c9e20 100644 --- a/packages/viewer-datagrid/src/css/row-hover.css +++ b/packages/viewer-datagrid/src/css/row-hover.css @@ -36,10 +36,11 @@ regular-table { &.psp-menu-open { box-shadow: - inset -2px 0px 0px var(--psp--color), - inset 2px 0px 0px var(--psp--color), + inset -1px 0px 0px var(--psp--color), + inset 1px 0px 0px var(--psp--color), 0px 1px 0px - var(--psp-datagrid--hover--border-color, #c5c9d080); + var(--psp-datagrid--hover--border-color, #c5c9d080), + 5px 0px 0px var(--psp-box-shadow--color); } } @@ -48,10 +49,11 @@ regular-table { .psp-select-region-inactive ).psp-menu-open { box-shadow: - inset -2px 0px 0px var(--psp--color), - inset 2px 0px 0px var(--psp--color), - inset 0px -2px 0px var(--psp--color), - 0px 1px 0px var(--psp-datagrid--hover--border-color, #c5c9d080); + inset -1px 0px 0px var(--psp--color), + inset 1px 0px 0px var(--psp--color), + inset 0px -1px 0px var(--psp--color), + 0px 1px 0px var(--psp-datagrid--hover--border-color, #c5c9d080), + 5px 0px 0px var(--psp-box-shadow--color); } tr:hover diff --git a/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts b/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts index 00a43e8f3e..4f752bc6c6 100644 --- a/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts +++ b/packages/viewer-datagrid/src/ts/custom_elements/datagrid.ts @@ -69,7 +69,7 @@ export class HTMLPerspectiveViewerDatagridPluginElement _bold: boolean = false; _italic: boolean = false; _word_wrap: boolean = false; - _column_menus: boolean = true; + _column_menus: boolean = false; _command_column: CommandColumn = "left"; _command_cells: boolean = true; _align?: Align; diff --git a/packages/viewer-datagrid/src/ts/model/create.ts b/packages/viewer-datagrid/src/ts/model/create.ts index f6243f8263..1741b406e0 100644 --- a/packages/viewer-datagrid/src/ts/model/create.ts +++ b/packages/viewer-datagrid/src/ts/model/create.ts @@ -237,7 +237,7 @@ export async function createModel( _edit_mode, _row_height: this?._row_height, _word_wrap: this?._word_wrap ?? false, - _column_menus: this?._column_menus ?? true, + _column_menus: this?._column_menus ?? false, _command_column: this?._command_column ?? "left", _command_cells: this?._command_cells ?? true, _align: this?._align, diff --git a/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts b/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts index 035844a426..e1ed8313d4 100644 --- a/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts +++ b/packages/viewer-datagrid/src/ts/plugin/column_config_schema.ts @@ -11,7 +11,11 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import type { ColumnType } from "@perspective-dev/client"; -import type { ColumnConfigSchema, ControlSpec } from "@perspective-dev/viewer"; +import type { + Align, + ColumnConfigSchema, + ControlSpec, +} from "@perspective-dev/viewer"; import { plugin_utils } from "../plugin_utils.ts"; import { measure_px } from "./plugin_config_schema.ts"; import { positive_px } from "./restore.ts"; @@ -64,7 +68,9 @@ export default function column_config_schema( font_size: positive_px(plugin_config.font_size), bold: plugin_config.bold === true, italic: plugin_config.italic === true, - align: schema.parse_align(plugin_config.align), + align: schema.ALIGNS.includes(plugin_config.align as Align) + ? (plugin_config.align as Align) + : undefined, word_wrap: plugin_config.word_wrap === true, }; @@ -122,7 +128,9 @@ export default function column_config_schema( { kind: "Alignment", key: "align" satisfies keyof ColumnConfig, - ...(grid.align !== undefined ? { default: grid.align } : {}), + default: + grid.align ?? + (type === "integer" || type === "float" ? "right" : "left"), }, { kind: "Bool", diff --git a/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts b/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts index da43ab0e33..07f49ab985 100644 --- a/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts +++ b/packages/viewer-datagrid/src/ts/plugin/plugin_config_schema.ts @@ -139,7 +139,7 @@ export default function plugin_config_schema( fields.push({ kind: "Bool", key: "column_menus" satisfies keyof DatagridPluginConfig, - default: true, + default: false, }); if (is_command_scope(this, "datagrid-row")) { diff --git a/packages/viewer-datagrid/src/ts/plugin/restore.ts b/packages/viewer-datagrid/src/ts/plugin/restore.ts index b0857fda52..c719d887da 100644 --- a/packages/viewer-datagrid/src/ts/plugin/restore.ts +++ b/packages/viewer-datagrid/src/ts/plugin/restore.ts @@ -21,6 +21,7 @@ import { parse_command_column, wrap_lines, } from "./plugin_config_schema.ts"; +import type { Align } from "@perspective-dev/viewer"; import { plugin_utils } from "../plugin_utils.ts"; import type { ColumnsConfig, @@ -119,7 +120,7 @@ function restore_grid_style( this._font_size = positive_px(token.font_size); this._word_wrap = token.word_wrap === true; - this._column_menus = token.column_menus !== false; + this._column_menus = token.column_menus === true; const command_column_before = this._command_column; this._command_column = parse_command_column(token.command_column); if (command_column_before !== this._command_column && this.model) { @@ -131,7 +132,9 @@ function restore_grid_style( this._command_cells = token.command_cells !== false; this._bold = token.bold === true; this._italic = token.italic === true; - this._align = schema.parse_align(token.align); + this._align = schema.ALIGNS.includes(token.align as Align) + ? (token.align as Align) + : undefined; this._row_height = positive_px(token.row_height); this._zebra_rows = Math.max( diff --git a/packages/viewer-datagrid/src/ts/plugin/save.ts b/packages/viewer-datagrid/src/ts/plugin/save.ts index 91dcb92a5b..72dde3711d 100644 --- a/packages/viewer-datagrid/src/ts/plugin/save.ts +++ b/packages/viewer-datagrid/src/ts/plugin/save.ts @@ -19,7 +19,7 @@ export function save( const token: DatagridPluginConfig = { scroll_lock: !!this._is_scroll_lock, edit_mode: this._edit_mode, - column_menus: this._column_menus ? undefined : false, + column_menus: this._column_menus ? true : undefined, command_column: this._command_column === "left" ? undefined diff --git a/packages/viewer-datagrid/src/ts/style_handlers/body.ts b/packages/viewer-datagrid/src/ts/style_handlers/body.ts index 95932b6825..58c828686a 100644 --- a/packages/viewer-datagrid/src/ts/style_handlers/body.ts +++ b/packages/viewer-datagrid/src/ts/style_handlers/body.ts @@ -64,14 +64,7 @@ interface ColState { const HEADER_ALIGNMENT: ColumnAlignment = { text: "left", vertical: "middle" }; -function resolve_alignment( - align: Align | undefined, - is_numeric: boolean, -): ColumnAlignment { - if (align === undefined) { - return { text: is_numeric ? "right" : "left", vertical: "middle" }; - } - +function resolve_alignment(align: Align): ColumnAlignment { return { text: align.endsWith("left") ? "left" @@ -280,7 +273,11 @@ export function applyBodyCellStyles( size_key, isHeader ? HEADER_ALIGNMENT - : resolve_alignment(c.align ?? model._align, c.is_numeric), + : resolve_alignment( + c.align ?? + model._align ?? + (c.is_numeric ? "right" : "left"), + ), ); } diff --git a/packages/viewer-datagrid/src/ts/types.ts b/packages/viewer-datagrid/src/ts/types.ts index 67f942513e..f7e2370420 100644 --- a/packages/viewer-datagrid/src/ts/types.ts +++ b/packages/viewer-datagrid/src/ts/types.ts @@ -266,7 +266,7 @@ export interface DatagridPluginConfig { /** * Whether the header shows the per-column edit-button row while the - * settings panel is open (default `true`). + * settings panel is open (default `false`). */ column_menus?: boolean; diff --git a/packages/viewer-datagrid/test/js/activation.spec.ts b/packages/viewer-datagrid/test/js/activation.spec.ts index 1698a2076d..0bb15b41b0 100644 --- a/packages/viewer-datagrid/test/js/activation.spec.ts +++ b/packages/viewer-datagrid/test/js/activation.spec.ts @@ -32,11 +32,13 @@ test.describe("Panel activation", () => { await v.restore({ plugin: "Datagrid", columns: ["Sales", "Profit"], + plugin_config: { column_menus: true }, }); await v.addPanel({ plugin: "Datagrid", table: tableName, columns: ["State", "Sales"], + plugin_config: { column_menus: true }, }); await v.toggleConfig(true); await v.flush(); diff --git a/packages/viewer-datagrid/test/js/column_config_validation.spec.ts b/packages/viewer-datagrid/test/js/column_config_validation.spec.ts index 662dd3892e..815c213545 100644 --- a/packages/viewer-datagrid/test/js/column_config_validation.spec.ts +++ b/packages/viewer-datagrid/test/js/column_config_validation.spec.ts @@ -45,6 +45,7 @@ async function select_mode( key: "fg_mode" | "bg_mode", value: string, ) { + await view.restore({ plugin_config: { column_menus: true } }); await view.openSettingsPanel(); await view.dataGrid.regularTable.editBtnRow .locator("th.psp-menu-enabled span") diff --git a/packages/viewer-datagrid/test/js/column_list_buttons.spec.ts b/packages/viewer-datagrid/test/js/column_list_buttons.spec.ts new file mode 100644 index 0000000000..6138d3a747 --- /dev/null +++ b/packages/viewer-datagrid/test/js/column_list_buttons.spec.ts @@ -0,0 +1,66 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { expect, test } from "@perspective-dev/test"; +import type { Page } from "@playwright/test"; + +async function setup(page: Page, config: Record) { + await page.goto("/tools/test/src/html/basic-test.html"); + await page.evaluate(async () => { + while (!(window as any)["__TEST_PERSPECTIVE_READY__"]) { + await new Promise((x) => setTimeout(x, 10)); + } + }); + + await page.evaluate(async (config) => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.restore({ plugin: "Datagrid", settings: true, ...config }); + await viewer.flush(); + }, config); +} + +async function saved_columns(page: Page): Promise<(string | null)[]> { + return await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.flush(); + return (await viewer.save()).columns; + }); +} + +test.describe("Active column list buttons", () => { + test("Clear keeps only the first active column", async ({ page }) => { + await setup(page, { columns: ["Row ID", "Sales", "Profit"] }); + await page.locator("perspective-viewer #clear-columns").click(); + await expect.poll(() => saved_columns(page)).toEqual(["Row ID"]); + await expect( + page.locator("perspective-viewer #clear-columns"), + ).toHaveCount(0); + }); + + test("+ All activates every inactive column", async ({ page }) => { + await setup(page, { columns: ["Sales"] }); + const names = await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + const table = await viewer.getTable(); + return Object.keys(await table.schema()); + }); + + await page.locator("perspective-viewer #add-all-columns").click(); + await expect + .poll(async () => (await saved_columns(page)).length) + .toEqual(names.length); + + const columns = await saved_columns(page); + expect(columns[0]).toEqual("Sales"); + expect([...columns].sort()).toEqual([...names].sort()); + }); +}); diff --git a/packages/viewer-datagrid/test/js/column_settings.spec.ts b/packages/viewer-datagrid/test/js/column_settings.spec.ts index ce184ca901..484a952760 100644 --- a/packages/viewer-datagrid/test/js/column_settings.spec.ts +++ b/packages/viewer-datagrid/test/js/column_settings.spec.ts @@ -25,6 +25,10 @@ test.describe("Datagrid Column Styles", function () { await new Promise((x) => setTimeout(x, 10)); } }); + await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.restore({ plugin_config: { column_menus: true } }); + }); }); test("Interacting with column settings does not override column width", async function ({ @@ -220,6 +224,10 @@ runTests("Datagrid Column Styles", () => { await new Promise((x) => setTimeout(x, 10)); } }); + await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.restore({ plugin_config: { column_menus: true } }); + }); }); // These tests only check that a connection is made between the column settings sidebar @@ -338,6 +346,10 @@ runTests("Datagrid Column Styles - Split-by", () => { await new Promise((x) => setTimeout(x, 10)); } }); + await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.restore({ plugin_config: { column_menus: true } }); + }); }); test("Datagrid Column Styles - Only edit buttons get styled", async ({ @@ -351,6 +363,7 @@ runTests("Datagrid Column Styles - Split-by", () => { } }); const viewer = new PspViewer(page); + await viewer.restore({ plugin_config: { column_menus: true } }); const headers = viewer.dataGrid.regularTable.table .locator("thead") .filter({ @@ -388,6 +401,7 @@ runTests("Datagrid Column Styles - Split-by", () => { group_by: [], split_by: [], settings: true, + plugin_config: { column_menus: true }, }); const btn = await table.getEditBtnByName("Sales"); await btn.locator("span:not(.rt-column-resize)").click(); diff --git a/packages/viewer-datagrid/test/js/column_settings_activation.spec.ts b/packages/viewer-datagrid/test/js/column_settings_activation.spec.ts new file mode 100644 index 0000000000..ded1d7a5f0 --- /dev/null +++ b/packages/viewer-datagrid/test/js/column_settings_activation.spec.ts @@ -0,0 +1,139 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { expect, test } from "@perspective-dev/test"; +import type { Page } from "@playwright/test"; + +const TABLE = "load-viewer-csv"; +const DRAWER = "perspective-viewer #column_settings_sidebar"; + +async function setup(page: Page): Promise<[string, string]> { + await page.goto("/tools/test/src/html/basic-test.html"); + await page.evaluate(async () => { + while (!(window as any)["__TEST_PERSPECTIVE_READY__"]) { + await new Promise((x) => setTimeout(x, 10)); + } + }); + + return await page.evaluate(async (table) => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.restore({ + plugin: "Datagrid", + columns: ["State", "Sales"], + settings: true, + }); + + await viewer.addPanel({ + plugin: "Datagrid", + table, + columns: ["State", "Sales"], + }); + + await viewer.flush(); + const [first, second] = await viewer.getPanelNames(); + await viewer.toggleColumnSettings("Sales", { panel: first }); + await viewer.flush(); + return [first, second]; + }, TABLE); +} + +async function indicators(page: Page): Promise> { + return await page.evaluate(() => + Object.fromEntries( + Array.from( + document.querySelectorAll("perspective-viewer-datagrid"), + ).map((plugin) => [ + plugin.getAttribute("slot") ?? "", + (plugin.shadowRoot ?? plugin).querySelectorAll(".psp-menu-open") + .length, + ]), + ), + ); +} + +async function active_panel(page: Page): Promise { + return await page.evaluate(() => + (document.querySelector("perspective-viewer") as any).getActivePanel(), + ); +} + +test.describe("Column settings and panel activation", () => { + test("activating another panel closes the column settings", async ({ + page, + }) => { + const [first, second] = await setup(page); + await expect(page.locator(DRAWER)).toHaveCount(1); + await expect + .poll(async () => (await indicators(page))[first]) + .toBeGreaterThan(0); + + await page.evaluate(async (second) => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.setActivePanel(second); + await viewer.flush(); + }, second); + + expect(await active_panel(page)).toBe(second); + await expect(page.locator(DRAWER)).toHaveCount(0); + await expect + .poll(async () => indicators(page)) + .toEqual({ [first]: 0, [second]: 0 }); + }); + + test("Panel Settings on another panel closes the column settings", async ({ + page, + }) => { + const [first, second] = await setup(page); + await expect + .poll(async () => (await indicators(page))[first]) + .toBeGreaterThan(0); + + await page + .locator( + `perspective-viewer-datagrid[slot="${second}"] regular-table tbody tr`, + ) + .first() + .locator("td") + .nth(1) + .click({ button: "right" }); + + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + await menu + .locator(".context-menu-item", { hasText: "Panel Settings" }) + .click(); + + await expect.poll(async () => active_panel(page)).toBe(second); + await expect(page.locator(DRAWER)).toHaveCount(0); + await expect + .poll(async () => indicators(page)) + .toEqual({ [first]: 0, [second]: 0 }); + }); + + test("closing the active panel closes its column settings", async ({ + page, + }) => { + const [first, second] = await setup(page); + await expect(page.locator(DRAWER)).toHaveCount(1); + await page.evaluate(async (first) => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.removePanel(first); + await viewer.flush(); + }, first); + + expect(await active_panel(page)).toBe(second); + await expect(page.locator(DRAWER)).toHaveCount(0); + await expect + .poll(async () => indicators(page)) + .toEqual({ [second]: 0 }); + }); +}); diff --git a/packages/viewer-datagrid/test/js/column_style.spec.ts b/packages/viewer-datagrid/test/js/column_style.spec.ts index c61247f86c..d2deb572e6 100644 --- a/packages/viewer-datagrid/test/js/column_style.spec.ts +++ b/packages/viewer-datagrid/test/js/column_style.spec.ts @@ -66,6 +66,7 @@ test.describe("Column Style Tests", () => { await page.evaluate(async () => { await document.querySelector("perspective-viewer")!.restore({ plugin: "Datagrid", + plugin_config: { column_menus: true }, }); }); @@ -222,6 +223,7 @@ test.describe("Column Style Tests", () => { await page.evaluate(async () => { await document.querySelector("perspective-viewer")!.restore({ plugin: "Datagrid", + plugin_config: { column_menus: true }, }); }); @@ -300,6 +302,7 @@ test.describe("Column Style Tests", () => { await page.evaluate(async () => { await document.querySelector("perspective-viewer")!.restore({ plugin: "Datagrid", + plugin_config: { column_menus: true }, }); }); @@ -422,6 +425,7 @@ test.describe("Column Style Tests", () => { plugin: "Datagrid", columns: ["Row ID", "Profit"], settings: true, + plugin_config: { column_menus: true }, columns_config: { Profit: { bg_mode: "gradient" }, }, @@ -931,6 +935,7 @@ test.describe("Column Style Tests", () => { plugin: "Datagrid", group_by: ["State"], settings: true, + plugin_config: { column_menus: true }, }); await viewer.flush(); }); diff --git a/packages/viewer-datagrid/test/js/command_buttons.spec.ts b/packages/viewer-datagrid/test/js/command_buttons.spec.ts index 558e10fcdb..93ddb2a041 100644 --- a/packages/viewer-datagrid/test/js/command_buttons.spec.ts +++ b/packages/viewer-datagrid/test/js/command_buttons.spec.ts @@ -212,7 +212,7 @@ test.describe("Datagrid command buttons", () => { page, { columns: ["State", "Sales"], - plugin_config: { command_column: "right" }, + plugin_config: { command_column: "right", column_menus: true }, }, ["datagrid-row"], ); diff --git a/packages/viewer-datagrid/test/js/context_menu_column_settings.spec.ts b/packages/viewer-datagrid/test/js/context_menu_column_settings.spec.ts new file mode 100644 index 0000000000..9409ae6d70 --- /dev/null +++ b/packages/viewer-datagrid/test/js/context_menu_column_settings.spec.ts @@ -0,0 +1,245 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { expect, test } from "@perspective-dev/test"; +import type { Page } from "@playwright/test"; + +const GRID = "perspective-viewer-datagrid regular-table"; +const COLUMN_ITEM = /\w['"] Settings/; + +async function setup(page: Page, config: Record) { + await page.goto("/tools/test/src/html/basic-test.html"); + await page.evaluate(async () => { + while (!(window as any)["__TEST_PERSPECTIVE_READY__"]) { + await new Promise((x) => setTimeout(x, 10)); + } + }); + + await page.evaluate(async (config) => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.restore({ plugin: "Datagrid", ...config }); + await viewer.flush(); + (window as any).__TOGGLES__ = []; + viewer.addEventListener( + "perspective-toggle-column-settings", + (event: CustomEvent) => + (window as any).__TOGGLES__.push(event.detail), + ); + }, config); +} + +test.describe("Datagrid context menu column settings", () => { + test("a cell's context menu opens its column's settings", async ({ + page, + }) => { + await setup(page, { columns: ["State", "Sales"] }); + const cell = page + .locator(`${GRID} tbody tr`) + .first() + .locator("td") + .nth(1); + + await cell.click({ button: "right" }); + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + await menu + .locator(".context-menu-item", { hasText: COLUMN_ITEM }) + .click(); + + await expect + .poll(async () => + page.evaluate(() => (window as any).__TOGGLES__.at(-1)), + ) + .toEqual({ open: true, column_name: "Sales" }); + }); + + test("column settings open the closed settings sidebar in the same frame", async ({ + page, + }) => { + await setup(page, { columns: ["State", "Sales"], settings: false }); + await page.evaluate(() => { + const viewer = document.querySelector("perspective-viewer")!; + const states: string[] = []; + (window as any).__FRAMES__ = states; + const sample = () => { + const state = [ + viewer.hasAttribute("settings"), + viewer.querySelector("#column_settings_sidebar") !== null || + viewer.shadowRoot?.querySelector( + "#column_settings_sidebar", + ) != null, + ].join(","); + + if (states.at(-1) !== state) { + states.push(state); + } + + requestAnimationFrame(sample); + }; + + requestAnimationFrame(sample); + }); + + const cell = page + .locator(`${GRID} tbody tr`) + .first() + .locator("td") + .nth(1); + + await cell.click({ button: "right" }); + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + await menu.locator(".context-menu-item", { hasText: "Sales" }).click(); + + await expect( + page.locator("perspective-viewer #column_settings_sidebar"), + ).toHaveCount(1); + + await expect + .poll(async () => + page.evaluate(async () => { + const viewer = document.querySelector( + "perspective-viewer", + ) as any; + return (await viewer.save()).settings; + }), + ) + .toBe(true); + + expect(await page.evaluate(() => (window as any).__FRAMES__)).toEqual([ + "false,false", + "true,true", + ]); + }); + + test("a divider separates column settings from the panel commands", async ({ + page, + }) => { + await setup(page, { columns: ["State", "Sales"] }); + const cell = page + .locator(`${GRID} tbody tr`) + .first() + .locator("td") + .nth(1); + + await cell.click({ button: "right" }); + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + const rows = await menu + .locator(".context-menu-item, .context-menu-separator") + .evaluateAll((elems) => + elems.map((elem) => + elem.classList.contains("context-menu-separator") + ? null + : (elem.textContent ?? "").trim(), + ), + ); + + const divider = rows.indexOf(null); + expect(rows[divider - 2]).toContain("Sales"); + expect(rows[divider - 1]).toEqual("Panel Settings"); + expect(rows[divider + 1]).toMatch(/^New/); + }); + + test("Panel Settings opens the settings sidebar", async ({ page }) => { + await setup(page, { columns: ["State", "Sales"], settings: false }); + const cell = page + .locator(`${GRID} tbody tr`) + .first() + .locator("td") + .nth(1); + + await cell.click({ button: "right" }); + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + await menu + .locator(".context-menu-item", { hasText: "Panel Settings" }) + .click(); + + await expect + .poll(async () => + page.evaluate(async () => { + const viewer = document.querySelector( + "perspective-viewer", + ) as any; + return (await viewer.save()).settings; + }), + ) + .toBe(true); + }); + + test("settings items hide when the sidebar already shows them", async ({ + page, + }) => { + await setup(page, { columns: ["State", "Sales"], settings: true }); + const cell = page + .locator(`${GRID} tbody tr`) + .first() + .locator("td") + .nth(1); + + await cell.click({ button: "right" }); + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + await expect( + menu.locator(".context-menu-item", { hasText: "Panel Settings" }), + ).toHaveCount(0); + + const column = menu.locator(".context-menu-item", { + hasText: "Sales", + }); + + await expect(column).toHaveCount(1); + await column.click(); + await expect + .poll(async () => + page.evaluate(() => (window as any).__TOGGLES__.at(-1)), + ) + .toEqual({ open: true, column_name: "Sales" }); + + await cell.click({ button: "right" }); + await menu.waitFor(); + await expect( + menu.locator(".context-menu-item", { hasText: "Settings" }), + ).toHaveCount(0); + + await expect( + menu.locator(".context-menu-item, .context-menu-separator").first(), + ).not.toHaveClass(/context-menu-separator/); + }); + + test("a row header's context menu has no column settings", async ({ + page, + }) => { + await setup(page, { columns: ["Sales"], group_by: ["State"] }); + const header = page + .locator(`${GRID} tbody tr`) + .nth(1) + .locator("th:not(.psp-tree-spacer)") + .first(); + + await header.click({ button: "right" }); + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + await expect( + menu.locator(".context-menu-item", { hasText: "Duplicate" }), + ).toBeVisible(); + + await expect( + menu.locator(".context-menu-item", { hasText: COLUMN_ITEM }), + ).toHaveCount(0); + + await expect( + menu.locator(".context-menu-item, .context-menu-separator").first(), + ).not.toHaveClass(/context-menu-separator/); + }); +}); diff --git a/packages/viewer-datagrid/test/js/control_groups.spec.ts b/packages/viewer-datagrid/test/js/control_groups.spec.ts index e9d9132d88..de15e8ef8b 100644 --- a/packages/viewer-datagrid/test/js/control_groups.spec.ts +++ b/packages/viewer-datagrid/test/js/control_groups.spec.ts @@ -23,6 +23,7 @@ test.describe("Datagrid column style control groups", function () { }); async function openNumericStyleTab(page: any, view: PspViewer) { + await view.restore({ plugin_config: { column_menus: true } }); await view.openSettingsPanel(); const editBtn = view.dataGrid.regularTable.editBtnRow .locator("th.psp-menu-enabled span") diff --git a/packages/viewer-datagrid/test/js/header_recycling.spec.ts b/packages/viewer-datagrid/test/js/header_recycling.spec.ts index 40b704d84b..6b8ffe8ecd 100644 --- a/packages/viewer-datagrid/test/js/header_recycling.spec.ts +++ b/packages/viewer-datagrid/test/js/header_recycling.spec.ts @@ -51,6 +51,7 @@ test.describe("header th recycling", () => { group_by: ["Region"], split_by: ["Category"], settings: true, + plugin_config: { column_menus: true }, }); await restore({ settings: true, diff --git a/packages/viewer-datagrid/test/js/plugin_config_options.spec.ts b/packages/viewer-datagrid/test/js/plugin_config_options.spec.ts index 9f12c3b45f..e6b6c11164 100644 --- a/packages/viewer-datagrid/test/js/plugin_config_options.spec.ts +++ b/packages/viewer-datagrid/test/js/plugin_config_options.spec.ts @@ -510,7 +510,7 @@ test.describe("Datagrid plugin_config text and row options", () => { expect(variants.unsupported).toContain("READ_ONLY"); }); - test("column_menus hides the header edit row while settings are open", async ({ + test("column_menus shows the header edit row while settings are open", async ({ page, }) => { await goto_ready(page); @@ -532,23 +532,12 @@ test.describe("Datagrid plugin_config text and row options", () => { }; }); - expect(await header()).toEqual({ - rows: 2, - menus: 2, - ids: ["psp-column-titles", "psp-column-edit-buttons"], - }); - - await restore_plugin_config(page, { column_menus: false }); expect(await header()).toEqual({ rows: 1, menus: 0, ids: [""], }); - expect(await saved_plugin_config(page)).toEqual({ - column_menus: false, - }); - await restore_plugin_config(page, { column_menus: true }); expect(await header()).toEqual({ rows: 2, @@ -556,6 +545,17 @@ test.describe("Datagrid plugin_config text and row options", () => { ids: ["psp-column-titles", "psp-column-edit-buttons"], }); + expect(await saved_plugin_config(page)).toEqual({ + column_menus: true, + }); + + await restore_plugin_config(page, { column_menus: false }); + expect(await header()).toEqual({ + rows: 1, + menus: 0, + ids: [""], + }); + expect(await saved_plugin_config(page)).toEqual({}); }); @@ -1050,7 +1050,7 @@ test.describe("Datagrid plugin_config text and row options", () => { font_family: "inherit", font_size: expect.any(Number), word_wrap: false, - align: undefined, + align: "left", }); expect(pick(defaults.custom)).toEqual({ diff --git a/packages/viewer-datagrid/test/js/restyle.spec.ts b/packages/viewer-datagrid/test/js/restyle.spec.ts index 11d8aaa00c..90ffd4c9da 100644 --- a/packages/viewer-datagrid/test/js/restyle.spec.ts +++ b/packages/viewer-datagrid/test/js/restyle.spec.ts @@ -120,6 +120,7 @@ test.describe("Datagrid restyle()", () => { theme: "Pro Light", settings: true, sort: [["Row ID", "desc"]], + plugin_config: { column_menus: true }, }); }); diff --git a/rust/perspective-viewer/Cargo.toml b/rust/perspective-viewer/Cargo.toml index 97b0eed380..c6be036832 100644 --- a/rust/perspective-viewer/Cargo.toml +++ b/rust/perspective-viewer/Cargo.toml @@ -35,9 +35,6 @@ path = "src/rust/lib.rs" [features] external-bootstrap = [] - -# Look up time zone rules and time zone, currency and unit names in linked -# locale data rather than in the browser, for builds that run outside one. bundled-locale-data = ["dep:jiff"] metadata = [] default = ["llm-agent"] @@ -70,7 +67,6 @@ derivative = "2.2.0" # Easy way to define & implement a singleton trait (type extension) extend = "1.1.2" -# Locale-aware number and date formatting, pinned as parts are pre-stable fixed_decimal = { version = "=0.7.3", features = ["ryu"] } icu_calendar = { version = "=2.4.0" } icu_datetime = { version = "=2.4.0" } diff --git a/rust/perspective-viewer/src/css/column-selector.css b/rust/perspective-viewer/src/css/column-selector.css index 88459169bd..954e249416 100644 --- a/rust/perspective-viewer/src/css/column-selector.css +++ b/rust/perspective-viewer/src/css/column-selector.css @@ -726,4 +726,42 @@ background-color: var(--psp--color); border-color: var(--psp--color); } + + #active-columns #clear-columns, + #sub-columns #add-all-columns { + position: absolute; + right: 0; + z-index: 1; + font-size: var(--label--font-size, 0.75em); + padding: var(--column_type--padding, 0px 0px 0px 0px); + color: var(--psp-inactive--color); + cursor: pointer; + user-select: none; + } + + #active-columns #clear-columns { + margin-top: -43px; + margin-right: 30px; + } + + #sub-columns #add-all-columns { + top: -30px; + right: 30px; + height: 28px; + display: inline-flex; + align-items: flex-end; + } + + #active-columns #clear-columns:hover, + #sub-columns #add-all-columns:hover { + color: var(--psp--color, inherit); + } + + #active-columns #clear-columns:before { + content: var(--psp-label--clear-columns--content, var(--psp-missing)); + } + + #sub-columns #add-all-columns:before { + content: var(--psp-label--add-all-columns--content, var(--psp-missing)); + } } diff --git a/rust/perspective-viewer/src/rust/components/column_selector.rs b/rust/perspective-viewer/src/rust/components/column_selector.rs index 02af45bae1..a4b8120894 100644 --- a/rust/perspective-viewer/src/rust/components/column_selector.rs +++ b/rust/perspective-viewer/src/rust/components/column_selector.rs @@ -133,6 +133,12 @@ pub enum ColumnSelectorMsg { Redraw, HoverActiveIndex(Option), Drop((String, DragTarget, DragEffect, usize)), + + /// Deactivate every active column but the plugin's required ones. + ClearColumns, + + /// Activate every inactive column. + AddAllColumns, } use ColumnSelectorMsg::*; @@ -146,6 +152,66 @@ pub struct ColumnSelector { on_reset: Rc>, } +/// The number of leading active columns "Clear" keeps: the plugin's required +/// columns, or one when it declares none. +fn kept_columns(plugin_static_config: &PluginStaticConfig) -> usize { + plugin_static_config.min_config_columns.unwrap_or(0).max(1) +} + +/// `columns` with `added` filling any empty required slot, then the tail from +/// the last named slot on, past any optional named slots left empty. +fn with_all_columns( + columns: &[Option], + plugin_static_config: &PluginStaticConfig, + added: Vec, +) -> Vec> { + let positional = plugin_static_config.positional_columns(); + let required = plugin_static_config + .min_config_columns + .unwrap_or(0) + .min(positional); + + let mut added = added.into_iter(); + let mut head: Vec> = columns.iter().take(positional).cloned().collect(); + head.resize(positional, None); + for slot in head.iter_mut().take(required) { + if slot.is_none() { + *slot = added.next(); + } + } + + head.extend( + columns + .iter() + .skip(positional) + .filter(|x| x.is_some()) + .cloned(), + ); + head.extend(added.map(Some)); + head +} + +/// Commit `columns` as the active columns, closing the column settings of a +/// column it removes. +fn apply_columns(props: &ColumnSelectorProps, columns: Vec>) { + let update = ViewConfigUpdate { + columns: Some(columns), + ..ViewConfigUpdate::default() + }; + + close_column_settings_if_displaced( + &props.presentation, + &props.renderer, + &props.metadata, + &props.view_config, + &update, + ); + + if let Ok(task) = apply_and_render(&props.session, &props.renderer, update) { + spawn_owned("column-selector", task); + } +} + fn close_column_settings_if_displaced( presentation: &Presentation, renderer: &Renderer, @@ -310,6 +376,44 @@ impl Component for ColumnSelector { }, Drop((_, _, DragEffect::Move(DragTarget::Active), _)) => true, Drop((..)) => true, + ClearColumns => { + let columns = &ctx.props().view_config.columns; + let keep = kept_columns(&ctx.props().plugin_static_config); + if columns.len() > keep { + apply_columns(ctx.props(), columns[..keep].to_vec()); + } + + false + }, + AddAllColumns => { + let props = ctx.props(); + let iter = ColumnsIteratorSet::new( + &props.view_config, + &props.metadata, + &props.renderer, + &props.presentation, + ); + + let added: Vec = iter + .expression() + .chain(iter.window()) + .chain(iter.inactive()) + .map(|x| x.name.to_owned()) + .collect(); + + if !added.is_empty() { + apply_columns( + props, + with_all_columns( + &props.view_config.columns, + &props.plugin_static_config, + added, + ), + ); + } + + false + }, } } @@ -341,6 +445,7 @@ impl Component for ColumnSelector { }; let is_last_column = config.columns.len() == 1; + let can_clear = config.columns.len() > kept_columns(&ctx.props().plugin_static_config); let is_aggregated = config.is_aggregated(); let columns_iter = ColumnsIteratorSet::new(&config, metadata, renderer, presentation); let onselect = ctx.link().callback(|()| Redraw); @@ -486,11 +591,15 @@ impl Component for ColumnSelector { .is_some_and(|entry| !entry.is_empty()); let on_open_expr_panel = &ctx.props().on_open_expr_panel; + let on_clear = + (idx == 0 && can_clear).then(|| ctx.link().callback(|()| ClearColumns)); + html_nested! { + + + }); } let mut selected_columns = vec![html! { diff --git a/rust/perspective-viewer/src/rust/components/column_selector/active_column.rs b/rust/perspective-viewer/src/rust/components/column_selector/active_column.rs index b7c1c4d152..d71f7bae1a 100644 --- a/rust/perspective-viewer/src/rust/components/column_selector/active_column.rs +++ b/rust/perspective-viewer/src/rust/components/column_selector/active_column.rs @@ -87,6 +87,11 @@ pub struct ActiveColumnProps { #[prop_or_default] pub col_type: Option, + /// Fires when this column's "Clear" button, beside its slot label, is + /// clicked; only the first active column has one. + #[prop_or_default] + pub on_clear: Option>, + /// Session metadata snapshot — threaded from `SessionProps`. pub metadata: SessionMetadataRc, @@ -109,6 +114,7 @@ impl PartialEq for ActiveColumnProps { && self.is_window == rhs.is_window && self.is_modified == rhs.is_modified && self.show_edit_btn == rhs.show_edit_btn + && self.on_clear.is_some() == rhs.on_clear.is_some() && self.col_type == rhs.col_type && self.metadata == rhs.metadata && self.view_config == rhs.view_config @@ -256,6 +262,16 @@ impl Component for ActiveColumn { } => (label.clone(), ColumnState::Invalid), }; + let clear = ctx + .props() + .on_clear + .as_ref() + .filter(|_| name.0.is_some()) + .map(|on_clear| { + let onmousedown = left_click(on_clear.reform(|_| ())); + html! { } + }); + let ondragenter = ctx.props().ondragenter.reform(move |event: DragEvent| { // Safari does not set `relatedTarget` so this event must be allowed // to bubble so we can count entry/exit stacks to @@ -303,6 +319,7 @@ impl Component for ActiveColumn { data-index={ctx.props().idx.to_string()} ondragenter={ondragenter.clone()} > + { clear }
} @@ -317,6 +334,7 @@ impl Component for ActiveColumn { data-index={ctx.props().idx.to_string()} ondragenter={ondragenter.clone()} > + { clear } } @@ -382,6 +400,7 @@ impl Component for ActiveColumn { {onmouseout} ondragenter={ondragenter.clone()} > + { clear } , - /// Bubble-phase `pointerdown` listener on the viewer host that activates - /// the panel whose frame is on the event's composed path. + /// Bubble-phase primary-button `pointerdown` listener on the viewer host + /// that activates the panel whose frame is on the event's composed path. _pointerdown_listener: Closure, /// The `` ELEMENT the layout listeners are attached to. @@ -215,10 +215,6 @@ pub struct MainPanel { /// layout and not yet committed. pending_removals: HashSet, - /// Ids observed in a committed layout tree, the only model-held panels a - /// later commit can report closed. - on_screen: HashSet, - /// The in-flight panel drag, from its first `BeforeResize` until it is /// dropped on `LayoutUpdated` (the drop). drag: Option, @@ -364,7 +360,8 @@ impl Component for MainPanel { let pointerdown_cb = ctx.link().callback(MainPanelMsg::PanelPointerDown); let viewer_elem = ctx.props().presentation.viewer_elem().clone(); let pointerdown_listener = Closure::wrap(Box::new(move |event: web_sys::Event| { - if let Some(frame) = panel_frame_on_path(&event, viewer_elem.unchecked_ref()) + if event.unchecked_ref::().button() == 0 + && let Some(frame) = panel_frame_on_path(&event, viewer_elem.unchecked_ref()) && !frame.class_list().contains("closing") && let Some(name) = frame.get_attribute("name") { @@ -395,7 +392,6 @@ impl Component for MainPanel { layout_ref: NodeRef::default(), inserted: Vec::new(), pending_removals: HashSet::new(), - on_screen: HashSet::new(), _layout_update_listener: listener, _layout_select_listener: select_listener, _layout_before_resize_listener: before_resize_listener, diff --git a/rust/perspective-viewer/src/rust/components/main_panel/reconcile.rs b/rust/perspective-viewer/src/rust/components/main_panel/reconcile.rs index 71f49e12b7..27b295f92b 100644 --- a/rust/perspective-viewer/src/rust/components/main_panel/reconcile.rs +++ b/rust/perspective-viewer/src/rust/components/main_panel/reconcile.rs @@ -134,7 +134,6 @@ impl MainPanel { if self.listener_target.as_ref() != Some(&el) { if self.listener_target.is_some() { self.inserted.clear(); - self.on_screen.clear(); } let _ = el.add_event_listener_with_callback( diff --git a/rust/perspective-viewer/src/rust/components/main_panel/render.rs b/rust/perspective-viewer/src/rust/components/main_panel/render.rs index b7feba25da..60cb3fc6ac 100644 --- a/rust/perspective-viewer/src/rust/components/main_panel/render.rs +++ b/rust/perspective-viewer/src/rust/components/main_panel/render.rs @@ -369,6 +369,8 @@ impl MainPanel { presentation={ctx.props().presentation.clone()} {theme} {maximized} + is_settings_open={ctx.props().is_settings_open} + open_column={ctx.props().presentation_props.open_column_settings.name()} commands={self.context_menu_commands.clone()} on_custom={ctx.link().callback(MainPanelMsg::CustomCommand)} on_command={ctx.link().callback(MainPanelMsg::Command)} diff --git a/rust/perspective-viewer/src/rust/components/main_panel/update.rs b/rust/perspective-viewer/src/rust/components/main_panel/update.rs index 2df7624c02..b375413b7e 100644 --- a/rust/perspective-viewer/src/rust/components/main_panel/update.rs +++ b/rust/perspective-viewer/src/rust/components/main_panel/update.rs @@ -49,9 +49,9 @@ impl MainPanel { false } - /// Report closed every panel this commit dropped from the layout, judged - /// against the live `Workspace` panel set (see `reconcile`), and re-render - /// so its frame leaves the DOM in the commit's paint. + /// Report closed every panel gone from the `Workspace` whose cell this + /// commit removed, and re-render so its frame leaves the DOM in the + /// commit's paint. pub(super) fn on_layout_updated(&mut self, ctx: &Context) -> bool { let Some(el) = self.layout_ref.cast::() else { return false; @@ -61,17 +61,13 @@ impl MainPanel { let layout: RegularLayout = el.unchecked_into(); let panel_ids = ctx.props().workspace.panel_ids(); let mut closed = Vec::new(); - let on_screen = &mut self.on_screen; self.inserted.retain(|id| { - if layout.contains_panel(id) { - on_screen.insert(id.clone()); - true - } else if on_screen.remove(id) || !panel_ids.iter().any(|p| p.as_str() == id) { + let kept = layout.contains_panel(id) || panel_ids.iter().any(|p| p.as_str() == id); + if !kept { closed.push(id.clone()); - false - } else { - true } + + kept }); let closed_any = !closed.is_empty(); @@ -166,20 +162,16 @@ impl MainPanel { }) }); - // Make the right-clicked panel active so active-targeting - // commands (e.g. Reset) act on it; then show the menu. - if let Some(id) = &id { - ctx.props().on_activate_panel.emit(id.clone()); - } - let panel = id .as_deref() .and_then(|id| ctx.props().workspace.panel(&PanelId::from(id))); - if !ctx - .props() - .presentation - .is_command_scope(CommandLocation::ContextMenu) + let is_body = origin == MenuOrigin::Body; + if !is_body + && !ctx + .props() + .presentation + .is_command_scope(CommandLocation::ContextMenu) { self.pending_menu = None; self.context_menu_commands = PtrEqRc::default(); @@ -197,7 +189,7 @@ impl MainPanel { panel.as_ref(), CommandLocation::ContextMenu, (x, y), - origin == MenuOrigin::Body, + is_body, ) .await; diff --git a/rust/perspective-viewer/src/rust/components/panel_menu.rs b/rust/perspective-viewer/src/rust/components/panel_menu.rs index b7324b9a0f..853c1da8ef 100644 --- a/rust/perspective-viewer/src/rust/components/panel_menu.rs +++ b/rust/perspective-viewer/src/rust/components/panel_menu.rs @@ -68,6 +68,12 @@ pub enum PanelCommand { Restore, ToggleMaster, Close, + + /// Open the settings of the named column of the panel. + ColumnSettings(String), + + /// Open the settings sidebar on the panel. + PanelSettings, } /// Which format-picker dropdown the context menu spawned in place of itself. @@ -105,6 +111,14 @@ pub struct PanelMenuProps { /// Maximize/Restore item). pub maximized: bool, + /// Whether the settings sidebar is open on the active panel. + #[prop_or_default] + pub is_settings_open: bool, + + /// The column whose settings are open on the active panel, if any. + #[prop_or_default] + pub open_column: Option, + /// The custom commands rendered above the built-in items. #[prop_or_default] pub commands: PtrEqRc, @@ -129,6 +143,8 @@ impl PartialEq for PanelMenuProps { && self.panel_id == rhs.panel_id && self.theme == rhs.theme && self.maximized == rhs.maximized + && self.is_settings_open == rhs.is_settings_open + && self.open_column == rhs.open_column && self.commands == rhs.commands } } @@ -296,42 +312,70 @@ impl PanelMenu { is_pivoted && can_derive(&x.session) }); - vec![ - ContextMenuEntry::Submenu { - label: "New".to_owned(), - on_select: Some(cmd(PanelCommand::New)), - entries: vec![ContextMenuEntry::Custom(self.new_submenu_body(ctx))], - }, - item("Duplicate", cmd(PanelCommand::Duplicate), false), - item("Derive Table", cmd(PanelCommand::Derive), !can_derive_view), - item("Reset", cmd(PanelCommand::Reset), false), - item( - "Export", - ctx.link() - .callback(|_| PanelMenuMsg::OpenPicker(PickerKind::Export)), - false, - ), - item( - "Copy", - ctx.link() - .callback(|_| PanelMenuMsg::OpenPicker(PickerKind::Copy)), - false, - ), - if ctx.props().maximized { - item("Restore", cmd(PanelCommand::Restore), false) - } else { - item("Maximize", cmd(PanelCommand::Maximize), false) - }, - // Never gated: masters broadcast from ANY select/click - // event (flat grids fall back to the clicked cell's `==` - // clause), not just a grouped row tree. - item( - if is_master { "Detail" } else { "Master" }, - cmd(PanelCommand::ToggleMaster), - false, - ), - item("Close", cmd(PanelCommand::Close), !can_close), - ] + let is_active = ctx.props().workspace.active_id() == Some(PanelId::from(panel_id)); + let column_settings = ctx + .props() + .commands + .column + .clone() + .filter(|column| !is_active || ctx.props().open_column.as_ref() != Some(column)) + .map(|column| { + item( + format!("\"{column}\' Settings").as_str(), + cmd(PanelCommand::ColumnSettings(column)), + false, + ) + }); + + let panel_settings = (!is_active || !ctx.props().is_settings_open) + .then(|| item("Panel Settings", cmd(PanelCommand::PanelSettings), false)); + + let mut entries: Vec = + column_settings.into_iter().chain(panel_settings).collect(); + + if !entries.is_empty() { + entries.push(ContextMenuEntry::Separator); + } + + entries + .into_iter() + .chain([ + ContextMenuEntry::Submenu { + label: "New".to_owned(), + on_select: Some(cmd(PanelCommand::New)), + entries: vec![ContextMenuEntry::Custom(self.new_submenu_body(ctx))], + }, + item("Duplicate", cmd(PanelCommand::Duplicate), false), + item("Derive Table", cmd(PanelCommand::Derive), !can_derive_view), + item("Reset", cmd(PanelCommand::Reset), false), + item( + "Export", + ctx.link() + .callback(|_| PanelMenuMsg::OpenPicker(PickerKind::Export)), + false, + ), + item( + "Copy", + ctx.link() + .callback(|_| PanelMenuMsg::OpenPicker(PickerKind::Copy)), + false, + ), + if ctx.props().maximized { + item("Restore", cmd(PanelCommand::Restore), false) + } else { + item("Maximize", cmd(PanelCommand::Maximize), false) + }, + // Never gated: masters broadcast from ANY select/click + // event (flat grids fall back to the clicked cell's + // `==` clause), not just a grouped row tree. + item( + if is_master { "Detail" } else { "Master" }, + cmd(PanelCommand::ToggleMaster), + false, + ), + item("Close", cmd(PanelCommand::Close), !can_close), + ]) + .collect() }, }; diff --git a/rust/perspective-viewer/src/rust/components/viewer.rs b/rust/perspective-viewer/src/rust/components/viewer.rs index d8ba86a539..c1f91a9426 100644 --- a/rust/perspective-viewer/src/rust/components/viewer.rs +++ b/rust/perspective-viewer/src/rust/components/viewer.rs @@ -349,8 +349,8 @@ impl Component for PerspectiveViewer { ToggleSettingsInit(update, announce, resolve) => { self.on_toggle_settings_init(ctx, update, announce, resolve) }, - ToggleSettingsComplete(update, resolve) => { - self.on_toggle_settings_complete(ctx, update, resolve) + ToggleSettingsComplete(update, column, resolve) => { + self.on_toggle_settings_complete(ctx, update, column, resolve) }, DividerMove(divider, target) => self.on_divider_move(ctx, divider, target), DividerPump(divider) => self.on_divider_pump(ctx, divider), @@ -363,6 +363,7 @@ impl Component for PerspectiveViewer { sender, toggle, } => self.on_open_column_settings(ctx, target, sender, toggle), + OpenSettingsWithColumn(target) => self.on_open_settings_with_column(ctx, target), ColumnSettingsPanelAutoWidth(w) => self.on_column_settings_panel_auto_width(ctx, w), ToggleColumnSettingsPin => self.on_toggle_column_settings_pin(ctx), ToggleColumnSettingsPinComplete(resolve) => { diff --git a/rust/perspective-viewer/src/rust/components/viewer/msg.rs b/rust/perspective-viewer/src/rust/components/viewer/msg.rs index c0f973b7d1..46cf47ca0a 100644 --- a/rust/perspective-viewer/src/rust/components/viewer/msg.rs +++ b/rust/perspective-viewer/src/rust/components/viewer/msg.rs @@ -83,6 +83,10 @@ pub enum PerspectiveViewerMsg { sender: Option>, toggle: bool, }, + + /// Open the column settings of `target`, opening the settings pane in the + /// same commit when it is closed. + OpenSettingsWithColumn(ColumnSettingsTarget), PreloadFontsUpdate, /// Element-level reset (the public `reset()` API): reset EVERY panel and @@ -181,7 +185,7 @@ pub enum PerspectiveViewerMsg { /// host box is unchanged, so nothing else resizes the plugins), which /// leaves canvas plugins CSS-stretched at their old backing size. API /// entry points send [`Self::ToggleSettingsInit`]. - ToggleSettingsComplete(SettingsUpdate, Sender<()>), + ToggleSettingsComplete(SettingsUpdate, Option, Sender<()>), /// Toggle (or force) the settings pane with the FULL choreography: /// presize every visible plugin to its post-toggle box, commit the diff --git a/rust/perspective-viewer/src/rust/components/viewer/panels.rs b/rust/perspective-viewer/src/rust/components/viewer/panels.rs index d6a11234d9..fbbf1bcebd 100644 --- a/rust/perspective-viewer/src/rust/components/viewer/panels.rs +++ b/rust/perspective-viewer/src/rust/components/viewer/panels.rs @@ -76,6 +76,10 @@ impl PerspectiveViewer { ) -> bool { let id = PanelId::from(id); let prev = ctx.props().workspace.active_id(); + if prev.as_ref() != Some(&id) && ctx.props().workspace.panel(&id).is_some() { + ctx.props().presentation.set_open_column_settings(None); + } + if prev.as_ref() == Some(&id) || !ctx.props().workspace.set_active(id.clone()) { let resynced = self.resync_active(ctx); if let Some(completion) = completion { @@ -142,6 +146,10 @@ impl PerspectiveViewer { /// its engines still alive, or `None` for an unknown id. fn detach_panel(&mut self, ctx: &Context, id: &PanelId) -> Option { let was_active = ctx.props().workspace.active_id().as_ref() == Some(id); + if was_active { + ctx.props().presentation.set_open_column_settings(None); + } + let removed = ctx.props().workspace.remove_panel(id)?; if was_active { if let Some(next) = ctx.props().workspace.panel_ids().first().cloned() { diff --git a/rust/perspective-viewer/src/rust/components/viewer/render.rs b/rust/perspective-viewer/src/rust/components/viewer/render.rs index 6230118abf..d9e2ea7f8a 100644 --- a/rust/perspective-viewer/src/rust/components/viewer/render.rs +++ b/rust/perspective-viewer/src/rust/components/viewer/render.rs @@ -28,6 +28,8 @@ use crate::components::main_panel::MainPanel; use crate::components::panel_menu::PanelCommand; use crate::components::settings_panel::SettingsPanel; use crate::components::style::StyleSurface; +use crate::config::SettingsUpdate; +use crate::presentation::ColumnSettingsTarget; use crate::queries::*; use crate::session::TableLoadState; use crate::ui::{FontLoader, SplitPanel, StyleProvider}; @@ -186,6 +188,14 @@ impl PerspectiveViewer { PanelCommand::Reset => vec![ResetPanel(Some(id), false, None)], PanelCommand::ToggleMaster => vec![ToggleMaster(id)], PanelCommand::Close => vec![ClosePanel(id, None)], + PanelCommand::ColumnSettings(column) => vec![ + SetActivePanel(id, None), + OpenSettingsWithColumn(ColumnSettingsTarget::Column(column)), + ], + PanelCommand::PanelSettings => vec![ + SetActivePanel(id, None), + ToggleSettingsInit(Some(SettingsUpdate::Update(true)), true, None), + ], PanelCommand::Maximize | PanelCommand::Restore => vec![], } })} diff --git a/rust/perspective-viewer/src/rust/components/viewer/settings.rs b/rust/perspective-viewer/src/rust/components/viewer/settings.rs index 13727638b3..9d2b58d683 100644 --- a/rust/perspective-viewer/src/rust/components/viewer/settings.rs +++ b/rust/perspective-viewer/src/rust/components/viewer/settings.rs @@ -117,15 +117,15 @@ impl PerspectiveViewer { false }, (Some(SettingsUpdate::SetDefault), resolve) => { - self.init_toggle_settings_task(ctx, Some(false), announce, resolve); + self.init_toggle_settings_task(ctx, Some(false), announce, resolve, None); false }, (Some(SettingsUpdate::Update(force)), resolve) => { - self.init_toggle_settings_task(ctx, Some(force), announce, resolve); + self.init_toggle_settings_task(ctx, Some(force), announce, resolve, None); false }, (None, resolve) => { - self.init_toggle_settings_task(ctx, None, announce, resolve); + self.init_toggle_settings_task(ctx, None, announce, resolve, None); false }, } @@ -135,6 +135,7 @@ impl PerspectiveViewer { &mut self, ctx: &Context, update: SettingsUpdate, + column: Option, resolve: Sender<()>, ) -> bool { match update { @@ -145,7 +146,21 @@ impl PerspectiveViewer { true }, SettingsUpdate::Update(force) if force != self.settings_open => { - ctx.props().presentation.set_open_column_settings(None); + let ocs = column + .filter(|_| force) + .map(|target| self.column_settings_for(Some(target))); + + if ocs.is_some() { + self.settings_geometry.selected_tab = SelectedTab::Query; + } + + ctx.props() + .presentation + .set_open_column_settings(ocs.clone()); + if let Some(ocs) = ocs { + self.presentation_props.open_column_settings = ocs; + } + self.settings_open = force; self.on_rendered.push(resolve); true @@ -184,6 +199,7 @@ impl PerspectiveViewer { force: Option, announce: bool, sender: Option>>, + column: Option, ) { let is_open = ctx.props().presentation.is_settings_open(); match force { @@ -197,7 +213,7 @@ impl PerspectiveViewer { let force = !is_open; let callback = ctx.link().callback(move |resolve| { let update = SettingsUpdate::Update(force); - ToggleSettingsComplete(update, resolve) + ToggleSettingsComplete(update, column.clone(), resolve) }); if is_open { @@ -407,6 +423,36 @@ impl PerspectiveViewer { } } + /// The open column settings of `target`, on the tab its column opens to. + fn column_settings_for(&self, target: Option) -> OpenColumnSettings { + let tab = match &target { + Some(ColumnSettingsTarget::NewExpression) => Some(ColumnSettingsTab::Attributes), + Some(ColumnSettingsTarget::Column(name)) => { + Some(if self.session_props.is_column_active(name) { + ColumnSettingsTab::Style + } else { + ColumnSettingsTab::Attributes + }) + }, + None => None, + }; + + OpenColumnSettings { target, tab } + } + + pub(super) fn on_open_settings_with_column( + &mut self, + ctx: &Context, + target: ColumnSettingsTarget, + ) -> bool { + if self.settings_open { + self.on_open_column_settings(ctx, Some(target), None, false) + } else { + self.init_toggle_settings_task(ctx, Some(true), true, None, Some(target)); + false + } + } + pub(super) fn on_open_column_settings( &mut self, ctx: &Context, @@ -414,25 +460,13 @@ impl PerspectiveViewer { sender: Option>, toggle: bool, ) -> bool { - let mut open_column_settings = ctx.props().presentation.get_open_column_settings(); + let open_column_settings = ctx.props().presentation.get_open_column_settings(); if target == open_column_settings.target { if toggle { ctx.props().presentation.set_open_column_settings(None); } } else { - open_column_settings.target.clone_from(&target); - open_column_settings.tab = match &target { - Some(ColumnSettingsTarget::NewExpression) => Some(ColumnSettingsTab::Attributes), - Some(ColumnSettingsTarget::Column(name)) => { - Some(if self.session_props.is_column_active(name) { - ColumnSettingsTab::Style - } else { - ColumnSettingsTab::Attributes - }) - }, - None => None, - }; - + let open_column_settings = self.column_settings_for(target.clone()); ctx.props() .presentation .set_open_column_settings(Some(open_column_settings)); diff --git a/rust/perspective-viewer/src/rust/custom_elements/viewer.rs b/rust/perspective-viewer/src/rust/custom_elements/viewer.rs index 7b318372aa..e4048a20e8 100644 --- a/rust/perspective-viewer/src/rust/custom_elements/viewer.rs +++ b/rust/perspective-viewer/src/rust/custom_elements/viewer.rs @@ -335,10 +335,13 @@ impl PerspectiveViewerElement { .flatten() .map(|id| id.as_str().to_owned()); - let layout = this - .layout_element() - .map(|l| l.save().into_serde_ext::()) - .transpose()?; + let layout = match this.workspace.pending_layout() { + Some(layout) => Some(layout), + None => this + .layout_element() + .map(|l| l.save().into_serde_ext::()) + .transpose()?, + }; Ok(JsValue::from_serde_ext(&WorkspaceConfig { version: API_VERSION.to_string(), diff --git a/rust/perspective-viewer/src/rust/queries/resolve_commands.rs b/rust/perspective-viewer/src/rust/queries/resolve_commands.rs index 1cb17b2c06..bd1c6e4b42 100644 --- a/rust/perspective-viewer/src/rust/queries/resolve_commands.rs +++ b/rust/perspective-viewer/src/rust/queries/resolve_commands.rs @@ -37,6 +37,9 @@ impl CommandLocation { pub struct ResolvedCommands { pub context: JsValue, pub commands: Vec, + + /// The one column the gesture's hit targets, if it targets exactly one. + pub column: Option, } /// The panel whose active plugin element is `plugin`. @@ -74,11 +77,15 @@ pub async fn resolve_commands( _ => None, }; + let column = hit.as_ref().and_then(hit_column); let context = match command_context(panel, location, Some(point), hit) { Ok(context) => context, Err(err) => { tracing::error!("Failed to build command context: {err}"); - return ResolvedCommands::default(); + return ResolvedCommands { + column, + ..ResolvedCommands::default() + }; }, }; @@ -95,7 +102,24 @@ pub async fn resolve_commands( ) .unwrap_or_default(); - ResolvedCommands { context, commands } + ResolvedCommands { + context, + commands, + column, + } +} + +/// The one column a resolved `hit` targets, if it targets exactly one. +fn hit_column(hit: &JsValue) -> Option { + let names: Array = Reflect::get(hit, &"column_names".into()) + .ok()? + .dyn_into() + .ok()?; + if names.length() == 1 { + names.get(0).as_string() + } else { + None + } } /// Evaluate the app's schema at `location` for every ref in `refs` against diff --git a/rust/perspective-viewer/src/rust/workspace.rs b/rust/perspective-viewer/src/rust/workspace.rs index e4f7dbef1e..414b57563b 100644 --- a/rust/perspective-viewer/src/rust/workspace.rs +++ b/rust/perspective-viewer/src/rust/workspace.rs @@ -450,6 +450,11 @@ impl Workspace { self.0.borrow_mut().pending_layout = Some(layout); } + /// The staged layout tree, if any, without consuming it. + pub fn pending_layout(&self) -> Option { + self.0.borrow().pending_layout.clone() + } + /// Take (consume) the staged layout tree, if any. pub fn take_pending_layout(&self) -> Option { self.0.borrow_mut().pending_layout.take() diff --git a/rust/perspective-viewer/src/themes/intl.css b/rust/perspective-viewer/src/themes/intl.css index 1a05713701..3b0c82a4e0 100644 --- a/rust/perspective-viewer/src/themes/intl.css +++ b/rust/perspective-viewer/src/themes/intl.css @@ -189,6 +189,7 @@ perspective-viewer { --psp-label--value-fit--content: "Value size"; --psp-label--breakdown--content: "Breakdown"; --psp-label--chart-type--content: "Glyph type"; + --psp-label--new-panel-button--content: "New"; /* Plugin settings — viewer-charts */ --psp-label--auto-alt-y-axis--content: "Auto Y axis"; diff --git a/rust/perspective-viewer/src/themes/intl/ar.css b/rust/perspective-viewer/src/themes/intl/ar.css index 060f8c4f77..3b50663e38 100644 --- a/rust/perspective-viewer/src/themes/intl/ar.css +++ b/rust/perspective-viewer/src/themes/intl/ar.css @@ -179,6 +179,7 @@ perspective-viewer { --psp-label--value-fit--content: "حجم القيمة"; --psp-label--breakdown--content: "تفصيل"; --psp-label--chart-type--content: "نوع الشكل"; + --psp-label--new-panel-button--content: "جديد"; --psp-label--auto-alt-y-axis--content: "محور Y تلقائي"; --psp-label--facet-mode--content: "وضع التقسيم"; diff --git a/rust/perspective-viewer/src/themes/intl/de.css b/rust/perspective-viewer/src/themes/intl/de.css index cd78b73f47..41d0fd8612 100644 --- a/rust/perspective-viewer/src/themes/intl/de.css +++ b/rust/perspective-viewer/src/themes/intl/de.css @@ -176,6 +176,7 @@ perspective-viewer { --psp-label--value-fit--content: "Wertgröße"; --psp-label--breakdown--content: "Aufschlüsselung"; --psp-label--chart-type--content: "Glyphentyp"; + --psp-label--new-panel-button--content: "Neu"; /* Plugin settings — viewer-charts */ --psp-label--auto-alt-y-axis--content: "Automatische duale Y-Achse"; diff --git a/rust/perspective-viewer/src/themes/intl/es.css b/rust/perspective-viewer/src/themes/intl/es.css index a1d778baae..ae4a147731 100644 --- a/rust/perspective-viewer/src/themes/intl/es.css +++ b/rust/perspective-viewer/src/themes/intl/es.css @@ -176,6 +176,7 @@ perspective-viewer { --psp-label--value-fit--content: "Tamaño del valor"; --psp-label--breakdown--content: "Desglose"; --psp-label--chart-type--content: "Tipo de glifo"; + --psp-label--new-panel-button--content: "Nuevo"; /* Plugin settings — viewer-charts */ --psp-label--auto-alt-y-axis--content: "Eje Y dual automático"; diff --git a/rust/perspective-viewer/src/themes/intl/fr.css b/rust/perspective-viewer/src/themes/intl/fr.css index 5341b3c4b0..efcf23bc32 100644 --- a/rust/perspective-viewer/src/themes/intl/fr.css +++ b/rust/perspective-viewer/src/themes/intl/fr.css @@ -176,6 +176,7 @@ perspective-viewer { --psp-label--value-fit--content: "Taille de la valeur"; --psp-label--breakdown--content: "Répartition"; --psp-label--chart-type--content: "Type de glyphe"; + --psp-label--new-panel-button--content: "Nouveau"; /* Plugin settings — viewer-charts */ --psp-label--auto-alt-y-axis--content: "Axe Y double automatique"; diff --git a/rust/perspective-viewer/src/themes/intl/ja.css b/rust/perspective-viewer/src/themes/intl/ja.css index 1785dea567..2e7b995cb9 100644 --- a/rust/perspective-viewer/src/themes/intl/ja.css +++ b/rust/perspective-viewer/src/themes/intl/ja.css @@ -176,6 +176,7 @@ perspective-viewer { --psp-label--value-fit--content: "値のサイズ"; --psp-label--breakdown--content: "内訳"; --psp-label--chart-type--content: "グリフの種類"; + --psp-label--new-panel-button--content: "新規"; /* Plugin settings — viewer-charts */ --psp-label--auto-alt-y-axis--content: "自動デュアルY軸"; diff --git a/rust/perspective-viewer/src/themes/intl/pt.css b/rust/perspective-viewer/src/themes/intl/pt.css index 9881f4a398..c8dce5ecd3 100644 --- a/rust/perspective-viewer/src/themes/intl/pt.css +++ b/rust/perspective-viewer/src/themes/intl/pt.css @@ -176,6 +176,7 @@ perspective-viewer { --psp-label--value-fit--content: "Tamanho do valor"; --psp-label--breakdown--content: "Detalhamento"; --psp-label--chart-type--content: "Tipo de glifo"; + --psp-label--new-panel-button--content: "Novo"; /* Plugin settings — viewer-charts */ --psp-label--auto-alt-y-axis--content: "Eixo Y duplo automático"; diff --git a/rust/perspective-viewer/src/themes/intl/zh.css b/rust/perspective-viewer/src/themes/intl/zh.css index cef450b531..8ae8763849 100644 --- a/rust/perspective-viewer/src/themes/intl/zh.css +++ b/rust/perspective-viewer/src/themes/intl/zh.css @@ -176,6 +176,7 @@ perspective-viewer { --psp-label--value-fit--content: "数值大小"; --psp-label--breakdown--content: "细分"; --psp-label--chart-type--content: "图元类型"; + --psp-label--new-panel-button--content: "新建"; /* Plugin settings — viewer-charts */ --psp-label--auto-alt-y-axis--content: "自动双Y轴"; diff --git a/rust/perspective-viewer/src/ts/plugin_utils/column_style.ts b/rust/perspective-viewer/src/ts/plugin_utils/column_style.ts index 646a3e07e8..4aa404192f 100644 --- a/rust/perspective-viewer/src/ts/plugin_utils/column_style.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/column_style.ts @@ -53,9 +53,8 @@ export type StringMode = (typeof STRING_MODES)[number]; export type DatetimeMode = (typeof DATETIME_MODES)[number]; /** - * Every foreground treatment some column type accepts. The subset a given - * column accepts is `fg_modes_for(type)`; `column_config_schema()` - * advertises exactly that subset, and the viewer rejects any other value. + * Every foreground treatment some column type accepts, of which a column + * accepts `fg_modes_for(type)`. */ export type FgMode = NumberFgMode | StringMode | DatetimeMode; @@ -94,16 +93,6 @@ export function bg_modes_for(type: ColumnType): readonly BgMode[] { } } -/** The `fg_mode` an omitted key stands for: colored text for numbers. */ -export function default_fg_mode(type: ColumnType): FgMode { - return type === "integer" || type === "float" ? "color" : "disabled"; -} - -/** The `bg_mode` an omitted key stands for. */ -export function default_bg_mode(_type: ColumnType): BgMode { - return "disabled"; -} - /** `raw` as an `fg_mode` a column of `type` accepts, else `undefined`. */ export function parse_fg_mode( type: ColumnType, @@ -162,18 +151,14 @@ export interface ResolvedColors { export type Resolved = Omit & ResolvedColors; /** - * A column's {@link ColumnStyleConfig} with its `fg_color` / `bg_color` - * strings parsed once at `restore()`. Column types are not known at restore - * time, so every reader runs and each parsed form is present when its - * grammar matched; the per-type cell style handlers pick the form their - * mode needs. + * A column's {@link ColumnStyleConfig} with its `fg_color` / `bg_color` strings + * parsed once at `restore()`. */ export type ResolvedColumnStyle = Resolved; /** - * Every parsed form of one `fg_color` / `bg_color` string. Column types - * are unknown here (`restore()` may run before the model exists), so each - * reader runs and the style handlers pick the form their mode needs. + * Every form one `fg_color` / `bg_color` string parses as, for each mode's + * style handler to pick from. */ interface ParsedColor { color?: ColorRecord; diff --git a/rust/perspective-viewer/src/ts/plugin_utils/meta_columns.ts b/rust/perspective-viewer/src/ts/plugin_utils/meta_columns.ts index 2ce964cedb..89c4cfa9bf 100644 --- a/rust/perspective-viewer/src/ts/plugin_utils/meta_columns.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/meta_columns.ts @@ -11,34 +11,8 @@ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ /** - * Single-source-of-truth predicate for "this column is metadata, hide - * it from the user-visible grid." Five distinct names show up across - * the perspective protocol; older datagrid code filtered them by - * exact-match in three places, which only worked when the wire shape - * was the JSON-sidecar form (`__ROW_PATH__` array-of-arrays). - * - * The DuckDB virtual-server backend additionally surfaces per-level - * `__ROW_PATH___` columns directly in `to_columns_string` / - * `to_json` output (a side effect of keeping them in the frozen Arrow - * batch so that `to_arrow` consumers — viewer-charts via - * `with_typed_arrays` — see them inline, matching native - * `perspective-server`'s `to_arrow` behavior). Without this helper, - * those per-level columns slip through the legacy exact-match filters - * and render as user columns to the right of the grid. - * - * Match list: - * - `__ROW_PATH__` — JSON sidecar; used by the tree header. - * - `__ROW_PATH___` — per-level columns from the virtual server's - * inline-arrow shape. - * - `__ID__` — per-row identity column. - * - `__GROUPING_ID__` — internal SQL-rollup discriminator. The - * virtual server strips it server-side, but - * we cover it defensively in case a future - * backend leaks it. - * - * User columns named with leading/trailing double-underscores (e.g. - * `__user_col__`) are *not* matched — the regex requires the exact - * stems above. + * The metadata column names, `__ROW_PATH__`, `__ROW_PATH___`, `__ID__` and + * `__GROUPING_ID__`. */ const META_COLUMN_RE = /^__(?:ROW_PATH(?:_\d+)?|ID|GROUPING_ID)__$/; diff --git a/rust/perspective-viewer/src/ts/plugin_utils/schema.ts b/rust/perspective-viewer/src/ts/plugin_utils/schema.ts index aabaab9f11..66bed60162 100644 --- a/rust/perspective-viewer/src/ts/plugin_utils/schema.ts +++ b/rust/perspective-viewer/src/ts/plugin_utils/schema.ts @@ -15,8 +15,6 @@ import { rgbToHex } from "./color.ts"; import { native } from "./native.ts"; import { bg_modes_for, - default_bg_mode, - default_fg_mode, fg_modes_for, parse_bg_mode, parse_fg_mode, @@ -59,11 +57,6 @@ export const ALIGNS: readonly Align[] = [ "bottom-right", ]; -/** An `align` value from a token, or `undefined` for anything else. */ -export function parse_align(raw: unknown): Align | undefined { - return ALIGNS.includes(raw as Align) ? (raw as Align) : undefined; -} - /** CSS generic font families, which are never quoted when applied. */ export const GENERIC_FONT_FAMILIES: readonly string[] = [ "inherit", @@ -118,16 +111,15 @@ export function color_group( return undefined; } - const fg_mode = - parse_fg_mode(type, current_value?.fg_mode) ?? default_fg_mode(type); - - const bg_mode = - parse_bg_mode(type, current_value?.bg_mode) ?? default_bg_mode(type); + const default_fg: FgMode = + type === "integer" || type === "float" ? "color" : "disabled"; + const fg_mode = parse_fg_mode(type, current_value?.fg_mode) ?? default_fg; + const bg_mode = parse_bg_mode(type, current_value?.bg_mode) ?? "disabled"; const color_fields: ControlSpec[] = [ - mode_spec("fg_mode", fg_modes, default_fg_mode(type)), + mode_spec("fg_mode", fg_modes, default_fg), ...value_specs(type, "fg", fg_mode, theme), - mode_spec("bg_mode", bg_modes, default_bg_mode(type)), + mode_spec("bg_mode", bg_modes, "disabled"), ...value_specs(type, "bg", bg_mode, theme), ]; @@ -159,11 +151,8 @@ function mode_spec( } /** - * The controls a foreground or background `mode` gates in for a column of - * `type`: the `fg_color` / `bg_color` value control in the grammar the - * (type, mode) pair reads - gradient stops for numbers, a color for - * string / datetime `"color"`, a palette for string `"series"` - plus the - * numeric scale extent. Nothing for `"disabled"`. + * The value controls a foreground or background `mode` gates in for a column of + * `type`, none for `"disabled"`. */ function value_specs( type: ColumnType, diff --git a/rust/perspective-viewer/test/js/multi_panel/context_menu_commands.spec.ts b/rust/perspective-viewer/test/js/multi_panel/context_menu_commands.spec.ts index 7c43acf17d..115b7c0a87 100644 --- a/rust/perspective-viewer/test/js/multi_panel/context_menu_commands.spec.ts +++ b/rust/perspective-viewer/test/js/multi_panel/context_menu_commands.spec.ts @@ -103,6 +103,11 @@ async function openMenu(page, selector = "perspective-viewer-plugin") { return menu; } +async function expectBuiltinOnly(menu) { + await expect(menu.locator(TOP_LEVEL).nth(0)).toHaveText("Panel Settings"); + await expect(menu.locator(".context-menu-separator")).toHaveCount(1); +} + async function commandCount(page): Promise { return await page.evaluate(() => window["__COMMANDS__"].length); } @@ -116,14 +121,18 @@ test.describe("Context menu custom commands", () => { const rows = menu.locator(TOP_LEVEL); await expect(rows.nth(0)).toHaveText("Hello"); await expect(rows.nth(1)).toHaveClass(/context-menu-separator/); - await expect(rows.nth(2)).toContainText("New"); + await expect(rows.nth(2)).toHaveText("Panel Settings"); + await expect(rows.nth(3)).toHaveClass(/context-menu-separator/); + await expect(rows.nth(4)).toContainText("New"); }); - test("an empty command list adds no separator", async ({ page }) => { + test("an empty command list adds no rows above the built-in items", async ({ + page, + }) => { await declareCommands(page, []); const menu = await openMenu(page); - await expect(menu.locator(".context-menu-separator")).toHaveCount(0); - await expect(menu.locator(TOP_LEVEL).nth(0)).toContainText("New"); + await expectBuiltinOnly(menu); + await expect(menu.locator(TOP_LEVEL).nth(2)).toContainText("New"); }); test("a disabled command dispatches nothing", async ({ page }) => { @@ -186,7 +195,7 @@ test.describe("Context menu custom commands", () => { ]); const menu = await openMenu(page); - await expect(menu.locator(".context-menu-separator")).toHaveCount(0); + await expectBuiltinOnly(menu); await expect( menu.locator(".context-menu-item", { hasText: "Empty" }), ).toHaveCount(0); @@ -312,7 +321,7 @@ test.describe("Context menu custom commands", () => { }); const menu = await openMenu(page); - await expect(menu.locator(".context-menu-separator")).toHaveCount(0); + await expectBuiltinOnly(menu); await expect( menu.locator(".context-menu-item", { hasText: "Hello" }), ).toHaveCount(0); @@ -351,7 +360,7 @@ test.describe("Context menu custom commands", () => { }); const menu = await openMenu(page); - await expect(menu.locator(".context-menu-separator")).toHaveCount(0); + await expectBuiltinOnly(menu); await expect( menu.locator(".context-menu-item", { hasText: "Duplicate" }), ).toBeVisible(); @@ -368,7 +377,7 @@ test.describe("Context menu custom commands", () => { await declareCommands(page, [{ kind: "Bogus", key: "x", label: "X" }]); const menu = await openMenu(page); - await expect(menu.locator(".context-menu-separator")).toHaveCount(0); + await expectBuiltinOnly(menu); await expect( menu.locator(".context-menu-item", { hasText: "Duplicate" }), ).toBeVisible(); @@ -379,7 +388,7 @@ test.describe("Context menu custom commands", () => { }) => { await declareCommands(page, [HELLO], { scopes: ["datagrid-row"] }); const menu = await openMenu(page); - await expect(menu.locator(".context-menu-separator")).toHaveCount(0); + await expectBuiltinOnly(menu); expect(await page.evaluate(() => window["__CONTEXTS__"].length)).toBe( 0, ); diff --git a/rust/perspective-viewer/test/js/multi_panel/context_menu_commands_plugin.spec.ts b/rust/perspective-viewer/test/js/multi_panel/context_menu_commands_plugin.spec.ts index 7873d52e06..48f6f75996 100644 --- a/rust/perspective-viewer/test/js/multi_panel/context_menu_commands_plugin.spec.ts +++ b/rust/perspective-viewer/test/js/multi_panel/context_menu_commands_plugin.spec.ts @@ -164,10 +164,14 @@ async function openMenu(page, selector: string) { } test.describe("Context menu custom commands with a hit-testing plugin", () => { - test("no schema means the plugin is never hit-tested", async ({ page }) => { + test("a body right-click hit-tests the plugin without a schema", async ({ + page, + }) => { await loadHitPlugin(page); await openMenu(page, "regular-layout-frame"); - expect(await page.evaluate(() => window["__HIT_TESTS__"])).toEqual([]); + expect(await page.evaluate(() => window["__HIT_TESTS__"].length)).toBe( + 1, + ); }); test("a body right-click carries the plugin's hit at the click point", async ({ diff --git a/rust/perspective-viewer/test/js/multi_panel/context_menu_viewer.spec.ts b/rust/perspective-viewer/test/js/multi_panel/context_menu_viewer.spec.ts index 71e06aa42b..e79aad2d3c 100644 --- a/rust/perspective-viewer/test/js/multi_panel/context_menu_viewer.spec.ts +++ b/rust/perspective-viewer/test/js/multi_panel/context_menu_viewer.spec.ts @@ -49,6 +49,60 @@ async function twoPanelsSecondActive(page) { } test.describe("Viewer-wide context menu", () => { + test("a right-click leaves the active panel and offers Panel Settings", async ({ + page, + }) => { + await restoreWorkspace(page, { + layout: { + type: "split-layout", + orientation: "horizontal", + sizes: [0.5, 0.5], + children: [ + { type: "tab-layout", tabs: ["one"], selected: 0 }, + { type: "tab-layout", tabs: ["two"], selected: 0 }, + ], + }, + panels: { + one: { table: TABLE, plugin: "Debug" }, + two: { table: TABLE, plugin: "Debug" }, + }, + }); + + await openSettings(page); + await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.setActivePanel("two"); + }); + + await page + .locator('perspective-viewer perspective-viewer-plugin[slot="one"]') + .click({ button: "right" }); + + const menu = page.locator("perspective-context-menu"); + await menu.waitFor(); + expect( + await page.evaluate(() => + ( + document.querySelector("perspective-viewer") as any + ).getActivePanel(), + ), + ).toBe("two"); + + await menu + .locator(".context-menu-item", { hasText: "Panel Settings" }) + .click(); + + await expect + .poll(async () => + page.evaluate(() => + ( + document.querySelector("perspective-viewer") as any + ).getActivePanel(), + ), + ) + .toBe("one"); + }); + test("a status bar right-click targets the active panel", async ({ page, }) => { diff --git a/rust/perspective-viewer/test/js/settings_panel/add_all_named_columns.spec.ts b/rust/perspective-viewer/test/js/settings_panel/add_all_named_columns.spec.ts new file mode 100644 index 0000000000..30e6d99958 --- /dev/null +++ b/rust/perspective-viewer/test/js/settings_panel/add_all_named_columns.spec.ts @@ -0,0 +1,66 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { test, expect, PageView } from "../helpers.ts"; + +test.beforeEach(async ({ page }) => { + await page.goto( + "/rust/perspective-viewer/test/html/column-selector-modes.html", + ); + await page.evaluate(async () => { + while (!(window as any)["__TEST_PERSPECTIVE_READY__"]) { + await new Promise((x) => setTimeout(x, 10)); + } + }); +}); + +test.describe("+ All with named columns", () => { + test("starts at the last named column", async ({ page }) => { + const view = new PageView(page); + await view.restore({ settings: true, columns: ["Sales", "Profit"] }); + + const names = await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + const table = await viewer.getTable(); + return Object.keys(await table.schema()); + }); + + const configUpdated = await view.getEventListener( + "perspective-config-update", + ); + + await page.locator("perspective-viewer #add-all-columns").click(); + await configUpdated(); + const columns = (await view.save()).columns; + expect(columns.slice(0, 4)).toEqual(["Sales", "Profit", null, null]); + expect(columns.length).toEqual(names.length + 2); + expect(columns.slice(4).sort()).toEqual( + names.filter((x) => x !== "Sales" && x !== "Profit").sort(), + ); + }); + + test("fills an empty required named column", async ({ page }) => { + const view = new PageView(page); + await view.restore({ settings: true, columns: ["Sales"] }); + const configUpdated = await view.getEventListener( + "perspective-config-update", + ); + + await page.locator("perspective-viewer #add-all-columns").click(); + await configUpdated(); + const columns = (await view.save()).columns; + expect(columns[0]).toEqual("Sales"); + expect(columns[1]).not.toBeNull(); + expect(columns.slice(2, 4)).toEqual([null, null]); + expect(columns[4]).not.toBeNull(); + }); +}); diff --git a/rust/perspective-viewer/test/js/settings_panel/alignment_control.spec.ts b/rust/perspective-viewer/test/js/settings_panel/alignment_control.spec.ts index 2dcc9d7869..c9f92f2ebf 100644 --- a/rust/perspective-viewer/test/js/settings_panel/alignment_control.spec.ts +++ b/rust/perspective-viewer/test/js/settings_panel/alignment_control.spec.ts @@ -180,6 +180,47 @@ test.describe("Alignment control", () => { expect(await checked_cells(font, "align")).toEqual(["top-left"]); }); + test("column grid ghosts its type's alignment while the grid's is unset", async ({ + page, + }) => { + const view = new PageView(page); + await view.restore({ + settings: true, + plugin: "Datagrid", + columns: ["Sales", "Region"], + }); + + const sales = await open_group( + await open_style_tab(view, "Sales"), + page, + "font", + ); + + await expect(cell(sales, "align", "right")).toHaveAttribute( + "aria-checked", + "true", + ); + + expect(await checked_cells(sales, "align")).toEqual(["right"]); + await expect(cell(sales, "align", "right")).toHaveClass(/is-default/); + await cell(sales, "align", "right").click(); + expect(((await view.save()) as any).columns_config).toEqual({}); + + const region = await open_group( + await open_style_tab(view, "Region"), + page, + "font", + ); + + await expect(cell(region, "align", "left")).toHaveAttribute( + "aria-checked", + "true", + ); + + expect(await checked_cells(region, "align")).toEqual(["left"]); + await expect(cell(region, "align", "left")).toHaveClass(/is-default/); + }); + test("charts legend anchor is corners-only with a ghost default", async ({ page, }) => { diff --git a/rust/perspective-viewer/test/js/viewer_config/localization.spec.ts b/rust/perspective-viewer/test/js/viewer_config/localization.spec.ts index 3df335edbf..0e78bd7615 100644 --- a/rust/perspective-viewer/test/js/viewer_config/localization.spec.ts +++ b/rust/perspective-viewer/test/js/viewer_config/localization.spec.ts @@ -29,6 +29,7 @@ test.describe("Localization", function () { test("labels > renders no visible label text", async function ({ page }) { const view = new PspViewer(page); + await view.restore({ plugin_config: { column_menus: true } }); await view.openSettingsPanel(); const editBtn = view.dataGrid.regularTable.editBtnRow .locator("th.psp-menu-enabled span") diff --git a/rust/perspective-viewer/tools.mjs b/rust/perspective-viewer/tools.mjs index 103814fd08..c8d1f64cad 100644 --- a/rust/perspective-viewer/tools.mjs +++ b/rust/perspective-viewer/tools.mjs @@ -92,7 +92,7 @@ const DOCS_DTS_FILES = [ scope: [ "type LabelPosition", "type ValueFit", - "type Breakdown", + "type LayoutMode", "interface ColumnConfig", "interface SummaryPluginConfig", ], From 721759e1e855100e5d66782ca34da4299cff03e1 Mon Sep 17 00:00:00 2001 From: Andrew Stein Date: Sun, 22 Nov 2026 19:07:22 -0500 Subject: [PATCH 4/4] Add `@perspective-dev/viewer-summary` Signed-off-by: Andrew Stein --- .github/workflows/build.yaml | 10 +- Cargo.toml | 1 + DEVELOPMENT.md | 1 + docs/md/how_to/javascript/installation.md | 3 + docs/md/how_to/javascript/viewer.md | 1 + docs/package.json | 1 + docs/src/data/features.js | 89 ++ docs/src/index.ts | 1 + examples/bundler-test/package.json | 3 +- examples/bundler-test/src/app.ts | 1 + package.json | 2 + packages/viewer-summary/README.md | 72 ++ packages/viewer-summary/build.mjs | 74 ++ packages/viewer-summary/clean.mjs | 15 + packages/viewer-summary/package.json | 65 + packages/viewer-summary/src/css/summary.css | 251 ++++ packages/viewer-summary/src/ts/index.ts | 48 + packages/viewer-summary/src/ts/layout.ts | 1065 +++++++++++++++++ .../viewer-summary/src/ts/plugin_utils.ts | 21 + packages/viewer-summary/src/ts/schema.ts | 215 ++++ packages/viewer-summary/src/ts/summary.ts | 874 ++++++++++++++ packages/viewer-summary/src/ts/tiles.ts | 180 +++ packages/viewer-summary/src/ts/types.ts | 177 +++ .../viewer-summary/test/js/summary.spec.ts | 638 ++++++++++ packages/viewer-summary/test/js/tsconfig.json | 9 + packages/viewer-summary/tsconfig.json | 10 + packages/viewer-summary/types.d.ts | 21 + pnpm-lock.yaml | 39 + pnpm-workspace.yaml | 1 + rust/perspective-viewer/src/themes/intl.css | 7 +- .../perspective-viewer/src/themes/intl/ar.css | 7 +- .../perspective-viewer/src/themes/intl/de.css | 7 +- .../perspective-viewer/src/themes/intl/es.css | 7 +- .../perspective-viewer/src/themes/intl/fr.css | 7 +- .../perspective-viewer/src/themes/intl/ja.css | 7 +- .../perspective-viewer/src/themes/intl/pt.css | 7 +- .../perspective-viewer/src/themes/intl/zh.css | 7 +- .../src/themes/phosphor.css | 1 + .../src/themes/pro/palette.css | 3 +- tools/scripts/setup.mjs | 5 + tools/scripts/test_consumers.mjs | 1 + tools/scripts/test_js.mjs | 1 + tools/test/playwright.config.ts | 11 +- tools/test/src/html/summary-test.html | 32 + 44 files changed, 3976 insertions(+), 22 deletions(-) create mode 100644 packages/viewer-summary/README.md create mode 100644 packages/viewer-summary/build.mjs create mode 100644 packages/viewer-summary/clean.mjs create mode 100644 packages/viewer-summary/package.json create mode 100644 packages/viewer-summary/src/css/summary.css create mode 100644 packages/viewer-summary/src/ts/index.ts create mode 100644 packages/viewer-summary/src/ts/layout.ts create mode 100644 packages/viewer-summary/src/ts/plugin_utils.ts create mode 100644 packages/viewer-summary/src/ts/schema.ts create mode 100644 packages/viewer-summary/src/ts/summary.ts create mode 100644 packages/viewer-summary/src/ts/tiles.ts create mode 100644 packages/viewer-summary/src/ts/types.ts create mode 100644 packages/viewer-summary/test/js/summary.spec.ts create mode 100644 packages/viewer-summary/test/js/tsconfig.json create mode 100644 packages/viewer-summary/tsconfig.json create mode 100644 packages/viewer-summary/types.d.ts create mode 100644 tools/test/src/html/summary-test.html diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index a6787c71e2..7c22e9f1f0 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -171,7 +171,7 @@ jobs: - name: WebAssembly Build run: pnpm run build --ci env: - PACKAGE: "server,client,viewer,viewer-datagrid,viewer-charts,react,anywidget" + PACKAGE: "server,client,viewer,viewer-datagrid,viewer-charts,viewer-summary,react,anywidget" PSP_USE_CCACHE: "1" - name: Run df -h @@ -188,6 +188,7 @@ jobs: rust/perspective-viewer/src packages/viewer-charts/dist packages/viewer-datagrid/dist + packages/viewer-summary/dist packages/react/dist # The `PerspectiveWidget` anywidget JS/CSS bundle, needed by any @@ -890,7 +891,7 @@ jobs: id: run_tests run: pnpm run test -- --fetch-snapshots env: - PACKAGE: "server,client,viewer,viewer-datagrid,viewer-charts,react" + PACKAGE: "server,client,viewer,viewer-datagrid,viewer-charts,viewer-summary,react" PSP_BROWSER_SUITE: chrome PSP_SNAPSHOT_REPO: ${{ vars.PSP_SNAPSHOT_REPO }} PSP_SNAPSHOT_TOKEN: ${{ secrets.PSP_SNAPSHOT_TOKEN }} @@ -954,7 +955,7 @@ jobs: env: # TODO(texodus): no GL firefox on GHA # PACKAGE: "viewer,viewer-datagrid,viewer-charts" - PACKAGE: "viewer,viewer-datagrid" + PACKAGE: "viewer,viewer-datagrid,viewer-summary" PSP_BROWSER_SUITE: firefox PSP_SNAPSHOT_REPO: ${{ vars.PSP_SNAPSHOT_REPO }} PSP_SNAPSHOT_TOKEN: ${{ secrets.PSP_SNAPSHOT_TOKEN }} @@ -1357,6 +1358,9 @@ jobs: - run: pnpm pack --pack-destination=../.. working-directory: ./packages/viewer-charts + - run: pnpm pack --pack-destination=../.. + working-directory: ./packages/viewer-summary + - run: pnpm pack --pack-destination=../.. working-directory: ./packages/react diff --git a/Cargo.toml b/Cargo.toml index 416c86a6f6..8acda8135a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,6 +79,7 @@ incremental = true # These are only respected when `cargo` is invoked from the project root [patch.crates-io] +# simd-adler32 = { git = "https://github.com/mcountryman/simd-adler32.git", rev = "b279034d9eb554c3e5e0af523db044f08d8297ba" } protobuf-src = { git = "https://github.com/carlocorradini/rust-protobuf-native.git", rev = "1aba500e469f8bdc384a0fe9e69c189fda72e059" } perspective-client = { path = "rust/perspective-client" } perspective-server = { path = "rust/perspective-server" } diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index b0609b152c..b81febade4 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -24,6 +24,7 @@ All commands in this guide are run from the repository root. | `rust/perspective-viewer` | `@perspective-dev/viewer`, the `` Custom Element | | `rust/perspective` | The `perspective` Rust crate | | `packages/viewer-datagrid`, `packages/viewer-charts` | Viewer plugins | +| `packages/viewer-summary` | The Summary viewer plugin | | `packages/react`, `packages/jupyterlab`, `packages/anywidget` | Framework and notebook integrations | | `tools/scripts`, `tools/test`, `tools/bench` | Build scripts, the shared test harness and the benchmark suite | | `examples`, `docs` | Example projects and the documentation site | diff --git a/docs/md/how_to/javascript/installation.md b/docs/md/how_to/javascript/installation.md index 8471fb4809..0c8978a47b 100644 --- a/docs/md/how_to/javascript/installation.md +++ b/docs/md/how_to/javascript/installation.md @@ -22,6 +22,9 @@ separately and must be imported individually. - `@perspective-dev/viewer-charts` A set of charting components base on WebGL. +- `@perspective-dev/viewer-summary` + A grid of tiles showing each column's total as large fitted text. + When imported after `@perspective-dev/viewer`, the plugin modules will register themselves automatically, and the renderers they export will be available in the `plugin` dropdown in the `` UI. diff --git a/docs/md/how_to/javascript/viewer.md b/docs/md/how_to/javascript/viewer.md index 07d8f9b1aa..3b42ae0d5c 100644 --- a/docs/md/how_to/javascript/viewer.md +++ b/docs/md/how_to/javascript/viewer.md @@ -81,6 +81,7 @@ The viewer provides an interactive side panel with: columns via the [expression language](../../explanation/view/config/expressions.md). - **Plugin selector** - switch between the visualization plugins registered on the page. `@perspective-dev/viewer-datagrid` provides `Datagrid`; + `@perspective-dev/viewer-summary` provides `Summary`; `@perspective-dev/viewer-charts` provides `X Bar`, `Y Bar`, `Y Line`, `Y Scatter`, `Y Area`, `X/Y Scatter`, `X/Y Line`, `Density`, `Treemap`, `Sunburst`, `Heatmap`, `Candlestick`, `OHLC`, `Map Scatter`, `Map Line` and diff --git a/docs/package.json b/docs/package.json index c5f9adec98..7f18e4982c 100644 --- a/docs/package.json +++ b/docs/package.json @@ -19,6 +19,7 @@ "@duckdb/duckdb-wasm": "catalog:", "@perspective-dev/viewer-charts": "workspace:^", "@perspective-dev/viewer-datagrid": "workspace:^", + "@perspective-dev/viewer-summary": "workspace:^", "@perspective-dev/viewer": "workspace:^", "@perspective-dev/client": "workspace:^", "@perspective-dev/server": "workspace:^", diff --git a/docs/src/data/features.js b/docs/src/data/features.js index 15d6ccb3e4..2ab47ee01b 100644 --- a/docs/src/data/features.js +++ b/docs/src/data/features.js @@ -1421,4 +1421,93 @@ export default [ }, viewport: { width: 600, height: 450 }, }, + { + name: "Summary", + description: "Summary. One big number: total Sales.", + config: { + title: "Summary", + plugin: "Summary", + columns: ["Sales"], + columns_config: { + Sales: { + number_format: { + minimumFractionDigits: 0, + maximumFractionDigits: 0, + }, + }, + }, + }, + }, + { + name: "Summary Mixed Types", + description: + "Summary. Tiles for float, integer, date and string columns, each with an aggregate that keeps its type.", + config: { + title: "Summary Mixed Types", + plugin: "Summary", + columns: ["Sales", "Quantity", "Discount", "Order Date", "Segment"], + aggregates: { + Sales: "sum", + Quantity: "sum", + Discount: "avg", + "Order Date": "max", + Segment: "dominant", + }, + }, + }, + { + name: "Summary Split By", + description: "Summary. Sales and Profit tiles for each Region.", + config: { + title: "Summary Split By", + plugin: "Summary", + columns: ["Sales", "Profit"], + split_by: ["Region"], + }, + }, + { + name: "Summary Split By 2", + description: + "Summary. Sales by Region and Category, grouped by Region with each Region's total.", + config: { + title: "Summary Split By 2", + plugin: "Summary", + columns: ["Sales"], + split_by: ["Region", "Category"], + split_rollup_mode: "rollup", + plugin_config: { layout_mode: "hierarchy" }, + }, + }, + { + name: "Summary Bars", + description: + "Summary. Sales, Profit and Quantity for each Region, drawn as bars.", + config: { + title: "Summary Bars", + plugin: "Summary", + columns: ["Sales", "Profit", "Quantity"], + split_by: ["Region"], + columns_config: { + Sales: { fg_mode: "bar", fg_gradient: 800000 }, + Profit: { fg_mode: "bar", fg_gradient: 120000 }, + Quantity: { fg_mode: "bar", fg_gradient: 15000 }, + }, + }, + }, + { + name: "Summary Label Bars", + description: + "Summary. Sales, Profit and Quantity for each Category, drawn as bars with the value overlaid.", + config: { + title: "Summary Label Bars", + plugin: "Summary", + columns: ["Sales", "Profit", "Quantity"], + split_by: ["Category"], + columns_config: { + Sales: { fg_mode: "label-bar", fg_gradient: 900000 }, + Profit: { fg_mode: "label-bar", fg_gradient: 150000 }, + Quantity: { fg_mode: "label-bar", fg_gradient: 25000 }, + }, + }, + }, ]; diff --git a/docs/src/index.ts b/docs/src/index.ts index 9d62321378..e73c2ad4c0 100644 --- a/docs/src/index.ts +++ b/docs/src/index.ts @@ -12,6 +12,7 @@ import "@perspective-dev/viewer"; import "@perspective-dev/viewer-datagrid"; +import "@perspective-dev/viewer-summary"; import "@perspective-dev/viewer-charts"; import { initAboutDialog } from "./components/about_dialog.js"; diff --git a/examples/bundler-test/package.json b/examples/bundler-test/package.json index eba953c466..97a3c6aff7 100644 --- a/examples/bundler-test/package.json +++ b/examples/bundler-test/package.json @@ -16,7 +16,8 @@ "@perspective-dev/react": "workspace:^", "@perspective-dev/viewer": "workspace:^", "@perspective-dev/viewer-charts": "workspace:^", - "@perspective-dev/viewer-datagrid": "workspace:^" + "@perspective-dev/viewer-datagrid": "workspace:^", + "@perspective-dev/viewer-summary": "workspace:^" }, "devDependencies": { "@types/emscripten": "catalog:", diff --git a/examples/bundler-test/src/app.ts b/examples/bundler-test/src/app.ts index 3310fa16e1..ccdfedda70 100644 --- a/examples/bundler-test/src/app.ts +++ b/examples/bundler-test/src/app.ts @@ -28,6 +28,7 @@ import { } from "@perspective-dev/viewer"; import "@perspective-dev/viewer-datagrid"; import "@perspective-dev/viewer-charts"; +import "@perspective-dev/viewer-summary"; import { PerspectiveViewer } from "@perspective-dev/react"; import type { DuckDBHandler } from "@perspective-dev/client/virtual_servers/duckdb"; import type { ClickhouseHandler } from "@perspective-dev/client/virtual_servers/clickhouse"; diff --git a/package.json b/package.json index 5989fd6236..69425ee165 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "packages/react", "packages/viewer-datagrid", "packages/viewer-charts", + "packages/viewer-summary", "packages/jupyterlab", "packages/cli", "rust/perspective-js", @@ -46,6 +47,7 @@ "@perspective-dev/viewer": "workspace:^", "@perspective-dev/viewer-charts": "workspace:^", "@perspective-dev/viewer-datagrid": "workspace:^", + "@perspective-dev/viewer-summary": "workspace:^", "@playwright/experimental-ct-react": "catalog:", "@playwright/test": "catalog:", "chalk": "catalog:", diff --git a/packages/viewer-summary/README.md b/packages/viewer-summary/README.md new file mode 100644 index 0000000000..d23864b762 --- /dev/null +++ b/packages/viewer-summary/README.md @@ -0,0 +1,72 @@ +# `@perspective-dev/viewer-summary` + +[![npm](https://img.shields.io/npm/v/@perspective-dev/viewer-summary.svg?style=for-the-badge)](https://www.npmjs.com/package/@perspective-dev/viewer-summary) + +A summary (KPI tile) plugin for ``: each selected column's +total, drawn as large fitted text in a grid of tiles. + +Perspective is an open-source data grid, pivot table and charting component for +large, real-time and streaming datasets. + +- One tile per column, laid out to give the largest value text the panel allows, + re-fitted as the panel resizes, or in a fixed grid set by + `plugin_config.grid_columns` / `grid_rows`. +- The view is always the grand total (`group_rollup_mode: "total"`); filters and + expressions apply as usual. +- `split_by` draws a tile per split value, labelled with the split values above + the column name; `split_rollup_mode: "rollup"` adds the column totals. + `plugin_config.layout_mode: "hierarchy"` instead nests the tiles in a labelled + group per split value, level by level, fitted to the panel. +- Labels sit above, below, left or right of the value, or are hidden, chosen + automatically or set by `label_position` for every tile or per column. +- Per-column number and date formatting, colors, gradients, bars and pulse on + update, shared with the Datagrid plugin. +- Live updates: tiles repaint as the underlying `Table` streams. + +## Usage + +Importing the package registers the plugin with ``: + +```html + + + + + +``` + +With a bundler: + +```bash +npm install @perspective-dev/client @perspective-dev/viewer @perspective-dev/viewer-summary +``` + +```javascript +import "@perspective-dev/viewer"; +import "@perspective-dev/viewer-summary"; +``` + +## Documentation + +- [Project site and live examples](https://perspective-dev.github.io/) +- [User guide](https://perspective-dev.github.io/guide/) +- [Example gallery](https://perspective-dev.github.io/gallery/index.html) +- [GitHub](https://github.com/perspective-dev/perspective) diff --git a/packages/viewer-summary/build.mjs b/packages/viewer-summary/build.mjs new file mode 100644 index 0000000000..0b3f85e5c0 --- /dev/null +++ b/packages/viewer-summary/build.mjs @@ -0,0 +1,74 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { NodeModulesExternal } from "@perspective-dev/esbuild-plugin/external.js"; +import { build } from "@perspective-dev/esbuild-plugin/build.js"; +import { bundle as bundleCss } from "lightningcss"; +import * as fs from "node:fs"; +import { inlineUrlVisitor } from "../../rust/perspective-viewer/tools.mjs"; + +import "zx/globals"; + +const BUILD = [ + { + define: { + global: "window", + }, + entryPoints: ["src/ts/index.ts"], + plugins: [NodeModulesExternal()], + format: "esm", + loader: { + ".css": "text", + }, + outfile: "dist/esm/perspective-viewer-summary.js", + }, + { + define: { + global: "window", + }, + entryPoints: ["src/ts/index.ts"], + plugins: [], + format: "esm", + loader: { + ".css": "text", + }, + outfile: "dist/cdn/perspective-viewer-summary.js", + }, +]; + +async function compile_css() { + fs.mkdirSync("dist/css", { recursive: true }); + const { code } = bundleCss({ + filename: "./src/css/summary.css", + minify: true, + visitor: inlineUrlVisitor("./src/css/summary.css"), + }); + + fs.writeFileSync("dist/css/perspective-viewer-summary.css", code); +} + +async function build_all() { + await compile_css(); + await Promise.all(BUILD.map(build)).catch(() => process.exit(1)); + try { + await $`tsc --project ./tsconfig.json`.stdio( + "inherit", + "inherit", + "inherit", + ); + } catch (e) { + console.error(e.stdout); + process.exit(1); + } +} + +build_all(); diff --git a/packages/viewer-summary/clean.mjs b/packages/viewer-summary/clean.mjs new file mode 100644 index 0000000000..49a5253931 --- /dev/null +++ b/packages/viewer-summary/clean.mjs @@ -0,0 +1,15 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import * as fs from "node:fs"; + +fs.rmSync("dist", { recursive: true, force: true }); diff --git a/packages/viewer-summary/package.json b/packages/viewer-summary/package.json new file mode 100644 index 0000000000..8e6a5883c2 --- /dev/null +++ b/packages/viewer-summary/package.json @@ -0,0 +1,65 @@ +{ + "name": "@perspective-dev/viewer-summary", + "version": "5.9.4", + "description": "Summary (KPI tile) plugin for ``, showing each column's total as fitted text.", + "keywords": [ + "perspective", + "summary", + "kpi", + "big-number", + "single-value", + "stat", + "visualization", + "dashboard", + "analytics", + "bi", + "streaming", + "real-time", + "wasm", + "webassembly", + "arrow", + "web-component" + ], + "homepage": "https://perspective-dev.github.io", + "unpkg": "dist/cdn/perspective-viewer-summary.js", + "jsdelivr": "dist/cdn/perspective-viewer-summary.js", + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/perspective-viewer-summary.js" + }, + "./dist/*": "./dist/*", + "./package.json": "./package.json" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "files": [ + "dist/**/*" + ], + "scripts": { + "build": "node ./build.mjs", + "clean": "node ./clean.mjs" + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/perspective-dev/perspective.git", + "directory": "packages/viewer-summary" + }, + "author": "", + "license": "Apache-2.0", + "dependencies": { + "@perspective-dev/client": "workspace:~", + "@perspective-dev/viewer": "workspace:~" + }, + "devDependencies": { + "lightningcss": "catalog:", + "@perspective-dev/esbuild-plugin": "workspace:^", + "@perspective-dev/test": "workspace:^", + "prettier": "catalog:", + "typescript": "catalog:", + "zx": "catalog:" + } +} diff --git a/packages/viewer-summary/src/css/summary.css b/packages/viewer-summary/src/css/summary.css new file mode 100644 index 0000000000..103ae4cab9 --- /dev/null +++ b/packages/viewer-summary/src/css/summary.css @@ -0,0 +1,251 @@ +/* ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ + * ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ + * ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ + * ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ + * ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ + * ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ + * ┃ Copyright (c) 2017, the Perspective Authors. ┃ + * ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ + * ┃ This file is part of the Perspective library, distributed under the terms ┃ + * ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ + * ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + */ + +:host { + position: relative; + display: block; + width: 100%; + height: 100%; + overflow: hidden; + font-family: inherit; + color: var(--psp--color); +} + +#tiles { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + display: flex; + flex-wrap: wrap; + align-content: flex-start; + gap: 1px; + overflow: hidden; + background-color: var(--psp--background-color); + container-type: size; +} + +#tiles.tile-fit .tile { + container-type: size; +} + +#tiles.scroll { + overflow-y: auto; +} + +.tile { + box-sizing: border-box; + display: flex; + flex-direction: column; + justify-content: var(--psp-summary--v, center); + align-items: stretch; + flex: 1 1 + calc( + (100% - (var(--psp-summary--cols, 1) - 1) * 1px) / + var(--psp-summary--cols, 1) - 1px + ); + height: calc( + (100% - (var(--psp-summary--rows, 1) - 1) * 1px) / + var(--psp-summary--rows, 1) + ); + min-width: 0; + padding: var(--psp-summary--padding, 4px); + overflow: hidden; + cursor: default; + box-shadow: + 1px 0 0 0 var(--psp-inactive--border-color), + 0 1px 0 0 var(--psp-inactive--border-color); +} + +#tiles.hierarchy .tile { + box-shadow: none; +} + +#tiles.scroll .tile { + height: var(--psp-summary--tile-height); +} + +#tiles.hierarchy, +.group-body { + display: grid; + grid-template-columns: repeat( + var(--psp-summary--tracks, 1), + minmax(0, 1fr) + ); + grid-template-rows: repeat(var(--psp-summary--rows, 1), minmax(0, 1fr)); + gap: 4px; +} + +#tiles.hierarchy.leaf, +.group-body.leaf { + gap: 1px; +} + +#tiles.hierarchy.split-rows, +.group-body.split-rows { + grid-template-rows: var(--psp-summary--split); +} + +#tiles.hierarchy.split-columns, +.group-body.split-columns { + grid-template-columns: var(--psp-summary--split); +} + +#tiles.hierarchy > *, +.group-body > * { + grid-column: span var(--psp-summary--span, 1); + min-width: 0; + min-height: 0; +} + +#tiles.hierarchy > .last-row, +.group-body > .last-row { + grid-column: span var(--psp-summary--last-span, 1); +} + +#tiles.hierarchy .tile { + flex: none; + height: auto; +} + +.group { + box-sizing: border-box; + display: flex; + flex-direction: column; + border: 1px solid var(--psp-inactive--border-color); + padding: 0 3px 3px; +} + +.group.headless { + border: none; + padding: 0; +} + +.group-header { + flex: 0 0 19px; + line-height: 19px; + padding: 0 1px; + font-size: 11px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + opacity: 0.7; +} + +.group-body { + flex: 1 1 0; +} + +#tiles.hierarchy.scroll, +#tiles.hierarchy.scroll .group-body { + grid-template-rows: none; + grid-auto-rows: auto; + align-content: start; +} + +#tiles.hierarchy.scroll.leaf, +#tiles.hierarchy.scroll .group-body.leaf { + grid-auto-rows: var(--psp-summary--tile-height); +} + +#tiles.hierarchy.scroll .group-body { + flex: 0 0 auto; +} + +.tile.label-left, +.tile.label-right { + flex-direction: row; + justify-content: flex-start; + align-items: var(--psp-summary--v, center); +} + +.label { + flex: 0 0 auto; + font-size: var(--psp-summary--label-size, 10px); + line-height: 1.3; + white-space: pre; + overflow: hidden; + text-overflow: ellipsis; + text-align: var(--psp-summary--t, center); + color: var(--psp-summary--label--color, var(--psp--color)); + opacity: 0.7; +} + +.tile.label-bottom .label, +.tile.label-right .label { + order: 2; +} + +.tile.label-none .label { + display: none; +} + +.tile.label-left .label { + max-width: 40%; + margin-right: 0.75em; +} + +.tile.label-right .label { + max-width: 40%; + margin-left: 0.75em; +} + +.body { + flex: 0 0 auto; + display: flex; + flex-direction: column; + align-items: var(--psp-summary--h, center); + min-width: 0; +} + +.tile.label-left .body, +.tile.label-right .body { + flex: 1 1 0; +} + +.value { + max-width: 100%; + font-size: var(--psp-summary--value-size, 14px); + line-height: 1.1; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.psp-null .value { + opacity: 0.4; +} + +.track { + display: none; +} + +.psp-color-mode-bar .track { + display: block; + align-self: stretch; + height: calc(var(--psp-summary--value-size, 14px) * 0.12); + margin-top: calc(var(--psp-summary--value-size, 14px) * 0.08); + background-color: color-mix(in srgb, currentColor 15%, transparent); + background-image: var(--psp-label-bar-color); + background-repeat: no-repeat; + background-size: var(--psp-bar-size, 0%) 100%; + background-position-x: var(--psp-bar-anchor, 0%); +} + +.tile.psp-color-mode-label-bar { + background-image: var(--psp-label-bar-color); + background-repeat: no-repeat; + background-size: var(--psp-bar-size, 0%) 100%; + background-position-x: 0%; +} diff --git a/packages/viewer-summary/src/ts/index.ts b/packages/viewer-summary/src/ts/index.ts new file mode 100644 index 0000000000..594ab7653c --- /dev/null +++ b/packages/viewer-summary/src/ts/index.ts @@ -0,0 +1,48 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { HTMLPerspectiveViewerSummaryPluginElement } from "./summary.ts"; + +interface PerspectiveViewerConstructor { + registerPlugin(tagName: string): void; +} + +async function _register_element(): Promise { + if (customElements.get("perspective-viewer-summary")) { + console.warn( + 'Custom element "perspective-viewer-summary" is already registered; skipping duplicate registration (Perspective was loaded more than once on this page).', + ); + return; + } + + customElements.define( + "perspective-viewer-summary", + HTMLPerspectiveViewerSummaryPluginElement, + ); + + await customElements.whenDefined("perspective-viewer"); + const PerspectiveViewer = customElements.get( + "perspective-viewer", + ) as unknown as PerspectiveViewerConstructor; + PerspectiveViewer.registerPlugin("perspective-viewer-summary"); +} + +_register_element(); + +export { HTMLPerspectiveViewerSummaryPluginElement }; +export type { + ColumnConfig, + LabelPosition, + LayoutMode, + SummaryPluginConfig, + ValueFit, +} from "./types.ts"; diff --git a/packages/viewer-summary/src/ts/layout.ts b/packages/viewer-summary/src/ts/layout.ts new file mode 100644 index 0000000000..83e769e15d --- /dev/null +++ b/packages/viewer-summary/src/ts/layout.ts @@ -0,0 +1,1065 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { LabelPosition, TileGroup } from "./types.ts"; + +export type LabelPlacement = Exclude; + +/** A tile's text widths per pixel of font size, and its label lines. */ +export interface TileMetrics { + value: number; + label: number; + lines: number; + + /** The tile's label position, its column's over the plugin's. */ + position: LabelPosition; +} + +export interface LayoutInput { + width: number; + height: number; + tiles: TileMetrics[]; + uniform: boolean; + + /** Height reserved beneath each value, in multiples of its font size. */ + extra: number; + + /** The tile columns `plugin_config.grid_columns` asks for. */ + grid_columns: number | undefined; + + /** The tile rows `plugin_config.grid_rows` asks for. */ + grid_rows: number | undefined; +} + +export interface Layout { + cols: number; + rows: number; + + /** Fixed tile height in pixels when the tiles overflow and scroll. */ + tile_height: number | undefined; + padding: number; + placements: LabelPlacement[]; + label_sizes: number[]; + value_sizes: number[]; + + /** Each container's grid, when tiles nest in groups. */ + containers?: Map; + + /** Each tile's padding, when tiles nest in groups. */ + paddings?: number[]; +} + +/** The grid of one container of tiles or groups. */ +export interface ContainerGrid { + cols: number; + + /** The rows the container's height is divided into, or `undefined` for rows sized by their content. */ + rows: number | undefined; + + /** The items in the last row, which stretch to fill it. */ + last: number; + + /** The `SPLIT_STEPS`ths of a rollup's length that its totals take. */ + split?: number; +} + +interface Rect { + left: number; + top: number; + width: number; + height: number; +} + +export const GAP = 1; +const VALUE_LINE_HEIGHT = 1.1; +const LABEL_LINE_HEIGHT = 1.3; +export const TRACK_EXTRA = 0.2; + +const LABEL_RATIO = 0.28; +const LABEL_MIN = 10; +const LABEL_MAX = 22; +const MIN_VALUE_SIZE = 14; +const INLINE_LABEL_MAX = 0.4; +const INLINE_LABEL_GAP = 0.75; +const FIT_SLACK = 0.96; +const SCROLL_PADDING = 8; +const SCROLLBAR = 12; + +interface Metrics { + value: number; + label: number; + lines: number; +} + +interface Fit { + value: number; + label: number; + padding: number; + placement: LabelPlacement; +} + +/** The tiles sharing one label position, by the widest of their texts. */ +interface Group { + position: LabelPosition; + widest: Metrics; +} + +function clamp(x: number, lo: number, hi: number): number { + return Math.max(lo, Math.min(hi, x)); +} + +function is_stacked(placement: LabelPlacement): boolean { + return placement === "top" || placement === "bottom"; +} + +function placement_of(position: LabelPosition): LabelPlacement { + return position === "auto" ? "top" : position; +} + +/** The largest value font size that fits a `(w, h)` cell beside `label`. */ +function fit_value( + w: number, + h: number, + padding: number, + label: number, + em: Metrics, + placement: LabelPlacement, + extra: number, +): number { + const iw = Math.max(1, w - 2 * padding); + const ih = Math.max(1, h - 2 * padding); + const lines = VALUE_LINE_HEIGHT + extra; + if (placement === "none") { + return Math.min(ih / lines, iw / em.value); + } + + if (is_stacked(placement)) { + return Math.min( + (ih - label * LABEL_LINE_HEIGHT * em.lines) / lines, + iw / em.value, + ); + } + + const label_width = Math.min(em.label * label, iw * INLINE_LABEL_MAX); + return Math.min( + ih / lines, + (iw - label_width - label * INLINE_LABEL_GAP) / em.value, + ); +} + +function label_for(value: number, placement: LabelPlacement): number { + return placement === "none" + ? 0 + : clamp(value * LABEL_RATIO, LABEL_MIN, LABEL_MAX); +} + +function fit_cell( + w: number, + h: number, + em: Metrics, + placement: LabelPlacement, + extra: number, +): Fit { + const padding = clamp(Math.min(w, h) * 0.08, 4, 24); + const ih = Math.max(1, h - 2 * padding); + const share = is_stacked(placement) + ? LABEL_RATIO * LABEL_LINE_HEIGHT * em.lines + : 0; + + const by_height = ih / (VALUE_LINE_HEIGHT + extra + share); + const guess = fit_value( + w, + h, + padding, + label_for(by_height, placement), + em, + placement, + extra, + ); + + const label = label_for(guess, placement); + const value = fit_value(w, h, padding, label, em, placement, extra); + return { value, label, padding, placement }; +} + +function best_fit( + w: number, + h: number, + em: Metrics, + position: LabelPosition, + extra: number, +): Fit { + if (position !== "auto") { + return fit_cell(w, h, em, position, extra); + } + + const top = fit_cell(w, h, em, "top", extra); + const left = fit_cell(w, h, em, "left", extra); + return left.value > top.value ? left : top; +} + +function group_tiles(tiles: TileMetrics[]): Group[] { + const groups = new Map(); + for (const tile of tiles) { + const widest = groups.get(tile.position); + groups.set(tile.position, { + value: Math.max(widest?.value ?? 0, tile.value), + label: Math.max(widest?.label ?? 0, tile.label), + lines: Math.max(widest?.lines ?? 0, tile.lines), + }); + } + + return [...groups].map(([position, widest]) => ({ position, widest })); +} + +/** Each group's fit in a `(w, h)` cell, and the smallest value among them. */ +function fit_groups( + w: number, + h: number, + groups: Group[], + extra: number, +): { fits: Map; value: number } { + const fits = new Map(); + let value = Infinity; + for (const group of groups) { + const fit = best_fit(w, h, group.widest, group.position, extra); + fits.set(group.position, fit); + value = Math.min(value, fit.value); + } + + return { fits, value }; +} + +/** The width of tile `index`, whose row stretches to fill the container. */ +function tile_width( + index: number, + count: number, + cols: number, + rows: number, + width: number, +): number { + const row = Math.floor(index / cols); + const in_row = row < rows - 1 ? cols : count - (rows - 1) * cols; + return (width - (in_row - 1) * GAP) / in_row; +} + +interface Grid { + cols: number; + + /** The rows the panel's height is divided into. */ + rows: number; + + /** The rows the tiles occupy. */ + occupied: number; +} + +/** The grid `grid_columns` and `grid_rows` ask for, if either does. */ +function explicit_grid( + count: number, + grid_columns: number | undefined, + grid_rows: number | undefined, +): Grid | undefined { + if (grid_columns !== undefined) { + const cols = Math.min(grid_columns, count); + const occupied = Math.ceil(count / cols); + return { cols, rows: grid_rows ?? occupied, occupied }; + } + + if (grid_rows !== undefined) { + const cols = Math.ceil(count / Math.min(grid_rows, count)); + const occupied = Math.ceil(count / cols); + return { cols, rows: occupied, occupied }; + } + + return undefined; +} + +/** + * The grid shape, label placements and font sizes that give `input.tiles` + * the largest value text in a `(width, height)` box, falling back to + * fixed-height scrolling tiles when that text would be too small to read, + * unless `grid_columns` or `grid_rows` fix the shape. + */ +export function compute_layout(input: LayoutInput): Layout { + const { width, height, tiles, uniform, extra } = input; + const count = tiles.length; + if (count === 0 || width <= 0 || height <= 0) { + return { + cols: 1, + rows: 1, + tile_height: undefined, + padding: 4, + placements: tiles.map((x) => placement_of(x.position)), + label_sizes: tiles.map(() => LABEL_MIN), + value_sizes: tiles.map(() => MIN_VALUE_SIZE), + }; + } + + const groups = group_tiles(tiles); + let box_width = width; + let tile_height: number | undefined; + let fits: Map; + let padding: number; + let grid = explicit_grid(count, input.grid_columns, input.grid_rows); + let cell_height: number; + if (grid !== undefined) { + if (grid.occupied > grid.rows) { + box_width = Math.max(1, width - SCROLLBAR); + tile_height = (height - (grid.rows - 1) * GAP) / grid.rows; + } + + cell_height = (height - (grid.rows - 1) * GAP) / grid.rows; + const w = (box_width - (grid.cols - 1) * GAP) / grid.cols; + fits = fit_groups(w, cell_height, groups, extra).fits; + padding = fits.values().next().value!.padding; + } else { + let best: ReturnType | undefined; + let total = Infinity; + grid = { cols: 1, rows: count, occupied: count }; + for (let c = 1; c <= count; c++) { + const r = Math.ceil(count / c); + const w = (width - (c - 1) * GAP) / c; + const h = (height - (r - 1) * GAP) / r; + const candidate = fit_groups(w, h, groups, extra); + if ( + best === undefined || + candidate.value > best.value || + (candidate.value === best.value && c * r < total) + ) { + grid = { cols: c, rows: r, occupied: r }; + total = c * r; + best = candidate; + } + } + + fits = best!.fits; + padding = fits.values().next().value!.padding; + cell_height = (height - (grid.rows - 1) * GAP) / grid.rows; + if (best!.value * FIT_SLACK < MIN_VALUE_SIZE) { + fits = new Map(); + let min_width = 0; + let fallback_height = 0; + for (const { position, widest } of groups) { + const placement = placement_of(position); + const label = placement === "none" ? 0 : LABEL_MIN; + const inline = placement === "left" || placement === "right"; + fits.set(position, { + value: 0, + label, + padding: SCROLL_PADDING, + placement, + }); + + fallback_height = Math.max( + fallback_height, + (MIN_VALUE_SIZE / FIT_SLACK) * (VALUE_LINE_HEIGHT + extra) + + (is_stacked(placement) + ? label * LABEL_LINE_HEIGHT * widest.lines + : 0) + + 2 * SCROLL_PADDING, + ); + + min_width = Math.max( + min_width, + (MIN_VALUE_SIZE / FIT_SLACK) * widest.value + + (inline + ? (widest.label + INLINE_LABEL_GAP) * label + : 0) + + 2 * SCROLL_PADDING, + ); + } + + tile_height = Math.ceil(fallback_height); + box_width = Math.max(1, width - SCROLLBAR); + const cols = clamp( + Math.floor((box_width + GAP) / (min_width + GAP)), + 1, + count, + ); + + const rows = Math.ceil(count / cols); + grid = { cols, rows, occupied: rows }; + cell_height = tile_height; + padding = SCROLL_PADDING; + } + } + + const widest = new Map(groups.map((x) => [x.position, x.widest])); + const sizes = tiles.map((em, index) => { + const fit = fits.get(em.position)!; + const w = tile_width(index, count, grid.cols, grid.occupied, box_width); + return fit_value( + w, + cell_height, + padding, + fit.label, + uniform ? widest.get(em.position)! : em, + fit.placement, + extra, + ); + }); + + const shared = Math.min(...sizes); + const value_sizes = sizes.map((x) => { + const px = (uniform ? shared : x) * FIT_SLACK; + return Math.max(1, Math.floor(px * 2) / 2); + }); + + return { + cols: grid.cols, + rows: grid.rows, + tile_height, + padding, + placements: tiles.map((x) => fits.get(x.position)!.placement), + label_sizes: tiles.map((x) => fits.get(x.position)!.label), + value_sizes, + }; +} + +/** Whether this browser's CSS has `round()`, absent before Chrome 125. */ +const CSS_ROUND = + typeof CSS !== "undefined" && + CSS.supports("width", "round(down, 1px, 0.5px)"); + +function num(x: number): string { + return String(Number(x.toFixed(4))); +} + +/** + * {@link fit_value} as a CSS length, for a content box of `iw` by `ih` and a + * label font size of `label`, all CSS lengths. + */ +function css_fit( + iw: string, + ih: string, + label: string, + em: Metrics, + placement: LabelPlacement, + extra: number, +): string { + const lines = num(VALUE_LINE_HEIGHT + extra); + const value = num(em.value); + if (placement === "none") { + return `min(${ih} / ${lines}, ${iw} / ${value})`; + } + + if (is_stacked(placement)) { + return `min((${ih} - ${label} * ${num(LABEL_LINE_HEIGHT * em.lines)}) / ${lines}, ${iw} / ${value})`; + } + + return `min(${ih} / ${lines}, (${iw} - min(${label} * ${num(em.label)}, ${iw} * ${INLINE_LABEL_MAX}) - ${label} * ${INLINE_LABEL_GAP}) / ${value})`; +} + +/** The final value font size for the fit `fit`, as `compute_layout` rounds it. */ +function css_size(fit: string): string { + return CSS_ROUND + ? `max(1px, round(down, ${fit} * ${FIT_SLACK}, 0.5px))` + : `max(1px, ${fit} * ${FIT_SLACK})`; +} + +/** + * The shared value font size of a flat, uniform `layout` as a CSS length in + * the container units of the tile grid, sized to a full row's cell. + */ +export function uniform_value_css( + layout: Layout, + tiles: TileMetrics[], + extra: number, +): string | undefined { + if (tiles.length === 0) { + return undefined; + } + + const padding = num(2 * layout.padding); + const iw = `((100cqw - ${(layout.cols - 1) * GAP}px) / ${layout.cols} - ${padding}px)`; + const ih = + layout.tile_height === undefined + ? `((100cqh - ${(layout.rows - 1) * GAP}px) / ${layout.rows} - ${padding}px)` + : `${num(layout.tile_height - 2 * layout.padding)}px`; + + const fits = group_tiles(tiles).map(({ position, widest }) => { + const index = tiles.findIndex((x) => x.position === position); + return css_fit( + iw, + ih, + `${num(layout.label_sizes[index])}px`, + widest, + layout.placements[index], + extra, + ); + }); + + return css_size(fits.length === 1 ? fits[0] : `min(${fits.join(", ")})`); +} + +/** + * One tile's value font size as a CSS length in the container units of the + * tile itself, its label size read from `--psp-summary--label-size`. + */ +export function tile_value_css( + em: Metrics, + placement: LabelPlacement, + extra: number, +): string { + return css_size( + css_fit( + "100cqw", + "100cqh", + "var(--psp-summary--label-size)", + em, + placement, + extra, + ), + ); +} + +export const GROUP_HEADER = 20; +export const GROUP_PAD = 4; +export const GROUP_GAP = 4; +export const SPLIT_STEPS = 64; + +const STACKED: Grid = { cols: 1, rows: 2, occupied: 2 }; +const BESIDE: Grid = { cols: 2, rows: 1, occupied: 1 }; + +function header_of(node: TileGroup): number { + return node.label === undefined ? 0 : GROUP_HEADER; +} + +function pad_of(node: TileGroup): number { + return node.label === undefined ? 0 : GROUP_PAD; +} + +interface Choice { + value: number; + grid: Grid; + split?: number; +} + +/** Fits the groups of one tree to boxes, memoized by group shape and size. */ +/** + * The share in `[lo, hi]` whose smaller value is largest, given that the + * first value grows with the share and the second shrinks. + */ +function balance( + values: (k: number) => [number, number], + lo: number, + hi: number, +): { split: number; value: number } { + while (lo < hi) { + const mid = (lo + hi) >> 1; + const [t, g] = values(mid); + if (t >= g) { + hi = mid; + } else { + lo = mid + 1; + } + } + + const value = Math.min(...values(lo)); + const below = lo > 1 ? Math.min(...values(lo - 1)) : -Infinity; + return below > value + ? { split: lo - 1, value: below } + : { split: lo, value }; +} + +class HierarchyFit { + private shapes = new Map(); + private ids = new Map(); + private memos = new Map>>(); + private by_shape: Map>[] = []; + private groups: Group[]; + private extra: number; + private grid_columns: number | undefined; + private grid_rows: number | undefined; + + constructor( + groups: Group[], + extra: number, + grid_columns: number | undefined, + grid_rows: number | undefined, + ) { + this.groups = groups; + this.extra = extra; + this.grid_columns = grid_columns; + this.grid_rows = grid_rows; + } + + shape(node: TileGroup): string { + let shape = this.shapes.get(node); + if (shape === undefined) { + shape = `${node.label === undefined ? "u" : "h"}${node.rollup ? "r" : ""}${node.tiles.length}[${node.groups.map((x) => this.shape(x)).join(",")}]`; + this.shapes.set(node, shape); + } + + return shape; + } + + /** The memo of `node`, shared by every group of the same shape. */ + private memo(node: TileGroup): Map> { + let memo = this.memos.get(node); + if (memo === undefined) { + const shape = this.shape(node); + let id = this.ids.get(shape); + if (id === undefined) { + id = this.by_shape.push(new Map()) - 1; + this.ids.set(shape, id); + } + + memo = this.by_shape[id]; + this.memos.set(node, memo); + } + + return memo; + } + + /** The grid of `node`'s items that fits a `(w, h)` content box best. */ + choose(node: TileGroup, w: number, h: number): Choice { + const memo = this.memo(node); + let by_height = memo.get(w); + if (by_height === undefined) { + by_height = new Map(); + memo.set(w, by_height); + } + + const cached = by_height.get(h); + if (cached !== undefined) { + return cached; + } + + const choice = node.rollup + ? this.choose_split(node, w, h) + : this.choose_grid(node, w, h); + + by_height.set(h, choice); + return choice; + } + + /** A rollup's totals and groups values when its totals take `k` steps. */ + private split_values( + node: TileGroup, + stacked: boolean, + w: number, + h: number, + ): (k: number) => [number, number] { + const [totals, groups] = node.groups; + const length = (stacked ? h : w) - GROUP_GAP; + return (k) => { + const first = (length * k) / SPLIT_STEPS; + return stacked + ? [ + this.choose(totals, w, first).value, + this.choose(groups, w, length - first).value, + ] + : [ + this.choose(totals, first, h).value, + this.choose(groups, length - first, h).value, + ]; + }; + } + + /** + * The orientation and share of a rollup's length for its totals that + * gives the largest value text, the smallest such share. + */ + private choose_split(node: TileGroup, w: number, h: number): Choice { + let best: Choice = { + value: 0, + grid: STACKED, + split: SPLIT_STEPS / 2, + }; + + for (const grid of [STACKED, BESIDE]) { + const stacked = grid === STACKED; + if ((stacked ? h : w) <= GROUP_GAP || (stacked ? w : h) <= 0) { + continue; + } + + const { split, value } = balance( + this.split_values(node, stacked, w, h), + 1, + SPLIT_STEPS - 1, + ); + + if (value > best.value) { + best = { value, grid, split }; + } + } + + return best; + } + + /** + * The largest share of a rollup's length for its totals that keeps the + * value text of `choice`, whose share is the smallest that does. + */ + private widen_split( + node: TileGroup, + w: number, + h: number, + choice: Choice, + ): number { + const values = this.split_values(node, choice.grid.cols === 1, w, h); + let split = choice.split!; + const [t, g] = values(split); + if (t < g) { + return split; + } + + let end = SPLIT_STEPS - 1; + while (split < end) { + const mid = (split + end + 1) >> 1; + if (values(mid)[1] >= g) { + split = mid; + } else { + end = mid - 1; + } + } + + return split; + } + + private choose_grid(node: TileGroup, w: number, h: number): Choice { + const leaf = node.groups.length === 0; + const count = leaf ? node.tiles.length : node.groups.length; + const gap = leaf ? GAP : GROUP_GAP; + let choice: Choice = { + value: 0, + grid: { cols: 1, rows: 1, occupied: 1 }, + }; + + if (count > 0 && w > 0 && h > 0) { + const explicit = leaf + ? explicit_grid(count, this.grid_columns, this.grid_rows) + : undefined; + + const grids = + explicit !== undefined + ? [ + { + ...explicit, + rows: Math.max(explicit.rows, explicit.occupied), + }, + ] + : Array.from({ length: count }, (_, i) => { + const rows = Math.ceil(count / (i + 1)); + return { cols: i + 1, rows, occupied: rows }; + }); + + let total = Infinity; + let best: Choice | undefined; + for (const grid of grids) { + const cw = (w - (grid.cols - 1) * gap) / grid.cols; + const ch = (h - (grid.rows - 1) * gap) / grid.rows; + const value = leaf + ? fit_groups(cw, ch, this.groups, this.extra).value + : Math.min( + ...node.groups.map( + (child) => + this.choose( + child, + cw - 2 * pad_of(child), + ch - header_of(child) - pad_of(child), + ).value, + ), + ); + + const cells = grid.cols * grid.rows; + if ( + best === undefined || + value > best.value || + (value === best.value && cells < total) + ) { + best = { value, grid }; + total = cells; + } + } + + choice = best!; + } + + return choice; + } + + /** + * Record the grid of `node` and every group in it for a content box, and + * the box each tile gets. + */ + place( + node: TileGroup, + box: Rect, + tile_rects: Rect[], + containers: Map, + ): void { + const choice = this.choose(node, box.width, box.height); + const { grid } = choice; + if (node.rollup && choice.split !== undefined) { + const [totals, groups] = node.groups; + const split = this.widen_split(node, box.width, box.height, choice); + const stacked = grid.cols === 1; + const length = (stacked ? box.height : box.width) - GROUP_GAP; + const first = (length * split) / SPLIT_STEPS; + containers.set(node, { + cols: grid.cols, + rows: grid.rows, + last: grid.cols, + split, + }); + + this.place( + totals, + stacked ? { ...box, height: first } : { ...box, width: first }, + tile_rects, + containers, + ); + + this.place( + groups, + stacked + ? { + ...box, + top: box.top + first + GROUP_GAP, + height: length - first, + } + : { + ...box, + left: box.left + first + GROUP_GAP, + width: length - first, + }, + tile_rects, + containers, + ); + + return; + } + + const leaf = node.groups.length === 0; + const count = leaf ? node.tiles.length : node.groups.length; + const gap = leaf ? GAP : GROUP_GAP; + const cell_height = (box.height - (grid.rows - 1) * gap) / grid.rows; + containers.set(node, { + cols: grid.cols, + rows: grid.rows, + last: count - (grid.occupied - 1) * grid.cols, + }); + + for (let i = 0; i < count; i++) { + const row = Math.floor(i / grid.cols); + const in_row = + row < grid.occupied - 1 + ? grid.cols + : count - (grid.occupied - 1) * grid.cols; + + const width = (box.width - (in_row - 1) * gap) / in_row; + const rect = { + left: box.left + (i - row * grid.cols) * (width + gap), + top: box.top + row * (cell_height + gap), + width, + height: cell_height, + }; + + if (leaf) { + tile_rects[node.tiles[i]] = rect; + } else { + const child = node.groups[i]; + const pad = pad_of(child); + const header = header_of(child); + this.place( + child, + { + left: rect.left + pad, + top: rect.top + header, + width: rect.width - 2 * pad, + height: rect.height - header - pad, + }, + tile_rects, + containers, + ); + } + } + } +} + +/** + * Record `node`'s groups as full-width sections of fixed-height tile rows, + * and the box each tile gets. + */ +function stack( + node: TileGroup, + width: number, + tile: { width: number; height: number }, + tile_rects: Rect[], + containers: Map, +): void { + if (node.groups.length === 0) { + const count = node.tiles.length; + const cols = clamp( + Math.floor((width + GAP) / (tile.width + GAP)), + 1, + Math.max(1, count), + ); + + const occupied = Math.ceil(count / cols); + containers.set(node, { + cols, + rows: undefined, + last: count - (occupied - 1) * cols, + }); + + node.tiles.forEach((index, i) => { + const row = Math.floor(i / cols); + const in_row = + row < occupied - 1 ? cols : count - (occupied - 1) * cols; + + tile_rects[index] = { + left: 0, + top: 0, + width: (width - (in_row - 1) * GAP) / in_row, + height: tile.height, + }; + }); + + return; + } + + containers.set(node, { cols: 1, rows: undefined, last: 1 }); + for (const child of node.groups) { + stack(child, width - 2 * pad_of(child), tile, tile_rects, containers); + } +} + +/** + * The grids and font sizes that give `input.tiles`, nested as `tree`, the + * largest value text in a `(width, height)` box, falling back to scrolling + * full-width sections when that text would be too small to read. + */ +export function compute_hierarchy_layout( + input: LayoutInput, + tree: TileGroup, +): Layout { + const { width, height, tiles, uniform, extra } = input; + const count = tiles.length; + if (count === 0 || width <= 0 || height <= 0) { + return compute_layout(input); + } + + const groups = group_tiles(tiles); + const widest = new Map(groups.map((x) => [x.position, x.widest])); + const fitter = new HierarchyFit( + groups, + extra, + input.grid_columns, + input.grid_rows, + ); + + const tile_rects: Rect[] = new Array(count); + const containers = new Map(); + let tile_height: number | undefined; + let fits: Map; + const best = fitter.choose(tree, width, height); + if (best.value * FIT_SLACK >= MIN_VALUE_SIZE) { + fitter.place( + tree, + { left: 0, top: 0, width, height }, + tile_rects, + containers, + ); + + fits = new Map(); + for (const { position, widest: em } of groups) { + const rects = tiles.flatMap((x, i) => + x.position === position ? [tile_rects[i]] : [], + ); + + fits.set( + position, + best_fit( + Math.min(...rects.map((x) => x.width)), + Math.min(...rects.map((x) => x.height)), + em, + position, + extra, + ), + ); + } + } else { + fits = new Map(); + let min_width = 0; + tile_height = 0; + for (const { position, widest: em } of groups) { + const placement = placement_of(position); + const label = placement === "none" ? 0 : LABEL_MIN; + const inline = placement === "left" || placement === "right"; + fits.set(position, { + value: 0, + label, + padding: SCROLL_PADDING, + placement, + }); + + tile_height = Math.max( + tile_height, + Math.ceil( + (MIN_VALUE_SIZE / FIT_SLACK) * (VALUE_LINE_HEIGHT + extra) + + (is_stacked(placement) + ? label * LABEL_LINE_HEIGHT * em.lines + : 0) + + 2 * SCROLL_PADDING, + ), + ); + + min_width = Math.max( + min_width, + (MIN_VALUE_SIZE / FIT_SLACK) * em.value + + (inline ? (em.label + INLINE_LABEL_GAP) * label : 0) + + 2 * SCROLL_PADDING, + ); + } + + stack( + tree, + Math.max(1, width - SCROLLBAR), + { width: min_width, height: tile_height }, + tile_rects, + containers, + ); + } + + const sizes = tiles.map((em, index) => { + const fit = fits.get(em.position)!; + const rect = tile_rects[index]; + return fit_value( + rect.width, + rect.height, + fit.padding, + fit.label, + uniform ? widest.get(em.position)! : em, + fit.placement, + extra, + ); + }); + + const shared = Math.min(...sizes); + return { + cols: 1, + rows: 1, + tile_height, + padding: fits.values().next().value!.padding, + placements: tiles.map((x) => fits.get(x.position)!.placement), + label_sizes: tiles.map((x) => fits.get(x.position)!.label), + value_sizes: sizes.map((x) => { + const px = (uniform ? shared : x) * FIT_SLACK; + return Math.max(1, Math.floor(px * 2) / 2); + }), + containers, + paddings: tiles.map((x) => fits.get(x.position)!.padding), + }; +} diff --git a/packages/viewer-summary/src/ts/plugin_utils.ts b/packages/viewer-summary/src/ts/plugin_utils.ts new file mode 100644 index 0000000000..099201c543 --- /dev/null +++ b/packages/viewer-summary/src/ts/plugin_utils.ts @@ -0,0 +1,21 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { PluginUtils } from "@perspective-dev/viewer"; + +let UTILS: PluginUtils | undefined; + +/** The code `` shares with its plugins. */ +export function plugin_utils(): PluginUtils { + UTILS ??= customElements.get("perspective-viewer").plugin_utils; + return UTILS; +} diff --git a/packages/viewer-summary/src/ts/schema.ts b/packages/viewer-summary/src/ts/schema.ts new file mode 100644 index 0000000000..bb6592b802 --- /dev/null +++ b/packages/viewer-summary/src/ts/schema.ts @@ -0,0 +1,215 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { ColumnType } from "@perspective-dev/client"; +import type { + Align, + ColumnConfigSchema, + ColumnRole, + ControlSpec, + ThemeStyle, +} from "@perspective-dev/viewer"; +import { plugin_utils } from "./plugin_utils.ts"; +import { + LABEL_POSITIONS, + LAYOUT_MODES, + VALUE_FITS, + type ColumnConfig, + type LabelPosition, + type ResolvedPluginConfig, + type SummaryPluginConfig, +} from "./types.ts"; + +const MAX_GRID = 100; + +const LABEL_VARIANTS = variants(LABEL_POSITIONS, { + auto: "Auto", + top: "Top", + bottom: "Bottom", + left: "Left", + right: "Right", + none: "Hidden", +}); + +function one_of( + values: readonly T[], + raw: unknown, +): T | undefined { + return (values as readonly unknown[]).includes(raw) + ? (raw as T) + : undefined; +} + +/** `raw` as a {@link LabelPosition}, else `undefined`. */ +export function parse_label_position(raw: unknown): LabelPosition | undefined { + return one_of(LABEL_POSITIONS, raw); +} + +/** `raw` as a fixed count of grid tracks, else `undefined` for automatic. */ +function parse_grid(raw: unknown): number | undefined { + return typeof raw === "number" && Number.isFinite(raw) && raw >= 1 + ? Math.min(Math.floor(raw), MAX_GRID) + : undefined; +} + +/** A `plugin_config` token with every unset or invalid key defaulted. */ +export function parse_plugin_config(raw: unknown): ResolvedPluginConfig { + const token = ( + raw !== null && typeof raw === "object" ? raw : {} + ) as Record; + + return { + label_position: parse_label_position(token.label_position) ?? "auto", + value_fit: one_of(VALUE_FITS, token.value_fit) ?? "uniform", + layout_mode: one_of(LAYOUT_MODES, token.layout_mode) ?? "flat", + grid_columns: parse_grid(token.grid_columns), + grid_rows: parse_grid(token.grid_rows), + font_family: + typeof token.font_family === "string" && + token.font_family !== "inherit" + ? token.font_family + : undefined, + bold: token.bold === true, + italic: token.italic === true, + align: plugin_utils().schema.ALIGNS.includes(token.align as Align) + ? (token.align as Align) + : undefined, + }; +} + +function font_group( + defaults: Pick< + ResolvedPluginConfig, + "font_family" | "bold" | "italic" | "align" + >, +): ControlSpec { + return { + kind: "Group", + key: "font", + fields: [ + { + kind: "Font", + key: "font_family" satisfies keyof ColumnConfig & + keyof SummaryPluginConfig, + default: defaults.font_family ?? "inherit", + bold: { + key: "bold" satisfies keyof ColumnConfig, + default: defaults.bold, + }, + italic: { + key: "italic" satisfies keyof ColumnConfig, + default: defaults.italic, + }, + }, + { + kind: "Alignment", + key: "align" satisfies keyof ColumnConfig, + ...(defaults.align !== undefined + ? { default: defaults.align } + : {}), + }, + ], + }; +} + +/** The Style-tab controls of one Summary column. */ +export function summary_column_config_schema( + type: ColumnType, + current_value: Record | null, + plugin: ResolvedPluginConfig, + role: ColumnRole | undefined, + theme: () => ThemeStyle, +): ColumnConfigSchema { + const { color_group, format_fields } = plugin_utils().schema; + if (role === "group_by" || role === "split_by") { + return { fields: format_fields(type) }; + } + + const fields: ControlSpec[] = [ + { + kind: "Enum", + key: "label_position" satisfies keyof ColumnConfig, + default: plugin.label_position, + variants: LABEL_VARIANTS, + }, + font_group({ + ...plugin, + align: + plugin.align ?? + (type === "integer" || type === "float" ? "right" : "left"), + }), + ]; + + const colors = color_group(type, current_value, theme); + if (colors !== undefined) { + fields.push(colors); + } + + fields.push(...format_fields(type)); + return { fields }; +} + +function variants(values: readonly string[], labels: Record) { + return values.map((value) => ({ value, label: labels[value] })); +} + +/** The Summary's plugin-level settings. */ +export function summary_plugin_config_schema(): ColumnConfigSchema { + const fields: ControlSpec[] = [ + { + kind: "Enum", + key: "label_position" satisfies keyof SummaryPluginConfig, + default: "auto", + variants: LABEL_VARIANTS, + }, + { + kind: "Enum", + key: "value_fit" satisfies keyof SummaryPluginConfig, + default: "uniform", + variants: variants(VALUE_FITS, { + uniform: "Uniform", + independent: "Per Tile", + }), + }, + { + kind: "Enum", + key: "layout_mode" satisfies keyof SummaryPluginConfig, + default: "flat", + variants: variants(LAYOUT_MODES, { + flat: "Flat", + hierarchy: "Hierarchy", + }), + }, + ]; + + for (const key of ["grid_columns", "grid_rows"] as const) { + fields.push({ + kind: "Number", + key: key satisfies keyof SummaryPluginConfig, + default: 0, + min: 0, + max: MAX_GRID, + step: 1, + }); + } + + fields.push( + font_group({ + font_family: undefined, + bold: false, + italic: false, + align: undefined, + }), + ); + + return { fields }; +} diff --git a/packages/viewer-summary/src/ts/summary.ts b/packages/viewer-summary/src/ts/summary.ts new file mode 100644 index 0000000000..472e87d7d8 --- /dev/null +++ b/packages/viewer-summary/src/ts/summary.ts @@ -0,0 +1,874 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { + ColumnType, + ColumnWindow, + Filter, + Scalar, + View, + ViewConfig, + ViewWindow, +} from "@perspective-dev/client"; +import type { + Align, + CellStyleModel, + ColumnConfigSchema, + ColumnRole, + HTMLPerspectiveViewerElement, + IPerspectiveViewerPlugin, + PerspectiveClickEventDetail, + PluginStaticConfig, + ThemeStyle, +} from "@perspective-dev/viewer"; +import summaryStyles from "../../dist/css/perspective-viewer-summary.css"; +import { + SPLIT_STEPS, + TRACK_EXTRA, + compute_hierarchy_layout, + compute_layout, + tile_value_css, + uniform_value_css, + type Layout, + type TileMetrics, +} from "./layout.ts"; +import { plugin_utils } from "./plugin_utils.ts"; +import { + parse_label_position, + parse_plugin_config, + summary_column_config_schema, + summary_plugin_config_schema, +} from "./schema.ts"; +import { build_tiles, build_tree } from "./tiles.ts"; +import type { + ColumnsConfig, + ResolvedColumnsConfig, + ResolvedPluginConfig, + Schema, + Tile, + TileGroup, +} from "./types.ts"; + +const MEASURE_PX = 100; +const MIN_EM_WIDTH = 0.6; +const METRIC_CACHE_LIMIT = 4096; +const LABEL_PLACEMENTS = ["top", "bottom", "left", "right", "none"] as const; +const EXPORT_LABEL_SEPARATOR = " · "; + +const FLEX_ALIGN = { start: "flex-start", center: "center", end: "flex-end" }; +const TEXT_ALIGN = { start: "left", center: "center", end: "right" }; + +interface TileElements { + tile: HTMLElement; + label: HTMLElement; + value: HTMLElement; +} + +interface ViewState { + config: ViewConfig; + schema: Schema; + split_types: ColumnType[]; +} + +interface ThemeFont { + family: string; + weight: string; + style: string; +} + +function horizontal(align: Align): keyof typeof FLEX_ALIGN { + return align.endsWith("left") + ? "start" + : align.endsWith("right") + ? "end" + : "center"; +} + +function vertical(align: Align): keyof typeof FLEX_ALIGN { + return align.startsWith("top") + ? "start" + : align.startsWith("bottom") + ? "end" + : "center"; +} + +function is_numeric(type: ColumnType): boolean { + return type === "integer" || type === "float"; +} + +/** + * The `` Summary plugin, which draws the grand-total row + * of a `View` as one fitted tile per column. + */ +export class HTMLPerspectiveViewerSummaryPluginElement + extends HTMLElement + implements IPerspectiveViewerPlugin +{ + private static _sheet: CSSStyleSheet | undefined; + private static _measure: CanvasRenderingContext2D | null | undefined; + + private _container: HTMLElement; + private _config: ResolvedPluginConfig = parse_plugin_config(undefined); + private _styles: ResolvedColumnsConfig = {}; + private _theme?: ThemeStyle; + private _font?: ThemeFont; + private _view_state?: ViewState; + private _tiles: Tile[] = []; + private _elements: TileElements[] = []; + private _tree?: TileGroup; + private _bodies: Map = new Map(); + private _nested = false; + private _metrics: TileMetrics[] = []; + private _row: Record = {}; + private _previous?: Map; + private _is_new_view = false; + private _metric_cache: Map = new Map(); + private _series_color_map: Map> = new Map(); + private _series_color_seed: Map = new Map(); + + private _on_click = (event: MouseEvent): void => { + const target = event.target as Element | null; + const tile_elem = target?.closest?.(".tile") as HTMLElement | null; + const index = Number(tile_elem?.dataset.index); + const tile = this._tiles[index]; + const state = this._view_state; + const viewer = this + .parentElement as HTMLPerspectiveViewerElement | null; + if (!tile || !state || !viewer) { + return; + } + + const split_by = state.config.split_by ?? []; + const filter: Filter[] = [...(state.config.filter ?? [])]; + tile.split.forEach((value, level) => { + if (value !== null) { + filter.push([split_by[level], "==", value] as Filter); + } + }); + + viewer.dispatchEvent( + new CustomEvent("perspective-click", { + bubbles: true, + composed: true, + detail: { + row: this._row, + column_names: [tile.name], + config: { filter }, + panel: this.getAttribute("slot") ?? undefined, + }, + }), + ); + }; + + constructor() { + super(); + const Elem = HTMLPerspectiveViewerSummaryPluginElement; + if (!Elem._sheet) { + Elem._sheet = new CSSStyleSheet(); + Elem._sheet.replaceSync( + plugin_utils().cell_style.css + summaryStyles, + ); + } + + const shadow = this.attachShadow({ mode: "open" }); + shadow.adoptedStyleSheets.push(Elem._sheet); + this._container = document.createElement("div"); + this._container.id = "tiles"; + this._container.addEventListener("click", this._on_click); + shadow.appendChild(this._container); + } + + get_static_config(): PluginStaticConfig { + return { + name: "Summary", + category: "Basic", + select_mode: "toggle", + config_column_names: ["Columns"], + group_rollup_modes: ["total"], + split_rollup_modes: ["flat", "rollup"], + priority: 0, + max_columns: 100, + can_render_column_styles: true, + renders_text: true, + }; + } + + plugin_config_schema( + _view_config?: Record, + _current_value?: Record | null, + ): ColumnConfigSchema { + return summary_plugin_config_schema(); + } + + column_config_schema( + type: string, + _group: string | undefined, + _column_name: string, + current_value: Record | null, + _viewer_config?: Record, + plugin_config?: Record | null, + role?: ColumnRole, + ): ColumnConfigSchema { + return summary_column_config_schema( + type as ColumnType, + current_value, + plugin_config === undefined || plugin_config === null + ? this._config + : parse_plugin_config(plugin_config), + role, + () => + this._theme ?? plugin_utils().theme_style.readThemeStyle(this), + ); + } + + async draw(view: View, column_limit?: number | null): Promise { + const viewer = this + .parentElement as HTMLPerspectiveViewerElement | null; + const panel = this.getAttribute("slot") ?? undefined; + const table = await viewer?.getTable?.({ panel }); + const [config, schema, expression_schema, table_schema] = + await Promise.all([ + view.get_config(), + view.schema(), + view.expression_schema(), + table?.schema() ?? {}, + ]); + + const types: Schema = { + ...(table_schema as Schema), + ...(expression_schema as Schema), + }; + + this._view_state = { + config: config as ViewConfig, + schema: { ...(schema as Schema), ...(expression_schema as Schema) }, + split_types: (config.split_by ?? []).map( + (name: string) => types[name] ?? "string", + ), + }; + + this._is_new_view = true; + this._previous = undefined; + this._series_color_map.clear(); + this._series_color_seed.clear(); + await this._load(view, column_limit); + } + + async update(view: View, column_limit?: number | null): Promise { + if (this._view_state === undefined) { + await this.draw(view, column_limit); + return; + } + + await this._load(view, column_limit); + } + + async resize(): Promise { + if (!this.isConnected || this.offsetParent == null) { + return; + } + + this._apply(this._plan(this.clientWidth, this.clientHeight)); + } + + async presize(width: number, height: number): Promise<(() => void) | void> { + if ( + !this.isConnected || + this.offsetParent == null || + this._tiles.length === 0 + ) { + return; + } + + const layout = this._plan(width, height); + return () => this._apply(layout); + } + + restyle(): void { + if (!this.isConnected || this._theme === undefined) { + return; + } + + this._read_theme(); + } + + restore(token: unknown, columns_config?: ColumnsConfig): void { + const utils = plugin_utils(); + this._config = parse_plugin_config(token); + const styles: ResolvedColumnsConfig = {}; + for (const [name, config] of Object.entries(columns_config ?? {})) { + styles[name] = utils.column_style.resolve_column_style( + JSON.parse(JSON.stringify(config)), + ); + } + + utils.format.free_formatters(this._styles); + this._styles = styles; + } + + async render(_view: View, _viewport?: ViewWindow): Promise { + return this._tiles + .map((x) => { + const label = [...x.path, x.name].join(EXPORT_LABEL_SEPARATOR); + return `${label}\t${x.text}`; + }) + .join("\n"); + } + + async clear(): Promise { + this._container.replaceChildren(); + this._elements = []; + this._bodies = new Map(); + this._nested = false; + this._tree = undefined; + this._tiles = []; + this._metrics = []; + this._previous = undefined; + } + + delete(): void { + plugin_utils().format.free_formatters(this._styles); + this._container.replaceChildren(); + this._elements = []; + this._bodies = new Map(); + this._nested = false; + this._tree = undefined; + this._tiles = []; + this._metrics = []; + this._previous = undefined; + this._view_state = undefined; + this._row = {}; + } + + private _read_theme(): void { + const style = window.getComputedStyle(this); + this._theme = plugin_utils().theme_style.readThemeStyle(this); + this._font = { + family: style.fontFamily, + weight: style.fontWeight, + style: style.fontStyle, + }; + + this._metric_cache.clear(); + } + + private async _load( + view: View, + column_limit?: number | null, + ): Promise { + const state = this._view_state!; + const split_by = state.config.split_by ?? []; + const limit = + typeof column_limit === "number" ? column_limit : undefined; + const window: ViewWindow = { + start_row: 0, + end_row: 1, + ...(limit !== undefined ? { start_col: 0, end_col: limit } : {}), + }; + + const column_window: ColumnWindow = { + start_col: 0, + end_col: limit ?? null, + }; + + const [data, area] = await Promise.all([ + view.to_columns(window), + split_by.length > 0 ? view.column_paths(column_window) : undefined, + ]); + + if (this._theme === undefined && this.isConnected) { + this._read_theme(); + } + + const source = data as Record; + this._row = Object.fromEntries( + Object.entries(source).map(([key, values]) => [key, values?.[0]]), + ); + + this._tiles = build_tiles({ + columns: source, + area: area as (Scalar | null | undefined)[][] | undefined, + schema: state.schema, + split_by, + split_types: state.split_types, + styles: this._styles, + hierarchy: this._config.layout_mode === "hierarchy", + }); + + const tree = + this._config.layout_mode === "hierarchy" + ? build_tree(this._tiles) + : undefined; + + this._tree = + tree !== undefined && tree.groups.length > 0 ? tree : undefined; + this._reconcile(); + this._sync_groups(); + this._paint(); + this._metrics = this._tiles.map((tile) => this._measure_tile(tile)); + if (this.isConnected && this.offsetParent != null) { + this._apply(this._plan(this.clientWidth, this.clientHeight)); + } + } + + private _reconcile(): void { + const same = + this._elements.length === this._tiles.length && + this._tiles.every( + (tile, index) => + this._elements[index].tile.dataset.key === tile.key, + ); + + if (same && !this._is_new_view) { + return; + } + + this._is_new_view = false; + this._previous = undefined; + this._elements = this._tiles.map((tile, index) => { + const elem = document.createElement("div"); + elem.className = "tile"; + elem.dataset.key = tile.key; + elem.dataset.index = String(index); + const label = document.createElement("div"); + label.className = "label"; + const body = document.createElement("div"); + body.className = "body"; + const value = document.createElement("div"); + value.className = "value"; + const track = document.createElement("div"); + track.className = "track"; + body.append(value, track); + elem.append(label, body); + return { tile: elem, label, value }; + }); + + this._container.replaceChildren(...this._elements.map((x) => x.tile)); + } + + private _sync_groups(): void { + const tiles = this._elements.map((x) => x.tile); + if (this._tree === undefined) { + if (this._nested) { + for (const tile of tiles) { + tile.style.removeProperty("--psp-summary--padding"); + tile.classList.remove("last-row"); + } + + this._container.replaceChildren(...tiles); + this._container.classList.remove( + "leaf", + "split-rows", + "split-columns", + ); + + for (const key of ["tracks", "span", "last-span", "split"]) { + this._container.style.removeProperty( + `--psp-summary--${key}`, + ); + } + + this._bodies = new Map(); + this._nested = false; + } + + return; + } + + const bodies = new Map(); + const fill = (node: TileGroup, body: HTMLElement): HTMLElement[] => { + bodies.set(node, body); + body.classList.toggle("leaf", node.groups.length === 0); + if (node.groups.length === 0) { + return node.tiles.map((index) => tiles[index]); + } + + return node.groups.map((child) => { + const group = document.createElement("div"); + group.className = "group"; + group.classList.toggle("headless", child.label === undefined); + if (child.label !== undefined) { + const header = document.createElement("div"); + header.className = "group-header"; + header.textContent = child.label; + header.title = child.label; + group.append(header); + } + + const child_body = document.createElement("div"); + child_body.className = "group-body"; + child_body.append(...fill(child, child_body)); + group.append(child_body); + return group; + }); + }; + + this._container.replaceChildren(...fill(this._tree, this._container)); + this._bodies = bodies; + this._nested = true; + } + + private _style_model(): CellStyleModel | undefined { + if (this._theme === undefined) { + return undefined; + } + + const previous = this._previous; + const keys = previous ? [...previous.keys()] : []; + return { + ...this._theme, + _series_color_map: this._series_color_map, + _series_color_seed: this._series_color_seed, + _config: { split_by: [] }, + _ids: [[]], + _column_paths: this._tiles.map((x) => x.key), + _is_old_viewport: previous !== undefined, + last_meta: previous + ? keys.map((key) => [previous.get(key)]) + : undefined, + last_reverse_ids: previous ? new Map([["", 0]]) : undefined, + last_reverse_columns: previous + ? new Map(keys.map((key, index) => [key, index])) + : undefined, + }; + } + + private _paint(): void { + const { + cell_style: { + cell_style_boolean, + cell_style_datetime, + cell_style_numeric, + cell_style_string, + }, + color: { infer_foreground_from_background, parseColor }, + schema: { css_font_family }, + } = plugin_utils(); + + const model = this._style_model(); + this._tiles.forEach((tile, index) => { + const { tile: elem, label, value } = this._elements[index]; + const plugin = this._styles[tile.name]; + const numeric = is_numeric(tile.type); + label.textContent = tile.label; + label.title = tile.label; + value.textContent = tile.text; + elem.dataset.column = tile.name; + elem.classList.toggle("psp-null", tile.value === null); + elem.classList.toggle( + "psp-color-mode-bar", + numeric && plugin?.fg_mode === "bar", + ); + + elem.classList.toggle( + "psp-color-mode-label-bar", + numeric && plugin?.fg_mode === "label-bar", + ); + + const family = plugin?.font_family ?? this._config.font_family; + value.style.fontFamily = + family && family !== "inherit" ? css_font_family(family) : ""; + + value.style.fontWeight = + (plugin?.bold ?? this._config.bold) ? "bold" : ""; + + value.style.fontStyle = + (plugin?.italic ?? this._config.italic) ? "italic" : ""; + + const align = + plugin?.align ?? + this._config.align ?? + (numeric ? "right" : "left"); + const h = horizontal(align); + elem.style.setProperty("--psp-summary--h", FLEX_ALIGN[h]); + elem.style.setProperty("--psp-summary--t", TEXT_ALIGN[h]); + elem.style.setProperty( + "--psp-summary--v", + FLEX_ALIGN[vertical(align)], + ); + if (model !== undefined) { + const metadata = { + user: tile.value, + value: tile.value, + dy: 0, + x: index, + column_header: [tile.name], + } as any; + + if (numeric) { + cell_style_numeric( + model, + plugin, + tile.type, + elem, + metadata, + false, + ); + } else if (tile.type === "boolean") { + cell_style_boolean(model, plugin, elem, metadata); + } else if (tile.type === "string") { + cell_style_string(model, plugin, elem, metadata); + } else if (tile.type === "date" || tile.type === "datetime") { + cell_style_datetime(model, plugin, elem, metadata); + } else { + elem.style.backgroundColor = ""; + elem.style.color = ""; + } + } + + const background = elem.style.backgroundColor; + if (background) { + elem.style.setProperty( + "--psp-summary--label--color", + infer_foreground_from_background(parseColor(background)), + ); + } else { + elem.style.removeProperty("--psp-summary--label--color"); + } + }); + + this._previous = new Map(this._tiles.map((x) => [x.key, x.value])); + } + + private _em_width(text: string, font: string): number { + const key = `${font}\n${text}`; + const cached = this._metric_cache.get(key); + if (cached !== undefined) { + return cached; + } + + const Elem = HTMLPerspectiveViewerSummaryPluginElement; + if (Elem._measure === undefined) { + Elem._measure = document.createElement("canvas").getContext("2d"); + } + + let width = text.length * MIN_EM_WIDTH; + if (Elem._measure) { + Elem._measure.font = font; + width = Elem._measure.measureText(text).width / MEASURE_PX; + } + + if (this._metric_cache.size >= METRIC_CACHE_LIMIT) { + this._metric_cache.clear(); + } + + const em = Math.max(width, MIN_EM_WIDTH); + this._metric_cache.set(key, em); + return em; + } + + private _measure_tile(tile: Tile): TileMetrics { + const base = this._font ?? { + family: "monospace", + weight: "normal", + style: "normal", + }; + + const plugin = this._styles[tile.name]; + const family = plugin?.font_family ?? this._config.font_family; + const value_family = + family && family !== "inherit" + ? `${plugin_utils().schema.css_font_family(family)}, ${base.family}` + : base.family; + + const weight = + (plugin?.bold ?? this._config.bold) ? "bold" : base.weight; + const style = + (plugin?.italic ?? this._config.italic) ? "italic" : base.style; + + const label_font = `${base.style} ${base.weight} ${MEASURE_PX}px ${base.family}`; + const lines = tile.label.split("\n"); + return { + value: this._em_width( + tile.text, + `${style} ${weight} ${MEASURE_PX}px ${value_family}`, + ), + label: Math.max(...lines.map((x) => this._em_width(x, label_font))), + lines: lines.length, + position: + parse_label_position(plugin?.label_position) ?? + this._config.label_position, + }; + } + + private _extra(): number { + const has_track = this._tiles.some( + (x) => + is_numeric(x.type) && this._styles[x.name]?.fg_mode === "bar", + ); + + return has_track ? TRACK_EXTRA : 0; + } + + private _plan(width: number, height: number): Layout { + const input = { + width, + height, + tiles: this._metrics, + uniform: this._config.value_fit === "uniform", + extra: this._extra(), + grid_columns: this._config.grid_columns, + grid_rows: this._config.grid_rows, + }; + + return this._tree + ? compute_hierarchy_layout(input, this._tree) + : compute_layout(input); + } + + private _apply(layout: Layout): void { + const container = this._container; + container.classList.toggle("scroll", layout.tile_height !== undefined); + const nested = layout.containers !== undefined; + const uniform = this._config.value_fit === "uniform"; + const extra = this._extra(); + container.classList.toggle("hierarchy", nested); + container.classList.toggle("tile-fit", !nested && !uniform); + container.style.setProperty("--psp-summary--cols", String(layout.cols)); + container.style.setProperty("--psp-summary--rows", String(layout.rows)); + container.style.setProperty( + "--psp-summary--padding", + `${layout.padding}px`, + ); + + if (layout.tile_height !== undefined) { + container.style.setProperty( + "--psp-summary--tile-height", + `${layout.tile_height}px`, + ); + } else { + container.style.removeProperty("--psp-summary--tile-height"); + } + + const shared = + !nested && uniform + ? uniform_value_css(layout, this._metrics, extra) + : undefined; + + if (shared === undefined) { + container.style.removeProperty("--psp-summary--value-size"); + } else { + container.style.setProperty("--psp-summary--value-size", shared); + } + + this._place(layout); + layout.value_sizes.forEach((size, index) => { + const tile = this._elements[index]?.tile; + if (tile === undefined) { + return; + } + + const value_size = nested + ? `${size}px` + : uniform + ? undefined + : tile_value_css( + this._metrics[index], + layout.placements[index], + extra, + ); + + if (value_size === undefined) { + tile.style.removeProperty("--psp-summary--value-size"); + } else if ( + tile.style.getPropertyValue("--psp-summary--value-size") !== + value_size + ) { + tile.style.setProperty("--psp-summary--value-size", value_size); + } + + tile.style.setProperty( + "--psp-summary--label-size", + `${layout.label_sizes[index]}px`, + ); + + for (const placement of LABEL_PLACEMENTS) { + tile.classList.toggle( + `label-${placement}`, + placement === layout.placements[index], + ); + } + }); + } + + private _place(layout: Layout): void { + const { containers, paddings } = layout; + if (containers === undefined) { + return; + } + + for (const [node, grid] of containers) { + const body = this._bodies.get(node); + if (body === undefined) { + continue; + } + + const short = grid.last < grid.cols; + body.style.setProperty( + "--psp-summary--tracks", + String(short ? grid.cols * grid.last : grid.cols), + ); + + body.style.setProperty( + "--psp-summary--span", + String(short ? grid.last : 1), + ); + + body.style.setProperty( + "--psp-summary--last-span", + String(short ? grid.cols : 1), + ); + + if (grid.rows === undefined) { + body.style.removeProperty("--psp-summary--rows"); + } else { + body.style.setProperty( + "--psp-summary--rows", + String(grid.rows), + ); + } + + const split = grid.split; + body.classList.toggle( + "split-rows", + split !== undefined && grid.cols === 1, + ); + + body.classList.toggle( + "split-columns", + split !== undefined && grid.cols !== 1, + ); + + if (split === undefined) { + body.style.removeProperty("--psp-summary--split"); + } else { + body.style.setProperty( + "--psp-summary--split", + `minmax(0, ${split}fr) minmax(0, ${SPLIT_STEPS - split}fr)`, + ); + } + + const items = [...body.children]; + const first_last = items.length - grid.last; + items.forEach((item, index) => + item.classList.toggle("last-row", short && index >= first_last), + ); + } + + paddings?.forEach((padding, index) => { + this._elements[index]?.tile.style.setProperty( + "--psp-summary--padding", + `${padding}px`, + ); + }); + } +} diff --git a/packages/viewer-summary/src/ts/tiles.ts b/packages/viewer-summary/src/ts/tiles.ts new file mode 100644 index 0000000000..22ff024f08 --- /dev/null +++ b/packages/viewer-summary/src/ts/tiles.ts @@ -0,0 +1,180 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { ColumnType, Scalar } from "@perspective-dev/client"; +import { plugin_utils } from "./plugin_utils.ts"; +import type { + ResolvedColumnsConfig, + Schema, + Tile, + TileGroup, +} from "./types.ts"; + +export const NULL_TEXT = "-"; + +export interface TileSource { + /** Row 0 of the view, as `View.to_columns` keys it. */ + columns: Record; + + /** `View.column_paths` for the same columns, absent without `split_by`. */ + area: (Scalar | null | undefined)[][] | undefined; + schema: Schema; + split_by: string[]; + split_types: ColumnType[]; + styles: ResolvedColumnsConfig; + + /** Whether tiles nest in groups, which then carry their split values. */ + hierarchy: boolean; +} + +interface Entry { + key: string; + name: string; + split: (Scalar | null)[]; + value: unknown; +} + +function format_value( + source: TileSource, + column: string, + type: ColumnType, + value: unknown, +): string { + if (value === null || value === undefined) { + return NULL_TEXT; + } + + const formatter = plugin_utils().format.format_raw( + type, + source.styles[column] ?? {}, + ); + + return formatter ? formatter.format(value as number) : String(value); +} + +function format_split( + source: TileSource, + level: number, + value: Scalar, +): string { + return format_value( + source, + source.split_by[level], + source.split_types[level] ?? "string", + value, + ); +} + +function entries(source: TileSource): Entry[] { + const { isMetaColumn } = plugin_utils().column_style; + const keys = Object.keys(source.columns).filter((x) => !isMetaColumn(x)); + const area = source.area; + const depth = area?.length ?? 1; + return keys.map((key, index) => ({ + key, + name: area ? String(area[depth - 1]?.[index] ?? key) : key, + split: area + ? area.slice(0, depth - 1).map((level) => level[index] ?? null) + : [], + value: source.columns[key]?.[0] ?? null, + })); +} + +function tile(source: TileSource, entry: Entry): Tile { + const type = source.schema[entry.name] ?? "string"; + const path = entry.split.flatMap((value, level) => + value === null ? [] : [format_split(source, level, value)], + ); + + return { + key: entry.key, + name: entry.name, + split: entry.split, + type, + value: entry.value, + text: format_value(source, entry.name, type, entry.value), + path, + label: source.hierarchy ? entry.name : [...path, entry.name].join("\n"), + }; +} + +/** + * The tiles of one view row, one per column, a `split_by` column labelled + * with its split values above its column name unless they nest in groups. + */ +export function build_tiles(source: TileSource): Tile[] { + return entries(source).map((entry) => tile(source, entry)); +} + +/** The split values of `tile` down to its first `null`, the rollup levels. */ +function prefix(tile: Tile): (Scalar | null)[] { + const end = tile.split.indexOf(null); + return end === -1 ? tile.split : tile.split.slice(0, end); +} + +/** + * `tiles` nested in a group per split value, level by level, the tiles of a + * group that also has groups moved into a first group with no header and its + * groups into a second. + */ +export function build_tree(tiles: Tile[]): TileGroup { + const root: TileGroup = { + key: "", + label: undefined, + tiles: [], + groups: [], + }; + const index = new Map(); + tiles.forEach((tile, i) => { + let node = root; + const levels = prefix(tile); + levels.forEach((_, depth) => { + const key = JSON.stringify(levels.slice(0, depth + 1)); + let child = index.get(key); + if (child === undefined) { + child = { key, label: tile.path[depth], tiles: [], groups: [] }; + index.set(key, child); + node.groups.push(child); + } + + node = child; + }); + + node.tiles.push(i); + }); + + const split_totals = (node: TileGroup) => { + node.groups.forEach(split_totals); + if (node.tiles.length > 0 && node.groups.length > 0) { + node.groups = [ + { + key: `${node.key}#totals`, + label: undefined, + tiles: node.tiles, + groups: [], + }, + { + key: `${node.key}#groups`, + label: undefined, + tiles: [], + groups: node.groups, + }, + ]; + + node.tiles = []; + node.rollup = true; + } + }; + + split_totals(root); + return root; +} diff --git a/packages/viewer-summary/src/ts/types.ts b/packages/viewer-summary/src/ts/types.ts new file mode 100644 index 0000000000..c1c092ae11 --- /dev/null +++ b/packages/viewer-summary/src/ts/types.ts @@ -0,0 +1,177 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import type { ColumnType, Scalar } from "@perspective-dev/client"; +import type { + Align, + ColumnStyleConfig, + Resolved, +} from "@perspective-dev/viewer"; + +/** Where a tile's column label sits relative to its value. */ +export type LabelPosition = + | "auto" + | "top" + | "bottom" + | "left" + | "right" + | "none"; + +/** Whether every tile shares one value text size or each fits its own. */ +export type ValueFit = "uniform" | "independent"; + +/** Whether `split_by` tiles form one grid or nest in a group per split value. */ +export type LayoutMode = "flat" | "hierarchy"; + +export const LABEL_POSITIONS = [ + "auto", + "top", + "bottom", + "left", + "right", + "none", +] as const satisfies readonly LabelPosition[]; + +export const VALUE_FITS = [ + "uniform", + "independent", +] as const satisfies readonly ValueFit[]; + +export const LAYOUT_MODES = [ + "flat", + "hierarchy", +] as const satisfies readonly LayoutMode[]; + +/** + * Summary per-column style configuration - one value of the `columns_config` + * map of a `ViewerConfigUpdate` when the Summary plugin is active, with the + * color and format keys of {@link ColumnStyleConfig}. + */ +export interface ColumnConfig extends ColumnStyleConfig { + /** Font family of this column's value, overriding `plugin_config.font_family`. */ + font_family?: string; + + /** Bold value text, overriding `plugin_config.bold`. */ + bold?: boolean; + + /** Italic value text, overriding `plugin_config.italic`. */ + italic?: boolean; + + /** Placement of this tile's content, overriding `plugin_config.align`. */ + align?: Align; + + /** Where this tile's label sits, overriding `plugin_config.label_position`. */ + label_position?: LabelPosition; +} + +export type ColumnsConfig = Record; + +/** Each column's {@link ColumnConfig} with its color strings parsed at `restore()`. */ +export type ResolvedColumnsConfig = Record>; + +export type Schema = Record; + +/** + * Summary plugin-level configuration - the `plugin_config` slot of a + * `ViewerConfigUpdate` when the Summary plugin is active. + */ +export interface SummaryPluginConfig { + /** + * Where each tile's column label sits: `"auto"` (default) picks `"top"` + * or `"left"`, whichever leaves the larger value text. + */ + label_position?: LabelPosition; + + /** + * `"uniform"` (default) sizes every value to the tightest tile's fit; + * `"independent"` fits each tile's value to its own text. + */ + value_fit?: ValueFit; + + /** + * `"flat"` (default) draws every `split_by` column as one grid of tiles; + * `"hierarchy"` nests them in a labelled group per split value, level + * by level, with any rollup totals first in each group. + */ + layout_mode?: LayoutMode; + + /** + * The number of tile columns, or `0` (default) to fit them to the + * panel; under `"hierarchy"`, of the tiles in each innermost group. + */ + grid_columns?: number; + + /** + * The number of tile rows in view, or `0` (default) to fit them to the + * panel; under `"hierarchy"`, of the tiles in each innermost group. + */ + grid_rows?: number; + + /** Font family of every value, `"inherit"` by default. */ + font_family?: string; + + /** Bold values unless a column's own `bold` overrides it. */ + bold?: boolean; + + /** Italic values unless a column's own `italic` overrides it. */ + italic?: boolean; + + /** + * Placement of each tile's content, by default `"right"` for numbers and + * `"left"` otherwise. + */ + align?: Align; +} + +/** A {@link SummaryPluginConfig} with every enum defaulted. */ +export interface ResolvedPluginConfig { + label_position: LabelPosition; + value_fit: ValueFit; + layout_mode: LayoutMode; + grid_columns: number | undefined; + grid_rows: number | undefined; + font_family: string | undefined; + bold: boolean; + italic: boolean; + align: Align | undefined; +} + +/** One tile: a column's value in the total row, formatted. */ +export interface Tile { + key: string; + name: string; + split: (Scalar | null)[]; + type: ColumnType; + value: unknown; + text: string; + + /** The tile's formatted split values, outermost first, without nulls. */ + path: string[]; + + /** The tile's column name, under `"flat"` after its split values, one per line. */ + label: string; +} + +/** A group of tiles under one split value, or the root of every group. */ +export interface TileGroup { + key: string; + + /** The group's split value, or `undefined` for a group with no header. */ + label: string | undefined; + + /** Indices of the tiles directly in this group, when it has no groups. */ + tiles: number[]; + groups: TileGroup[]; + + /** Whether `groups` is this group's rollup totals then its other groups. */ + rollup?: boolean; +} diff --git a/packages/viewer-summary/test/js/summary.spec.ts b/packages/viewer-summary/test/js/summary.spec.ts new file mode 100644 index 0000000000..39f73c44df --- /dev/null +++ b/packages/viewer-summary/test/js/summary.spec.ts @@ -0,0 +1,638 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +import { PageView, expect, test } from "@perspective-dev/test"; +import type { Page } from "@playwright/test"; + +const INACTIVE_DRAG = + "#sub-columns .column-selector-column:not(.column-selector-column-hidden) .column-selector-draggable"; + +interface TileInfo { + label: string; + text: string; + top: number; + left: number; + width: number; + value_size: number; + color: string; +} + +async function goto_ready(page: Page): Promise { + await page.goto("/tools/test/src/html/summary-test.html"); + await page.evaluate(async () => { + while (!(window as any)["__TEST_PERSPECTIVE_READY__"]) { + await new Promise((x) => setTimeout(x, 10)); + } + }); +} + +async function restore(page: Page, config: Record) { + await page.evaluate(async (config) => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.restore(config); + await viewer.flush(); + }, config); +} + +async function resize(page: Page, width: number, height: number) { + await page.setViewportSize({ width, height }); + await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.resize(); + await viewer.flush(); + }); +} + +async function read_tiles(page: Page): Promise { + return await page.evaluate(() => { + const plugin = document.querySelector("perspective-viewer-summary")!; + + return [...plugin.shadowRoot!.querySelectorAll(".tile")].map((tile) => { + const rect = tile.getBoundingClientRect(); + const value = tile.querySelector(".value")!; + return { + label: tile.querySelector(".label")!.textContent ?? "", + text: value.textContent ?? "", + top: Math.round(rect.top), + left: Math.round(rect.left), + width: rect.width, + value_size: parseFloat(getComputedStyle(value).fontSize), + color: getComputedStyle(tile).color, + }; + }); + }); +} + +interface Box { + left: number; + top: number; + right: number; + bottom: number; +} + +async function read_hierarchy(page: Page): Promise<{ + groups: (Box & { label: string })[]; + tiles: (Box & { label: string })[]; +}> { + return await page.evaluate(() => { + const plugin = document.querySelector("perspective-viewer-summary")!; + const box = (elem: Element) => { + const rect = elem.getBoundingClientRect(); + return { + left: rect.left, + top: rect.top, + right: rect.right, + bottom: rect.bottom, + }; + }; + + return { + groups: [ + ...plugin.shadowRoot!.querySelectorAll(".group:not(.headless)"), + ].map((group) => ({ + label: group.querySelector(".group-header")!.textContent ?? "", + ...box(group), + })), + tiles: [...plugin.shadowRoot!.querySelectorAll(".tile")].map( + (tile) => ({ + label: tile.querySelector(".label")!.textContent ?? "", + ...box(tile), + }), + ), + }; + }); +} + +function contains(outer: Box, inner: Box): boolean { + return ( + inner.left >= outer.left - 0.5 && + inner.top >= outer.top - 0.5 && + inner.right <= outer.right + 0.5 && + inner.bottom <= outer.bottom + 0.5 + ); +} + +async function plugin_width(page: Page): Promise { + return await page.evaluate( + () => + document + .querySelector("perspective-viewer-summary")! + .getBoundingClientRect().width, + ); +} + +async function formatted_totals(page: Page, columns: string[]) { + return await page.evaluate(async (columns) => { + const viewer = document.querySelector("perspective-viewer") as any; + const view = await viewer.getView(); + const data = await view.to_columns(); + const formatter = new Intl.NumberFormat( + navigator.languages as string[], + { + style: "decimal", + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }, + ); + + return columns.map((x) => formatter.format(data[x][0])); + }, columns); +} + +test.describe("Summary plugin", () => { + test.beforeEach(async ({ page }) => { + await goto_ready(page); + }); + + test("draws one tile per column from the total row", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + }); + + const saved = await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + return await viewer.save(); + }); + + expect(saved.group_rollup_mode).toEqual("total"); + const tiles = await read_tiles(page); + expect(tiles.map((x) => x.label)).toEqual(["Sales", "Profit"]); + expect(tiles.map((x) => x.text)).toEqual( + await formatted_totals(page, ["Sales", "Profit"]), + ); + }); + + test("grid shape follows the panel aspect ratio", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit", "Quantity", "Discount"], + }); + + await resize(page, 1600, 180); + const wide = await read_tiles(page); + expect(new Set(wide.map((x) => x.top)).size).toEqual(1); + + await resize(page, 300, 1000); + const tall = await read_tiles(page); + expect(new Set(tall.map((x) => x.left)).size).toEqual(1); + }); + + test("every row of tiles fills the panel width", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit", "Quantity", "Discount", "Row ID"], + }); + + await resize(page, 900, 700); + const tiles = await read_tiles(page); + const width = await plugin_width(page); + const rows = new Map(); + for (const tile of tiles) { + rows.set(tile.top, [...(rows.get(tile.top) ?? []), tile.width]); + } + + for (const widths of rows.values()) { + const total = widths.reduce((a, b) => a + b, 0) + widths.length - 1; + expect(Math.abs(total - width)).toBeLessThan(2); + } + }); + + test("value text grows with the panel", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + }); + + await resize(page, 600, 400); + const small = await read_tiles(page); + await resize(page, 1400, 1000); + const large = await read_tiles(page); + expect(large[0].value_size).toBeGreaterThan(small[0].value_size * 1.5); + expect(small[0].value_size).toEqual(small[1].value_size); + }); + + test("flat split_by draws a tile per split value", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales"], + split_by: ["Region"], + split_rollup_mode: "flat", + }); + + const tiles = await read_tiles(page); + expect(tiles.map((x) => x.label)).toEqual([ + "Central\nSales", + "East\nSales", + "South\nSales", + "West\nSales", + ]); + }); + + test("rollup split_by draws the total beside each split value", async ({ + page, + }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales"], + split_by: ["Region"], + split_rollup_mode: "rollup", + }); + + const tiles = await read_tiles(page); + expect(tiles.map((x) => x.label).sort()).toEqual([ + "Central\nSales", + "East\nSales", + "Sales", + "South\nSales", + "West\nSales", + ]); + + const total = tiles.find((x) => x.label === "Sales")!; + expect(total.text).toEqual( + (await formatted_totals(page, ["Sales"]))[0], + ); + }); + + test("a column's label_position overrides the plugin's", async ({ + page, + }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + plugin_config: { label_position: "left" }, + columns_config: { Profit: { label_position: "none" } }, + }); + + const labels = await page.evaluate(() => { + const plugin = document.querySelector( + "perspective-viewer-summary", + )!; + return [...plugin.shadowRoot!.querySelectorAll(".tile")].map( + (tile) => { + const label = tile.querySelector(".label")!; + const value = tile.querySelector(".value")!; + const display = getComputedStyle(label).display; + return { + display, + beside: + display !== "none" && + label.getBoundingClientRect().right <= + value.getBoundingClientRect().left, + }; + }, + ); + }); + + expect(labels).toEqual([ + { display: "block", beside: true }, + { display: "none", beside: false }, + ]); + }); + + test("grid_columns and grid_rows fix the grid shape", async ({ page }) => { + const columns = ["Sales", "Profit", "Quantity", "Discount"]; + await resize(page, 1600, 180); + await restore(page, { + plugin: "Summary", + columns, + plugin_config: { grid_columns: 1 }, + }); + + const stacked = await read_tiles(page); + expect(new Set(stacked.map((x) => x.left)).size).toEqual(1); + expect(new Set(stacked.map((x) => x.top)).size).toEqual(4); + + await resize(page, 300, 1000); + await restore(page, { + plugin: "Summary", + columns, + plugin_config: { grid_columns: 0, grid_rows: 1 }, + }); + + const row = await read_tiles(page); + expect(new Set(row.map((x) => x.top)).size).toEqual(1); + }); + + test("label-bar anchors positive and negative bars alike", async ({ + page, + }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Neg Sales"], + expressions: { "Neg Sales": '-"Sales"' }, + columns_config: { + Sales: { fg_mode: "label-bar", fg_gradient: 10000000 }, + "Neg Sales": { fg_mode: "label-bar", fg_gradient: 10000000 }, + }, + }); + + const positions = await page.evaluate(() => { + const plugin = document.querySelector( + "perspective-viewer-summary", + )!; + return [...plugin.shadowRoot!.querySelectorAll(".tile")].map( + (tile) => getComputedStyle(tile).backgroundPositionX, + ); + }); + + expect(positions).toEqual(["0%", "0%"]); + }); + + test("applies the column's Datagrid style keys", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales"], + columns_config: { + Sales: { + fg_color: + "linear-gradient(to right, #ff0000 0%, #00ff00 100%)", + number_format: { + minimumFractionDigits: 0, + maximumFractionDigits: 0, + }, + }, + }, + }); + + const [tile] = await read_tiles(page); + expect(tile.color).toEqual("rgb(0, 255, 0)"); + expect(tile.text).not.toContain("."); + }); + + test("an unset align follows the column type", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "State", "Profit"], + aggregates: { State: "dominant" }, + columns_config: { Profit: { align: "top" } }, + }); + + const aligns = await page.evaluate(() => { + const plugin = document.querySelector( + "perspective-viewer-summary", + )!; + return [...plugin.shadowRoot!.querySelectorAll(".tile")].map( + (tile) => { + const style = (tile as HTMLElement).style; + return [ + style.getPropertyValue("--psp-summary--h"), + style.getPropertyValue("--psp-summary--v"), + ]; + }, + ); + }); + + expect(aligns).toEqual([ + ["flex-end", "center"], + ["flex-start", "center"], + ["center", "flex-start"], + ]); + }); + + test("the plugin align control shows no default", async ({ page }) => { + await restore(page, { + plugin: "Summary", + settings: true, + columns: ["Sales", "Profit"], + }); + + const view = new PageView(page); + await view.container.locator("#plugin_tabbar_tab").click(); + const tab = view.container.locator("#plugin-tab"); + const font = tab.locator("details.control-group", { + has: page.locator("#font-group-label"), + }); + + await font.waitFor({ state: "visible" }); + if (!(await font.evaluate((el: HTMLDetailsElement) => el.open))) { + await font.locator("summary").click(); + } + + const grid = font.locator("#align-alignment"); + await expect(grid.locator("button")).toHaveCount(9); + await expect(grid.locator(".is-default")).toHaveCount(0); + }); + + test("dropping a column on the total group_by keeps total", async ({ + page, + }) => { + const view = new PageView(page); + await view.restore({ + plugin: "Summary", + settings: true, + columns: ["Sales"], + }); + + const source = view.container.locator(INACTIVE_DRAG).first(); + const target = view.container.locator("#group_by"); + await source.dragTo(target, { steps: 100 }); + await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + await viewer.flush(); + }); + + const config = await view.save(); + expect(config.plugin).toEqual("Summary"); + expect(config.group_rollup_mode).toEqual("total"); + expect(config.group_by).toEqual([]); + }); + + test("restoring a group_by keeps total", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales"], + group_by: ["Region"], + }); + + const saved = await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + return await viewer.save(); + }); + + expect(saved.group_rollup_mode).toEqual("total"); + expect(saved.group_by).toEqual([]); + expect((await read_tiles(page)).map((x) => x.label)).toEqual(["Sales"]); + }); + + test("hierarchy nests split_by tiles in a group per split value", async ({ + page, + }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + split_by: ["Region"], + split_rollup_mode: "flat", + plugin_config: { layout_mode: "hierarchy" }, + }); + + const { groups, tiles } = await read_hierarchy(page); + expect(groups.map((x) => x.label)).toEqual([ + "Central", + "East", + "South", + "West", + ]); + + expect(tiles.map((x) => x.label).sort()).toEqual([ + "Profit", + "Profit", + "Profit", + "Profit", + "Sales", + "Sales", + "Sales", + "Sales", + ]); + + for (const group of groups) { + expect(tiles.filter((x) => contains(group, x)).length).toEqual(2); + } + }); + + test("hierarchy puts rollup totals outside every group", async ({ + page, + }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + split_by: ["Region"], + split_rollup_mode: "rollup", + plugin_config: { layout_mode: "hierarchy" }, + }); + + const { groups, tiles } = await read_hierarchy(page); + expect(groups.length).toEqual(4); + expect(tiles.length).toEqual(10); + const outside = tiles.filter( + (tile) => !groups.some((group) => contains(group, tile)), + ); + + expect(outside.map((x) => x.label).sort()).toEqual(["Profit", "Sales"]); + }); + + test("hierarchy splits rollup totals from the groups", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + split_by: ["Region"], + split_rollup_mode: "rollup", + plugin_config: { layout_mode: "hierarchy" }, + }); + + const parts = await page.evaluate(() => { + const plugin = document.querySelector( + "perspective-viewer-summary", + )!; + const root = plugin.shadowRoot!.querySelector("#tiles")!; + return [...root.children].map((child) => ({ + headless: child.classList.contains("headless"), + tiles: child.querySelectorAll(":scope > .group-body > .tile") + .length, + groups: child.querySelectorAll(".group:not(.headless)").length, + })); + }); + + expect(parts).toEqual([ + { headless: true, tiles: 2, groups: 0 }, + { headless: true, tiles: 0, groups: 4 }, + ]); + + const { groups, tiles } = await read_hierarchy(page); + const totals = tiles.filter( + (tile) => !groups.some((group) => contains(group, tile)), + ); + + const above = totals.every((tile) => + groups.every((group) => tile.bottom <= group.top + 0.5), + ); + + const before = totals.every((tile) => + groups.every((group) => tile.right <= group.left + 0.5), + ); + + expect(above || before).toBe(true); + const extent = (boxes: Box[]) => + above + ? Math.max(...boxes.map((x) => x.right)) - + Math.min(...boxes.map((x) => x.left)) + : Math.max(...boxes.map((x) => x.bottom)) - + Math.min(...boxes.map((x) => x.top)); + + expect(Math.abs(extent(totals) - extent(groups))).toBeLessThan(1); + }); + + test("grid_columns fixes the tiles inside each hierarchy group", async ({ + page, + }) => { + await resize(page, 1600, 400); + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit", "Quantity"], + split_by: ["Region"], + split_rollup_mode: "flat", + plugin_config: { layout_mode: "hierarchy", grid_columns: 1 }, + }); + + const { groups, tiles } = await read_hierarchy(page); + for (const group of groups) { + const inner = tiles.filter((x) => contains(group, x)); + expect(inner.length).toEqual(3); + expect(new Set(inner.map((x) => Math.round(x.left))).size).toEqual( + 1, + ); + } + }); + + test("value text follows its box without a resize call", async ({ + page, + }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + }); + + const before = (await read_tiles(page))[0].value_size; + await page.evaluate(async () => { + const plugin = document.querySelector( + "perspective-viewer-summary", + ) as HTMLElement; + + plugin.style.width = `${plugin.clientWidth / 3}px`; + plugin.style.height = `${plugin.clientHeight / 3}px`; + await new Promise((x) => requestAnimationFrame(x)); + }); + + const after = await read_tiles(page); + expect(after[0].value_size).toBeLessThan(before); + expect(after[0].value_size).toEqual(after[1].value_size); + }); + + test("exports label and value lines as text", async ({ page }) => { + await restore(page, { + plugin: "Summary", + columns: ["Sales", "Profit"], + }); + + const text = await page.evaluate(async () => { + const viewer = document.querySelector("perspective-viewer") as any; + return await viewer.export({ method: "plugin" }); + }); + + const [sales, profit] = await formatted_totals(page, [ + "Sales", + "Profit", + ]); + + expect(text).toEqual(`Sales\t${sales}\nProfit\t${profit}`); + }); +}); diff --git a/packages/viewer-summary/test/js/tsconfig.json b/packages/viewer-summary/test/js/tsconfig.json new file mode 100644 index 0000000000..5cdea6dce5 --- /dev/null +++ b/packages/viewer-summary/test/js/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "rootDir": ".", + "allowImportingTsExtensions": true + }, + "include": ["./**/*.ts"] +} diff --git a/packages/viewer-summary/tsconfig.json b/packages/viewer-summary/tsconfig.json new file mode 100644 index 0000000000..e1c6dd4877 --- /dev/null +++ b/packages/viewer-summary/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist/esm", + "rootDir": "./src/ts", + "resolveJsonModule": true, + "esModuleInterop": true + }, + "include": ["./src/ts/**/*", "./types.d.ts"] +} diff --git a/packages/viewer-summary/types.d.ts b/packages/viewer-summary/types.d.ts new file mode 100644 index 0000000000..8d702d12eb --- /dev/null +++ b/packages/viewer-summary/types.d.ts @@ -0,0 +1,21 @@ +// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃ +// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃ +// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃ +// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃ +// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +// ┃ Copyright (c) 2017, the Perspective Authors. ┃ +// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ +// ┃ This file is part of the Perspective library, distributed under the terms ┃ +// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ +// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ + +declare module "*.html" { + const value: string; + export default value; +} + +declare module "*.css" { + const value: string; + export default value; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a06598a0a4..65a3d91ecb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -218,6 +218,9 @@ importers: '@perspective-dev/viewer-datagrid': specifier: workspace:^ version: link:packages/viewer-datagrid + '@perspective-dev/viewer-summary': + specifier: workspace:^ + version: link:packages/viewer-summary '@playwright/experimental-ct-react': specifier: 'catalog:' version: 1.62.0(@types/node@24.9.1)(jiti@1.21.7)(less@4.4.2)(terser@5.44.0)(tsx@4.20.6)(vite@8.3.0(@types/node@24.9.1)(jiti@1.21.7)(less@4.4.2)(terser@5.44.0)(tsx@4.20.6)(yaml@2.8.1))(yaml@2.8.1) @@ -269,6 +272,9 @@ importers: '@perspective-dev/viewer-datagrid': specifier: workspace:^ version: link:../packages/viewer-datagrid + '@perspective-dev/viewer-summary': + specifier: workspace:^ + version: link:../packages/viewer-summary puppeteer: specifier: 'catalog:' version: 24.26.1(supports-color@8.1.1)(typescript@5.9.3) @@ -312,6 +318,9 @@ importers: '@perspective-dev/viewer-datagrid': specifier: workspace:^ version: link:../../packages/viewer-datagrid + '@perspective-dev/viewer-summary': + specifier: workspace:^ + version: link:../../packages/viewer-summary devDependencies: '@types/emscripten': specifier: 'catalog:' @@ -556,6 +565,8 @@ importers: specifier: 'catalog:' version: 4.1.5 + examples/python-remote-client: {} + examples/python-starlette: {} examples/python-tornado: @@ -911,6 +922,34 @@ importers: specifier: 'catalog:' version: 8.8.5 + packages/viewer-summary: + dependencies: + '@perspective-dev/client': + specifier: workspace:~ + version: link:../../rust/perspective-js + '@perspective-dev/viewer': + specifier: workspace:~ + version: link:../../rust/perspective-viewer + devDependencies: + '@perspective-dev/esbuild-plugin': + specifier: workspace:^ + version: link:../../tools/esbuild-plugin + '@perspective-dev/test': + specifier: workspace:^ + version: link:../../tools/test + lightningcss: + specifier: 'catalog:' + version: 1.33.0 + prettier: + specifier: 'catalog:' + version: 3.6.2 + typescript: + specifier: 'catalog:' + version: 5.9.3 + zx: + specifier: 'catalog:' + version: 8.8.5 + rust/metadata: {} rust/perspective: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 513293edb5..59a9156df6 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -6,6 +6,7 @@ packages: - "tools/esbuild-plugin" - "packages/viewer-datagrid" - "packages/viewer-charts" + - "packages/viewer-summary" - "packages/workspace" - "packages/anywidget" - "packages/jupyterlab" diff --git a/rust/perspective-viewer/src/themes/intl.css b/rust/perspective-viewer/src/themes/intl.css index 3b0c82a4e0..180d7d3c43 100644 --- a/rust/perspective-viewer/src/themes/intl.css +++ b/rust/perspective-viewer/src/themes/intl.css @@ -19,6 +19,8 @@ perspective-viewer { --psp-label--transpose-button--content: "Swap"; --psp-label--config-button--content: "configure"; --psp-label--all-columns--content: "All Columns"; + --psp-label--add-all-columns--content: "Add"; + --psp-label--clear-columns--content: "Clear"; --psp-label--untitled--content: "untitled"; /* Plugin names */ @@ -155,7 +157,6 @@ perspective-viewer { --psp-label--role--facets--content: "Facets"; --psp-label--role--row-groups--content: "Row Groups"; --psp-label--role--column-groups--content: "Column Groups"; - --psp-label--role--breakdown--content: "Breakdown"; /* Window editor */ --psp-label--window-source--content: "Column"; @@ -187,7 +188,9 @@ perspective-viewer { --psp-label--zebra-color--content: "Zebra color"; --psp-label--label-position--content: "Label position"; --psp-label--value-fit--content: "Value size"; - --psp-label--breakdown--content: "Breakdown"; + --psp-label--layout-mode--content: "Layout"; + --psp-label--grid-columns--content: "Grid columns"; + --psp-label--grid-rows--content: "Grid rows"; --psp-label--chart-type--content: "Glyph type"; --psp-label--new-panel-button--content: "New"; diff --git a/rust/perspective-viewer/src/themes/intl/ar.css b/rust/perspective-viewer/src/themes/intl/ar.css index 3b50663e38..6ce2bb6b84 100644 --- a/rust/perspective-viewer/src/themes/intl/ar.css +++ b/rust/perspective-viewer/src/themes/intl/ar.css @@ -18,6 +18,8 @@ perspective-viewer { --psp-label--transpose-button--content: "تبديل"; --psp-label--config-button--content: "تكوين"; --psp-label--all-columns--content: "كل الأعمدة"; + --psp-label--add-all-columns--content: "+ الكل"; + --psp-label--clear-columns--content: "مسح"; --psp-label--untitled--content: "بدون عنوان"; --psp-plugin-name--datagrid--content: "شبكة البيانات"; @@ -147,7 +149,6 @@ perspective-viewer { --psp-label--role--facets--content: "الأوجه"; --psp-label--role--row-groups--content: "مجموعات الصفوف"; --psp-label--role--column-groups--content: "مجموعات الأعمدة"; - --psp-label--role--breakdown--content: "تفصيل"; --psp-label--window-source--content: "العمود"; --psp-label--window-order-by--content: "ترتيب حسب"; @@ -177,7 +178,9 @@ perspective-viewer { --psp-label--zebra-color--content: "لون التناوب"; --psp-label--label-position--content: "موضع التسمية"; --psp-label--value-fit--content: "حجم القيمة"; - --psp-label--breakdown--content: "تفصيل"; + --psp-label--layout-mode--content: "التخطيط"; + --psp-label--grid-columns--content: "أعمدة الشبكة"; + --psp-label--grid-rows--content: "صفوف الشبكة"; --psp-label--chart-type--content: "نوع الشكل"; --psp-label--new-panel-button--content: "جديد"; diff --git a/rust/perspective-viewer/src/themes/intl/de.css b/rust/perspective-viewer/src/themes/intl/de.css index 41d0fd8612..c33af9a3ec 100644 --- a/rust/perspective-viewer/src/themes/intl/de.css +++ b/rust/perspective-viewer/src/themes/intl/de.css @@ -19,6 +19,8 @@ perspective-viewer { --psp-label--transpose-button--content: "Tauschen"; --psp-label--config-button--content: "Konfigurieren"; --psp-label--all-columns--content: "Alle Spalten"; + --psp-label--add-all-columns--content: "Alle"; + --psp-label--clear-columns--content: "Leeren"; --psp-label--untitled--content: "Ohne Titel"; /* Plugin names */ @@ -150,7 +152,6 @@ perspective-viewer { --psp-label--role--facets--content: "Facetten"; --psp-label--role--row-groups--content: "Zeilengruppen"; --psp-label--role--column-groups--content: "Spaltengruppen"; - --psp-label--role--breakdown--content: "Aufschlüsselung"; /* Plugin settings */ --psp-label--edit-mode--content: "Bearbeitungsmodus"; @@ -174,7 +175,9 @@ perspective-viewer { --psp-label--zebra-color--content: "Zebra-Farbe"; --psp-label--label-position--content: "Beschriftungsposition"; --psp-label--value-fit--content: "Wertgröße"; - --psp-label--breakdown--content: "Aufschlüsselung"; + --psp-label--layout-mode--content: "Anordnung"; + --psp-label--grid-columns--content: "Rasterspalten"; + --psp-label--grid-rows--content: "Rasterzeilen"; --psp-label--chart-type--content: "Glyphentyp"; --psp-label--new-panel-button--content: "Neu"; diff --git a/rust/perspective-viewer/src/themes/intl/es.css b/rust/perspective-viewer/src/themes/intl/es.css index ae4a147731..3003a52b23 100644 --- a/rust/perspective-viewer/src/themes/intl/es.css +++ b/rust/perspective-viewer/src/themes/intl/es.css @@ -19,6 +19,8 @@ perspective-viewer { --psp-label--transpose-button--content: "Intercambiar"; --psp-label--config-button--content: "Configurar"; --psp-label--all-columns--content: "Todas las columnas"; + --psp-label--add-all-columns--content: "+ Todas"; + --psp-label--clear-columns--content: "Borrar"; --psp-label--untitled--content: "Sin título"; /* Plugin names */ @@ -150,7 +152,6 @@ perspective-viewer { --psp-label--role--facets--content: "Facetas"; --psp-label--role--row-groups--content: "Grupos de filas"; --psp-label--role--column-groups--content: "Grupos de columnas"; - --psp-label--role--breakdown--content: "Desglose"; /* Plugin settings */ --psp-label--edit-mode--content: "Modo de edición"; @@ -174,7 +175,9 @@ perspective-viewer { --psp-label--zebra-color--content: "Color cebra"; --psp-label--label-position--content: "Posición de etiqueta"; --psp-label--value-fit--content: "Tamaño del valor"; - --psp-label--breakdown--content: "Desglose"; + --psp-label--layout-mode--content: "Disposición"; + --psp-label--grid-columns--content: "Columnas de la cuadrícula"; + --psp-label--grid-rows--content: "Filas de la cuadrícula"; --psp-label--chart-type--content: "Tipo de glifo"; --psp-label--new-panel-button--content: "Nuevo"; diff --git a/rust/perspective-viewer/src/themes/intl/fr.css b/rust/perspective-viewer/src/themes/intl/fr.css index efcf23bc32..dc15500bfe 100644 --- a/rust/perspective-viewer/src/themes/intl/fr.css +++ b/rust/perspective-viewer/src/themes/intl/fr.css @@ -19,6 +19,8 @@ perspective-viewer { --psp-label--transpose-button--content: "Échanger"; --psp-label--config-button--content: "Configurer"; --psp-label--all-columns--content: "Toutes les colonnes"; + --psp-label--add-all-columns--content: "+ Toutes"; + --psp-label--clear-columns--content: "Effacer"; --psp-label--untitled--content: "Sans titre"; /* Plugin names */ @@ -150,7 +152,6 @@ perspective-viewer { --psp-label--role--facets--content: "Facettes"; --psp-label--role--row-groups--content: "Groupes de lignes"; --psp-label--role--column-groups--content: "Groupes de colonnes"; - --psp-label--role--breakdown--content: "Répartition"; /* Plugin settings */ --psp-label--edit-mode--content: "Mode édition"; @@ -174,7 +175,9 @@ perspective-viewer { --psp-label--zebra-color--content: "Couleur zébrée"; --psp-label--label-position--content: "Position du libellé"; --psp-label--value-fit--content: "Taille de la valeur"; - --psp-label--breakdown--content: "Répartition"; + --psp-label--layout-mode--content: "Disposition"; + --psp-label--grid-columns--content: "Colonnes de la grille"; + --psp-label--grid-rows--content: "Lignes de la grille"; --psp-label--chart-type--content: "Type de glyphe"; --psp-label--new-panel-button--content: "Nouveau"; diff --git a/rust/perspective-viewer/src/themes/intl/ja.css b/rust/perspective-viewer/src/themes/intl/ja.css index 2e7b995cb9..88851fc821 100644 --- a/rust/perspective-viewer/src/themes/intl/ja.css +++ b/rust/perspective-viewer/src/themes/intl/ja.css @@ -19,6 +19,8 @@ perspective-viewer { --psp-label--transpose-button--content: "スワップ"; --psp-label--config-button--content: "設定"; --psp-label--all-columns--content: "すべての列"; + --psp-label--add-all-columns--content: "+ すべて"; + --psp-label--clear-columns--content: "クリア"; --psp-label--untitled--content: "無題"; /* Plugin names */ @@ -150,7 +152,6 @@ perspective-viewer { --psp-label--role--facets--content: "ファセット"; --psp-label--role--row-groups--content: "行グループ"; --psp-label--role--column-groups--content: "列グループ"; - --psp-label--role--breakdown--content: "内訳"; /* Plugin settings */ --psp-label--edit-mode--content: "編集モード"; @@ -174,7 +175,9 @@ perspective-viewer { --psp-label--zebra-color--content: "縞模様の色"; --psp-label--label-position--content: "ラベル位置"; --psp-label--value-fit--content: "値のサイズ"; - --psp-label--breakdown--content: "内訳"; + --psp-label--layout-mode--content: "レイアウト"; + --psp-label--grid-columns--content: "グリッドの列数"; + --psp-label--grid-rows--content: "グリッドの行数"; --psp-label--chart-type--content: "グリフの種類"; --psp-label--new-panel-button--content: "新規"; diff --git a/rust/perspective-viewer/src/themes/intl/pt.css b/rust/perspective-viewer/src/themes/intl/pt.css index c8dce5ecd3..d21da9a12a 100644 --- a/rust/perspective-viewer/src/themes/intl/pt.css +++ b/rust/perspective-viewer/src/themes/intl/pt.css @@ -19,6 +19,8 @@ perspective-viewer { --psp-label--transpose-button--content: "Trocar"; --psp-label--config-button--content: "Configurar"; --psp-label--all-columns--content: "Todas as colunas"; + --psp-label--add-all-columns--content: "+ Todas"; + --psp-label--clear-columns--content: "Limpar"; --psp-label--untitled--content: "Sem título"; /* Plugin names */ @@ -150,7 +152,6 @@ perspective-viewer { --psp-label--role--facets--content: "Facetas"; --psp-label--role--row-groups--content: "Grupos de linhas"; --psp-label--role--column-groups--content: "Grupos de colunas"; - --psp-label--role--breakdown--content: "Detalhamento"; /* Plugin settings */ --psp-label--edit-mode--content: "Modo de edição"; @@ -174,7 +175,9 @@ perspective-viewer { --psp-label--zebra-color--content: "Cor zebrada"; --psp-label--label-position--content: "Posição do rótulo"; --psp-label--value-fit--content: "Tamanho do valor"; - --psp-label--breakdown--content: "Detalhamento"; + --psp-label--layout-mode--content: "Disposição"; + --psp-label--grid-columns--content: "Colunas da grade"; + --psp-label--grid-rows--content: "Linhas da grade"; --psp-label--chart-type--content: "Tipo de glifo"; --psp-label--new-panel-button--content: "Novo"; diff --git a/rust/perspective-viewer/src/themes/intl/zh.css b/rust/perspective-viewer/src/themes/intl/zh.css index 8ae8763849..404a84f5a2 100644 --- a/rust/perspective-viewer/src/themes/intl/zh.css +++ b/rust/perspective-viewer/src/themes/intl/zh.css @@ -19,6 +19,8 @@ perspective-viewer { --psp-label--transpose-button--content: "交换"; --psp-label--config-button--content: "配置"; --psp-label--all-columns--content: "所有列"; + --psp-label--add-all-columns--content: "+ 全部"; + --psp-label--clear-columns--content: "清除"; --psp-label--untitled--content: "无标题"; /* Plugin names */ @@ -150,7 +152,6 @@ perspective-viewer { --psp-label--role--facets--content: "分面"; --psp-label--role--row-groups--content: "行分组"; --psp-label--role--column-groups--content: "列分组"; - --psp-label--role--breakdown--content: "细分"; /* Plugin settings */ --psp-label--edit-mode--content: "编辑模式"; @@ -174,7 +175,9 @@ perspective-viewer { --psp-label--zebra-color--content: "斑马色"; --psp-label--label-position--content: "标签位置"; --psp-label--value-fit--content: "数值大小"; - --psp-label--breakdown--content: "细分"; + --psp-label--layout-mode--content: "布局"; + --psp-label--grid-columns--content: "网格列数"; + --psp-label--grid-rows--content: "网格行数"; --psp-label--chart-type--content: "图元类型"; --psp-label--new-panel-button--content: "新建"; diff --git a/rust/perspective-viewer/src/themes/phosphor.css b/rust/perspective-viewer/src/themes/phosphor.css index 9e63b1a033..74a718ec7d 100644 --- a/rust/perspective-viewer/src/themes/phosphor.css +++ b/rust/perspective-viewer/src/themes/phosphor.css @@ -49,6 +49,7 @@ perspective-viewer [theme="Phosphor"] { --psp-input--filter: invert(1) hue-rotate(70deg); --psp-warning--color: var(--theme-bg0); --psp-warning--background: var(--theme-amber); + --psp-box-shadow--color: #00ff4120; /* Syntax */ --psp-code-editor--symbol--color: var(--theme-green-mid); diff --git a/rust/perspective-viewer/src/themes/pro/palette.css b/rust/perspective-viewer/src/themes/pro/palette.css index 4977f7e737..897933ef66 100644 --- a/rust/perspective-viewer/src/themes/pro/palette.css +++ b/rust/perspective-viewer/src/themes/pro/palette.css @@ -25,7 +25,8 @@ --psp-icon-overflow-hint--color: #fdfffd; --psp-placeholder--background: #8b868045; - --psp-dropdown--box-shadow: 5px 5px 0 #00000020; + --psp-box-shadow--color: light-dark(#00000020, #ffffff20); + --psp-dropdown--box-shadow: 5px 5px 0 var(--psp-box-shadow--color); --psp-button--font-size: 16px; --psp-config-button--padding: 15px 8px 6px 8px; diff --git a/tools/scripts/setup.mjs b/tools/scripts/setup.mjs index 6d688cef93..699f4db4c0 100644 --- a/tools/scripts/setup.mjs +++ b/tools/scripts/setup.mjs @@ -182,6 +182,11 @@ async function focus_package() { name: "@perspective-dev/viewer-charts", value: "viewer-charts", }, + { + key: "u", + name: "@perspective-dev/viewer-summary", + value: "viewer-summary", + }, { key: "i", name: "@perspective-dev/jupyterlab", diff --git a/tools/scripts/test_consumers.mjs b/tools/scripts/test_consumers.mjs index 8148ee94b0..c91ab7f48b 100644 --- a/tools/scripts/test_consumers.mjs +++ b/tools/scripts/test_consumers.mjs @@ -41,6 +41,7 @@ const PACKAGES = [ }, { dir: "packages/viewer-datagrid" }, { dir: "packages/viewer-charts" }, + { dir: "packages/viewer-summary" }, { dir: "packages/react" }, ]; diff --git a/tools/scripts/test_js.mjs b/tools/scripts/test_js.mjs index 76120f853b..0dad3dfd25 100644 --- a/tools/scripts/test_js.mjs +++ b/tools/scripts/test_js.mjs @@ -33,6 +33,7 @@ const IS_PLAYWRIGHT = get_scope().reduce( "viewer", "viewer-datagrid", "viewer-charts", + "viewer-summary", "viewer-workspace", "workspace", ].includes(pkg), diff --git a/tools/test/playwright.config.ts b/tools/test/playwright.config.ts index bf1cc3f7b7..1265840c9d 100644 --- a/tools/test/playwright.config.ts +++ b/tools/test/playwright.config.ts @@ -86,7 +86,12 @@ const SUITE_DEVICES: Record = { const SUITE_DEVICE_LIST = (SUITE_DEVICES[BROWSER_SUITE] ?? SUITE_DEVICES.full) as (keyof typeof DEVICE_OPTIONS)[]; -const FIREFOX_SUITE_PACKAGES = ["viewer", "viewer-datagrid", "viewer-charts"]; +const FIREFOX_SUITE_PACKAGES = [ + "viewer", + "viewer-datagrid", + "viewer-charts", + "viewer-summary", +]; const DEVICE_OPTIONS = { "Desktop Chrome": { @@ -146,6 +151,10 @@ const BROWSER_PACKAGES = [ packageName: "viewer-charts", testDir: "packages/viewer-charts/test/ts", }, + { + packageName: "viewer-summary", + testDir: "packages/viewer-summary/test/js", + }, { packageName: "jupyterlab", testDir: "packages/jupyterlab/test/js", diff --git a/tools/test/src/html/summary-test.html b/tools/test/src/html/summary-test.html new file mode 100644 index 0000000000..e91ca24d70 --- /dev/null +++ b/tools/test/src/html/summary-test.html @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + +