Skip to main content

byob_types/
layout.rs

1//! What byob's interface shows, and in what order: the **layout**.
2//!
3//! Every optional piece of the window's chrome has an id in [`ELEMENTS`] (`reply.tokens`,
4//! `header.usage`, …) and a [`Show`] mode: always, only while the pointer is on it, or never.
5//! A few regions ([`REGIONS`]) can be reordered: their elements, plus plugin views drawn
6//! there (`view:<plugin>/<view>`), which are placed and hidden the same way as byob's own.
7//!
8//! The engine keeps one layout (settings.json `layout`) and sends it to every client, so a
9//! change made in Settings or by the model (the `ui_layout` tool) shows everywhere at once.
10//! Only what differs from the defaults is stored; elements a newer build adds get their
11//! defaults, and ids this build doesn't know are kept (a newer build's, or a plugin's that
12//! isn't loaded).
13
14use std::collections::BTreeMap;
15
16use serde::de::DeserializeOwned;
17use serde::{Deserialize, Deserializer, Serialize};
18use serde_json::Value;
19
20// Reading is forgiving: a value this build can't read (a newer build's, a hand edit) is
21// dropped alone, so the rest of the layout (Spaces, sections, pins) survives.
22
23/// A field of the wrong shape is its default.
24fn lenient<'de, D: Deserializer<'de>, T: DeserializeOwned + Default>(d: D) -> Result<T, D::Error> {
25    Ok(serde_json::from_value(Value::deserialize(d)?).unwrap_or_default())
26}
27
28/// A list whose entries are read one by one: those that can't be are dropped.
29fn lenient_list<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<Vec<T>, D::Error> {
30    match Value::deserialize(d)? {
31        Value::Array(items) => Ok(items.into_iter().filter_map(|v| serde_json::from_value(v).ok()).collect()),
32        _ => Ok(Vec::new()),
33    }
34}
35
36/// A map whose entries are read one by one: those that can't be are dropped.
37fn lenient_map<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<BTreeMap<String, T>, D::Error> {
38    match Value::deserialize(d)? {
39        Value::Object(map) => Ok(map.into_iter().filter_map(|(k, v)| serde_json::from_value(v).ok().map(|v| (k, v))).collect()),
40        _ => Ok(BTreeMap::new()),
41    }
42}
43
44/// How an element is shown.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum Show {
48    /// Always there.
49    Shown,
50    /// Only while the pointer is on what it belongs to (the reply, the header, the row).
51    Hover,
52    /// Never.
53    Hidden,
54}
55
56impl Show {
57    pub const ALL: [Self; 3] = [Self::Shown, Self::Hover, Self::Hidden];
58
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Self::Shown => "shown",
62            Self::Hover => "hover",
63            Self::Hidden => "hidden",
64        }
65    }
66
67    pub fn parse(s: &str) -> Option<Self> {
68        match s.trim().to_ascii_lowercase().as_str() {
69            "shown" | "show" | "always" | "visible" | "on" => Some(Self::Shown),
70            "hover" | "on_hover" | "on hover" | "hovered" => Some(Self::Hover),
71            "hidden" | "hide" | "never" | "off" | "none" => Some(Self::Hidden),
72            _ => None,
73        }
74    }
75
76    /// Whether it is drawn now, `hovered` being whether the pointer is on its owner.
77    pub fn visible(self, hovered: bool) -> bool {
78        match self {
79            Self::Shown => true,
80            Self::Hover => hovered,
81            Self::Hidden => false,
82        }
83    }
84}
85
86/// A region whose elements can be reordered.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct Region {
89    pub id: &'static str,
90    /// Where it is, for people (and the model).
91    pub describe: &'static str,
92    /// Whether plugin views (`view:…`) are drawn here.
93    pub plugin_views: bool,
94}
95
96/// An element of the interface that can be shown, hidden or moved.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct Element {
99    pub id: &'static str,
100    /// Its name in Settings.
101    pub label: &'static str,
102    /// What it is, for people (and the model).
103    pub describe: &'static str,
104    /// The region it can be moved within, if any.
105    pub region: Option<&'static str>,
106    pub default: Show,
107    /// Whether [`Show::Hover`] means something for it (else it acts as shown).
108    pub hover: bool,
109}
110
111pub const HEADER: &str = "header";
112pub const TOOLBAR: &str = "toolbar";
113pub const REPLY: &str = "reply";
114
115/// The regions that can be reordered, each listed left to right.
116pub const REGIONS: &[Region] = &[
117    Region { id: HEADER, describe: "the header after the chat's title, left to right", plugin_views: false },
118    Region { id: TOOLBAR, describe: "the header's buttons on the right, left to right (the More menu always stays last)", plugin_views: true },
119    Region { id: REPLY, describe: "the details under a reply, left to right", plugin_views: false },
120];
121
122const fn el(id: &'static str, label: &'static str, describe: &'static str, region: Option<&'static str>, default: Show, hover: bool) -> Element {
123    Element { id, label, describe, region, default, hover }
124}
125
126/// Everything the layout knows, in the order Settings lists them (and each region's default order).
127pub const ELEMENTS: &[Element] = &[
128    // Header, after the title.
129    el("header.model", "Model", "the model chip: which model this chat uses; click it to switch", Some(HEADER), Show::Shown, true),
130    el("header.usage", "Context meter", "the bar of how full the chat's context is; click it for details", Some(HEADER), Show::Shown, true),
131    el("header.server", "Server address", "the server's address inside the model chip, on wide windows", None, Show::Shown, false),
132    el("header.usage_numbers", "Context numbers", "tokens used out of the context window, next to the context meter", None, Show::Shown, true),
133    el("header.wordmark", "Wordmark", "the \"byob\" name on the left of the header, on wide windows", None, Show::Shown, false),
134    el("header.workspace", "Workspace name", "the workspace's name before the chat's title", None, Show::Shown, true),
135    // Header, right.
136    el("toolbar.panes", "Plugin panes", "buttons that open plugins' panes beside the chat", Some(TOOLBAR), Show::Shown, true),
137    el("toolbar.artifacts", "Artifacts button", "the button that shows or hides the artifact pane", Some(TOOLBAR), Show::Shown, true),
138    el("toolbar.plugins", "Plugins chip", "how many plugins are on, with a badge when one has trouble", Some(TOOLBAR), Show::Shown, true),
139    // Messages.
140    el("message.role", "Who said it", "\"You\" and \"byob\" above each message", None, Show::Shown, false),
141    el(
142        "message.thinking",
143        "Thinking",
144        "the \"Thought\" row that opens the model's thinking; hidden, it shows only while the model is still thinking",
145        None,
146        Show::Shown,
147        false,
148    ),
149    el("message.thought_size", "Thinking length", "how long the model's thinking was, next to \"Thought\" (\"1.1k chars\")", None, Show::Shown, false),
150    el(
151        "message.steps",
152        "Tool steps",
153        "a row for each tool the model ran (\"Read notes.md\", \"Made Rain haiku\"); hidden, they show only while running (failed ones are hidden too; questions and approvals always show)",
154        None,
155        Show::Shown,
156        false,
157    ),
158    el("message.step_files", "Files changed", "\"1 file\" (\"3 files\") on a tool's row when it changed files", None, Show::Shown, false),
159    el("message.subagent_details", "Subagent details", "the model and tokens on a subagent's row", None, Show::Shown, false),
160    el("message.edit", "Edit button", "\"Edit\" on your messages: change one and start the chat over from there", None, Show::Hover, true),
161    el("message.undo", "Undo button", "\"Undo changes\" under a reply that changed files", None, Show::Shown, true),
162    el(
163        "reply.tokens",
164        "Tokens",
165        "tokens under each reply: how full the context was at its end, what the model wrote, and what several requests read together",
166        Some(REPLY),
167        Show::Shown,
168        true,
169    ),
170    el("reply.time", "Time", "how long the reply took, under each reply", Some(REPLY), Show::Shown, true),
171    el("reply.speed", "Speed", "tokens per second the model wrote, under each reply", Some(REPLY), Show::Hidden, true),
172    // Artifacts and code in replies.
173    el("artifact.kind", "Artifact kind", "the kind badge on an artifact's card in a reply (\"DOCUMENT\", \"APP\", \"CHART\")", None, Show::Shown, false),
174    el("artifact.version", "Artifact version", "the version on an artifact's card in a reply (\"v1\") and its note", None, Show::Shown, false),
175    el(
176        "artifact.shown",
177        "Artifact shown note",
178        "\"Shown beside the chat\" on an artifact's card in a reply while it's open in the artifact pane",
179        None,
180        Show::Shown,
181        true,
182    ),
183    el("code.language", "Code language", "the language (\"rust\", \"code\") at the top left of a code block", None, Show::Shown, true),
184    el("code.copy", "Code copy button", "\"Copy\" at the top right of a code block", None, Show::Shown, true),
185    // Elsewhere.
186    el("chat.starters", "Suggestions", "the suggested prompts in an empty chat (\"Ask anything to get started, or try:\")", None, Show::Shown, false),
187    el(
188        "composer.attach",
189        "Attach button",
190        "the paperclip that attaches files, left of the message box (dropping or pasting files still works)",
191        None,
192        Show::Shown,
193        false,
194    ),
195    el("composer.keys", "Composer keys", "\"Enter to send, Shift+Enter for a new line\" in the empty message box", None, Show::Shown, false),
196    el("sidebar.shortcuts", "Sidebar shortcuts", "the keyboard shortcuts on New chat and the search field", None, Show::Shown, true),
197];
198
199/// Where elements that aren't in a region are, by id prefix, in the order Settings lists them.
200pub const GROUPS: &[(&str, &str)] = &[
201    ("header", "Header"),
202    ("message", "Messages"),
203    ("artifact", "Artifacts in replies"),
204    ("code", "Code blocks"),
205    ("chat", "Empty chat"),
206    ("composer", "Message box"),
207    ("sidebar", "Sidebar"),
208];
209
210/// The heading of the group element `id` is in ([`GROUPS`]).
211pub fn group(id: &str) -> &'static str {
212    let prefix = id.split('.').next().unwrap_or_default();
213    GROUPS.iter().find(|(p, _)| *p == prefix).map_or("Other", |(_, name)| name)
214}
215
216/// The element with id `id`.
217pub fn element(id: &str) -> Option<&'static Element> {
218    ELEMENTS.iter().find(|e| e.id == id)
219}
220
221/// The region with id `id`.
222pub fn region(id: &str) -> Option<&'static Region> {
223    REGIONS.iter().find(|r| r.id == id)
224}
225
226/// The id of plugin `plugin`'s view `view` in a layout.
227pub fn view_id(plugin: &str, view: &str) -> String {
228    format!("view:{plugin}/{view}")
229}
230
231/// Ready-made layouts.
232pub const PRESETS: &[(&str, &str)] = &[
233    ("everything", "every detail shown (byob's default)"),
234    ("balanced", "details of replies and the context numbers on hover; labels and shortcut hints hidden"),
235    ("minimal", "only what you need: details on hover, the rest hidden"),
236];
237
238/// Most entries kept per map (ids are few; the rest is a hostile or broken file).
239const MAX_ENTRIES: usize = 256;
240const MAX_ID: usize = 160;
241
242/// Most sections the chat list keeps, items in one, and characters in a section's name.
243const MAX_SECTIONS: usize = 64;
244/// Pinned projects (and, apart, pinned artifacts) the list keeps.
245const MAX_PINS: usize = 64;
246/// Spaces, and what one Space can hold.
247const MAX_SPACES: usize = 16;
248const MAX_SPACE_ITEMS: usize = 5000;
249const MAX_SECTION_ITEMS: usize = 512;
250const MAX_SECTION_NAME: usize = 80;
251
252/// A section of the chat list the person made: a name and what they moved into it
253/// (`chat:<id>`, `ws:<id>`). Only an arrangement: chats and projects stay what they are.
254#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
255#[serde(default)]
256pub struct ListSection {
257    #[serde(deserialize_with = "lenient")]
258    pub id: String,
259    #[serde(deserialize_with = "lenient")]
260    pub name: String,
261    #[serde(deserialize_with = "lenient_list")]
262    pub items: Vec<String>,
263}
264
265/// How the chat list groups what isn't in a section.
266#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "snake_case")]
268pub enum ListGroup {
269    /// Chats without a project, then each project with its chats.
270    #[default]
271    Project,
272    /// Every chat by when it was last active.
273    Date,
274    /// One list.
275    None,
276}
277
278/// The order within the chat list's groups.
279#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(rename_all = "snake_case")]
281pub enum ListSort {
282    #[default]
283    Updated,
284    Name,
285}
286
287/// The chat list's arrangement: the person's sections, the grouping and the order. Part of
288/// the layout so it is the same in every window and browser tab.
289#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
290#[serde(default)]
291pub struct ChatList {
292    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
293    pub sections: Vec<ListSection>,
294    #[serde(deserialize_with = "lenient")]
295    pub group: ListGroup,
296    #[serde(deserialize_with = "lenient")]
297    pub sort: ListSort,
298    /// Projects pinned to the top of the list, by id, in order.
299    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
300    pub pinned_projects: Vec<String>,
301    /// Artifacts pinned to the top of the list, in order.
302    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
303    pub pinned_artifacts: Vec<ListPin>,
304    /// Spaces (Work, Personal, a client): each shows only its own projects and chats. With
305    /// fewer than two there are none to switch between. What no Space claims is the first's.
306    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
307    pub spaces: Vec<ListSpace>,
308}
309
310/// A Space: its name, its color (`#rrggbb`), and the projects and chats it holds
311/// (`ws:<id>`, `chat:<id>`).
312#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
313#[serde(default)]
314pub struct ListSpace {
315    #[serde(deserialize_with = "lenient")]
316    pub id: String,
317    #[serde(deserialize_with = "lenient")]
318    pub name: String,
319    #[serde(deserialize_with = "lenient")]
320    pub color: String,
321    #[serde(deserialize_with = "lenient_list")]
322    pub items: Vec<String>,
323}
324
325/// An artifact pinned to the chat list: the chat it's in, its id, and its title to show.
326#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
327#[serde(default)]
328pub struct ListPin {
329    #[serde(deserialize_with = "lenient")]
330    pub chat: String,
331    #[serde(deserialize_with = "lenient")]
332    pub id: String,
333    #[serde(deserialize_with = "lenient")]
334    pub title: String,
335}
336
337impl ChatList {
338    pub fn is_default(&self) -> bool {
339        *self == Self::default()
340    }
341
342    /// Within the limits: few enough sections and items, names and ids that are text.
343    #[must_use]
344    pub fn sanitized(mut self) -> Self {
345        let ok = |id: &String| !id.is_empty() && id.len() <= MAX_ID && !id.chars().any(char::is_control);
346        self.sections.retain(|s| ok(&s.id));
347        self.sections.truncate(MAX_SECTIONS);
348        for s in &mut self.sections {
349            s.name = s.name.chars().filter(|c| !c.is_control()).take(MAX_SECTION_NAME).collect::<String>().trim().to_owned();
350            if s.name.is_empty() {
351                "Section".clone_into(&mut s.name);
352            }
353            s.items.retain(&ok);
354            s.items.dedup();
355            s.items.truncate(MAX_SECTION_ITEMS);
356        }
357        self.pinned_projects.retain(&ok);
358        self.pinned_projects.dedup();
359        self.pinned_projects.truncate(MAX_PINS);
360        self.pinned_artifacts.retain(|p| ok(&p.chat) && ok(&p.id));
361        self.pinned_artifacts.dedup_by(|a, b| a.id == b.id);
362        self.pinned_artifacts.truncate(MAX_PINS);
363        self.spaces.retain(|sp| ok(&sp.id));
364        self.spaces.truncate(MAX_SPACES);
365        for sp in &mut self.spaces {
366            sp.name = sp.name.chars().filter(|c| !c.is_control()).take(MAX_SECTION_NAME).collect::<String>().trim().to_owned();
367            if sp.name.is_empty() {
368                "Space".clone_into(&mut sp.name);
369            }
370            let hex = sp.color.strip_prefix('#').unwrap_or("");
371            if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
372                sp.color.clear();
373            }
374            sp.items.retain(&ok);
375            sp.items.dedup();
376            sp.items.truncate(MAX_SPACE_ITEMS);
377        }
378        for p in &mut self.pinned_artifacts {
379            p.title = p.title.chars().filter(|c| !c.is_control()).take(MAX_SECTION_NAME * 2).collect::<String>().trim().to_owned();
380        }
381        self
382    }
383}
384
385/// What the interface shows: the modes and orders that differ from the defaults.
386#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
387#[serde(default)]
388pub struct Layout {
389    /// Element id → how it is shown.
390    #[serde(deserialize_with = "lenient_map", skip_serializing_if = "BTreeMap::is_empty")]
391    pub show: BTreeMap<String, Show>,
392    /// Region id → element ids in the order wanted. Ids a region doesn't have are skipped;
393    /// those it has but the list doesn't name follow, in their default order.
394    #[serde(deserialize_with = "lenient_map", skip_serializing_if = "BTreeMap::is_empty")]
395    pub order: BTreeMap<String, Vec<String>>,
396    /// The chat list's sections and view.
397    #[serde(deserialize_with = "lenient", skip_serializing_if = "ChatList::is_default")]
398    pub chat_list: ChatList,
399}
400
401impl Layout {
402    pub fn is_default(&self) -> bool {
403        self.show.is_empty() && self.order.is_empty() && self.chat_list.is_default()
404    }
405
406    /// How element (or plugin view) `id` is shown. Unknown ids are shown.
407    pub fn show(&self, id: &str) -> Show {
408        let mode = self.show.get(id).copied().or_else(|| element(id).map(|e| e.default)).unwrap_or(Show::Shown);
409        match element(id) {
410            Some(e) if !e.hover && mode == Show::Hover => Show::Shown,
411            _ => mode,
412        }
413    }
414
415    /// Whether `id` is drawn now (`hovered`: the pointer is on what it belongs to).
416    pub fn visible(&self, id: &str, hovered: bool) -> bool {
417        self.show(id).visible(hovered)
418    }
419
420    /// Set how `id` is shown; back to the default stores nothing.
421    pub fn set_show(&mut self, id: &str, mode: Show) {
422        if element(id).is_some_and(|e| e.default == mode) {
423            self.show.remove(id);
424        } else {
425            self.show.insert(id.to_owned(), mode);
426        }
427    }
428
429    /// Region `region`'s elements in order: byob's own (in [`ELEMENTS`] order) and then
430    /// `extra` (plugin views drawn there, as found), arranged by the stored order. Hidden
431    /// ones are included; ask [`Self::show`].
432    pub fn arrange(&self, region: &str, extra: &[String]) -> Vec<String> {
433        let mut present: Vec<String> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id.to_owned()).collect();
434        for id in extra {
435            if !present.contains(id) {
436                present.push(id.clone());
437            }
438        }
439        let Some(wanted) = self.order.get(region) else { return present };
440        let mut out: Vec<String> = Vec::with_capacity(present.len());
441        for id in wanted {
442            if present.contains(id) && !out.contains(id) {
443                out.push(id.clone());
444            }
445        }
446        for id in present {
447            if !out.contains(&id) {
448                out.push(id);
449            }
450        }
451        out
452    }
453
454    /// Put region `region` in this order (see [`Self::order`]); the default order stores nothing.
455    pub fn set_order(&mut self, region: &str, ids: Vec<String>) {
456        let default: Vec<&str> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id).collect();
457        let mut ids: Vec<String> = ids.into_iter().filter(|id| !id.is_empty()).collect();
458        ids.dedup();
459        if ids.is_empty() || ids.iter().map(String::as_str).eq(default.iter().copied()) {
460            self.order.remove(region);
461        } else {
462            self.order.insert(region.to_owned(), ids);
463        }
464    }
465
466    /// Move `id` one place earlier (`dir` < 0) or later within region `region`, among `extra`.
467    pub fn nudge(&mut self, region: &str, extra: &[String], id: &str, dir: i32) {
468        let mut ids = self.arrange(region, extra);
469        let Some(i) = ids.iter().position(|x| x == id) else { return };
470        let j = if dir < 0 { i.checked_sub(1) } else { Some(i + 1).filter(|j| *j < ids.len()) };
471        if let Some(j) = j {
472            ids.swap(i, j);
473            self.set_order(region, ids);
474        }
475    }
476
477    /// A ready-made layout by name ([`PRESETS`]).
478    pub fn preset(name: &str) -> Option<Self> {
479        let mut l = Self::default();
480        let hover = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hover));
481        let hide = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hidden));
482        match name.trim().to_ascii_lowercase().as_str() {
483            "everything" | "default" | "full" => {}
484            "balanced" => {
485                hover(&mut l, &["reply.tokens", "reply.time", "header.usage_numbers", "sidebar.shortcuts"]);
486                hide(&mut l, &["message.role", "message.thought_size", "composer.keys"]);
487            }
488            "minimal" => {
489                hover(&mut l, &["reply.tokens", "reply.time", "sidebar.shortcuts", "toolbar.plugins", "artifact.shown", "message.undo", "code.copy"]);
490                hide(
491                    &mut l,
492                    &[
493                        "message.role",
494                        "message.thought_size",
495                        "message.step_files",
496                        "message.subagent_details",
497                        "artifact.version",
498                        "code.language",
499                        "composer.keys",
500                        "header.usage_numbers",
501                        "header.server",
502                        "header.wordmark",
503                    ],
504                );
505            }
506            _ => return None,
507        }
508        Some(l)
509    }
510
511    /// Drop what a broken or hostile file could hold: too many entries, absurd ids, empty orders.
512    #[must_use]
513    pub fn sanitized(mut self) -> Self {
514        let ok = |id: &String| !id.is_empty() && id.len() <= MAX_ID && !id.chars().any(char::is_control);
515        self.show.retain(|id, _| ok(id));
516        while self.show.len() > MAX_ENTRIES {
517            self.show.pop_last();
518        }
519        self.order.retain(|region, ids| {
520            ids.retain(&ok);
521            ids.truncate(MAX_ENTRIES);
522            ok(region) && !ids.is_empty()
523        });
524        while self.order.len() > MAX_ENTRIES {
525            self.order.pop_last();
526        }
527        self.chat_list = self.chat_list.sanitized();
528        self
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535
536    /// Regression: one value this build can't read (a newer build's show mode or grouping, a
537    /// hand edit) made the whole layout unreadable, and settings.json falls back to the
538    /// default layout: every Space, section and pin was gone, and the next save made it so.
539    #[test]
540    fn one_unreadable_value_loses_only_itself() {
541        let json = r#"{
542            "show": {"reply.tokens": "hidden", "header.usage": "sometimes"},
543            "order": {"composer": ["a", 5]},
544            "chat_list": {"group": "by_mood", "sort": "name", "pinned_projects": "w1",
545                "sections": [{"id": "s", "name": "Later", "items": ["chat:1"]}],
546                "spaces": [{"id": "space-1", "name": "Work", "items": ["ws:w1"]}, {"id": "space-2", "name": "Home", "items": [7]}]}
547        }"#;
548        let l: Layout = serde_json::from_str(json).unwrap();
549        assert_eq!(l.show.get("reply.tokens"), Some(&Show::Hidden));
550        assert!(!l.show.contains_key("header.usage"));
551        assert_eq!((l.chat_list.group, l.chat_list.sort), (ListGroup::Project, ListSort::Name));
552        assert!(l.chat_list.pinned_projects.is_empty());
553        assert_eq!(l.chat_list.sections.len(), 1);
554        let spaces: Vec<&str> = l.chat_list.spaces.iter().map(|s| s.name.as_str()).collect();
555        assert_eq!(spaces, ["Work", "Home"]);
556        assert_eq!(l.chat_list.spaces[0].items, ["ws:w1"]);
557    }
558
559    #[test]
560    fn the_chat_list_rides_in_the_layout_and_stays_within_limits() {
561        // Old layouts read as before; a default chat list writes nothing.
562        let l: Layout = serde_json::from_str(r#"{"show":{"reply.speed":"shown"}}"#).unwrap();
563        assert!(l.chat_list.is_default());
564        assert!(!serde_json::to_string(&l).unwrap().contains("chat_list"));
565        let mut l = Layout::default();
566        l.chat_list.group = ListGroup::Date;
567        l.chat_list.sections.push(ListSection {
568            id: "s1".into(),
569            name: "  Design\u{7} work  ".into(),
570            items: vec!["chat:a".into(), "chat:a".into(), String::new()],
571        });
572        let back: Layout = serde_json::from_str(&serde_json::to_string(&l).unwrap()).unwrap();
573        let clean = back.sanitized();
574        assert_eq!(clean.chat_list.group, ListGroup::Date);
575        assert_eq!(clean.chat_list.sections[0].name, "Design work");
576        assert_eq!(clean.chat_list.sections[0].items, ["chat:a"]);
577        assert!(!clean.is_default());
578        let many = ChatList { sections: (0..100).map(|i| ListSection { id: format!("s{i}"), ..ListSection::default() }).collect(), ..ChatList::default() };
579        let many = many.sanitized();
580        assert_eq!(many.sections.len(), MAX_SECTIONS);
581        assert_eq!(many.sections[0].name, "Section");
582    }
583
584    #[test]
585    fn defaults_show_everything_but_speed_and_store_nothing() {
586        let l = Layout::default();
587        for e in ELEMENTS {
588            assert_eq!(l.show(e.id), e.default, "{}", e.id);
589        }
590        assert_eq!(l.show("reply.speed"), Show::Hidden);
591        assert_eq!(l.show("view:todo/count"), Show::Shown);
592        let mut l = Layout::default();
593        l.set_show("reply.tokens", Show::Hover);
594        l.set_show("reply.tokens", Show::Shown);
595        assert!(l.is_default(), "back to the default stores nothing");
596        assert_eq!(serde_json::to_string(&l).unwrap(), "{}");
597    }
598
599    #[test]
600    fn hover_falls_back_to_shown_where_it_means_nothing() {
601        let mut l = Layout::default();
602        l.set_show("message.role", Show::Hover);
603        assert_eq!(l.show("message.role"), Show::Shown);
604        l.set_show("reply.time", Show::Hover);
605        assert!(!l.visible("reply.time", false));
606        assert!(l.visible("reply.time", true));
607    }
608
609    #[test]
610    fn arranging_puts_named_ids_first_and_keeps_the_rest_in_their_order() {
611        let views = vec!["view:todo/count".to_owned()];
612        let mut l = Layout::default();
613        assert_eq!(l.arrange(TOOLBAR, &views), ["toolbar.panes", "toolbar.artifacts", "toolbar.plugins", "view:todo/count"]);
614        l.set_order(TOOLBAR, vec!["view:todo/count".into(), "nope".into(), "toolbar.plugins".into()]);
615        assert_eq!(l.arrange(TOOLBAR, &views), ["view:todo/count", "toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
616        // A plugin view that isn't loaded is skipped (and kept for when it is).
617        assert_eq!(l.arrange(TOOLBAR, &[]), ["toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
618        assert!(l.order[TOOLBAR].contains(&"view:todo/count".to_owned()));
619    }
620
621    #[test]
622    fn nudging_moves_one_place_and_the_default_order_stores_nothing() {
623        let mut l = Layout::default();
624        l.nudge(REPLY, &[], "reply.time", -1);
625        assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"]);
626        l.nudge(REPLY, &[], "reply.time", -1);
627        assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"], "already first");
628        l.nudge(REPLY, &[], "reply.time", 1);
629        assert!(l.is_default());
630    }
631
632    #[test]
633    fn presets_are_named_and_known() {
634        for (name, _) in PRESETS {
635            assert!(Layout::preset(name).is_some(), "{name}");
636        }
637        assert!(Layout::preset("everything").unwrap().is_default());
638        assert!(Layout::preset("sparkly").is_none());
639        let min = Layout::preset("minimal").unwrap();
640        assert!(!min.visible("reply.tokens", false) && min.visible("reply.tokens", true));
641        for id in min.show.keys() {
642            assert!(element(id).is_some(), "{id}");
643        }
644    }
645
646    #[test]
647    fn modes_parse_loosely_and_sanitizing_drops_junk() {
648        assert_eq!(Show::parse(" Hide "), Some(Show::Hidden));
649        assert_eq!(Show::parse("on hover"), Some(Show::Hover));
650        assert_eq!(Show::parse("maybe"), None);
651        let l: Layout = serde_json::from_str(r#"{"show": {"": "hidden", "a\u0007": "hidden", "reply.time": "hover"}, "order": {"reply": []}}"#).unwrap();
652        let l = l.sanitized();
653        assert_eq!(l.show.len(), 1);
654        assert!(l.order.is_empty());
655    }
656
657    #[test]
658    fn every_element_is_unique_and_its_region_exists() {
659        for (i, e) in ELEMENTS.iter().enumerate() {
660            assert!(ELEMENTS[..i].iter().all(|o| o.id != e.id), "{}", e.id);
661            assert!(e.region.is_none_or(|r| region(r).is_some()), "{}", e.id);
662        }
663    }
664}