glory-ui 0.10.0

Pure Rust semantic widgets and windowed lists for Glory
Documentation
#![cfg(feature = "markdown")]
use std::cell::{Cell, RefCell};
use std::rc::Rc;

use glory_render::memory::Memory;
use glory_render::*;
use glory_ui::App;
use glory_ui::markdown::*;

struct Host {
    memory: Memory,
    selection: Rc<Cell<TextSelection>>,
    inputs: Vec<Input>,
    incoming: Rc<RefCell<Vec<Input>>>,
    applied: u64,
}
impl Render for Host {
    fn style_profile(&self) -> glory_render::style::Profile {
        self.memory.style_profile()
    }
    fn capabilities(&self) -> Capabilities {
        Capabilities {
            input: true,
            focus: true,
            ..Default::default()
        }
    }
    fn apply(&mut self, edits: &[Mutation]) -> Result<Receipt, Error> {
        let result = self.memory.apply(edits)?;
        self.applied = result.applied;
        Ok(result)
    }
    fn action(&mut self, action: Action) -> Result<(), Error> {
        if let Action::SelectText { selection, .. } = action {
            self.selection.set(selection);
        }
        Ok(())
    }
    fn request(&mut self, query: Query, token: QueryToken) -> Result<(), Error> {
        self.memory.node(query.node())?;
        let selection = self.selection.get();
        self.inputs.push(Input::Response {
            token,
            applied: self.applied,
            result: Ok(QueryValue::Selection {
                start: selection.start,
                end: selection.end,
            }),
        });
        Ok(())
    }
    fn drain(&mut self, inputs: &mut Vec<Input>) {
        inputs.append(&mut self.inputs);
        inputs.append(&mut self.incoming.borrow_mut());
    }
}
fn fixture() -> (App, Rc<Cell<TextSelection>>) {
    let selection = Rc::new(Cell::new(TextSelection::default()));
    let output = selection.clone();
    (
        App::new(move |id| Host {
            memory: Memory::new(id),
            selection: output,
            inputs: Vec::new(),
            incoming: Rc::new(RefCell::new(Vec::new())),
            applied: 0,
        }),
        selection,
    )
}
fn revision(app: &App, node: NodeId) -> u64 {
    let tree = app.tree();
    let Props::Input(input) = tree.node(node).unwrap().descriptor.view().props else {
        panic!("input")
    };
    input.revision
}
fn input(app: &App, node: NodeId, value: &str, composing: bool) {
    app.dispatch(
        node,
        Event::ValueChanged {
            value: value.into(),
            composing,
            revision: revision(app, node),
        },
    )
    .unwrap();
}

#[test]
fn commands_use_real_unicode_selection_and_share_accepted_typing_history() {
    let (app, selection) = fixture();
    let scope = app.scope();
    let value = scope.cage("hello πŸ˜€ world".to_owned());
    let node = scope.cage(None);
    let controller = scope.cage(None);
    app.mount(
        markdown_input()
            .value(value)
            .node_ref(node)
            .controller_ref(controller)
            .on_value_change(move |next| value.revise(|value| *value = next)),
    )
    .unwrap();
    selection.set(TextSelection {
        start: 6,
        end: 8,
        ..Default::default()
    });
    let editor = controller.get().unwrap();
    editor.command(Command::Bold).unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "hello **πŸ˜€** world");
    assert_eq!(
        selection.get(),
        TextSelection {
            start: 8,
            end: 10,
            ..Default::default()
        }
    );
    editor.undo().unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "hello πŸ˜€ world");
    assert_eq!(
        selection.get(),
        TextSelection {
            start: 6,
            end: 8,
            ..Default::default()
        }
    );
    editor.redo().unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "hello **πŸ˜€** world");
    input(&app, node.get().unwrap(), "hello **πŸ˜€** world!", false);
    editor.undo().unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "hello **πŸ˜€** world");
    app.clear().unwrap();
    assert!(controller.get().is_none());
    assert!(editor.command(Command::Italic).is_err());
}

#[test]
fn controlled_rejection_and_external_replacement_do_not_create_false_history() {
    let (app, selection) = fixture();
    let value = app.scope().cage("original".to_owned());
    let controller = app.scope().cage(None);
    let proposals = Rc::new(RefCell::new(Vec::new()));
    let output = proposals.clone();
    app.mount(
        markdown_input()
            .value(value)
            .controller_ref(controller)
            .on_value_change(move |next| output.borrow_mut().push(next)),
    )
    .unwrap();
    selection.set(TextSelection {
        start: 0,
        end: 8,
        ..Default::default()
    });
    let editor = controller.get().unwrap();
    editor.command(Command::Bold).unwrap();
    app.pump().unwrap();
    assert_eq!(proposals.borrow().as_slice(), ["**original**"]);
    assert_eq!(value.get(), "original");
    assert_eq!(editor.history().get(), (false, false));
    value.revise(|value| *value = "server update".into());
    app.flush().unwrap();
    assert_eq!(editor.history().get(), (false, false));
}

#[test]
fn composition_is_atomic_and_external_source_wins_over_stale_composition() {
    let (app, _) = fixture();
    let value = app.scope().cage("a".to_owned());
    let node = app.scope().cage(None);
    let controller = app.scope().cage(None);
    let proposals = app.scope().cage(0);
    app.mount(
        markdown_input()
            .value(value)
            .node_ref(node)
            .controller_ref(controller)
            .on_value_change(move |next| {
                proposals.revise(|count| *count += 1);
                value.revise(|value| *value = next);
            }),
    )
    .unwrap();
    let id = node.get().unwrap();
    input(&app, id, "aδΈ­", true);
    assert_eq!(value.get(), "a");
    assert_eq!(proposals.get(), 0);
    controller.get().unwrap().command(Command::Bold).unwrap();
    input(&app, id, "aδΈ­ζ–‡", false);
    assert_eq!(value.get(), "aδΈ­ζ–‡");
    assert_eq!(proposals.get(), 1);
    input(&app, id, "aδΈ­ζ–‡x", true);
    value.revise(|value| *value = "remote".into());
    app.flush().unwrap();
    input(&app, id, "aδΈ­ζ–‡ζ–°", false);
    assert_eq!(value.get(), "remote");
    assert_eq!(proposals.get(), 1);
}

#[test]
fn disabled_readonly_and_byte_limits_guard_commands_and_proposals() {
    let (app, selection) = fixture();
    let value = app.scope().cage("a".to_owned());
    let readonly = app.scope().cage(true);
    let enabled = app.scope().cage(true);
    let controller = app.scope().cage(None);
    let node = app.scope().cage(None);
    app.mount(
        markdown_input()
            .value(value)
            .readonly(readonly)
            .enabled(enabled)
            .max_bytes(4)
            .node_ref(node)
            .controller_ref(controller)
            .on_value_change(move |next| value.revise(|value| *value = next)),
    )
    .unwrap();
    let editor = controller.get().unwrap();
    editor.command(Command::Bold).unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "a");
    readonly.revise(|value| *value = false);
    app.flush().unwrap();
    input(&app, node.get().unwrap(), "12345", false);
    assert_eq!(value.get(), "a");
    enabled.revise(|value| *value = false);
    app.flush().unwrap();
    selection.set(TextSelection {
        start: 0,
        end: 1,
        ..Default::default()
    });
    editor.command(Command::Italic).unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "a");
}

#[test]
fn delayed_selection_never_formats_an_external_replacement() {
    let (app, selection) = fixture();
    let value = app.scope().cage("old".to_owned());
    let controller = app.scope().cage(None);
    app.mount(
        markdown_input()
            .value(value)
            .controller_ref(controller)
            .on_value_change(move |next| value.revise(|value| *value = next)),
    )
    .unwrap();
    selection.set(TextSelection {
        start: 0,
        end: 3,
        ..Default::default()
    });
    controller.get().unwrap().command(Command::Bold).unwrap();
    value.revise(|value| *value = "new".into());
    app.pump().unwrap();
    assert_eq!(value.get(), "new");
}

#[test]
fn source_keyboard_commands_capture_exact_selection_and_continue_tasks() {
    let (app, _) = fixture();
    let value = app.scope().cage("- [x] δΈ­ζ–‡πŸ˜€".to_owned());
    let node = app.scope().cage(None);
    app.mount(
        markdown_input()
            .value(value)
            .node_ref(node)
            .on_value_change(move |next| value.revise(|value| *value = next)),
    )
    .unwrap();
    let id = node.get().unwrap();
    let end = value.get().encode_utf16().count();
    app.dispatch(
        id,
        Event::RichCommand {
            command: RichCommand::ContinueLine,
            revision: revision(&app, id),
            selection: Some(TextSelection {
                start: end,
                end,
                ..Default::default()
            }),
        },
    )
    .unwrap();
    assert_eq!(value.get(), "- [x] δΈ­ζ–‡πŸ˜€\n- [ ] ");
    assert_eq!(
        RichCommand::input_key(KeyboardInput {
            key: "Tab",
            ..Default::default()
        }),
        None
    );
    assert_eq!(
        RichCommand::input_key(KeyboardInput {
            key: "Enter",
            composing: true,
            ..Default::default()
        }),
        None
    );
}

#[test]
fn batched_typing_and_typing_before_a_command_frame_keep_valid_undo_selections() {
    let incoming = Rc::new(RefCell::new(Vec::new()));
    let events = incoming.clone();
    let app = App::new(move |id| Host {
        memory: Memory::new(id),
        selection: Rc::new(Cell::new(TextSelection::default())),
        inputs: Vec::new(),
        incoming: events,
        applied: 0,
    });
    let value = app.scope().cage("πŸ˜€".to_owned());
    let controller = app.scope().cage(None);
    let node = app.scope().cage(None);
    app.mount(
        markdown_input()
            .value(value)
            .node_ref(node)
            .controller_ref(controller)
            .on_value_change(move |next| value.revise(|value| *value = next)),
    )
    .unwrap();
    let id = node.get().unwrap();
    let current = revision(&app, id);
    for text in ["πŸ˜€a", "πŸ˜€ab", "πŸ˜€abc"] {
        incoming.borrow_mut().push(Input::Event {
            node: id,
            event: Event::ValueChanged {
                value: text.into(),
                composing: false,
                revision: current,
            },
        });
    }
    app.pump().unwrap();
    assert_eq!(value.get(), "πŸ˜€abc");
    controller.get().unwrap().undo().unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "πŸ˜€");
    value.revise(|value| *value = "- item".into());
    app.flush().unwrap();
    let current = revision(&app, id);
    incoming.borrow_mut().push(Input::Event {
        node: id,
        event: Event::RichCommand {
            command: RichCommand::ContinueLine,
            revision: current,
            selection: Some(TextSelection {
                start: 6,
                end: 6,
                ..Default::default()
            }),
        },
    });
    for text in ["- itema", "- itemab"] {
        incoming.borrow_mut().push(Input::Event {
            node: id,
            event: Event::ValueChanged {
                value: text.into(),
                composing: false,
                revision: current,
            },
        });
    }
    app.pump().unwrap();
    assert_eq!(value.get(), "- item\n- ab");
    controller.get().unwrap().undo().unwrap();
    app.pump().unwrap();
    assert_eq!(value.get(), "- item");
}