perspective_viewer/components/
font_loader.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::cell::{Cell, Ref, RefCell};
14use std::future::Future;
15use std::iter::{Iterator, repeat_with};
16use std::rc::Rc;
17
18use futures::future::{join_all, select_all};
19use perspective_js::utils::{global, *};
20use wasm_bindgen::JsCast;
21use wasm_bindgen::prelude::*;
22use wasm_bindgen_futures::JsFuture;
23use yew::prelude::*;
24
25use crate::utils::*;
26
27const FONT_DOWNLOAD_TIMEOUT_MS: i32 = 1000;
28
29/// This test string is injected into the DOM with the target `font-family`
30/// applied. It is important for this string to contain the correct unicode
31/// range, as otherwise the browser may download the latin-only variant of the
32/// font which will later be invalidated.
33const FONT_TEST_SAMPLE: &str = "ABCDΔ";
34
35/// `state` is private to force construction of props with the `::new()` static
36/// method, which initializes the async `load_fonts_task()` method.
37#[derive(Clone, Properties)]
38pub struct FontLoaderProps {
39    state: Rc<FontLoaderState>,
40}
41
42impl PartialEq for FontLoaderProps {
43    fn eq(&self, _rhs: &Self) -> bool {
44        false
45    }
46}
47
48/// The `FontLoader` component ensures that fonts are loaded before they are
49/// visible.
50pub struct FontLoader {}
51
52impl Component for FontLoader {
53    type Message = ();
54    type Properties = FontLoaderProps;
55
56    fn create(_ctx: &Context<Self>) -> Self {
57        Self {}
58    }
59
60    fn update(&mut self, _ctx: &Context<Self>, _msg: ()) -> bool {
61        false
62    }
63
64    fn view(&self, ctx: &Context<Self>) -> yew::virtual_dom::VNode {
65        if matches!(ctx.props().get_status(), FontLoaderStatus::Finished) {
66            html! {}
67        } else {
68            let inner = ctx
69                .props()
70                .get_fonts()
71                .iter()
72                .map(font_test_html)
73                .collect::<Html>();
74
75            html! { <><style>{ ":host{opacity:0!important;}" }</style>{ inner }</> }
76        }
77    }
78}
79
80/// The possible font loading state, which proceeds from top to bottom once per
81/// `<perspective-viewer>` element.
82#[derive(Clone, Copy)]
83pub enum FontLoaderStatus {
84    Uninitialized,
85    Loading,
86    Finished,
87}
88
89type PromiseSet = Vec<ApiFuture<JsValue>>;
90
91pub struct FontLoaderState {
92    status: Cell<FontLoaderStatus>,
93    elem: web_sys::HtmlElement,
94    on_update: Callback<()>,
95    fonts: RefCell<Vec<(String, String)>>,
96}
97
98impl FontLoaderProps {
99    pub fn new(elem: &web_sys::HtmlElement, on_update: Callback<()>) -> Self {
100        let inner = FontLoaderState {
101            status: Cell::new(FontLoaderStatus::Uninitialized),
102            elem: elem.clone(),
103            on_update,
104            fonts: RefCell::new(vec![]),
105        };
106
107        let state = yew::props!(Self {
108            state: Rc::new(inner)
109        });
110
111        ApiFuture::spawn(state.clone().load_fonts_task_safe());
112        state
113    }
114
115    pub fn get_status(&self) -> FontLoaderStatus {
116        self.state.status.get()
117    }
118
119    fn get_fonts(&self) -> Ref<Vec<(String, String)>> {
120        self.state.fonts.borrow()
121    }
122
123    /// We only want errors in this task to warn, since they are not necessarily
124    /// error conditions and mainly of interest to developers.
125    async fn load_fonts_task_safe(self) -> ApiResult<JsValue> {
126        if let Err(msg) = self.load_fonts_task().await {
127            web_sys::console::warn_1(&msg.into());
128        };
129
130        Ok(JsValue::UNDEFINED)
131    }
132
133    /// Awaits loading of a required set of font/weight pairs, given an element
134    /// with a CSS variable of the format:
135    /// ```css
136    /// perspective-viewer {
137    ///     --preload-fonts: "Roboto Mono:200;Open Sans:300,400";
138    /// }
139    /// ```
140    async fn load_fonts_task(self) -> ApiResult<JsValue> {
141        await_dom_loaded().await?;
142        let txt = global::window()
143            .get_computed_style(&self.state.elem)?
144            .unwrap()
145            .get_property_value("--preload-fonts")?;
146
147        let mut block_promises: PromiseSet = vec![];
148        let preload_fonts = parse_fonts(&txt);
149        self.state.fonts.borrow_mut().clone_from(&preload_fonts);
150        self.state.status.set(FontLoaderStatus::Loading);
151        self.state.on_update.emit(());
152
153        for (family, weight) in preload_fonts.iter() {
154            let task = timeout_font_task(family, weight);
155            let mut block_fonts: PromiseSet = vec![ApiFuture::new(task)];
156
157            for entry in font_iter(global::document().fonts().values()) {
158                let font_face = js_sys::Reflect::get(&entry, js_intern::js_intern!("value"))?
159                    .dyn_into::<web_sys::FontFace>()?;
160
161                // Safari always has to be "different".
162                if family == &font_face.family().replace('"', "")
163                    && (weight == &font_face.weight()
164                        || (font_face.weight() == "normal" && weight == "400"))
165                {
166                    block_fonts.push(ApiFuture::new(async move {
167                        Ok(JsFuture::from(font_face.loaded()?).await?)
168                    }));
169                }
170            }
171
172            let fut = async { select_all(block_fonts.into_iter()).await.0 };
173            block_promises.push(ApiFuture::new(fut))
174        }
175
176        if block_promises.len() != preload_fonts.len() {
177            web_sys::console::warn_1(&format!("Missing preload fonts {:?}", &preload_fonts).into());
178        }
179
180        let res = join_all(block_promises)
181            .await
182            .into_iter()
183            .collect::<ApiResult<Vec<JsValue>>>()
184            .map(|_| JsValue::UNDEFINED);
185
186        self.state.status.set(FontLoaderStatus::Finished);
187        self.state.on_update.emit(());
188        res
189    }
190}
191
192// An async task which times out.  Can be used to timeout an optional async task
193// by combinging with `Promise::any`.
194fn timeout_font_task(
195    family: &str,
196    weight: &str,
197) -> impl Future<Output = ApiResult<JsValue>> + use<> {
198    let timeout_msg = format!("Timeout awaiting font \"{family}:{weight}\"");
199    async {
200        set_timeout(FONT_DOWNLOAD_TIMEOUT_MS).await?;
201        Err(timeout_msg.into())
202    }
203}
204
205/// Generates a `<span>` for a specific font family and weight with `opacity:0`,
206/// since not all of the fonts may be shown and when e.g. the settings panel is
207/// closed, and this will defer font loading.
208fn font_test_html((family, weight): &(String, String)) -> Html {
209    let style = format!("opacity:0;font-family:\"{family}\";font-weight:{weight}");
210
211    html! { <span {style}>{ FONT_TEST_SAMPLE }</span> }
212}
213
214fn parse_font(txt: &str) -> Option<Vec<(String, String)>> {
215    match *txt.trim().split(':').collect::<Vec<_>>().as_slice() {
216        [family, weights] => Some(
217            weights
218                .split(',')
219                .map(|weight| (family.to_owned(), weight.to_owned()))
220                .collect::<Vec<_>>(),
221        ),
222        _ => None,
223    }
224}
225
226/// Parse a `--preload-fonts` value into (Family, Weight) tuples.
227fn parse_fonts(txt: &str) -> Vec<(String, String)> {
228    let trim = txt.trim();
229    let trim = if trim.len() > 2 {
230        &trim[1..trim.len() - 1]
231    } else {
232        trim
233    };
234
235    trim.split(';')
236        .filter_map(parse_font)
237        .flatten()
238        .collect::<Vec<_>>()
239}
240
241/// wasm_bindgen doesn't fully implement `FontFaceIterator`, but this is
242/// basically how it would be implemented if it was.
243fn font_iter(
244    iter: web_sys::FontFaceSetIterator,
245) -> impl Iterator<Item = web_sys::FontFaceSetIteratorResult> {
246    repeat_with(move || iter.next())
247        .filter_map(|x| x.ok())
248        .take_while(|entry| {
249            !js_sys::Reflect::get(entry, js_intern::js_intern!("done"))
250                .unwrap()
251                .as_bool()
252                .unwrap()
253        })
254}