Repository navigation
[StimulusBundle] Add applications to load a distinct set of controllers per AssetMapper entrypoint - #4020
[StimulusBundle] Add applications to load a distinct set of controllers per AssetMapper entrypoint#4020Prometee wants to merge 4 commits into
Conversation
📊 Packages dist files size differenceThanks for the PR! Here is the difference in size of the packages dist files between the base branch and the PR.
|
||||||||||||||||||
997bd80 to
fd2503d
Compare
|
I feel like symfony/symfony#54377 is somewhere related to your request. |
|
Hi Francis, Thanks a lot for tackling this! Scoping controllers per area has been requested for a long time (#2321), and your PR gets the hard part right: one compiled module per application, reusing the controller map generator, with the global loader left untouched. While testing it locally, I ended up building an alternative implementation on top of your commit: smnandre/ux@fd2503d...sa/stimulus-applications-alt In one sentence: the application module is a project file, so I treated it like one, and made the isolated mode really isolate the area. What it changes:
Eager and lazy controllers work per application, as does the More details in a second comment. Curious to hear what you think, and feel free to take whatever is useful! |
Context: what AssetMapper does per page
Both follow the import graph. With a single global loader, every entrypoint reaches every controller, so neither helps. Applications give each area its own graph, which is what makes preloads, and the Three issuesThe import name. The extra loader. An isolation leak. The ideaTreat the application module like any other project file: it lives in the project, the entrypoint imports it with a relative path, and the bundle replaces its content at compile time. The global An application needs three files: # config/packages/stimulus.yaml
stimulus:
applications:
admin: ~ # assets/admin/stimulus.js + assets/admin/controllers/// assets/admin/stimulus.js: replaced at compile time, gives editors and TypeScript the types
export { startStimulusApp } from '@symfony/stimulus-bundle';// assets/admin.js: the entrypoint, the only importmap.php entry
import { startStimulusApp } from './admin/stimulus.js';
startStimulusApp();What AssetMapper serves for import { loadControllers, startApplication } from "../@symfony/stimulus-bundle/runtime.js";
import controller_0 from "./controllers/dashboard_controller.js";
export const eagerControllers = {"dashboard": controller_0};
export const lazyControllers = {"report": () => import("./controllers/report_controller.js")};
export const isApplicationDebug = true;
export const startStimulusApp = () => startApplication(eagerControllers, lazyControllers, isApplicationDebug);
export { loadControllers };Eager and lazy work as with the global loader: eager controllers are imported and preloaded, lazy ones ( Use casesThe examples below use this project: Default: no applicationsNothing to configure, nothing changes from 3.x.
An admin areastimulus:
applications:
admin: ~An application inherits the global controllers and the global
Map everywhere except the adminKeep everything global, and disable Map for the admin only, with an admin file merged over the global one: stimulus:
applications:
admin:
controllers_json: '%kernel.project_dir%/assets/admin/controllers.json'
merge_controllers_json: true// assets/admin/controllers.json
{ "controllers": { "@symfony/ux-map": { "map": { "enabled": false } } } }
The merge works per controller and per key: the admin file only overrides what it sets. A package Flex adds later to the global file reaches the admin too. An isolated admin
stimulus:
applications:
admin:
include_global: false
An isolated admin with its own MapThe admin declares the UX controllers it wants in its own stimulus:
applications:
admin:
include_global: false
controllers_json: '%kernel.project_dir%/assets/admin/controllers.json'// assets/admin/controllers.json
{ "controllers": { "@symfony/ux-map": { "map": { "enabled": true, "fetch": "lazy" } } } }
For Map in the admin only, also set No default applicationEvery page belongs to an area: a stimulus:
applications:
front: ~ # assets/front/stimulus.js + assets/front/controllers/ (menu)
admin: ~
Shared controllersTo share a directory between some areas only, list it in each of them. An area reusing stimulus:
applications:
admin:
controller_paths:
- '%kernel.project_dir%/assets/admin/controllers'
- '%kernel.project_dir%/assets/shared/controllers' # notify (eager)
shop:
controller_paths:
- '%kernel.project_dir%/assets/shop/controllers' # cart (eager)
- '%kernel.project_dir%/assets/shared/controllers'
include_global: false
When two controllers have the same name, the application one wins over the global one, which wins over a UX package. Under the hoodWhat gets replaced, and what does not. The entrypoint ( Who replaces it.
When. Whenever AssetMapper builds the asset. In dev, on the first request that needs it, then from the AssetMapper cache until a dependency changes. In prod, once, when Order. The compiler runs at priority 100, before The runtime import. The generated code imports Cache. The compiled module depends on the controller directories and the Configuration. Guards. Before replacing the content, the compiler checks that the module is empty or holds the stub only. Anything else fails with a message pointing to the entrypoint, instead of being silently dropped. The compiler also catches the stub in a file that no application uses (a typo in Outside AssetMapper. Recap
CompatibilityApplications are an AssetMapper feature. The controller list is built on the PHP side, by the AssetMapper compiler of the bundle, from
The bundle requires Symfony 7.4 or later. Scoping preloads does not depend on the Symfony version. Scoping the import map does:
Without # config/packages/asset_mapper.yaml (Symfony 8.2+)
asset_mapper:
importmap_entries: reachableTested against the lowest dependencies ( |
|
PS: thanks to Claude, for understanding my ideas, constraints and problems.. |
fd2503d to
e35dca6
Compare
|
Thanks a lot @smnandre for the thorough review and for building an alternative on top of my commit, it's really helpful. I agree with the three issues you raised:
The Two changes I'd like to propose on top of your branch:
And two minor points:
If you agree, I'll pull your two commits into this PR (with you as co-author), apply the points above, add a test for a module outside |
|
Thank you @Prometee ! Really glad it helps, and great to see we land on the same page 😄 Both of your suggestions make sense to me:
Deprecating One thing on the CHANGELOG: 3.6, 3.7 and 3.8 are already released, so the entry does belong to And of course, take the commits, with pleasure, that's what they're there for! #oss |
|
Thanks a lot @Prometee! One last thing, and it's my fault: I merged the "Use stubs for mocks" commit separately in #4351, so it now conflicts with 3.x. Could you rebase on 3.x and drop that commit? (keep your version of The rebase also fixes the "App Demo Native" job, which #4352 repaired on 3.x. |
…rs per AssetMapper entrypoint | Q | A | -------------- | --- | Bug fix? | no | New feature? | yes | Deprecations? | no | Documentation? | yes | Issues | symfony#2321 | License | MIT With AssetMapper, StimulusBundle compiles one loader from the global `controller_paths` and `assets/controllers.json`. Every entrypoint that starts Stimulus gets all of these controllers. Eager controllers of one area, such as the admin, are imported and preloaded on the pages of another area. Webpack Encore and Reprise can already use a different set of controllers per build. AssetMapper cannot. This PR adds the `stimulus.applications` option. Each application compiles its own loader, and that loader only imports and preloads the controllers of the application. The global `@symfony/stimulus-bundle` loader is unchanged. ```yaml stimulus: applications: admin: loader: '%kernel.project_dir%/assets/admin/stimulus_loader.js' controller_paths: ['%kernel.project_dir%/assets/admin/controllers'] include_global_paths: false controllers_json: '%kernel.project_dir%/assets/admin/controllers.json' merge_controllers_json: false ``` ```php // importmap.php 'admin' => ['path' => './assets/admin.js', 'entrypoint' => true], '@symfony/stimulus-bundle/admin' => ['path' => './assets/admin/stimulus_loader.js'], ``` ```js // assets/admin.js import { startStimulusApp } from '@symfony/stimulus-bundle/admin'; startStimulusApp(); ``` Options of an application: - `loader` (required): an empty `.js` file inside an AssetMapper path. The bundle replaces its content when the asset is compiled. Each application needs its own file. - `controller_paths` (default `[]`): controllers of the application. They override controllers with the same name from the global paths and from `controllers.json`. - `include_global_paths` (default `true`): also load the controllers of the global `controller_paths`. - `controllers_json` (default `null`): a file with the same format as `assets/controllers.json`. When set, it replaces the global file for the application. When `null`, the application uses the global file. - `merge_controllers_json` (default `false`): merge the application file over the global one instead of replacing it. A controller not listed in the application file keeps its global settings. For a listed controller, `enabled`, `fetch` and `name` override the global values. `autoimport` entries are merged by path. `"enabled": false` removes a controller from the application. This option requires `controllers_json`. | | Before | After | | --- | --- | --- | | Loaders | One loader for all entrypoints | One loader per application, plus the unchanged global loader | | Controllers on the admin pages | All global controllers | Only the controllers of the `admin` application | | `controllers.json` | One global file | Global file, or a file per application that replaces or merges over it | Implementation notes: - The startup code moved from `loader.js` to a new `@symfony/stimulus-bundle/core.js` module. It does not import any controller list. `loader.js` and each application loader import it with their own controllers. Importing `loader.js` from an application loader would also import the global `controllers.js`, so all global controllers would be preloaded again. The exports of `loader.js` (`startStimulusApp`, `loadControllers`) do not change. - `core.js` is a new module, so it appears in the importmap and in the preloads of every page that uses the global loader. - Application loaders use the same `ControllersMapGenerator` as the global loader, so their controllers are sorted by name as introduced in symfony#3703 (for symfony#3562), and their digest stays stable between builds. - The configuration is checked when the container is built. Application names must match `[a-z][a-z0-9_-]*`, and `default` is reserved. The loader must be an existing `.js` file, and a loader cannot be used by two applications. These checks run after parameter resolution and on the real path of the file. An application `controllers_json` file must exist. - When a `controllers.json` file refers to an unknown package or controller, the error message now names the file that was read. - Symfony Flex only updates the global `assets/controllers.json`. With `merge_controllers_json: false`, the application files have to be updated by hand. The documentation says so.
…check orphan stubs only with applications Co-authored-by: Simon André <smn.andre@gmail.com>
6b16e6a to
33d7824
Compare
@Kocal Yes, they're complementary: symfony/symfony#54377 is about the import map listing every entry, fixed in Symfony 8.2 by importmap_entries: reachable (symfony/symfony#65622). This PR scopes the controllers each entrypoint imports and preloads. With a single global loader every entrypoint reaches every controller, so reachable can't filter them; with applications, each area has its own graph, and on 8.2+ reachable scopes the import map per area too. |
With AssetMapper, StimulusBundle compiles one loader from the global
controller_pathsandassets/controllers.json. Every entrypoint that starts Stimulus gets all of these controllers: eager controllers of one area, such as the admin, are imported and preloaded on the pages of another area. Webpack Encore and Reprise can already use a different set of controllers per build. AssetMapper cannot.This PR adds the
stimulus.applicationsoption. Each application gets its own module, compiled by the bundle, which only imports and preloads the controllers of the application. The global@symfony/stimulus-bundleloader keeps working as before.Example with an admin area:
With the conventions,
admin: ~is the same as:The admin pages then load
dashboardandhello; the other pages only loadhello.Options of an application:
loader(defaultassets/<name>/stimulus.js): the module of the application, inside an AssetMapper path. It must be empty or contain only the stub above; any other content fails compilation.controller_paths(default: thecontrollers/directory next to the module, when it exists and is not a global controller path): controllers of the application. They override controllers with the same name from the global paths and fromcontrollers.json.include_global(defaulttrue): also load the globalcontroller_pathsand the globalcontrollers.json. Withfalse, the application only gets its own controllers and its owncontrollers_json, if any.controllers_json(defaultnull): a file with the same format asassets/controllers.json, replacing the global file for the application.merge_controllers_json(defaultfalse): merge the application file over the global one instead of replacing it. Requirescontrollers_jsonandinclude_global: true.For assets stored outside
assets/, only the module has to be configured: the controllers are loaded from thecontrollers/directory next to it.assets/(default)frontend/assets/admin/controllers/frontend/admin/controllers/An isolated admin, with neither the global controllers nor the global UX packages, and its own Chart.js controller:
The admin pages then load
dashboardand, on first use,chart;helloand the global UX packages are not loaded.adminapplicationcontrollers.jsoninclude_global: false), or a file per application that replaces or merges over itImplementation notes:
loader.jsto@symfony/stimulus-bundle/runtime.js. The compiler writes the controller list directly intoloader.jsand into each application module, so the global loader has the same preloads as before.dist/controllers.jsis still compiled for code importing it directly; its deprecation will be proposed separately.[a-z][a-z0-9_-]*(defaultis reserved), the module must be an existing.jsfile not shared by two applications, and an applicationcontrollers_jsonfile must exist.controllers.jsonfiles of its application, so adding or editing a controller recompiles it; the container is rebuilt when the conventioncontrollers/directory appears.importmap_entries: reachable, the import map is scoped per application as well.assets/controllers.json. Application files withcontrollers_jsonhave to be updated by hand. The documentation says so.Thanks @smnandre for the alternative implementation this PR is now based on.