Skip to main content

perspective_viewer/components/
datetime_column_style.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
13mod custom;
14mod simple;
15
16use std::fmt::Display;
17use std::rc::Rc;
18use std::sync::LazyLock;
19
20use derivative::Derivative;
21use perspective_js::json;
22use perspective_js::utils::global::navigator;
23use wasm_bindgen::prelude::*;
24use yew::prelude::*;
25
26use crate::components::datetime_column_style::custom::DatetimeStyleCustom;
27use crate::components::datetime_column_style::simple::DatetimeStyleSimple;
28use crate::config::*;
29use crate::ui::{ModalLink, SelectValueField, SetModalLink};
30use crate::utils::WeakScope;
31
32/// The `date_format` editor for `date` and `datetime` columns.
33#[derive(Properties, Derivative)]
34#[derivative(Debug)]
35pub struct DatetimeColumnStyleProps {
36    pub enable_time_config: bool,
37    pub config: Option<DatetimeColumnStyleConfig>,
38
39    /// The format the column inherits when it stores none.
40    pub default_format: Rc<DatetimeFormat>,
41
42    #[prop_or_default]
43    pub on_change: Callback<ColumnConfigFieldUpdate>,
44
45    #[prop_or_default]
46    pub keys: Vec<String>,
47
48    #[prop_or_default]
49    #[derivative(Debug = "ignore")]
50    weak_link: WeakScope<DatetimeColumnStyle>,
51}
52
53impl ModalLink<DatetimeColumnStyle> for DatetimeColumnStyleProps {
54    fn weak_link(&self) -> &'_ WeakScope<DatetimeColumnStyle> {
55        &self.weak_link
56    }
57}
58
59impl PartialEq for DatetimeColumnStyleProps {
60    fn eq(&self, other: &Self) -> bool {
61        self.enable_time_config == other.enable_time_config
62            && self.config == other.config
63            && self.default_format == other.default_format
64    }
65}
66
67/// A display-field edit, applied to the shown shape given the shape a reset
68/// restores.
69pub type ShapeEdit = Rc<dyn Fn(&DatetimeFormat, &DatetimeFormat) -> DatetimeFormat>;
70
71pub enum DatetimeColumnStyleMsg {
72    ShapeChanged(ShapeEdit),
73    ToParts,
74    ToPreset,
75    TimezoneChanged(Option<String>),
76    Hour12Changed(Option<bool>),
77}
78
79/// A display field's select value: one of its forms, or not shown.
80#[derive(Clone, Copy, Debug, PartialEq)]
81pub enum PartChoice<T> {
82    Shown(T),
83    Hidden,
84}
85
86impl<T: Display> Display for PartChoice<T> {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        match self {
89            Self::Shown(x) => x.fmt(f),
90            Self::Hidden => f.write_str("disabled"),
91        }
92    }
93}
94
95impl<T> From<Option<T>> for PartChoice<T> {
96    fn from(value: Option<T>) -> Self {
97        value.map_or(Self::Hidden, Self::Shown)
98    }
99}
100
101impl<T> PartChoice<T> {
102    /// The field value this choice stores, given the value a reset restores.
103    pub fn resolve(choice: Option<Self>, reset: Option<T>) -> Option<T> {
104        match choice {
105            None => reset,
106            Some(Self::Hidden) => None,
107            Some(Self::Shown(x)) => Some(x),
108        }
109    }
110}
111
112/// Every form of `T`, then [`PartChoice::Hidden`] when `hideable`.
113pub fn part_choices<T: strum::IntoEnumIterator>(hideable: bool) -> Rc<Vec<PartChoice<T>>> {
114    let mut values: Vec<_> = T::iter().map(PartChoice::Shown).collect();
115    if hideable {
116        values.push(PartChoice::Hidden);
117    }
118
119    Rc::new(values)
120}
121
122#[derive(Debug)]
123pub struct DatetimeColumnStyle {
124    stored: DatetimeFormat,
125}
126
127impl Component for DatetimeColumnStyle {
128    type Message = DatetimeColumnStyleMsg;
129    type Properties = DatetimeColumnStyleProps;
130
131    fn create(ctx: &Context<Self>) -> Self {
132        ctx.set_modal_link();
133        Self {
134            stored: stored_format(ctx.props()),
135        }
136    }
137
138    fn changed(&mut self, ctx: &Context<Self>, old: &Self::Properties) -> bool {
139        let stored = stored_format(ctx.props());
140        let rerender = self.stored != stored
141            || old.enable_time_config != ctx.props().enable_time_config
142            || old.default_format != ctx.props().default_format;
143
144        self.stored = stored;
145        rerender
146    }
147
148    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
149        let inherited = &*ctx.props().default_format;
150        let with_time = ctx.props().enable_time_config;
151        let next = match msg {
152            DatetimeColumnStyleMsg::ShapeChanged(edit) => {
153                let effective = inherited.overlay(&self.stored);
154                let reset_shape = if effective.has_parts() {
155                    parts_reset_shape(inherited, with_time)
156                } else {
157                    preset_reset_shape(inherited, with_time)
158                };
159
160                let shape = edit(&effective.shape(), &reset_shape);
161                if !shape.has_shape() {
162                    return false;
163                }
164
165                self.stored.with_shape(&shape)
166            },
167            DatetimeColumnStyleMsg::ToParts => self
168                .stored
169                .with_shape(&parts_reset_shape(inherited, with_time)),
170            DatetimeColumnStyleMsg::ToPreset => self
171                .stored
172                .with_shape(&preset_reset_shape(inherited, with_time)),
173            DatetimeColumnStyleMsg::TimezoneChanged(time_zone) => DatetimeFormat {
174                time_zone: time_zone.filter(|tz| *tz != inherited_time_zone(inherited)),
175                ..self.stored.clone()
176            },
177            DatetimeColumnStyleMsg::Hour12Changed(hour12) => DatetimeFormat {
178                hour12: hour12.filter(|h| *h != inherited_hour12(inherited)),
179                ..self.stored.clone()
180            },
181        };
182
183        self.stored = next.diff(inherited);
184        let mut value = serde_json::Map::new();
185        if !self.stored.is_empty()
186            && let Ok(format) = serde_json::to_value(&self.stored)
187        {
188            value.insert("date_format".to_owned(), format);
189        }
190
191        ctx.props().on_change.emit(ColumnConfigFieldUpdate {
192            keys: ctx.props().keys.clone(),
193            value,
194        });
195
196        true
197    }
198
199    fn view(&self, ctx: &Context<Self>) -> Html {
200        let inherited = &*ctx.props().default_format;
201        let with_time = ctx.props().enable_time_config;
202        let effective = inherited.overlay(&self.stored);
203        let hour_values = Rc::new(vec!["12 Hour", "24 Hour"]);
204        let hour_label = |hour12: bool| if hour12 { "12 Hour" } else { "24 Hour" };
205        html! {
206            <div id="column-style-container" class="datetime-column-style-container">
207                if with_time {
208                    <SelectValueField<String>
209                        label="timezone"
210                        values={ALL_TIMEZONES.with(|x| (*x).clone())}
211                        default_value={inherited_time_zone(inherited)}
212                        on_change={ctx.link().callback(DatetimeColumnStyleMsg::TimezoneChanged)}
213                        current_value={inherited_time_zone(&effective)}
214                    />
215                    <SelectValueField<&'static str>
216                        label="hours"
217                        values={hour_values}
218                        default_value={hour_label(inherited_hour12(inherited))}
219                        on_change={ctx.link().callback(|x: Option<&'static str>| DatetimeColumnStyleMsg::Hour12Changed(x.map(|x| x == "12 Hour")))}
220                        current_value={hour_label(inherited_hour12(&effective))}
221                    />
222                }
223                if effective.has_parts() {
224                    if with_time {
225                        <div class="row">
226                            <button
227                                id="datetime_format"
228                                data-title="Custom"
229                                data-title-hover="Switch to Simple"
230                                onclick={ctx.link().callback(|_| DatetimeColumnStyleMsg::ToPreset)}
231                            />
232                        </div>
233                    }
234                    <DatetimeStyleCustom
235                        enable_time_config={with_time}
236                        shape={effective.shape()}
237                        default_shape={parts_reset_shape(inherited, with_time)}
238                        on_change={ctx.link().callback(DatetimeColumnStyleMsg::ShapeChanged)}
239                    />
240                } else {
241                    if with_time {
242                        <div class="row">
243                            <button
244                                id="datetime_format"
245                                data-title="Simple"
246                                data-title-hover="Switch to Custom"
247                                onclick={ctx.link().callback(|_| DatetimeColumnStyleMsg::ToParts)}
248                            />
249                        </div>
250                    }
251                    <DatetimeStyleSimple
252                        enable_time_config={with_time}
253                        shape={effective.shape()}
254                        default_shape={preset_reset_shape(inherited, with_time)}
255                        on_change={ctx.link().callback(DatetimeColumnStyleMsg::ShapeChanged)}
256                    />
257                }
258            </div>
259        }
260    }
261}
262
263fn parts_reset_shape(inherited: &DatetimeFormat, with_time: bool) -> DatetimeFormat {
264    if inherited.has_parts() {
265        inherited.shape()
266    } else {
267        DatetimeFormat::parts_base(with_time)
268    }
269}
270
271fn preset_reset_shape(inherited: &DatetimeFormat, with_time: bool) -> DatetimeFormat {
272    if inherited.has_preset() {
273        inherited.shape()
274    } else {
275        DatetimeFormat::base(with_time)
276    }
277}
278
279fn stored_format(props: &DatetimeColumnStyleProps) -> DatetimeFormat {
280    props
281        .config
282        .as_ref()
283        .and_then(|config| config.date_format.clone())
284        .unwrap_or_default()
285}
286
287fn inherited_time_zone(format: &DatetimeFormat) -> String {
288    format
289        .time_zone
290        .clone()
291        .unwrap_or_else(|| (*USER_TIMEZONE).clone())
292}
293
294fn inherited_hour12(format: &DatetimeFormat) -> bool {
295    format.hour12.unwrap_or(*USER_HOUR12)
296}
297
298#[wasm_bindgen]
299extern "C" {
300    #[wasm_bindgen(js_name = supportedValuesOf, js_namespace = Intl)]
301    pub fn supported_values_of(s: &JsValue) -> js_sys::Array;
302}
303
304thread_local! {
305    static ALL_TIMEZONES: LazyLock<Rc<Vec<String>>> = LazyLock::new(|| {
306        Rc::new(
307            supported_values_of(&JsValue::from("timeZone"))
308                .iter()
309                .map(|x| x.as_string().unwrap())
310                .collect(),
311        )
312    });
313}
314
315static USER_TIMEZONE: LazyLock<String> = LazyLock::new(|| {
316    js_sys::Reflect::get(
317        &js_sys::Intl::DateTimeFormat::new(&navigator().languages(), &json!({})).resolved_options(),
318        &JsValue::from("timeZone"),
319    )
320    .unwrap()
321    .as_string()
322    .unwrap()
323});
324
325static USER_HOUR12: LazyLock<bool> = LazyLock::new(|| {
326    js_sys::Reflect::get(
327        &js_sys::Intl::DateTimeFormat::new(&navigator().languages(), &json!({"hour": "numeric"}))
328            .resolved_options(),
329        &JsValue::from("hour12"),
330    )
331    .ok()
332    .and_then(|x| x.as_bool())
333    .unwrap_or(true)
334});