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
Proof of Concept for a DatasetInputs decorator (#9863)
Benjamin Bädorfda59a6f0c0f4
diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.jsindex e006cfec5ac..6a9d94ae626 100644--- a/frontend/.eslintrc.js+++ b/frontend/.eslintrc.js@@ -154,6 +154,13 @@ module.exports = {* Any template/HTML related rules you wish to use/reconfigure over and above the* recommended set provided by the @angular-eslint project would go here.*/++ // jasmine is unusable with unsafe member access, as expect(...) is always any+ "@typescript-eslint/no-unsafe-member-access": "off",+ "@typescript-eslint/no-unsafe-call": "off",++ // Allow more than one class definitions per file (test components)+ "max-classes-per-file": "off",}}],diff --git a/frontend/src/app/core/setup/global-dynamic-components.const.ts b/frontend/src/app/core/setup/global-dynamic-components.const.tsindex 41b42dc5070..9766218e887 100644--- a/frontend/src/app/core/setup/global-dynamic-components.const.ts+++ b/frontend/src/app/core/setup/global-dynamic-components.const.ts@@ -37,6 +37,10 @@ import {ToastsContainerComponent,toastsContainerSelector,} from 'core-app/shared/components/toaster/toasts-container.component';+import {+ OpSidemenuComponent,+ sidemenuSelector,+} from 'core-app/shared/components/sidemenu/sidemenu.component';import {CkeditorAugmentedTextareaComponent,ckeditorAugmentedTextareaSelector,@@ -45,7 +49,10 @@ import {PersistentToggleComponent,persistentToggleSelector,} from 'core-app/shared/components/persistent-toggle/persistent-toggle.component';-import { OpPrincipalComponent, principalSelector } from 'core-app/shared/components/principal/principal.component';+import {+ OpPrincipalComponent,+ principalSelector,+} from 'core-app/shared/components/principal/principal.component';import {HideSectionLinkComponent,hideSectionLinkSelector,@@ -194,6 +201,7 @@ export const globalDynamicComponents:OptionalBootstrapDefinition[] = [{ selector: boardsMenuSelector, cls: BoardsMenuComponent },{ selector: globalSearchWorkPackagesSelectorEntry, cls: GlobalSearchWorkPackagesEntryComponent },{ selector: toastsContainerSelector, cls: ToastsContainerComponent },+ { selector: sidemenuSelector, cls: OpSidemenuComponent },{ selector: adminTypeFormConfigurationSelector, cls: TypeFormConfigurationComponent },{ selector: ckeditorAugmentedTextareaSelector, cls: CkeditorAugmentedTextareaComponent, embeddable: true },{ selector: persistentToggleSelector, cls: PersistentToggleComponent },diff --git a/frontend/src/app/shared/components/dataset-inputs.decorator.ts b/frontend/src/app/shared/components/dataset-inputs.decorator.tsnew file mode 100644index 00000000000..60a86d5f371--- /dev/null+++ b/frontend/src/app/shared/components/dataset-inputs.decorator.ts@@ -0,0 +1,98 @@+import 'reflect-metadata';+import {+ Component,+ ElementRef,+ ɵDirectiveDef,+} from '@angular/core';++/** We expect an ElementRef to be present on the target class */+export interface DatasetInputsDecorated extends Component {+ elementRef:ElementRef<HTMLElement>;+}++export interface DatasetInputsComponent extends DatasetInputsDecorated {+ elementRef:ElementRef<HTMLElement>;+ [key:string]:unknown;+}++/**+ * The DatasetInputs decorator automatically sets input values from `data` attributes set on a component tag.+ * This is useful if you're rendering the tag in the backend but want to provide data to the component via its inputs.+ *+ * Usage:+ *+ * ```+ * @DatasetInputs+ * @Component({ selector: 'my-component' })+ * export class MyComponent {+ * @Input() someInput:string[] = [];+ * }+ * ```+ *+ * Now you can send data from the backend to the component by JSON:+ *+ * <%= content_tag 'my-component',+ * '',+ * data: {+ * 'some-input': ['a', 'b'].to_json+ * }+ * %>+ * Warning: this is only checked during the constructor phase once. Changes to the dataset+ * will not be reflected in the inputs. If you need inputs that update, use normal Angular bindings.+ */+/* The class decorator requires any[] args to it to function */+/* eslint-disable-next-line @typescript-eslint/no-explicit-any */+export function DatasetInputs<T extends { new(...args:any[]):DatasetInputsDecorated }>(constructor:T):any {+ return class extends constructor {+ /* The class decorator requires any[] args to it to function */+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */+ constructor(...args:any[]) {+ super(...args);++ // TypeScript won't allow us to do the necessary metaprogramming here since it does not+ // know about these keys (probably because we should not touch them)+ const cstr = constructor as unknown as DatasetInputsComponent;++ // Here we find the declared input names of the component.+ // With them way we can make sure we don't overwrite any non-input values.+ // This seems to always be ɵcmp, but we don't want to depend on that knowledge.+ // FIXME: Is there a better way to get to this information? It does not seem to be part of Reflect metadata+ const declaredInputsParentKey = Object.keys(cstr)+ .find((key:string) => typeof (cstr[key] as ɵDirectiveDef<unknown>).declaredInputs === 'object');++ if (!declaredInputsParentKey) {+ throw new Error('Could not find declared inputs for component');+ }++ const input = cstr[declaredInputsParentKey] as ɵDirectiveDef<unknown>;+ const inputs = input.declaredInputs as { [key:string]:string };++ Object.keys(inputs)+ .forEach((outsideName) => {+ const insideName = inputs[outsideName];++ const { dataset } = (this as unknown as DatasetInputsComponent).elementRef.nativeElement;++ if (!dataset[outsideName]) {+ return;+ }++ try {+ (this as unknown as DatasetInputsComponent)[insideName] = JSON.parse(dataset[outsideName] || '');+ } catch (err) {+ console.error("Couldn't parse input: ", outsideName, this.elementRef.nativeElement.dataset);+ console.error(`+Make sure to make all data attributes you want to use as input JSON parseable.+This means that plain strings have to be wrapped in double quotes, and the attribute value is easiest to set with single quotes.+An example:++<op-example example-input='"myString"'></op-example>+`);++ // Rethrow since an error at this point is basically a syntax error and should be fixed+ throw err;+ }+ });+ }+ };+}diff --git a/frontend/src/app/shared/components/sidemenu/sidemenu.component.ts b/frontend/src/app/shared/components/sidemenu/sidemenu.component.tsindex f397184fcbd..d4f934d570c 100644--- a/frontend/src/app/shared/components/sidemenu/sidemenu.component.ts+++ b/frontend/src/app/shared/components/sidemenu/sidemenu.component.ts@@ -4,6 +4,7 @@ import {Component,Input,HostBinding,+ ElementRef,} from '@angular/core';import { I18nService } from 'core-app/core/i18n/i18n.service';@@ -18,8 +19,10 @@ export interface IOpSidemenuItem {collapsible?:boolean;}+export const sidemenuSelector = 'op-sidemenu';+@Component({- selector: 'op-sidemenu',+ selector: sidemenuSelector,templateUrl: './sidemenu.component.html',styleUrls: ['./sidemenu.component.sass'],changeDetection: ChangeDetectionStrategy.OnPush,@@ -38,6 +41,7 @@ export class OpSidemenuComponent {public collapsed = false;constructor(+ readonly elementRef:ElementRef,readonly cdRef:ChangeDetectorRef,readonly I18n:I18nService,) {