From 1d6d394b739567e8dab3c0cd4480e4d2a405bd24 Mon Sep 17 00:00:00 2001 From: KazariEX <1364035137@qq.com> Date: Tue, 8 Oct 2024 00:22:03 +0800 Subject: [PATCH] fix: avoid running `dispose` multiple times --- src/index.ts | 10 ++++------ src/utils.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index 135506c..e6b530c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 { @@ -70,13 +70,11 @@ 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); @@ -84,7 +82,7 @@ export function createPlainShiki(shiki: HighlighterCore) { highlight?.delete(range); } } - } + }); function patch(loads: ColorLoad[], oldLoads: ColorLoad[]) { for (const { range, name } of walkTokens(oldLoads)) { diff --git a/src/utils.ts b/src/utils.ts index 7436014..6d61f33 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -10,6 +10,18 @@ export function debounce(func: (...args: T) => void, { }; } +export function once(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;