# Scripts in depth A script's four shapes, when its code runs, scripts inside data, and what a splice checks. To your server, a script is a value, a `Client`: something the phone will compute as a `T`. This page is what follows from that, for when a screen does something you didn't expect. ## Four shapes ```ts title="server/shapes.ts" import { type Client, cs } from "@backtickjs/core"; // An expression is what it computes. export const greeting: Client = cs`new Date().getHours() < 12 ? "Good morning" : "Good afternoon"`; // A block is what it returns. export const meal: Client = cs`{ const hour = new Date().getHours(); return hour < 11 ? "Breakfast" : "Lunch"; }`; // A function is the function. export const double: Client<(n: number) => number> = cs`(n: number) => n * 2`; // A class is the class. export const Tally: Client { add(): number }> = cs`class Tally { count = 0; add() { return ++this.count; } }`; ``` A script is an expression, a block of statements, a function, or a class. An expression is a `Client` of its value; a block, of what it returns; a function, of the function itself; a class, of the class. A function that returns JSX is a client component. A script makes a value: one that makes none, a block that returns nothing, is refused where it's written. TypeScript infers each type; the annotations above only show them. Your server can't read the `T`, which doesn't exist until the phone runs the script. It can splice the script into another, pass it around, and return it from a server component. Annotate a function that builds scripts with `Client`, taking the phone's number and giving back the phone's string: ```ts title="server/formatted.ts" import { type Client, cs } from "@backtickjs/core"; // A script built from another: the phone computes `amount`, then formats it. export function formatted(amount: Client): Client { return cs`"$" + $amount.toFixed(2)`; } export const total = formatted(cs`4.5 + 4`); ``` ## Reading a script A script is one value, made when the bundle loads, as a module-level `const` is in TypeScript: every splice of it reads that value. - **A function is one function.** `$logTap` is the same function at every read, and its body runs each time it's called. Code that runs each time it's used is written this way, and called: `$logVisit()`. - **A class is one class**, as a module-level class is. - **An expression or a block is its value**, made once: a store, a context or styles every component shares. - **A script that reads a variable of the script around it** is made each time that script runs, as code written in a function is. ```tsx title="server/Log.tsx" import { cs } from "@backtickjs/core"; import { Text } from "react-native" with { backtick: "client" }; // Code that runs each time it's used is a function, called where it runs. const logVisit = cs`() => console.log("visit")`; // A function with a parameter: one function, whose body runs each call. const logTap = cs`(what: string) => console.log("tap " + what)`; export async function Home() { return cs`{ $logVisit(); $logVisit(); $logTap("a"); $logTap("b"); return <$Text>Logged; }`; } ``` A client component is one function for the bundle, so React sees the same component on every render and keeps its state. A component made by a call, such as `memo(…)`, is one value too, as at module level: ```tsx title="server/Rows.tsx" import { cs } from "@backtickjs/core"; import { memo, useState } from "react" with { backtick: "client" }; import { Pressable, Text, View } from "react-native" with { backtick: "client", }; // A client component, written as a function: one component for the bundle. const Row = cs`(props: { label: string }) => { const [count, setCount] = $useState(0); return ( <$Pressable onPress={() => setCount(count + 1)}> <$Text> {props.label} {count} ); }`; // memo(…) is a call, and a script is one value: one component for the bundle. const MemoRow = cs`$memo($Row)`; export const List = cs`() => { const [taps, setTaps] = $useState(0); return ( <$View> <$Pressable onPress={() => setTaps(taps + 1)}> <$Text>list {taps} <$MemoRow label="row" /> ); }`; export async function Home() { return cs`<$List />`; } ``` What every component shares, a context or a store, is written the same way. `ThemeContext` is one context for the bundle, as `createContext` at module level is one, so the provider and the consumer find each other. ```tsx title="server/Theme.tsx" import { cs } from "@backtickjs/core"; import { createContext, useContext } from "react" with { backtick: "client" }; import { Text, View } from "react-native" with { backtick: "client" }; // One context for the bundle, as `createContext` at module level is one. const ThemeContext = cs`$createContext("light")`; const Label = cs`() => { const theme = $useContext($ThemeContext); return <$Text>{theme}; }`; export async function Home({ dark }: { dark: boolean }) { const theme = dark ? "dark" : "light"; return cs`( <$View> <$ThemeContext.Provider value={$theme}> <$Label /> )`; } ``` Each run of a `cs` line is one value: a server component that makes a script makes one per request. ## No template literals inside a script A script is a template literal itself, so it can't hold one: a backtick in its code is refused, with "A `cs` client script can't hold a template literal". Build the string with `+` instead: `n + "%"`, not `` `${n}%` ``. In a string or a comment, write a backtick as `` \` ``, as anywhere in a template literal. ## A script in data A splice can carry scripts inside data. On the phone, each `Client` in it is the `U` it computes; everything else is unchanged. `Spliced` names that type, and TypeScript applies it to every splice: ```ts title="server/menu.ts" import { type Client, cs, type Spliced } from "@backtickjs/core"; type Item = { name: string; price: number; // Computed on the phone, from its own clock. available: Client; }; export const menu: Item[] = [ { name: "Flat white", price: 4.5, available: cs`true` }, { name: "Croissant", price: 3, available: cs`new Date().getHours() < 11` }, ]; // On the phone, each `available` is the boolean its script computes. export type MenuOnPhone = Spliced; // { name: string; price: number; available: boolean }[] export const names = cs`$menu .filter((item) => item.available) .map((item) => item.name)`; ``` ## Client code handed to a server component A server component drawn inside a client component can be handed that component's local values, as client code: ```tsx title="server/LiveSection.tsx" import { type Client, cs } from "@backtickjs/core"; import { useState } from "react" with { backtick: "client" }; import { Pressable, Text, View } from "react-native" with { backtick: "client", }; const Like = cs`() => { const [liked, setLiked] = $useState(false); return ( <$Pressable onPress={() => setLiked(!liked)}> <$Text>{liked ? "♥" : "♡"} ); }`; // A server component handed client code: its title is the phone's to compute. async function Section({ title }: { title: Client }) { return cs`( <$View> <$Text>{$title} <$Like /> )`; } // A client component drawing that server component, handing it a local. const Cart = cs`() => { const [count, setCount] = $useState(0); return ( <$View> <$Pressable onPress={() => setCount(count + 1)}> <$Text>Add {${(
)}} ); }`; export async function Home() { return cs`<$Cart />`; } ``` `` cs`count + " in your cart"` `` is a fragment of `Cart`'s code, reading its `count`. `Section` splices it as `$title`, and the phone computes it each time it's read, so the title follows the count. `Section` itself runs once, on your server: it decides the layout, and the phone fills in what depends on its state. ## Data, never code A spliced string arrives as a string, whatever it holds. A note that reads like code is still only text: ```tsx title="server/Data.tsx" import { cs } from "@backtickjs/core"; import { Text } from "react-native" with { backtick: "client" }; // A splice is written into the bundle as data, never as code: whatever this // string holds, the phone shows it as text. export async function Note({ text }: { text: string }) { return cs`<$Text>{$text}`; } ``` For a note holding `"); require("fs").rmSync("/"); ("`, the bundle writes it escaped, inside quotes: ```js const $thunk1 = () => ("\"); require(\"fs\").rmSync(\"/\"); (\""); ``` Nothing a user types can become code on the phone. ## What a splice checks A splice checks a value member by member, so an object typed with an interface splices as one typed with a type alias does. `Spliceable` written by hand, in an annotation or a `satisfies`, matches an object through an index signature, which TypeScript never gives an interface: annotate with your own types and let the splice check them. Numbers include `NaN`, `Infinity` and `-0`, which arrive as themselves, as do bigints. A class whose members are all data looks like a plain object to TypeScript, so the bundler is what refuses it, when it builds the screen. A value that contains itself is refused too: a bundle writes each value out in full. [Errors](/docs/errors/#from-the-bundler) has each message. The rest of `@backtickjs/core` is how Backtick's own pieces talk to each other; its [README](https://github.com/backtickjs/backtick/tree/main/packages/core#api) lists them. An app doesn't need it.