lingxia-surface 0.16.0

Core surface presentation primitives (roles, kinds, positions) for the LingXia framework
Documentation
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
//! Platform-neutral projection of ordered `main` surfaces.
//!
//! Desktop skins may render this as sidebar tabs while compact skins may not
//! render a switcher at all. The identity and lifecycle semantics stay the
//! same in both cases.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::{SurfaceContent, SurfaceGraph, SurfaceIcon, SurfaceId, SurfacePresentation};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    rename_all = "lowercase",
    rename_all_fields = "camelCase"
)]
pub enum SwitcherContentKind {
    Lxapp { app_id: String },
    Page { app_id: String },
    Browser,
    Native { capability: String },
}

impl From<&SurfaceContent> for SwitcherContentKind {
    fn from(content: &SurfaceContent) -> Self {
        match content {
            SurfaceContent::Lxapp { app_id, .. } => Self::Lxapp {
                app_id: app_id.clone(),
            },
            SurfaceContent::Page { app_id, .. } => Self::Page {
                app_id: app_id.clone(),
            },
            SurfaceContent::Browser { .. } => Self::Browser,
            SurfaceContent::Native { capability, .. } => Self::Native {
                capability: capability.clone(),
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SurfaceSwitcherItem {
    pub surface_id: SurfaceId,
    pub content: SwitcherContentKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<SurfaceIcon>,
    pub active: bool,
    pub root: bool,
    pub closable: bool,
    pub renameable: bool,
    pub title_overridden: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SurfaceSwitcherSnapshot {
    pub revision: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub root_surface_id: Option<SurfaceId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_surface_id: Option<SurfaceId>,
    pub items: Vec<SurfaceSwitcherItem>,
}

impl SurfaceSwitcherSnapshot {
    pub(crate) fn derive(
        graph: &SurfaceGraph,
        presentations: &HashMap<SurfaceId, SurfacePresentation>,
    ) -> Self {
        let root_surface_id = graph.root_main_id().map(str::to_string);
        let active_surface_id = graph.active_main_id.clone();
        let items = graph
            .mains()
            .into_iter()
            .map(|surface| {
                let presentation = presentations
                    .get(&surface.id)
                    .cloned()
                    .unwrap_or_else(|| SurfacePresentation::for_content(&surface.content));
                let root = root_surface_id.as_deref() == Some(surface.id.as_str());
                SurfaceSwitcherItem {
                    surface_id: surface.id.clone(),
                    content: (&surface.content).into(),
                    title: presentation.title().map(str::to_string),
                    icon: presentation.icon,
                    active: active_surface_id.as_deref() == Some(surface.id.as_str()),
                    root,
                    closable: !root && presentation.capabilities.close,
                    renameable: presentation.capabilities.rename,
                    title_overridden: presentation.custom_title.is_some(),
                }
            })
            .collect();
        Self {
            revision: 0,
            root_surface_id,
            active_surface_id,
            items,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CloseOutcome {
    Closed { removed: Vec<SurfaceId> },
    RejectedRoot { surface_id: SurfaceId },
    NotFound,
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ReplaceMainsError {
    #[error("surface '{surface_id}' is not a main")]
    InvalidRole { surface_id: SurfaceId },
    #[error("duplicate main surface id '{surface_id}'")]
    DuplicateId { surface_id: SurfaceId },
}

impl CloseOutcome {
    pub fn removed(&self) -> &[SurfaceId] {
        match self {
            Self::Closed { removed } => removed,
            Self::RejectedRoot { .. } | Self::NotFound => &[],
        }
    }

    pub fn into_removed(self) -> Vec<SurfaceId> {
        match self {
            Self::Closed { removed } => removed,
            Self::RejectedRoot { .. } | Self::NotFound => Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Role, Surface, SurfaceCapabilities, SurfaceManager, SurfacePresentation};

    fn enable_rename(manager: &mut SurfaceManager, id: &str) {
        let content = manager.graph().get(id).unwrap().content.clone();
        let mut presentation = SurfacePresentation::for_content(&content);
        presentation.capabilities = SurfaceCapabilities {
            close: true,
            rename: true,
        };
        assert!(manager.set_presentation(id, presentation));
    }

    #[test]
    fn first_main_is_the_stable_non_closable_root() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::browser(
            "browser-root",
            Role::Main,
            "https://example.com",
        ));
        manager.open(Surface::native("terminal", Role::Main, "terminal"));

        let snapshot = manager.switcher_snapshot();
        assert_eq!(snapshot.root_surface_id.as_deref(), Some("browser-root"));
        assert!(snapshot.items[0].root);
        assert!(!snapshot.items[0].closable);
        assert!(snapshot.items[1].closable);
        assert_eq!(
            manager.close("browser-root"),
            CloseOutcome::RejectedRoot {
                surface_id: "browser-root".into()
            }
        );
    }

    #[test]
    fn lxapp_content_serializes_provider_identity_for_platform_skins() {
        let content = SwitcherContentKind::Lxapp {
            app_id: "lingxia-chat".into(),
        };

        assert_eq!(
            serde_json::to_value(content).unwrap(),
            serde_json::json!({ "kind": "lxapp", "appId": "lingxia-chat" })
        );
    }

    #[test]
    fn close_other_mains_crosses_content_kinds_but_preserves_root() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        manager.open(Surface::browser(
            "docs",
            Role::Main,
            "https://docs.example.com",
        ));
        manager.open(Surface::native("terminal", Role::Main, "terminal"));
        manager.open(Surface::lxapp("tools", Role::Main, "tools"));

        assert_eq!(manager.close_other_mains("terminal"), vec!["docs"]);
        let snapshot = manager.switcher_snapshot();
        assert_eq!(
            snapshot
                .items
                .iter()
                .map(|item| item.surface_id.as_str())
                .collect::<Vec<_>>(),
            vec!["home", "terminal", "tools"]
        );
    }

    #[test]
    fn custom_title_overrides_provider_updates_until_reset() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::native("terminal", Role::Main, "terminal"));
        enable_rename(&mut manager, "terminal");

        assert!(manager.update_automatic_title("terminal", Some("~/github")));
        assert!(manager.rename("terminal", Some("workspace")));
        assert!(manager.update_automatic_title("terminal", Some("~/github/LingXia")));
        assert_eq!(
            manager.switcher_snapshot().items[0].title.as_deref(),
            Some("workspace")
        );

        assert!(manager.rename("terminal", None));
        assert_eq!(
            manager.switcher_snapshot().items[0].title.as_deref(),
            Some("~/github/LingXia")
        );
    }

    #[test]
    fn lxapp_titles_are_not_user_renameable() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        manager.open(Surface::lxapp("tools", Role::Main, "tools"));

        assert!(!manager.rename("home", Some("renamed")));
        assert_eq!(
            manager.switcher_snapshot().items[0].title.as_deref(),
            Some("home")
        );
        assert!(!manager.switcher_snapshot().items[1].closable);
    }

    #[test]
    fn close_after_uses_global_switcher_order() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        manager.open(Surface::browser(
            "docs",
            Role::Main,
            "https://docs.example.com",
        ));
        manager.open(Surface::native("terminal", Role::Main, "terminal"));

        manager.open(Surface::lxapp("tools", Role::Main, "tools"));
        assert_eq!(manager.close_mains_after("home"), vec!["docs", "terminal"]);
        assert_eq!(manager.switcher_snapshot().items.len(), 2);
    }

    #[test]
    fn declaration_replace_overrides_an_early_seeded_root_atomically() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        let terminal = Surface::native("terminal", Role::Main, "terminal");
        let browser = Surface::browser("browser", Role::Main, "https://example.com");

        let snapshot = manager
            .replace_mains(vec![
                (
                    terminal.clone(),
                    SurfacePresentation::for_content(&terminal.content),
                ),
                (
                    browser.clone(),
                    SurfacePresentation::for_content(&browser.content),
                ),
            ])
            .unwrap();

        assert_eq!(snapshot.root_surface_id.as_deref(), Some("terminal"));
        assert_eq!(snapshot.active_surface_id.as_deref(), Some("terminal"));
        assert_eq!(
            snapshot
                .items
                .iter()
                .map(|item| item.surface_id.as_str())
                .collect::<Vec<_>>(),
            vec!["terminal", "browser"]
        );
        assert!(manager.graph().get("home").is_none());
    }

    #[test]
    fn invalid_declaration_replace_is_atomic() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        let before = manager.switcher_snapshot();
        let duplicate = Surface::native("terminal", Role::Main, "terminal");

        assert_eq!(
            manager.replace_mains(vec![
                (
                    duplicate.clone(),
                    SurfacePresentation::for_content(&duplicate.content),
                ),
                (
                    duplicate.clone(),
                    SurfacePresentation::for_content(&duplicate.content),
                ),
            ]),
            Err(ReplaceMainsError::DuplicateId {
                surface_id: "terminal".into()
            })
        );
        assert_eq!(manager.switcher_snapshot(), before);
    }

    #[test]
    fn closed_registered_main_can_be_opened_again() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        let terminal = Surface::native("terminal", Role::Main, "terminal");
        let presentation = SurfacePresentation::for_content(&terminal.content);
        manager
            .open_main(terminal.clone(), presentation.clone())
            .unwrap();
        assert!(matches!(
            manager.close("terminal"),
            CloseOutcome::Closed { .. }
        ));

        let snapshot = manager.open_main(terminal, presentation).unwrap();
        assert_eq!(snapshot.active_surface_id.as_deref(), Some("terminal"));
        assert_eq!(
            snapshot
                .items
                .iter()
                .map(|item| item.surface_id.as_str())
                .collect::<Vec<_>>(),
            vec!["home", "terminal"]
        );
    }

    #[test]
    fn opening_browser_main_never_reuses_an_aside_with_the_same_url() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        manager.open(Surface::browser(
            "browser-aside",
            Role::Aside,
            "https://example.com",
        ));
        let browser_main = Surface::browser("browser-main", Role::Main, "https://example.com");

        let snapshot = manager
            .open_main(
                browser_main.clone(),
                SurfacePresentation::for_content(&browser_main.content),
            )
            .unwrap();

        assert_eq!(snapshot.active_surface_id.as_deref(), Some("browser-main"));
        assert_eq!(manager.graph().role_of("browser-main"), Some(Role::Main));
        assert_eq!(manager.graph().role_of("browser-aside"), Some(Role::Aside));
    }

    #[test]
    fn native_surface_moves_between_aside_and_main_without_replacing_root() {
        let mut manager = SurfaceManager::new(1200.0);
        manager.open(Surface::lxapp("home", Role::Main, "home"));
        manager.open(Surface::native("terminal", Role::Aside, "terminal"));

        let terminal_main = Surface::native("terminal", Role::Main, "terminal");
        let snapshot = manager
            .open_main(
                terminal_main.clone(),
                SurfacePresentation::for_content(&terminal_main.content),
            )
            .unwrap();
        assert_eq!(snapshot.root_surface_id.as_deref(), Some("home"));
        assert_eq!(snapshot.active_surface_id.as_deref(), Some("terminal"));
        assert_eq!(manager.graph().asides().len(), 0);

        manager.open(Surface::native("terminal", Role::Aside, "terminal"));
        let snapshot = manager.switcher_snapshot();
        assert_eq!(snapshot.root_surface_id.as_deref(), Some("home"));
        assert_eq!(snapshot.active_surface_id.as_deref(), Some("home"));
        assert_eq!(snapshot.items.len(), 1);
        assert_eq!(manager.graph().asides()[0].id, "terminal");
    }

    #[test]
    fn native_root_cannot_move_to_aside() {
        for with_other_main in [false, true] {
            let mut manager = SurfaceManager::new(1200.0);
            manager.open(Surface::native("terminal", Role::Main, "terminal"));
            if with_other_main {
                manager.open(Surface::lxapp("tools", Role::Main, "tools"));
            }

            let outcome = manager.open(Surface::native("terminal", Role::Aside, "terminal"));

            assert_eq!(outcome.decision, crate::Decision::DowngradedRole);
            assert_eq!(outcome.resolved_role, Role::Main);
            assert_eq!(manager.graph().root_main_id(), Some("terminal"));
            assert_eq!(manager.graph().role_of("terminal"), Some(Role::Main));
            assert!(manager.graph().asides().is_empty());
            assert!(manager.graph().is_valid());
        }
    }
}