Search by

silarhi / app-js-bundle

guillaume-sainthillier

load_page Twig function, TypeScript enums and typed form shapes for Symfony, the PHP companion to @silarhi/app-js

Package info

github.com/silarhi/app-js-bundle

Type:symfony-bundle

pkg:composer/silarhi/app-js-bundle

Statistics

Installs: 778

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 1

v0.11.3 2026-11-27 11:13 UTC

README

Latest Stable Version Total Downloads License PHP Version CI Status Coverage

App JS Bundle

The PHP companion to @silarhi/app-js for Symfony.
load_page(), PHP enums and constants as TypeScript modules, and form shapes that check formView() paths when compiling.

Features

  • load_page(), the Twig function behind the data-page listener;
  • app-js:dump-enums, the PHP enums marked #[EnumToJs] as TypeScript or JavaScript modules;
  • app-js:dump-constants, the public constants of the classes marked #[ConstantsToJs], so a limit lives in one place;
  • app-js:dump-forms, the shape of the form types marked #[FormToJs], for formView<Shape>() to check form paths and choice values when compiling;
  • app-js:dump, every dump at once;
  • FormViolations and FormViolationsResponse, the errors of a form keyed by the paths formView() reads.

Install

composer require silarhi/app-js-bundle
// config/bundles.php
return [
    // ...
    Silarhi\AppJsBundle\SilarhiAppJsBundle::class => ['all' => true],
];

Without the bundle

The bundle class is optional: an application without the framework, symfony/dependency-injection or symfony/http-kernel builds the dumpers and the commands by hand. fromDirectories() finds the enums and the classes marked #[EnumToJs] and #[ConstantsToJs] the way the bundle does, from directories and their namespace prefix:

use Silarhi\AppJsBundle\Command\DumpCommand;
use Silarhi\AppJsBundle\Command\DumpConstantsCommand;
use Silarhi\AppJsBundle\Command\DumpEnumsCommand;
use Silarhi\AppJsBundle\Constants\ConstantsDumper;
use Silarhi\AppJsBundle\Enum\EnumDumper;
use Silarhi\AppJsBundle\Twig\AppJsExtension;
use Silarhi\AppJsBundle\Writer\Format;
use Silarhi\AppJsBundle\Writer\GeneratedFilesWriter;

$writer = new GeneratedFilesWriter();
$enumDumper = EnumDumper::fromDirectories([__DIR__ . '/src/Enum' => 'App\\Enum'], Format::JavaScript);
$constantsDumper = ConstantsDumper::fromDirectories([__DIR__ . '/src/Model' => 'App\\Model'], Format::JavaScript);

$application->addCommands([
    new DumpEnumsCommand($enumDumper, $writer, __DIR__ . '/assets/js/enums'),
    new DumpConstantsCommand($constantsDumper, $writer, __DIR__ . '/assets/js/constants'),
    new DumpCommand(), // app-js:dump runs the dumps registered in the same application
]);

$twig->addExtension(new AppJsExtension($translator)); // load_page(), the translator is optional

fromDirectories() loads every file of the directories, and throws the errors the bundle reports when the container builds: two modules with the same name, an #[EnumToJs] method that is not public, is static or takes a required parameter.

Pages

<div {{ load_page('party', {id: party.id}) }}></div>
<div {{ load_page(['party', 'address']) }}></div>

renders the data-page and data-page-params attributes that @silarhi/app-js reads to load the page modules.

The params are JSON, with the values JSON cannot encode on its own turned into what a page reads:

<div {{ load_page('party', {form: form, startsAt: party.startsAt, status: party.status, title: t('party.title')}) }}>
  • a form view is its id, for formView(form);
  • a date is in ISO 8601 (2026-11-26T10:30:00+01:00);
  • an enum case is its value, or its name for a unit enum;
  • a translatable message (t('party.title')) is translated in the current locale.

Enums

use Silarhi\AppJsBundle\Attribute\EnumToJs;

#[EnumToJs]
enum LeaseStatus: string
{
    case Draft = 'draft';
    case Active = 'active';
}
bin/console app-js:dump-enums

writes assets/js/enums/LeaseStatus.ts:

export const DRAFT_NAME = 'Draft'
export const ACTIVE_NAME = 'Active'

const LeaseStatus = Object.freeze({
    Draft: 'draft',
    Active: 'active',
})
export default LeaseStatus

export type LeaseStatusValue = (typeof LeaseStatus)[keyof typeof LeaseStatus]

Only the enums marked #[EnumToJs] are dumped (#[EnumToJs(name: 'Status')] renames the module). Unit enums take their case names as values. LeaseStatusValue is the union of the values ('draft' | 'active'); with format: js, it is a JSDoc @typedef.

The results of the methods named in methods are dumped too, one map per method, by case value, so the page reads the label or the color of a value it got:

#[EnumToJs(methods: ['label', 'color'])]
enum LeaseStatus: string
{
    // ...

    public function label(): TranslatableMessage
    {
        return t('lease_status.' . $this->value);
    }

    public function color(): string
    {
        return self::Active === $this ? 'success' : 'secondary';
    }
}
export const LABEL = Object.freeze({
    draft: 'lease_status.draft',
    active: 'lease_status.active',
})

export const COLOR = Object.freeze({
    draft: 'secondary',
    active: 'success',
})

A method is public, not static, and takes no required parameter; its export is its name in upper snake case. A result is dumped as a constant is (see Constants), and a translatable message as its key, for the page's translator: the dump never depends on the locale.

On Symfony 7.3+, the bundle finds them through autoconfiguration, wherever they live: an enum must be loaded by a service resource of the application, as the default App\ resource of config/services.yaml loads src/, and not sit under one of its exclude paths. Symfony 6.4 to 7.2 registers no enum in the container: list their directories in enums.paths instead (see Configuration).

Constants

use Silarhi\AppJsBundle\Attribute\ConstantsToJs;

#[ConstantsToJs]
final class MediaUpload
{
    public const MAX_SIZE = 2_000_000; // the #[Assert\File(maxSize: self::MAX_SIZE)] of the class, and the page's text
    public const MIME_TYPES = ['image/jpeg', 'image/png'];
    private const MAX_PIXELS = 25_000_000; // not dumped
}
bin/console app-js:dump-constants

writes assets/js/constants/MediaUpload.ts:

// Generated by app-js:dump-constants from App\Model\MediaUpload, do not edit
export const MAX_SIZE = 2000000
export const MIME_TYPES = Object.freeze(['image/jpeg', 'image/png'])

Only the public constants are dumped, in their order: a class keeps out what is not the page's business by making it private or protected. A value is a scalar, null, an enum case (its value, or its name for a unit enum) or an array of those: a list becomes a frozen array, a map a frozen object. Any other object fails the dump. #[ConstantsToJs(name: 'Limits')] renames the module. An enum may carry the attribute too: its constants are dumped, not its cases (#[EnumToJs] does).

The classes are found through autoconfiguration, like the enums: a class must be loaded by a service resource of the application (the default App\ one loads src/). For a class no resource loads (an excluded src/Entity, for instance), list its directory in constants.paths (see Configuration).

Form shapes

use Silarhi\AppJsBundle\Attribute\FormToJs;

#[FormToJs]
final class PartyType extends AbstractType
{
    // name, address (an AddressType), phones (a collection of PhoneType)
}
bin/console app-js:dump-forms

writes assets/js/forms/PartyForm.ts:

// Generated by app-js:dump-forms from App\Form\PartyType, do not edit
import type { FormCollection, FormField } from '@silarhi/app-js/form'

export interface PartyForm {
    name: FormField<HTMLInputElement, string>
    country: FormField<HTMLSelectElement, string | null>
    status: FormField<HTMLSelectElement, 'draft' | 'active' | null>
    tags: FormField<HTMLElement, ('work' | 'home')[]>
    address: {
        street: FormField<HTMLInputElement, string>
        city: FormField<HTMLInputElement, string>
    }
    phones: FormCollection<{
        number: FormField<HTMLInputElement, string>
    }>
}

and the page checks its paths when compiling:

import type { PartyForm } from '@/js/forms/PartyForm'

const form = formView<PartyForm>(container.querySelector('form'))
form.get('phones.0.number')
form.get('adress.city') // TS2345
form.get('country').element // HTMLSelectElement | null
form.field('tags').value // ('work' | 'home')[]
form.field('status').setValue('actve') // TS2345

The shape is read from the form view, as formView() reads the DOM: embedded forms are nested objects, collections take the shape of their prototype and rendered items, expanded choices are one field. The CSRF token is left out.

A field names the element it is rendered as and the value field().value reads, from the core type it extends:

  1. a choice (an entity, an enum, a country) is an HTMLSelectElement read as string | null, or string[] when multiple; expanded, the container of its options read as string, or string[] when multiple. Each string is the union of the values of its options when the form renders them all: an enum or a list of choices ('draft' | 'active' | null), '' included when a placeholder option is rendered. An entity, whose values are ids from the database, the Intl lists (country, currency, language, locale, timezone) and the selects of a date or a time, whose years follow the current one, stay string;
  2. a checkbox is read as a boolean, a radio as string | undefined (the checked value of its group);
  3. a textarea and the other core types rendered as an input are read as a string; a button has no value.

A type no core type tells about, or a field two variants render differently, is a plain FormField: an HTMLElement read as any value. A form type of your own whose widget renders something else than its parent, or a field whose behavior (bindField()) reads another value, should extend a type that renders and reads the same.

An embedded form whose type is marked #[FormToJs] too is a reference to its interface, imported from its file:

import type { FormCollection, FormField } from '@silarhi/app-js/form'
import type { AddressForm } from './AddressForm'
import type { PhoneForm } from './PhoneForm'

export interface PartyForm {
    name: FormField
    address: AddressForm
    phones: FormCollection<PhoneForm>
}

Only when the shapes are the same: an embedded form built with options that change its fields (->add('billingAddress', AddressType::class, ['with_country' => true])) keeps its own shape, written out.

Fields that are not always rendered

A form whose fields depend on its options or its data is built once per variant. A field missing from a variant becomes optional (siren?: FormField), so the page reads it with form.find().

A build without data (no variant, or a variant that gives none) gets the form's empty data, as Symfony computes it when the form is submitted empty: a new instance of its data_class by default, or what its own empty_data gives (a type whose class needs constructor arguments sets it). It is computed from the resolved options, so neither buildForm() nor a PRE_SET_DATA listener ever runs without data: a type that reads $options['data'], or whose listeners add fields, renders as the page of a new entity and needs no variant for an empty entity. Only an object counts: a type without data_class ([]), required: false (null) or an empty_data that fails (reading submitted fields, a class that cannot be built) keeps the build without data; -v tells which failed.

The options every build needs go in options, and the values an option takes in matrix: the form is built once per combination, with the options (2 × 2 = 4 builds here):

#[FormToJs(
    options: ['profile' => Profile::Landlord],
    matrix: [
        'person_type' => [PersonType::Company, PersonType::Individual],
        'new' => [false, true],
    ],
)]
final class PartyType extends AbstractType

A matrix builds every combination, so it fits options that change the form on their own. Builds that need objects or services, or options that only go together, come from a provider, a service by its class:

#[FormToJs(variants: LeaseFormVariants::class)]
final class LeaseType extends AbstractType

final class LeaseFormVariants implements FormVariantProviderInterface
{
    public function getVariants(): iterable
    {
        yield 'furnished' => new FormVariant(data: (new Lease())->setFurnished(true));
        yield 'unfurnished' => new FormVariant(['issuer' => new Issuer()]); // data: a new Lease, its empty data
    }
}

With options or a matrix too, each variant of the provider is built with each combination, its own options winning. A matrix stops at 64 builds.

Build the data in memory: the dump must give the same files on every machine, never read it from a database. An entity field is built without its choices, so the dump runs no query.

A field every build has, but the template renders only sometimes ({% if … %}{{ form_row(form.sharedAccount) }}, the others marked rendered with setRendered), is made optional by its dot path, so the shape does not promise it:

#[FormToJs(optional: ['sharedAccount', 'address.country', 'phones.{index}.fax'])]
final class SubscriptionType extends AbstractType

A path that matches no field of any build fails the dump. A field no build has cannot be made optional: its element and value come from a build, so give a variant that renders it.

Fields added by a PRE_SET_DATA listener only appear with data. app-js:dump-forms warns about each form type with such a listener and no build with data (given, or its empty data); #[FormToJs(dynamic: false)] silences it for listeners that add no field.

Other options: #[FormToJs(name: 'Party')] names the interface and its file (PartyForm for PartyType by default).

Configuration

# config/packages/silarhi_app_js.yaml
silarhi_app_js:
    enums:
        output_dir: '%kernel.project_dir%/assets/js/enums' # owned by app-js:dump-enums: its other .ts files are removed
        format: ts # or js
        # Symfony 6.4 to 7.2 only: the directories scanned for #[EnumToJs] enums, with their namespace prefix
        paths:
            '%kernel.project_dir%/src/Enum': 'App\Enum'
    constants:
        output_dir: '%kernel.project_dir%/assets/js/constants' # owned by app-js:dump-constants
        format: ts # or js
        # The directories scanned for #[ConstantsToJs] classes no service resource loads, with their namespace prefix
        paths:
            '%kernel.project_dir%/src/Entity': 'App\Entity'
    forms:
        output_dir: '%kernel.project_dir%/assets/js/forms' # owned by app-js:dump-forms
        format: ts # or js

JavaScript

With format: js, the enums are .js modules (the same code), and the form shapes .d.ts declarations: a shape is a type only. A JavaScript page reads it through JSDoc, and checkJs checks the paths:

/** @type {import('@silarhi/app-js/form').FormView<import('@/js/forms/PartyForm').PartyForm>} */
const form = formView(container.querySelector('form'))

Continuous integration

Commit the dumped files and check they are up to date:

bin/console app-js:dump --check --strict

app-js:dump runs app-js:dump-enums, app-js:dump-constants and app-js:dump-forms (when the form component is enabled), each one even when another fails, with the same options. --check fails when a file would change, without writing it, and lists those files; with -v, it shows their diff. --strict fails on the warnings of the forms.

Form errors

A form submitted through postForm() of @silarhi/app-js/http gets its errors back by the paths formView() reads:

use Silarhi\AppJsBundle\Http\FormViolationsResponse;

if ($form->isSubmitted() && !$form->isValid()) {
    return new FormViolationsResponse($form); // a 422
}
{
    "violations": [
        { "path": "", "message": "…" },
        { "path": "phones.0.number", "message": "This value is not valid." }
    ]
}
import { formView, showViolations } from '@silarhi/app-js/form'
import { postForm, violationsOf } from '@silarhi/app-js/http'

try {
    await postForm(element.action, element)
} catch (error) {
    // is-invalid and invalid-feedback on each field, the errors of the form itself first in it
    clear = showViolations(formView(element), violationsOf(error))
}

The path of an error is the one of the form it is attached to, the root form's name left out; '' holds the errors of the form itself. FormViolations::collect($form) gives the same list, for a response of your own.

License

MIT