Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/model/link.rs

4.6 KiB, 1 run

created by r1870400018:63264, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-library `model/link.rs`, version 0.15.1).
3// Modified for Austenite: the element's fields, defaults and default show, ported to Hematite's types, IR and error handling.
4// U5 owns this file: link. The show leaves the body in place under the internal style `link.current`,
5// the resolved destination -- a URL string, a location, or a position dictionary -- which inline flow
6// reads to make the body's text a link area, as Typst's `LinkElem::current` is read. A label destination
7// is resolved to the labelled element's location here. Typst's alternative text for a link, for tagged
8// PDF, is not produced.
9
10use crate::diag::DiagnosticKind;
11use crate::eval::args::Args;
12use crate::eval::content::{
13 Content,
14 ElemKind,
15 FieldDefault,
16 FieldSpec,
17 FieldType,
18};
19use crate::eval::lib::model::common::{
20 self,
21 expect,
22 to_content,
23 CastErr,
24 K,
25};
26use crate::eval::lib::model::lookup;
27use crate::eval::styles::{
28 StyleChain,
29 Styles,
30};
31use crate::eval::value::Value;
32use crate::eval::Engine;
33
34use oxedyne_fe2o3_core::prelude::*;
35
36const ANY: FieldType = FieldType::Any;
37
38static LINK: [FieldSpec; 3] = [
39 FieldSpec::required("dest", ANY),
40 FieldSpec::required("body", ANY),
41 FieldSpec::named("current", ANY, FieldDefault::None).internal(),
42];
43
44pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
45 match kind {
46 ElemKind::Link => &LINK,
47 _ => &[],
48 }
49}
50
51pub fn cast(_kind: ElemKind, name: &str, v: Value) -> Result<Value, CastErr> {
52 match name {
53 "dest" => dest(v),
54 "body" => expect(&v, &[K::Content]).map(|_| to_content(v)),
55 _ => Ok(v),
56 }
57}
58
59/// A destination: a URL, a label, a location, or a position (`(page: 1, x: 0pt, y: 0pt)`).
60fn dest(v: Value) -> Result<Value, CastErr> {
61 match &v {
62 Value::Str(s) if s.is_empty() => Err(CastErr::Value("URL must not be empty".to_string())),
63 Value::Str(s) if s.len() > 8000 => Err(CastErr::Value("URL is too long".to_string())),
64 Value::Str(_) | Value::Label(_) | Value::Location(_) => Ok(v),
65 Value::Dict(d) => {
66 for key in ["page", "x", "y"] {
67 if !d.contains(key) {
68 return Err(CastErr::Value(fmt!("dictionary does not contain key \"{}\"", key)));
69 }
70 }
71 Ok(v)
72 }
73 other => Err(CastErr::Type(common::mismatch("string, dictionary, location, or label", other))),
74 }
75}
76
77/// The text a URL shows when no body is given: the URL, less a `mailto:` or `tel:` scheme.
78pub fn body_from_url(url: &str) -> Content {
79 let shown = url.strip_prefix("mailto:").or_else(|| url.strip_prefix("tel:")).unwrap_or(url);
80 common::text(shown)
81}
82
83/// `link(dest, body)`: the body may be left out after a URL, which then shows itself.
84pub fn construct(engine: &mut Engine, args: &mut Args) -> Outcome<Content> {
85 let span = args.span;
86 let a = match args.items.iter().position(|a| a.name.is_none()) {
87 Some(p) => args.items.remove(p),
88 None => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: dest")),
89 };
90 let d = match dest(a.value) {
91 Ok(d) => d,
92 Err(e) => return Err(engine.error(DiagnosticKind::Type, a.span, e.message())),
93 };
94 let next = args.items.iter().position(|a| a.name.is_none()).map(|p| args.items.remove(p));
95 let body = match (next, &d) {
96 (Some(b), _) => match expect(&b.value, &[K::Content]) {
97 Ok(()) => to_content(b.value),
98 Err(e) => return Err(engine.error(DiagnosticKind::Type, b.span, e.message())),
99 },
100 (None, Value::Str(url)) => Value::Content(body_from_url(url).with_span(span)),
101 (None, _) => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: body")),
102 };
103 res!(super::finish(engine, args));
104 common::raw_elem(ElemKind::Link, span, vec![("dest", d), ("body", body)])
105}
106
107pub fn show_set() -> Outcome<Styles> {
108 common::props(vec![(ElemKind::Text, "hyphenate", Value::Bool(false))])
109}
110
111pub fn show(engine: &mut Engine, elem: &Content, _styles: &StyleChain) -> Outcome<Option<Content>> {
112 let span = elem.span();
113 let body = common::body(elem, "body");
114 let dest = match elem.field("dest") {
115 Some(Value::Label(l)) => {
116 let l = l.clone();
117 let target = res!(lookup::label(engine, &l, span));
118 match target.location() {
119 Some(loc) => Value::Location(loc),
120 None => return Err(engine.error(DiagnosticKind::Type, span, "cannot link to an element without a location")),
121 }
122 }
123 Some(v) => v.clone(),
124 None => Value::None,
125 };
126 Ok(Some(res!(common::set(body, ElemKind::Link, "current", dest))))
127}
128
129/// Content linked to a location, as Typst's `DirectLinkElem` makes a reference or an outline entry.
130pub fn to_location(body: Content, loc: crate::eval::locate::Location) -> Outcome<Content> {
131 common::set(body, ElemKind::Link, "current", Value::Location(loc))
132}