Lapis Docs

Extending

Plugins

A plugin is a Composer package that requires lapis/cms and contains a Lapis\Plugins\Plugin class. Install it with composer require …, and Lapis finds it by itself. There is nothing to register.

composer require lapis/opening-hours
./lapis plugins          # the installed plugins and what they add

To switch a plugin off without removing it, name it in lapis.config.php:

// lapis.config.php
plugins: ['opening-hours' => false],

The plugin class

A plugin class has a name, a title and a register() method. register() gets an Extend object, and every extension point is one call on it:

<?php // src/OpeningHoursPlugin.php
final class OpeningHoursPlugin implements Plugin
{
    public function name(): string { return 'opening-hours'; }
    public function title(): string { return 'Opening hours'; }

    public function register(Extend $lapis): void
    {
        $lapis->settings(['hours_note' => new Text('Note')]);             // Settings panel, own group
        $lapis->blockType('hours', new BlockType(                          // <x-block type="hours" …>
            label: 'Opening hours',
            fields: new Rows('Opening hours', fields: [                    // how editors edit it: no JS
                'days' => new Text('Days'),
                'open' => new Time('Opens'),
                'closed' => new Toggle('Closed'),
            ]),
            render: fn (mixed $value, array $attributes): string => '…',  // escape it!
        ));
        $lapis->panel('opening-hours', 'Opening hours', settings: ['hours_note']); // a toolbar panel: no JS
        $lapis->pageType('event', 'Event');
        $lapis->middleware(new NoIndex(), path: 'internal/*');            // like the keys of _middleware.php
        $lapis->table('closed-days', new Table(                            // like a data/*.php file
            label: 'Closed days',
            columns: ['day' => new Date('Day', required: true)],
        ));
        $lapis->pages(__DIR__ . '/../pages', prefix: 'opening-hours');     // like the pages/ folder
    }
}

The plugin's settings appear in a group of their own in the Settings panel, named after the plugin (or pass group: to settings()). BlockType also accepts tag: for the default wrapper element ('div' by default).

A mistake in a plugin's own code, such as a block type name that is no slug or a panel name another plugin took, throws Lapis\SiteCodeWasInvalid when the plugin loads: a bug to fix, so it is not declared with @throws.

A plugin keeps its files apart, as a site does:

src/          the PHP classes (the PSR-4 folder)
lang/         the texts: messages.en.yml, messages.hu.yml, one file per language
components/   the view components (x-*.view.php)
pages/        routed pages (optional)
editor/       editor scripts (optional)

A plugin's texts are under a key of its own (opening_hours.title), and Lapis has Tempest discover lang/ and components/ like src/. Another language is one more file: copy messages.en.yml to messages.de.yml and translate the values. A label is then the key, new Date('opening_hours.day'), and it is shown in the site's language. The site's own files win over the plugin's, see Translations.

Editing without JavaScript

Most plugins describe how their content is edited in PHP, with the field types of the global settings: Text, Textarea, Time, Toggle, Select, Url, Image, Color, Rows and the rest. The editor draws them in its own panel, the same way on phones and in every language.

A block type's name must be free: the built-in names (text, richtext, image, link and repeat, the order of an <x-repeat>'s items) and those of other plugins are refused when the plugin loads.

Block types with fields

When a block type has fields, clicking the block opens a panel with those fields. Save stores the value, and the server renders the block again with render. The shape of the value follows the fields:

  • With fields: new Rows(…), or any single field, the value is that field's value, for example a list of rows.
  • With fields: ['title' => new Text('Title'), 'urgent' => new Toggle('Urgent')], the value is an array with those keys.

Before a value is saved, the field types clean it. A Time becomes "HH:MM" or null, a Toggle a boolean, a Select one of its options, and a Url or an Image a safe address. Rows left empty are dropped, and a field left empty has no value, so the template's default shows. For rules of your own, sanitize: fn (mixed $value): mixed runs after that. The opening hours plugin uses it to drop rows without days or times.

Panels

$lapis->panel($name, $label, settings: [...], title: …) adds a button under "More" in the toolbar. It opens a panel that edits the listed global settings, the plugin's own or the site's, and saves them like the Settings panel does. Only admins may save settings, so only admins see the button.

Tables and pages

A plugin's table is created, migrated and edited like a data table of the site, and a site file with the same name in data/ replaces it.

The plugin's pages/ folder is routed under the given prefix, with route files, templates with #[Get] loaders and page functions. When the site has its own file for the same route, the site wins. To protect the plugin's pages, add middleware for their path: $lapis->middleware(…, path: 'opening-hours/*').

Tempest also discovers the components in components/, the console commands and the #[EventHandler]s of the plugin package, as in any Tempest package.

Events

Lapis dispatches events on Tempest's event bus, from the editor, the console and your own code alike. To listen, put Tempest's #[EventHandler] on a method that takes the event:

use Lapis\Events\BlocksPublished;
use Tempest\EventBus\EventHandler;

final class NotifyTeam
{
    #[EventHandler]
    public function onPublished(BlocksPublished $event): void
    {
        // …
    }
}

These events are in Lapis\Events:

Event When
PageCreated, PageUpdated, PageDeleted A page record was created, changed (with the old values) or deleted.
PagesReordered Pages were put in a new order (the ids, in order).
BlockSaved, BlocksPublished, DraftsDiscarded A block draft was saved, drafts were published or discarded.
SettingsSaved The global settings were saved.
MediaUploaded, MediaReplaced, MediaDeleted A file of the media library changed.
MediaUpdated A file's alt text, caption or focus point changed (changed lists which, movedFocus() tells a moved focus point).
DataChanged A record of a data table changed.
FormSubmitted A visitor sent a form.
UserChanged, SignedIn An account changed, someone signed in.
PageRendered A full page was rendered. $event->addToHead($html) adds before </head> (JSON-LD, a style), $event->addToBody($html) before </body> (a banner, a script), and $html itself can be changed.
EditorStateBuilding The editor's data is being built. $event->plugin($name, $data) hands data to the plugin's editor module, which reads it with lapis.plugin($name).
AssetsCompiling ./lapis assets:compile (and so ./lapis deploy) is about to write public/assets.
DoctorChecking ./lapis doctor is collecting its checks.

Build steps and checks

The last two events are for plugins with a build step or checks of their own:

#[EventHandler]
public function build(AssetsCompiling $event): void      // ./lapis assets:compile, so ./lapis deploy too
{
    if (! $this->compiler->build()) {
        $event->fail('Tailwind: the build failed');         // nothing is compiled, deploy stops
    }
}

#[EventHandler]
public function check(DoctorChecking $event): void       // ./lapis doctor (and the end of deploy)
{
    $event->check($this->built() ? 'ok' : 'warn', 'Tailwind', 'built: assets/build/app.css');
}

AssetsCompiling runs before public/assets is written, so the files a plugin writes into assets/ are versioned and compiled with the rest. DoctorChecking takes 'ok', 'warn', 'info' or 'fail', and a 'fail' makes doctor exit with an error. $event->production tells whether ENVIRONMENT is production.

Editor modules

When fields are not enough, for a map or a drag-and-drop schedule, a plugin brings its own editing interface. It is an ES module, given as editor: of the block type or with $lapis->editorScript($file), and it is only loaded for signed-in editors. The module gets the editor's lapis object:

export default function (lapis) {
    const { h, t } = lapis;

    lapis.registerPanel('hours', {
        label: t('opening_hours.title'),     // toolbar button
        render(body, panel) {                // panel.footer(...buttons), panel.close()
            body.append(h('p', {}, t('opening_hours.hello', { name: lapis.user.name })));
        },
    });

    lapis.registerBlockType('hours', {
        async edit(el, value) { return newValue; },   // null = cancel; the server renders it after saving
    });
}

A block type registered in a module wins over the fields of its PHP definition. The lapis object has these members:

lapis.
version Editor API version (1).
h(tag, attrs, ...children) Makes an element.
t(key, params) A text in the site's language: a key of a lang/messages.<locale>.yml or app/localization.<locale>.yml (MessageFormat 2), or the key itself when it has none.
api(path, body) Calls the editor API (/_lapis/api/…) with the editor's token.
toast(text, 'error'?) Shows a short message.
user, locale, page The signed-in user, the language and the page being edited (read-only).
can(ability) Whether the user may do 'settings', 'users', 'redirects' or 'log' (admins only).
plugin(name) What the plugin's PHP side added with EditorStateBuilding::plugin().
settings.get(key), await settings.set(key, value) Reads a global setting. set saves one key or an object of { key: value } pairs (admins only).
registerPanel(name, def) Adds a toolbar panel (label, render(body, panel), optional title, meta).
registerBlockType(type, def) Adds a custom block editor (async edit(el, value)).

Example and tests

lapis/opening-hours is a complete plugin with its own tests, and it uses almost every extension point (all but pages). It is a good start for your own plugin: copy it, then rename the package, the namespace and name().

composer require lapis/opening-hours

For tests, Lapis\Testing\LapisTestCase has assertPluginLoaded(), renderBlock() and editorState(). To catch events, use Tempest's $this->eventBus. See Testing.