Skip to content

Commit

Permalink
fix: avoid running dispose multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
KazariEX committed Oct 7, 2024
1 parent 1226ba0 commit 1d6d394
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
10 changes: 4 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { BundledLanguage, BundledTheme, CodeToTokensWithThemesOptions, HighlighterCore } from "shiki";
import { diff } from "./diff";
import { debounce, isArrayEqual } from "./utils";
import { debounce, isArrayEqual, once } from "./utils";
import type { ColorLoad, LoadLine } from "./types";

export interface MountPlainShikiOptions {
Expand Down Expand Up @@ -70,21 +70,19 @@ export function createPlainShiki(shiki: HighlighterCore) {
update();
}

function dispose() {
const dispose = once(() => {
watch && el.removeEventListener("input", debouncedUpdate);

const idx = document.adoptedStyleSheets.indexOf(stylesheet);
if (idx !== -1) {
document.adoptedStyleSheets.splice(idx, 1);
}
document.adoptedStyleSheets.splice(idx, 1);

for (const [name, ranges] of colorRanges) {
const highlight = CSS.highlights.get(name);
for (const range of ranges) {
highlight?.delete(range);
}
}
}
});

function patch(loads: ColorLoad[], oldLoads: ColorLoad[]) {
for (const { range, name } of walkTokens(oldLoads)) {
Expand Down
12 changes: 12 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ export function debounce<T extends unknown[]>(func: (...args: T) => void, {
};
}

export function once<T extends unknown[]>(func: (...args: T) => void) {
let called = false;
return function(this: unknown, ...args: T) {
if (called) {
return false;
}
called = true;
func.apply(this, args);
return true;
};
}

export function isArrayEqual(a: unknown[], b: unknown[]) {
if (a.length !== b.length) {
return false;
Expand Down

0 comments on commit 1d6d394

Please sign in to comment.