pathland-render-html 0.2.2

Pathland HTML renderer: maps opcode frames onto declarative HTML elements
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
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
//! Flat C ABI (`pathland_html_*`) — the cross-language host surface for the
//! HTML renderer. Every function is a pure function of a self-contained PLPL
//! batch: it parses the raw bytes, renders a full document or fragment in one
//! streaming pass (no retained state), and returns a NUL-terminated C string
//! the caller owns (release with `pathland_html_free`).
//!
//! Java binds this via JNA (`com.pathland.render.html` shim); Swift/.NET bind
//! the same ABI.

use std::ffi::{CStr, CString, c_char};
use std::os::raw::c_uchar;

use pathland_core_transport::decode_frame;

use crate::{DocumentMeta, css, HtmlRenderer};

fn render_bytes_with_css(
    batch: *const c_uchar,
    len: u32,
    root: u32,
    fragment: bool,
    debug: bool,
    css_base: Option<&str>,
) -> *const c_char {
    if batch.is_null() {
        return std::ptr::null();
    }
    let bytes = unsafe { std::slice::from_raw_parts(batch, len as usize) };
    let (opcodes, strings) = match decode_frame(bytes) {
        Ok(decoded) => decoded,
        Err(_) => return std::ptr::null(),
    };
    let renderer = HtmlRenderer::new().with_debug_comments(debug);
    let html = if fragment {
        renderer.render_fragment(&opcodes, &strings, root)
    } else if let Some(base) = css_base {
        renderer.render_document_linked(&opcodes, &strings, root, base)
    } else {
        renderer.render_document(&opcodes, &strings, root)
    };
    match CString::new(html) {
        Ok(cs) => cs.into_raw(),
        Err(_) => std::ptr::null(),
    }
}

/// Optional document metadata for [`pathland_html_render_with_meta`]
/// (flattened, `#[repr(C)]`). String fields are UTF-8 NUL-terminated C strings;
/// NULL means unset. The three flag bytes are non-zero to enable Open Graph,
/// Twitter cards, and JSON-LD structured data respectively.
#[repr(C)]
pub struct PathlandHtmlMeta {
    pub title: *const c_char,
    pub description: *const c_char,
    pub canonical_url: *const c_char,
    pub site_name: *const c_char,
    pub image_url: *const c_char,
    pub og_type: *const c_char,
    pub twitter_card: *const c_char,
    pub twitter_site: *const c_char,
    pub open_graph: u8,
    pub twitter: u8,
    pub structured_data: u8,
}

/// Copy one nullable C string into an owned `DocumentMeta` field.
unsafe fn meta_string(value: *const c_char) -> Option<String> {
    if value.is_null() {
        None
    } else {
        unsafe { CStr::from_ptr(value) }
            .to_str()
            .ok()
            .map(str::to_string)
    }
}

/// Decode a [`PathlandHtmlMeta`] pointer (NULL → the legacy document head).
unsafe fn document_meta(meta: *const PathlandHtmlMeta) -> DocumentMeta {
    if meta.is_null() {
        return DocumentMeta::none();
    }
    let meta = unsafe { &*meta };
    DocumentMeta {
        title: unsafe { meta_string(meta.title) },
        description: unsafe { meta_string(meta.description) },
        canonical_url: unsafe { meta_string(meta.canonical_url) },
        site_name: unsafe { meta_string(meta.site_name) },
        image_url: unsafe { meta_string(meta.image_url) },
        og_type: unsafe { meta_string(meta.og_type) },
        twitter_card: unsafe { meta_string(meta.twitter_card) },
        twitter_site: unsafe { meta_string(meta.twitter_site) },
        open_graph: meta.open_graph != 0,
        twitter: meta.twitter != 0,
        structured_data: meta.structured_data != 0,
    }
}

fn render_bytes(
    batch: *const c_uchar,
    len: u32,
    root: u32,
    fragment: bool,
    debug: bool,
) -> *const c_char {
    render_bytes_with_css(batch, len, root, fragment, debug, None)
}

/// Render a self-contained PLPL batch as a **full HTML document**. Returns a
/// NUL-terminated C string owned by the caller (release with `pathland_html_free`);
/// NULL when the batch is malformed.
///
/// # Safety
/// `batch` must point to `len` readable bytes; the batch is decoded
/// bounds-checked before any rendering.
#[no_mangle]
pub unsafe extern "C" fn pathland_html_render(batch: *const c_uchar, len: u32, root: u32) -> *const c_char {
    render_bytes(batch, len, root, false, false)
}

/// Render a self-contained PLPL batch as an **HTML fragment** (no `<html>`).
/// Ownership and safety as [`pathland_html_render`].
#[no_mangle]
pub unsafe extern "C" fn pathland_html_render_fragment(
    batch: *const c_uchar,
    len: u32,
    root: u32,
) -> *const c_char {
    render_bytes(batch, len, root, true, false)
}

/// Render a self-contained PLPL batch as a **full HTML document** with
/// **debug comments** on every node (a non-zero `debug` enables them — see
/// [`crate::debug`]). Ownership and safety as [`pathland_html_render`].
#[no_mangle]
pub unsafe extern "C" fn pathland_html_render_debug(
    batch: *const c_uchar,
    len: u32,
    root: u32,
    debug: u8,
) -> *const c_char {
    render_bytes(batch, len, root, false, debug != 0)
}

/// Render a self-contained PLPL batch as an **HTML fragment** with **debug
/// comments** on every node (a non-zero `debug` enables them). Ownership and
/// safety as [`pathland_html_render`].
#[no_mangle]
pub unsafe extern "C" fn pathland_html_render_fragment_debug(
    batch: *const c_uchar,
    len: u32,
    root: u32,
    debug: u8,
) -> *const c_char {
    render_bytes(batch, len, root, true, debug != 0)
}

/// Release a string returned by [`pathland_html_render`] /
/// [`pathland_html_render_fragment`]. No-op on NULL.
///
/// # Safety
/// `ptr` must be a pointer previously returned by this module (or NULL).
#[no_mangle]
pub unsafe extern "C" fn pathland_html_free(ptr: *const c_char) {
    if !ptr.is_null() {
        drop(CString::from_raw(ptr as *mut c_char));
    }
}

/// Render a self-contained PLPL batch as a **full HTML document** whose base
/// design is a content-hashed stylesheet link at `{css_base}/{name}` instead of
/// an inline `<style>` block (see [`pathland_html_base_css_name`]). `debug`
/// non-zero enables node comments. Ownership and safety as
/// [`pathland_html_render`]; `css_base` must be a valid NUL-terminated C string
/// (or NULL, which falls back to the inline document).
#[no_mangle]
pub unsafe extern "C" fn pathland_html_render_linked(
    batch: *const c_uchar,
    len: u32,
    root: u32,
    css_base: *const c_char,
    debug: u8,
) -> *const c_char {
    let css_base = if css_base.is_null() {
        None
    } else {
        match unsafe { CStr::from_ptr(css_base) }.to_str() {
            Ok(base) => Some(base),
            Err(_) => return std::ptr::null(),
        }
    };
    render_bytes_with_css(batch, len, root, false, debug != 0, css_base)
}

/// Render a self-contained PLPL batch as a **full HTML document** with
/// host-supplied [`PathlandHtmlMeta`] (canonical URL, Open Graph/Twitter cards,
/// JSON-LD). `css_base` may be NULL for the inline base design; `meta` may be
/// NULL for the legacy head. `debug` non-zero enables node comments. Ownership
/// and safety as [`pathland_html_render`].
///
/// # Safety
/// `batch` must point to `len` readable bytes; `css_base` and every non-NULL
/// string field in `meta` must be valid NUL-terminated C strings.
#[no_mangle]
pub unsafe extern "C" fn pathland_html_render_with_meta(
    batch: *const c_uchar,
    len: u32,
    root: u32,
    css_base: *const c_char,
    meta: *const PathlandHtmlMeta,
    debug: u8,
) -> *const c_char {
    if batch.is_null() {
        return std::ptr::null();
    }
    let bytes = unsafe { std::slice::from_raw_parts(batch, len as usize) };
    let (opcodes, strings) = match decode_frame(bytes) {
        Ok(decoded) => decoded,
        Err(_) => return std::ptr::null(),
    };
    let renderer = HtmlRenderer::new().with_debug_comments(debug != 0);
    let meta = unsafe { document_meta(meta) };
    let html = if css_base.is_null() {
        renderer.render_document_with_meta(&opcodes, &strings, root, &meta)
    } else {
        let base = match unsafe { CStr::from_ptr(css_base) }.to_str() {
            Ok(base) => base,
            Err(_) => return std::ptr::null(),
        };
        renderer.render_document_linked_with_meta(&opcodes, &strings, root, base, &meta)
    };
    match CString::new(html) {
        Ok(cs) => cs.into_raw(),
        Err(_) => std::ptr::null(),
    }
}

/// The generated base-design stylesheet (the bytes served at
/// `{base}/[`pathland_html_base_css_name`]`). Returns a NUL-terminated C string
/// owned by the caller (release with [`pathland_html_free`]).
#[no_mangle]
pub extern "C" fn pathland_html_base_css() -> *const c_char {
    match CString::new(css::builtin_css()) {
        Ok(cs) => cs.into_raw(),
        Err(_) => std::ptr::null(),
    }
}

/// The content-hashed asset name of the base stylesheet (e.g.
/// `base-5f86423db422.css`), so a host can serve it with immutable caching and
/// emit a cache-busting `<link>`. Returns a NUL-terminated C string owned by the
/// caller (release with [`pathland_html_free`]).
#[no_mangle]
pub extern "C" fn pathland_html_base_css_name() -> *const c_char {
    match CString::new(css::builtin_css_name()) {
        Ok(cs) => cs.into_raw(),
        Err(_) => std::ptr::null(),
    }
}

/// The full `<svg>` for a canonical `ICON_NAME` — the renderer-owned glyph
/// served at `/_pathland/icons/<name>.svg`. This is how every host language
/// (Java via JNA, Swift/.NET/Node/Go via this same ABI) serves the web
/// renderer's icon glyphs from ONE Rust source, instead of copying static
/// files per platform. Returns a NUL-terminated C string owned by the caller
/// (release with [`pathland_html_free`]); never NULL except when `name` is
/// NULL — an unknown/extension name yields this renderer's fallback glyph (the
/// same one SSR inlines), so a host can always answer with a glyph.
///
/// # Safety
/// `name` must be a valid NUL-terminated C string (or NULL).
#[no_mangle]
pub unsafe extern "C" fn pathland_html_icon_svg(name: *const c_char) -> *const c_char {
    if name.is_null() {
        return std::ptr::null();
    }
    let name = unsafe { CStr::from_ptr(name) }.to_string_lossy().into_owned();
    let open = crate::icons::WEB_SVG_OPEN;
    let inner = crate::icons::web_inner(&name).unwrap_or_else(crate::icons::web_fallback_svg);
    let svg = format!("{open}{inner}</svg>");
    match CString::new(svg) {
        Ok(cs) => cs.into_raw(),
        Err(_) => std::ptr::null(),
    }
}

#[cfg(test)]
mod tests {
    use std::ffi::CStr;

    use pathland_core::{Opcode, category, component_type, property_id, parameter, tree};
    use pathland_core_transport::encode_frame;

    use super::*;

    #[test]
    fn capi_renders_a_full_document_and_frees() {
        let mut opcodes = Vec::new();
        let mut strings = Vec::new();
        opcodes.push(Opcode::new(category::TREE, tree::CREATE_NODE, 0, 1, component_type::TEXT as u32, 0));
        strings.extend_from_slice(&(2u32).to_le_bytes());
        strings.extend_from_slice(b"Hi");
        opcodes.push(Opcode::new(category::PARAMETER, parameter::SET_TEXT, 0, 1, 0, 0));
        let bytes = encode_frame(&opcodes, &strings);

        let ptr = unsafe { pathland_html_render(bytes.as_ptr(), bytes.len() as u32, 1) };
        assert!(!ptr.is_null());
        let html = unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned();
        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("<span data-pathland-id=\"1\">Hi</span>"));
        unsafe { pathland_html_free(ptr) };

        let frag = unsafe { pathland_html_render_fragment(bytes.as_ptr(), bytes.len() as u32, 1) };
        let html = unsafe { CStr::from_ptr(frag) }.to_string_lossy().into_owned();
        assert!(!html.contains("<!DOCTYPE html>"));
        assert!(html.contains("data-pathland-id=\"1\""));
        unsafe { pathland_html_free(frag) };
    }

    #[test]
    fn capi_exposes_the_base_css_and_renders_a_linked_document() {
        let css_ptr = pathland_html_base_css();
        assert!(!css_ptr.is_null());
        let css = unsafe { CStr::from_ptr(css_ptr) }.to_string_lossy().into_owned();
        assert!(css.contains("--pl-color-primary"), "base design bytes");
        unsafe { pathland_html_free(css_ptr) };

        let name_ptr = pathland_html_base_css_name();
        assert!(!name_ptr.is_null());
        let name = unsafe { CStr::from_ptr(name_ptr) }.to_string_lossy().into_owned();
        assert!(name.starts_with("base-") && name.ends_with(".css"), "{name}");
        unsafe { pathland_html_free(name_ptr) };

        let mut opcodes = Vec::new();
        opcodes.push(Opcode::new(
            category::TREE,
            tree::CREATE_NODE,
            0,
            1,
            component_type::TEXT as u32,
            0,
        ));
        let bytes = encode_frame(&opcodes, &[]);
        let base = std::ffi::CString::new("/_pathland").unwrap();
        let ptr = unsafe {
            pathland_html_render_linked(bytes.as_ptr(), bytes.len() as u32, 1, base.as_ptr(), 0)
        };
        assert!(!ptr.is_null());
        let html = unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned();
        assert!(
            html.contains(&format!(
                "<link rel=\"stylesheet\" href=\"/_pathland/{name}\">"
            )),
            "{html}"
        );
        assert!(!html.contains("<style>"), "linked document omits inline base CSS: {html}");
        unsafe { pathland_html_free(ptr) };
    }

    #[test]
    fn capi_renders_slot_route_and_transition_attrs() {
        // A VSTACK slot carrying ROUTE (STRING) + TRANSITION (F32 enum 3 = Slide): the
        // DOM client reads data-pathland-route to mirror the URL and may animate a swap.
        let mut opcodes = Vec::new();
        let mut strings = Vec::new();
        opcodes.push(Opcode::new(category::TREE, tree::CREATE_NODE, 0, 1, component_type::VSTACK as u32, 0));
        strings.extend_from_slice(&(9u32).to_le_bytes());
        strings.extend_from_slice(b"/users/42");
        opcodes.push(Opcode::new(
            category::PARAMETER,
            parameter::SET_PROPERTY,
            0,
            1,
            (0x05u32 << 16) | property_id::ROUTE as u32,
            0,
        ));
        opcodes.push(Opcode::new(
            category::PARAMETER,
            parameter::SET_PROPERTY,
            0,
            1,
            (0x04u32 << 16) | property_id::TRANSITION as u32,
            3.0f32.to_bits(),
        ));
        opcodes.push(Opcode::new(
            category::PARAMETER,
            parameter::SET_PROPERTY,
            0,
            1,
            (0x04u32 << 16) | property_id::NAV_CHROME as u32,
            1.0f32.to_bits(),
        ));
        opcodes.push(Opcode::new(
            category::PARAMETER,
            parameter::SET_PROPERTY,
            0,
            1,
            (0x02u32 << 16) | property_id::NAV_DEPTH as u32,
            2,
        ));
        let bytes = encode_frame(&opcodes, &strings);

        let frag = unsafe { pathland_html_render_fragment(bytes.as_ptr(), bytes.len() as u32, 1) };
        let html = unsafe { CStr::from_ptr(frag) }.to_string_lossy().into_owned();
        assert!(html.contains("data-pathland-route=\"/users/42\""), "{html}");
        assert!(html.contains("data-pathland-transition=\"slide\""), "{html}");
        assert!(html.contains("data-pathland-nav-chrome=\"custom\""), "{html}");
        assert!(html.contains("data-pathland-depth=\"2\""), "{html}");
        unsafe { pathland_html_free(frag) };
    }

    #[test]
    fn capi_debug_render_emits_node_comments() {
        let mut opcodes = Vec::new();
        opcodes.push(Opcode::new(category::TREE, tree::CREATE_NODE, 0, 1, component_type::VSTACK as u32, 0));
        opcodes.push(Opcode::new(
            category::PARAMETER,
            parameter::SET_PROPERTY,
            0,
            1,
            (0x04u32 << 16) | property_id::SPACING as u32,
            4.0f32.to_bits(),
        ));
        let bytes = encode_frame(&opcodes, &[]);

        // Debug on: a per-node comment naming component + modifiers.
        let ptr = unsafe { pathland_html_render_debug(bytes.as_ptr(), bytes.len() as u32, 1, 1) };
        let html = unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned();
        assert!(html.contains("<!-- #1 VStack: spacing=4 -->"), "{html}");
        unsafe { pathland_html_free(ptr) };

        // Debug off is byte-identical to the plain export (no comments).
        let ptr = unsafe { pathland_html_render_debug(bytes.as_ptr(), bytes.len() as u32, 1, 0) };
        let html = unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned();
        assert!(!html.contains("<!--"), "{html}");
        unsafe { pathland_html_free(ptr) };
    }

    #[test]
    fn capi_rejects_a_truncated_batch() {
        let ptr = unsafe { pathland_html_render([0u8, 1, 2].as_ptr(), 3, 1) };
        assert!(ptr.is_null());
    }

    #[test]
    fn capi_serves_icon_svgs_from_the_shared_renderer() {
        // Canonical name → the full inline `<svg>`, matching what SSR inlines.
        let cname = std::ffi::CString::new(pathland_core::icon::HOME).unwrap();
        let ptr = unsafe { pathland_html_icon_svg(cname.as_ptr()) };
        assert!(!ptr.is_null());
        let svg = unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned();
        assert!(svg.starts_with("<svg class=\"pathland-icon\""), "{svg}");
        assert!(svg.ends_with("</svg>"), "{svg}");
        assert!(svg.len() > 40, "a real glyph path is inlined: {svg}");
        unsafe { pathland_html_free(ptr) };

        // Unknown/extension name → this renderer's fallback glyph (never NULL):
        // hosts can always answer with a glyph.
        let unknown = std::ffi::CString::new("definitely-not-an-icon").unwrap();
        let ptr = unsafe { pathland_html_icon_svg(unknown.as_ptr()) };
        assert!(!ptr.is_null());
        let svg = unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned();
        assert!(svg.contains("<circle"), "{svg}");
        unsafe { pathland_html_free(ptr) };

        // NULL input → NULL.
        assert!(unsafe { pathland_html_icon_svg(std::ptr::null()) }.is_null());
    }
    #[test]
    fn capi_renders_document_meta() {
        let mut opcodes = Vec::new();
        opcodes.push(Opcode::new(
            category::TREE,
            tree::CREATE_NODE,
            0,
            1,
            component_type::TEXT as u32,
            0,
        ));
        let bytes = encode_frame(&opcodes, &[]);
        let canonical = std::ffi::CString::new("https://example.com/library").unwrap();
        let title = std::ffi::CString::new("Fallback title").unwrap();
        let site = std::ffi::CString::new("Pathland Music").unwrap();
        let meta = PathlandHtmlMeta {
            title: title.as_ptr(),
            description: std::ptr::null(),
            canonical_url: canonical.as_ptr(),
            site_name: site.as_ptr(),
            image_url: std::ptr::null(),
            og_type: std::ptr::null(),
            twitter_card: std::ptr::null(),
            twitter_site: std::ptr::null(),
            open_graph: 1,
            twitter: 1,
            structured_data: 1,
        };
        let ptr = unsafe {
            pathland_html_render_with_meta(
                bytes.as_ptr(),
                bytes.len() as u32,
                1,
                std::ptr::null(),
                &meta,
                0,
            )
        };
        assert!(!ptr.is_null());
        let html = unsafe { CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned();
        assert!(html.contains("<title>Fallback title</title>"), "{html}");
        assert!(
            html.contains("<link rel=\"canonical\" href=\"https://example.com/library\">"),
            "{html}"
        );
        assert!(html.contains("\"@type\":\"WebPage\""), "{html}");
        unsafe { pathland_html_free(ptr) };

        // A NULL meta pointer keeps the legacy head.
        let plain = unsafe {
            pathland_html_render_with_meta(
                bytes.as_ptr(),
                bytes.len() as u32,
                1,
                std::ptr::null(),
                std::ptr::null(),
                0,
            )
        };
        let html = unsafe { CStr::from_ptr(plain) }
            .to_string_lossy()
            .into_owned();
        assert!(!html.contains("rel=\"canonical\""), "{html}");
        assert!(!html.contains("application/ld+json"), "{html}");
        unsafe { pathland_html_free(plain) };
    }
}