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
use std::sync::Arc;

use dioxus_core::AttributeValue;
use dioxus_hooks::{use_memo_with_dependencies, Dependency};
use dioxus_signals::{ReadOnlySignal, Readable};
use freya_node_state::{CanvasReference, CanvasRunner, CustomAttributeValues};

/// Holds a rendering hook callback that allows to render to the Canvas.
#[derive(PartialEq, Clone)]
pub struct UseCanvas {
    runner: ReadOnlySignal<UseCanvasRunner>,
}

#[derive(Clone)]
pub struct UseCanvasRunner(pub Arc<Box<CanvasRunner>>);

impl PartialEq for UseCanvasRunner {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl UseCanvas {
    pub fn attribute(&self) -> AttributeValue {
        AttributeValue::any_value(CustomAttributeValues::Canvas(CanvasReference {
            runner: self.runner.read().0.clone(),
        }))
    }
}

/// Register a rendering hook to gain access to the Canvas.
///
/// ## Usage
/// ```rust,no_run
/// # use freya::prelude::*;
/// fn app() -> Element {
///     let canvas = use_canvas((), |_| {
///         Box::new(|canvas, font_collection, area| {
///             // Draw using the canvas !
///         })
///     });
///
///     rsx!(
///         Canvas {
///             canvas
///         }
///     )
/// }
/// ```
pub fn use_canvas<D: Dependency>(
    dependencies: D,
    renderer_cb: impl Fn(D::Out) -> Box<CanvasRunner> + 'static,
) -> UseCanvas
where
    D::Out: 'static,
{
    let runner = use_memo_with_dependencies(dependencies, move |dependencies| {
        UseCanvasRunner(Arc::new(renderer_cb(dependencies)))
    });

    UseCanvas { runner }
}