Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/API/v3/frameworks/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ deprecated: false

V3 apps run **without a build step**. Source files are uploaded to the media library and fetched at runtime via `Fliplet.Media.getContents`. Dependencies are resolved through `Fliplet.require.lazy`, not `import`. This changes which framework features work and which quietly fail.

Fetch the per-framework doc (`v3-framework-vue`, `v3-framework-react`, etc.) before scaffolding. This doc is for picking.
Read the [Vue](vue), [React](react), [Alpine](alpine) or [vanilla JS](vanilla) guide before scaffolding with your chosen framework. This page helps you choose.

## The runtime constraints (apply to every framework)

Expand Down Expand Up @@ -39,11 +39,11 @@ Default order when the user hasn't expressed a preference:
1. **One screen, no forms**: vanilla JS
2. **Multi-screen, reactive state**: Vue 3 — best balance of no-build ergonomics and features
3. **Form-heavy single-page CRUD**: Alpine.js
4. **User explicitly asked for React**: React, via `htm` or `React.createElement` (see `v3-framework-react`)
4. **User explicitly asked for React**: React, via `htm` or `React.createElement` (see the [React guide](react))

## What to fetch next

After picking, call `get_fliplet_docs('v3-framework-<name>')` for the specific constraints. Every per-framework doc covers: loading the framework, features that need a build step (and what to do instead), wiring to `Fliplet.Router`, binding `Fliplet.Media.authenticate`, common errors, and DO/DON'T.
After picking, fetch the matching guide with `fetch_fliplet_doc({ path: 'API/v3/frameworks/vue.md' })` (or the `react`, `alpine` or `vanilla` path) for its setup and constraints. Every per-framework doc covers: loading the framework, features that need a build step (and what to do instead), wiring to `Fliplet.Router`, binding `Fliplet.Media.authenticate`, common errors, and DO/DON'T.

## Related

Expand Down
112 changes: 94 additions & 18 deletions docs/API/v3/frameworks/vue.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,54 +9,130 @@ deprecated: false

# V3 Vue apps

Vue 3 is the best-supported multi-screen framework in V3 because a runtime-compiler build exists — meaning `template` strings compile in the browser without a toolchain. The traps below come from using the wrong Vue build, or reaching for features that assume Vite/webpack.
V3 Vue apps use the browser runtime compiler and Fliplet’s media helpers to load Vue single-file components (SFCs) without a build step. Keep `App.js` as a JavaScript component export and each screen as ordinary `<template>`, `<script>` and `<style>` blocks.

## Loading the framework

Add `vue` via `add_dependencies` with `lazy: true`, then:
Register Vue and Vue Router as lazy app resources with verified CDN URLs through `add_dependencies`. They are third-party libraries, so an empty dependency URL does not select a Fliplet package. For example:

```json
[
{ "name": "vue", "latest": "https://unpkg.com/vue@3/dist/vue.global.prod.js", "lazy": true },
{ "name": "vue-router", "latest": "https://unpkg.com/vue-router@4/dist/vue-router.global.prod.js", "lazy": true }
]
```

Run the following inside your boot script's `Fliplet().then(async function() { ... })` callback, before creating the router or mounting the app:

```js
await Fliplet.require.lazy('vue');
await Fliplet.require.lazy.chain('vue');
await Fliplet.require.lazy.chain('vue-router');
const Vue = window.Vue;
const VueRouter = window.VueRouter;
```

`Fliplet.require.lazy(name)` resolves once the UMD bundle has executed; the module itself lands on `window` (`window.Vue`, `window.VueRouter`). Read it off `window` after the `await` — assigning the awaited value directly gives you the URL string, not the module.
Load Vue before its companion libraries; they read `window.Vue` when executing. The lazy loader resolves to the resource URL, so read the module from its browser global after awaiting it.

Use the runtime-compiler build (`vue.global.js` or `vue.global.prod.js`). It compiles the extracted template in the browser. The runtime-only build cannot compile these templates.

## Loading Vue screen files

**Pick the runtime-compiler build (usually `vue.global.js`), not the runtime-only build.** The runtime-only build (`vue.runtime.global.js`) does not include the template compiler — any component that uses `template: '...'` strings will fail to render. The runtime-only build only works if every component is authored as a pre-compiled render function, which is impractical without a bundler.
The boot script loads a screen's source through `Fliplet.Router.resolveRoute(path)`, which already uses authenticated media loading. `Fliplet.Media.parseSFC(source)` extracts `{ template, script, style }` strings; `Fliplet.Media.evalModule(parts.script)` returns the component's default export. Assign the template to that component and insert its CSS. These Fliplet helpers are preloaded; this path needs no `vue3-sfc-loader` dependency.

For Vue Router, the separate dependency:
Upload each screen as a `.vue` file and register it in the [route manifest](../routing). A simple screen looks like this:

{% raw %}
```html
<template>
<section class="welcome-screen"><h1>{{ title }}</h1></section>
</template>
<script>
export default {
data: function() { return { title: 'Welcome' }; }
};
</script>
<style>
.welcome-screen { padding: 24px; }
</style>
```
{% endraw %}

Use this helper in the boot script before building the routes below:

```js
await Fliplet.require.lazy('vue-router');
const VueRouter = window.VueRouter;
function loadVueScreen(source) {
const parts = Fliplet.Media.parseSFC(source);
const screen = Fliplet.Media.evalModule(parts.script);
screen.template = parts.template;
if (parts.style) {
const style = document.createElement('style');
style.textContent = parts.style;
document.head.appendChild(style);
}
return screen;
}
```

`parseSFC` extracts blocks; it does not compile advanced Vue syntax or preprocess CSS. Use `export default { ... }` in the screen's script, without a separate `template` property. Styles are global: prefix selectors with the screen's root class. Keep `App.js` as JavaScript only and load its exported component with `Fliplet.Media.getContentsAsModule(appFileId)`; pass that returned object directly to `Vue.createApp(App)`.

## Features that need a build step

| Feature | Why it fails | Do this instead |
|---|---|---|
| `.vue` single-file components | There is no loader resolving them at runtime | Use plain component objects with `template:` strings, **or** add `vue3-sfc-loader` as a dependency if the app genuinely needs SFCs. Pick one approach per app and stay consistent. |
| `<script setup>` | Requires SFC compilation | Use the Options API or explicit `setup()` function on component objects. |
| `<style scoped>` | Requires SFC compilation | Scope manually by wrapping each component's CSS in a root class selector. |
| `<style scoped>` or CSS preprocessing | Extracted styles are inserted as plain global CSS | Use plain CSS with a screen-specific root class; `scoped` and `lang` attributes do not transform it. |
| Bare ESM imports (`import Vue from 'vue'`) | No bundler resolves the specifier | Use `Fliplet.require.lazy('vue')`. |
| TypeScript (`.ts`, `.tsx`) | No transpiler | Plain JavaScript. |

## Wiring to Fliplet.Router

Full contract is in [V3 routing](../routing). Vue-specific note: the history backend is platform-conditional — path history with the base path on web, hash history on native (Cordova `file://` blocks `pushState` path changes):
After loading Vue, Vue Router and the helper above, build routes from the [V3 route manifest](../routing). This example requires a registered home screen at `/`. Use path history with the base path on web and hash history on native, where Cordova `file://` blocks path changes:

```js
const manifest = Fliplet.Router.getRouteManifest();
const routes = manifest.routes.map(function(entry) {
const record = {
path: entry.path,
meta: { manifestEntry: entry },
component: function() {
return Promise.resolve(loadVueScreen(record.meta.screenContent));
}
};
return record;
});
routes.push({ path: '/:pathMatch(.*)*', component: { template: '<p>Page not found.</p>' } });

const router = VueRouter.createRouter({
history: Fliplet.Router.isNative()
? VueRouter.createWebHashHistory() // native — hash only
: VueRouter.createWebHistory(Fliplet.Router.getBasePath()), // web — path + basename
routes: [...]
? VueRouter.createWebHashHistory()
: VueRouter.createWebHistory(Fliplet.Router.getBasePath()),
routes: routes
});

router.beforeEach(async function(to) {
const matched = to.matched.find(function(record) { return record.meta.manifestEntry; });
if (!matched) return true; // Unknown URLs use only the local not-found view.
const result = await Fliplet.Router.resolveRoute(matched.meta.manifestEntry);
if (!result.allowed) {
const target = result.redirectTo;
if (target && target !== to.path && manifest.routes.some(function(entry) { return entry.path === target; })) {
return target;
}
throw new Error('This page is unavailable.');
}
matched.meta.screenContent = result.content;
return true;
});
router.onError(function() {
document.getElementById('app').textContent = 'This page could not be loaded. Please reload to try again.';
});
```

Resolve the matched manifest entry before evaluating source. A navigation guard rechecks access on cached revisits and parameter-only changes; a lazy component loader alone does not. Pass the manifest entry (such as `/items/:id`), not the concrete navigation path (`/items/42`). Denials redirect only to a registered, different route; transient errors remain errors. Preserve equivalent existing guards and error handling.

Unconditional `createWebHistory()` throws a `file:` `SecurityError` on native; unconditional `createWebHashHistory()` produces ugly `#/route` URLs on web. The boot-HTML lint flags both unless you branch on `Fliplet.Router.isNative()` (`unguarded-web-history` / `create-web-hash-history`).

Build routes from `Fliplet.Router.getRouteManifest()` — do not hardcode. In each route's resolver, call `Fliplet.Router.resolveRoute(path)`. The `content` field in its result IS the screen's source — already fetched for you via `Fliplet.Media.getContents`. Return it from your loader and render it in your component; don't fetch the file again.
Mount your root component with `Vue.createApp(App).use(router).mount('#app')` after loading `App.js`, inside the [Fliplet initialization callback](../app-bootstrap#3-init-sequence). Its template should contain `<router-view></router-view>` and the boot HTML must contain `<div id="app"></div>`. Open `/` to confirm the registered screen renders. Reuse `result.content`; do not fetch the screen again.

## Binding Fliplet.Media.authenticate

Expand Down Expand Up @@ -125,8 +201,8 @@ Vue batches DOM updates. Use `await this.$nextTick()` (Options API) or `await Vu
| Symptom in `get_preview_logs('errors')` | Cause | Fix |
|---|---|---|
| `[Vue warn]: Component is missing template or render function` | Runtime-only Vue build loaded; `template:` strings silently ignored | Switch to the runtime-compiler build (`vue.global.js`) |
| `Uncaught SyntaxError: Unexpected token '<'` inside a component file | `.vue` SFC uploaded without `vue3-sfc-loader` | Either convert the component to a plain object with `template:` string, or add `vue3-sfc-loader` |
| Blank screen, no errors | Component returned from `Fliplet.Media.getContents` wasn't registered before router resolved | Register the component inside the route resolver, not at module load |
| `Uncaught SyntaxError: Unexpected token '<'` inside a component file | SFC or HTML content was evaluated as JavaScript | For a screen, extract its script with `parseSFC` before `evalModule`; keep `App.js` free of HTML and style blocks. |
| Blank route | The resolver did not return a component with its extracted template, or no route matched | Return `loadVueScreen(result.content)` and confirm the manifest contains the opened route. |

## DO / DON'T

Expand All @@ -136,7 +212,7 @@ Vue batches DOM updates. Use `await this.$nextTick()` (Options API) or `await Vu
- DO bind authenticated media URLs into reactive `data()` fields.
- DON'T use `createWebHistory()` unconditionally — it throws a `file:` `SecurityError` on native. Gate it on `Fliplet.Router.isNative()`.
- DON'T use `createWebHashHistory()` on web — hash mode is only for native.
- DON'T author `.vue` SFCs without `vue3-sfc-loader` loaded.
- DO load screen SFCs through `parseSFC` and `evalModule`, then assign the extracted template.
- DON'T `import` anything — use `Fliplet.require.lazy`.

## Related
Expand Down
2 changes: 2 additions & 0 deletions docs/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ cd docs
npm run test:unit # stdlib node:test; covers both bin/ scripts
```

The Vue routing recipe test executes the published example with Vue and Vue Router. To also exercise the paired API runtime instead of the portable fixture, run `FLIPLET_API_ROOT=/path/to/fliplet-api node --test bin/__tests__/vue-routing-example.test.mjs` from `docs/`.

## Primitives published under `.well-known/`

These are the AI-consumption surfaces. Publish URLs on `developers.fliplet.com`:
Expand Down
86 changes: 86 additions & 0 deletions docs/bin/__tests__/vue-routing-example.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Execute the published recipe, not a separately maintained implementation.
import { it } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { JSDOM } from 'jsdom';

const require = createRequire(import.meta.url);
const guide = readFileSync(new URL('../../API/v3/frameworks/vue.md', import.meta.url), 'utf8');
const helper = guide.match(/```js\n(function loadVueScreen[\s\S]*?)```/)[1];
const wiring = guide.split('## Wiring to Fliplet.Router')[1].match(/```js\n([\s\S]*?)```/)[1];
const vue = readFileSync(require.resolve('vue/dist/vue.global.prod.js'), 'utf8');
const routerSource = readFileSync(require.resolve('vue-router/dist/vue-router.global.prod.js'), 'utf8');

async function fixture() {
const dom = new JSDOM('<div id="app"></div>', { url: 'https://example.test/preview/', runScripts: 'outside-only' });
const w = dom.window;
w.eval(vue); w.eval(routerSource);
const entries = [{ path: '/', fileId: 1, public: true }, { path: '/items/:id', fileId: 2 }, { path: '/login', fileId: 3, public: true }];
const state = { denied: false, failure: false, calls: [], evaluations: 0 };
const source = id => `<template><p>${id === 2 ? 'Item {{ $route.params.id }}' : 'Screen ' + id}</p></template><script>export default {};</script><style>.example { padding: 1px; }</style>`;
w.Fliplet = {
Hooks: { on() {} }, // Media registers unrelated login/logout cache hooks.
Env: { get: key => ({ appSettings: { v3: { routes: entries, authRedirect: '/login' } }, basePath: '/preview/', platform: 'web' })[key] },
User: { getCachedSession: async () => state.denied ? null : {} },
Media: {
parseSFC: text => Object.fromEntries(['template', 'script', 'style'].map(tag => [tag, text.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`))?.[1] || ''])),
evalModule: text => w.Function(text.replace('export default', 'return'))()
}
};
if (process.env.FLIPLET_API_ROOT) {
for (const [folder, file] of [['fliplet-media', 'media'], ['fliplet-router', 'router']]) {
w.eval(readFileSync(`${process.env.FLIPLET_API_ROOT}/public/assets/${folder}/1.0/${file}.js`, 'utf8'));
}
} else {
w.Fliplet.Router = {
getRouteManifest: () => ({ routes: entries }), isNative: () => false, getBasePath: () => '/preview/',
resolveRoute: async entry => {
if (!entry.public && state.denied) return { allowed: false, redirectTo: '/login' };
return { allowed: true, content: await w.Fliplet.Media.getContents(entry.fileId) };
}
};
}
w.Fliplet.Media.getContents = async id => { if (state.failure) throw new Error('Network unavailable'); return source(id); };
const resolve = w.Fliplet.Router.resolveRoute;
w.Fliplet.Router.resolveRoute = entry => { state.calls.push(entry); return resolve(entry); };
const evaluate = w.Fliplet.Media.evalModule;
w.Fliplet.Media.evalModule = text => { state.evaluations++; return evaluate(text); };
w.eval(helper + wiring + '\nwindow.router = router; window.app = Vue.createApp({ template: "<router-view />" }).use(router).mount("#app");');
await w.router.isReady(); await w.Vue.nextTick();
return { dom, w, state };
}

it('loads extracted SFCs and resolves manifest identity for dynamic navigation', async () => {
const { dom, w, state } = await fixture();
try {
assert.match(w.document.body.textContent, /Screen 1/);
await w.router.push('/items/42'); await w.Vue.nextTick();
assert.equal(state.calls.at(-1).path, '/items/:id');
assert.match(w.document.body.textContent, /Item 42/);
const count = state.calls.length;
await w.router.push('/items/43'); await w.Vue.nextTick();
assert.equal(state.calls.length, count + 1);
assert.match(w.document.body.textContent, /Item 43/);
await w.router.push('/unknown'); await w.Vue.nextTick();
assert.match(w.document.body.textContent, /Page not found/);
} finally { dom.window.close(); }
});

it('denies before evaluation and rechecks cached routes; network errors do not become authorization', async () => {
const { dom, w, state } = await fixture();
try {
state.denied = true;
await w.router.push('/items/42'); await w.Vue.nextTick();
assert.equal(w.router.currentRoute.value.path, '/login');
assert.equal(state.evaluations, 2); // Home and login only.
state.denied = false;
await w.router.push('/items/42'); await w.router.push('/');
state.denied = true;
await w.router.push('/items/43');
assert.equal(w.router.currentRoute.value.path, '/login');
state.denied = false; state.failure = true;
await assert.rejects(w.router.push('/items/44'), /Network unavailable/);
assert.match(w.document.body.textContent, /could not be loaded/);
} finally { dom.window.close(); }
});
26 changes: 25 additions & 1 deletion docs/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"dompurify": "3.4.16",
"jsdom": "26.1.0",
"marked": "18.1.0",
"vue": "3.5.43"
"vue": "3.5.43",
"vue-router": "4.6.3"
}
}
Loading