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 Import updates #3305

Merged
merged 8 commits into from
Jul 23, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
10 changes: 8 additions & 2 deletions cli/src/tasks/new-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ async function createTSPlugin(
) {
const newPluginPath = join(pluginPath, 'src');

const originalIndex = await readFileAsync(
join(newPluginPath, 'index.ts'),
'utf8',
);
const originalDefinitions = await readFileAsync(
join(newPluginPath, 'definitions.ts'),
'utf8',
Expand All @@ -166,9 +170,11 @@ async function createTSPlugin(
join(newPluginPath, 'web.ts'),
'utf8',
);
let definitions = originalDefinitions.replace(/Echo/g, className);
const index = originalIndex.replace(/MyPlugin/g, className);
const definitions = originalDefinitions.replace(/MyPlugin/g, className);
const web = originalWeb.replace(/MyPlugin/g, className);

await writeFileAsync(join(newPluginPath, `index.ts`), index, 'utf8');
await writeFileAsync(
join(newPluginPath, `definitions.ts`),
definitions,
Expand Down Expand Up @@ -321,7 +327,7 @@ function generatePackageJSON(answers: NewPluginAnswers, cliVersion: string) {
rimraf: '^3.0.0',
rollup: '^2.21.0',
swiftlint: '^1.0.1',
typescript: '~3.8.3',
typescript: '~3.9.7',
},
peerDependencies: {
'@capacitor/core': `^${cliVersion}`,
Expand Down
3 changes: 2 additions & 1 deletion core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export {

export * from './core-plugin-definitions';
export * from './global';
export * from './plugins';
export * from './web-plugins';
export * from './web/index';
export * from './web';
104 changes: 104 additions & 0 deletions core/src/plugins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { Capacitor } from './global';
import { WebPlugin } from './web';

const PLUGIN_REGISTRY = new (class {
protected readonly plugins: {
[plugin: string]: RegisteredPlugin<unknown>;
} = {};

get(name: string): RegisteredPlugin<unknown> | undefined {
return this.plugins[name];
}

has(name: string): boolean {
return !!this.get(name);
}

register(plugin: RegisteredPlugin<unknown>): void {
this.plugins[plugin.name] = plugin;
}
})();

/**
* A map of plugin implementations.
*
* Each key should be the lowercased platform name as recognized by Capacitor,
* e.g. 'android', 'ios', and 'web'. Each value must be an instance of a plugin
* implementation for the respective platform.
*/
export type PluginImplementations<T> = {
[platform: string]: T;
};

/**
* Represents a plugin registered with Capacitor.
*/
export class RegisteredPlugin<T> {
constructor(
readonly name: string,
readonly implementations: Readonly<PluginImplementations<T>>,
) {}

/**
* Return the appropriate implementation of this plugin.
*
* Supply a platform to return the implementation for it, otherwise this
* method will return the implementation for the current platform as detected
* by Capacitor.
*
* @param platform Optionally return the implementation of the given
* platform.
*/
getImplementation(platform?: string): T | undefined {
return this.implementations[platform ? platform : Capacitor.platform];
}
}

/**
* Register plugin implementations with Capacitor.
*
* This function will create and register an instance that contains the
* implementations of the plugin.
*
* Each plugin has multiple implementations, one per platform. Each
* implementation must adhere to a common interface to ensure client code
* behaves consistently across each platform.
*
* @param name The unique CamelCase name of this plugin.
* @param implementations The map of plugin implementations.
*/
export const registerPlugin = <T>(
name: string,
implementations: Readonly<PluginImplementations<T>>,
): RegisteredPlugin<T> => {
const plugin = new RegisteredPlugin(name, implementations);
PLUGIN_REGISTRY.register(plugin);

return plugin;
};

/**
* TODO
*
* @deprecated Don't use this.
*/
export const registerWebPlugin = (plugin: WebPlugin) => {
console.warn(
`Capacitor plugin ${plugin.config.name} is using deprecated method 'registerWebPlugin'`,
); // TODO: add link to upgrade guide

if (!PLUGIN_REGISTRY.has(plugin.config.name)) {
const { name, platforms = ['web'] } = plugin.config;
const implementations: PluginImplementations<unknown> = {};

PLUGIN_REGISTRY.register(
new RegisteredPlugin(
name,
platforms.reduce((acc, value) => {
acc[value] = plugin;
return acc;
}, implementations),
),
);
}
};
9 changes: 0 additions & 9 deletions core/src/web-plugins.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { Plugins } from './global';
import { mergeWebPlugins, mergeWebPlugin, WebPlugin } from './web/index';

export * from './web/accessibility';
export * from './web/app';
export * from './web/browser';
Expand All @@ -18,9 +15,3 @@ export * from './web/permissions';
export * from './web/splash-screen';
export * from './web/storage';
export * from './web/toast';

mergeWebPlugins(Plugins);

export const registerWebPlugin = (plugin: WebPlugin) => {
mergeWebPlugin(Plugins, plugin);
};
5 changes: 1 addition & 4 deletions core/src/web/accessibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import {
export class AccessibilityPluginWeb extends WebPlugin
implements AccessibilityPlugin {
constructor() {
super({
name: 'Accessibility',
platforms: ['web'],
});
super({ name: 'Accessibility' });
}

isScreenReaderEnabled(): Promise<ScreenReaderEnabledResult> {
Expand Down
5 changes: 1 addition & 4 deletions core/src/web/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import { AppPlugin, AppLaunchUrl, AppState } from '../core-plugin-definitions';

export class AppPluginWeb extends WebPlugin implements AppPlugin {
constructor() {
super({
name: 'App',
platforms: ['web'],
});
super({ name: 'App' });

if (typeof document !== 'undefined') {
document.addEventListener(
Expand Down
5 changes: 1 addition & 4 deletions core/src/web/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ export class BrowserPluginWeb extends WebPlugin implements BrowserPlugin {
_lastWindow: Window;

constructor() {
super({
name: 'Browser',
platforms: ['web'],
});
super({ name: 'Browser' });
}

async open(options: BrowserOpenOptions): Promise<void> {
Expand Down
5 changes: 1 addition & 4 deletions core/src/web/camera.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import {

export class CameraPluginWeb extends WebPlugin implements CameraPlugin {
constructor() {
super({
name: 'Camera',
platforms: ['web'],
});
super({ name: 'Camera' });
}

async getPhoto(options: CameraOptions): Promise<CameraPhoto> {
Expand Down
5 changes: 1 addition & 4 deletions core/src/web/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ declare var ClipboardItem: any;

export class ClipboardPluginWeb extends WebPlugin implements ClipboardPlugin {
constructor() {
super({
name: 'Clipboard',
platforms: ['web'],
});
super({ name: 'Clipboard' });
}

async write(options: ClipboardWrite): Promise<void> {
Expand Down
5 changes: 1 addition & 4 deletions core/src/web/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@ declare var navigator: any;

export class DevicePluginWeb extends WebPlugin implements DevicePlugin {
constructor() {
super({
name: 'Device',
platforms: ['web'],
});
super({ name: 'Device' });
}

async getInfo(): Promise<DeviceInfo> {
Expand Down
5 changes: 1 addition & 4 deletions core/src/web/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ export class FilesystemPluginWeb extends WebPlugin implements FilesystemPlugin {
static _debug: boolean = true;

constructor() {
super({
name: 'Filesystem',
platforms: ['web'],
});
super({ name: 'Filesystem' });
}

async initDb(): Promise<IDBDatabase> {
Expand Down
5 changes: 1 addition & 4 deletions core/src/web/geolocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ import { extend } from '../util';
export class GeolocationPluginWeb extends WebPlugin
implements GeolocationPlugin {
constructor() {
super({
name: 'Geolocation',
platforms: ['web'],
});
super({ name: 'Geolocation' });
}

getCurrentPosition(
Expand Down
100 changes: 9 additions & 91 deletions core/src/web/index.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,5 @@
import {
Capacitor,
PluginListenerHandle,
PermissionsRequestResult,
} from '../definitions';

declare var Capacitor: Capacitor;

export class WebPluginRegistry {
plugins: { [name: string]: WebPlugin } = {};
loadedPlugins: { [name: string]: WebPlugin } = {};

constructor() {}

addPlugin(plugin: WebPlugin) {
this.plugins[plugin.config.name] = plugin;
}

getPlugin(name: string) {
return this.plugins[name];
}

loadPlugin(name: string) {
let plugin = this.getPlugin(name);
if (!plugin) {
console.error(`Unable to load web plugin ${name}, no such plugin found.`);
return;
}

plugin.load();
}

getPlugins() {
let p = [];
for (let name in this.plugins) {
p.push(this.plugins[name]);
}
return p;
}
}

let WebPlugins = new WebPluginRegistry();
export { WebPlugins };
import { PluginListenerHandle, PermissionsRequestResult } from '../definitions';
import { Capacitor } from '../global';

export type ListenerCallback = (err: any, ...args: any[]) => void;

Expand All @@ -55,12 +14,14 @@ export interface WebPluginConfig {
/**
* The name of the plugin
*/
name: string;
readonly name: string;

/**
* The platforms this web plugin should run on. Leave null
* for this plugin to always run.
* TODO
*
* @deprecated Don't use this.
*/
platforms?: string[];
readonly platforms?: string[];
}

export class WebPlugin {
Expand All @@ -69,16 +30,7 @@ export class WebPlugin {
listeners: { [eventName: string]: ListenerCallback[] } = {};
windowListeners: { [eventName: string]: WindowListenerHandle } = {};

constructor(
public config: WebPluginConfig,
pluginRegistry?: WebPluginRegistry,
) {
if (!pluginRegistry) {
WebPlugins.addPlugin(this);
} else {
pluginRegistry.addPlugin(this);
}
}
constructor(public config: WebPluginConfig) {}

private addWindowListener(handle: WindowListenerHandle): void {
window.addEventListener(handle.windowEventName, handle.handler);
Expand Down Expand Up @@ -184,37 +136,3 @@ export class WebPlugin {
this.loaded = true;
}
}

const shouldMergeWebPlugin = (plugin: WebPlugin) => {
return (
plugin.config.platforms &&
plugin.config.platforms.indexOf(Capacitor.platform) >= 0
);
};

/**
* For all our known web plugins, merge them into the global plugins
* registry if they aren't already existing. If they don't exist, that
* means there's no existing native implementation for it.
* @param knownPlugins the Capacitor.Plugins global registry.
*/
export const mergeWebPlugins = (knownPlugins: any) => {
let plugins = WebPlugins.getPlugins();
for (let plugin of plugins) {
mergeWebPlugin(knownPlugins, plugin);
}
};

export const mergeWebPlugin = (knownPlugins: any, plugin: WebPlugin) => {
// If we already have a plugin registered (meaning it was defined in the native layer),
// then we should only overwrite it if the corresponding web plugin activates on
// a certain platform. For example: Geolocation uses the WebPlugin on Android but not iOS
if (
knownPlugins.hasOwnProperty(plugin.config.name) &&
!shouldMergeWebPlugin(plugin)
) {
return;
}

knownPlugins[plugin.config.name] = plugin;
};
5 changes: 1 addition & 4 deletions core/src/web/local-notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ export class LocalNotificationsPluginWeb extends WebPlugin
private pending: LocalNotification[] = [];

constructor() {
super({
name: 'LocalNotifications',
platforms: ['web'],
});
super({ name: 'LocalNotifications' });
}

createChannel(channel: NotificationChannel): Promise<void> {
Expand Down
Loading