euv-docs 0.37.14

A documentation site generator powered by euv + euv-ui (Rust/WASM).
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
use super::*;

/// Renders the public catalog of stored projects.
///
/// The catalog is fetched from the artifact API and rendered in Rust, so
/// the documentation home page needs no script and no hand-written
/// stylesheet: the cards carry the framework's own `c_catalog*` classes.
///
/// The component owns the request, so it can render the three states the
/// catalog has: loading, failed and loaded. The failed state carries a
/// retry button, because a transient network failure must not leave the
/// page with a dead end.
///
/// The cards are built in plain Rust and handed to the grid through the
/// component's children. A `html!` loop needs static data, and the
/// catalog is runtime data, so the cards travel as children instead.
///
/// # Arguments
///
/// - `VirtualNode<DocsCatalogProps>` - The props node carrying the route.
///
/// # Returns
///
/// - `VirtualNode` - The rendered catalog.
#[component]
pub(crate) fn docs_catalog(node: VirtualNode<DocsCatalogProps>) -> VirtualNode {
    let DocsCatalogProps { route_signal }: DocsCatalogProps =
        node.try_get_props().unwrap_or_default();
    // The locale is resolved once, before the cards are built. Reading
    // the signal inside the loop would make every card register its own
    // dependency on the route.
    let locale: String = route_signal.get();
    let files_label: String = locale_text(&locale, DOCS_KEY_CATALOG_FILES);
    let size_label: String = locale_text(&locale, DOCS_KEY_CATALOG_SIZE);
    let updated_label: String = locale_text(&locale, DOCS_KEY_CATALOG_UPDATED);
    let loading_label: String = locale_text(&locale, DOCS_KEY_CATALOADING);
    let error_label: String = locale_text(&locale, DOCS_KEY_CATALOG_ERROR);
    let retry_label: String = locale_text(&locale, DOCS_KEY_CATALOG_RETRY);
    let catalog: UseAsyncHandle<Vec<DocsCatalogArtifact>, ()> =
        use_async::<Vec<DocsCatalogArtifact>, ()>();
    match catalog.state() {
        AsyncState::<Vec<DocsCatalogArtifact>, ()>::Loading(_) => {
            // The request is issued from the loading state, and the
            // retry button re-enters that state, so both paths send
            // exactly one request.
            //
            // A host build has no page to fetch from, so the request is
            // not issued there and the host build renders the failure
            // state instead of spawning a browser future.
            #[cfg(target_arch = "wasm32")]
            catalog.refetch(|| async { request_catalog().await });
            html! {
                div {
                    class: c_catalog()
                    p {
                        class: c_catalog_card_summary()
                        role: CATALOG_ROLE_STATUS
                        {
                            loading_label.clone()
                        }
                    }
                }
            }
        }
        AsyncState::<Vec<DocsCatalogArtifact>, ()>::Err(_) => html! {
            div {
                class: c_catalog()
                p {
                    class: c_catalog_card_summary()
                    role: CATALOG_ROLE_STATUS
                    {
                        error_label.clone()
                    }
                }
                button {
                    class: c_catalog_button()
                    type: CATALOG_BUTTON_TYPE
                    onclick: move |_event: Event| {
                        catalog.set_state(AsyncState::<Vec<DocsCatalogArtifact>, ()>::Loading(()));
                    }
                    {
                        retry_label.clone()
                    }
                }
            }
        },
        AsyncState::<Vec<DocsCatalogArtifact>, ()>::Ok(artifacts) => {
            let mut cards: Vec<VirtualNode> = Vec::with_capacity(artifacts.len());
            for artifact in artifacts.iter() {
                cards.push(docs_catalog_card(
                    artifact.clone(),
                    files_label.clone(),
                    size_label.clone(),
                    updated_label.clone(),
                ));
            }
            let children: VirtualNode = VirtualNode::Fragment(cards);
            html! {
                div {
                    class: c_catalog()
                    div {
                        class: c_catalog_grid()
                        children
                    }
                }
            }
        }
    }
}

/// Renders one catalog card.
///
/// The card carries both the framework's `c_catalog_card` class and the
/// documentation site's own `docs-catalog-card` class: the framework owns
/// the styling, and the site's class is the contract the documentation
/// runtime validator asserts on.
///
/// # Arguments
///
/// - `DocsCatalogArtifact` - The artifact the card describes.
/// - `String` - The localized label of the file count field.
/// - `String` - The localized label of the total size field.
/// - `String` - The localized label of the update time field.
///
/// # Returns
///
/// - `VirtualNode` - The rendered card.
fn docs_catalog_card(
    artifact: DocsCatalogArtifact,
    files_label: String,
    size_label: String,
    updated_label: String,
) -> VirtualNode {
    let link: String = CATALOG_LINK_TEMPLATE.replace("{name}", &artifact.get_name());
    let name: String = artifact.get_name().clone();
    let digest: String = artifact.get_sha256().clone();
    let files: String = artifact.get_file_count().to_string();
    let size: String = format_bytes(artifact.get_total_bytes());
    let updated: String = format_timestamp(artifact.get_updated_at());
    html! {
        article {
            class: c_catalog_card()
            class: CATALOG_CARD_CLASS
            h3 {
                class: c_catalog_card_title()
                a {
                    class: c_catalog_card_title_link()
                    href: link.clone()
                    {
                        name.clone()
                    }
                }
            }
            dl {
                class: c_catalog_card_details()
                dt {
                    class: c_catalog_card_details_label()
                    {
                        files_label.clone()
                    }
                }
                dd {
                    class: c_catalog_card_details_value()
                    {
                        files.clone()
                    }
                }
                dt {
                    class: c_catalog_card_details_label()
                    {
                        size_label.clone()
                    }
                }
                dd {
                    class: c_catalog_card_details_value()
                    {
                        size.clone()
                    }
                }
                dt {
                    class: c_catalog_card_details_label()
                    {
                        updated_label.clone()
                    }
                }
                dd {
                    class: c_catalog_card_details_value()
                    time {
                        datetime: updated.clone()
                        {
                            updated.clone()
                        }
                    }
                }
            }
            code {
                class: c_catalog_card_digest()
                {
                    digest.clone()
                }
            }
        }
    }
}

/// Requests the catalog and parses it.
///
/// The framework's fetch primitive is a browser API, so a host build
/// has no page to fetch from and the request cannot be made there.
///
/// # Returns
///
/// - `Result<Vec<DocsCatalogArtifact>, String>` - The stored projects, or
///   the reason they could not be read.
#[cfg(target_arch = "wasm32")]
async fn request_catalog() -> Result<Vec<DocsCatalogArtifact>, String> {
    let response: FetchResponse = fetch(CATALOG_URL)
        .await
        .map_err(|error: FetchError| format!("{ERROR_CATALOG_SHAPE}: {error}"))?;
    if !response.is_ok() {
        return Err(ERROR_CATALOG_SHAPE.to_string());
    }
    Ok(parse_catalog(&response.bytes())?.get_artifacts())
}

/// Formats a byte count the way the catalog shows it.
///
/// # Arguments
///
/// - `u64` - The byte count.
///
/// # Returns
///
/// - `String` - The formatted size.
fn format_bytes(bytes: u64) -> String {
    const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
    let mut value: f64 = bytes as f64;
    let mut unit: usize = 0;
    while value >= 1024.0 && unit < UNITS.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes} B")
    } else {
        format!("{value:.2} {}", UNITS[unit])
    }
}

/// Formats a Unix timestamp as an ISO-8601 instant.
///
/// # Arguments
///
/// - `i64` - Seconds since the Unix epoch.
///
/// # Returns
///
/// - `String` - The ISO-8601 instant, or the raw seconds when the instant
///   cannot be represented.
fn format_timestamp(seconds: i64) -> String {
    match chrono::DateTime::from_timestamp(seconds, 0) {
        Some(instant) => instant.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        None => seconds.to_string(),
    }
}

/// Parses the catalog API response.
///
/// The response is `{"success":true,"data":{"count":N,"artifacts":[...]}}`.
/// Every field the cards show is validated here, because a malformed
/// value would otherwise reach the page as a broken card: the name must
/// be a safe path segment, the digest must be a hex SHA-256, and the
/// counts must be non-negative integers.
///
/// # Arguments
///
/// - `&[u8]` - The raw response body.
///
/// # Returns
///
/// - `Result<DocsCatalog, String>` - The parsed catalog, or the reason
///   the response must not be rendered.
pub fn parse_catalog(bytes: &[u8]) -> Result<DocsCatalog, String> {
    let text: &str = from_utf8(bytes).map_err(|_| ERROR_CATALOG_ENCODING.to_string())?;
    let root: Value = serde_json::from_str(text)
        .map_err(|error: Error| format!("{ERROR_CATALOG_SHAPE}: {error}"))?;
    let data: &Value = root.get("data").unwrap_or(&root);
    let artifacts: &Value = data
        .get("artifacts")
        .ok_or_else(|| ERROR_CATALOG_SHAPE.to_string())?;
    let list: &Vec<Value> = artifacts
        .as_array()
        .ok_or_else(|| ERROR_CATALOG_SHAPE.to_string())?;
    let mut parsed: Vec<DocsCatalogArtifact> = Vec::with_capacity(list.len());
    let mut names: Vec<String> = Vec::with_capacity(list.len());
    for item in list {
        let name: String =
            text_field(item, "name").ok_or_else(|| ERROR_CATALOG_SHAPE.to_string())?;
        if !is_safe_artifact_name(&name) || names.contains(&name) {
            return Err(ERROR_CATALOG_SHAPE.to_string());
        }
        names.push(name.clone());
        let sha256: String =
            text_field(item, "sha256").ok_or_else(|| ERROR_CATALOG_SHAPE.to_string())?;
        if !is_sha256(&sha256) {
            return Err(ERROR_CATALOG_SHAPE.to_string());
        }
        parsed.push(DocsCatalogArtifact::new(
            name,
            count_field(item, "fileCount")?,
            count_field(item, "totalBytes")?,
            sha256,
            count_field(item, "updatedAt")? as i64,
        ));
    }
    if let Some(count) = data.get("count").and_then(Value::as_u64)
        && count as usize != parsed.len()
    {
        return Err(ERROR_CATALOG_SHAPE.to_string());
    }
    Ok(DocsCatalog::new(parsed))
}

/// Reads a string field from a catalog entry.
///
/// # Arguments
///
/// - `&Value` - The entry.
/// - `&str` - The field name.
///
/// # Returns
///
/// - `Option<String>` - The value, or `None` when the field is absent or
///   is not a string.
fn text_field(item: &Value, field: &str) -> Option<String> {
    item.get(field).and_then(Value::as_str).map(str::to_string)
}

/// Reads a non-negative integer field from a catalog entry.
///
/// # Arguments
///
/// - `&Value` - The entry.
/// - `&str` - The field name.
///
/// # Returns
///
/// - `Result<u64, String>` - The value, or the reason the entry must not
///   be rendered.
fn count_field(item: &Value, field: &str) -> Result<u64, String> {
    item.get(field)
        .and_then(Value::as_u64)
        .ok_or_else(|| ERROR_CATALOG_SHAPE.to_string())
}

/// Whether the name is a safe path for a published page.
///
/// A published artifact is addressed either by its bare name, such as
/// `docs`, or by its qualified name, such as `docs-pages/docs`, which
/// names the organization and the repository. The catalog lists the
/// qualified name, so both shapes have to be accepted — but a qualified
/// name is only safe when each of its two segments is safe on its own.
/// A name with a different number of segments, an empty segment or a
/// traversing segment is refused.
///
/// # Arguments
///
/// - `&str` - The artifact name.
///
/// # Returns
///
/// - `bool` - `true` when the name can be used in a link.
fn is_safe_artifact_name(name: &str) -> bool {
    if name.is_empty() || name.len() > 63 {
        return false;
    }
    let segments: Vec<&str> = name.split(ORG_REPO_SEPARATOR).collect();
    if segments.len() > 2 {
        return false;
    }
    segments
        .iter()
        .all(|segment: &&str| is_safe_name_segment(segment))
}

/// Whether the segment is a safe path segment on its own.
///
/// # Arguments
///
/// - `&str` - The segment.
///
/// # Returns
///
/// - `bool` - `true` when the segment can be used in a link.
fn is_safe_name_segment(segment: &str) -> bool {
    !segment.is_empty()
        && segment
            .bytes()
            .all(|byte: u8| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == HYPHEN)
        && !segment.starts_with(HYPHEN_CHAR)
        && !segment.ends_with(HYPHEN_CHAR)
}

/// Whether the digest is a hex SHA-256.
///
/// # Arguments
///
/// - `&str` - The digest.
///
/// # Returns
///
/// - `bool` - `true` when the digest is well formed.
fn is_sha256(digest: &str) -> bool {
    digest.len() == 64
        && digest
            .bytes()
            .all(|byte: u8| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
}