0152. Behaviours: script written once and used from any file's script
- Status: Accepted
- Date: 2026-11-16
- Decided by: Mik (approved as built, 16 Nov 2026, including the rules in the Update sections)
- Planning item: Mik, 16 Nov 2026: "add the ability to define a component behaviour from within the frontmatter if you believe it could simplify and make it easier to work with"
- Answers so far: Mik, 16 Nov 2026: frontmatter-only files with a file-name rule; allow both destructuring and one object; allow both live inputs and getter functions; also allow behaviours as
.tsfiles with the same naming rule.
Context
A component's behaviour is already written in its frontmatter, and only there: state, derived, effect, handlers and helpers all sit in the script block between the --- lines, and markup calls them by name (spec/language/script-and-components.md). Unlike Astro, where the frontmatter runs on the server and browser code goes in a separate <script>, Duolith's frontmatter is the code that runs on the phone and in the browser. So nothing needs to move into the frontmatter.
What is missing is a way to use the same behaviour in two files. Today it cannot be shared at all:
- a component's script cannot export (E0118), and a page's cannot (E0147);
- a value imported from the project's own
.tsfile is refused, because the build ships only pages and components (E0356, decision 0099); - a component brings its markup with it, so it cannot lend only its behaviour.
The kit shows the cost. DatePicker.duo and DateRangePicker.duo share 143 of the 152 lines of their scripts: the date helpers, the locale's first weekday, the month on show, the cursor, the weeks grid, the arrow-key moves and the disabled-day rules. Only the props and choose differ. A fix to one (such as the clock-change rule) has to be made twice, and nothing checks that it was. Apps will hit the same wall with a search box with debounce, a form step, a paged list or a timer.
Decision
Add behaviours: script-only files whose exported functions hold state, derived values and effects, and which any page, layout, component or other behaviour calls from its own frontmatter.
Writing one
A behaviour file is named <name>.behaviour.duo and holds a script block and nothing else. The name decides what it is, so the compiler, duolith check and the language server all know a behaviour file without opening it, and it may sit in any folder but pages/ (behaviours/ is the convention, and where duolith create puts the first one). The same behaviour may instead be written as <name>.behaviour.ts: the script without the --- lines, under the same rules and checks. Choose .ts when the file is only script and you want it to open as plain TypeScript in any tool; choose .duo to keep it beside the rest of the project's files in one language. Both are imported the same way, and one name cannot exist as both (E0177). Its frontmatter is written exactly like a component's: the same state, derived and effect, the same rewrites, so no .value anywhere.
behaviours/calendar.behaviour.duo
---
import { derived, effect, state } from "@duolith/client";
export function calendar(input: { start: string; min?: string; max?: string; locale?: string }) {
let cursor = state(nearestAvailable(input.start));
let month = state(startOfMonth(cursor));
let weeks = derived(() => weeksOf(month, firstDayOfWeek(input.locale)));
function move(days: number) {
cursor = nearestAvailable(addDays(cursor, days));
month = startOfMonth(cursor);
}
return { cursor, month, weeks, move };
}
// Plain helpers may sit beside it and be exported too.
export function addDays(iso: string, days: number): string { /* ... */ }
---
Using one
packages/kit/parts/DatePicker.duo
---
import { bindable, props } from "@duolith/client";
import { calendar } from "../behaviours/calendar.behaviour.duo";
let { value = bindable(""), min, max, locale } = props<{ value?: string; min?: string; max?: string; locale?: string }>();
let { cursor, month, weeks, move } = calendar({ start: value, min, max, locale });
function choose(day: string) {
value = day;
}
---
- Inputs stay live, and may also be getters. The argument is one object, passed like props: each property's whole expression stays live, conditions included, so
calendar({ min: booking ? booking.from : today })follows bothbookingandtoday. When the behaviour wants to decide when and how often to read a value, or to pass arguments to it, it declares that input as a function (source: (page: number) => Post[]) and the caller passes one. The behaviour's declared type decides which an input is, and the TypeScript checker fails a call that passes the other, so there is no way to forget an arrow and read a value once. The behaviour reads its input and cannot assign it. - What it returns can be destructured or kept as one object.
let { month, move } = calendar(...)gives names that keep their kind: a returned state is state the caller may assign andbind:to, a derived value is read-only (E0109), a function is a function.let cal = calendar(...)keeps the object, andcal.month,cal.month = x,bind:value={cal.month}andcal.move(1)work the same way, with the same checks. Each call has its own state, as each placed component does. - Writes go back through what the caller passes or the functions the behaviour returns. The behaviour never reaches into the caller.
What the build refuses
Each of these fails duolith build, duolith check and the editor, with an explanation and a fix:
| Code | Refused |
|---|---|
| E0171 | Calling a behaviour anywhere but the top level of a script or of another behaviour, such as inside a condition, a loop or a handler, where it would make new state each time |
| E0172 | Markup, <style> or a slot in a .behaviour.duo file |
| E0173 | A behaviour whose result is not one return { ... } of its own names, so the build cannot know what each name is |
| E0174 | Assigning a behaviour's input |
| E0175 | props(), guard() or a component import in a behaviour: it has no markup and is not a screen |
| E0176 | Behaviours that import each other in a cycle |
| E0177 | A .behaviour.duo file in pages/, placed as a component, or imported without naming what it imports; a file named .behavior.duo or .behavior.ts (the fix names the spelling); name.behaviour.duo and name.behaviour.ts side by side; a .behaviour.ts file imported from a file the duolith build does not compile, such as a Node script, where it would run without the state rules |
| E0178 | Copying a returned state or derived value into a plain variable at a script's top level (let m = cal.month), which reads it once and stops following it; the fix is to destructure it or use derived(() => cal.month) |
| E0179 | A behaviour's input that is not one object literal written in the call (added in the update below) |
| E0180 | A behaviour written in a form the build cannot compile (added in the update below) |
E0356 gains one more allowed source: a behaviour file. Types still flow through the TypeScript checker, so a wrong input, a missing name or a misspelt return fails as a type error (decisions 0095 to 0099).
Where it reaches
- Language:
spec/language/script-and-components.mdgets a "Behaviours" section; the glossary gains behaviour. - Analysis: a behaviour's facts (exports, each one's returned names and their kinds) join the component facts, and the callers' rewrites use them.
- Emission:
crates/scriptcompiles a behaviour file to a module whose exported function makes its cells inside the caller's lifetime; web and native emit the same module. - Editor: the script view types behaviour files and calls; completions list a behaviour's returned names.
- Kit:
DatePickerandDateRangePickermove onto onecalendarbehaviour; the gesture parts' swipe handling is a second candidate. - Docs and examples: a guide page,
llms/, andexamples/componentsuses one behaviour from two components.
Alternatives considered
| Option | Why not |
|---|---|
| Leave it; copy the script | The kit already carries 143 duplicated lines in two parts, and nothing checks the copies stay the same. |
_name.duo as the file rule | A leading _ already means a layout or a reserved page file (_layout, _not-found, E0144). A suffix says what the file is wherever it sits. |
Any .ts file may call state | The same rewrites would apply to some .ts files and not others with nothing to say which. The .behaviour.ts suffix says the rules apply, to the compiler, the language server and the reader. |
| Let a component also export a behaviour from its frontmatter | One file would be both a part and a library; placing it and importing from it would run its script on different terms. |
| Only destructuring, or only one object | Mik chose both (16 Nov 2026). Both are checked alike, and E0178 closes the one way the object form could read a value once. |
| Only getters, as plain JavaScript passes them | A forgotten arrow would read the value once and silently stop updating. Here an input is live unless the behaviour asks for a function, and the type checker enforces which. |
use: actions that attach behaviour to one element | A different need (behaviour tied to an element). Gestures and focus are already elements' own events; it can be its own record if it is wanted. |
Consequences
- One behaviour can be written once, fixed once and tested once, and the kit's calendar code halves.
- A component's script stays the only place behaviour is written, so there is still one way to write it.
- The compiler must know each behaviour's return shape before it rewrites a caller, so behaviours are analysed before the files that call them, and a cycle is an error (E0176).
- A behaviour is tested today through a page or component that calls it (
duolith test, the conformance fixtures, the kit's browser tests). Calling one without placing any markup, through@duolith/testing, was planned and has not been built; it needs its own work. - Ten new diagnostic codes (E0171 to E0180), with conformance fixtures, reference docs and a change note.
Update: details the implementation settled
Building it settled details the record above left open. None changes what Mik chose:
- Which functions are behaviours. An exported function is a behaviour when its body calls
state,derived,effector another behaviour at its top level. Every other export is a plain helper, called anywhere and never rewritten, soaddMonthssits besidecalendarand both are imported from one file. A behaviour may return nothing; when it returns, it is onereturn { ... }(E0173). - The input. A behaviour takes one plain parameter (
input) with its type. A destructured parameter, like an assigned input, is E0174, because destructuring would read each input once and stop it being live. - E0175 also covers file-level state.
state,derived,effector a behaviour call at the top of a behaviour file, outside any function, would be shared by every caller, so it is refused with props(), guard() and component and kit imports. - E0177 also covers an import of a file that is not there, and a namespace import (
import * as d from ...), besides the default import. - Imports name the whole file. A
.behaviour.tsfile is imported with its extension, like a.behaviour.duofile, so the script view's TypeScript options allow.tsextensions; a value import from any other local.tsfile is still E0356, reported by the compiler. - The kit's behaviours live in
packages/kit/parts/behaviours/, and a part imports one as./behaviours/calendar.behaviour.duo. An app does not import them from@duolith/kit;duolith add DatePickercopies the part and each kit behaviour it imports, at any depth, into the app'scomponents/andbehaviours/, points the part's import at../behaviours/, and keeps a behaviour file the app already has. - Not done yet:
duolith createdoes not make a first behaviour file;@duolith/testinghas no way to call a behaviour without placing markup, so the Consequences above say how a behaviour is tested meanwhile; in the editor, a.behaviour.tsfile is checked by TypeScript through its view and through the pages that import it, while its own E0171 to E0180 problems are reported byduolith checkandduolith build.
Update 2: the rules a review added
A review found ways a behaviour could compile and then silently stop following its state, or fail at run time. Each is now refused by the build with an explanation and a fix, or made to work. Status stays Proposed: these need Mik's approval with the rest.
- A result kept as one object stays live. The emitted behaviour returns an object of accessors (
get count(),set count(v)for a state, a getter alone for a derived value, the function itself for a function), socal.countreads the cell each time andcal.count = 2writes it. An unpacked result reads through the same object:let { count, double } = counter(...)keeps a hiddenduolith$behaviourNfor the call and rewrites eachcountto a read of it, so nothing is copied. - Unpacking may rename, give defaults and keep a rest name.
let { count: shown = 0, ...rest } = counter(...)works:shownreads the result, falling back to the default while it isundefined, andrestis the result object. Unpacking deeper than the returned names, an array pattern or a computed key is E0178, because those read once. - Copying a whole result is E0178. At the top of a script, spreading a result (
{ ...cal }) or unpacking a kept result again (let { count } = cal) reads each value once. Reading one through another name for the result (let same = cal; same.count) is followed, sosame.countis checked ascal.countis. Passing the object on whole, to a function or a prop, is allowed. - A returned derived value is read-only through the object too.
cal.double = 1,cal["double"] = 1anddelete cal.doubleare E0109 from the analyzer; TypeScript also sees the derived value as read-only, because the script view writes it as a getter, and its TS2540 is reported as E0109. - The input is one object literal written in the call (E0179). A variable, a spread or extra arguments would be read once.
- The input is read where it is used (E0174). Besides an assignment, writing it deeper (
input.range.from = x), through another name for it (const same = input), or unpacking it at the top of the body (let { start } = input) is refused. - A behaviour has one form (E0180). A function that makes state written as an arrow or function expression, an
asyncor generator behaviour (which would make state after its caller has gone on), a second parameter, a default export in a behaviour file, andstate,derivedoreffectimported under another name are refused. - State is known by what it resolves to. A call makes state only when
state,derivedoreffectresolves to the import from@duolith/client, so a local function of that name is a plain helper. A behaviour call is known by its binding too: a type reference (typeof counter) is not a call, and a shadowing local is not the behaviour. - More ways to export and call.
export { level as lift }, a re-export from another behaviour file (export { counter as tally } from "./counter.behaviour.ts", orexport *) and a call to another behaviour of the same file, exported or not, all work, and their results keep their kinds. - E0175 covers every declarator of a statement (
let a = 1, shared = state(0)), and state inside an object at the top of the file. - E0177 covers more. An import that names nothing (
import "./x.behaviour.ts",import {} from ...) is refused. The check for a.ts,.mtsor.ctsfile that imports or re-exports a behaviour runs over the whole project (every folder butnode_modules,dist,generated,targetand hidden ones), whether or not a page reaches the file, as does the check for a misspelt name or both forms side by side. One import is reported once. - E0171 looks at every declarator of a statement, so
let a = 1, b = counter()is not taken for a nested call. - The kit's DatePicker keeps computing
todayper instance inside its setup, as the old script did; moving it to the top of the behaviour file would be file-level state (E0175). - Known gap: TypeScript's read-only does not hold across assignment, so passing a result to a parameter typed
{ double: number }and writing it there is not caught. A renamed import ofstatein a page or component (outside behaviour files) was already not recognised before this record and is left to its own fix.