-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathnumber_column_style.rs
More file actions
571 lines (502 loc) · 18.5 KB
/
number_column_style.rs
File metadata and controls
571 lines (502 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, the Perspective Authors.
//
// This file is part of the Perspective library, distributed under the terms
// of the Apache License 2.0. The full license can be found in the LICENSE
// file.
use super::color_range_selector::*;
use super::containers::modal_anchor::*;
use super::containers::radio_list::RadioList;
use crate::*;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::str::FromStr;
use wasm_bindgen::*;
use web_sys::*;
use yew::prelude::*;
use yew::*;
#[cfg(test)]
use crate::utils::WeakScope;
pub static CSS: &str = include_str!("../../../build/css/column-style.css");
#[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)]
pub enum NumberColorMode {
#[serde(rename = "disabled")]
Disabled,
#[serde(rename = "foreground")]
Foreground,
#[serde(rename = "background")]
Background,
#[serde(rename = "gradient")]
Gradient,
#[serde(rename = "bar")]
Bar,
}
impl Default for NumberColorMode {
fn default() -> Self {
NumberColorMode::Foreground
}
}
impl Display for NumberColorMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let text = match self {
NumberColorMode::Foreground => "foreground",
NumberColorMode::Background => "background",
NumberColorMode::Gradient => "gradient",
NumberColorMode::Bar => "bar",
_ => panic!("Unknown color mode!"),
};
write!(f, "{}", text)
}
}
impl FromStr for NumberColorMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"foreground" => Ok(NumberColorMode::Foreground),
"background" => Ok(NumberColorMode::Background),
"gradient" => Ok(NumberColorMode::Gradient),
"bar" => Ok(NumberColorMode::Bar),
x => Err(format!("Unknown NumberColorMode::{}", x)),
}
}
}
impl NumberColorMode {
fn is_foreground(&self) -> bool {
*self == NumberColorMode::Foreground
}
fn is_enabled(&self) -> bool {
*self != NumberColorMode::Disabled
}
fn needs_gradient(&self) -> bool {
*self == NumberColorMode::Gradient || *self == NumberColorMode::Bar
}
}
#[cfg_attr(test, derive(Debug))]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct NumberColumnStyleConfig {
#[serde(default = "NumberColorMode::default")]
#[serde(skip_serializing_if = "NumberColorMode::is_foreground")]
pub number_color_mode: NumberColorMode,
#[serde(skip_serializing_if = "Option::is_none")]
pub fixed: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pos_color: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub neg_color: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gradient: Option<f64>,
}
/// Exactly like a `ColumnStyleConfig`, except without `Option<>` fields, as
/// this struct represents the default values we should use in the GUI when they
/// are `None` in the real config. It is also used to decide when to omit a
/// field when serialized a `ColumnStyleConfig` to JSON.
#[derive(Deserialize, Clone, Default, Debug)]
pub struct NumberColumnStyleDefaultConfig {
pub gradient: f64,
pub fixed: u32,
pub pos_color: String,
pub neg_color: String,
#[serde(default = "NumberColorMode::default")]
pub color_mode: NumberColorMode,
}
pub enum NumberColumnStyleMsg {
Reset(NumberColumnStyleConfig, NumberColumnStyleDefaultConfig),
SetPos(i32, i32),
FixedChanged(String),
ColorEnabledChanged(bool),
PosColorChanged(String),
NegColorChanged(String),
NumberColorModeChanged(NumberColorMode),
GradientChanged(String),
}
/// A `ColumnStyle` component is mounted to the window anchored at the screen
/// position of `elem`. It needs two input configs, the current configuration
/// object and a default version without `Option<>`
#[derive(Properties, Clone)]
pub struct NumberColumnStyleProps {
#[prop_or_default]
pub config: NumberColumnStyleConfig,
#[prop_or_default]
pub default_config: NumberColumnStyleDefaultConfig,
#[prop_or_default]
pub on_change: Callback<NumberColumnStyleConfig>,
#[cfg(test)]
#[prop_or_default]
pub weak_link: WeakScope<NumberColumnStyle>,
}
impl PartialEq for NumberColumnStyleProps {
fn eq(&self, _other: &Self) -> bool {
false
}
}
impl NumberColumnStyleProps {}
/// The `ColumnStyle` component stores its UI state privately in its own struct,
/// rather than its props (which has two version of this data itself, the
/// JSON serializable config record and the defaults record).
pub struct NumberColumnStyle {
top: i32,
left: i32,
config: NumberColumnStyleConfig,
color_mode: NumberColorMode,
pos_color: String,
neg_color: String,
gradient: f64,
}
impl Component for NumberColumnStyle {
type Message = NumberColumnStyleMsg;
type Properties = NumberColumnStyleProps;
fn create(ctx: &Context<Self>) -> Self {
enable_weak_link_test!(ctx.props(), ctx.link());
NumberColumnStyle::reset(&ctx.props().config, &ctx.props().default_config)
}
fn changed(&mut self, ctx: &Context<Self>) -> bool {
let mut new =
NumberColumnStyle::reset(&ctx.props().config, &ctx.props().default_config);
std::mem::swap(self, &mut new);
true
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
NumberColumnStyleMsg::Reset(config, default_config) => {
let mut new = NumberColumnStyle::reset(&config, &default_config);
std::mem::swap(self, &mut new);
true
}
NumberColumnStyleMsg::SetPos(top, left) => {
self.top = top;
self.left = left;
true
}
NumberColumnStyleMsg::FixedChanged(fixed) => {
let fixed = match fixed.parse::<u32>() {
Ok(x) if x != ctx.props().default_config.fixed => Some(x),
Ok(_) => None,
Err(_) if fixed.is_empty() => Some(0),
Err(_) => None,
};
self.config.fixed = fixed.map(|x| std::cmp::min(15, x));
self.dispatch_config(ctx);
true
}
NumberColumnStyleMsg::ColorEnabledChanged(val) => {
if val {
let color_mode = match self.color_mode {
NumberColorMode::Disabled => NumberColorMode::default(),
x => x,
};
self.config.number_color_mode = color_mode;
self.config.pos_color = Some(self.pos_color.to_owned());
self.config.neg_color = Some(self.neg_color.to_owned());
if self.color_mode.needs_gradient() {
self.config.gradient = Some(self.gradient);
} else {
self.config.gradient = None;
}
} else {
self.config.number_color_mode = NumberColorMode::Disabled;
self.config.pos_color = None;
self.config.neg_color = None;
self.config.gradient = None;
}
self.dispatch_config(ctx);
true
}
NumberColumnStyleMsg::PosColorChanged(val) => {
self.pos_color = val;
self.config.pos_color = Some(self.pos_color.to_owned());
self.dispatch_config(ctx);
false
}
NumberColumnStyleMsg::NegColorChanged(val) => {
self.neg_color = val;
self.config.neg_color = Some(self.neg_color.to_owned());
self.dispatch_config(ctx);
false
}
NumberColumnStyleMsg::NumberColorModeChanged(val) => {
self.color_mode = val;
self.config.number_color_mode = val;
if self.color_mode.needs_gradient() {
self.config.gradient = Some(self.gradient);
} else {
self.config.gradient = None;
}
self.dispatch_config(ctx);
true
}
NumberColumnStyleMsg::GradientChanged(gradient) => {
self.config.gradient = match gradient.parse::<f64>() {
Ok(x) => {
self.gradient = x;
Some(x)
}
Err(_) if gradient.is_empty() => {
self.gradient = ctx.props().default_config.gradient;
Some(ctx.props().default_config.gradient)
}
Err(_) => {
self.gradient = ctx.props().default_config.gradient;
None
}
};
self.dispatch_config(ctx);
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
// Fixed precision control oninput callback
let fixed_oninput = ctx.link().callback(|event: InputEvent| {
NumberColumnStyleMsg::FixedChanged(
event
.target()
.unwrap()
.unchecked_into::<web_sys::HtmlInputElement>()
.value(),
)
});
let fixed_value = self
.config
.fixed
.unwrap_or(ctx.props().default_config.fixed)
.to_string();
// Color enabled/disabled oninput callback
let color_enabled_oninput = ctx.link().callback(move |event: InputEvent| {
let input = event
.target()
.unwrap()
.unchecked_into::<web_sys::HtmlInputElement>();
NumberColumnStyleMsg::ColorEnabledChanged(input.checked())
});
let selected_color_mode = match self.color_mode {
NumberColorMode::Disabled => NumberColorMode::default(),
x => x,
};
// Color mode radio callback
let color_mode_changed = ctx
.link()
.callback(NumberColumnStyleMsg::NumberColorModeChanged);
let select_values = vec![
NumberColorMode::Foreground,
NumberColorMode::Background,
NumberColorMode::Gradient,
NumberColorMode::Bar,
];
let foreground_controls =
if self.config.number_color_mode == NumberColorMode::Foreground {
html_template! {
<span class="row">{ "Foreground" }</span>
<div class="row section inner_section">
<ColorRangeSelector with self.color_props(ctx) />
</div>
}
} else {
html! {
<span class="row">{ "Foreground" }</span>
}
};
let background_controls =
if self.config.number_color_mode == NumberColorMode::Background {
html_template! {
<span class="row">{ "Background" }</span>
<div class="row section inner_section">
<ColorRangeSelector with self.color_props(ctx) />
</div>
}
} else {
html! {
<span class="row">{ "Background" }</span>
}
};
let gradient_controls =
if self.config.number_color_mode == NumberColorMode::Gradient {
html_template! {
<span class="row">{ "Gradient" }</span>
<div class="row section inner_section">
<ColorRangeSelector with self.color_props(ctx) />
<MaxValueChooser with self.max_value_props(ctx) />
</div>
}
} else {
html! {
<span class="row">{ "Gradient" }</span>
}
};
let bar_controls = if self.config.number_color_mode == NumberColorMode::Bar {
html_template! {
<span class="row">{ "Bar" }</span>
<div class="row section inner_section">
<ColorRangeSelector with self.color_props(ctx) />
<MaxValueChooser with self.max_value_props(ctx) />
</div>
}
} else {
html! {
<span class="row">{ "Bar" }</span>
}
};
html! {
<>
<style>
{ &CSS }
</style>
<ModalAnchor top={ self.top } left={ self.left } />
<div id="column-style-container">
<div>
<label id="fixed-examples" class="indent">{
self.make_fixed_text(ctx)
}</label>
</div>
<div class="row section">
<input type="checkbox" checked=true disabled=true/>
<input
id="fixed-param"
class="parameter"
type="number"
min="0"
step="1"
value={ fixed_value }
oninput={ fixed_oninput }/>
</div>
<div>
<label class="indent">{ "Color" }</label>
</div>
<div>
<input
id="color-selected"
type="checkbox"
oninput={ color_enabled_oninput }
checked={ self.config.number_color_mode.is_enabled() } />
<RadioList<NumberColorMode>
class="indent"
disabled={ !self.config.number_color_mode.is_enabled() }
values={ select_values }
selected={ selected_color_mode }
on_change={ color_mode_changed } >
{ foreground_controls }
{ background_controls }
{ gradient_controls }
{ bar_controls }
</RadioList<NumberColorMode>>
</div>
</div>
</>
}
}
}
#[derive(Properties, PartialEq, Clone)]
pub struct MaxValueChooserProps {
max_value: f64,
on_max_value: Callback<String>,
}
#[function_component(MaxValueChooser)]
fn max_value_chooser(props: &MaxValueChooserProps) -> Html {
let oninput = props.on_max_value.reform(|event: InputEvent| {
event
.target()
.unwrap()
.unchecked_into::<HtmlInputElement>()
.value()
});
html_template! {
<label>{ "Max" }</label>
<input
id="gradient-param"
value={ format!("{}", props.max_value) }
class="parameter"
oninput={ oninput }
type="number"
min="0" />
}
}
impl NumberColumnStyle {
/// When this config has changed, we must signal the wrapper element.
fn dispatch_config(&self, ctx: &Context<Self>) {
let config = match &self.config {
NumberColumnStyleConfig {
pos_color: Some(pos_color),
neg_color: Some(neg_color),
..
} if *pos_color == ctx.props().default_config.pos_color
&& *neg_color == ctx.props().default_config.neg_color =>
{
NumberColumnStyleConfig {
pos_color: None,
neg_color: None,
..self.config
}
}
x => x.clone(),
};
ctx.props().on_change.emit(config);
}
fn color_props(&self, ctx: &Context<Self>) -> ColorRangeProps {
let pos_color_oninput =
ctx.link().callback(NumberColumnStyleMsg::PosColorChanged);
let neg_color_oninput =
ctx.link().callback(NumberColumnStyleMsg::NegColorChanged);
props!(ColorRangeProps {
pos_color: self.pos_color.to_owned(),
neg_color: self.neg_color.to_owned(),
on_pos_color: pos_color_oninput,
on_neg_color: neg_color_oninput
})
}
fn max_value_props(&self, ctx: &Context<Self>) -> MaxValueChooserProps {
let on_max_value = ctx.link().callback(NumberColumnStyleMsg::GradientChanged);
props!(MaxValueChooserProps {
max_value: self.gradient,
on_max_value
})
}
/// Human readable precision hint, e.g. "Prec 0.001" for `{fixed: 3}`.
fn make_fixed_text(&self, ctx: &Context<Self>) -> String {
let fixed = match self.config.fixed {
Some(x) if x > 0 => format!("0.{}1", "0".repeat(x as usize - 1)),
None if ctx.props().default_config.fixed > 0 => {
let n = ctx.props().default_config.fixed as usize - 1;
format!("0.{}1", "0".repeat(n))
}
Some(_) | None => "1".to_owned(),
};
format!("Prec {}", fixed)
}
fn reset(
config: &NumberColumnStyleConfig,
default_config: &NumberColumnStyleDefaultConfig,
) -> NumberColumnStyle {
let mut config = config.clone();
let gradient = match config.gradient {
Some(x) => x,
None => default_config.gradient,
};
let pos_color = config
.pos_color
.as_ref()
.unwrap_or(&default_config.pos_color)
.to_owned();
let neg_color = config
.neg_color
.as_ref()
.unwrap_or(&default_config.neg_color)
.to_owned();
let color_mode = match config.number_color_mode {
NumberColorMode::Disabled => NumberColorMode::default(),
x => {
config.pos_color = Some(pos_color.to_owned());
config.neg_color = Some(neg_color.to_owned());
x
}
};
NumberColumnStyle {
top: 0,
left: 0,
config,
color_mode,
pos_color,
neg_color,
gradient,
}
}
}