MMOframework
Why AI Playground Libraries Developers Agency
FR EN
Build a project live
Getting started · beginner

Your first .jhs element

One file for the markup, the code and the style: an element that lists your API's data and adds to it. - **You will have:** `<mmo-team-list>`, an element that reads `team.json`, lists the team, adds a member from its form and shows what the server refused; a Team page that uses it; and their tests. - **You need:** **Entities and a database** done: the team API, on its table. ## 1. One file, three parts A `.jhs` file is an element: its markup, its code in a `<script>`, its style in a `<style>`. mmo.client compiles it, in PHP, into the javascript the theme sends to the browser: no node, no bundler. Create `src/customElements/mmo-team-list.jhs`. Its root tag is the element: ```jhs from=src/customElements/mmo-team-list.jhs <mmo-team-list heading> <h2>{heading}</h2> ``` - **The name starts with `mmo-`**: the compiler refuses any other. - **Its attributes are written on the root tag**: `heading` is one. The element watches it, and `{heading}` shows its value. ## 2. The markup: bindings and loops The markup is html with a few additions. `{path}` shows a value of the element's data, and follows it when it changes. `<for path="members">` repeats its content for each member, and inside it `{name}` is that member's name: ```jhs from=src/customElements/mmo-team-list.jhs <ul> <for path="members"> <li><span class="name" set-textContent="{name}"></span> <span class="role" set-textContent="{role}"></span></li> </for> </ul> <if test="{empty}"><p class="empty">Nobody yet.</p></if> ``` **`set-textContent`, not `{name}`, for what users wrote.** `{path}` in text is inserted as html: a member named `<img src=x onerror=alert(1)>` would run code in every visitor's browser. `set-textContent="{name}"` sets the element's text: the same name shows as it was typed. Keep `{path}` in text for values you wrote yourself, like `heading`, which the page sets. `<if test="{empty}">` shows its content only while `empty` is true. ## 3. The code: a class The `<script>` holds one class, named after the element without `mmo-`, in PascalCase: `TeamList` for `mmo-team-list`. The compiler finds it by that name and makes it the element. ```js from=src/customElements/mmo-team-list.jhs class TeamList { init() { super.init(); this.load(); } /** @return {Promise<void>} the list read again from the server */ async load() { const response = await fetch(MMO.url('team.json'), {headers: {Accept: 'application/json'}}); const members = (await response.json()).data; this.view.set('members', members); this.view.set('empty', !members.length); } ``` - **`init()`** runs once, when the element is on the page; `super.init()` draws the markup. - **`this.view`** is the element's data. `set()` changes a value, and the markup bound to it follows: no code writes the list. - **`MMO.url('team.json')`**, never `'/team.json'`: the site is not always at the root of its domain. It is `\MMO\url()` on the javascript side. - **`.data`**: what the route returned, as in the controller's guide. The form calls a method of the class with `onsubmit="$this.add(event)"`: `$this` is the element. It sends the form to `team.json`, then shows the server's errors, or reads the list again: ```js from=src/customElements/mmo-team-list.jhs const response = await fetch(MMO.url('team.json'), {method: 'POST', headers: {Accept: 'application/json'}, body: new URLSearchParams(new FormData(form))}); const data = (await response.json()).data; if (response.status !== 201) { this.view.set('error', Object.values(data.errors ?? {}).join(' ')); return; } ``` The browser checks what it can (`required`), the server checks everything: the message it sends back for a name of spaces is the one shown. ## 4. The style: the design system's tokens The `<style>` applies to the element only: its page's styles do not reach inside, and its own do not leak out. It is written with the design system's tokens rather than colours and sizes of its own, so it follows the theme, the dark mode included: ```css from=src/customElements/mmo-team-list.jhs :host { display: block; @use lib::surface($radius.md); padding: $space.lg; } ``` `:host` is the element itself. `@use lib::surface(...)` gives it the background, border and radius of every card of the theme; `$space.lg`, `$color.line`, `$color.bad` are tokens. ## 5. Add it to the theme The theme compiles the framework's elements into one file, `www/bin/mmo.client.jhs.js`. Add the project's, in `src/bootstrap.php`: ```php from=src/bootstrap.php //the project's elements, compiled with the framework's into the theme's bundle: `$[..]` keeps the framework's \MMO\client\Theme::class => [ 'assets' => [ '?jhs' => ['$[..]', __DIR__ . '/customElements/**.jhs'], ], ], ``` `$[..]` keeps the list that was already there and adds to it; without it, the framework's own elements would be gone. In development, the theme compiles the bundle again whenever a `.jhs` file has changed. ## 6. Use it in a page A Team page, `src/pages/team/team.phtml` (with its `index.json`, as in **Pages**). The element is a tag like any other: ```php from=src/pages/team/team.phtml <h1>Our team</h1> <mmo-team-list heading="Engineering, sales and support"></mmo-team-list> ``` Open <http://localhost:8000/team>: the team, then the form. Add a member: the list is read again, sorted by name. Type only spaces as a name: the server's message shows under the form. ## 7. Test it A test cannot click, but it can check what fails most often: that the file compiles, that the theme bundles it, and that the page holds it. `tests/unit/TestTeamList.php`: ```php from=tests/unit/TestTeamList.php public function testTheElementCompiles(): void { //what the theme does to every .jhs of the bundle: a mistake in the file fails here, not in a browser $js = JHSCompiler::Shared()->compileText((string)file_get_contents(\MMO\filename('{AcmePortal}/customElements/mmo-team-list.jhs'))); $this->assertStringContainsString('mmo-team-list', $js); $this->assertStringContainsString('class MMO_TeamList_JHS', $js); } ``` ```bash phpunit ``` What the element does in the browser, you check in the browser, as in step 6. ## Common mistakes - **`{name}` for a value a user wrote.** It is inserted as html. Use `set-textContent="{name}"`. - **A tag without `mmo-`, or a class with another name.** The compiler stops: "must start with mmo-" or "cannot find class". - **A `render()` method in the class.** The compiler writes its own from the markup, and one of the two is lost. Name yours otherwise. - **`'?jhs' => [__DIR__ . '/customElements/**.jhs']` without `$[..]`.** Only your elements are left: every `<mmo-...>` of the framework stops working. - **`fetch('/team.json')`.** Wrong as soon as the site is in a folder. Use `MMO.url('team.json')`. ## Going further - Next: **Tests and verify**. - [JHS-Syntax](https://mmoframework.fr/en/documentation/mmo.client/mcp/JHS-Syntax.md), [Custom-Elements](https://mmoframework.fr/en/documentation/mmo.client/mcp/Custom-Elements.md) and [Styling](https://mmoframework.fr/en/documentation/mmo.client/mcp/Styling.md): every construct, the base classes, the tokens. - The demo of mmo.client, on the hub: every element of the framework, live, before you write your own.
Your next step

Try it yourself, or build the first one with us.

I'm a developer

Try it now. Nothing to install, nobody to call.

Build a project live

Read the guides

I lead a team

A working prototype of your AI product, on your data, in one week.

Prototype in a week

Open the page for your team