Skip to content

Commit

Permalink
fix(plugins-runtime): remove plugin event listener on close
Browse files Browse the repository at this point in the history
  • Loading branch information
juanfran committed Jul 23, 2024
1 parent ef2cb7c commit 2138985
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
7 changes: 7 additions & 0 deletions libs/plugins-runtime/src/lib/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ export function createApi(context: PenpotContext, manifest: Manifest): Penpot {
let modal: PluginModalElement | null = null;

const closePlugin = () => {
// remove all event listeners
Object.entries(listeners).forEach(([, map]) => {
map.forEach((id) => {
context.removeListener(id);
});
});

if (modal) {
modals.delete(modal);

Expand Down
11 changes: 10 additions & 1 deletion libs/plugins-runtime/src/lib/api/plugin-api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,15 @@ describe('Plugin api', () => {
expect(mockContext.removeListener).toHaveBeenCalled();
expect((mockContext.removeListener.mock as any).lastCall[0]).toBe(id);
});

it('remove event on close plugin', () => {
const callback = vi.fn();

api.on('pagechange', callback);
api.closePlugin();

expect(mockContext.removeListener).toHaveBeenCalled();
});
});

describe.concurrent('permissions', () => {
Expand Down Expand Up @@ -227,7 +236,7 @@ describe('Plugin api', () => {
expect(modalMock.setTheme).toHaveBeenCalledWith('dark');
});

it('close puglin', () => {
it('close plugin', () => {
const name = 'test';
const url = 'http://fake.com';
const options = { width: 100, height: 100 };
Expand Down
16 changes: 10 additions & 6 deletions libs/plugins-runtime/src/lib/load-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ export function setContextBuilder(builder: ContextBuilder) {

export const ɵloadPlugin = async function (manifest: Manifest) {
try {
const closeAllPlugins = () => {
createdApis.forEach((pluginApi) => {
pluginApi.closePlugin();
});

createdApis = [];
};

const context = contextBuilder && contextBuilder(manifest.pluginId);

if (!context) {
Expand All @@ -35,9 +43,7 @@ export const ɵloadPlugin = async function (manifest: Manifest) {
}

if (createdApis && !multiPlugin) {
createdApis.forEach((pluginApi) => {
pluginApi.closePlugin();
});
closeAllPlugins();
}

const pluginApi = createApi(context, manifest);
Expand Down Expand Up @@ -70,9 +76,7 @@ export const ɵloadPlugin = async function (manifest: Manifest) {
c.evaluate(code);

const listenerId: symbol = context.addListener('finish', () => {
createdApis.forEach((pluginApi) => {
pluginApi.closePlugin();
});
closeAllPlugins();

context?.removeListener(listenerId);
});
Expand Down

0 comments on commit 2138985

Please sign in to comment.