summaryrefslogtreecommitdiff
path: root/crates/typst-html/src/typed.rs
blob: 190ff4f168a3261882d97de14fdd4f8245c6314a (plain) (blame)
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! The typed HTML element API (e.g. `html.div`).
//!
//! The typed API is backed by generated data derived from the HTML
//! specification. See [generated] and `tools/codegen`.

use std::fmt::Write;
use std::num::{NonZeroI64, NonZeroU64};
use std::sync::LazyLock;

use bumpalo::Bump;
use comemo::Tracked;
use ecow::{eco_format, eco_vec, EcoString};
use typst_assets::html as data;
use typst_library::diag::{bail, At, Hint, HintedStrResult, SourceResult};
use typst_library::engine::Engine;
use typst_library::foundations::{
    Args, Array, AutoValue, CastInfo, Content, Context, Datetime, Dict, Duration,
    FromValue, IntoValue, NativeFuncData, NativeFuncPtr, NoneValue, ParamInfo,
    PositiveF64, Reflect, Scope, Str, Type, Value,
};
use typst_library::layout::{Axes, Axis, Dir, Length};
use typst_library::visualize::Color;
use typst_macros::cast;

use crate::{css, tag, HtmlAttr, HtmlAttrs, HtmlElem, HtmlTag};

/// Hook up all typed HTML definitions.
pub(super) fn define(html: &mut Scope) {
    for data in FUNCS.iter() {
        html.define_func_with_data(data);
    }
}

/// Lazily created functions for all typed HTML constructors.
static FUNCS: LazyLock<Vec<NativeFuncData>> = LazyLock::new(|| {
    // Leaking is okay here. It's not meaningfully different from having
    // memory-managed values as `FUNCS` is a static.
    let bump = Box::leak(Box::new(Bump::new()));
    data::ELEMS.iter().map(|info| create_func_data(info, bump)).collect()
});

/// Creates metadata for a native HTML element constructor function.
fn create_func_data(
    element: &'static data::ElemInfo,
    bump: &'static Bump,
) -> NativeFuncData {
    NativeFuncData {
        function: NativeFuncPtr(bump.alloc(
            move |_: &mut Engine, _: Tracked<Context>, args: &mut Args| {
                construct(element, args)
            },
        )),
        name: element.name,
        title: {
            let title = bump.alloc_str(element.name);
            title[0..1].make_ascii_uppercase();
            title
        },
        docs: element.docs,
        keywords: &[],
        contextual: false,
        scope: LazyLock::new(&|| Scope::new()),
        params: LazyLock::new(bump.alloc(move || create_param_info(element))),
        returns: LazyLock::new(&|| CastInfo::Type(Type::of::<Content>())),
    }
}

/// Creates parameter signature metadata for an element.
fn create_param_info(element: &'static data::ElemInfo) -> Vec<ParamInfo> {
    let mut params = vec![];
    for attr in element.attributes() {
        params.push(ParamInfo {
            name: attr.name,
            docs: attr.docs,
            input: AttrType::convert(attr.ty).input(),
            default: None,
            positional: false,
            named: true,
            variadic: false,
            required: false,
            settable: false,
        });
    }
    let tag = HtmlTag::constant(element.name);
    if !tag::is_void(tag) {
        params.push(ParamInfo {
            name: "body",
            docs: "The contents of the HTML element.",
            input: CastInfo::Type(Type::of::<Content>()),
            default: None,
            positional: true,
            named: false,
            variadic: false,
            required: false,
            settable: false,
        });
    }
    params
}

/// The native constructor function shared by all HTML elements.
fn construct(element: &'static data::ElemInfo, args: &mut Args) -> SourceResult<Value> {
    let mut attrs = HtmlAttrs::default();
    let mut errors = eco_vec![];

    args.items.retain(|item| {
        let Some(name) = &item.name else { return true };
        let Some(attr) = element.get_attr(name) else { return true };

        let span = item.value.span;
        let value = std::mem::take(&mut item.value.v);
        let ty = AttrType::convert(attr.ty);
        match ty.cast(value).at(span) {
            Ok(Some(string)) => attrs.push(HtmlAttr::constant(attr.name), string),
            Ok(None) => {}
            Err(diags) => errors.extend(diags),
        }

        false
    });

    if !errors.is_empty() {
        return Err(errors);
    }

    let tag = HtmlTag::constant(element.name);
    let mut elem = HtmlElem::new(tag);
    if !attrs.0.is_empty() {
        elem.attrs.set(attrs);
    }

    if !tag::is_void(tag) {
        let body = args.eat::<Content>()?;
        elem.body.set(body);
    }

    Ok(elem.into_value())
}

/// A dynamic representation of an attribute's type.
///
/// See the documentation of [`data::Type`] for more details on variants.
enum AttrType {
    Presence,
    Native(NativeType),
    Strings(StringsType),
    Union(UnionType),
    List(ListType),
}

impl AttrType {
    /// Converts the type definition into a representation suitable for casting
    /// and reflection.
    const fn convert(ty: data::Type) -> AttrType {
        use data::Type;
        match ty {
            Type::Presence => Self::Presence,
            Type::None => Self::of::<NoneValue>(),
            Type::NoneEmpty => Self::of::<NoneEmpty>(),
            Type::NoneUndefined => Self::of::<NoneUndefined>(),
            Type::Auto => Self::of::<AutoValue>(),
            Type::TrueFalse => Self::of::<TrueFalseBool>(),
            Type::YesNo => Self::of::<YesNoBool>(),
            Type::OnOff => Self::of::<OnOffBool>(),
            Type::Int => Self::of::<i64>(),
            Type::NonNegativeInt => Self::of::<u64>(),
            Type::PositiveInt => Self::of::<NonZeroU64>(),
            Type::Float => Self::of::<f64>(),
            Type::PositiveFloat => Self::of::<PositiveF64>(),
            Type::Str => Self::of::<Str>(),
            Type::Char => Self::of::<char>(),
            Type::Datetime => Self::of::<Datetime>(),
            Type::Duration => Self::of::<Duration>(),
            Type::Color => Self::of::<Color>(),
            Type::HorizontalDir => Self::of::<HorizontalDir>(),
            Type::IconSize => Self::of::<IconSize>(),
            Type::ImageCandidate => Self::of::<ImageCandidate>(),
            Type::SourceSize => Self::of::<SourceSize>(),
            Type::Strings(start, end) => Self::Strings(StringsType { start, end }),
            Type::Union(variants) => Self::Union(UnionType(variants)),
            Type::List(inner, separator, shorthand) => {
                Self::List(ListType { inner, separator, shorthand })
            }
        }
    }

    /// Produces the dynamic representation of an attribute type backed by a
    /// native Rust type.
    const fn of<T: IntoAttr>() -> Self {
        Self::Native(NativeType::of::<T>())
    }

    /// See [`Reflect::input`].
    fn input(&self) -> CastInfo {
        match self {
            Self::Presence => bool::input(),
            Self::Native(ty) => (ty.input)(),
            Self::Union(ty) => ty.input(),
            Self::Strings(ty) => ty.input(),
            Self::List(ty) => ty.input(),
        }
    }

    /// See [`Reflect::castable`].
    fn castable(&self, value: &Value) -> bool {
        match self {
            Self::Presence => bool::castable(value),
            Self::Native(ty) => (ty.castable)(value),
            Self::Union(ty) => ty.castable(value),
            Self::Strings(ty) => ty.castable(value),
            Self::List(ty) => ty.castable(value),
        }
    }

    /// Tries to cast the value into this attribute's type and serialize it into
    /// an HTML attribute string.
    fn cast(&self, value: Value) -> HintedStrResult<Option<EcoString>> {
        match self {
            Self::Presence => value.cast::<bool>().map(|b| b.then(EcoString::new)),
            Self::Native(ty) => (ty.cast)(value),
            Self::Union(ty) => ty.cast(value),
            Self::Strings(ty) => ty.cast(value),
            Self::List(ty) => ty.cast(value),
        }
    }
}

/// An enumeration with generated string variants.
///
/// `start` and `end` are used to index into `data::ATTR_STRINGS`.
struct StringsType {
    start: usize,
    end: usize,
}

impl StringsType {
    fn input(&self) -> CastInfo {
        CastInfo::Union(
            self.strings()
                .iter()
                .map(|(val, desc)| CastInfo::Value(val.into_value(), desc))
                .collect(),
        )
    }

    fn castable(&self, value: &Value) -> bool {
        match value {
            Value::Str(s) => self.strings().iter().any(|&(v, _)| v == s.as_str()),
            _ => false,
        }
    }

    fn cast(&self, value: Value) -> HintedStrResult<Option<EcoString>> {
        if self.castable(&value) {
            value.cast().map(Some)
        } else {
            Err(self.input().error(&value))
        }
    }

    fn strings(&self) -> &'static [(&'static str, &'static str)] {
        &data::ATTR_STRINGS[self.start..self.end]
    }
}

/// A type that accepts any of the contained types.
struct UnionType(&'static [data::Type]);

impl UnionType {
    fn input(&self) -> CastInfo {
        CastInfo::Union(self.iter().map(|ty| ty.input()).collect())
    }

    fn castable(&self, value: &Value) -> bool {
        self.iter().any(|ty| ty.castable(value))
    }

    fn cast(&self, value: Value) -> HintedStrResult<Option<EcoString>> {
        for item in self.iter() {
            if item.castable(&value) {
                return item.cast(value);
            }
        }
        Err(self.input().error(&value))
    }

    fn iter(&self) -> impl Iterator<Item = AttrType> {
        self.0.iter().map(|&ty| AttrType::convert(ty))
    }
}

/// A list of items separated by a specific separator char.
///
/// - <https://html.spec.whatwg.org/#space-separated-tokens>
/// - <https://html.spec.whatwg.org/#comma-separated-tokens>
struct ListType {
    inner: &'static data::Type,
    separator: char,
    shorthand: bool,
}

impl ListType {
    fn input(&self) -> CastInfo {
        if self.shorthand {
            Array::input() + self.inner().input()
        } else {
            Array::input()
        }
    }

    fn castable(&self, value: &Value) -> bool {
        Array::castable(value) || (self.shorthand && self.inner().castable(value))
    }

    fn cast(&self, value: Value) -> HintedStrResult<Option<EcoString>> {
        let ty = self.inner();
        if Array::castable(&value) {
            let array = value.cast::<Array>()?;
            let mut out = EcoString::new();
            for (i, item) in array.into_iter().enumerate() {
                let item = ty.cast(item)?.unwrap();
                if item.as_str().contains(self.separator) {
                    let buf;
                    let name = match self.separator {
                        ' ' => "space",
                        ',' => "comma",
                        _ => {
                            buf = eco_format!("'{}'", self.separator);
                            buf.as_str()
                        }
                    };
                    bail!(
                        "array item may not contain a {name}";
                        hint: "the array attribute will be encoded as a \
                               {name}-separated string"
                    );
                }
                if i > 0 {
                    out.push(self.separator);
                    if self.separator == ',' {
                        out.push(' ');
                    }
                }
                out.push_str(&item);
            }
            Ok(Some(out))
        } else if self.shorthand && ty.castable(&value) {
            let item = ty.cast(value)?.unwrap();
            Ok(Some(item))
        } else {
            Err(self.input().error(&value))
        }
    }

    fn inner(&self) -> AttrType {
        AttrType::convert(*self.inner)
    }
}

/// A dynamic representation of attribute backed by a native type implementing
/// - the standard `Reflect` and `FromValue` traits for casting from a value,
/// - the special `IntoAttr` trait for conversion into an attribute string.
#[derive(Copy, Clone)]
struct NativeType {
    input: fn() -> CastInfo,
    cast: fn(Value) -> HintedStrResult<Option<EcoString>>,
    castable: fn(&Value) -> bool,
}

impl NativeType {
    /// Creates a dynamic native type from a native Rust type.
    const fn of<T: IntoAttr>() -> Self {
        Self {
            cast: |value| {
                let this = value.cast::<T>()?;
                Ok(Some(this.into_attr()))
            },
            input: T::input,
            castable: T::castable,
        }
    }
}

/// Casts a native type into an HTML attribute.
pub trait IntoAttr: FromValue {
    /// Turn the value into an attribute string.
    fn into_attr(self) -> EcoString;
}

impl IntoAttr for Str {
    fn into_attr(self) -> EcoString {
        self.into()
    }
}

/// A boolean that is encoded as a string:
/// - `false` is encoded as `"false"`
/// - `true` is encoded as `"true"`
pub struct TrueFalseBool(pub bool);

cast! {
    TrueFalseBool,
    v: bool => Self(v),
}

impl IntoAttr for TrueFalseBool {
    fn into_attr(self) -> EcoString {
        if self.0 { "true" } else { "false" }.into()
    }
}

/// A boolean that is encoded as a string:
/// - `false` is encoded as `"no"`
/// - `true` is encoded as `"yes"`
pub struct YesNoBool(pub bool);

cast! {
    YesNoBool,
    v: bool => Self(v),
}

impl IntoAttr for YesNoBool {
    fn into_attr(self) -> EcoString {
        if self.0 { "yes" } else { "no" }.into()
    }
}

/// A boolean that is encoded as a string:
/// - `false` is encoded as `"off"`
/// - `true` is encoded as `"on"`
pub struct OnOffBool(pub bool);

cast! {
    OnOffBool,
    v: bool => Self(v),
}

impl IntoAttr for OnOffBool {
    fn into_attr(self) -> EcoString {
        if self.0 { "on" } else { "off" }.into()
    }
}

impl IntoAttr for AutoValue {
    fn into_attr(self) -> EcoString {
        "auto".into()
    }
}

impl IntoAttr for NoneValue {
    fn into_attr(self) -> EcoString {
        "none".into()
    }
}

/// A `none` value that turns into an empty string attribute.
struct NoneEmpty;

cast! {
    NoneEmpty,
    _: NoneValue => NoneEmpty,
}

impl IntoAttr for NoneEmpty {
    fn into_attr(self) -> EcoString {
        "".into()
    }
}

/// A `none` value that turns into the string `"undefined"`.
struct NoneUndefined;

cast! {
    NoneUndefined,
    _: NoneValue => NoneUndefined,
}

impl IntoAttr for NoneUndefined {
    fn into_attr(self) -> EcoString {
        "undefined".into()
    }
}

impl IntoAttr for char {
    fn into_attr(self) -> EcoString {
        eco_format!("{self}")
    }
}

impl IntoAttr for i64 {
    fn into_attr(self) -> EcoString {
        eco_format!("{self}")
    }
}

impl IntoAttr for u64 {
    fn into_attr(self) -> EcoString {
        eco_format!("{self}")
    }
}

impl IntoAttr for NonZeroI64 {
    fn into_attr(self) -> EcoString {
        eco_format!("{self}")
    }
}

impl IntoAttr for NonZeroU64 {
    fn into_attr(self) -> EcoString {
        eco_format!("{self}")
    }
}

impl IntoAttr for f64 {
    fn into_attr(self) -> EcoString {
        // HTML float literal allows all the things that Rust's float `Display`
        // impl produces.
        eco_format!("{self}")
    }
}

impl IntoAttr for PositiveF64 {
    fn into_attr(self) -> EcoString {
        self.get().into_attr()
    }
}

impl IntoAttr for Color {
    fn into_attr(self) -> EcoString {
        eco_format!("{}", css::color(self))
    }
}

impl IntoAttr for Duration {
    fn into_attr(self) -> EcoString {
        // https://html.spec.whatwg.org/#valid-duration-string
        let mut out = EcoString::new();
        macro_rules! part {
            ($s:literal) => {
                if !out.is_empty() {
                    out.push(' ');
                }
                write!(out, $s).unwrap();
            };
        }

        let [weeks, days, hours, minutes, seconds] = self.decompose();
        if weeks > 0 {
            part!("{weeks}w");
        }
        if days > 0 {
            part!("{days}d");
        }
        if hours > 0 {
            part!("{hours}h");
        }
        if minutes > 0 {
            part!("{minutes}m");
        }
        if seconds > 0 || out.is_empty() {
            part!("{seconds}s");
        }

        out
    }
}

impl IntoAttr for Datetime {
    fn into_attr(self) -> EcoString {
        let fmt = typst_utils::display(|f| match self {
            Self::Date(date) => datetime::date(f, date),
            Self::Time(time) => datetime::time(f, time),
            Self::Datetime(datetime) => datetime::datetime(f, datetime),
        });
        eco_format!("{fmt}")
    }
}

mod datetime {
    use std::fmt::{self, Formatter, Write};

    pub fn datetime(f: &mut Formatter, datetime: time::PrimitiveDateTime) -> fmt::Result {
        // https://html.spec.whatwg.org/#valid-global-date-and-time-string
        date(f, datetime.date())?;
        f.write_char('T')?;
        time(f, datetime.time())
    }

    pub fn date(f: &mut Formatter, date: time::Date) -> fmt::Result {
        // https://html.spec.whatwg.org/#valid-date-string
        write!(f, "{:04}-{:02}-{:02}", date.year(), date.month() as u8, date.day())
    }

    pub fn time(f: &mut Formatter, time: time::Time) -> fmt::Result {
        // https://html.spec.whatwg.org/#valid-time-string
        write!(f, "{:02}:{:02}", time.hour(), time.minute())?;
        if time.second() > 0 {
            write!(f, ":{:02}", time.second())?;
        }
        Ok(())
    }
}

/// A direction on the X axis: `ltr` or `rtl`.
pub struct HorizontalDir(Dir);

cast! {
    HorizontalDir,
    v: Dir => {
        if v.axis() == Axis::Y {
            bail!("direction must be horizontal");
        }
        Self(v)
    },
}

impl IntoAttr for HorizontalDir {
    fn into_attr(self) -> EcoString {
        self.0.into_attr()
    }
}

impl IntoAttr for Dir {
    fn into_attr(self) -> EcoString {
        match self {
            Self::LTR => "ltr".into(),
            Self::RTL => "rtl".into(),
            Self::TTB => "ttb".into(),
            Self::BTT => "btt".into(),
        }
    }
}

/// A width/height pair for `<link rel="icon" sizes="..." />`.
pub struct IconSize(Axes<u64>);

cast! {
    IconSize,
    v: Axes<u64> => Self(v),
}

impl IntoAttr for IconSize {
    fn into_attr(self) -> EcoString {
        eco_format!("{}x{}", self.0.x, self.0.y)
    }
}

/// <https://html.spec.whatwg.org/#image-candidate-string>
pub struct ImageCandidate(EcoString);

cast! {
    ImageCandidate,
    mut v: Dict => {
        let src = v.take("src")?.cast::<EcoString>()?;
        let width: Option<NonZeroU64> =
            v.take("width").ok().map(Value::cast).transpose()?;
        let density: Option<PositiveF64> =
            v.take("density").ok().map(Value::cast).transpose()?;
        v.finish(&["src", "width", "density"])?;

        if src.is_empty() {
            bail!("`src` must not be empty");
        } else if src.starts_with(',') || src.ends_with(',') {
            bail!("`src` must not start or end with a comma");
        }

        let mut out = src;
        match (width, density) {
            (None, None) => {}
            (Some(width), None) => write!(out, " {width}w").unwrap(),
            (None, Some(density)) => write!(out, " {}d", density.get()).unwrap(),
            (Some(_), Some(_)) => bail!("cannot specify both `width` and `density`"),
        }

        Self(out)
    },
}

impl IntoAttr for ImageCandidate {
    fn into_attr(self) -> EcoString {
        self.0
    }
}

/// <https://html.spec.whatwg.org/multipage/images.html#valid-source-size-list>
pub struct SourceSize(EcoString);

cast! {
    SourceSize,
    mut v: Dict => {
        let condition = v.take("condition")?.cast::<EcoString>()?;
        let size = v
            .take("size")?
            .cast::<Length>()
            .hint("CSS lengths that are not expressible as Typst lengths are not yet supported")
            .hint("you can use `html.elem` to create a raw attribute")?;
        Self(eco_format!("({condition}) {}", css::length(size)))
    },
}

impl IntoAttr for SourceSize {
    fn into_attr(self) -> EcoString {
        self.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tags_and_attr_const_internible() {
        for elem in data::ELEMS {
            let _ = HtmlTag::constant(elem.name);
        }
        for attr in data::ATTRS {
            let _ = HtmlAttr::constant(attr.name);
        }
    }
}