use crate::a11y::{LiveRegion, LiveRegionHost};
use crate::{Editor, RootElement, RootElementRef};
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Default)]
pub(crate) struct Body {
regions: RefCell<Vec<Rc<LiveRegion>>>,
}
impl Body {
pub(crate) fn new() -> Rc<Self> {
Rc::new(Self::default())
}
pub(crate) fn regions(&self) -> Vec<Rc<LiveRegion>> {
self.regions.borrow().clone()
}
pub(crate) fn region(&self) -> Option<Rc<LiveRegion>> {
self.regions.borrow().first().cloned()
}
pub(crate) fn read_live_region(&self) -> String {
self.region().expect("a live region").text_content()
}
}
impl LiveRegionHost for Body {
fn mount_live_region(&self, region: &Rc<LiveRegion>) {
self.regions.borrow_mut().push(region.clone());
}
fn unmount_live_region(&self, region: &Rc<LiveRegion>) {
self.regions.borrow_mut().retain(|r| !Rc::ptr_eq(r, region));
}
}
pub(crate) struct Root {
body: Rc<Body>,
}
impl RootElement for Root {
fn live_region_host(self: Rc<Self>) -> Option<Rc<dyn LiveRegionHost>> {
Some(self.body.clone())
}
}
pub(crate) fn mount_root_in(editor: &Editor, body: &Rc<Body>) {
editor
.set_root_element(Some(RootElementRef(Rc::new(Root { body: body.clone() }))))
.unwrap();
}
pub(crate) fn mount_root(editor: &Editor) -> Rc<Body> {
let body = Body::new();
mount_root_in(editor, &body);
body
}