1use std::{collections::BTreeMap, fmt};
10
11use rustc_hash::FxHashSet;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13
14use crate::{
15 engine::{ExpandDepth, SortDirection},
16 model::{ColumnId, OwnedValue},
17 state::ColumnZone,
18};
19
20#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
184#[non_exhaustive]
185pub struct GridLayout {
186 version: u32,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 view_id: Option<String>,
189 columns: Vec<LayoutColumn>,
190 #[serde(default, skip_serializing_if = "Vec::is_empty")]
191 sort: Vec<LayoutSort>,
192 #[serde(default, skip_serializing_if = "Vec::is_empty")]
193 group_by: Vec<LayoutGroup>,
194 #[serde(default, skip_serializing_if = "LayoutExpansion::is_unwritten")]
195 expansion: LayoutExpansion,
196}
197
198impl GridLayout {
199 pub const VERSION: u32 = 1;
201
202 pub fn new() -> Self {
204 Self {
205 version: Self::VERSION,
206 view_id: None,
207 columns: Vec::new(),
208 sort: Vec::new(),
209 group_by: Vec::new(),
210 expansion: LayoutExpansion::default(),
211 }
212 }
213
214 pub fn with_view_id(mut self, view_id: impl Into<String>) -> Self {
217 self.view_id = Some(view_id.into());
218 self
219 }
220
221 pub fn with_column(mut self, column: LayoutColumn) -> Self {
223 self.columns.push(column);
224 self
225 }
226
227 pub fn with_sort(mut self, sort: impl IntoIterator<Item = LayoutSort>) -> Self {
229 self.sort = sort.into_iter().collect();
230 self
231 }
232
233 pub fn with_group_by(mut self, levels: impl IntoIterator<Item = LayoutGroup>) -> Self {
236 self.group_by = levels.into_iter().collect();
237 self
238 }
239
240 pub fn with_expansion(mut self, expansion: LayoutExpansion) -> Self {
243 self.expansion = expansion;
244 self
245 }
246
247 pub fn version(&self) -> u32 {
249 self.version
250 }
251
252 pub fn view_id(&self) -> Option<&str> {
254 self.view_id.as_deref()
255 }
256
257 pub fn columns(&self) -> &[LayoutColumn] {
260 &self.columns
261 }
262
263 pub fn column(&self, id: &str) -> Option<&LayoutColumn> {
265 self.columns.iter().find(|column| column.id.as_str() == id)
266 }
267
268 pub fn sort(&self) -> &[LayoutSort] {
270 &self.sort
271 }
272
273 pub fn group_by(&self) -> &[LayoutGroup] {
276 &self.group_by
277 }
278
279 pub fn expansion(&self) -> Option<&LayoutExpansion> {
282 (!self.expansion.is_default()).then_some(&self.expansion)
283 }
284}
285
286#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
288#[non_exhaustive]
289pub struct LayoutColumn {
290 id: ColumnId,
291 #[serde(deserialize_with = "deserialize_width")]
292 width: f32,
293 #[serde(default = "default_visible", skip_serializing_if = "is_visible")]
294 visible: bool,
295 #[serde(
296 rename = "frozen",
297 default,
298 skip_serializing_if = "is_scrolling",
299 with = "frozen"
300 )]
301 zone: ColumnZone,
302}
303
304impl LayoutColumn {
305 pub fn new(id: impl Into<ColumnId>, width: impl Into<f32>) -> Self {
310 Self {
311 id: id.into(),
312 width: width.into(),
313 visible: true,
314 zone: ColumnZone::Scrolling,
315 }
316 }
317
318 pub fn with_width(mut self, width: impl Into<f32>) -> Self {
321 self.width = width.into();
322 self
323 }
324
325 pub fn with_visible(mut self, visible: bool) -> Self {
327 self.visible = visible;
328 self
329 }
330
331 pub fn with_zone(mut self, zone: ColumnZone) -> Self {
333 self.zone = zone;
334 self
335 }
336
337 pub fn id(&self) -> &ColumnId {
339 &self.id
340 }
341
342 pub fn width(&self) -> f32 {
344 self.width
345 }
346
347 pub fn is_visible(&self) -> bool {
349 self.visible
350 }
351
352 pub fn zone(&self) -> ColumnZone {
354 self.zone
355 }
356}
357
358fn default_visible() -> bool {
359 true
360}
361
362fn is_visible(visible: &bool) -> bool {
363 *visible
364}
365
366fn is_scrolling(zone: &ColumnZone) -> bool {
367 *zone == ColumnZone::Scrolling
368}
369
370fn deserialize_width<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f32, D::Error> {
374 Ok(Option::<f32>::deserialize(deserializer)?.unwrap_or(f32::NAN))
375}
376
377mod frozen {
381 use serde::{Deserialize, Deserializer, Serialize, Serializer};
382
383 use crate::state::ColumnZone;
384
385 #[derive(Serialize, Deserialize)]
386 #[serde(rename_all = "lowercase")]
387 enum FrozenSide {
388 Left,
389 Right,
390 }
391
392 pub(super) fn serialize<S: Serializer>(
393 zone: &ColumnZone,
394 serializer: S,
395 ) -> Result<S::Ok, S::Error> {
396 match zone {
397 ColumnZone::FrozenLeft => Some(FrozenSide::Left),
398 ColumnZone::Scrolling => None,
399 ColumnZone::FrozenRight => Some(FrozenSide::Right),
400 }
401 .serialize(serializer)
402 }
403
404 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
405 deserializer: D,
406 ) -> Result<ColumnZone, D::Error> {
407 Ok(match Option::<FrozenSide>::deserialize(deserializer)? {
408 Some(FrozenSide::Left) => ColumnZone::FrozenLeft,
409 None => ColumnZone::Scrolling,
410 Some(FrozenSide::Right) => ColumnZone::FrozenRight,
411 })
412 }
413}
414
415#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
417pub struct LayoutSort {
418 column: ColumnId,
419 direction: SortDirection,
420}
421
422impl LayoutSort {
423 pub fn new(column: impl Into<ColumnId>, direction: SortDirection) -> Self {
425 Self {
426 column: column.into(),
427 direction,
428 }
429 }
430
431 pub fn column(&self) -> &ColumnId {
433 &self.column
434 }
435
436 pub fn direction(&self) -> SortDirection {
438 self.direction
439 }
440}
441
442#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
449#[non_exhaustive]
450pub struct LayoutGroup {
451 column: ColumnId,
452 direction: SortDirection,
453}
454
455impl LayoutGroup {
456 pub fn new(column: impl Into<ColumnId>, direction: SortDirection) -> Self {
458 Self {
459 column: column.into(),
460 direction,
461 }
462 }
463
464 pub fn column(&self) -> &ColumnId {
466 &self.column
467 }
468
469 pub fn direction(&self) -> SortDirection {
471 self.direction
472 }
473}
474
475#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
493#[non_exhaustive]
494pub struct LayoutExpansion {
495 #[serde(default)]
496 depth: ExpandDepth,
497 #[serde(default, skip_serializing_if = "TogglePaths::is_unwritten")]
498 toggled: TogglePaths,
499}
500
501impl LayoutExpansion {
502 pub fn new(depth: ExpandDepth) -> Self {
504 Self {
505 depth,
506 toggled: TogglePaths::default(),
507 }
508 }
509
510 pub fn with_toggled(mut self, path: impl IntoIterator<Item = OwnedValue>) -> Self {
513 self.toggled.paths.push(path.into_iter().collect());
514 self
515 }
516
517 pub fn depth(&self) -> ExpandDepth {
519 self.depth
520 }
521
522 pub fn toggled(&self) -> &[Vec<OwnedValue>] {
525 &self.toggled.paths
526 }
527
528 pub fn is_default(&self) -> bool {
530 self.depth == ExpandDepth::All && self.toggled.paths.is_empty()
531 }
532
533 fn is_unwritten(&self) -> bool {
536 self.depth == ExpandDepth::All && self.toggled.is_unwritten()
537 }
538}
539
540#[derive(Clone, Debug, Default, PartialEq, Eq)]
543struct TogglePaths {
544 paths: Vec<Vec<OwnedValue>>,
545 unreadable: usize,
548}
549
550impl TogglePaths {
551 fn is_unwritten(&self) -> bool {
552 !self.paths.iter().any(|path| is_writable(path))
553 }
554}
555
556fn is_writable(path: &[OwnedValue]) -> bool {
558 path.iter()
559 .all(|value| !matches!(value, OwnedValue::Float(float) if !float.is_finite()))
560}
561
562impl Serialize for TogglePaths {
563 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
564 serializer.collect_seq(self.paths.iter().filter(|path| is_writable(path)))
565 }
566}
567
568impl<'de> Deserialize<'de> for TogglePaths {
569 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
572 let saved = Vec::<Vec<serde_json::Value>>::deserialize(deserializer)?;
573 let mut toggled = Self::default();
574 for path in saved {
575 match path
576 .into_iter()
577 .map(OwnedValue::deserialize)
578 .collect::<Result<Vec<_>, _>>()
579 {
580 Ok(path) => toggled.paths.push(path),
581 Err(_) => toggled.unreadable += 1,
582 }
583 }
584 Ok(toggled)
585 }
586}
587
588#[derive(Clone, Debug, PartialEq, Eq)]
591#[non_exhaustive]
592pub enum LayoutError {
593 UnsupportedVersion {
596 found: u32,
598 },
599 ViewMismatch {
601 expected: String,
603 found: String,
605 },
606 MissingViewId,
608 Decode(String),
610 Encode(String),
612}
613
614impl fmt::Display for LayoutError {
615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 match self {
617 Self::UnsupportedVersion { found } => write!(
618 f,
619 "layout version {found} is not supported; this build reads 1 to {}",
620 GridLayout::VERSION
621 ),
622 Self::ViewMismatch { expected, found } => {
623 write!(f, "the layout is for view \"{found}\", not \"{expected}\"")
624 }
625 Self::MissingViewId => f.write_str("the layout has no view id"),
626 Self::Decode(message) => write!(f, "the layout could not be read: {message}"),
627 Self::Encode(message) => write!(f, "the layout could not be written: {message}"),
628 }
629 }
630}
631
632impl std::error::Error for LayoutError {}
633
634pub(crate) fn check_version(found: u32) -> Result<(), LayoutError> {
636 if (1..=GridLayout::VERSION).contains(&found) {
637 Ok(())
638 } else {
639 Err(LayoutError::UnsupportedVersion { found })
640 }
641}
642
643#[derive(Clone, Debug, Default, PartialEq, Eq)]
648pub struct LayoutReport {
649 ignored_columns: Vec<ColumnId>,
650 added_columns: Vec<ColumnId>,
651 dropped_sort: Vec<ColumnId>,
652 dropped_group_by: Vec<ColumnId>,
653 dropped_expansion: usize,
654}
655
656impl LayoutReport {
657 pub(crate) fn resolve(context: &LayoutMergeContext<'_>, saved: &GridLayout) -> Self {
663 let mut ignored_columns = Vec::new();
664 for column in saved.columns() {
665 if !context.contains(column.id().as_str()) && !ignored_columns.contains(column.id()) {
666 ignored_columns.push(column.id().clone());
667 }
668 }
669 let added_columns = context
670 .columns()
671 .iter()
672 .filter(|column| saved.column(column.id().as_str()).is_none())
673 .map(|column| column.id().clone())
674 .collect();
675 let mut sorted = FxHashSet::default();
676 let mut dropped_sort = Vec::new();
677 for key in saved.sort() {
678 let id = key.column();
679 let kept = context.contains(id.as_str()) && sorted.insert(id.as_str());
680 if !kept && !dropped_sort.contains(id) {
681 dropped_sort.push(id.clone());
682 }
683 }
684 let grouping = ResolvedGrouping::new(context, saved);
685 Self {
686 ignored_columns,
687 added_columns,
688 dropped_sort,
689 dropped_group_by: grouping.dropped_group_by,
690 dropped_expansion: grouping.dropped_expansion,
691 }
692 }
693
694 pub fn ignored_columns(&self) -> &[ColumnId] {
696 &self.ignored_columns
697 }
698
699 pub fn added_columns(&self) -> &[ColumnId] {
701 &self.added_columns
702 }
703
704 pub fn dropped_sort(&self) -> &[ColumnId] {
706 &self.dropped_sort
707 }
708
709 pub fn dropped_group_by(&self) -> &[ColumnId] {
713 &self.dropped_group_by
714 }
715
716 pub fn dropped_expansion(&self) -> usize {
720 self.dropped_expansion
721 }
722
723 pub fn is_exact(&self) -> bool {
727 self.ignored_columns.is_empty()
728 && self.added_columns.is_empty()
729 && self.dropped_sort.is_empty()
730 && self.dropped_group_by.is_empty()
731 && self.dropped_expansion == 0
732 }
733}
734
735pub(crate) struct ResolvedGrouping<'a> {
740 levels: Vec<&'a LayoutGroup>,
741 toggled: Vec<&'a [OwnedValue]>,
742 depth: ExpandDepth,
743 dropped_group_by: Vec<ColumnId>,
744 dropped_expansion: usize,
745}
746
747impl<'a> ResolvedGrouping<'a> {
748 pub(crate) fn new(context: &LayoutMergeContext<'_>, saved: &'a GridLayout) -> Self {
757 let mut grouped = FxHashSet::default();
758 let mut levels = Vec::with_capacity(saved.group_by.len());
759 let mut dropped_group_by = Vec::new();
760 for level in &saved.group_by {
761 let id = level.column();
762 if context.is_groupable(id.as_str()) && grouped.insert(id.as_str()) {
763 levels.push(level);
764 } else if !dropped_group_by.contains(id) {
765 dropped_group_by.push(id.clone());
766 }
767 }
768 let expansion = &saved.expansion;
769 let toggled: Vec<&[OwnedValue]> = expansion
770 .toggled()
771 .iter()
772 .map(Vec::as_slice)
773 .filter(|path| (1..=levels.len()).contains(&path.len()))
774 .collect();
775 let dropped_expansion =
776 expansion.toggled.unreadable + (expansion.toggled().len() - toggled.len());
777 Self {
778 levels,
779 toggled,
780 depth: expansion.depth(),
781 dropped_group_by,
782 dropped_expansion,
783 }
784 }
785
786 pub(crate) fn levels(&self) -> &[&'a LayoutGroup] {
788 &self.levels
789 }
790
791 pub(crate) fn toggled(&self) -> &[&'a [OwnedValue]] {
794 &self.toggled
795 }
796
797 pub(crate) fn depth(&self) -> ExpandDepth {
799 self.depth
800 }
801}
802
803pub trait LayoutCodec: 'static {
808 fn encode(&self, layout: &GridLayout) -> Result<String, LayoutError>;
810
811 fn decode(&self, text: &str) -> Result<GridLayout, LayoutError>;
815}
816
817#[derive(Clone, Copy, Debug, Default)]
819pub struct JsonLayoutCodec {
820 pretty: bool,
821}
822
823impl JsonLayoutCodec {
824 pub fn pretty(mut self, pretty: bool) -> Self {
826 self.pretty = pretty;
827 self
828 }
829
830 pub fn is_pretty(&self) -> bool {
832 self.pretty
833 }
834}
835
836impl LayoutCodec for JsonLayoutCodec {
837 fn encode(&self, layout: &GridLayout) -> Result<String, LayoutError> {
838 if self.pretty {
839 serde_json::to_string_pretty(layout)
840 } else {
841 serde_json::to_string(layout)
842 }
843 .map_err(|error| LayoutError::Encode(error.to_string()))
844 }
845
846 fn decode(&self, text: &str) -> Result<GridLayout, LayoutError> {
847 let decode_error = |error: serde_json::Error| LayoutError::Decode(error.to_string());
848 let value: serde_json::Value = serde_json::from_str(text).map_err(decode_error)?;
849 let Some(object) = value.as_object() else {
850 return Err(LayoutError::Decode("expected a JSON object".into()));
851 };
852 let found = match object.get("version") {
853 None => return Err(LayoutError::Decode("missing field `version`".into())),
854 Some(version) => version.as_u64().ok_or_else(|| {
855 LayoutError::Decode(format!("`version` is not a whole number: {version}"))
856 })?,
857 };
858 check_version(u32::try_from(found).unwrap_or(u32::MAX))?;
859 serde_json::from_value(value).map_err(decode_error)
862 }
863}
864
865#[derive(Clone, Copy, Debug)]
868pub struct LayoutMergeContext<'a> {
869 columns: &'a [LayoutColumn],
870 ungroupable: &'a [ColumnId],
872}
873
874impl<'a> LayoutMergeContext<'a> {
875 pub(crate) fn new(columns: &'a [LayoutColumn]) -> Self {
878 Self {
879 columns,
880 ungroupable: &[],
881 }
882 }
883
884 pub(crate) fn with_ungroupable(mut self, ids: &'a [ColumnId]) -> Self {
886 self.ungroupable = ids;
887 self
888 }
889
890 pub fn columns(&self) -> &'a [LayoutColumn] {
893 self.columns
894 }
895
896 pub fn column(&self, id: &str) -> Option<&'a LayoutColumn> {
898 self.columns
899 .iter()
900 .find(|column| column.id().as_str() == id)
901 }
902
903 pub fn contains(&self, id: &str) -> bool {
905 self.column(id).is_some()
906 }
907
908 pub fn is_groupable(&self, id: &str) -> bool {
911 self.contains(id) && !self.ungroupable.iter().any(|column| column.as_str() == id)
912 }
913}
914
915pub trait LayoutMerge: 'static {
922 fn merge(&self, context: &LayoutMergeContext<'_>, saved: &GridLayout) -> Vec<LayoutColumn>;
927}
928
929#[derive(Clone, Copy, Debug, Default)]
934pub struct AppendNewColumns;
935
936impl LayoutMerge for AppendNewColumns {
937 fn merge(&self, context: &LayoutMergeContext<'_>, saved: &GridLayout) -> Vec<LayoutColumn> {
938 fn zone_ix(zone: ColumnZone) -> usize {
939 match zone {
940 ColumnZone::FrozenLeft => 0,
941 ColumnZone::Scrolling => 1,
942 ColumnZone::FrozenRight => 2,
943 }
944 }
945
946 let mut merged = FxHashSet::default();
947 let mut zones: [Vec<LayoutColumn>; 3] = Default::default();
948 for column in saved.columns() {
949 let id = column.id().as_str();
950 if context.contains(id) && merged.insert(id) {
951 zones[zone_ix(column.zone())].push(column.clone());
952 }
953 }
954 for column in context.columns() {
955 if !merged.contains(column.id().as_str()) {
956 zones[zone_ix(column.zone())].push(column.clone());
957 }
958 }
959 zones.into_iter().flatten().collect()
960 }
961}
962
963#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
971pub struct LayoutLibrary {
972 #[serde(default)]
973 views: BTreeMap<String, ViewLayouts>,
974}
975
976#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
977struct ViewLayouts {
978 #[serde(default, skip_serializing_if = "Option::is_none")]
979 default: Option<String>,
980 #[serde(default)]
981 layouts: BTreeMap<String, GridLayout>,
982}
983
984impl LayoutLibrary {
985 pub fn new() -> Self {
987 Self::default()
988 }
989
990 pub fn insert(
994 &mut self,
995 name: impl Into<String>,
996 layout: GridLayout,
997 ) -> Result<(), LayoutError> {
998 let view_id = layout.view_id().ok_or(LayoutError::MissingViewId)?;
999 self.views
1000 .entry(view_id.to_owned())
1001 .or_default()
1002 .layouts
1003 .insert(name.into(), layout);
1004 Ok(())
1005 }
1006
1007 pub fn get(&self, view_id: &str, name: &str) -> Option<&GridLayout> {
1009 self.views.get(view_id)?.layouts.get(name)
1010 }
1011
1012 pub fn names<'a>(&'a self, view_id: &str) -> impl Iterator<Item = &'a str> + use<'a> {
1014 self.views
1015 .get(view_id)
1016 .into_iter()
1017 .flat_map(|view| view.layouts.keys().map(String::as_str))
1018 }
1019
1020 pub fn remove(&mut self, view_id: &str, name: &str) -> Option<GridLayout> {
1023 let view = self.views.get_mut(view_id)?;
1024 let layout = view.layouts.remove(name)?;
1025 if view.default.as_deref() == Some(name) {
1026 view.default = None;
1027 }
1028 if view.layouts.is_empty() {
1029 self.views.remove(view_id);
1030 }
1031 Some(layout)
1032 }
1033
1034 pub fn rename(&mut self, view_id: &str, from: &str, to: impl Into<String>) -> bool {
1038 let to = to.into();
1039 let Some(view) = self.views.get_mut(view_id) else {
1040 return false;
1041 };
1042 if to != from && view.layouts.contains_key(&to) {
1043 return false;
1044 }
1045 let Some(layout) = view.layouts.remove(from) else {
1046 return false;
1047 };
1048 if view.default.as_deref() == Some(from) {
1049 view.default = Some(to.clone());
1050 }
1051 view.layouts.insert(to, layout);
1052 true
1053 }
1054
1055 pub fn set_default(&mut self, view_id: &str, name: Option<&str>) -> bool {
1059 let view = self.views.get_mut(view_id);
1060 match (view, name) {
1061 (Some(view), Some(name)) if view.layouts.contains_key(name) => {
1062 view.default = Some(name.to_owned());
1063 true
1064 }
1065 (_, Some(_)) => false,
1066 (Some(view), None) => {
1067 view.default = None;
1068 true
1069 }
1070 (None, None) => true,
1071 }
1072 }
1073
1074 pub fn default_layout(&self, view_id: &str) -> Option<(&str, &GridLayout)> {
1076 let view = self.views.get(view_id)?;
1077 let (name, layout) = view.layouts.get_key_value(view.default.as_deref()?)?;
1078 Some((name.as_str(), layout))
1079 }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084 use super::*;
1085
1086 fn reference_layout() -> GridLayout {
1090 GridLayout::new()
1091 .with_view_id("trades")
1092 .with_column(LayoutColumn::new("id", 80_f32).with_zone(ColumnZone::FrozenLeft))
1093 .with_column(LayoutColumn::new("instrument", 140_f32))
1094 .with_column(LayoutColumn::new("time", 92.5_f32))
1095 .with_column(LayoutColumn::new("fee", 90_f32).with_visible(false))
1096 .with_column(LayoutColumn::new("price", 100_f32))
1097 .with_column(LayoutColumn::new("side", 60_f32).with_zone(ColumnZone::FrozenRight))
1098 .with_column(
1099 LayoutColumn::new("venue", 72_f32)
1100 .with_visible(false)
1101 .with_zone(ColumnZone::FrozenRight),
1102 )
1103 .with_sort([
1104 LayoutSort::new("time", SortDirection::Descending),
1105 LayoutSort::new("instrument", SortDirection::Ascending),
1106 ])
1107 }
1108
1109 #[test]
1110 fn test_layout_builder() {
1111 let empty = GridLayout::new();
1112 assert_eq!(empty.version(), GridLayout::VERSION);
1113 assert_eq!(empty.view_id(), None);
1114 assert!(empty.columns().is_empty() && empty.sort().is_empty());
1115
1116 let column = LayoutColumn::new("price", 100_f32);
1117 assert_eq!(column.id().as_str(), "price");
1118 assert_eq!(column.width(), 100.);
1119 assert!(column.is_visible());
1120 assert_eq!(column.zone(), ColumnZone::Scrolling);
1121
1122 let layout = GridLayout::new()
1123 .with_view_id("orders")
1124 .with_column(
1125 LayoutColumn::new("price", 100_f32)
1126 .with_width(gpui_kit::px(120.))
1127 .with_visible(false)
1128 .with_zone(ColumnZone::FrozenRight),
1129 )
1130 .with_column(LayoutColumn::new(String::from("qty"), 60_f32))
1131 .with_column(LayoutColumn::new("price", 30_f32))
1132 .with_sort([LayoutSort::new("qty", SortDirection::Ascending)])
1133 .with_sort([LayoutSort::new("price", SortDirection::Descending)]);
1134 assert_eq!(layout.view_id(), Some("orders"));
1135 let ids: Vec<_> = layout.columns().iter().map(|c| c.id().as_str()).collect();
1136 assert_eq!(ids, ["price", "qty", "price"]);
1137 let price = layout.column("price").unwrap();
1139 assert_eq!(price.width(), 120.);
1140 assert!(!price.is_visible());
1141 assert_eq!(price.zone(), ColumnZone::FrozenRight);
1142 assert_eq!(layout.column("fee"), None);
1143 assert_eq!(layout.sort().len(), 1);
1145 assert_eq!(layout.sort()[0].column().as_str(), "price");
1146 assert_eq!(layout.sort()[0].direction(), SortDirection::Descending);
1147
1148 assert!(!JsonLayoutCodec::default().is_pretty());
1149 assert!(JsonLayoutCodec::default().pretty(true).is_pretty());
1150 assert_eq!(
1151 LayoutError::UnsupportedVersion { found: 2 }.to_string(),
1152 "layout version 2 is not supported; this build reads 1 to 1"
1153 );
1154 }
1155
1156 #[test]
1157 fn test_layout_json_matches_fixture() {
1158 let fixture = include_str!("../tests/fixtures/layout-v1.json").replace("\r\n", "\n");
1160 let layout = reference_layout();
1161
1162 let pretty = JsonLayoutCodec::default().pretty(true);
1163 assert_eq!(format!("{}\n", pretty.encode(&layout).unwrap()), fixture);
1164 assert_eq!(pretty.decode(&fixture).unwrap(), layout);
1165
1166 let ungrouped = layout
1169 .clone()
1170 .with_group_by(Vec::new())
1171 .with_expansion(LayoutExpansion::default());
1172 assert_eq!(ungrouped, layout);
1173 assert_eq!(format!("{}\n", pretty.encode(&ungrouped).unwrap()), fixture);
1174 let read = pretty.decode(&fixture).unwrap();
1175 assert!(read.group_by().is_empty());
1176 assert_eq!(read.expansion(), None);
1177
1178 let codec = JsonLayoutCodec::default();
1181 let compact = codec.encode(&layout).unwrap();
1182 assert!(!compact.contains('\n'));
1183 assert_eq!(codec.decode(&compact).unwrap(), layout);
1184 assert_eq!(
1185 serde_json::from_str::<GridLayout>(&fixture).unwrap(),
1186 layout
1187 );
1188 }
1189
1190 #[test]
1191 fn test_layout_decode_defaults_and_unknown_fields() {
1192 let codec = JsonLayoutCodec::default();
1193 let layout = codec
1194 .decode(
1195 r#"{
1196 "version": 1,
1197 "view_id": null,
1198 "columns": [
1199 { "id": "a", "width": 50 },
1200 { "id": "b", "width": 60.5, "visible": true, "frozen": null, "tint": "red" },
1201 { "id": "c", "width": null, "visible": false, "frozen": "right" }
1202 ],
1203 "filters": ["a"],
1204 "density": { "rows": "compact" }
1205 }"#,
1206 )
1207 .unwrap();
1208 assert_eq!(layout.version(), 1);
1209 assert_eq!(layout.view_id(), None);
1210 assert!(layout.sort().is_empty());
1211 let a = layout.column("a").unwrap();
1212 assert_eq!(a.width(), 50.);
1213 assert!(a.is_visible());
1214 assert_eq!(a.zone(), ColumnZone::Scrolling);
1215 let b = layout.column("b").unwrap();
1216 assert_eq!(
1217 (b.width(), b.is_visible(), b.zone()),
1218 (60.5, true, ColumnZone::Scrolling)
1219 );
1220 let c = layout.column("c").unwrap();
1223 assert!(c.width().is_nan());
1224 assert_eq!((c.is_visible(), c.zone()), (false, ColumnZone::FrozenRight));
1225
1226 assert_eq!(
1228 codec.encode(&layout).unwrap(),
1229 concat!(
1230 r#"{"version":1,"columns":[{"id":"a","width":50.0},{"id":"b","width":60.5},"#,
1231 r#"{"id":"c","width":null,"visible":false,"frozen":"right"}]}"#,
1232 )
1233 );
1234
1235 for text in [
1237 r#"{"version":1,"columns":[{"id":"a","width":50,"frozen":"top"}]}"#,
1238 r#"{"version":1,"columns":[{"id":"a","width":"wide"}]}"#,
1239 r#"{"version":1,"columns":[{"width":50}]}"#,
1240 r#"{"version":1,"columns":[],"sort":[{"column":"a","direction":"up"}]}"#,
1241 r#"{"version":1,"columns":[],"group_by":[{"column":"a","direction":"up"}]}"#,
1242 r#"{"version":1,"columns":[],"group_by":[{"direction":"ascending"}]}"#,
1243 r#"{"version":1,"columns":[],"group_by":["a"]}"#,
1244 r#"{"version":1,"columns":[],"expansion":{"depth":"deep"}}"#,
1245 r#"{"version":1,"columns":[],"expansion":"all"}"#,
1246 r#"{"version":1,"columns":[],"expansion":{"toggled":"AAPL"}}"#,
1247 r#"{"version":1,"columns":[],"expansion":{"toggled":["AAPL"]}}"#,
1248 ] {
1249 assert!(
1250 matches!(codec.decode(text), Err(LayoutError::Decode(_))),
1251 "{text}"
1252 );
1253 }
1254 }
1255
1256 fn text(value: &str) -> OwnedValue {
1257 OwnedValue::Text(value.into())
1258 }
1259
1260 fn grouped_layout() -> GridLayout {
1265 let expansion = LayoutExpansion::new(ExpandDepth::All)
1266 .with_toggled([text("AAPL")])
1267 .with_toggled([text("MSFT"), text("Sell")])
1268 .with_toggled([OwnedValue::Empty])
1269 .with_toggled([OwnedValue::Bool(true)])
1270 .with_toggled([OwnedValue::Int(12)])
1271 .with_toggled([OwnedValue::Float(12.0)]);
1272 #[cfg(feature = "decimal")]
1273 let expansion =
1274 expansion.with_toggled([OwnedValue::Decimal(rust_decimal::Decimal::new(1020, 2))]);
1275 GridLayout::new()
1276 .with_view_id("trades")
1277 .with_column(LayoutColumn::new("instrument", 140_f32))
1278 .with_column(LayoutColumn::new("side", 60_f32))
1279 .with_column(LayoutColumn::new("price", 100_f32))
1280 .with_sort([LayoutSort::new("price", SortDirection::Descending)])
1281 .with_group_by([
1282 LayoutGroup::new("instrument", SortDirection::Ascending),
1283 LayoutGroup::new("side", SortDirection::Descending),
1284 ])
1285 .with_expansion(expansion)
1286 }
1287
1288 fn ids(ids: &[ColumnId]) -> Vec<&str> {
1289 ids.iter().map(ColumnId::as_str).collect()
1290 }
1291
1292 #[test]
1293 fn test_layout_groups_builder() {
1294 let level = LayoutGroup::new("side", SortDirection::Descending);
1295 assert_eq!(level.column().as_str(), "side");
1296 assert_eq!(level.direction(), SortDirection::Descending);
1297
1298 let expansion = LayoutExpansion::new(ExpandDepth::Levels(1))
1299 .with_toggled([text("AAPL")])
1300 .with_toggled(Vec::new());
1301 assert_eq!(expansion.depth(), ExpandDepth::Levels(1));
1302 assert_eq!(expansion.toggled(), [vec![text("AAPL")], Vec::new()]);
1303 assert!(!expansion.is_default());
1304 assert!(LayoutExpansion::default().is_default());
1305 assert!(!LayoutExpansion::new(ExpandDepth::Captions).is_default());
1306 assert!(
1307 !LayoutExpansion::default()
1308 .with_toggled([text("a")])
1309 .is_default()
1310 );
1311
1312 let layout = GridLayout::new()
1313 .with_group_by([level.clone()])
1314 .with_group_by([level.clone(), level.clone()])
1315 .with_expansion(LayoutExpansion::new(ExpandDepth::Captions))
1316 .with_expansion(expansion.clone());
1317 assert_eq!(layout.group_by(), [level.clone(), level]);
1319 assert_eq!(layout.expansion(), Some(&expansion));
1320 assert!(GridLayout::new().group_by().is_empty());
1321 assert_eq!(GridLayout::new().expansion(), None);
1322 assert_eq!(
1323 layout
1324 .with_expansion(LayoutExpansion::default())
1325 .expansion(),
1326 None
1327 );
1328 }
1329
1330 #[test]
1331 fn test_layout_groups_fixture() {
1332 use std::mem::discriminant;
1333
1334 let fixture = include_str!("../tests/fixtures/layout-v1-groups.json").replace("\r\n", "\n");
1335 let layout = grouped_layout();
1336 let pretty = JsonLayoutCodec::default().pretty(true);
1337 let read = pretty.decode(&fixture).unwrap();
1338 assert_eq!(serde_json::from_str::<GridLayout>(&fixture).unwrap(), read);
1340
1341 let toggled = read.expansion().unwrap().toggled();
1343 assert_eq!(
1344 discriminant(&toggled[4][0]),
1345 discriminant(&OwnedValue::Int(12))
1346 );
1347 assert_eq!(
1348 discriminant(&toggled[5][0]),
1349 discriminant(&OwnedValue::Float(12.0))
1350 );
1351
1352 let schema = [
1353 LayoutColumn::new("instrument", 100_f32),
1354 LayoutColumn::new("side", 100_f32),
1355 LayoutColumn::new("price", 100_f32),
1356 ];
1357 let context = LayoutMergeContext::new(&schema);
1358 let report = LayoutReport::resolve(&context, &read);
1359 assert!(report.dropped_group_by().is_empty());
1360
1361 #[cfg(feature = "decimal")]
1362 {
1363 assert_eq!(format!("{}\n", pretty.encode(&layout).unwrap()), fixture);
1364 assert_eq!(read, layout);
1365 assert!(
1366 matches!(&toggled[6][0], OwnedValue::Decimal(value) if value.to_string() == "10.20")
1367 );
1368 assert!(report.is_exact());
1369 }
1370 #[cfg(not(feature = "decimal"))]
1371 {
1372 assert_eq!(read.group_by(), layout.group_by());
1375 assert_eq!(toggled, layout.expansion().unwrap().toggled());
1376 assert_eq!(report.dropped_expansion(), 1);
1377 assert!(!report.is_exact());
1378 assert_eq!(
1380 pretty.encode(&read).unwrap(),
1381 pretty.encode(&layout).unwrap()
1382 );
1383 }
1384 let compact = JsonLayoutCodec::default();
1386 let text = compact.encode(&read).unwrap();
1387 assert_eq!(
1388 compact.encode(&compact.decode(&text).unwrap()).unwrap(),
1389 text
1390 );
1391 }
1392
1393 #[test]
1394 fn test_expansion_default_omitted() {
1395 let codec = JsonLayoutCodec::default();
1396 let empty = r#"{"version":1,"columns":[]}"#;
1397 for layout in [
1400 GridLayout::new().with_expansion(LayoutExpansion::new(ExpandDepth::All)),
1401 GridLayout::new()
1402 .with_group_by(Vec::new())
1403 .with_expansion(LayoutExpansion::default()),
1404 GridLayout::new().with_expansion(
1405 LayoutExpansion::default()
1406 .with_toggled([text("a"), OwnedValue::Float(f64::NAN)])
1407 .with_toggled([OwnedValue::Float(f64::NEG_INFINITY)]),
1408 ),
1409 ] {
1410 assert_eq!(codec.encode(&layout).unwrap(), empty);
1411 }
1412 let read = codec.decode(empty).unwrap();
1413 assert_eq!(read, GridLayout::new());
1414 assert_eq!(read.expansion(), None);
1415
1416 for (depth, json) in [
1418 (ExpandDepth::Captions, r#""captions""#),
1419 (ExpandDepth::Levels(0), "0"),
1420 (ExpandDepth::Levels(3), "3"),
1421 ] {
1422 let layout = GridLayout::new().with_expansion(LayoutExpansion::new(depth));
1423 let text = codec.encode(&layout).unwrap();
1424 assert_eq!(
1425 text,
1426 format!(r#"{{"version":1,"columns":[],"expansion":{{"depth":{json}}}}}"#)
1427 );
1428 assert_eq!(codec.decode(&text).unwrap(), layout);
1429 assert_eq!(layout.expansion().map(LayoutExpansion::depth), Some(depth));
1430 }
1431
1432 let mixed = GridLayout::new().with_expansion(
1434 LayoutExpansion::new(ExpandDepth::Levels(1))
1435 .with_toggled([text("a"), OwnedValue::Float(f64::INFINITY)])
1436 .with_toggled([text("b")]),
1437 );
1438 assert_eq!(
1439 codec.encode(&mixed).unwrap(),
1440 r#"{"version":1,"columns":[],"expansion":{"depth":1,"toggled":[["b"]]}}"#
1441 );
1442
1443 for (json, depth) in [
1446 (r#"{"depth":"all"}"#, ExpandDepth::All),
1447 (r#"{"depth":"captions"}"#, ExpandDepth::Captions),
1448 (r#"{"depth":0}"#, ExpandDepth::Levels(0)),
1449 (r#"{"depth":2,"rows":[[1]]}"#, ExpandDepth::Levels(2)),
1450 (r#"{}"#, ExpandDepth::All),
1451 (r#"{"toggled":[]}"#, ExpandDepth::All),
1452 ] {
1453 let text = format!(r#"{{"version":1,"columns":[],"expansion":{json}}}"#);
1454 let layout = codec.decode(&text).unwrap();
1455 assert_eq!(
1456 layout
1457 .expansion()
1458 .map_or(ExpandDepth::All, LayoutExpansion::depth),
1459 depth,
1460 "{json}"
1461 );
1462 }
1463 for json in [r#""deep""#, r#""All""#, "-1", "1.5", "65536", "null", "[1]"] {
1464 let text = format!(r#"{{"version":1,"columns":[],"expansion":{{"depth":{json}}}}}"#);
1465 assert!(
1466 matches!(codec.decode(&text), Err(LayoutError::Decode(_))),
1467 "{json}"
1468 );
1469 }
1470 }
1471
1472 #[test]
1473 fn test_layout_report_groups() {
1474 let schema = ["a", "b", "c", "d", "e"].map(|id| LayoutColumn::new(id, 50_f32));
1476 let ungroupable = [ColumnId::from("e")];
1477 let context = LayoutMergeContext::new(&schema).with_ungroupable(&ungroupable);
1478 assert!(context.is_groupable("a") && context.contains("e"));
1479 assert!(!context.is_groupable("e") && !context.is_groupable("gone"));
1480 assert!(
1481 LayoutMergeContext::new(&schema).is_groupable("e"),
1482 "every column can be grouped by default"
1483 );
1484
1485 let saved = JsonLayoutCodec::default()
1486 .decode(
1487 r#"{
1488 "version": 1,
1489 "columns": [
1490 { "id": "a", "width": 50 }, { "id": "b", "width": 50 },
1491 { "id": "c", "width": 50 }, { "id": "d", "width": 50 },
1492 { "id": "e", "width": 50 }
1493 ],
1494 "sort": [
1495 { "column": "gone", "direction": "ascending" },
1496 { "column": "e", "direction": "ascending" }
1497 ],
1498 "group_by": [
1499 { "column": "a", "direction": "ascending" },
1500 { "column": "gone", "direction": "ascending" },
1501 { "column": "b", "direction": "descending" },
1502 { "column": "a", "direction": "descending" },
1503 { "column": "e", "direction": "ascending" },
1504 { "column": "gone", "direction": "descending" },
1505 { "column": "c", "direction": "ascending" }
1506 ],
1507 "expansion": {
1508 "depth": 9,
1509 "toggled": [
1510 ["x"], [], [1, 2, 3], [1, 2, 3, 4], ["x", "y"],
1511 [{ "date": "2026-11-04" }], ["x", [1]], [18446744073709551615]
1512 ]
1513 }
1514 }"#,
1515 )
1516 .unwrap();
1517 assert_eq!(saved.expansion().unwrap().toggled().len(), 5);
1519
1520 let report = LayoutReport::resolve(&context, &saved);
1521 assert_eq!(ids(report.dropped_group_by()), ["gone", "a", "e"]);
1523 assert_eq!(report.dropped_expansion(), 5);
1525 assert_eq!(ids(report.dropped_sort()), ["gone"]);
1527 assert!(report.ignored_columns().is_empty() && report.added_columns().is_empty());
1528 assert!(!report.is_exact());
1529
1530 let resolved = ResolvedGrouping::new(&context, &saved);
1532 let levels: Vec<_> = resolved
1533 .levels()
1534 .iter()
1535 .map(|level| (level.column().as_str(), level.direction()))
1536 .collect();
1537 assert_eq!(
1538 levels,
1539 [
1540 ("a", SortDirection::Ascending),
1541 ("b", SortDirection::Descending),
1542 ("c", SortDirection::Ascending),
1543 ]
1544 );
1545 let int = OwnedValue::Int;
1546 assert_eq!(
1547 resolved.toggled(),
1548 [
1549 &[text("x")][..],
1550 &[int(1), int(2), int(3)],
1551 &[text("x"), text("y")],
1552 ]
1553 );
1554 assert_eq!(resolved.depth(), ExpandDepth::Levels(9));
1556
1557 let gone = GridLayout::new()
1559 .with_group_by([LayoutGroup::new("gone", SortDirection::Ascending)])
1560 .with_expansion(LayoutExpansion::new(ExpandDepth::Captions).with_toggled([text("x")]));
1561 let report = LayoutReport::resolve(&context, &gone);
1562 assert_eq!(ids(report.dropped_group_by()), ["gone"]);
1563 assert_eq!(report.dropped_expansion(), 1);
1564 let resolved = ResolvedGrouping::new(&context, &gone);
1565 assert!(resolved.levels().is_empty() && resolved.toggled().is_empty());
1566 assert_eq!(resolved.depth(), ExpandDepth::Captions);
1567
1568 let depth_only = |expansion: LayoutExpansion| {
1570 schema
1571 .iter()
1572 .cloned()
1573 .fold(GridLayout::new(), GridLayout::with_column)
1574 .with_expansion(expansion)
1575 };
1576 let report = LayoutReport::resolve(
1577 &context,
1578 &depth_only(LayoutExpansion::new(ExpandDepth::Levels(0))),
1579 );
1580 assert!(report.is_exact());
1581 let report = LayoutReport::resolve(
1582 &context,
1583 &depth_only(LayoutExpansion::new(ExpandDepth::Levels(0)).with_toggled([text("x")])),
1584 );
1585 assert_eq!(report.dropped_expansion(), 1);
1586
1587 let fits = depth_only(
1589 LayoutExpansion::new(ExpandDepth::All)
1590 .with_toggled([text("x")])
1591 .with_toggled([text("x"), OwnedValue::Empty]),
1592 )
1593 .with_group_by([
1594 LayoutGroup::new("d", SortDirection::Descending),
1595 LayoutGroup::new("a", SortDirection::Ascending),
1596 ]);
1597 assert!(LayoutReport::resolve(&context, &fits).is_exact());
1598 assert_eq!(ResolvedGrouping::new(&context, &fits).toggled().len(), 2);
1599 }
1600
1601 #[test]
1602 fn test_old_build_reads_new_layout() {
1603 #[derive(Debug, PartialEq, Serialize, Deserialize)]
1605 struct OldLayout {
1606 version: u32,
1607 #[serde(default, skip_serializing_if = "Option::is_none")]
1608 view_id: Option<String>,
1609 columns: Vec<LayoutColumn>,
1610 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1611 sort: Vec<LayoutSort>,
1612 }
1613
1614 let fixture = include_str!("../tests/fixtures/layout-v1-groups.json");
1616 let old: OldLayout = serde_json::from_str(fixture).unwrap();
1617 let layout = grouped_layout();
1618 assert_eq!(old.version, GridLayout::VERSION);
1619 assert_eq!(old.view_id.as_deref(), layout.view_id());
1620 assert_eq!(old.columns, layout.columns());
1621 assert_eq!(old.sort, layout.sort());
1622
1623 let saved_again = serde_json::to_string(&old).unwrap();
1626 let read = JsonLayoutCodec::default().decode(&saved_again).unwrap();
1627 assert_eq!(
1628 read,
1629 layout
1630 .with_group_by(Vec::new())
1631 .with_expansion(LayoutExpansion::default())
1632 );
1633
1634 let reference = reference_layout();
1636 let old = OldLayout {
1637 version: reference.version(),
1638 view_id: reference.view_id().map(str::to_owned),
1639 columns: reference.columns().to_vec(),
1640 sort: reference.sort().to_vec(),
1641 };
1642 assert_eq!(
1643 serde_json::to_string(&old).unwrap(),
1644 JsonLayoutCodec::default().encode(&reference).unwrap()
1645 );
1646 }
1647
1648 #[test]
1649 fn test_layout_round_trip_property() {
1650 const IDS: [&str; 10] = ["id", "a", "b", "c", "d", "e", "f", "g", "Цена", "量"];
1651 const PIECES: [&str; 10] = ["a", "Я", "✓", "😀", "\"", "\\", "\n", " ", "é", "中"];
1652
1653 fn value(rng: &mut fastrand::Rng) -> OwnedValue {
1654 match rng.u8(..7) {
1655 0 => OwnedValue::Empty,
1656 1 => OwnedValue::Bool(rng.bool()),
1657 2 => OwnedValue::Int(rng.i64(..)),
1658 3 => loop {
1660 let float = f64::from_bits(rng.u64(..));
1661 if float.is_finite() {
1662 break OwnedValue::Float(float);
1663 }
1664 },
1665 4 => OwnedValue::Float(match rng.u8(..4) {
1667 0 => (rng.f64() - 0.5) * 1e6,
1668 1 => rng.i32(..) as f64,
1669 2 => 0.,
1670 _ => -0.,
1671 }),
1672 _ => OwnedValue::Text(
1673 (0..rng.usize(..6))
1674 .map(|_| PIECES[rng.usize(..PIECES.len())])
1675 .collect::<String>()
1676 .into(),
1677 ),
1678 }
1679 }
1680
1681 fn direction(rng: &mut fastrand::Rng) -> SortDirection {
1682 if rng.bool() {
1683 SortDirection::Ascending
1684 } else {
1685 SortDirection::Descending
1686 }
1687 }
1688
1689 let zones = [
1690 ColumnZone::FrozenLeft,
1691 ColumnZone::Scrolling,
1692 ColumnZone::FrozenRight,
1693 ];
1694 for seed in 0..300 {
1695 let mut rng = fastrand::Rng::with_seed(seed);
1696 let mut layout = GridLayout::new();
1697 if rng.bool() {
1698 layout = layout.with_view_id(PIECES[rng.usize(..PIECES.len())]);
1699 }
1700 for _ in 0..rng.usize(..=8) {
1701 layout = layout.with_column(
1702 LayoutColumn::new(IDS[rng.usize(..IDS.len())], rng.u16(1..800) as f32 / 2.)
1703 .with_visible(rng.bool())
1704 .with_zone(zones[rng.usize(..3)]),
1705 );
1706 }
1707 let id = |rng: &mut fastrand::Rng| IDS[rng.usize(..IDS.len())];
1708 let sort: Vec<_> = (0..rng.usize(..=3))
1709 .map(|_| LayoutSort::new(id(&mut rng), direction(&mut rng)))
1710 .collect();
1711 let levels: Vec<_> = (0..rng.usize(..=3))
1712 .map(|_| LayoutGroup::new(id(&mut rng), direction(&mut rng)))
1713 .collect();
1714 let depth = match rng.u8(..4) {
1715 0 => ExpandDepth::All,
1716 1 => ExpandDepth::Captions,
1717 _ => ExpandDepth::Levels(rng.u16(..5)),
1718 };
1719 let mut expansion = LayoutExpansion::new(depth);
1720 for _ in 0..rng.usize(..=10) {
1721 let path: Vec<_> = (0..rng.usize(1..=3)).map(|_| value(&mut rng)).collect();
1722 expansion = expansion.with_toggled(path);
1723 }
1724 let layout = layout
1725 .with_sort(sort)
1726 .with_group_by(levels)
1727 .with_expansion(expansion);
1728
1729 for codec in [
1730 JsonLayoutCodec::default(),
1731 JsonLayoutCodec::default().pretty(true),
1732 ] {
1733 let text = codec.encode(&layout).unwrap();
1734 let read = codec.decode(&text).unwrap();
1735 assert_eq!(read, layout, "seed {seed}: {text}");
1736 assert_eq!(codec.encode(&read).unwrap(), text, "seed {seed}");
1738 }
1739 }
1740 }
1741
1742 #[test]
1747 #[ignore = "timing; run in release with --ignored --nocapture"]
1748 #[cfg(not(target_family = "wasm"))]
1749 fn test_layout_codec_timing() {
1750 use std::{hint::black_box, time::Instant};
1751
1752 let names: Vec<String> = (0..128).map(|ix| format!("column_{ix}")).collect();
1753 let mut expansion = LayoutExpansion::new(ExpandDepth::Levels(1));
1754 for ix in 0..10 {
1755 expansion = expansion.with_toggled([
1756 text(&format!("instrument {ix}")),
1757 text("Buy"),
1758 OwnedValue::Float(100.25 + f64::from(ix)),
1759 ]);
1760 }
1761 let layout = names
1762 .iter()
1763 .map(|name| LayoutColumn::new(name.clone(), 96.5_f32))
1764 .fold(
1765 GridLayout::new().with_view_id("trades"),
1766 GridLayout::with_column,
1767 )
1768 .with_sort([LayoutSort::new("column_3", SortDirection::Descending)])
1769 .with_group_by(
1770 names[..3]
1771 .iter()
1772 .map(|name| LayoutGroup::new(name.clone(), SortDirection::Ascending)),
1773 )
1774 .with_expansion(expansion);
1775
1776 let codec = JsonLayoutCodec::default();
1777 let text = codec.encode(&layout).unwrap();
1778 let micros = |run: &dyn Fn()| {
1779 (0..5)
1780 .map(|_| {
1781 let started = Instant::now();
1782 for _ in 0..1_000 {
1783 run();
1784 }
1785 started.elapsed().as_secs_f64() * 1e6 / 1_000.
1786 })
1787 .fold(f64::MAX, f64::min)
1788 };
1789 let encode = micros(&|| {
1790 black_box(codec.encode(black_box(&layout)).unwrap());
1791 });
1792 let decode = micros(&|| {
1793 black_box(codec.decode(black_box(&text)).unwrap());
1794 });
1795 println!(
1796 "{} bytes: encode {encode:.1} µs, decode {decode:.1} µs",
1797 text.len()
1798 );
1799 }
1800
1801 #[test]
1802 fn test_layout_version_rules() {
1803 let codec = JsonLayoutCodec::default();
1804 for (text, found) in [
1805 (r#"{"version":2,"columns":[]}"#, 2),
1806 (r#"{"version":0,"columns":[]}"#, 0),
1807 (r#"{"version":99,"columns":"by id"}"#, 99),
1810 (r#"{"version":4294967296,"columns":[]}"#, u32::MAX),
1811 ] {
1812 assert_eq!(
1813 codec.decode(text),
1814 Err(LayoutError::UnsupportedVersion { found }),
1815 "{text}"
1816 );
1817 }
1818 for text in [
1819 r#"{"columns":[]}"#,
1820 r#"{"version":"1","columns":[]}"#,
1821 r#"{"version":-1,"columns":[]}"#,
1822 r#"{"version":1.5,"columns":[]}"#,
1823 r#"{"version":1}"#,
1824 r#"[{"version":1,"columns":[]}]"#,
1825 "not json",
1826 "",
1827 ] {
1828 assert!(
1829 matches!(codec.decode(text), Err(LayoutError::Decode(_))),
1830 "{text}"
1831 );
1832 }
1833
1834 let newer: GridLayout = serde_json::from_str(r#"{"version":2,"columns":[]}"#).unwrap();
1837 assert_eq!(newer.version(), 2);
1838 assert_eq!(
1839 check_version(newer.version()),
1840 Err(LayoutError::UnsupportedVersion { found: 2 })
1841 );
1842 assert_eq!(check_version(GridLayout::VERSION), Ok(()));
1843 }
1844
1845 #[test]
1846 fn test_append_new_columns() {
1847 let schema = [
1849 LayoutColumn::new("id", 80_f32).with_zone(ColumnZone::FrozenLeft),
1850 LayoutColumn::new("name", 120_f32),
1851 LayoutColumn::new("fee", 60_f32),
1852 LayoutColumn::new("price", 90_f32),
1853 LayoutColumn::new("flag", 40_f32).with_zone(ColumnZone::FrozenLeft),
1854 LayoutColumn::new("qty", 70_f32).with_visible(false),
1855 LayoutColumn::new("note", 200_f32).with_visible(false),
1856 LayoutColumn::new("side", 50_f32).with_zone(ColumnZone::FrozenRight),
1857 ];
1858 let context = LayoutMergeContext::new(&schema);
1859 assert!(context.contains("fee") && !context.contains("gone"));
1860 assert_eq!(context.column("qty"), Some(&schema[5]));
1861
1862 let saved = GridLayout::new()
1863 .with_column(LayoutColumn::new("price", 101_f32))
1864 .with_column(LayoutColumn::new("gone", 55_f32))
1865 .with_column(LayoutColumn::new("name", 133_f32).with_visible(false))
1866 .with_column(LayoutColumn::new("price", 999_f32).with_zone(ColumnZone::FrozenLeft))
1867 .with_column(LayoutColumn::new("qty", 71_f32).with_zone(ColumnZone::FrozenRight))
1868 .with_column(LayoutColumn::new("id", 81_f32).with_zone(ColumnZone::FrozenLeft))
1869 .with_column(LayoutColumn::new("side", 51_f32).with_zone(ColumnZone::FrozenRight))
1870 .with_column(LayoutColumn::new("gone", 56_f32))
1871 .with_sort([
1872 LayoutSort::new("gone", SortDirection::Descending),
1873 LayoutSort::new("price", SortDirection::Ascending),
1874 LayoutSort::new("price", SortDirection::Descending),
1875 LayoutSort::new("side", SortDirection::Ascending),
1876 LayoutSort::new("zz", SortDirection::Ascending),
1877 ]);
1878
1879 let merged = AppendNewColumns.merge(&context, &saved);
1883 let expected = [
1884 LayoutColumn::new("id", 81_f32).with_zone(ColumnZone::FrozenLeft),
1885 LayoutColumn::new("flag", 40_f32).with_zone(ColumnZone::FrozenLeft),
1886 LayoutColumn::new("price", 101_f32),
1887 LayoutColumn::new("name", 133_f32).with_visible(false),
1888 LayoutColumn::new("fee", 60_f32),
1889 LayoutColumn::new("note", 200_f32).with_visible(false),
1890 LayoutColumn::new("qty", 71_f32).with_zone(ColumnZone::FrozenRight),
1891 LayoutColumn::new("side", 51_f32).with_zone(ColumnZone::FrozenRight),
1892 ];
1893 assert_eq!(merged, expected);
1894
1895 let report = LayoutReport::resolve(&context, &saved);
1898 assert_eq!(ids(report.ignored_columns()), ["gone"]);
1899 assert_eq!(ids(report.added_columns()), ["fee", "flag", "note"]);
1900 assert_eq!(ids(report.dropped_sort()), ["gone", "price", "zz"]);
1901 assert!(!report.is_exact());
1902
1903 let schema_only = AppendNewColumns.merge(&context, &GridLayout::new());
1905 let order: Vec<_> = schema_only.iter().map(|c| c.id().as_str()).collect();
1906 assert_eq!(
1907 order,
1908 ["id", "flag", "name", "fee", "price", "qty", "note", "side"]
1909 );
1910
1911 let round_trip = merged
1913 .iter()
1914 .cloned()
1915 .fold(GridLayout::new(), GridLayout::with_column)
1916 .with_sort([LayoutSort::new("price", SortDirection::Ascending)]);
1917 assert!(LayoutReport::resolve(&context, &round_trip).is_exact());
1918 assert_eq!(AppendNewColumns.merge(&context, &round_trip), merged);
1919 }
1920
1921 #[test]
1922 fn test_layout_library() {
1923 let trades = |width: f32| {
1924 GridLayout::new()
1925 .with_view_id("trades")
1926 .with_column(LayoutColumn::new("price", width))
1927 };
1928 let names = |library: &LayoutLibrary, view_id: &str| -> Vec<String> {
1929 library.names(view_id).map(str::to_owned).collect()
1930 };
1931
1932 let mut library = LayoutLibrary::new();
1933 assert_eq!(
1934 library.insert("Wide", GridLayout::new()),
1935 Err(LayoutError::MissingViewId)
1936 );
1937 library.insert("Wide", trades(200.)).unwrap();
1938 library.insert("Compact", trades(60.)).unwrap();
1939 library.insert("Wide", trades(240.)).unwrap();
1940 library
1941 .insert("Default", GridLayout::new().with_view_id("orders"))
1942 .unwrap();
1943 assert_eq!(names(&library, "trades"), ["Compact", "Wide"]);
1944 assert_eq!(names(&library, "orders"), ["Default"]);
1945 assert_eq!(names(&library, "positions"), Vec::<String>::new());
1946 assert_eq!(library.get("trades", "Wide"), Some(&trades(240.)));
1947 assert_eq!(library.get("orders", "Wide"), None);
1948
1949 assert_eq!(library.default_layout("trades"), None);
1950 assert!(!library.set_default("trades", Some("Missing")));
1951 assert!(!library.set_default("positions", Some("Wide")));
1952 assert!(library.set_default("trades", Some("Compact")));
1953 assert_eq!(
1954 library.default_layout("trades"),
1955 Some(("Compact", &trades(60.)))
1956 );
1957
1958 assert!(!library.rename("trades", "Compact", "Wide"));
1960 assert!(!library.rename("trades", "Missing", "Other"));
1961 assert!(!library.rename("positions", "Compact", "Other"));
1962 assert!(library.rename("trades", "Compact", "Compact"));
1963 assert!(library.rename("trades", "Compact", "Narrow"));
1964 assert_eq!(names(&library, "trades"), ["Narrow", "Wide"]);
1965 assert_eq!(
1966 library.default_layout("trades"),
1967 Some(("Narrow", &trades(60.)))
1968 );
1969
1970 let text = serde_json::to_string(&library).unwrap();
1972 assert_eq!(
1973 serde_json::from_str::<LayoutLibrary>(&text).unwrap(),
1974 library
1975 );
1976 let mut orders_only = LayoutLibrary::new();
1977 orders_only
1978 .insert("Default", GridLayout::new().with_view_id("orders"))
1979 .unwrap();
1980 assert_eq!(
1981 serde_json::to_string(&orders_only).unwrap(),
1982 r#"{"views":{"orders":{"layouts":{"Default":{"version":1,"view_id":"orders","columns":[]}}}}}"#
1983 );
1984
1985 assert_eq!(library.remove("trades", "Narrow"), Some(trades(60.)));
1987 assert_eq!(library.remove("trades", "Narrow"), None);
1988 assert_eq!(library.default_layout("trades"), None);
1989 assert!(library.set_default("trades", Some("Wide")));
1990 assert!(library.set_default("trades", None));
1991 assert_eq!(library.default_layout("trades"), None);
1992 assert_eq!(library.remove("trades", "Wide"), Some(trades(240.)));
1993 assert_eq!(names(&library, "trades"), Vec::<String>::new());
1994 assert!(library.set_default("trades", None));
1995 assert_eq!(
1996 library.get("orders", "Default").map(GridLayout::version),
1997 Some(1)
1998 );
1999 }
2000}