Skip to main content

perspective_viewer/config/
viewer_config.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::sync::LazyLock;
14
15use perspective_client::Version;
16use perspective_client::config::viewer::{ViewerConfig, ViewerConfigInitial, ViewerConfigUpdate};
17use perspective_js::utils::*;
18use serde::{Deserialize, Serialize};
19use ts_rs::TS;
20use wasm_bindgen::prelude::*;
21
22/// The `@perspective-dev/viewer` package version, stamped on every saved
23/// config.
24pub static API_VERSION: LazyLock<&'static str> = LazyLock::new(|| {
25    #[derive(Deserialize)]
26    struct Package {
27        version: &'static str,
28    }
29    let pkg: &'static str = include_str!("../../../package.json");
30    let pkg: Package = serde_json::from_str(pkg).unwrap();
31    pkg.version
32});
33
34/// The `version` a raw config, or else one of its workspace panels, was saved
35/// by.
36pub fn saved_version(config: &JsValue) -> Option<String> {
37    let version = |value: &JsValue| {
38        js_sys::Reflect::get(value, &JsValue::from_str("version"))
39            .ok()?
40            .as_string()
41    };
42
43    version(config).or_else(|| {
44        ["panels", "viewers"].into_iter().find_map(|key| {
45            let panels = js_sys::Reflect::get(config, &JsValue::from_str(key)).ok()?;
46            let panels = panels.dyn_into::<js_sys::Object>().ok()?;
47            js_sys::Object::values(&panels)
48                .iter()
49                .find_map(|panel| version(&panel))
50        })
51    })
52}
53
54/// Await `result`, naming the release a config was `saved` by in its error
55/// when that is outside this release's `major.minor`.
56pub async fn noting_saved_version<T>(
57    saved: Option<String>,
58    result: impl std::future::Future<Output = ApiResult<T>>,
59) -> ApiResult<T> {
60    result.await.map_err(|error| {
61        let Some(saved) = saved else {
62            return error;
63        };
64
65        let current = Version::parse(&API_VERSION);
66        match (Version::parse(&saved), current) {
67            (Some(version), Some(current)) if version.same_minor(&current) => error,
68            (Some(version), Some(current)) if version < current => ApiError::new(format!(
69                "{error} (this config was saved by {saved}, and this is {}; configs from older \
70                 releases can be upgraded with `perspective-migrate`)",
71                *API_VERSION
72            )),
73            _ => ApiError::new(format!(
74                "{error} (this config was saved by {saved}, and this is {})",
75                *API_VERSION
76            )),
77        }
78    })
79}
80
81/// Encode a config to a `JsValue`.
82pub trait EncodeConfig {
83    /// Encode this config to a `JsValue` in a supported type.
84    fn encode(&self) -> ApiResult<JsValue>;
85}
86
87impl<V: TS + Serialize, T: TS + Serialize> EncodeConfig for ViewerConfig<V, T> {
88    fn encode(&self) -> ApiResult<JsValue> {
89        Ok(JsValue::from_serde_ext(self)?)
90    }
91}
92
93/// Decode a config from a `JsValue`, rejecting unknown keys.
94pub trait DecodeConfig: Sized {
95    /// Decode `value` into this config type.
96    fn decode(value: &JsValue) -> ApiResult<Self>;
97}
98
99impl DecodeConfig for ViewerConfigUpdate {
100    fn decode(value: &JsValue) -> ApiResult<Self> {
101        Ok(value.into_serde_ext()?)
102    }
103}
104
105impl DecodeConfig for ViewerConfigInitial {
106    fn decode(value: &JsValue) -> ApiResult<Self> {
107        Ok(value.into_serde_ext()?)
108    }
109}