leptos_meta 0.8.6

Tools to set HTML metadata in the Leptos web framework.
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
use crate::{use_head, MetaContext, ServerMetaContext};
use leptos::{
    attr::{any_attribute::AnyAttribute, Attribute},
    component,
    oco::Oco,
    prelude::{ArcTrigger, Notify, Track},
    reactive::{effect::RenderEffect, owner::use_context},
    tachys::{
        dom::document,
        hydration::Cursor,
        view::{
            add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
            RenderHtml,
        },
    },
    text_prop::TextProp,
    IntoView,
};
use or_poisoned::OrPoisoned;
use std::sync::{
    atomic::{AtomicU32, Ordering},
    Arc, Mutex, RwLock,
};

/// Contains the current state of the document's `<title>`.
#[derive(Clone, Default)]
pub struct TitleContext {
    id: Arc<AtomicU32>,
    formatter_stack: Arc<RwLock<Vec<(TitleId, Formatter)>>>,
    text_stack: Arc<RwLock<Vec<(TitleId, TextProp)>>>,
    revalidate: ArcTrigger,
    #[allow(clippy::type_complexity)]
    effect: Arc<Mutex<Option<RenderEffect<Option<Oco<'static, str>>>>>>,
}

impl core::fmt::Debug for TitleContext {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("TitleContext").finish()
    }
}

type TitleId = u32;

impl TitleContext {
    fn next_id(&self) -> TitleId {
        self.id.fetch_add(1, Ordering::Relaxed)
    }

    fn invalidate(&self) {
        self.revalidate.notify();
    }

    fn spawn_effect(&self) {
        let this = self.clone();
        let revalidate = self.revalidate.clone();

        let mut effect_lock = self.effect.lock().or_poisoned();
        if effect_lock.is_none() {
            *effect_lock = Some(RenderEffect::new({
                move |_| {
                    revalidate.track();
                    let text = this.as_string();
                    document().set_title(text.as_deref().unwrap_or_default());
                    text
                }
            }));
        }
    }

    fn push_text_and_formatter(
        &self,
        id: TitleId,
        text: Option<TextProp>,
        formatter: Option<Formatter>,
    ) {
        if let Some(text) = text {
            self.text_stack.write().or_poisoned().push((id, text));
        }
        if let Some(formatter) = formatter {
            self.formatter_stack
                .write()
                .or_poisoned()
                .push((id, formatter));
        }
        self.invalidate();
    }

    fn update_text_and_formatter(
        &self,
        id: TitleId,
        text: Option<TextProp>,
        formatter: Option<Formatter>,
    ) {
        let mut text_stack = self.text_stack.write().or_poisoned();
        let mut formatter_stack = self.formatter_stack.write().or_poisoned();
        let text_pos =
            text_stack.iter().position(|(item_id, _)| *item_id == id);
        let formatter_pos = formatter_stack
            .iter()
            .position(|(item_id, _)| *item_id == id);

        match (text_pos, text) {
            (None, None) => {}
            (Some(old), Some(new)) => {
                text_stack[old].1 = new;
                self.invalidate();
            }
            (Some(old), None) => {
                text_stack.remove(old);
                self.invalidate();
            }
            (None, Some(new)) => {
                text_stack.push((id, new));
                self.invalidate();
            }
        }
        match (formatter_pos, formatter) {
            (None, None) => {}
            (Some(old), Some(new)) => {
                formatter_stack[old].1 = new;
                self.invalidate();
            }
            (Some(old), None) => {
                formatter_stack.remove(old);
                self.invalidate();
            }
            (None, Some(new)) => {
                formatter_stack.push((id, new));
                self.invalidate();
            }
        }
    }

    fn remove_id(&self, id: TitleId) -> (Option<TextProp>, Option<Formatter>) {
        let mut text_stack = self.text_stack.write().or_poisoned();
        let text = text_stack
            .iter()
            .position(|(item_id, _)| *item_id == id)
            .map(|pos| text_stack.remove(pos).1);

        let mut formatter_stack = self.formatter_stack.write().or_poisoned();
        let formatter = formatter_stack
            .iter()
            .position(|(item_id, _)| *item_id == id)
            .map(|pos| formatter_stack.remove(pos).1);

        self.invalidate();

        (text, formatter)
    }

    /// Converts the title into a string that can be used as the text content of a `<title>` tag.
    pub fn as_string(&self) -> Option<Oco<'static, str>> {
        let title = self
            .text_stack
            .read()
            .or_poisoned()
            .last()
            .map(|n| n.1.get());

        title.map(|title| {
            if let Some(formatter) =
                self.formatter_stack.read().or_poisoned().last()
            {
                (formatter.1 .0)(title.into_owned()).into()
            } else {
                title
            }
        })
    }
}

/// A function that is applied to the text value before setting `document.title`.
#[repr(transparent)]
pub struct Formatter(Box<dyn Fn(String) -> String + Send + Sync>);

impl<F> From<F> for Formatter
where
    F: Fn(String) -> String + Send + Sync + 'static,
{
    #[inline(always)]
    fn from(f: F) -> Formatter {
        Formatter(Box::new(f))
    }
}

/// A component to set the document’s title by creating an [`HTMLTitleElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTitleElement).
///
/// The `title` and `formatter` can be set independently of one another. For example, you can create a root-level
/// `<Title formatter=.../>` that will wrap each of the text values of `<Title/>` components created lower in the tree.
///
/// ```
/// use leptos::prelude::*;
/// use leptos_meta::*;
///
/// #[component]
/// fn MyApp() -> impl IntoView {
///     provide_meta_context();
///     let formatter = |text| format!("{text} — Leptos Online");
///
///     view! {
///       <main>
///         <Title formatter/>
///         // ... routing logic here
///       </main>
///     }
/// }
///
/// #[component]
/// fn PageA() -> impl IntoView {
///     view! {
///       <main>
///         <Title text="Page A"/> // sets title to "Page A — Leptos Online"
///       </main>
///     }
/// }
///
/// #[component]
/// fn PageB() -> impl IntoView {
///     view! {
///       <main>
///         <Title text="Page B"/> // sets title to "Page B — Leptos Online"
///       </main>
///     }
/// }
/// ```
#[component]
pub fn Title(
    /// A function that will be applied to any text value before it’s set as the title.
    #[prop(optional, into)]
    mut formatter: Option<Formatter>,
    /// Sets the current `document.title`.
    #[prop(optional, into)]
    mut text: Option<TextProp>,
) -> impl IntoView {
    let meta = use_head();
    let server_ctx = use_context::<ServerMetaContext>();
    let id = meta.title.next_id();
    if let Some(cx) = server_ctx {
        // if we are server rendering, we will not actually use these values via RenderHtml
        // instead, they'll be handled separately by the server integration
        // so it's safe to take them out of the props here
        cx.title
            .push_text_and_formatter(id, text.take(), formatter.take());
    };

    TitleView {
        id,
        meta,
        formatter,
        text,
    }
}

struct TitleView {
    id: u32,
    meta: MetaContext,
    formatter: Option<Formatter>,
    text: Option<TextProp>,
}

struct TitleViewState {
    id: TitleId,
    meta: MetaContext,
    // these are only Some(_) after being unmounted, and hold these values until dropped or remounted
    formatter: Option<Formatter>,
    text: Option<TextProp>,
}

impl Drop for TitleViewState {
    fn drop(&mut self) {
        // when TitleViewState is dropped, it should remove its ID from the text and formatter stacks
        // so that they no longer appear. it will also revalidate the whole title in case this one was active
        self.meta.title.remove_id(self.id);
    }
}

impl Render for TitleView {
    type State = TitleViewState;

    fn build(self) -> Self::State {
        let TitleView {
            id,
            meta,
            formatter,
            text,
        } = self;
        meta.title.spawn_effect();
        TitleViewState {
            id,
            meta,
            text,
            formatter,
        }
    }

    fn rebuild(self, _state: &mut Self::State) {
        self.meta.title.update_text_and_formatter(
            self.id,
            self.text,
            self.formatter,
        );
    }
}

impl AddAnyAttr for TitleView {
    type Output<SomeNewAttr: Attribute> = TitleView;

    fn add_any_attr<NewAttr: Attribute>(
        self,
        _attr: NewAttr,
    ) -> Self::Output<NewAttr>
    where
        Self::Output<NewAttr>: RenderHtml,
    {
        self
    }
}

impl RenderHtml for TitleView {
    type AsyncOutput = Self;
    type Owned = Self;

    const MIN_LENGTH: usize = 0;
    const EXISTS: bool = false;

    fn dry_resolve(&mut self) {}

    async fn resolve(self) -> Self::AsyncOutput {
        self
    }

    fn to_html_with_buf(
        self,
        _buf: &mut String,
        _position: &mut Position,
        _escape: bool,
        _mark_branches: bool,
        _extra_attrs: Vec<AnyAttribute>,
    ) {
        // meta tags are rendered into the buffer stored into the context
        // the value has already been taken out, when we're on the server
    }

    fn hydrate<const FROM_SERVER: bool>(
        self,
        _cursor: &Cursor,
        _position: &PositionState,
    ) -> Self::State {
        let TitleView {
            id,
            meta,
            formatter,
            text,
        } = self;
        meta.title.spawn_effect();
        // these need to be pushed here, rather than on mount, because mount() is not called when hydrating
        meta.title.push_text_and_formatter(id, text, formatter);
        TitleViewState {
            id,
            meta,
            text: None,
            formatter: None,
        }
    }

    fn into_owned(self) -> Self::Owned {
        self
    }
}

impl Mountable for TitleViewState {
    fn unmount(&mut self) {
        let (text, formatter) = self.meta.title.remove_id(self.id);
        if text.is_some() {
            self.text = text;
        }
        if formatter.is_some() {
            self.formatter = formatter;
        }
    }

    fn mount(
        &mut self,
        _parent: &leptos::tachys::renderer::types::Element,
        _marker: Option<&leptos::tachys::renderer::types::Node>,
    ) {
        // TitleView::el() guarantees that there is a <title> in the <head>
        // so there is no element to be mounted
        //
        // "mounting" in this case means that we actually want this title to be in active use
        // as a result, we will push it into the title stack and revalidate
        self.meta.title.push_text_and_formatter(
            self.id,
            self.text.take(),
            self.formatter.take(),
        );
    }

    fn insert_before_this(&self, _child: &mut dyn Mountable) -> bool {
        false
    }

    fn elements(&self) -> Vec<leptos::tachys::renderer::types::Element> {
        vec![]
    }
}