Skip to content

Generated code ​

What the compiler writes, and the API each component gets.

Generated code is ordinary Rust that calls this crate: there is no template engine and no reflection at run time. Commit it, and let pnpm ferrovue --check in CI catch a stale copy.

What is stable ​

Applications write Rust against generated modules, so their shape is API. What this page documents is the contract: within a major version, a newer compiler keeps every item below, with the name, the type shape and, for functions, the parameters in the order given here, and the Rust an application writes against them keeps compiling. That is:

  • the files of the output directory and the module names they give (DataList.vue is data_list, pages/books/[id].vue is books_id), and the version check at the top of mod.rs;
  • in each component module: NAME; Props, its public fields and, with builders on (the default), its new and its setters; the structs of local types, with the same; the enums of its unions of string literals, with their names, variants, ALL, as_str, Display, FromStr, TryFrom<&str> and Union; for a union unions names an enum for, that enum; Slots, each …SlotProps and each …Slot; render and try_render, with their parameters in the order below; html; and, for a component that renders from its props alone, island, into_html and into_island;
  • types.rs's structs, enums and constants, route_table.rs's ROUTES, PATHS, BASE and router(), stores.rs's state structs and Stores, i18n.rs's LOCALE, FALLBACK, LOCALES and i18n(locale), provides.rs's Provides, and twins.rs's …Props, …Slots and …Render;
  • the derives the tables below list, which an application relies on to copy, print and serialise what it builds;
  • render_json, under #[cfg(test)], and the fixture keys it reads.

Outside the contract, and free to change in any release: try_render_scoped and every other #[doc(hidden)] item; the bodies of functions, and the order of what they reserve, write and call; the names of render's parameters (an unread one is named with a leading _); private items, such as the fixture plumbing in mod.rs; comments; and the order of the pub mod lines. What render writes is held to Vue's output, which the conformance suite checks.

The repository's crates/ferrovue-contract crate generates every item listed here from a few components and uses each as an application would; CI builds and runs it against the compiler of the same commit, so a change that breaks an item fails there first.

The output directory ​

Each run replaces the files ferrovue wrote in the configured out directory: the .rs files that open with its // @generated by ferrovue header. A file of your own there is left as it is, and ferrovue --check reports it as not generated, so keep your own modules outside out.

FileWritten whenHolds
mod.rsalwaysThe version check, one pub mod per file below, and a #[cfg(test)] render_json for a project's conformance tests
<component>.rsone per .vue file, pages includedThe component's types and renderers: DataList.vue becomes data_list.rs, and the page books/[id].vue becomes books_id.rs
types.rsthe server render reaches a type or a constant exported from a .ts fileThe shared types the render reaches (the types of props and of their fields, of provided and injected values, of store state and of twins' props, and the enums of the unions of string literals they hold), in the order their files declare them and written once so components passing them to one another agree on them, and each constant a template reads, as a const. See shared types
route_table.rsroutes or router is configuredROUTES, PATHS, BASE and router(). See routing
stores.rsstores is configuredA struct per store's state, named for its id (cart has CartState), the types it uses, and Stores, with a field per store. See pinia
i18n.rsi18n is configuredLOCALE, FALLBACK, every locale's messages in LOCALES, and i18n(locale). See i18n
provides.rsa component calls provide or injectProvides, what the components' ancestors provide, with a field per key. See provide_inject
loaders.rsa component awaits a loaderA struct per loader's call, the Loaders trait the app implements, dispatch and load. See loaders
twins.rstwins is configuredEach twin's …Props and …Slots, and …Render, the signature its function must have. See errors_and_limits

Include the directory as one module. #[rustfmt::skip] keeps rustfmt from rewriting it:

rust
#[rustfmt::skip]
mod generated;

The modules pass rustc's default warnings and cargo clippy -- -D warnings, so they can sit in a crate that denies warnings. mod.rs allows one lint for all of them, at its top:

rust
// The modules pass rustc's default warnings and clippy's default lints, with one exception:
// `dead_code`. Every component gets the whole of its API (`render`, `html`, `island`, their
// `into_` forms, `NAME`, a constructor and a setter per optional prop) and an app calls only what
// it needs.
#![allow(dead_code)]

The only other allows are clippy::too_many_arguments, on a function that takes more than seven arguments: a props constructor with more than seven required props, which takes one argument per required field, and a render, try_render, try_render_scoped or html that takes most of the parameters below; and clippy::enum_variant_names, on the enum of a union of string literals whose variants all share a word, as "primary-button" | "link-button" do.

The version check ​

Generated code calls the ferrovue crate, so the two must come from compatible releases. Below the allow, mod.rs names the version of generated code its compiler writes:

rust
ferrovue::__compat!(9);

The version is a number that changes only when generated code changes in a way the crate must match: when the compiler starts calling something an older crate lacks, or the crate stops supporting something older generated code calls. Each crate accepts the versions it supports and stops the build at this line for any other, before the compiler reports anything else:

text
error: this module was generated as version 9 of ferrovue's generated code, and this `ferrovue` crate supports versions 6 to 8: use the `ferrovue` npm package and the `ferrovue` crate of one release, and run `ferrovue` to generate the module again
 --> src/generated/mod.rs:12:1
   |
12 | ferrovue::__compat!(9);
   | ^^^^^^^^^^^^^^^^^^^^^^

A newer crate stops an older module the same way once it no longer supports what the module calls. The 0.8 crate supports version 2 alone: modules of version 1, from 0.7, build RouteDef, Locale, Message and Args with struct literals, and these types are #[non_exhaustive] from 0.8 on, so version 2 builds them with their const constructors and with_ methods. Version 3 adds Date props, which generated code reads through JsTime, hands to a child and writes into data-props with helpers the 0.8 crate lacks; the 0.9 crate supports versions 2 and 3, since a module of version 2 calls nothing it changed. Version 4 adds loaders: a component that awaits one takes a Loads, and the generated loaders module calls what the 0.9 crate lacks; the 0.10 crate supports versions 2 to 4. Version 5 adds the enums of unions of string literals, whose FromStr fails with ParseUnionError, which the 0.10 crate lacks, and dates inside lists, dictionaries and interfaces, which it writes with helpers the 0.10 crate lacks; the 0.11 crate supports versions 2 to 5. Version 6 reads the literal of every union's enum through Union, which the 0.11 crate lacks, so that an enum unions names in ferrovue.config.json is read as a generated one is, and names every item of the crates at the module that defines it (fv::html::Html, fv::router::Route, fv::core::escape_into), which the 0.12 crate no longer lifts to its root: so the 0.12 crate supports version 6 alone, and stops a module of an earlier version at this line. Version 7 writes the keys of loaders that take an object, with calls of the key the 0.12 crate lacks; the 0.13 crate supports versions 6 and 7, and a module of version 6 builds unchanged. Version 8 writes the anchor of each <RouterLink> with one call of a helper the 0.13 crate lacks; the 0.14 crate supports versions 6 to 8. Version 9 writes the string a list's .join() builds, and the anchor of a <RouterLink> with a string to, straight into the page with helpers the 0.15 crate lacks; the 0.16 crate supports versions 6 to 9. The upgrade pages, upgrading_to_0_16, upgrading_to_0_14, upgrading_to_0_13, upgrading_to_0_12, upgrading_to_0_11, upgrading_to_0_10, upgrading_to_0_9 and upgrading_to_0_8, give the steps for each release.

__compat! itself is #[doc(hidden)] and may change form in any release; the check at the top of mod.rs stays.

A component's module ​

Every component module has, in this order:

ItemWhat it is
NAMEThe component's name, "DataList": what data-island carries, and what a Part of a Page records
One enum per union of string literals its props and local types holdSize for type Size = "sm" | "md", ButtonSize for size: "sm" | "md" in Button.vue's props: a variant per literal, ALL, as_str(), Display, FromStr, TryFrom<&str> and Union, deriving Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize and serde::Deserialize. One that a .ts file declares is in types.rs. See props
One struct per local interface or object typeRow for export interface Row { … }, with the same derives and builder as Props
One tuple struct per tuple typePair(pub Cow<'a, str>, pub i64) for type Pair = [string, number], CardScore for score: [string, number] in Card: a public field per part, deriving Debug, Clone and serde::Serialize, which writes it as an array, and with builders on a new that takes every part in order. See props
Props<'a>The props, one public field per prop, deriving Debug, Clone and serde::Serialize, and Default when every prop is optional. With builders on, Props::new takes the required props in declaration order and each optional prop other than one named new has a setter of its name. See props
…SlotProps<'v> and …Slot<'s>For each scoped slot: what its outlet passes (with <'v> only when it borrows), and the closure type a parent supplies. A component that takes fv_provides has a …Slot<'s> for each of its slots, scoped or not, whose closure is also given the Provides its content renders with. See slots
Slots<'s>When the component renders a <slot> or <RouterView>: what a parent puts in each, an Option per <slot> and the page as router_view. It derives Clone and Copy, and Default when it has no router_view
renderWrite the component into a buffer. It panics with the message of a refusal at render time, which try_render returns
try_renderrender, returning Result<(), fv::render::Refused>: the Refused of props that ask for what cannot be written as Vue writes it, such as a date string browsers read differently. See errors_and_limits
try_render_scopedOnly for a component a parent may hand <style scoped> ids to, or pass attributes it does not declare as props: try_render with those last. Generated parents call it; it is #[doc(hidden)] and outside the contract. See scoped_styles and fallthrough attributes
htmlThe same render as an Html value, whose try_render_to and try_into_string return the refusal
islandOnly for a component that renders from its props alone: the render wrapped as a hydratable island
into_html and into_islandBeside island: html and island taking the props by value, so the Html holds them

Props has no lifetime when none of its fields borrow (a component whose props are all numbers and booleans has a plain Props), and a component with no props has an empty Props.

A struct that a parent hands to a child, alone or in a list, gets a #[doc(hidden)]borrowed(&self): the same value with each string a Cow::Borrowed of the parent's, which the parent passes as rows: props.rows.iter().map(|v| v.borrowed()).collect(). Handing a child its rows then copies no text, however the parent's props were built. A dictionary (Record) handed to a child, alone or in a struct, keeps its keys borrowed the same way. A TrustedHtml, a project's own dateType and an enum of the application that unions maps a union to are cloned inside the copy. Where trustedHtml or dateType names a type with the lifetime 'a, a struct holding it has no borrowed() and is cloned whole.

The module is laid out for git diff. The render's out.reserve writes its constant on a line of its own and each term it adds on the next ones, so an edit of the template's markup changes the constant's line and the line of the markup. A child's props, the attributes and styles given to attrs_into, the classes given to class_into and an object given to useHead go one item a line where they do not fit in 100 columns, so a changed prop or attribute changes its own line.

render and its parameters ​

render always takes the buffer first and the props second. After them come only the parameters the component needs, always in this order, and try_render takes the same:

rust
pub fn render(
    out: &mut String,
    props: &Props<'_>,
    fv_slots: Slots<'_>,                          // renders <slot> or <RouterView>
    fv_route: &fv::router::Route<'_>,             // <RouterLink>, useRoute() or $route
    fv_stores: &super::stores::Stores<'_>,        // reads a Pinia store
    fv_i18n: &fv::i18n::I18n,                     // $t or useI18n()
    fv_teleports: &fv::page::Teleports,       // <Teleport>
    fv_provides: super::provides::Provides<'_>,   // provide() or inject()
    fv_head: &fv::head::Head,                     // useHead() or useSeoMeta()
)

A component needs a parameter when it uses the feature itself or renders a child that does: a Card whose child Badge reads a store takes the stores too, and passes them on. Generated parents call their children's try_render directly and return a child's refusal with ?, so a page renders in one pass with no intermediate strings. The fv_ prefix keeps these names apart from anything a template names.

So, from the repository's own test components:

rust
// Greeting.vue: props alone.
pub fn render(out: &mut String, props: &Props<'_>)
// Layout.vue: <RouterView> and two <RouterLink>s.
pub fn render(out: &mut String, props: &Props<'_>, fv_slots: Slots<'_>, fv_route: &fv::router::Route<'_>)
// Card.vue: renders Badge, which reads a store.
pub fn render(out: &mut String, props: &Props<'_>, fv_stores: &super::stores::Stores<'_>)
// Modal.vue: <Teleport>.
pub fn render(out: &mut String, props: &Props<'_>, fv_teleports: &fv::page::Teleports)

A component that a parent may hand scope ids to (see scoped_styles) also has a try_render_scoped, which takes the parameters of try_render and then fv_attrs: &str, the ids its root carries besides its own. Its render and try_render call it with "":

rust
pub fn render(out: &mut String, props: &Props<'_>) {
    fv::render::rendered(try_render_scoped(out, props, ""));
}

pub fn try_render(out: &mut String, props: &Props<'_>) -> Result<(), fv::render::Refused> {
    try_render_scoped(out, props, "")
}

/// [`try_render`], with the scope ids a parent hands the root: ` data-v-…` each.
#[doc(hidden)]
pub fn try_render_scoped(out: &mut String, props: &Props<'_>, fv_attrs: &str) -> Result<(), fv::render::Refused> {
    // …
}

A component that a parent passes attributes it does not declare as props takes them, with the ids, as one Attrs instead: see fallthrough attributes.

A try_render or try_render_scoped that never reads its props, such as a component's that only passes its slot on, names the parameter _props, so that the module compiles without warnings; it is still the second parameter.

render appends to out and never reads or rewrites what is already there, so a page can be assembled in one String: write the document's head, render the body's components into the same buffer, write the tail. It first reserves an estimate of what it will write, from its literal markup, the strings its props hold and the numbers it writes, once per item for a loop, so that the buffer grows once.

Fallthrough attributes ​

What a parent passes a child beyond its props (<Badge class="wide" :title="t" /> where Badge declares neither) falls through, as in Vue: onto the child's single root, merged with the root's own class and style and replacing its other attributes where they stand, or, with inheritAttrs: false, onto whatever element binds v-bind="$attrs" (or a useAttrs() binding). Two roots take none. A root that is another component passes them on to that one, merged with the attributes it gives it. Listeners are dropped, as Vue's server drops them.

The parent knows at compile time which attributes it passes, but the child is generated once for every parent, so the two meet at run time. A child that some parent passes attributes to takes fv_attrs: &fv::attrs::Attrs<'_> in its try_render_scoped, the attributes in order followed by the scope ids, and the parent builds them from its template:

rust
// <Badge :label="name" class="wide" :title="note" /> in a parent's template:
super::badge::try_render_scoped(out, &super::badge::Props { label: Cow::Borrowed(&props.name) },
    &fv::attrs::Attrs::new(&[("class", fv::attrs::Attr::str("wide")), ("title", props.note.as_deref().map_or(fv::attrs::Attr::Undefined, fv::attrs::Attr::str))], ""))?;

// Badge's root, `<b class="badge">`:
out.push_str("<b");
if fv_attrs.is_empty() {
    out.push_str(" class=\"badge\"");
    out.push_str(fv_attrs.ids());
} else {
    fv::attrs::attrs_into(out, &[
        &[("class", fv::attrs::Attr::str("badge"))],
        fv_attrs.list(),
    ], 1, fv_attrs.ids());
}

With nothing passed (from render, which passes Attrs::NONE, or from a parent that passes none), the root is written exactly as it would be without; only when attributes arrive does attrs_into merge them as Vue's mergeProps does and write them as ssrRenderAttrs does. A component no parent passes attributes to has neither: its render_scoped, if it has one, takes the scope ids alone as a &str.

Attribute names are what the parent's template gives, and their values strings, numbers, booleans or absent (undefined, which removes the root's own attribute of that name), a class or a style in any form a template binds. An attribute that would reach a prop of the component a root passes it on to, a value read from $attrs (it has no type), $attrs in a component whose $attrs would hold scope ids, and attributes passed to a root <Transition> or <KeepAlive> around a v-if (which Vue's server drops but its client keeps) are refused at compile time.

A <textarea> at the root takes its content from a value passed to the component, and an <input v-model> at the root reads type and value from what it is passed. Both are written as Vue writes them when no parent passes those attributes, which the compiler knows from every component that renders it: the content of the <textarea>, or its v-model, and the model's value or, for type="checkbox" with a boolean model, checked, merged with the attributes that do arrive. A parent that passes value or type, a bound or radio type, and a checkbox bound to a list are refused (FV0424).

v-model on form controls ​

v-model writes a control's initial state as Vue's server does: a text input's value, a checkbox's checked, and the checked of a radio button or the selected of an <option> whose value is loosely equal to the model. The server compares a string model with a string value, and a model that may be absent with a literal value, an absent model written as String() writes it (undefined, or null for T | null): value="undefined" is checked while the model is absent. An <option> with no value is compared with null, which is what Vue's server compiler gives it: the option is selected while the model is "null", or null. Give each option a value to compare it with the model. A number or boolean model on a radio button or a <select> is refused (FV0413), and so is v-model on an <input> whose type is bound, where Vue's server chooses as it renders between checked and value (FV0426): write the type as a literal.

HTML comments ​

A template's HTML comments (<!-- note -->) render as the client build treats them. @vitejs/plugin-vue leaves them out of a production build and keeps them on the dev server, and its template.compilerOptions.comments sets either for both. The compiler decides it from ferrovue.config.json alone: comments when it is set, and otherwise whether isProduction is false. With neither key, the comments are left out, as in the production build the server ships with.

@vitejs/plugin-vueferrovue.config.json
vite buildneither key (comments left out)
the dev server"isProduction": false or "comments": true
template: { compilerOptions: { comments: true } }"comments": true

A comment left out changes more than the text: a component whose root element has a comment beside it has a single root in production, which a parent's class and other attributes fall through onto. A comment kept is written as Vue writes it, and a comment beside the root makes the root a fragment, written between <!--[--> and <!--]-->; attributes a parent passes still reach the one element in it, as in Vue's development build. A comment between v-if and v-else belongs to the branch after it.

The Vite plugin reads plugin-vue's choice. The dev server writes the modules with the comments its client keeps, and a build fails when ferrovue.config.json decides otherwise than plugin-vue, so that vite build and the ferrovue command write the same modules; run pnpm ferrovue again before committing modules the dev server wrote. attachSsrRender from ferrovue/testing/ssr takes { comments } for the same choice, and the conformance suite of ferrovue/testing passes the configuration's.

Whitespace ​

Vue condenses each run of whitespace in a template's text to one space and keeps the space where text meets its element's tags, so <button>\n remove\n</button> renders <button> remove </button>. A formatter that moves long text onto lines of its own adds those spaces to the page, in textContent and in what devtools shows. "whitespace": "trim-edges" in ferrovue.config.json trims them. The Vite plugin reads the key and gives plugin-vue trimEdges from ferrovue/whitespace, so the client compiles the same way, in vite build, on the dev server and in Vitest:

ts
// vite.config.ts
import vue from "@vitejs/plugin-vue";
import ferrovue from "ferrovue/vite";

export default {
  plugins: [vue(), ferrovue()],
};

A build without ferrovue's Vite plugin, such as a Vitest config with plugin-vue alone, adds the transform itself: vue({ template: { compilerOptions: { nodeTransforms: [trimEdges] } } }).

Each place a formatter writes a line break, and what the mode renders there:

The formatter writes"trim-edges" rendersWhy
<p>\n Some text\n</p><p>Some text</p>a block element's edges: a formatter adds and removes whitespace there freely
<button>\n Remove\n</button><button>Remove</button>an inline-block element's edges, the same
<p>ago<span>\n by\n</span>Ada</p><p>ago<span> by </span>Ada</p>an inline element's edges: the line break stands for the space typed there
<p>\n <span>by</span>\n <a>Ada</a>\n</p><p><span>by</span> <a>Ada</a></p>between two inline elements, a line break reads as a space
<div>\n <div>a</div>\n <div>b</div>\n</div><div><div>a</div><div>b</div></div>between block elements, no space shows, and Vue drops it
<span>by</span>\n<a>Ada</a> at the template's root<span>by</span> <a>Ada</a>the root's children render in place, as an element's do
<span>by</span>\n<!-- note -->\n<a>Ada</a><span>by</span> <a>Ada</a>, or <span>by</span> <!-- note --><a>Ada</a> with commentsthe line breaks around a comment read as one space
<b>a</b>\n<i v-if="no">x</i>\n<a>z</a><b>a</b> <!----> <a>z</a>the space is decided from the source, so it stays beside a v-if that renders nothing; the browser collapses the two
<a>one</a\n><a>two</a><a>one</a><a>two</a>hugged tags: no space is meant, as for elements a class makes inline-block
<pre>, <textarea>, v-pre, a static style with a preserving white-space, or a class of preserveWhitespaceas Vue condenses itthe text is shown as written, so it is left with everything inside it

The paragraphs below give each rule in full.

The mode trims the whitespace at the start of an element's first child and at the end of its last child, when those children are text written in the template and that whitespace holds a line break, as the whitespace a formatter adds does. A space typed on the same line as the tag stays. It applies to the content of block and inline-block elements, of components and of <template v-slot>. An inline element, such as <span>, <a> or <label>, keeps Vue's one space at its edges: a formatter such as Prettier or oxfmt treats the whitespace there as part of the text, and when it breaks the element's content across lines, the line break it writes stands for that space. Inline-block are <button>, <select>, <meter>, <progress>, <object>, <video> and <audio>, as formatters list them, and a formatter adds and removes whitespace at their edges freely:

Template"condense" (the default)"trim-edges"
<button>\n remove\n</button><button> remove </button><button>remove</button>
<p>\n Hello {{ name }}\n</p><p> Hello Ada</p><p>Hello Ada</p>
<p>\n <span>x</span>\n tail\n</p><p><span>x</span> tail </p><p><span>x</span> tail</p>
<MyButton>\n remove\n</MyButton>remove in the slotremove in the slot
<span> by </span><span> by </span>the same
<p>\n text </p><p> text </p><p>text </p>
<p>ago<span>\n by\n</span>Ada</p><p>ago<span> by </span>Ada</p>the same
<p>\n <span>by</span>\n <a>Ada</a>\n</p><p><span>by</span><a>Ada</a></p><p><span>by</span> <a>Ada</a></p>
<p><b>a</b> <i>b</i></p><p><b>a</b> <i>b</i></p>the same

Vue drops the whitespace between two elements when it holds a line break. A formatter such as Prettier reads a line break between two inline elements as a space, as HTML does, and moves <span>by</span> <a> onto two lines when the line grows long. So the mode renders a line break between two inline elements as one space. Inline are the HTML elements other than the block, list and table elements, <br> and the elements of the page's head, and components other than <Teleport>, <KeepAlive>, <Suspense>, <Transition>, <TransitionGroup> and <ClientOnly>, which render no element of their own in place, and <slot> and <template> with v-if, v-else-if, v-else or v-for, whose content renders in place. Vue removes the whitespace between the branches of a v-if, so the space counts after the last branch. The rule holds at the template's root, and across a comment, with the space before the comment where comments render. Vue's spacing holds between the <template v-slot>s of a component and inside <svg> and <math>. Between elements a stylesheet makes block, flex or grid items, the space does not show.

The space is decided when the template compiles, from its source, so it stays when a v-if or v-for beside it renders nothing. With only the first of two <template v-if>s on lines of their own rendering, the text ends in two spaces. The browser collapses them, so nothing shows, and they are in the server's HTML and in textContent, as in HTML written by hand. Where the branch renders, the space is the one it needs.

Everything else stays as Vue condenses it:

  • whitespace at an edge with no line break in it, such as the spaces of <span> by </span>, and the edges of an inline element;
  • the space typed between two elements, and between text and an interpolation;
  • a value an interpolation renders, such as a prop that starts with a space;
  • the content of <template v-if>, <template v-for> and of a <slot>'s fallback, which render among the text around them;
  • <pre>, <textarea>, an element with v-pre, and an element whose static style sets white-space to pre, pre-wrap, pre-line or break-spaces, with everything inside them. An element styled that way from a stylesheet is named by its class in preserveWhitespace;
  • an element whose static class, or whose :class expression, names a class listed in "preserveWhitespace": { "classes": [...] }, with everything inside it.

A stylesheet that gives a class a white-space of pre, pre-wrap, pre-line or break-spaces, such as Tailwind's whitespace-pre-line, shows the line breaks the mode would trim. List those classes in ferrovue.config.json, and the Vite plugin hands them to trimEdges:

jsonc
// ferrovue.config.json
{ "whitespace": "trim-edges", "preserveWhitespace": { "classes": ["whitespace-pre-line", "whitespace-pre-wrap"] } }

A build without ferrovue's Vite plugin gives plugin-vue trimEdges({ classes }) with the same list.

A class counts by its exact name, variants included, so md:whitespace-pre is a class of its own. A :class expression counts when a string or object key in it names a listed class, whether or not it applies at render, so :class="{ 'whitespace-pre-line': open }" keeps the text in both states. A class the element gets from a prop, or from a parent through its attributes, is not seen: write the class in the template, or the white-space in the style attribute. A class named as Tailwind names its white-space utilities, such as whitespace-pre-line, and left out of the list warns (FV0428) where the mode renders the element's contents otherwise than Vue does: a line break it trims at an edge or spaces between inline tags.

The mode reads tag names and sees no stylesheet, for white-space as for display. An element a class makes block, flex or grid, such as <span class="block">, still counts as inline, and a line break between it and its neighbour renders as a space. CSS discards whitespace next to a block box and between flex and grid items, so that space does not show. Between elements a class makes inline-block, written on lines of their own with no space meant between them, it shows as a gap: hug their tags, </a\n><a>, as a formatter writes them where no space is meant. Name those classes in "inlineBlockClasses", and the compiler warns (FV0427) at each line break it renders as a space beside such an element.

A space between such elements is sometimes meant, such as the one between a title link and its inline-block label. Written on one line, </a> <span class="flair">, it gives no warning, but a formatter moves the <span> to a line of its own once the <a> breaks over several lines. Mark that gap as meant with a comment between the two elements, on the line before the second:

vue
<a
  class="title"
  :href="title.href"
  >{{ title.text }}</a
>
<!-- ferrovue-ignore FV0427 -->
<span class="flair">{{ flair }}</span>

The comment names the warnings it silences, and changes nothing the page renders: the space is read past comments, and with "comments": true Vue renders the comment as it renders any other. A ferrovue-ignore comment that names no warning, names a code it cannot silence, or stands where FV0427 does not fire, as once the tags are hugged, warns of its own (FV0430), so a stale one shows.

A &nbsp; is text: it stays at an edge. So does whitespace written as a character reference, such as &#10;.

A plugin-vue given trimEdges by hand keeps it, and the Vite plugin checks that it agrees with ferrovue.config.json, as it does for comments: a build fails when one trims and the other does not, or when the two leave other classes, and the dev server warns. It finds trimEdges in template.compilerOptions.nodeTransforms from any copy of the package. attachSsrRender from ferrovue/testing/ssr takes { whitespace, preserveClasses } for the same choice, and the conformance suite of ferrovue/testing passes the configuration's.

<component :is> ​

<component :is> compiles when every value it can take is known when compiling. Each of these is a closed set:

  • an imported component, :is="Card", or an async one from defineAsyncComponent;
  • an HTML element's name, is="h2" or :is="'h2'";
  • a prop typed as a union of string literals, as: "h1" | "h2" (or an alias or enum of them), or as one string literal, as: "h1", required or with a default, declared in place, by an interface or by a type imported from a .ts file, or a defineModel of such a type, read by its local (:is="tag" of const tag = defineModel<"h1" | "h2">({ required: true })) or by its prop (:is="modelValue");
  • an object of imported components or element names, declared in <script setup> (const ICONS = { star: Star, moon: Moon }) or exported as a constant from a .ts file that imports them, read by such a prop or a literal key: ICONS[name], ICONS.star;
  • a ?: or a computed that chooses among any of these.

The choices become a match on the prop, or an if on the condition, and each arm renders its choice exactly as the static child or element would: the same props, fallthrough attributes, slots and scope ids. Choices that render the same component share an arm. A choice of elements alone writes the tag from the match:

rust
// <component :is="ICONS[name]" :label="label" />, where ICONS = { star: Star, moon: Moon }
// and name: "star" | "moon":
match props.name {
    IconName::Star => {
        super::star::render(out, &super::star::Props { label: Cow::Borrowed(&props.label) });
    }
    IconName::Moon => {
        super::moon::render(out, &super::moon::Props { label: Cow::Borrowed(&props.label) });
    }
}

// <component :is="as" class="heading"><slot /></component>, where as: "h1" | "h2":
let fv_tag = match props.r#as { HeadingAs::H1 => "h1", HeadingAs::H2 => "h2" };
out.push('<');
out.push_str(fv_tag);
out.push_str(" class=\"heading\">");
fv::render::slot_into(out, fv_slots.default, None);
out.push_str("</");
out.push_str(fv_tag);
out.push('>');

A union of string literals is an enum, so the match names each of its variants and holds no catch-all arm. Inside <KeepAlive> and <Transition> the choice renders as it does elsewhere, as on Vue's server.

Vue's server renders an element <component :is> chooses from virtual nodes, by rules that differ from a template's in a few places, and ferrovue follows them: a v-if that renders nothing writes <!--v-if-->, an attribute with an empty value is written bare (alt), a static class written just before :class gives its names first (class="a x"), and slot content a parent gives a <slot> inside the element is rendered the same way, through every component that passes it on. Where virtual nodes would differ in ways the compiler cannot reproduce, it refuses: a <slot> with fallback content inside such an element (Vue decides whether to show the fallback by rules of its own), one <slot> rendered both inside and outside one, v-show and v-model on a <select> inside one, a static class with other attributes between it and a later :class (Vue writes it where the static one stands), and v-html or v-text on <component :is> itself, which Vue's server leaves empty.

html and island ​

html takes the same parameters as render, minus the buffer, and returns an Html: the render applied to its arguments, run when it is written. Write it with Html::render_to or Html::into_string, or, with the maud feature, splice it into a maud::html! template, where it is written straight into maud's buffer:

rust
// With ferrovue's `maud` feature.
let page = maud::html! {
    (maud::DOCTYPE)
    body { (greeting::html(&props)) }
};

With the axum or actix-web feature, an Html is also a response of its own; web_frameworks shows how.

island exists only for a component whose render needs nothing but its props, because the client rebuilds the component from the props in data-props and nothing else. It wraps the markup as

html
<div data-island="Greeting" data-props='{"name":"Ada","unread":3}'>…</div>

with the props serialised by serde_json (a non-finite f64 as JavaScript writes it, NaN or Infinity, where serde_json would write null) and attribute-escaped. A component that takes slots, the route, stores, translations, teleports or the page head has no island; the page's own Vue app hydrates it instead. See islands_and_hydration.

html and island borrow the props, so the Html lives no longer than they do. Where island exists, into_html and into_island take the props by value instead, and the Html holds them: it borrows only what the props borrow (nothing, for props of 'static strings or Cows holding their own), so a function that builds the props can return the page, as a web handler does. Both render exactly as their borrowing forms.

rust
fn greet(name: String) -> ferrovue::html::Html<'static, greeting::Props<'static>> {
    greeting::into_html(greeting::Props::new(name, 0))
}

Names ​

In the .vue fileIn Rust
DataList.vuemodule data_list, NAME "DataList"
the page books/[id].vuemodule books_id, NAME "BooksId": the PascalCase of its path in the pages folder
a module name that is a Rust keyword, typemodule r#type, in type.rs; self, super and crate take a _: self_
prop showHeadfield show_head, with #[serde(rename = "showHead")] so the island's JSON uses Vue's name
prop type (a Rust keyword)field r#type
prop price$, a field $meta of an interfacefield price, renamed price$; field meta, renamed $meta: a name holding $ keeps its ASCII letters and digits, and takes _2, _3, … after a name another field holds ($tag beside tag is tag_2)
const $label = computed(…) in <script setup>the local s_label, or s_label_2 beside a binding label
v-model / defineModel()field model_value, renamed modelValue
<slot name="row">Slots::row, RowSlotProps, RowSlot
<RouterView>Slots::router_view
a store with id cartstores::CartState, Stores::cart
the twin StarRatingtwins::StarRatingProps, StarRatingSlots, StarRatingRender
provide(ThemeKey, …), provide("tone", …)Provides::theme_key, Provides::tone

The locals of a render ​

The locals a render declares are named after what they hold, so its Rust reads like the component. They belong to the bodies of functions, outside the contract:

  • a local that holds a JavaScript name is fv_ and that name in snake case: let sum is fv_sum, for (const r of rows) binds fv_r, rowCount is fv_row_count, v-for="item in items" binds fv_item, and the value a v-if="note" finds present is fv_note. A name a Rust identifier cannot spell, with a $ or an accented letter, keeps its ASCII letters and digits;
  • a value the compiler makes for itself is named by its role: fv_returned for what a return inside a loop gives, fv_next_a for the next value of a when a loop swaps it, fv_index, fv_entry, fv_tag for the tag <component :is> picks, and fv_slot_props and fv_slot_id in slot content;
  • fv_ keeps every local apart from props, out, the fv alias of this crate, the s_ names of <script setup> bindings, helper functions and Rust keywords;
  • a name the function holds already takes _2, _3, … in the order the locals first appear in it: a function inlined twice binds fv_word, then fv_word_2. The count is per function, so an edit to one component leaves the names of every other as they were, and an edit to one part of a template renames only a local whose name it takes first.
rust
// const total = computed(() => { let sum = 0; for (const r of props.rows) sum += r.n; return sum; });
let s_total = { let mut fv_sum: f64 = 0.0f64; for fv_r in props.rows.iter() { fv_sum += fv_r.n as f64; } fv_sum };

A list of strings a local holds keeps each string borrowed where it comes from the props, a string literal or a <script setup> binding, which all live as long as the render, so building it copies no text. So does a string reached through an arrow function's object parameter (posts.flatMap((p) => p.tags)), through ?. or ?? on an optional list, or through a const inside a computed's body that holds such strings: the list copies each Cow of the const, and a copy of a borrowed Cow borrows the same string. The string .find() or .at() picks is kept the same way. A string the expression makes or is handed as its own value, such as the pieces of w.split("-") in words.flatMap((w) => w.split("-")), is copied into the list, since that value is gone once the expression ends.

rust
// const long = computed(() => props.words.filter((w) => w.length > 2));
let s_long = props.words.iter().map(|v| Cow::<str>::Borrowed(&**v)).filter(|fv_w| fv_w.len() > 2).collect::<Vec<_>>();
// const first = computed(() => { const all = props.words.filter((w) => w.length > 2); return all.slice(0, 1); });
let s_first = { let fv_all = props.words.iter().map(|v| Cow::<str>::Borrowed(&**v)).filter(|fv_w| fv_w.len() > 2).collect::<Vec<_>>(); fv_all.iter().cloned().take(1).collect::<Vec<_>>() };

A render tests only what can go either way. It writes no test of the empty string for a value a v-if or || undefined has found present, or for a union with no "" member, and it writes an attribute bound to test ? "literal" : undefined as the literal inside if test. A v-for index and a .length are compared and added as i64: a count of what fits in memory is far below 2⁵³, where the i64 and JavaScript's number are the same.

A ref seeded with a number, a boolean, a string literal, null or undefined has no local. Setup may write a ref only where the server never runs the write, as in onMounted or an event handler, so the server renders the seed. The render reads the value in its place and keeps only the branch it takes: const fresh = ref(0) makes v-if="fresh > 0" an <!---->.

How a render writes text ​

A render writes the markup it knows at compile time in as few writes as it can, and reserves the room the page needs before the first one:

  • the text between two values is one out.push_str;
  • text of at most 48 bytes next to a v-if, a ?: or a v-show whose every branch starts or ends with text goes into each branch, so the branch and the markup beside it are one write. Text before the branches moves only when their tests can neither return nor write;
  • branches that only write text are one out.push_str of the text their test picks, and a test the compiler knows the result of leaves the text of the branch it takes.
  • a value built by formatting, such as a template literal or a string + in a function or a computed, is written into the page as it is formatted, escaped on the way, with write! through a hidden fv::core::escaping(out), and a JSON.stringify of a list is written item by item. A fallthrough attribute given a template literal holds it as a hidden value that formats it as it is written. A bare attribute tests its value for being empty from its parts, and a .join() from its items; a CSS variable whose text may be empty still builds the value to test it;
  • a string a loop builds by prepending, out = ch + out, grows in place.

What each branch writes, and the order of the writes, stay those of Vue's renderToString.

render_json, for your own conformance tests ​

mod.rs has, under #[cfg(test)], a render_json(component, json) that renders a component by name from a fixture: a JSON object of props plus optional $slots (each slot's content as HTML), $route (the location), $stores (Pinia state by store id) and $locale. Paired with ferrovue/testing on the npm side, which renders the same fixtures with Vue, it lets a project hold its own components to Vue's output byte for byte, as ferrovue's own suite does: the testing page sets up both halves in two calls. That function is why the props structs derive serde::Deserialize under cfg(test), and why the project needs serde_json as a dev-dependency.