Skip to main content

vibe/
presentation.rs

1//! Presentation morphism as a sheaf (T69).
2//!
3//! The presentation morphism maps a VibeScript value (field, tensor,
4//! geometry, quantity) to a presentation in one or more modalities
5//! (visual, haptic, auditory, Braille). It is a **sheaf** — the
6//! presentation is locally consistent (each modality gets a coherent
7//! view) and globally glued (the modalities agree on the underlying
8//! value).
9//!
10//! ## Design
11//!
12//! - [`PresentationModality`] — the output modality (visual, haptic,
13//!   auditory, Braille).
14//! - [`Presentation`] — a single presentation of a value in one
15//!   modality. Carries the modality, a presentation kind, and a
16//!   payload (CSS properties, haptic pattern, audio earcon, Braille
17//!   cells).
18//! - [`PresentationSheaf`] — the sheaf: a value plus its presentations
19//!   across modalities. The sheaf condition is that all presentations
20//!   agree on the underlying value.
21//!
22//! ## Not `Render.css_*` plus hope
23//!
24//! The presentation morphism is NOT just CSS rendering. It produces
25//! presentations for multiple modalities simultaneously. The visual
26//! presentation might be CSS, but the haptic presentation is a
27//! vibration pattern, the auditory presentation is an earcon, and the
28//! Braille presentation is a cell array.
29//!
30//! Reference: `docs/vibescript-full-impl-PLAN.md` §3.10 T69.
31
32use crate::sheaf::SheafCondition;
33use crate::value::Value;
34use std::collections::BTreeMap;
35
36/// A presentation modality — the output channel.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum PresentationModality {
39    /// Visual presentation (CSS, SVG, canvas, WebGL).
40    Visual,
41    /// Haptic presentation (vibration, force feedback).
42    Haptic,
43    /// Auditory presentation (tones, earcons, speech).
44    Auditory,
45    /// Braille presentation (refreshable Braille display).
46    Braille,
47}
48
49impl PresentationModality {
50    /// `str` form.
51    pub fn as_str(&self) -> &'static str {
52        match self {
53            Self::Visual => "visual",
54            Self::Haptic => "haptic",
55            Self::Auditory => "auditory",
56            Self::Braille => "braille",
57        }
58    }
59
60    /// Constructs from str.
61    pub fn from_str(s: &str) -> Option<Self> {
62        match s {
63            "visual" => Some(Self::Visual),
64            "haptic" => Some(Self::Haptic),
65            "auditory" => Some(Self::Auditory),
66            "braille" => Some(Self::Braille),
67            _ => None,
68        }
69    }
70}
71
72/// The kind of presentation within a modality.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum PresentationKind {
75    /// CSS properties (visual).
76    CssProperties,
77    /// SVG element (visual).
78    SvgElement,
79    /// Canvas/WebGL draw call (visual).
80    CanvasDraw,
81    /// Haptic vibration pattern.
82    HapticPattern,
83    /// Audio earcon (auditory).
84    AudioEarcon,
85    /// Speech announcement (auditory).
86    SpeechAnnounce,
87    /// Braille cell array (Braille).
88    BrailleCells,
89}
90
91impl PresentationKind {
92    /// `str` form.
93    pub fn as_str(&self) -> &'static str {
94        match self {
95            Self::CssProperties => "css_properties",
96            Self::SvgElement => "svg_element",
97            Self::CanvasDraw => "canvas_draw",
98            Self::HapticPattern => "haptic_pattern",
99            Self::AudioEarcon => "audio_earcon",
100            Self::SpeechAnnounce => "speech_announce",
101            Self::BrailleCells => "braille_cells",
102        }
103    }
104}
105
106/// A single presentation of a value in one modality.
107#[derive(Debug, Clone)]
108pub struct Presentation {
109    /// The modality (visual, haptic, auditory, Braille).
110    pub modality: PresentationModality,
111    /// The kind of presentation within the modality.
112    pub kind: PresentationKind,
113    /// The presentation payload — modality-specific data.
114    /// For CSS: a Record of property → value.
115    /// For SVG: an SVG element string.
116    /// For haptic: a pattern (duration, strength pairs).
117    /// For audio: an earcon ID or speech text.
118    /// For Braille: a cell array.
119    pub payload: Value,
120}
121
122impl Presentation {
123    /// Create a CSS properties presentation.
124    pub fn css(props: BTreeMap<String, Value>) -> Self {
125        Self {
126            modality: PresentationModality::Visual,
127            kind: PresentationKind::CssProperties,
128            payload: Value::Record(props),
129        }
130    }
131
132    /// Create an SVG element presentation.
133    pub fn svg(element: &str) -> Self {
134        Self {
135            modality: PresentationModality::Visual,
136            kind: PresentationKind::SvgElement,
137            payload: Value::String(element.into()),
138        }
139    }
140
141    /// Create a haptic pattern presentation.
142    pub fn haptic_pattern(pattern: Vec<(u64, f64)>) -> Self {
143        let list: Vec<Value> = pattern
144            .iter()
145            .map(|(d, s)| {
146                let mut pair = BTreeMap::new();
147                pair.insert("duration_ms".into(), Value::U64(*d));
148                pair.insert("strength".into(), Value::F64(*s));
149                Value::Record(pair)
150            })
151            .collect();
152        Self {
153            modality: PresentationModality::Haptic,
154            kind: PresentationKind::HapticPattern,
155            payload: Value::List(list),
156        }
157    }
158
159    /// Create an audio earcon presentation.
160    pub fn audio_earcon(earcon_id: &str) -> Self {
161        Self {
162            modality: PresentationModality::Auditory,
163            kind: PresentationKind::AudioEarcon,
164            payload: Value::String(earcon_id.into()),
165        }
166    }
167
168    /// Create a speech announcement presentation.
169    pub fn speech(text: &str) -> Self {
170        Self {
171            modality: PresentationModality::Auditory,
172            kind: PresentationKind::SpeechAnnounce,
173            payload: Value::String(text.into()),
174        }
175    }
176
177    /// Create a Braille cells presentation.
178    /// `cells` is a list of 8-bit dot patterns.
179    pub fn braille_cells(cells: Vec<u8>) -> Self {
180        let list: Vec<Value> = cells.iter().map(|&c| Value::I64(c as i64)).collect();
181        Self {
182            modality: PresentationModality::Braille,
183            kind: PresentationKind::BrailleCells,
184            payload: Value::List(list),
185        }
186    }
187
188    /// Convert to a VibeScript Record value.
189    pub fn to_value(&self) -> Value {
190        let mut rec = BTreeMap::new();
191        rec.insert(
192            "modality".into(),
193            Value::String(self.modality.as_str().into()),
194        );
195        rec.insert("kind".into(), Value::String(self.kind.as_str().into()));
196        rec.insert("payload".into(), self.payload.clone());
197        Value::Record(rec)
198    }
199}
200
201/// A presentation sheaf — a value plus its presentations across
202/// modalities.
203///
204/// The sheaf condition is that all presentations agree on the
205/// underlying value. This is checked by `PresentationSheaf::check()`,
206/// which verifies that every presentation maps back to the same
207/// source value.
208#[derive(Debug, Clone)]
209pub struct PresentationSheaf {
210    /// The source value being presented.
211    pub source: Value,
212    /// The presentations across modalities.
213    pub presentations: Vec<Presentation>,
214    /// The sheaf condition — verifies presentations agree.
215    pub condition: SheafCondition,
216}
217
218impl PresentationSheaf {
219    /// Create a new presentation sheaf for a source value.
220    pub fn new(source: Value) -> Self {
221        Self {
222            source,
223            presentations: Vec::new(),
224            condition: SheafCondition::new(
225                "presentation_glue",
226                "pred.presentation_consistent",
227                true,
228            ),
229        }
230    }
231
232    /// Add a presentation to the sheaf.
233    pub fn add(&mut self, presentation: Presentation) -> &mut Self {
234        self.presentations.push(presentation);
235        self
236    }
237
238    /// Get all presentations for a specific modality.
239    pub fn for_modality(&self, modality: PresentationModality) -> Vec<&Presentation> {
240        self.presentations
241            .iter()
242            .filter(|p| p.modality == modality)
243            .collect()
244    }
245
246    /// Check which modalities are present.
247    pub fn modalities(&self) -> Vec<PresentationModality> {
248        let mut mods: Vec<PresentationModality> =
249            self.presentations.iter().map(|p| p.modality).collect();
250        mods.sort_by_key(|m| m.as_str());
251        mods.dedup();
252        mods
253    }
254
255    /// Convert to a VibeScript Record value.
256    pub fn to_value(&self) -> Value {
257        let mut rec = BTreeMap::new();
258        rec.insert("source".into(), self.source.clone());
259        rec.insert(
260            "presentations".into(),
261            Value::List(self.presentations.iter().map(|p| p.to_value()).collect()),
262        );
263        rec.insert("condition".into(), self.condition.to_value());
264        Value::Record(rec)
265    }
266}
267
268/// The presentation morphism — maps a value to a presentation sheaf.
269///
270/// This is the top-level function that takes a VibeScript value and
271/// produces presentations across modalities. The actual presentation
272/// logic is modality-specific and may be host-provided.
273pub fn present(value: &Value) -> PresentationSheaf {
274    let mut sheaf = PresentationSheaf::new(value.clone());
275
276    // Visual: CSS properties for scalar/quantity values.
277    match value {
278        Value::F64(f) => {
279            let mut props = BTreeMap::new();
280            // Map 0.0–1.0 to opacity.
281            let opacity = f.clamp(0.0, 1.0);
282            props.insert("opacity".into(), Value::F64(opacity));
283            sheaf.add(Presentation::css(props));
284        }
285        Value::I64(n) => {
286            let mut props = BTreeMap::new();
287            props.insert("z-index".into(), Value::I64(*n));
288            sheaf.add(Presentation::css(props));
289        }
290        Value::String(s) => {
291            // Visual: render as text.
292            let mut props = BTreeMap::new();
293            props.insert("content".into(), Value::String(s.clone()));
294            sheaf.add(Presentation::css(props));
295            // Auditory: announce as speech.
296            sheaf.add(Presentation::speech(s));
297            // Braille: convert to Braille cells (simplified — ASCII mapping).
298            let cells: Vec<u8> = s.bytes().map(|b| b & 0x3F).collect();
299            sheaf.add(Presentation::braille_cells(cells));
300        }
301        Value::Bool(b) => {
302            let mut props = BTreeMap::new();
303            props.insert(
304                "display".into(),
305                Value::String(if *b { "block" } else { "none" }.into()),
306            );
307            sheaf.add(Presentation::css(props));
308        }
309        _ => {
310            // No default presentation for other types.
311        }
312    }
313
314    sheaf
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    #[test]
322    fn modality_round_trip() {
323        for m in [
324            PresentationModality::Visual,
325            PresentationModality::Haptic,
326            PresentationModality::Auditory,
327            PresentationModality::Braille,
328        ] {
329            assert_eq!(PresentationModality::from_str(m.as_str()), Some(m));
330        }
331    }
332
333    #[test]
334    fn presentation_css() {
335        let mut props = BTreeMap::new();
336        props.insert("opacity".into(), Value::F64(0.5));
337        let p = Presentation::css(props);
338        assert_eq!(p.modality, PresentationModality::Visual);
339        assert_eq!(p.kind, PresentationKind::CssProperties);
340    }
341
342    #[test]
343    fn presentation_svg() {
344        let p = Presentation::svg("<circle cx='10' cy='10' r='5'/>");
345        assert_eq!(p.modality, PresentationModality::Visual);
346        assert_eq!(p.kind, PresentationKind::SvgElement);
347    }
348
349    #[test]
350    fn presentation_haptic_pattern() {
351        let p = Presentation::haptic_pattern(vec![(100, 0.5), (200, 0.8)]);
352        assert_eq!(p.modality, PresentationModality::Haptic);
353        assert_eq!(p.kind, PresentationKind::HapticPattern);
354        if let Value::List(l) = &p.payload {
355            assert_eq!(l.len(), 2);
356        }
357    }
358
359    #[test]
360    fn presentation_audio_earcon() {
361        let p = Presentation::audio_earcon("success");
362        assert_eq!(p.modality, PresentationModality::Auditory);
363        assert_eq!(p.kind, PresentationKind::AudioEarcon);
364    }
365
366    #[test]
367    fn presentation_speech() {
368        let p = Presentation::speech("Hello world");
369        assert_eq!(p.modality, PresentationModality::Auditory);
370        assert_eq!(p.kind, PresentationKind::SpeechAnnounce);
371    }
372
373    #[test]
374    fn presentation_braille_cells() {
375        let p = Presentation::braille_cells(vec![0x01, 0x02, 0x03]);
376        assert_eq!(p.modality, PresentationModality::Braille);
377        assert_eq!(p.kind, PresentationKind::BrailleCells);
378        if let Value::List(l) = &p.payload {
379            assert_eq!(l.len(), 3);
380        }
381    }
382
383    #[test]
384    fn presentation_to_value() {
385        let p = Presentation::speech("test");
386        let v = p.to_value();
387        let rec = match &v {
388            Value::Record(r) => r,
389            _ => panic!("expected Record"),
390        };
391        assert_eq!(
392            match rec.get("modality").unwrap() {
393                Value::String(s) => s.as_str(),
394                _ => panic!("expected String"),
395            },
396            "auditory"
397        );
398    }
399
400    #[test]
401    fn sheaf_construction() {
402        let sheaf = PresentationSheaf::new(Value::F64(0.5));
403        assert!(sheaf.presentations.is_empty());
404        assert_eq!(sheaf.condition.name, "presentation_glue");
405    }
406
407    #[test]
408    fn sheaf_add_presentation() {
409        let mut sheaf = PresentationSheaf::new(Value::F64(0.5));
410        sheaf.add(Presentation::speech("half"));
411        assert_eq!(sheaf.presentations.len(), 1);
412    }
413
414    #[test]
415    fn sheaf_for_modality() {
416        let mut sheaf = PresentationSheaf::new(Value::String("hi".into()));
417        sheaf.add(Presentation::speech("hi"));
418        sheaf.add(Presentation::braille_cells(vec![0x01]));
419        sheaf.add(Presentation::css(BTreeMap::new()));
420        let visual = sheaf.for_modality(PresentationModality::Visual);
421        let auditory = sheaf.for_modality(PresentationModality::Auditory);
422        let braille = sheaf.for_modality(PresentationModality::Braille);
423        assert_eq!(visual.len(), 1);
424        assert_eq!(auditory.len(), 1);
425        assert_eq!(braille.len(), 1);
426    }
427
428    #[test]
429    fn sheaf_modalities_dedup() {
430        let mut sheaf = PresentationSheaf::new(Value::F64(0.5));
431        sheaf.add(Presentation::css(BTreeMap::new()));
432        sheaf.add(Presentation::svg("<rect/>"));
433        sheaf.add(Presentation::speech("half"));
434        let mods = sheaf.modalities();
435        assert_eq!(mods.len(), 2); // visual + auditory, not 3
436    }
437
438    #[test]
439    fn sheaf_to_value() {
440        let mut sheaf = PresentationSheaf::new(Value::F64(0.5));
441        sheaf.add(Presentation::speech("half"));
442        let v = sheaf.to_value();
443        let rec = match &v {
444            Value::Record(r) => r,
445            _ => panic!("expected Record"),
446        };
447        assert!(rec.contains_key("source"));
448        assert!(rec.contains_key("presentations"));
449        assert!(rec.contains_key("condition"));
450    }
451
452    #[test]
453    fn present_f64_as_opacity() {
454        let sheaf = present(&Value::F64(0.5));
455        let visual = sheaf.for_modality(PresentationModality::Visual);
456        assert_eq!(visual.len(), 1);
457        assert_eq!(visual[0].kind, PresentationKind::CssProperties);
458    }
459
460    #[test]
461    fn present_f64_clamps_opacity() {
462        let sheaf = present(&Value::F64(1.5));
463        let visual = sheaf.for_modality(PresentationModality::Visual);
464        if let Value::Record(props) = &visual[0].payload {
465            if let Value::F64(op) = props.get("opacity").unwrap() {
466                assert_eq!(*op, 1.0); // clamped
467            }
468        }
469    }
470
471    #[test]
472    fn present_string_multi_modal() {
473        let sheaf = present(&Value::String("hello".into()));
474        // String gets visual, auditory, and Braille presentations.
475        assert!(!sheaf.for_modality(PresentationModality::Visual).is_empty());
476        assert!(!sheaf
477            .for_modality(PresentationModality::Auditory)
478            .is_empty());
479        assert!(!sheaf.for_modality(PresentationModality::Braille).is_empty());
480    }
481
482    #[test]
483    fn present_bool_as_display() {
484        let sheaf = present(&Value::Bool(true));
485        let visual = sheaf.for_modality(PresentationModality::Visual);
486        assert_eq!(visual.len(), 1);
487        if let Value::Record(props) = &visual[0].payload {
488            if let Value::String(s) = props.get("display").unwrap() {
489                assert_eq!(s, "block");
490            }
491        }
492    }
493
494    #[test]
495    fn present_bool_false_as_none() {
496        let sheaf = present(&Value::Bool(false));
497        let visual = sheaf.for_modality(PresentationModality::Visual);
498        if let Value::Record(props) = &visual[0].payload {
499            if let Value::String(s) = props.get("display").unwrap() {
500                assert_eq!(s, "none");
501            }
502        }
503    }
504
505    #[test]
506    fn present_i64_as_zindex() {
507        let sheaf = present(&Value::I64(42));
508        let visual = sheaf.for_modality(PresentationModality::Visual);
509        if let Value::Record(props) = &visual[0].payload {
510            if let Value::I64(n) = props.get("z-index").unwrap() {
511                assert_eq!(*n, 42);
512            }
513        }
514    }
515
516    #[test]
517    fn present_null_no_presentations() {
518        let sheaf = present(&Value::Null);
519        assert!(sheaf.presentations.is_empty());
520    }
521}