silarhi / app-js-bundle
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
Requires
- php: >=8.2
- symfony/config: ^6.4 || ^7.0 || ^8.0
- symfony/console: ^6.4 || ^7.0 || ^8.0
- symfony/dependency-injection: ^6.4 || ^7.0 || ^8.0
- symfony/filesystem: ^6.4 || ^7.0 || ^8.0
- symfony/finder: ^6.4 || ^7.0 || ^8.0
- symfony/http-kernel: ^6.4 || ^7.0 || ^8.0
- symfony/string: ^6.4 || ^7.0 || ^8.0
Requires (Dev)
- ergebnis/composer-normalize: ^2.56.0
- friendsofphp/php-cs-fixer: ^3.95.30
- phpstan/extension-installer: ^1.4.3
- phpstan/phpstan: ^2.3.5
- phpstan/phpstan-strict-rules: ^2.1.1
- phpstan/phpstan-symfony: ^2.1.1
- phpunit/phpunit: ^11.5.57 || ^12.5.38 || ^13.4.1
- rector/rector: ^2.8.4
- symfony/error-handler: ^6.4 || ^7.0 || ^8.0
- symfony/form: ^6.4 || ^7.0 || ^8.0
- symfony/framework-bundle: ^6.4 || ^7.0 || ^8.0
- symfony/security-csrf: ^6.4 || ^7.0 || ^8.0
- symfony/twig-bundle: ^6.4 || ^7.0 || ^8.0
- twig/twig: ^3.30.0
Suggests
- symfony/form: Enables the form shapes (app-js:dump-forms)
- twig/twig: Enables the load_page Twig function
Provides
None
Conflicts
- symfony/form: <6.4
- twig/twig: <3.8
Replaces
None
README
App JS Bundle
The PHP companion to @silarhi/app-js for Symfony.
load_page(), PHP enums as TypeScript modules, and form shapes that check formView() paths when compiling.
Features
load_page(), the Twig function behind thedata-pagelistener;app-js:dump-enums, the PHP enums marked#[EnumToJs]as TypeScript or JavaScript modules;app-js:dump-forms, the shape of the form types marked#[FormToJs], forformView<Shape>()to check form paths when compiling.
Install
composer require silarhi/app-js-bundle
// config/bundles.php return [ // ... Silarhi\AppJsBundle\SilarhiAppJsBundle::class => ['all' => true], ];
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.
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
Only the enums marked #[EnumToJs] are dumped (#[EnumToJs(name: 'Status')] renames the module). Unit enums take
their case names as values.
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).
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> tags: FormField<HTMLElement, string[]> 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 // string[]
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:
- a choice (an entity, an enum, a country) is an
HTMLSelectElementread asstring | null, orstring[]when multiple; expanded, the container of its options read asstring, orstring[]when multiple; - a checkbox is read as a
boolean, a radio asstring | undefined(the checked value of its group); - 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.
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' 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-enums --check bin/console app-js:dump-forms --check --strict
--check fails when a file would change, without writing it; --strict fails on the warnings.
License
MIT