OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Allow dynamic imports
Oliver Günther61bc550c297c
diff --git a/docs/development/concepts/stimulus/README.md b/docs/development/concepts/stimulus/README.mdindex 0c1d552241e..ac79c720002 100644--- a/docs/development/concepts/stimulus/README.md+++ b/docs/development/concepts/stimulus/README.md@@ -19,6 +19,21 @@ All controllers live under `frontend/src/stimulus/controllers/`. The naming convIf you want to add a common pattern, manually register the controller under `frontend/src/stimulus/setup.ts`. Often you'll want to have a dynamically loaded controller instead though.+### Adding a static controller from a plugin++If you want to add a stimulus controller from plugin code, you can do so by manually adding it to the preregister:++```typescript+import { OpenProjectStimulusApplication } from 'core-app/stimulus/app';+import { MyTestControllerClass } from './test/foo/my-test.controller';+++OpenProjectStimulusApplication.preregister(+ 'test',+ MyTestControllerClass+);+```+### Dynamically loaded controllersTo dynamically load a controller, it needs to live under `frontend/src/stimulus/controllers/dynamic/<controller-name>.controller.ts`.@@ -41,6 +56,21 @@ If you want to organize your dynamic controllers in a subfolder, use the [doubleYou need to take care to prefix all actions, values etc. with the exact same pattern, e.g., `data-admin--settings-target="foobar"`.+#### Dynamically loading controllers from plugins++If you want to add a dynamic stimulus controller import from plugin code, you can do so by manually adding it to the preregister:++```typescript+import { OpenProjectStimulusApplication } from 'core-app/stimulus/app';++OpenProjectStimulusApplication.preregisterDynamic(+ 'test',+ () => import('./test.controller')+);+```++This ensures that the controller is loaded only when it is needed, and not at application startup. The controller will then be engaded when the `data-controller` attribute is present in the DOM through the same mechanism as for the core dynamic controllers.+### Requiring a page controllerIf you have a single controller used in a partial, we have added a helper to use in a partial in order to append a controller to the `#content-wrapper` tag. This is useful if your template doesn't have a single DOM root. For example, to load the dynamic `project-storage-form` controller and provide a custom value to it:diff --git a/frontend/src/stimulus/controllers/op-application.controller.ts b/frontend/src/stimulus/controllers/op-application.controller.tsindex ec988372dce..c50e647292a 100644--- a/frontend/src/stimulus/controllers/op-application.controller.ts+++ b/frontend/src/stimulus/controllers/op-application.controller.ts@@ -2,6 +2,7 @@ import { ControllerConstructor } from '@hotwired/stimulus/dist/types/core/controimport { ApplicationController } from 'stimulus-use';import { AttributeObserver } from '@hotwired/stimulus';import { debugLog } from 'core-app/shared/helpers/debug_output';+import { OpenProjectStimulusApplication } from 'core-stimulus/openproject-stimulus-application';export class OpApplicationController extends ApplicationController {private loaded = new Set<string>();@@ -30,19 +31,43 @@ export class OpApplicationController extends ApplicationController {const registered = this.application.router.modules.map((module) => module.definition.identifier);controllers.forEach((controller) => {- const path = this.derivePath(controller);if (!registered.includes(controller) && !this.loaded.has(controller)) {debugLog(`Loading controller ${controller}`);this.loaded.add(controller);- void import(/* webpackChunkName: "[request]" */`./dynamic/${path}.controller`)- .then((imported:{ default:ControllerConstructor }) => this.application.register(controller, imported.default))- .catch((err:unknown) => {- console.error('Failed to load dynamic controller chunk %O: %O', controller, err);++ void this+ .importController(controller)+ .then((clazz) => {+ if (clazz) {+ this.application.register(controller, clazz);+ }});}});}+ private async importController(controller:string):Promise<ControllerConstructor|null> {+ try {+ const imported = await this.fetchDynamicController(controller);+ return imported.default;+ } catch (err) {+ console.error('Failed to load dynamic controller chunk %O: %O', controller, err);+ return null;+ }+ }++ private async fetchDynamicController(controller:string) {+ if (OpenProjectStimulusApplication.dynamicImports.has(controller)) {+ return OpenProjectStimulusApplication.dynamicImports.get(controller)!();+ }++ // Default: Try to load the controller from dynamic/ subfolder.+ const path = this.derivePath(controller);+ return await import(/* webpackChunkName: "[request]" */ `./dynamic/${path}.controller`) as Promise<{+ default:ControllerConstructor+ }>;+ }+/*** Derive dynamic path from controller name.*diff --git a/frontend/src/stimulus/openproject-stimulus-application.ts b/frontend/src/stimulus/openproject-stimulus-application.tsindex 7d1eb4819d8..d304aaabecd 100644--- a/frontend/src/stimulus/openproject-stimulus-application.ts+++ b/frontend/src/stimulus/openproject-stimulus-application.ts@@ -1,9 +1,15 @@import { ControllerConstructor } from '@hotwired/stimulus/dist/types/core/controller';import { Application } from '@hotwired/stimulus';+export type DynamicControllerLoader = () => Promise<{ default:ControllerConstructor }>;+export class OpenProjectStimulusApplication extends Application {+ /** A map of controllers that have been preregistered. */static controllers = new Map<string, ControllerConstructor>();+ /** A map of a dynamic controller loader to load when the controller name is found */+ static dynamicImports = new Map<string, DynamicControllerLoader>();+/*** Register a controller to be used in the application,* allowing it to be registered before the Stimulus application is being initialized.@@ -17,6 +23,27 @@ export class OpenProjectStimulusApplication extends Application {this.controllers.set(name, controller);}+ /**+ * Register a dynamic controller to be imported using the given path,+ * allowing it to be defined somewhere else than within the dynamic/ subfolder.+ *+ * This is useful for plugins that want to define new dynamic controllers.+ * How to use this: In your plugin's main.ts, call this+ *+ * ```typescript+ * OpenProjectStimulusApplication.preregisterDynamic(+ * 'test',+ * () => import('./test.controller')+ * );+ * ```+ *+ * @param name the name/identifier of the controller+ * @param loader A callback to provide the controller asynchronously.+ */+ static preregisterDynamic(name:string, loader:DynamicControllerLoader) {+ this.dynamicImports.set(name, loader);+ }+async start():Promise<void> {this.preregisteredControllers.forEach((controller, name) => {this.register(name, controller);