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 all 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, 'pluginAdd')
})

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)
})
32 changes: 22 additions & 10 deletions packages/library/src/base/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
import { without } from 'lodash'
import { capitalize, without } from 'lodash'
import { Component } from './component'

type PluginEvent = 'plugin:add' | 'plugin:remove'
type PluginEvent = 'pluginAdd' | 'pluginRemove'
type EventHandler<E extends string, C, P> = {
[key in `on${Capitalize<E>}`]?: (context: C, ...params: P[]) => Promise<void>
}

export class Plugin<C extends Component = Component, E = string> {
async handle(context: C, event: E | PluginEvent, data?: any) {}
//@ts-expect-error TS2359: No methods in common with EventHandler type
export class Plugin<C extends Component = Component, E extends string = string>
implements EventHandler<PluginEvent, Component, any>
{
async handle(context: C, event: E | PluginEvent, ...params: any[]) {
//@ts-ignore Dynamic dispatch is too much for TS
this[`on${capitalize(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 @@ -16,7 +28,7 @@ export class PluginAPI<C extends Component = Component, E = string> {
this.plugins = plugins

// Initialize existing plugins
this.plugins.forEach(p => p.handle(this.context, 'plugin:add'))
this.plugins.forEach(p => p.handle(this.context, 'pluginAdd'))

// Setup event handlers
this.handle = this.handle.bind(this)
Expand All @@ -25,17 +37,17 @@ export class PluginAPI<C extends Component = Component, E = string> {

add(plugin: Plugin<C, E>) {
this.plugins.push(plugin)
plugin.handle(this.context, 'plugin:add')
plugin.handle(this.context, 'pluginAdd')
}

remove(plugin: Plugin<C, E>) {
plugin.handle(this.context, 'plugin:remove')
plugin.handle(this.context, 'pluginRemove')
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)}`
2 changes: 1 addition & 1 deletion packages/library/src/plugins/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ export default class Debug {

async handle(context: Component, event: string) {
switch (event) {
case 'plugin:add':
case 'pluginAdd':
return this.onInit(context)
case 'prepare':
return await this.onPrepare()
Expand Down
2 changes: 1 addition & 1 deletion packages/library/test/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -1055,7 +1055,7 @@ describe('Core', () => {
// Check result
assert.deepEqual(c.internals.plugins.plugins, [plugin])
assert.ok(
spy.calledWith(c, 'plugin:add')
spy.calledWith(c, 'pluginAdd')
)
})

Expand Down