kayvanbree / contexr

Stop redundantly defining your shortcuts in your shortcut library and your context menu. Start using Contexr!
MIT License
4 stars 0 forks source link

Decorators to define CtxActions #56

Open kayvanbree opened 5 years ago

kayvanbree commented 5 years ago

Is your feature request related to a problem? Please describe. Don't like the way we create context menu items

Describe the solution you'd like Use Decorators to create context items:

@CtxAction({
    id: 'add-item',
    text: 'Add element',
    context: ['element-list'],
    hotkey: 'ins',
    icon: 'fas fa-plus'
  })
  public ctxAddElement(args: any) {
    args.list.addElement();
  }

Decorator class is something like this:

import {Injector} from '@angular/core';
import {ContexrService} from '../providers/contexr.service';

interface CtxActionDecorator {
  injector: Injector;
  contexr: ContexrService;
  ngOnInit?: () => void;
}

export function CtxAction(context): MethodDecorator {
  return (classProto: CtxActionDecorator, prop: string) => {
    const ngOnInitUnmodified = classProto.ngOnInit;
    classProto.ngOnInit = function(this: CtxActionDecorator) {
      if (ngOnInitUnmodified) {
        ngOnInitUnmodified.call(this);
      }

      this.contexr.registerContextMenuItem({
        ...context,
        action: this[prop]
      });
    }
  }
}

Biggest problem of this solution is that this is not available as you would think. This is probably because the method is passed to the ContextMenuItem and not the class. Maybe we can change it and call it like this.item.class[this.item.action](this.item.args) in ContextMenuItemComponent...

kayvanbree commented 2 months ago

With the way arguments work since the Angular 18 update it doesn't seem like this is gonna work:

@CtxOption({
    label: "Decorator option",
    args: () => { this.name; }
})
someMethod(value: string) {
    console.log("Using decorator to get " + value);
}

We can not call this in the same way we would with the normal declaration in a field.

So unless we change how arguments work this is probably not gonna happen.