# Scripts that compose

> Three behaviours on one object, in three files, with no imports between them: spin publishes how to stop it and toggle reaches it by name.

Example `script-compose`, running at https://nacatamalon.com/en/examples/script-compose. The whole catalogue: https://nacatamalon.com/llms/examples.md.

Three behaviours on one object, in three files, with **no import between them**. Two only share the object: `spin` turns it and `breathe` resizes it, and neither knows the other exists. The third needs to call into one, which sharing the object does not cover, so `spin` returns a way to be stopped, its api, and `toggle` reaches it with `useScriptApi('spin')`. Press **Space**.

**Read the order in `index.ts`.** The consumer is attached before the publisher, and it works anyway: `useScriptApi` hands back a way to ask rather than the answer, so the question is asked once everything is running and the order of two lines cannot decide whether it works. `requires: ['spin']` is the half of that relationship a tool can read: it reports, and never stops a behaviour from running.

## Code

`index.ts`:

```ts
import { registerSpin } from './scripts/spin';
import { registerToggle } from './scripts/toggle';
import { registerBreathe } from './scripts/breathe';
import { createGame } from 'nacatamalon';
import { WIDTH, HEIGHT } from './settings';
import { Level } from './scenes/demo';

registerSpin();
registerToggle();
registerBreathe();

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: '#14121c',
});

// Declare Scenes
game({
    Level
});
```

`components/piece.ts`:

```ts
import { createSprite, useScript } from 'nacatamalon';

export const Piece = () => {
    createSprite({
        tint: '#e5c93b',
        width: 70,
        height: 70,
        transform: {
            x: 170,
            y: 100
        }
    });

    // The CONSUMER first, on purpose: the three run in this order, in one pass, and the one that
    // needs 'spin' is attached before the one that publishes it. It still works, because what
    // useScriptApi hands back is asked at the moment of use.
    useScript('toggle');
    useScript('spin', {
        speed: 2.2
    });
    useScript('breathe');
};
```

`scenes/demo.ts`:

```ts
import { createScene, createText, useLoadBitmapFont, useSpawn } from 'nacatamalon';
import * as Settings from '../settings';

import { Piece } from '../components/piece';

export const Level = () => {
    const font = useLoadBitmapFont(Settings.FONT);

    useSpawn(Piece)();
    createText({
        text: 'SPACE: STOP AND START',
        font,
        style: {
            fontSize: 8
        },
        tint: '#8fa4c4',
        transform: {
            x: 16,
            y: 176
        },
    });

    return createScene();
};
```

`scripts/breathe.ts`:

```ts
import { registerScript, useUpdate, sizeOf } from 'nacatamalon';

export const registerBreathe = () => {
    registerScript('breathe', (self) => {
        const [sprite] = self.drawables;

        if (sprite === undefined || sprite.type !== 'sprite') {
            return;
        }

        const base = sizeOf(sprite).width;

        useUpdate((_delta, time) => {
            const scale = 1 + Math.sin(time * 2) * 0.15;

            sprite.width = base * scale;
            sprite.height = base * scale;
        });
    });
};
```

`scripts/spin.ts`:

```ts
import { registerScript, useUpdate } from 'nacatamalon';

export const registerSpin = () => {
    registerScript<{ speed: number }>('spin', (self, props) => {
        const [sprite] = self.drawables;

        if (sprite === undefined || sprite.type !== 'sprite') {
            return;
        }

        let running = true;

        useUpdate((delta) => {
            if (running) {
                sprite.transform.rotation += props.speed * delta;
            }
        });

        // What it returns is its api: the others on the object reach it as useScriptApi('spin'), the
        // name it is registered under, the same word as in requires: ['spin'].
        return {
            stop: () => {
                running = false;
            },
            start: () => {
                running = true;
            },
            isRunning: () => running,
        };
    }, [
        {
            key: 'speed',
            label: 'Turn (rad/s)',
            type: 'number',
            default: 1.6,
            step: 0.2
        },
    ]);
};
```

`scripts/toggle.ts`:

```ts
import { registerScript, useKeyboard, useScriptApi, useUpdate } from 'nacatamalon';

export const registerToggle = () => {
    registerScript('toggle', () => {
    // Asked for here and read later. useScriptApi gives back a way to ask, not the answer, so it does
    // not matter that this behaviour is attached BEFORE the one it needs.
        const spin = useScriptApi<{ isRunning: () => boolean; start: () => void; stop: () => void }>('spin');
        const keys = useKeyboard();

        useUpdate(() => {
            if (!keys.justPressed(' ')) {
                return;
            }

            const api = spin();

            if (api === null) {
                return;
            }

            if (api.isRunning()) {
                api.stop();
            } else {
                api.start();
            }
        });
        // Saying what it needs is what turns "does nothing" into something somebody can read. It never
        // stops the behaviour from running: a half built object must not behave like a broken one.
    }, {
        requires: ['spin']
    });
};
```

`settings.ts`:

```ts
export const WIDTH = 340;
export const HEIGHT = 200;
export const FONT = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png',
};
```
