@protobase/cli 0.96.0 → 0.96.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,14 +6,18 @@ import { transform } from "lightningcss";
6
6
  //#region src/build/theme.ts
7
7
  /** The project's theme, at its root, and where a bundle's `public` folder has it: the app links it at `/protobase.theme.css`. */
8
8
  const themeFile = "protobase.theme.css";
9
+ /** The app's tokens, the CSS variables its components read, beside its stylesheet in @protobase/ui's src and dist alike. */
9
10
  const tokensFile = path.join(path.dirname(uiEntry), "tokens.css");
10
11
  /** The names of the tokens the installed @protobase/ui reads, such as `--primary` and `--radius`. */
11
12
  const themeTokens = async (file = tokensFile) => new Set([...(await readFile(file, "utf8")).matchAll(/(--[\w-]+)\s*:/g)].map(([, name]) => name));
12
- const isThemeSelector = (selector) => {
13
- if (selector.length !== 1) return false;
13
+ /** Which values a theme selector sets: the light ones on :root, the dark ones on [data-theme="dark"]; none for another. */
14
+ const themeScheme = (selector) => {
15
+ if (selector.length !== 1) return;
14
16
  const [part] = selector;
15
- return part.type === "pseudo-class" && part.kind === "root" || part.type === "attribute" && part.name === "data-theme" && part.operation?.value === "dark";
17
+ if (part.type === "pseudo-class" && part.kind === "root") return "light";
18
+ if (part.type === "attribute" && part.name === "data-theme" && part.operation?.value === "dark") return "dark";
16
19
  };
20
+ const isThemeSelector = (selector) => themeScheme(selector) !== void 0;
17
21
  const where = (file, line) => `${file}:${line + 1}`;
18
22
  const checkRule = (rule, file) => {
19
23
  if (rule.type === "font-face") return {
@@ -84,4 +88,4 @@ const buildTheme = async ({ projectDir, outFile }) => {
84
88
  return warnings;
85
89
  };
86
90
  //#endregion
87
- export { buildTheme, compileTheme, themeFile, themeTokens };
91
+ export { buildTheme, compileTheme, themeFile, themeScheme, themeTokens, tokensFile };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.96.0";
2
+ var version = "0.96.2";
3
3
  //#endregion
4
4
  export { version };
@@ -45,7 +45,25 @@ const chartShapes = (page, node, model) => {
45
45
  }
46
46
  }]];
47
47
  };
48
- /** The reads of a composed page: each block that lists records, with its filter and sort, and each chart's grouping. */
48
+ const callShapes = (page, node, models) => {
49
+ const calls = node.props.calls;
50
+ const model = models[calls.resource];
51
+ if (!model) return [];
52
+ const filter = configFilter(model, calls.filter);
53
+ const sort = configSort(model, threadSort(calls.time));
54
+ const params = [...calls.filter?.trim() ? [`filter=${calls.filter}`] : [], ...sort ? [`order_by=${sortText(sort)}`] : []];
55
+ const named = title(node);
56
+ return [{
57
+ resource: model.name,
58
+ request: `GET /${model.name}${params.length > 0 ? `?${params.join("&")}` : ""}`,
59
+ from: `page "${page.name}", <Thread${named ? ` "${named}"` : ""}> calls`,
60
+ query: {
61
+ ...filter && { filter },
62
+ ...sort && { sort }
63
+ }
64
+ }];
65
+ };
66
+ /** The reads of a composed page: each block that lists records, with its filter and sort, a thread's tool calls, and each chart's grouping. */
49
67
  const pageShapes = (page, models, views) => {
50
68
  const shapes = [];
51
69
  walkTree(page.tree, (node) => {
@@ -69,6 +87,7 @@ const pageShapes = (page, models, views) => {
69
87
  ...sort && { sort }
70
88
  }
71
89
  });
90
+ if (node.type === "Thread" && node.props.calls !== void 0) shapes.push(...callShapes(page, node, models));
72
91
  });
73
92
  return shapes;
74
93
  };
@@ -129,19 +129,23 @@ const recordChartShapes = (item, owner, models) => {
129
129
  }];
130
130
  };
131
131
  const threadShapes = (item, owner, models) => {
132
- const target = models[item.resource];
133
- const field = target?.fields[item.field];
134
- if (!target || !field || !target.fields[item.time]) return [];
135
- const sort = configSort(target, threadSort(item.time));
136
- return [{
137
- resource: target.name,
138
- request: request(target.name, `${field.name} = …`, sort),
139
- from: `thread "${item.title}" on the ${owner} record page`,
140
- query: {
141
- filter: compare(field),
142
- ...sort && { sort }
143
- }
144
- }];
132
+ const from = `thread "${item.title}" on the ${owner} record page`;
133
+ const latest = (source) => {
134
+ const target = models[source.resource];
135
+ const field = target?.fields[source.field];
136
+ if (!target || !field || !target.fields[source.time]) return [];
137
+ const sort = configSort(target, threadSort(source.time));
138
+ return [{
139
+ resource: target.name,
140
+ request: request(target.name, `${field.name} = …`, sort),
141
+ from,
142
+ query: {
143
+ filter: compare(field),
144
+ ...sort && { sort }
145
+ }
146
+ }];
147
+ };
148
+ return [...latest(item), ...item.calls ? latest(item.calls) : []];
145
149
  };
146
150
  const displayShapes = (model, view, models) => (view.list?.displays ?? []).flatMap((display) => {
147
151
  if (display.kind === "map") {
@@ -0,0 +1,55 @@
1
+ import { copySplashFile, removeTemplateSplash } from "./native-splash.js";
2
+ import path from "node:path";
3
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
+ //#region src/mobile/android-splash.ts
5
+ const res = "app/src/main/res";
6
+ const densities = [
7
+ "mdpi",
8
+ "hdpi",
9
+ "xhdpi",
10
+ "xxhdpi",
11
+ "xxxhdpi"
12
+ ];
13
+ /** The template's full-screen splash images, with Capacitor's logo, which nothing shows once its launch theme is Protobase's. */
14
+ const templateSplashImages = [`${res}/drawable/splash.png`, ...["port", "land"].flatMap((orientation) => densities.map((density) => `${res}/drawable-${orientation}-${density}/splash.png`))];
15
+ /**
16
+ * Protobase's splash for the splash screen plugin to show while the app reloads into a live update (its `layoutName`):
17
+ * the one the launch shows, drawn as the core-splashscreen library draws it.
18
+ */
19
+ const androidSplashFiles = [`${res}/drawable/protobase_splash.xml`, `${res}/layout/protobase_splash.xml`];
20
+ /** The splash screen plugin's `layoutName`, the layout in `androidSplashFiles`. */
21
+ const androidSplashLayout = "protobase_splash";
22
+ const stylesPath = `${res}/values/styles.xml`;
23
+ const templateLaunchTheme = ` <style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
24
+ <item name="android:background">@drawable/splash</item>
25
+ </style>`;
26
+ const launchTheme = ` <style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen.IconBackground">
27
+ <item name="windowSplashScreenBackground">@color/protobase_splash_background</item>
28
+ <item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher</item>
29
+ <item name="windowSplashScreenIconBackgroundColor">@color/ic_launcher_background</item>
30
+ </style>`;
31
+ /** The template's styles.xml with Protobase's launch theme; it fails on any other, which may set its own splash. */
32
+ const withLaunchTheme = (styles) => {
33
+ if (!styles.includes(templateLaunchTheme)) throw new Error("The generated android project's styles.xml is not Capacitor's template: its launch theme is not the one Protobase replaces");
34
+ return styles.replace(templateLaunchTheme, launchTheme);
35
+ };
36
+ /** The `protobase_splash_background` colour resource, in values for light mode and values-night for dark. */
37
+ const splashBackgroundResource = (color) => `<?xml version="1.0" encoding="utf-8"?>
38
+ <resources>
39
+ <color name="protobase_splash_background">${color}</color>
40
+ </resources>
41
+ `;
42
+ /** Gives the Android project in the workspace Protobase's splash screen on the app's background in place of Capacitor's. */
43
+ const withAndroidSplash = async (ws, { light, dark }) => {
44
+ const styles = path.join(ws, "android", stylesPath);
45
+ await writeFile(styles, withLaunchTheme(await readFile(styles, "utf8")));
46
+ for (const [values, color] of [["values", light], ["values-night", dark]]) {
47
+ const dir = path.join(ws, "android", res, values);
48
+ await mkdir(dir, { recursive: true });
49
+ await writeFile(path.join(dir, "protobase_splash.xml"), splashBackgroundResource(color));
50
+ }
51
+ for (const image of templateSplashImages) await removeTemplateSplash(ws, "android", image);
52
+ for (const file of androidSplashFiles) await copySplashFile(ws, "android", file);
53
+ };
54
+ //#endregion
55
+ export { androidSplashFiles, androidSplashLayout, splashBackgroundResource, templateSplashImages, withAndroidSplash, withLaunchTheme };
@@ -1,4 +1,5 @@
1
1
  import { pushPlugin } from "./pinned-packages.js";
2
+ import { androidSplashLayout } from "./android-splash.js";
2
3
  import path from "node:path";
3
4
  import { rm, writeFile } from "node:fs/promises";
4
5
  import { capacitorOrigin } from "@protobase/schema/internal";
@@ -48,7 +49,10 @@ const capacitorConfig = ({ appId, appName, fingerprint, shellVersion, plugins, l
48
49
  origin: capacitorOrigin[platform]
49
50
  },
50
51
  Keyboard: { autoBackdropColor: "dom" },
51
- SplashScreen: { launchAutoHide: false },
52
+ SplashScreen: {
53
+ launchAutoHide: false,
54
+ layoutName: androidSplashLayout
55
+ },
52
56
  ...push && { PushNotifications: { presentationOptions: pushPresentation } },
53
57
  ...apnsEnvironment && { ProtobasePush: { environment: apnsEnvironment } },
54
58
  ...liveUpdate && { LiveUpdate: {
@@ -1,8 +1,10 @@
1
+ import { withAndroidSplash } from "./android-splash.js";
1
2
  import { dataExtractionRules, dataExtractionRulesPath, withoutBackup } from "./android-backup.js";
2
3
  import { copyGoogleServices } from "./google-services.js";
3
4
  import { withLocalNetworking } from "./info-plist.js";
4
5
  import { withFreshInstall } from "./ios-fresh-install.js";
5
6
  import { setUpIosPush } from "./ios-push.js";
7
+ import { withIosSplash } from "./ios-splash.js";
6
8
  import { withProtobaseIcon } from "./native-icon.js";
7
9
  import path from "node:path";
8
10
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
@@ -12,13 +14,14 @@ const appDelegate = (ws) => path.join(ws, "ios", "App", "App", "AppDelegate.swif
12
14
  const androidManifest = (ws) => path.join(ws, "android", "app", "src", "main", "AndroidManifest.xml");
13
15
  /**
14
16
  * Generates the platform's native project in the workspace from its capacitor.config.json and app files, replacing
15
- * the last one: it is never edited by hand. Its home-screen icon is Protobase's, an Android app with push gets the
17
+ * the last one: it is never edited by hand. Its home-screen icon is Protobase's, and its splash screen that icon on the
18
+ * app's background in `splash`, light and dark, in place of Capacitor's logo. An Android app with push gets the
16
19
  * project's google-services.json from `googleServicesFrom`, an iOS app with push its entitlement in `apnsEnvironment` and
17
20
  * the token forwarding, and an iOS app calling the API over plain http may reach local addresses. Android apps opt out
18
21
  * of backup and device transfer, and iOS apps start as a fresh install after a restore or a move, so nothing carries
19
22
  * over to another phone.
20
23
  */
21
- const generatePlatform = async (ws, platform, { cleartext, googleServicesFrom, apnsEnvironment }, cap) => {
24
+ const generatePlatform = async (ws, platform, { cleartext, splash, googleServicesFrom, apnsEnvironment }, cap) => {
22
25
  await rm(path.join(ws, platform), {
23
26
  recursive: true,
24
27
  force: true
@@ -26,6 +29,7 @@ const generatePlatform = async (ws, platform, { cleartext, googleServicesFrom, a
26
29
  await cap(["add", platform]);
27
30
  await withProtobaseIcon(ws, platform);
28
31
  if (platform === "android") {
32
+ await withAndroidSplash(ws, splash);
29
33
  if (googleServicesFrom !== void 0) await copyGoogleServices(googleServicesFrom, ws);
30
34
  await writeFile(androidManifest(ws), withoutBackup(await readFile(androidManifest(ws), "utf8")));
31
35
  const rules = path.join(ws, "android", ...dataExtractionRulesPath);
@@ -33,6 +37,7 @@ const generatePlatform = async (ws, platform, { cleartext, googleServicesFrom, a
33
37
  await writeFile(rules, dataExtractionRules);
34
38
  return;
35
39
  }
40
+ await withIosSplash(ws, splash);
36
41
  await writeFile(appDelegate(ws), withFreshInstall(await readFile(appDelegate(ws), "utf8")));
37
42
  if (apnsEnvironment !== void 0) await setUpIosPush(ws, apnsEnvironment);
38
43
  if (!cleartext) return;
@@ -0,0 +1,53 @@
1
+ import { copySplashFile, removeTemplateSplash } from "./native-splash.js";
2
+ import path from "node:path";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ //#region src/mobile/ios-splash.ts
5
+ const assets = "App/App/Assets.xcassets";
6
+ /**
7
+ * The launch screen files the template has, which Protobase's replace: the storyboard, Protobase's as a plain view in
8
+ * the `SplashBackground` colour with the `Splash` image, the home-screen icon with its corners rounded, in its middle;
9
+ * and that image.
10
+ */
11
+ const iosSplashFiles = ["App/App/Base.lproj/LaunchScreen.storyboard", `${assets}/Splash.imageset`];
12
+ /** The folder of the `SplashBackground` colour in the app's asset catalog. */
13
+ const splashBackgroundSet = `${assets}/SplashBackground.colorset`;
14
+ const component = (hex, at) => `0x${hex.slice(at, at + 2).toUpperCase()}`;
15
+ const color = (hex) => ({
16
+ "color-space": "srgb",
17
+ components: {
18
+ red: component(hex, 1),
19
+ green: component(hex, 3),
20
+ blue: component(hex, 5),
21
+ alpha: "1.000"
22
+ }
23
+ });
24
+ /** The asset catalog's `SplashBackground` colour: `light`, and `dark` in dark mode, so the launch screen follows the phone's. */
25
+ const splashBackgroundContents = ({ light, dark }) => `${JSON.stringify({
26
+ colors: [{
27
+ color: color(light),
28
+ idiom: "universal"
29
+ }, {
30
+ appearances: [{
31
+ appearance: "luminosity",
32
+ value: "dark"
33
+ }],
34
+ color: color(dark),
35
+ idiom: "universal"
36
+ }],
37
+ info: {
38
+ author: "xcode",
39
+ version: 1
40
+ }
41
+ }, null, 2)}\n`;
42
+ /** Gives the iOS project in the workspace Protobase's launch screen on the app's background in place of Capacitor's. */
43
+ const withIosSplash = async (ws, colors) => {
44
+ for (const file of iosSplashFiles) {
45
+ await removeTemplateSplash(ws, "ios", file);
46
+ await copySplashFile(ws, "ios", file);
47
+ }
48
+ const set = path.join(ws, "ios", splashBackgroundSet);
49
+ await mkdir(set, { recursive: true });
50
+ await writeFile(path.join(set, "Contents.json"), splashBackgroundContents(colors));
51
+ };
52
+ //#endregion
53
+ export { iosSplashFiles, splashBackgroundContents, splashBackgroundSet, withIosSplash };
@@ -0,0 +1,23 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { cp, rm } from "node:fs/promises";
4
+ //#region src/mobile/native-splash.ts
5
+ /** Where @protobase/mobile, installed in the workspace `ws`, has the platform's splash files, by their native project paths. */
6
+ const protobaseSplashDir = (ws, platform) => path.join(ws, "node_modules", "@protobase", "mobile", "splash", platform);
7
+ /** Copies Protobase's splash file or folder `file` into the platform's native project in the workspace, by the same path. */
8
+ const copySplashFile = async (ws, platform, file) => {
9
+ const from = path.join(protobaseSplashDir(ws, platform), file);
10
+ if (!existsSync(from)) throw new Error(`@protobase/mobile has no ${path.join(platform, file)} of Protobase's splash screen`);
11
+ await cp(from, path.join(ws, platform, file), { recursive: true });
12
+ };
13
+ /**
14
+ * Removes the template's splash file or folder `file` from the platform's native project in the workspace. It must be
15
+ * one the template has, so a template that moves its splash fails here rather than leaving Capacitor's on the phone.
16
+ */
17
+ const removeTemplateSplash = async (ws, platform, file) => {
18
+ const at = path.join(ws, platform, file);
19
+ if (!existsSync(at)) throw new Error(`The generated ${platform} project has no ${file}, the splash screen Protobase's replaces`);
20
+ await rm(at, { recursive: true });
21
+ };
22
+ //#endregion
23
+ export { copySplashFile, protobaseSplashDir, removeTemplateSplash };
@@ -16,6 +16,7 @@ import { liveUpdateSettings } from "./live-update-settings.js";
16
16
  import { loadMobileProject } from "./load-project.js";
17
17
  import { signForDevelopment } from "./development-signing.js";
18
18
  import { checkIosPlugins, checkProtobasePlugin, guardIosLiveUpdate, guardLiveUpdate } from "./protobase-plugin.js";
19
+ import { splashColors } from "./splash-colors.js";
19
20
  import { mobileSpec, prepareWorkspace, workspaceDir, workspacePackageJson } from "./workspace.js";
20
21
  import path from "node:path";
21
22
  import { nativeFingerprint } from "@protobase/server/mobile-release";
@@ -25,6 +26,7 @@ const prepare = async ({ projectDir, platform, api, extensions, live, release },
25
26
  if (live !== void 0 && api !== void 0) throw new Error("--live opens protobase dev, which serves the API itself: leave out --api");
26
27
  const project = await loadMobileProject(projectDir, extensions);
27
28
  const mobile = checkMobileConfig(project.mobile);
29
+ const splash = await splashColors(projectDir);
28
30
  const url = live === void 0 ? apiUrl(api, project.auth?.issuer, platform) : new URL(`http://localhost:${live}`);
29
31
  if (release) checkReleaseUrl(url);
30
32
  const allowances = httpAllowances(url);
@@ -87,6 +89,7 @@ const prepare = async ({ projectDir, platform, api, extensions, live, release },
87
89
  const cap = capacitorRunner(ws, env, run);
88
90
  await generatePlatform(ws, platform, {
89
91
  ...allowances,
92
+ splash,
90
93
  ...push && platform === "android" && { googleServicesFrom: projectDir },
91
94
  ...apnsEnvironment && { apnsEnvironment }
92
95
  }, cap);
@@ -0,0 +1,78 @@
1
+ import { themeFile, themeScheme, tokensFile } from "../build/theme.js";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { readFile } from "node:fs/promises";
5
+ import { transform } from "lightningcss";
6
+ //#region src/mobile/splash-colors.ts
7
+ const record = (found, selectors, declarations) => {
8
+ for (const declaration of declarations) {
9
+ if (declaration.property !== "custom" || declaration.value.name !== "--background") continue;
10
+ for (const selector of selectors) {
11
+ const scheme = themeScheme(selector);
12
+ if (scheme) found[scheme] = declaration.value.value;
13
+ }
14
+ }
15
+ };
16
+ const backgrounds = (code, file) => {
17
+ const normal = {};
18
+ const important = {};
19
+ const visit = (rules) => {
20
+ for (const rule of rules) {
21
+ if (rule.type === "layer-block") visit(rule.value.rules);
22
+ if (rule.type !== "style") continue;
23
+ record(normal, rule.value.selectors, rule.value.declarations?.declarations ?? []);
24
+ record(important, rule.value.selectors, rule.value.declarations?.importantDeclarations ?? []);
25
+ }
26
+ };
27
+ transform({
28
+ filename: file,
29
+ code: Buffer.from(code),
30
+ visitor: { StyleSheet: (sheet) => void visit(sheet.rules) }
31
+ });
32
+ return {
33
+ light: important.light ?? normal.light,
34
+ dark: important.dark ?? normal.dark
35
+ };
36
+ };
37
+ const namedColor = (name) => {
38
+ let color;
39
+ transform({
40
+ filename: "name.css",
41
+ code: Buffer.from(`a{color:${name}}`),
42
+ visitor: { Declaration: { color: (declaration) => void (declaration.property === "color" && (color = declaration.value)) } }
43
+ });
44
+ return color;
45
+ };
46
+ const parsedColor = (value) => {
47
+ const [only] = value;
48
+ if (value.length !== 1 || !only) return;
49
+ if (only.type === "color") return only.value;
50
+ if (only.type === "token" && only.value.type === "ident") return namedColor(only.value.value);
51
+ };
52
+ const isRgb = (color) => typeof color === "object" && color.type === "rgb";
53
+ const hex = (value) => value.toString(16).padStart(2, "0");
54
+ const nativeColor = (value, where) => {
55
+ const color = parsedColor(value);
56
+ if (!isRgb(color) || color.alpha !== 1) throw new Error(`${where}: the native splash screen needs --background as an opaque sRGB colour, such as #f4f3ee, rgb() or hsl()`);
57
+ return `#${hex(color.r)}${hex(color.g)}${hex(color.b)}`;
58
+ };
59
+ /**
60
+ * The background the app's first screen paints, for the native splash screen: `--background` from the project's
61
+ * protobase.theme.css, where it sets it, and from the installed @protobase/ui's tokens otherwise. As in the app, a theme
62
+ * that sets it on :root only sets it for dark mode too.
63
+ */
64
+ const splashColors = async (projectDir, tokens = tokensFile) => {
65
+ const source = path.join(projectDir, themeFile);
66
+ const theme = existsSync(source) ? backgrounds(await readFile(source, "utf8"), themeFile) : {};
67
+ const ui = backgrounds(await readFile(tokens, "utf8"), tokens);
68
+ const pick = (scheme, ...choices) => {
69
+ for (const [value, where] of choices) if (value) return nativeColor(value, where);
70
+ throw new Error(`${tokens} sets no ${scheme} --background`);
71
+ };
72
+ return {
73
+ light: pick("light", [theme.light, themeFile], [ui.light, tokens]),
74
+ dark: pick("dark", [theme.dark, themeFile], [theme.light, themeFile], [ui.dark, tokens])
75
+ };
76
+ };
77
+ //#endregion
78
+ export { splashColors };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.96.0",
3
+ "version": "0.96.2",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -43,13 +43,13 @@
43
43
  "dependencies": {
44
44
  "@better-auth/core": "^1.7.12",
45
45
  "@hono/node-server": "^2.1.3",
46
- "@protobase/config": "0.96.0",
47
- "@protobase/layout": "0.96.0",
48
- "@protobase/query": "0.96.0",
49
- "@protobase/schema": "0.96.0",
50
- "@protobase/server": "0.96.0",
51
- "@protobase/ui": "0.96.0",
52
- "@protobase/workflows": "0.96.0",
46
+ "@protobase/config": "0.96.2",
47
+ "@protobase/layout": "0.96.2",
48
+ "@protobase/query": "0.96.2",
49
+ "@protobase/schema": "0.96.2",
50
+ "@protobase/server": "0.96.2",
51
+ "@protobase/ui": "0.96.2",
52
+ "@protobase/workflows": "0.96.2",
53
53
  "@react-email/render": "^2.1.0",
54
54
  "@scalar/hono-api-reference": "^0.12.10",
55
55
  "@sentry/vite-plugin": "^11.10.0",
@@ -9,6 +9,7 @@ Pages of your own, built from blocks in a JSX layout.
9
9
  - [Conditions](../reference/layouts.md#conditions): Part of a page shows only while a condition on a record or a count holds.
10
10
  - [App addresses](../reference/layouts.md#addresses): Links to lists, records, create forms and pages are typed addresses that can carry filters and prefilled values.
11
11
  - [Component fallbacks](../reference/custom-components.md#fallbacks): A custom component declares what a client that cannot draw it shows instead, or nothing, and the web shows it too when the component is missing or throws.
12
+ - [Text form](../reference/layouts.md#text-form): Every layout block renders to Markdown text through one shared function, built up from its children, as the last-resort fallback and for MCP clients and LLMs.
12
13
  - [Per-user pages](../reference/layouts.md#access): Each user gets the page without the parts, fields and actions they cannot use.
13
14
  - [Layout blocks](../reference/blocks.md#layout): Pages, responsive grids, cards and links.
14
15
  - [Tailwind classes](../reference/layouts.md#tailwind-classes) (experimental): Layouts can carry Tailwind classes, on plain elements and on blocks, for pages too custom for blocks.
@@ -20,6 +21,7 @@ Pages of your own, built from blocks in a JSX layout.
20
21
  - [Image block](../reference/blocks.md#image): A picture one of the app's API functions draws for the reader, such as a system map, at the size and theme the client asks, refreshed on a timer; a client that draws no images shows its alt text, or nothing.
21
22
  - [Chart block](../reference/blocks.md#chart): Counts, sums or averages by value or by date, as bars, lines or a donut, and over time split by a second field.
22
23
  - [Conversations](../reference/blocks.md#conversation): A chat declared in the layout: a thread of a resource's messages under each sender's name and time, following new ones as they arrive, and a box that sends one as the signed-in user.
24
+ - [Tool calls in threads](../reference/blocks.md#tool-calls): Conversation threads show tool calls in time order, with a status and an expandable input and result.
23
25
  - [Buttons and forms](../reference/blocks.md#behaviour): Buttons for named actions, and create or edit forms in a dialog.
24
26
  - [Settings block](../reference/blocks.md#settings): Each person's own settings from a resource with one record per person, saved as they change, with defaults until the first save.
25
27
  - [Users block](../reference/blocks.md#users): User management on any page: find users, set roles, block them and invite by email.
@@ -98,7 +98,7 @@ bun install
98
98
 
99
99
  ## Run the ERP example
100
100
 
101
- `tests/apps/erp` is a sample ERP on a real Postgres database, seeded with three years of history. It needs Docker for the database: `bun run db:up` starts the Postgres container and gives each example its database and a `.env` from its `.env.example`. The databases listen on `127.0.0.1` only, so on Docker Engine 28.0.0 or later other machines on the network cannot reach them, unless the daemon's `allow-direct-routing` option, off by default, lets them reach containers by their own address; an older Docker Engine lets hosts on the same local network segment reach them, so it needs a firewall that blocks them. On Linux with firewalld, Docker Engine 28.2.0 to 28.3.2 lets other hosts reach them again after a firewalld reload, so it needs that firewall too, or an upgrade to 28.3.3 or later. A checkout or worktree on an older base publishes them on every interface again, so rebase it onto `main` before any `docker compose up` or `db:up`.
101
+ `tests/apps/erp` is a sample ERP on a real Postgres database, seeded with three years of history. `bun run db:up` starts the Postgres container and gives each example its database and a `.env` from its `.env.example`. Without Docker, `POSTGRES_RUNNER=local` in the repository's `.env` runs the machine's own Postgres 18 and PgBouncer as plain processes on the same ports instead, with their data in `.protobase/postgres`; `POSTGRES_BIN` names the folder of `initdb` and `pg_ctl` when they are not on PATH. Supabase's Postgres, which `bun run test:record` needs, runs only in Docker. The databases listen on `127.0.0.1` only, so on Docker Engine 28.0.0 or later other machines on the network cannot reach them, unless the daemon's `allow-direct-routing` option, off by default, lets them reach containers by their own address; an older Docker Engine lets hosts on the same local network segment reach them, so it needs a firewall that blocks them. On Linux with firewalld, Docker Engine 28.2.0 to 28.3.2 lets other hosts reach them again after a firewalld reload, so it needs that firewall too, or an upgrade to 28.3.3 or later. A checkout or worktree on an older base publishes them on every interface again, so rebase it onto `main` before any `docker compose up` or `db:up`.
102
102
 
103
103
  ```sh
104
104
  bun run db:up && bun run --cwd tests/apps/erp db:migrate && bun run --cwd tests/apps/erp db:seed --scale small # the ERP's tables and Better Auth's
@@ -131,7 +131,7 @@ bun run --cwd tests/apps/property-portal dev # http://localhost:517
131
131
 
132
132
  | Command | Purpose |
133
133
  | --- | --- |
134
- | `bun run db:up` / `bun run db:down` | start or stop the Postgres container; `db:up` also creates the examples' databases and `.env` files |
134
+ | `bun run db:up` / `bun run db:down` | start or stop the Postgres container, or with `POSTGRES_RUNNER=local` in `.env` the local Postgres and PgBouncer processes; `db:up` also creates the examples' databases and `.env` files |
135
135
  | `bun run test` | the unit tests and the snapshot tests in `packages/*/tests/` and `tests/` (Vitest projects `unit*` and `snapshot*`): no Postgres server, subprocess or network. A snapshot test replays the SQL recorded for it from Postgres in `<test>.sql.json` |
136
136
  | `bun run test:record` | runs the snapshot tests on the Postgres container instead and writes their recordings, after building their templates (`bun run test:db snapshots`); run it when a change makes a snapshot test fail with `stale snapshot` |
137
137
  | `bun run test:unit` | only the unit tests, next to the code (Vitest projects `unit`, whose files share their modules, and `unit-isolated`, for those that mock a module or change a global), fully parallel; starting a Postgres client there throws |
@@ -37,7 +37,7 @@ export default defineConfig({
37
37
 
38
38
  The app is installed under the name it shows in its upper left, on iOS and Android alike: `protobase mobile` reads it from the server the app calls (its web manifest), so a `PROTOBASE_APP_NAME` the server runs with names the app on the phone too. When that server cannot be reached, `run` and `open` warn and take the project's own name, the config's `name` or `PROTOBASE_APP_NAME` in its environment, and `build` stops.
39
39
 
40
- On the home screen the app shows Protobase's icon, on iOS and Android alike. <gap>An app cannot show its own icon on the phone because setting the mobile app's icon is not implemented.</gap>
40
+ On the home screen the app shows Protobase's icon, on iOS and Android alike. While it starts, its splash screen shows that icon in the middle of the app's background: the `--background` [token](../reference/theme.md) of its `protobase.theme.css`, or the default without one, light or dark as the phone is. `protobase mobile` takes it as a colour such as `#f4f3ee`, `rgb()`, `hsl()` or `white`, and stops on one a phone's splash screen cannot show, such as `oklch()` or `var()`. <gap>An app cannot show its own icon on the phone, on the home screen or its splash screen, because setting the mobile app's icon is not implemented.</gap>
41
41
 
42
42
  With a mobile section, the API answers the app's origins, `capacitor://localhost` on iOS and `https://localhost` on Android, through [CORS](../reference/api.md#cors). Apps without one get no new dependency, and `protobase build` and `protobase dev` work as before.
43
43
 
@@ -501,11 +501,40 @@ The latest messages that match `filter`, oldest first, each under its sender's n
501
501
  | `text` | The message; shown rendered when the message resource's view marks it [`.markdown()`](ui-config.md#names-and-columns). Required. |
502
502
  | `status` | A short line under each message, such as whether it was delivered: a text or enum field, shown with its view's value labels, in red for a value it colours `red`; a message without a value shows none. Left out for a user who cannot read it. Experimental, see [Message status and a working indicator](ui-config.md#message-status-and-a-working-indicator). |
503
503
  | `working` | A condition on the record around the thread, as [`Show`](#show) takes, such as `state = 'working'`: while it holds, the thread ends in a working indicator. Left out for a user who cannot read what it names. Experimental. |
504
- | `limit` | How many of the latest it shows at first, and how many each **Load earlier messages** adds: 1 to 500, the API's largest page; default 50. |
504
+ | `calls` | Tool calls shown between the messages in time order, from a resource of their own; see [Tool calls](#tool-calls). Left out for a user who cannot read their name, time or status. |
505
+ | `limit` | How many of the latest messages it shows at first, and of the latest tool calls, and how many each **Load earlier messages** adds: 1 to 500, the API's largest page; default 50. |
505
506
  | `title`, `description`, `actions` | The heading; no card is drawn around the thread, so it can sit in a `Card` with its composer. |
506
507
  | `empty` | Text while there are no messages. |
507
508
  | `span` | Width in a grid. |
508
509
 
510
+ #### Tool calls
511
+
512
+ A thread with an assistant in it can show what the assistant did between its messages: each tool call it made, in time order, with the tool's name and its status, which opens to what the tool was called with, what it gave back and why it failed. `calls` names the resource that holds the calls and the fields the thread reads of each:
513
+
514
+ ```tsx
515
+ <Thread
516
+ resource="messages"
517
+ filter="chat_id = 1"
518
+ sender="author_id"
519
+ time="sent_at"
520
+ text="body"
521
+ calls={{ resource: 'tool_calls', filter: 'chat_id = 1', name: 'tool', time: 'called_at', status: 'state', input: 'input', result: 'output', error: 'failure' }}
522
+ />
523
+ ```
524
+
525
+ | `calls` key | |
526
+ | --- | --- |
527
+ | `resource`, `filter` | Which calls. `resource` is required. |
528
+ | `name` | The tool's name: a text field. Required. |
529
+ | `time` | When it was called: a date or timestamp field the API can sort by, which places it among the messages. A call at the same time as a message shows after it. Required. |
530
+ | `status` | A text or enum field: `done` shows a check, `running` a spinner and `error` an alert icon in red, each beside the value's label from the view; any other value shows its label without a mark, and a call without a value shows none. Required. |
531
+ | `input`, `result` | What the tool was called with and what it gave back, shown as indented JSON; a text that holds JSON shows as the value it holds. |
532
+ | `error` | Why the call failed: a text field. |
533
+
534
+ Each call is a line under the messages before it, closed at first; a call with an input, result or error opens and closes with a click on its line. The thread reads the latest calls as it reads the latest messages, `limit` at a time, newest first by `time`, so that read needs an index on the filter's field and `time`, which [`protobase doctor`](cli.md#doctor) checks, and **Load earlier messages** loads the earlier calls with the earlier messages, keeping them in time order. A user who cannot read the calls' `name`, `time` or `status` gets the thread without its calls, and one who cannot read `input`, `result` or `error` gets the calls without that part.
535
+
536
+ Clients that cannot draw the calls get their simpler forms from `@protobase/layout`: `threadLines(items)` gives one short line per item, a message as its sender and first line and a call as its name and status, and `threadMarkdown(items, words)` gives the thread as Markdown, for clients that read text, such as an MCP client or a language model: each message under its sender in bold, each call as its name and status with its input and result as JSON and its error in fenced code blocks. <gap>A watch cannot show a thread's tool calls as lines because drawing a thread on a watch is not implemented.</gap> <gap>An MCP client cannot read a thread as Markdown because serving a page's blocks as text is not implemented.</gap>
537
+
509
538
  ### Composer
510
539
 
511
540
  A text box that grows with its text: Enter or the send button creates a record of `resource` with the text in `field` and the `values`, and Shift+Enter starts a new line. The text stays in the box until the server took it, so a message it refuses is still there to send again, under the reason. It is not shown to a user who may not create a record of `resource` or write its fields.
@@ -53,6 +53,46 @@ A custom component declared with a [fallback](custom-components.md#fallbacks) ca
53
53
 
54
54
  A client that cannot draw the component, such as one without React, draws the fallback instead, and the checks read it like the rest of the tree.
55
55
 
56
+ ## Text form
57
+
58
+ Every layout block renders to Markdown text through one shared function, `renderText`, built up from its children. It is the last-resort form of a page, for a client that draws no blocks and for MCP clients and LLMs. Each element's text is made from its children's text, already rendered: a container such as `Grid`, `Box` or `Tabs` reads as its children in order with a blank line between them, and text and links run on in one line as they do on the web.
59
+
60
+ ```tsx
61
+ import { Field, Page, renderText } from '@protobase/layout'
62
+
63
+ renderText(<Page title="Order"><Field name="status" /></Page>, {
64
+ record: { status: 'in_progress' },
65
+ fields: { status: { label: 'Status', valueLabels: { in_progress: 'In progress' } } },
66
+ })
67
+ // # Order
68
+ //
69
+ // **Status**: In progress
70
+ ```
71
+
72
+ | Option | |
73
+ | --- | --- |
74
+ | `record` | The record around the tree. `Field`, `Stat field`, `Progress`, `Show` conditions and the `{field}`s of addresses read it, through relations as nested objects (`plan.name`); a count a condition names, such as `billing_profiles.count`, is a key of its own. Without it, a field reads as its label alone, a `Show` reads as all it holds, and addresses keep their `{field}`s. |
75
+ | `fields` | Per field path, its `label` and the `valueLabels` its enum values read as; a field without a label reads under its path. |
76
+ | `basePath` | What links start with, such as `https://example.com/admin`. |
77
+ | `forms` | Text forms by block type, over the built-in ones. |
78
+
79
+ A heading reads at its level: a `Page` title as `#`, a `Tab` label as `##`, and the title of a `Card` and of a data block as `###`, the data block's linked to its records' list as it filters them. A field's value reads as its enum label, a list as its items, and JSON as a code block.
80
+
81
+ A text form of your own is a function from its element and its children's text to Markdown. It can use the default as it is (`childrenText`), wrap a built-in form from `textForms`, or rework the children's text, such as a horizontal line between them:
82
+
83
+ ```ts
84
+ import { childrenText, markdown, renderText, textForms, type TextForm } from '@protobase/layout'
85
+
86
+ const ruled: TextForm = ({ children }) => markdown.blocks(children, '\n\n---\n\n')
87
+ const noted: TextForm = (context) => `${textForms.Card!(context)}\n\nUpdated hourly.`
88
+
89
+ renderText(tree, { forms: { Grid: ruled, Card: noted, SeatChart: childrenText } })
90
+ ```
91
+
92
+ A custom component reads as its [fallback](custom-components.md#fallbacks) when it declares one, and otherwise as what it holds, unless `forms` names it.
93
+
94
+ <gap>A data block's text form cannot list its records, such as a table's rows, because reading records for the text form is not implemented.</gap> <gap>A field's text form cannot apply its `format`, such as a relative time, because formatting in the text form is not implemented.</gap> <gap>MCP clients cannot read a page's text form because a tool that serves it is not implemented.</gap>
95
+
56
96
  ## What a layout may hold
57
97
 
58
98
  A prop is a string, a finite number, a boolean, `null`, or an array or plain object of those (elements included). It is JSON in the end, so the rules are checked twice:
@@ -1204,6 +1204,7 @@ The thread shows the latest messages oldest first, each under its sender's name
1204
1204
  | `text` | The message, a text field. Required. |
1205
1205
  | `status` | A short line under each message, such as whether it was delivered: a text or enum field. See [Message status and a working indicator](#message-status-and-a-working-indicator). |
1206
1206
  | `working` | A condition on this record, such as `state = 'working'`, while which the thread ends in a working indicator. |
1207
+ | `calls` | Tool calls shown between the messages in time order: the `resource` that holds them, the filterable relation `field` of it that holds this record's key, and the fields the [Thread block's `calls`](blocks.md#tool-calls) names, `name`, `time`, `status`, `input`, `result` and `error`. A `field` that is no relation to this resource, a field the calls do not have or of the wrong type, or a sensitive one stops the server at startup. |
1207
1208
  | `limit` | How many of the latest it shows at first, and how many each **Load earlier messages** adds: 1 to 500, the API's largest page; default 50. |
1208
1209
  | `empty` | Text while there are no messages. |
1209
1210
  | `help`, `when` | A line under the title, and whether it shows on the form, the read view or both. |
@@ -1226,7 +1227,7 @@ view<typeof tasks>('tasks').layout((r) => [
1226
1227
  ])
1227
1228
  ```
1228
1229
 
1229
- The messages are read with `field = <this record's key>` as the filter, newest first by `time`, so the user's access applies as on the list. That read needs an index on `(field, time)`, such as `create index on task_messages (task_id, sent_at)`, which [`protobase doctor`](cli.md#doctor) checks. A user who cannot read `field`, `sender`, `time` or `text` gets no thread, and one who may not create a message with `field` and `text` gets no composer. A `field` that is no relation to this resource, a `time` that is no date or timestamp the API can sort by, a `sender` that is no relation or text field, a thread `text` that is no text field, a sensitive field in the thread, or a composer `text` that is no writable text field stops the server at startup. As with a related section, the record page's count of the records that point at it leaves out the messages its thread shows.
1230
+ The messages are read with `field = <this record's key>` as the filter, newest first by `time`, so the user's access applies as on the list. That read needs an index on `(field, time)`, such as `create index on task_messages (task_id, sent_at)`, which [`protobase doctor`](cli.md#doctor) checks. Tool calls are read the same way, by their own `field` and `time`. A user who cannot read `field`, `sender`, `time` or `text` gets no thread, and one who may not create a message with `field` and `text` gets no composer. A `field` that is no relation to this resource, a `time` that is no date or timestamp the API can sort by, a `sender` that is no relation or text field, a thread `text` that is no text field, a sensitive field in the thread, or a composer `text` that is no writable text field stops the server at startup. As with a related section, the record page's count of the records that point at it leaves out the messages and tool calls its thread shows.
1230
1231
 
1231
1232
  #### Message status and a working indicator
1232
1233