| 1 |
import type Swup from '../Swup.js'; |
| 2 |
|
| 3 |
export type Plugin = { |
| 4 |
/** Identify as a swup plugin */ |
| 5 |
isSwupPlugin: true; |
| 6 |
/** Name of this plugin */ |
| 7 |
name: string; |
| 8 |
/** Version of this plugin. Currently not in use, defined here for backward compatibility. */ |
| 9 |
version?: string; |
| 10 |
/** The swup instance that mounted this plugin */ |
| 11 |
swup?: Swup; |
| 12 |
/** Version requirements of this plugin. Example: `{ swup: '>=4' }` */ |
| 13 |
requires?: Record<string, string | string[]>; |
| 14 |
/** Run on mount */ |
| 15 |
mount: () => void; |
| 16 |
/** Run on unmount */ |
| 17 |
unmount: () => void; |
| 18 |
_beforeMount?: () => void; |
| 19 |
_afterUnmount?: () => void; |
| 20 |
_checkRequirements?: () => boolean; |
| 21 |
}; |
| 22 |
|
| 23 |
const isSwupPlugin = (maybeInvalidPlugin: unknown): maybeInvalidPlugin is Plugin => { |
| 24 |
// @ts-ignore: this might be anything, object or no |
| 25 |
return Boolean(maybeInvalidPlugin?.isSwupPlugin); |
| 26 |
}; |
| 27 |
|
| 28 |
/** Install a plugin. */ |
| 29 |
export const use = function (this: Swup, plugin: unknown) { |
| 30 |
if (!isSwupPlugin(plugin)) { |
| 31 |
console.error('Not a swup plugin instance', plugin); |
| 32 |
return; |
| 33 |
} |
| 34 |
|
| 35 |
plugin.swup = this; |
| 36 |
if (plugin._checkRequirements) { |
| 37 |
if (!plugin._checkRequirements()) { |
| 38 |
return; |
| 39 |
} |
| 40 |
} |
| 41 |
if (plugin._beforeMount) { |
| 42 |
plugin._beforeMount(); |
| 43 |
} |
| 44 |
plugin.mount(); |
| 45 |
|
| 46 |
this.plugins.push(plugin); |
| 47 |
|
| 48 |
return this.plugins; |
| 49 |
}; |
| 50 |
|
| 51 |
/** Uninstall a plugin. */ |
| 52 |
export function unuse(this: Swup, pluginOrName: Plugin | string) { |
| 53 |
const plugin = this.findPlugin(pluginOrName); |
| 54 |
if (!plugin) { |
| 55 |
console.error('No such plugin', plugin); |
| 56 |
return; |
| 57 |
} |
| 58 |
|
| 59 |
plugin.unmount(); |
| 60 |
if (plugin._afterUnmount) { |
| 61 |
plugin._afterUnmount(); |
| 62 |
} |
| 63 |
|
| 64 |
this.plugins = this.plugins.filter((p) => p !== plugin); |
| 65 |
|
| 66 |
return this.plugins; |
| 67 |
} |
| 68 |
|
| 69 |
/** Find a plugin by name or reference. */ |
| 70 |
export function findPlugin(this: Swup, pluginOrName: Plugin | string) { |
| 71 |
return this.plugins.find( |
| 72 |
(plugin) => |
| 73 |
plugin === pluginOrName || |
| 74 |
plugin.name === pluginOrName || |
| 75 |
plugin.name === `Swup${String(pluginOrName)}` |
| 76 |
); |
| 77 |
} |