workflow-dom 0.19.0

DOM injection utilities for run-time injection of JavaScript and CSS
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use crate::error::Error;
use crate::result::Result;
use futures::future::{BoxFuture, FutureExt, join_all};
use js_sys::{Array, Uint8Array};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use web_sys::{Blob, Document, Url};
use workflow_core::channel::oneshot;
use workflow_core::lookup::*;
use workflow_core::time::*;
use workflow_log::*;
use workflow_wasm::callback::*;

/// Unique identifier of a [`Content`] entry within a [`Context`].
pub type Id = u64;
/// Map of content entries keyed by their [`Id`].
pub type ContentMap = HashMap<Id, Arc<Content>>;
/// Borrowed slice of `(id, content)` pairs used to declare content entries.
pub type ContentList<'l> = &'l [(Id, Arc<Content>)];

static mut DOCUMENT_ROOT: Option<web_sys::Element> = None;

/// Return the current browser [`web_sys::Document`].
pub fn document() -> Document {
    web_sys::window().unwrap().document().unwrap()
}

/// Return (lazily caching) the root element into which content is injected,
/// preferring the document `<head>` and falling back to `<body>`.
pub fn root() -> web_sys::Element {
    let document_root_ptr = &raw const DOCUMENT_ROOT;
    unsafe {
        match (*document_root_ptr).as_ref() {
            Some(root) => root.clone(),
            None => {
                let root = {
                    let collection = document().get_elements_by_tag_name("head");
                    if collection.length() > 0 {
                        collection.item(0).unwrap()
                    } else {
                        document().get_elements_by_tag_name("body").item(0).unwrap()
                    }
                };
                DOCUMENT_ROOT = Some(root.clone());
                root
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The kind of resource a [`Content`] entry holds.
pub enum ContentType {
    /// A JavaScript module (injected as `<script type="module">`).
    Module,
    /// A classic JavaScript script.
    Script,
    /// A CSS stylesheet.
    Style,
}

impl ContentType {
    /// Return `true` if this content type is JavaScript (a module or script).
    pub fn is_js(&self) -> bool {
        self == &ContentType::Script || self == &ContentType::Module
    }
}

#[allow(dead_code)]
/// The kind of dependency one [`Content`] entry declares on another,
/// determining how the reference is emitted into the generated source.
pub enum Reference {
    /// An `import` of another JavaScript module.
    Module,
    /// A reference to another script.
    Script,
    /// A reference to a stylesheet.
    Style,
    /// An `export ... from` re-export of another module.
    Export,
}

#[allow(dead_code)]
#[derive(Debug, Clone)]
/// Outcome of attempting to load a [`Content`] entry.
pub enum ContentStatus {
    /// The content was freshly loaded and injected into the DOM.
    Loaded,
    /// The content was already loaded; nothing was done.
    Exists,
    /// Loading failed.
    Error,
}

/// A single loadable DOM resource (JavaScript module, script or CSS
/// stylesheet) together with its identity, embedded source and the other
/// content entries it references.
pub struct Content {
    /// The kind of resource this content represents.
    pub content_type: ContentType,
    /// Object URL of the generated blob, set once the content is loaded.
    pub url: Mutex<Option<String>>,
    /// Unique identifier of this content entry.
    pub id: Id,
    /// Human-readable identifier, used as the injected element's `id`.
    pub ident: &'static str,
    /// The embedded source text of the resource.
    pub content: &'static str,
    /// Other content entries this resource imports from or exports, each as a
    /// reference kind, optional detail string and target content id.
    pub references: Option<&'static [(Reference, Option<&'static str>, Id)]>,
    /// Whether this content has already been injected into the DOM.
    pub is_loaded: AtomicBool,
}

// unsafe impl Send for Module {}
// unsafe impl Sync for Module {}

impl Content {
    /// Return the object URL of this content's blob once it has been created,
    /// or `None` if it has not yet been loaded.
    pub fn url(&self) -> Option<String> {
        self.url.lock().unwrap().clone()
    }

    // fn content(&self, ctx: &Context) -> Result<String> {
    fn content(&self, ctx: &Context) -> Result<String> {
        let mut text = String::new();

        if let Some(references) = &self.references {
            let mut imports = Vec::new();
            let mut exports = Vec::new();

            for (kind, what, id) in references.iter() {
                let module = ctx
                    .get(id)
                    .ok_or(format!("unable to lookup module `{}`", self.ident))?;
                let url = module
                    .url()
                    .ok_or(format!("[{}] module is not loaded `{}`", self.ident, id))?;
                match kind {
                    Reference::Module => match what {
                        Some(detail) => {
                            imports.push(format!("import {detail} from \"{url}\";"));
                        }
                        None => {
                            imports.push(format!("import \"{url}\";"));
                        }
                    },
                    Reference::Export => {
                        let module = ctx
                            .get(id)
                            .ok_or(format!("unable to lookup module `{}`", self.ident))?;
                        let url = module
                            .url()
                            .ok_or(format!("[{}] module is not loaded `{}`", self.ident, id))?;
                        exports.push(format!("export {} from \"{}\";", what.unwrap(), url));
                    }
                    _ => {}
                }
            }

            let imports = imports.join("\n");
            let exports = exports.join("\n");

            text += &imports;
            text += self.content;
            text += &exports;
            Ok(text)
        } else {
            Ok(self.content.to_string())
        }
    }

    /// Return `true` if this content has already been injected into the DOM.
    pub fn is_loaded(&self) -> bool {
        self.is_loaded.load(Ordering::SeqCst)
    }

    fn load_deps(self: Arc<Self>, ctx: Arc<Context>) -> BoxFuture<'static, Result<()>> {
        async move {
            if let Some(references) = &self.references {
                let futures = references
                    .iter()
                    .filter_map(|(_, _, id)| match ctx.get(id) {
                        Some(content) => {
                            if !content.is_loaded.load(Ordering::SeqCst) {
                                Some(content.load(&ctx))
                            } else {
                                None
                            }
                        }
                        _ => {
                            log_error!("Unable to locate module {}", id);
                            None
                        }
                    })
                    .collect::<Vec<_>>();

                join_all(futures).await;

                // for future in futures {
                //     future.await?;
                // }
            }
            Ok(())
        }
        .boxed()
    }

    /// Load this content (and its dependencies) into the DOM through the
    /// given [`Context`], returning the resulting [`ContentStatus`].
    pub async fn load(self: Arc<Self>, ctx: &Arc<Context>) -> Result<ContentStatus> {
        ctx.load_content(self).await
    }

    fn create_blob_url(&self, ctx: &Arc<Context>) -> Result<String> {
        let content = self.content(ctx)?;
        let args = Array::new_with_length(1);
        args.set(0, unsafe { Uint8Array::view(content.as_bytes()).into() });
        let options = web_sys::BlobPropertyBag::new();
        match self.content_type {
            ContentType::Module | ContentType::Script => {
                options.set_type("application/javascript");
            }
            ContentType::Style => {
                options.set_type("text/css");
            }
        }

        let blob = Blob::new_with_u8_array_sequence_and_options(&args, &options)?;
        let url = Url::create_object_url_with_blob(&blob)?;
        self.url.lock().unwrap().replace(url.clone());
        Ok(url)
    }

    async fn load_impl(self: &Arc<Self>, ctx: &Arc<Context>) -> Result<ContentStatus> {
        if self.is_loaded() {
            return Ok(ContentStatus::Exists);
        }

        self.clone().load_deps(ctx.clone()).await?;
        // log_info!("load ... {}", self.ident);

        let (sender, receiver) = oneshot();
        let url = self.create_blob_url(ctx)?;

        // let ident = self.ident.clone();
        let callback = callback!(move |_event: web_sys::CustomEvent| {
            // log_info!("{} ... done", ident);
            // TODO - analyze event
            let status = ContentStatus::Loaded;
            sender.try_send(status).expect("unable to post load event");
        });

        match &self.content_type {
            ContentType::Module | ContentType::Script => {
                self.inject_script(&url, &callback)?;
            }
            ContentType::Style => {
                self.inject_style(&url, &callback)?;
            }
        };
        let status = receiver.recv().await.expect("unable to recv() load event");
        self.is_loaded.store(true, Ordering::SeqCst);
        Ok(status)
    }

    fn inject_script<C>(&self, url: &str, callback: &C) -> Result<()>
    where
        C: AsRef<js_sys::Function>,
    {
        let script = document().create_element("script")?;
        script.add_event_listener_with_callback("load", callback.as_ref())?;

        match &self.content_type {
            ContentType::Module => {
                script.set_attribute("module", "true")?;
                script.set_attribute("type", "module")?;
            }
            ContentType::Script => {
                script.set_attribute("type", "application/javascript")?;
            }
            _ => {
                panic!(
                    "inject_script() unsupported content type `{:?}`",
                    self.content_type
                )
            }
        }
        script.set_attribute("src", url)?;
        script.set_attribute("id", self.ident)?;
        root().append_child(&script)?;
        Ok(())
    }

    fn inject_style<C>(&self, url: &str, callback: &C) -> Result<()>
    where
        C: AsRef<js_sys::Function>,
    {
        let style = document().create_element("link")?;
        style.add_event_listener_with_callback("load", callback.as_ref())?;
        style.set_attribute("type", "text/css")?;
        style.set_attribute("rel", "stylesheet")?;
        style.set_attribute("href", url)?;
        style.set_attribute("id", self.ident)?;
        root().append_child(&style)?;
        println!("injecting style `{}`", self.ident);
        Ok(())
    }
}

/// Registry and loading context for DOM content, tracking declared content
/// entries, de-duplicating in-flight load requests and counting loaded items.
pub struct Context {
    /// Map of registered content entries keyed by their id.
    pub content: Arc<Mutex<ContentMap>>,
    /// Coordinates concurrent load requests so that each content id is only
    /// loaded once while other callers await the shared result.
    pub lookup_handler: LookupHandler<Id, ContentStatus, Error>,
    /// Running count of content entries that have been loaded.
    pub loaded: AtomicUsize,
}

impl Default for Context {
    fn default() -> Self {
        Context {
            content: Arc::new(Mutex::new(ContentMap::new())),
            lookup_handler: LookupHandler::new(),
            loaded: AtomicUsize::new(0),
        }
    }
}

impl Context {
    // pub fn new(content : ContentMap) -> Context {
    //     Context {
    //         content : Arc::new(Mutex::new(content)),
    //         lookup_handler: LookupHandler::new(),
    //         loaded : AtomicUsize::new(0),
    //     }
    // }

    /// Register the given content entries with this context, making them
    /// available for later loading by id.
    pub fn declare(&self, content: ContentList) {
        self.content.lock().unwrap().extend(content.iter().cloned());
        // let mut map = self.content.lock().unwrap();
        // for (id, content) in content.iter() {
        //     map.insert(*id,content.clone());
        // }
    }

    /// Return the registered [`Content`] entry for the given id, if any.
    pub fn get(&self, id: &Id) -> Option<Arc<Content>> {
        self.content.lock().unwrap().get(id).cloned()
    }

    /// Load a single content entry, injecting it into the DOM. Concurrent
    /// requests for the same content are de-duplicated via the lookup handler,
    /// and already-loaded content resolves immediately as [`ContentStatus::Exists`].
    pub async fn load_content(self: &Arc<Self>, content: Arc<Content>) -> Result<ContentStatus> {
        if content.is_loaded() {
            Ok(ContentStatus::Exists)
        } else {
            match self.lookup_handler.queue(&content.id).await {
                RequestType::New(receiver) => {
                    self.loaded.fetch_add(1, Ordering::SeqCst);
                    let result = content.load_impl(self).await;
                    self.lookup_handler.complete(&content.id, result).await;
                    receiver.recv().await?
                }
                RequestType::Pending(receiver) => receiver.recv().await?,
            }
        }
    }

    /// Load all content entries identified by the given list of ids,
    /// resolving and injecting each into the DOM, and log the total number
    /// of references loaded along with the elapsed time.
    pub async fn load_ids(self: &Arc<Self>, list: &[Id]) -> Result<()> {
        let start = Instant::now();

        // let mut futures = Vec::with_capacity(list.len());
        // for id in list {
        //     if let Some(module) = self.get(id) {
        //         futures.push(module.load(self));
        //     }
        // }
        let futures = list
            .iter()
            .filter_map(|id| {
                match self.get(id) {
                    Some(module) => Some(module.load(self)),
                    _ => {
                        log_error!("Unable to locate module {}", id);
                        // TODO: panic
                        None
                    }
                }
            })
            .collect::<Vec<_>>();

        for future in futures {
            match future.await {
                Ok(_event) => {}
                Err(err) => {
                    log_error!("{}", err);
                }
            }
        }

        let elapsed = start.elapsed();
        let loaded = self.loaded.load(Ordering::SeqCst);
        log_info!(
            "Loaded {} references in {} msec",
            loaded,
            elapsed.as_millis()
        );

        Ok(())
    }
}

static mut CONTEXT: Option<Arc<Context>> = None;

/// Return the global, lazily-initialized loader [`Context`] singleton.
pub fn context() -> Arc<Context> {
    let context_ptr = &raw const CONTEXT;
    unsafe {
        if let Some(context) = (*context_ptr).as_ref() {
            context.clone()
        } else {
            let context = Arc::new(Context::default());
            CONTEXT = Some(context.clone());
            context
        }
    }
}

/// Declare the given content entries on the global loader [`Context`],
/// registering them for subsequent loading, and return that context.
pub fn declare(content: ContentList) -> Arc<Context> {
    let ctx = context();
    ctx.declare(content);
    ctx
}