Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plugin methods #188

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions packages/library/src/base/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Component } from './component'
import { Plugin, PluginAPI } from './plugin'

it('Calls plugin for registration', () => {
const p = new Plugin()
const spy = jest.spyOn(p, 'handle')
const c = new Component({ id: 'c', plugins: [p] })

expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledWith(c, 'plugin:add')
})

it('Calls plugin handle method on component event', () => {
const p = new Plugin()
const spy = jest.spyOn(p, 'handle')
const c = new Component({ id: 'c', plugins: [p] })

c.internals.emitter.trigger('foo', 'bar')

expect(spy).toHaveBeenCalledTimes(2)
expect(spy).toHaveBeenLastCalledWith(c, 'foo', 'bar')
})

it('Default plugin calls handler methods by name', () => {
const p = new Plugin()

const spyHandle = jest.spyOn(p, 'handle')
//@ts-ignore
p.onPluginAdd = () => {}
//@ts-ignore
const spyPluginAdd = jest.spyOn(p, 'onPluginAdd')
//@ts-ignore
p.onFoo = () => {}
//@ts-ignore
const spyFoo = jest.spyOn(p, 'onFoo')

const c = new Component({ id: 'c', plugins: [p] })
expect(spyHandle).toHaveBeenCalledTimes(1)
expect(spyPluginAdd).toHaveBeenCalledTimes(1)
expect(spyPluginAdd).toHaveBeenLastCalledWith(c)

c.internals.emitter.trigger('foo', 'bar')
expect(spyHandle).toHaveBeenCalledTimes(2)
expect(spyFoo).toHaveBeenCalledTimes(1)
expect(spyFoo).toHaveBeenLastCalledWith(c, 'bar')
})

it('Calls plugin handler with appropriate context', () => {
const p = new Plugin()
const c = new Component({ id: 'c', plugins: [p] })

let context = undefined

//@ts-ignore
p.onFoo = function () {
context = this
}
//@ts-ignore
const spy = jest.spyOn(p, 'onFoo')
c.internals.emitter.trigger('foo', 'bar')

expect(context).toEqual(p)
})
20 changes: 15 additions & 5 deletions packages/library/src/base/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { without } from 'lodash'
import { Component } from './component'
import { getEventMethodName } from './util/eventName'

type PluginEvent = 'plugin:add' | 'plugin:remove'

export class Plugin<C extends Component = Component, E = string> {
async handle(context: C, event: E | PluginEvent, data?: any) {}
export class Plugin<
C extends Component = Component,
E extends string = string,
> {
async handle(context: C, event: E | PluginEvent, ...params: any[]) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dynamic dispatching implementation here is clever, I think there's a good way to do it in TS!

First off, it might be easier just to hardcode a handful of empty methods in this base class here and manually trigger them from the handle.

However, if you want to go full TypeScript wizard, it is now possible with Template Literal Types to perform string manipulation on keys within types. To say, define a number of on${Event} methods computed from a union type of events. Here's a tsplayground where I play around with it: https://www.typescriptlang.org/play?#code/C4TwDgpgBAogbhAdsAcgQwLbQLxQOQBOAronlAD75gERho1mV5IAmeAUO6JLAsgBJpELADYQCAYRFoAzjKi4A3uyiqoAbQDWEEFACWiKAAMA9ogAkiiWjB7gaEXoBeEADzwkqTBAB8AXyMAXQAuKAAKAEoFHyg4Ez0Wdj9OAGNpOV5PAAURIgBzA1cJKAgAD2BWeQAjExMxIQAaWBLyyszkdCwYvQwwMSxkeQ8BIVFxKVl5ZTUoMwAlEkioZRU1ZJmzLJo6GiWVmfW1MxhhPc4DpKggA

Copy link
Owner Author

@FelixHenninger FelixHenninger Aug 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whoa, thanks! I had no idea this was possible in TS, this is truly excellent. I'll see if I can incorporate your example, many thanks for that!

Given the limited number of intrinsic string manipulation types it probably makes sense to rename some events, specifically plugin:add to pluginAdd etc., but that strikes me as a good idea anyway; as far as I know that's the only place we use the good ol' backbone.js event syntax. (those were the days!)

//@ts-ignore Dynamic dispatch is too much for TS
this[getEventMethodName(event)]?.call(this, context, ...params)
}
}

export class PluginAPI<C extends Component = Component, E = string> {
export class PluginAPI<
C extends Component = Component,
E extends string = string,
> {
plugins: Array<Plugin<C, E>>
context: C

Expand All @@ -33,9 +43,9 @@ export class PluginAPI<C extends Component = Component, E = string> {
this.plugins = without(this.plugins, plugin)
}

async handle(event: E, data: any) {
async handle(event: E, ...data: any[]) {
await Promise.all(
this.plugins.map(p => p.handle(this.context, event, data)),
this.plugins.map(p => p.handle(this.context, event, ...data)),
)
}
}
13 changes: 3 additions & 10 deletions packages/library/src/base/util/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// by Jason Miller, see https://github.com/developit/mitt .
// Any mistakes, of course, are entirely my own.

import { getEventMethodName } from './eventName'

export type EventHandler = (...payload: any[]) => void
type WildCardEventHandler<T> = (event: T, ...payload: any[]) => void

Expand All @@ -21,15 +23,6 @@ export type EmitterOptions = {
context?: object
}

// Event name splitter functions
const splitter = /(^|:)(\w)/gi
const getEventName = function (_m: string, _pre: string, eventName: string) {
return eventName.toUpperCase()
}
const getMethodName = function (event: string) {
return `on${event.replace(splitter, getEventName)}`
}

export class Emitter<T extends string = string> {
id?: string
options: EmitterOptions
Expand All @@ -52,7 +45,7 @@ export class Emitter<T extends string = string> {
}

// Trigger local method, if available
const methodName = getMethodName(event)
const methodName = getEventMethodName(event)
const method = (this.#context as any)[methodName]
if (method && typeof method === 'function') {
await method.apply(this.#context, payload)
Expand Down
9 changes: 9 additions & 0 deletions packages/library/src/base/util/eventName.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { getEventMethodName } from './eventName'

it('Generates basic method names', () => {
expect(getEventMethodName('foo')).toBe('onFoo')
})

it('Handles split method names', () => {
expect(getEventMethodName('foo:bar')).toBe('onFooBar')
})
7 changes: 7 additions & 0 deletions packages/library/src/base/util/eventName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Event name splitter functions
const splitter = /(^|:)(\w)/gi
const getEventName = (_m: string, _pre: string, eventName: string) =>
eventName.toUpperCase()

export const getEventMethodName = (event: string) =>
`on${event.replace(splitter, getEventName)}`