|
| 1 | +// Copyright (c) jdneo. All rights reserved. |
| 2 | +// Licensed under the MIT license. |
| 3 | + |
| 4 | +import { ConfigurationChangeEvent, Disposable, ExtensionContext, ViewColumn, WebviewPanel, window, workspace } from "vscode"; |
| 5 | +import { markdownEngine } from "./markdownEngine"; |
| 6 | + |
| 7 | +export abstract class LeetCodeWebview implements Disposable { |
| 8 | + |
| 9 | + protected panel: WebviewPanel | undefined; |
| 10 | + private context: ExtensionContext; |
| 11 | + private listener: Disposable; |
| 12 | + |
| 13 | + public initialize(context: ExtensionContext): void { |
| 14 | + this.context = context; |
| 15 | + this.listener = workspace.onDidChangeConfiguration((event: ConfigurationChangeEvent) => { |
| 16 | + if (event.affectsConfiguration("markdown") && this.panel) { |
| 17 | + this.panel.webview.html = this.getWebviewContent(); |
| 18 | + } |
| 19 | + }, this); |
| 20 | + } |
| 21 | + |
| 22 | + public dispose(): void { |
| 23 | + this.listener.dispose(); |
| 24 | + if (this.panel) { |
| 25 | + this.panel.dispose(); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + protected showWebviewInternal(): this is { panel: WebviewPanel } { |
| 30 | + if (!this.panel) { |
| 31 | + const option: ILeetCodeWebviewOption = this.getWebviewOption(); |
| 32 | + |
| 33 | + this.panel = window.createWebviewPanel(option.viewType, option.title, ViewColumn.One, { |
| 34 | + enableScripts: true, |
| 35 | + enableCommandUris: true, |
| 36 | + enableFindWidget: true, |
| 37 | + retainContextWhenHidden: true, |
| 38 | + localResourceRoots: markdownEngine.localResourceRoots, |
| 39 | + }); |
| 40 | + |
| 41 | + this.panel.onDidDispose(() => { |
| 42 | + this.panel = undefined; |
| 43 | + }, null, this.context.subscriptions); |
| 44 | + |
| 45 | + if (option.onDidReceiveMessage) { |
| 46 | + this.panel.webview.onDidReceiveMessage(option.onDidReceiveMessage, this, this.context.subscriptions); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + this.panel.webview.html = this.getWebviewContent(); |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + protected abstract getWebviewOption(): ILeetCodeWebviewOption; |
| 55 | + |
| 56 | + protected abstract getWebviewContent(): string; |
| 57 | +} |
| 58 | + |
| 59 | +export interface ILeetCodeWebviewOption { |
| 60 | + viewType: string; |
| 61 | + title: string; |
| 62 | + onDidReceiveMessage?: (message: any) => Promise<void>; |
| 63 | +} |
0 commit comments