From 9689ebc66a8f7f63e7371887462f169b239666ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 23 Nov 2026 16:31:09 +0100 Subject: [PATCH 1/2] [BootstrapAdminUi] Register the Stimulus controllers automatically with AssetMapper - Expose the copy-to-clipboard and theme-switcher Stimulus controllers to AssetMapper and add them to stimulus.controller_paths, like ShadcnAdminUi does - Add a conflict on symfony/asset-mapper < 6.4, which stays optional - Document the assets/controllers.json file and the assets/controllers/ directory required by StimulusBundle - Load the importmap in the stylesheets hook to avoid a flash of unstyled content - Add an Assets page to the Bootstrap Admin UI documentation --- docs/SUMMARY.md | 1 + docs/bootstrap-admin-ui/assets.md | 67 ++++++++++ .../components/copy-to-clipboard.md | 29 +---- docs/bootstrap-admin-ui/getting-started.md | 2 + docs/getting-started.md | 118 ++++++++++++++---- src/BootstrapAdminUi/composer.json | 4 + .../Symfony/SyliusBootstrapAdminUiBundle.php | 32 +++++ .../assets/controllers/.gitignore | 0 .../Functional/StimulusControllersTest.php | 35 ++++++ 9 files changed, 239 insertions(+), 49 deletions(-) create mode 100644 docs/bootstrap-admin-ui/assets.md create mode 100644 src/BootstrapAdminUi/tests/Functional/.application/assets/controllers/.gitignore create mode 100644 src/BootstrapAdminUi/tests/Functional/StimulusControllersTest.php diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index c1432c37..c1f895ec 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -68,6 +68,7 @@ ## 🎨 Bootstrap Admin UI * [Getting started](bootstrap-admin-ui/getting-started.md) +* [Assets](bootstrap-admin-ui/assets.md) * Components * [Copy to clipboard](bootstrap-admin-ui/components/copy-to-clipboard.md) diff --git a/docs/bootstrap-admin-ui/assets.md b/docs/bootstrap-admin-ui/assets.md new file mode 100644 index 00000000..2189d691 --- /dev/null +++ b/docs/bootstrap-admin-ui/assets.md @@ -0,0 +1,67 @@ +--- +description: >- + How the Bootstrap Admin UI package loads its stylesheets, scripts and Stimulus controllers. +--- + +# Assets + +## Prebuilt assets (default) + +The package ships prebuilt assets in its `public/` directory, installed by `assets:install` under `public/bundles/syliusbootstrapadminui/`. +They are loaded through the following hookables of the admin base layout: + +| Hook | Hookable | Content | +|---------------------------------|--------------|---------------------------------------------------------------------------------------| +| `sylius_admin.base#stylesheets` | `styles` | Tabler/Bootstrap styles of the admin panel | +| `sylius_admin.base#stylesheets` | `symfony_ux` | Stylesheets of the Symfony UX packages (Tom Select, Live Components) | +| `sylius_admin.base#javascripts` | `javascripts`| Scripts of the admin panel | +| `sylius_admin.base#javascripts` | `symfony_ux` | A Stimulus application with the Symfony UX controllers and the package's controllers | + +Nothing else is needed: this works whether your application uses Webpack Encore, AssetMapper or no frontend tooling at all. + +## Using your own Stimulus application (AssetMapper) + +If your application starts its own Stimulus application, for instance with AssetMapper, disable both `symfony_ux` hookables and load your importmap instead. +Follow the [Using AssetMapper](../getting-started.md#using-assetmapper) guide. + +## Stimulus controllers + +The package provides the following Stimulus controllers: + +| Identifier | Used by | +|---------------------|------------------------------------------------------------------------------| +| `copy-to-clipboard` | the [copy to clipboard](components/copy-to-clipboard.md) components | +| `theme-switcher` | the theme switcher of the navbar | + +They are registered by the prebuilt `symfony_ux` Stimulus application. +When you disable it and start your own Stimulus application with AssetMapper, the package registers them in it: it exposes its `assets/controllers/` directory to AssetMapper and adds it to the `stimulus.controller_paths` option, next to your `assets/controllers/` directory. Nothing else is needed. + +{% hint style="warning" %} +Do not load the prebuilt `symfony_ux` Stimulus application and your own one on the same page: both would connect these controllers (and the Symfony UX ones) to the same elements, so the theme switcher for instance would toggle twice on each click. +{% endhint %} + +### Versions that do not register their controllers + +Older versions of the package do not register their controllers in your Stimulus application: the matching components are rendered but do nothing (for instance, the dark/light theme button of the navbar), without any error. +Do what newer versions do in your configuration: StimulusBundle then registers them with their file names (`copy-to-clipboard`, `theme-switcher`). + +{% code title="config/packages/asset_mapper.yaml" lineNumbers="true" %} +```yaml +framework: + asset_mapper: + paths: + assets/: '' + vendor/sylius/bootstrap-admin-ui/assets/controllers: '@sylius/bootstrap-admin-ui/controllers' +``` +{% endcode %} + +{% code title="config/packages/stimulus.yaml" lineNumbers="true" %} +```yaml +stimulus: + controller_paths: + - '%kernel.project_dir%/assets/controllers' + - '%kernel.project_dir%/vendor/sylius/bootstrap-admin-ui/assets/controllers' +``` +{% endcode %} + +Remove this configuration once you upgrade to a version that registers its controllers. diff --git a/docs/bootstrap-admin-ui/components/copy-to-clipboard.md b/docs/bootstrap-admin-ui/components/copy-to-clipboard.md index a840d939..4e8e60d3 100644 --- a/docs/bootstrap-admin-ui/components/copy-to-clipboard.md +++ b/docs/bootstrap-admin-ui/components/copy-to-clipboard.md @@ -132,33 +132,12 @@ Register the controller **once in the application's existing Stimulus applicatio ### AssetMapper -Follow the [AssetMapper setup](../../getting-started.md#using-assetmapper) to disable the package's `symfony_ux` entrypoint when starting your own Stimulus application. Expose the controller source directory to AssetMapper: +Follow the [AssetMapper setup](../../getting-started.md#using-assetmapper) to disable the package's `symfony_ux` entrypoint when starting your own Stimulus application. -```yaml -# config/packages/asset_mapper.yaml -framework: - asset_mapper: - paths: - '%kernel.project_dir%/vendor/sylius/bootstrap-admin-ui/assets/controllers': 'sylius/bootstrap-admin-ui/controllers' -``` - -Add a local importmap entry (this does not install another JavaScript package): - -```bash -php bin/console importmap:require '@sylius/bootstrap-admin-ui/copy-to-clipboard' --path=./vendor/sylius/bootstrap-admin-ui/assets/controllers/copy-to-clipboard-controller.js -``` - -In the module where your application already starts Stimulus: - -```js -import { startStimulusApp } from '@symfony/stimulus-bundle'; -import CopyToClipboardController from '@sylius/bootstrap-admin-ui/copy-to-clipboard'; - -const app = startStimulusApp(); -app.register('copy-to-clipboard', CopyToClipboardController); -``` +The package registers its controllers in the Stimulus application started by StimulusBundle, with the `copy-to-clipboard` identifier: nothing else to configure. +If you registered it yourself by following a previous version of this page (`app.register('copy-to-clipboard', ...)`, a local importmap entry, an `asset_mapper` path), remove that code. -If `app` is already exported by another module, import and reuse it instead of calling `startStimulusApp()` again. The application's importmap must also provide `@hotwired/stimulus`, as in a normal Symfony Stimulus installation. +See the [Assets](../assets.md#stimulus-controllers) page for the other controllers of the package. The application's importmap must also provide `@hotwired/stimulus`, as in a normal Symfony Stimulus installation. ### Webpack Encore / an existing Sylius Stimulus application diff --git a/docs/bootstrap-admin-ui/getting-started.md b/docs/bootstrap-admin-ui/getting-started.md index 0e8925f4..8f43bb62 100644 --- a/docs/bootstrap-admin-ui/getting-started.md +++ b/docs/bootstrap-admin-ui/getting-started.md @@ -15,6 +15,8 @@ Install the package using Composer and Symfony Flex: composer require sylius/bootstrap-admin-ui ``` +The package works out of the box with its prebuilt assets. If your application starts its own Stimulus application (for instance with AssetMapper), read the [Assets](assets.md) page. + ## Configuring the CRUD templates CRUD templates are split into configurable blocks. diff --git a/docs/getting-started.md b/docs/getting-started.md index 57da928a..71625ff5 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -76,30 +76,90 @@ Now, it's your turn! ### Using AssetMapper -To prevent duplicate Ajax calls, disable the auto-initialized Stimulus app and Symfony UX stylesheets from the `sylius/bootstrap-admin-ui` package, so you can take control of Stimulus initialization in your own code. +By default, the `sylius/bootstrap-admin-ui` package loads prebuilt assets that start their own Stimulus application (the `symfony_ux` hookables). +If your application uses [AssetMapper](https://symfony.com/doc/current/frontend/asset_mapper.html) and starts its own Stimulus application, disable these prebuilt assets to avoid running two Stimulus applications (and duplicate Ajax calls), and take control of Stimulus initialization in your own code. -#### Disabling Stimulus app & Symfony UX stylesheets from third party package +#### Preparing Stimulus for AssetMapper -First, you need to disable the Stimulus App started by the `sylius/bootstrap-admin-ui` package and add a custom javascript app hook for the asset mapper. +StimulusBundle needs an `assets/controllers.json` file and an `assets/controllers/` directory. +When the StimulusBundle recipe was applied on a Webpack Encore project, the `assets/controllers/` directory may not exist. In this case, Symfony Flex fails with `The "assets/controllers" directory does not exist` and does not add `@symfony/stimulus-bundle` to your `importmap.php`. + +Create the directory if needed: + +```bash +mkdir -p assets/controllers +touch assets/controllers/.gitignore +``` + +Then declare the Symfony UX controllers used by the admin panel, with the same autoimported stylesheets as the prebuilt assets: + +{% code title="assets/controllers.json" lineNumbers="true" %} +```json +{ + "controllers": { + "@symfony/ux-autocomplete": { + "autocomplete": { + "enabled": true, + "fetch": "eager", + "autoimport": { + "tom-select/dist/css/tom-select.default.css": false, + "tom-select/dist/css/tom-select.bootstrap4.css": false, + "tom-select/dist/css/tom-select.bootstrap5.css": true + } + } + }, + "@symfony/ux-live-component": { + "live": { + "enabled": true, + "fetch": "eager", + "autoimport": { + "@symfony/ux-live-component/dist/live.min.css": true + } + } + } + }, + "entrypoints": [] +} +``` +{% endcode %} + +{% hint style="info" %} +The Stimulus controllers shipped with the `sylius/bootstrap-admin-ui` package (used by the [copy to clipboard](bootstrap-admin-ui/components/copy-to-clipboard.md) components and the theme switcher of the navbar) are registered automatically: nothing to add for them. +{% endhint %} + +Make sure StimulusBundle and Stimulus are in your `importmap.php`: + +```bash +php bin/console importmap:require @symfony/stimulus-bundle @hotwired/stimulus +``` + +The `@symfony/ux-autocomplete` and `@symfony/ux-live-component` packages also need their importmap entries (such as `tom-select` and the `tom-select/dist/css/*.css` files). Symfony Flex adds them when it installs these packages; if one is missing, add it with `php bin/console importmap:require`. + +#### Disabling the prebuilt Stimulus app & Symfony UX stylesheets + +Disable the `symfony_ux` hookables of the `sylius/bootstrap-admin-ui` package and add your own hookable that loads your importmap entrypoint. + +Load the importmap in the `sylius_admin.base#stylesheets` hook (in the ``) rather than in the `sylius_admin.base#javascripts` one (at the end of the ``): +the stylesheets imported by your JavaScript (Tom Select, Live Components, your own CSS) are then loaded before the page is rendered, which avoids a flash of unstyled content. +Hookables are rendered by descending priority, and the package stylesheets use the default priority (`0`): a negative priority makes sure your stylesheets come after them and can override them. {% tabs %} {% tab title="YAML" %} -{% code lineNumbers="true" %} +{% code title="config/packages/sylius_bootstrap_admin_ui.yaml" lineNumbers="true" %} ```yaml -# config/packages/sylius_bootstrap_admin_ui.yaml -# ... sylius_twig_hooks: hooks: # ... - # Disabling Symfony UX stylesheets 'sylius_admin.base#stylesheets': + # Disabling Symfony UX stylesheets symfony_ux: - enabled: false - - 'sylius_admin.base#javascripts': + enabled: false + # New hookable, rendered after the package stylesheets app: - priority: 200 - template: 'base/javascripts/app.html.twig' + template: 'base/stylesheets/app.html.twig' + priority: -100 + + 'sylius_admin.base#javascripts': # Disabling Stimulus App symfony_ux: enabled: false @@ -122,20 +182,20 @@ return static function (ContainerConfigurator $containerConfigurator): void { 'symfony_ux' => [ 'enabled' => false, ], + // New hookable, rendered after the package stylesheets + 'app' => [ + 'template' => 'base/stylesheets/app.html.twig', + 'priority' => -100, + ], ], - + 'sylius_admin.base#javascripts' => [ - // New hook - 'app' => [ - 'priority' => 200, - 'template' => 'base/javascripts/app.html.twig', - ], - // Disabling Stimulus App + // Disabling Stimulus App 'symfony_ux' => [ 'enabled' => false, ], ], - ], + ], ]); }; ``` @@ -143,7 +203,7 @@ return static function (ContainerConfigurator $containerConfigurator): void { {% endtab %} {% endtabs %} -{% code title="base/javascripts/app.html.twig" lineNumbers="true" %} +{% code title="templates/base/stylesheets/app.html.twig" lineNumbers="true" %} ```twig {{ importmap('app') }} ``` @@ -151,17 +211,27 @@ return static function (ContainerConfigurator $containerConfigurator): void { #### Starting Stimulus App +The StimulusBundle recipe starts the Stimulus application of your importmap entrypoint: + +{% code title="assets/stimulus_bootstrap.js" lineNumbers="true" %} ```js -// assets/bootstrap.js import { startStimulusApp } from '@symfony/stimulus-bundle'; const app = startStimulusApp(); // register any custom, 3rd party controllers here // app.register('some_controller_name', SomeImportedController); ``` +{% endcode %} +{% code title="assets/app.js" lineNumbers="true" %} ```js -// assets/app.js -import './bootstrap.js'; +import './stimulus_bootstrap.js'; // ... ``` +{% endcode %} + +{% hint style="info" %} +Older versions of the recipe name this file `assets/bootstrap.js`. +{% endhint %} + +The controllers declared in `assets/controllers.json`, the ones in your `assets/controllers/` directory and the ones of the `sylius/bootstrap-admin-ui` package are registered automatically. diff --git a/src/BootstrapAdminUi/composer.json b/src/BootstrapAdminUi/composer.json index 9a721828..317ed876 100644 --- a/src/BootstrapAdminUi/composer.json +++ b/src/BootstrapAdminUi/composer.json @@ -19,10 +19,14 @@ "symfony/ux-icons": "^2.20 || ^3.0", "symfony/ux-live-component": "^2.17 || ^3.0" }, + "conflict": { + "symfony/asset-mapper": "<6.4" + }, "require-dev": { "doctrine/doctrine-bundle": "^2.13 || ^3.0 || ^4.0", "doctrine/orm": "^3.3 || ^4.0", "phpunit/phpunit": "^10.5", + "symfony/asset-mapper": "^6.4 || ^7.4 || ^8.0", "symfony/browser-kit": "^6.4 || ^7.4 || ^8.0", "symfony/console": "^6.4 || ^7.4 || ^8.0", "symfony/css-selector": "^6.4 || ^7.4 || ^8.0", diff --git a/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php b/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php index ff4fb436..76a98112 100644 --- a/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php +++ b/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php @@ -13,6 +13,7 @@ namespace Sylius\BootstrapAdminUi\Symfony; +use Symfony\Component\AssetMapper\AssetMapperInterface; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; @@ -42,6 +43,26 @@ public function prependExtension(ContainerConfigurator $container, ContainerBuil $loader->load('services.php'); + if ($this->isAssetMapperAvailable($builder)) { + // Exposes the Stimulus controllers to AssetMapper. + $builder->prependExtensionConfig('framework', [ + 'asset_mapper' => [ + 'paths' => [ + $this->getPath() . '/assets/controllers' => '@sylius/bootstrap-admin-ui/controllers', + ], + ], + ]); + + // Registers the bundle controllers next to the application ones, in the Stimulus + // application started by the application: "copy-to-clipboard", "theme-switcher". + $builder->prependExtensionConfig('stimulus', [ + 'controller_paths' => [ + '%kernel.project_dir%/assets/controllers', + $this->getPath() . '/assets/controllers', + ], + ]); + } + if (!isset($bundles['SyliusAdminUiBundle'])) { return; } @@ -51,4 +72,15 @@ public function prependExtension(ContainerConfigurator $container, ContainerBuil 'hook_name_section_separator' => '#', ]); } + + private function isAssetMapperAvailable(ContainerBuilder $builder): bool + { + if (!interface_exists(AssetMapperInterface::class)) { + return false; + } + + $bundlesMetadata = $builder->getParameter('kernel.bundles_metadata'); + + return \is_array($bundlesMetadata) && isset($bundlesMetadata['FrameworkBundle']); + } } diff --git a/src/BootstrapAdminUi/tests/Functional/.application/assets/controllers/.gitignore b/src/BootstrapAdminUi/tests/Functional/.application/assets/controllers/.gitignore new file mode 100644 index 00000000..e69de29b diff --git a/src/BootstrapAdminUi/tests/Functional/StimulusControllersTest.php b/src/BootstrapAdminUi/tests/Functional/StimulusControllersTest.php new file mode 100644 index 00000000..306c4694 --- /dev/null +++ b/src/BootstrapAdminUi/tests/Functional/StimulusControllersTest.php @@ -0,0 +1,35 @@ +get('stimulus.asset_mapper.controllers_map_generator'); + + $controllersMap = $controllersMapGenerator->getControllersMap(); + + $this->assertArrayHasKey('copy-to-clipboard', $controllersMap); + $this->assertArrayHasKey('theme-switcher', $controllersMap); + $this->assertSame( + '@sylius/bootstrap-admin-ui/controllers/copy-to-clipboard-controller.js', + $controllersMap['copy-to-clipboard']->asset->logicalPath, + ); + } +} From 14e49a6c1f97889668c55381cc82a01bbf4c7284 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 24 Nov 2026 08:37:11 +0100 Subject: [PATCH 2/2] [BootstrapAdminUi] Add an importmap_entrypoint option to replace the prebuilt Symfony UX assets - Add a "sylius_bootstrap_admin_ui.importmap_entrypoint" option, null by default - When set, both symfony_ux hookables get an "entrypoint" configuration: the stylesheets one loads the importmap in the and the javascripts one no longer starts the prebuilt Stimulus application - Document the option instead of disabling the hookables by hand --- docs/bootstrap-admin-ui/assets.md | 14 ++- .../components/copy-to-clipboard.md | 2 +- docs/getting-started.md | 71 +++++--------- .../Symfony/SyliusBootstrapAdminUiBundle.php | 56 +++++++++++ .../shared/layout/importmap.html.twig | 1 + .../layout/symfony_ux_scripts.html.twig | 5 +- .../shared/layout/symfony_ux_styles.html.twig | 13 ++- .../Functional/SymfonyUxTemplatesTest.php | 46 +++++++++ .../SyliusBootstrapAdminUiBundleTest.php | 94 +++++++++++++++++++ 9 files changed, 246 insertions(+), 56 deletions(-) create mode 100644 src/BootstrapAdminUi/templates/shared/layout/importmap.html.twig create mode 100644 src/BootstrapAdminUi/tests/Functional/SymfonyUxTemplatesTest.php create mode 100644 src/BootstrapAdminUi/tests/Unit/Symfony/SyliusBootstrapAdminUiBundleTest.php diff --git a/docs/bootstrap-admin-ui/assets.md b/docs/bootstrap-admin-ui/assets.md index 2189d691..31a4b308 100644 --- a/docs/bootstrap-admin-ui/assets.md +++ b/docs/bootstrap-admin-ui/assets.md @@ -21,8 +21,15 @@ Nothing else is needed: this works whether your application uses Webpack Encore, ## Using your own Stimulus application (AssetMapper) -If your application starts its own Stimulus application, for instance with AssetMapper, disable both `symfony_ux` hookables and load your importmap instead. -Follow the [Using AssetMapper](../getting-started.md#using-assetmapper) guide. +If your application starts its own Stimulus application with AssetMapper, set the importmap entrypoint that starts it: + +```yaml +sylius_bootstrap_admin_ui: + importmap_entrypoint: app +``` + +Both `symfony_ux` hookables then load your importmap (in the ``) instead of the prebuilt Stimulus application and Symfony UX stylesheets. +Follow the [Using AssetMapper](../getting-started.md#using-assetmapper) guide to prepare your Stimulus application. ## Stimulus controllers @@ -34,10 +41,11 @@ The package provides the following Stimulus controllers: | `theme-switcher` | the theme switcher of the navbar | They are registered by the prebuilt `symfony_ux` Stimulus application. -When you disable it and start your own Stimulus application with AssetMapper, the package registers them in it: it exposes its `assets/controllers/` directory to AssetMapper and adds it to the `stimulus.controller_paths` option, next to your `assets/controllers/` directory. Nothing else is needed. +When you use your own Stimulus application instead (the `importmap_entrypoint` option), the package registers them in it: it exposes its `assets/controllers/` directory to AssetMapper and adds it to the `stimulus.controller_paths` option, next to your `assets/controllers/` directory. Nothing else is needed. {% hint style="warning" %} Do not load the prebuilt `symfony_ux` Stimulus application and your own one on the same page: both would connect these controllers (and the Symfony UX ones) to the same elements, so the theme switcher for instance would toggle twice on each click. +The `importmap_entrypoint` option takes care of it. {% endhint %} ### Versions that do not register their controllers diff --git a/docs/bootstrap-admin-ui/components/copy-to-clipboard.md b/docs/bootstrap-admin-ui/components/copy-to-clipboard.md index 4e8e60d3..32d6728a 100644 --- a/docs/bootstrap-admin-ui/components/copy-to-clipboard.md +++ b/docs/bootstrap-admin-ui/components/copy-to-clipboard.md @@ -132,7 +132,7 @@ Register the controller **once in the application's existing Stimulus applicatio ### AssetMapper -Follow the [AssetMapper setup](../../getting-started.md#using-assetmapper) to disable the package's `symfony_ux` entrypoint when starting your own Stimulus application. +Follow the [AssetMapper setup](../../getting-started.md#using-assetmapper) to replace the package's `symfony_ux` entrypoint with your own Stimulus application (the `importmap_entrypoint` option). The package registers its controllers in the Stimulus application started by StimulusBundle, with the `copy-to-clipboard` identifier: nothing else to configure. If you registered it yourself by following a previous version of this page (`app.register('copy-to-clipboard', ...)`, a local importmap entry, an `asset_mapper` path), remove that code. diff --git a/docs/getting-started.md b/docs/getting-started.md index 71625ff5..ed342d61 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -77,7 +77,7 @@ Now, it's your turn! ### Using AssetMapper By default, the `sylius/bootstrap-admin-ui` package loads prebuilt assets that start their own Stimulus application (the `symfony_ux` hookables). -If your application uses [AssetMapper](https://symfony.com/doc/current/frontend/asset_mapper.html) and starts its own Stimulus application, disable these prebuilt assets to avoid running two Stimulus applications (and duplicate Ajax calls), and take control of Stimulus initialization in your own code. +If your application uses [AssetMapper](https://symfony.com/doc/current/frontend/asset_mapper.html) and starts its own Stimulus application, replace these prebuilt assets with your importmap to avoid running two Stimulus applications (and duplicate Ajax calls), and take control of Stimulus initialization in your own code. #### Preparing Stimulus for AssetMapper @@ -135,34 +135,16 @@ php bin/console importmap:require @symfony/stimulus-bundle @hotwired/stimulus The `@symfony/ux-autocomplete` and `@symfony/ux-live-component` packages also need their importmap entries (such as `tom-select` and the `tom-select/dist/css/*.css` files). Symfony Flex adds them when it installs these packages; if one is missing, add it with `php bin/console importmap:require`. -#### Disabling the prebuilt Stimulus app & Symfony UX stylesheets +#### Loading your importmap in the admin panel -Disable the `symfony_ux` hookables of the `sylius/bootstrap-admin-ui` package and add your own hookable that loads your importmap entrypoint. - -Load the importmap in the `sylius_admin.base#stylesheets` hook (in the ``) rather than in the `sylius_admin.base#javascripts` one (at the end of the ``): -the stylesheets imported by your JavaScript (Tom Select, Live Components, your own CSS) are then loaded before the page is rendered, which avoids a flash of unstyled content. -Hookables are rendered by descending priority, and the package stylesheets use the default priority (`0`): a negative priority makes sure your stylesheets come after them and can override them. +Set the importmap entrypoint that starts your Stimulus application: {% tabs %} {% tab title="YAML" %} {% code title="config/packages/sylius_bootstrap_admin_ui.yaml" lineNumbers="true" %} ```yaml -sylius_twig_hooks: - hooks: - # ... - 'sylius_admin.base#stylesheets': - # Disabling Symfony UX stylesheets - symfony_ux: - enabled: false - # New hookable, rendered after the package stylesheets - app: - template: 'base/stylesheets/app.html.twig' - priority: -100 - - 'sylius_admin.base#javascripts': - # Disabling Stimulus App - symfony_ux: - enabled: false +sylius_bootstrap_admin_ui: + importmap_entrypoint: app ``` {% endcode %} {% endtab %} @@ -173,29 +155,8 @@ sylius_twig_hooks: use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { - // ... - - $containerConfigurator->extension('sylius_twig_hooks', [ - 'hooks' => [ - 'sylius_admin.base#stylesheets' => [ - // Disabling Symfony UX stylesheets - 'symfony_ux' => [ - 'enabled' => false, - ], - // New hookable, rendered after the package stylesheets - 'app' => [ - 'template' => 'base/stylesheets/app.html.twig', - 'priority' => -100, - ], - ], - - 'sylius_admin.base#javascripts' => [ - // Disabling Stimulus App - 'symfony_ux' => [ - 'enabled' => false, - ], - ], - ], + $containerConfigurator->extension('sylius_bootstrap_admin_ui', [ + 'importmap_entrypoint' => 'app', ]); }; ``` @@ -203,11 +164,21 @@ return static function (ContainerConfigurator $containerConfigurator): void { {% endtab %} {% endtabs %} -{% code title="templates/base/stylesheets/app.html.twig" lineNumbers="true" %} -```twig -{{ importmap('app') }} +The `symfony_ux` hookables of the `sylius_admin.base#stylesheets` and `sylius_admin.base#javascripts` hooks then stop loading the prebuilt Stimulus application and Symfony UX stylesheets, and your importmap is loaded instead. +It is loaded in the ``: the stylesheets imported by your JavaScript (Tom Select, Live Components, your own CSS) are rendered with the page, which avoids a flash of unstyled content. + +{% hint style="info" %} +The option sets the `entrypoint` configuration of both `symfony_ux` hookables. You can also set it per hook with Twig Hooks, as for the `entrypoint` of the Shadcn Admin UI layout: + +```yaml +sylius_twig_hooks: + hooks: + 'sylius_admin.base#stylesheets': + symfony_ux: { configuration: { entrypoint: 'app' } } + 'sylius_admin.base#javascripts': + symfony_ux: { configuration: { entrypoint: 'app' } } ``` -{% endcode %} +{% endhint %} #### Starting Stimulus App diff --git a/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php b/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php index 76a98112..5b795647 100644 --- a/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php +++ b/src/BootstrapAdminUi/src/Symfony/SyliusBootstrapAdminUiBundle.php @@ -14,8 +14,11 @@ namespace Sylius\BootstrapAdminUi\Symfony; use Symfony\Component\AssetMapper\AssetMapperInterface; +use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator; +use Symfony\Component\Config\Definition\Processor; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Extension\ConfigurationExtensionInterface; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\HttpKernel\Bundle\AbstractBundle; @@ -32,6 +35,20 @@ public function getPath(): string return $this->path; } + public function configure(DefinitionConfigurator $definition): void + { + $definition->rootNode() + ->children() + ->scalarNode('importmap_entrypoint') + ->info('Importmap entrypoint starting the Stimulus application of the admin panel, instead of the prebuilt Symfony UX assets. Requires symfony/asset-mapper.') + ->example('app') + ->defaultNull() + ->cannotBeEmpty() + ->end() + ->end() + ; + } + public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void { $bundles = $builder->getParameter('kernel.bundles'); @@ -71,6 +88,45 @@ public function prependExtension(ContainerConfigurator $container, ContainerBuil 'enable_autoprefixing' => true, 'hook_name_section_separator' => '#', ]); + + $entrypoint = $this->processConfiguration($builder)['importmap_entrypoint']; + if (null === $entrypoint) { + return; + } + + if (!$this->isAssetMapperAvailable($builder)) { + throw new \LogicException('The "sylius_bootstrap_admin_ui.importmap_entrypoint" option requires AssetMapper. Try running "composer require symfony/asset-mapper".'); + } + + // Only the configuration is prepended: the hookables themselves are defined in "config/app.php", + // imported by the application, which would override an "enabled" key prepended here. + $builder->prependExtensionConfig('sylius_twig_hooks', [ + 'hooks' => [ + 'sylius_admin.base#stylesheets' => [ + 'symfony_ux' => ['configuration' => ['entrypoint' => $entrypoint]], + ], + 'sylius_admin.base#javascripts' => [ + 'symfony_ux' => ['configuration' => ['entrypoint' => $entrypoint]], + ], + ], + ]); + } + + /** + * @return array{importmap_entrypoint: string|null} + */ + private function processConfiguration(ContainerBuilder $builder): array + { + $extension = $this->getContainerExtension(); + \assert($extension instanceof ConfigurationExtensionInterface); + $configs = $builder->getExtensionConfig($extension->getAlias()); + $configuration = $extension->getConfiguration($configs, $builder); + \assert(null !== $configuration); + + /** @var array{importmap_entrypoint: string|null} $config */ + $config = (new Processor())->processConfiguration($configuration, $configs); + + return $config; } private function isAssetMapperAvailable(ContainerBuilder $builder): bool diff --git a/src/BootstrapAdminUi/templates/shared/layout/importmap.html.twig b/src/BootstrapAdminUi/templates/shared/layout/importmap.html.twig new file mode 100644 index 00000000..531583a6 --- /dev/null +++ b/src/BootstrapAdminUi/templates/shared/layout/importmap.html.twig @@ -0,0 +1 @@ +{{ importmap(entrypoint) }} diff --git a/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_scripts.html.twig b/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_scripts.html.twig index f5b70d74..ef5e89e5 100644 --- a/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_scripts.html.twig +++ b/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_scripts.html.twig @@ -1 +1,4 @@ - +{# With an importmap entrypoint, the Stimulus application is started by the importmap loaded in the . #} +{% if hookable_metadata.configuration.entrypoint|default(null) is null %} + +{% endif %} diff --git a/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_styles.html.twig b/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_styles.html.twig index cc412806..db1c9b1a 100644 --- a/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_styles.html.twig +++ b/src/BootstrapAdminUi/templates/shared/layout/symfony_ux_styles.html.twig @@ -1 +1,12 @@ - +{# + With an importmap entrypoint (see the "importmap_entrypoint" option), the application starts its own + Stimulus application: its importmap is loaded instead of the prebuilt Symfony UX assets. + It is loaded in the , for the stylesheets it imports to be rendered with the page. + The importmap() function only exists with AssetMapper, hence the separate template. +#} +{% set entrypoint = hookable_metadata.configuration.entrypoint|default(null) %} +{% if entrypoint is not null %} + {{ include('@SyliusBootstrapAdminUi/shared/layout/importmap.html.twig', {entrypoint: entrypoint}) }} +{% else %} + +{% endif %} diff --git a/src/BootstrapAdminUi/tests/Functional/SymfonyUxTemplatesTest.php b/src/BootstrapAdminUi/tests/Functional/SymfonyUxTemplatesTest.php new file mode 100644 index 00000000..ae256143 --- /dev/null +++ b/src/BootstrapAdminUi/tests/Functional/SymfonyUxTemplatesTest.php @@ -0,0 +1,46 @@ + ['configuration' => []]]; + + $this->assertStringContainsString('symfony_ux', $this->render('symfony_ux_styles.html.twig', $context)); + $this->assertStringContainsString('symfony_ux', $this->render('symfony_ux_scripts.html.twig', $context)); + } + + public function testItDoesNotLoadThePrebuiltStimulusApplicationWithAnImportmapEntrypoint(): void + { + $context = ['hookable_metadata' => ['configuration' => ['entrypoint' => 'app']]]; + + $this->assertSame('', trim($this->render('symfony_ux_scripts.html.twig', $context))); + } + + /** + * @param array $context + */ + private function render(string $template, array $context): string + { + /** @var Environment $twig */ + $twig = self::getContainer()->get('twig'); + + return $twig->render('@SyliusBootstrapAdminUi/shared/layout/' . $template, $context); + } +} diff --git a/src/BootstrapAdminUi/tests/Unit/Symfony/SyliusBootstrapAdminUiBundleTest.php b/src/BootstrapAdminUi/tests/Unit/Symfony/SyliusBootstrapAdminUiBundleTest.php new file mode 100644 index 00000000..d1276a6f --- /dev/null +++ b/src/BootstrapAdminUi/tests/Unit/Symfony/SyliusBootstrapAdminUiBundleTest.php @@ -0,0 +1,94 @@ +prepend([]); + + $this->assertSame([], $this->symfonyUxConfigurations($builder)); + } + + public function testItLoadsTheImportmapEntrypointInsteadOfThePrebuiltSymfonyUxAssets(): void + { + $builder = $this->prepend(['importmap_entrypoint' => 'app']); + + $this->assertSame([ + 'sylius_admin.base#stylesheets' => ['entrypoint' => 'app'], + 'sylius_admin.base#javascripts' => ['entrypoint' => 'app'], + ], $this->symfonyUxConfigurations($builder)); + } + + /** + * @param array $config + */ + private function prepend(array $config): ContainerBuilder + { + $bundles = [ + 'FrameworkBundle' => FrameworkBundle::class, + 'SyliusAdminUiBundle' => SyliusAdminUiBundle::class, + ]; + + $builder = new ContainerBuilder(); + $builder->registerExtension(new SyliusTwigHooksExtension()); + $builder->setParameter('kernel.bundles', $bundles); + $builder->setParameter('kernel.bundles_metadata', array_map( + static fn (string $class): array => ['path' => \dirname((string) (new \ReflectionClass($class))->getFileName()), 'namespace' => ''], + $bundles, + )); + $builder->setParameter('kernel.environment', 'test'); + $builder->setParameter('kernel.build_dir', sys_get_temp_dir()); + $builder->setParameter('kernel.debug', false); + + $bundle = new SyliusBootstrapAdminUiBundle(); + $extension = $bundle->getContainerExtension(); + $this->assertNotNull($extension); + + if ([] !== $config) { + $builder->prependExtensionConfig($extension->getAlias(), $config); + } + + $extension->prepend($builder); + + return $builder; + } + + /** + * @return array> + */ + private function symfonyUxConfigurations(ContainerBuilder $builder): array + { + $configurations = []; + foreach ($builder->getExtensionConfig('sylius_twig_hooks') as $config) { + foreach ($config['hooks'] ?? [] as $hookName => $hookables) { + if (isset($hookables['symfony_ux']['configuration'])) { + $configurations[$hookName] = $hookables['symfony_ux']['configuration']; + } + } + } + + return $configurations; + } +}