Search by

trail / editor

dodgycoffee

Markdown and page editor for trail

Package info

source.tube/brindly/trail-editor

Issues

Type:trail-addon

pkg:composer/trail/editor

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

0.5.0 2026-11-21 20:51 UTC

This package is auto-updated.

Last update: 2026-11-21 20:53:19 UTC


README

A markdown based editor for trail

install

composer require trail/editor
php trail/trail editor::install

editor::install copies editor js + css into web/assets. Will need to be run after updates too, or add it to composer so it'll auto

use

It's basically 3 editors in one. editor, editor--simple, and editor--writer with their own contained assets to keep bloat off the page

<?= $this->insert('editor/field', ['name' => 'body', 'label' => 'Body', 'value' => $post->body]) ?>
{{ view('editor/field', {name: 'body', label: 'Body', value: post.body, max: 10000}) }}

Field options are name, label, value, preset, max, rows, id, class (on preview for styles), simple, drafts (on by default), uploads, and suggestions (both on by default once set up). Without js enabled it's a normal textarea

simple is a plain textarea with tools at the bottom right. Great for comments, replies, etc. Out of the way

<?= $this->insert('editor/field', ['name' => 'reply', 'label' => 'Reply', 'simple' => true, 'max' => 500]) ?>

shortcuts

Mod is ⌘ on macOS and ctrl elsewhere

Mod+B          bold
Mod+I          italic
Mod+Shift+X    strikethrough
Mod+K          link
Mod+E          code
Mod+S          save
Mod+Enter      save
Mod+Z          undo
Enter          continues list + quote
Tab            nest list item. Shift+Tab to undo
Escape         magic

toolbar presets

full and simple are built-in, but you can add your own groups

'editor' => [
    'presets' => [
        'wiki' => [['heading', 'bold', 'italic', 'link', 'code', 'table'], ['fullscreen']],
    ],
],

Tools options include heading, bold, italic, strike, link, image, code, quote, bullets, numbers, table, rule, fullscreen, mention, and emoji. image needs uploads, mention an @ needs a source, and emoji a folder source

drafts

Drafts auto save to localStorage and last about a week per page/field. It's a simple system. You can technically hook in your own server auto-save

previews

THere's a live preview. Tap the preview button and see what the markdown will look like. Register your own in an addon if you want

$box->factory(Markdown::class, static function (): Markdown {
    return new Markdown(ids: true)->inline(new Mentions());
});

uploads

Drag and drop, paste from clipboard, or just a selector. They all work. Images will be shrunk down and saved to a trail/storage disk, and set as upload: refs to render

final readonly class SignedInOwner implements Owner
{
    public function __construct(private Visitor $visitor) {}

    public function id(Request $request): ?string
    {
        return null === $this->visitor->user ? null : (string) $this->visitor->user->id;
    }
}

Theres a uploads::prune cli job you can setup to run daily. It will auto-delete any asset that nothing is using after 8 days

suggestions

@, [[, and : can also bring up suggestion/picker. But you have to actuall map something to it so it knows what to suggest

'suggest' => ['@' => People::class, '[[' => Pages::class],

final readonly class People implements Source
{
    public function __construct(private Connection $database) {}

    public function find(string $query, Request $request): array
    {
        $found = [];
        $rows = $this->database->all('select username from users where username like ? limit 8', ["{$query}%"]);

        foreach ($rows as $row) {
            $found[] = new Suggestion($row->username, "@{$row->username}");
        }

        return $found;
    }
}

Suggestion accepts a label, insert text, and an optional hint + image url

custom emoji

You can easily add emoji by just dropping files in web/assets/img/emoji. The tag pulls from the filename. Accepts png, webp, gif, avif, and svg. they use the emoji class to format

img.emoji {
    height: 1.375em;
    vertical-align: -.3em;
}

writer

This one took fkn forever. It's a writer field type. Kind of like what you see on medium, but better and more flexible.

It does live preview as you type, brings up tool when text is selected, accepts markdown directly and renders it, and even has a handy + for adding sections and blocks.

<h1 data-page-title><?= e($page->title) ?></h1>

<?= $this->insert('editor/page', [
    'fields' => ['markdown' => $page->body, 'title' => $page->title],
    'save' => $canEdit ? "/wiki/{$page->slug}" : null,
]) ?>

Title and subtitle mapped to whatever data-page-title and data-page-subtitle are. Saving will include a hash so people get warnings when someone else made an edit, to prevent overwriting

if (SavePage::isStale($request, $fields)) {
    return SavePage::conflict($fields);
}

$posted = SavePage::posted($request, array_keys($fields));

// store
return SavePage::done($posted);

flat file

You can also store pages as flat .md instead. I use Frontmatter from trail/markdown to keep the extra keys intact

[$meta, $body] = Frontmatter::split(file_get_contents($file));
$fields = ['markdown' => $body, ...$meta];

if (SavePage::isStale($request, $fields)) {
    return SavePage::conflict($fields);
}

$posted = SavePage::posted($request, array_keys($fields));
$page = Frontmatter::join(array_diff_key($posted, ['markdown' => true]), $posted['markdown']);

file_put_contents("{$file}.tmp", $page);
rename("{$file}.tmp", $file);

return SavePage::done($posted);

extensions

Obviously i added extension support. You can do it from your addons register(). There's 2 types. markdown + blocks

Markdown is a trail/markdown Block or Inline element. For adding custom syntax to any editor

Blocks are exclusive to writer's + menu. Its fairly flexible

Editor::extend(new Callout());

final readonly class Callout implements Block, Extension, Editable
{
    public function name(): string { return 'callout'; }
    public function label(): string { return 'callout'; }
    public function icon(): string { return Editor::icon('info'); }

    // Block: starts(), parse(), tags(). mark parts with data-field="title"
    public function fields(): array
    {
        return [
            'kind' => Field::select('kind', ['tip' => 'tip', 'warning' => 'warning']),
            'title' => Field::text('title', 'Heads up'),
            'body' => Field::markdown('body'),
        ];
    }

    public function read(string $source): array { /* source to values */ }
    public function write(array $values): string { /* values to source */ }
}

Available fields are text, markdown, image, link, select, and toggle

You can also do more advanced stuff like adding your own JS interactions. + fires writer:block. The baked in Unsplash feature was done as an extension just to build the system and provide a working example

document.addEventListener('writer:block', async (event) => {
    let { name, insert } = event.detail

    if ('stamp' !== name) {
        return
    }

    event.preventDefault()
    await insert('![stamp](/img/stamp.png)')
})

embeds

Currently supports YouTube, Vimeo, and Bunny Stream links. Anything else just syats as a link. And ampty block won't render at all so it isn't broken

@[embed](https://youtu.be/dQw4w9WgXcQ?t=42)

If you enable Unsplash (requires an API key) the + gets an Unpslash photo search built in. It'll hotlink and credit any photo automatically. Setting app names you in Unsplash's referral links

'unsplash' => ['key' => App::env('UNSPLASH_ACCESS_KEY') ?? '', 'app' => 'my-site'],

styles

The editor is tied to some css vars you can overwrite to style it more how you like. There is a light and dark mode already using color-scheme. If you need more than that you can just build your own editor using the trail/markdown package as a parser

[data-editor] {
    --accent: #2563eb;
    --box: #fff;
    --box-line: #c8c8c8;
    --radius: .25rem;
    --button: transparent;
    --button-hover: #ececec;
    --button-on: #e4e4e4;
    --button-radius: .25rem;
}

config

'editor' => [
    // preview route
    'routes' => true,

    // route prefix
    'prefix' => '/editor',

    // gates on editor routes [eg RequireUser::class]
    'gates' => [],

    // longest preview [bytes]
    'longest' => 200_000,

    // custom toolbar presets
    'presets' => [],

    // image uploads
    'uploads' => [

        // who can upload [class, null is off]
        'owner' => null,

        // storage disk [null for default]
        'disk' => null,

        // folder on disk
        'folder' => 'editor',

        // markdown for prune [eg 'posts.body', 'content/**/*.md']
        'in' => [],

        // save as [webp, jpg, png, avif, keep]
        'type' => 'webp',
        'quality' => 82,

        // widest [px]
        'width' => 2000,

        // largest upload [bytes]
        'maxBytes' => 10_000_000,

        // largest pixels [null for 25 million]
        'maxPixels' => null,

        // per person per day [null for no cap]
        'daily' => ['files' => 100, 'bytes' => 100_000_000],
    ],

    // custom emoji [false is off]
    'emoji' => 'web/assets/img/emoji',

    // suggestion sources [trigger => class]
    'suggest' => [],

    // youtube + vimeo embeds
    'embeds' => true,

    // unsplash photos
    'unsplash' => false,
],