vscode#TextDocumentContentProvider TypeScript Examples

The following examples show how to use vscode#TextDocumentContentProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompiledCodeContentProvider.ts    From language-tools with MIT License 5 votes vote down vote up
export default class CompiledCodeContentProvider implements TextDocumentContentProvider {
    static scheme = SVELTE_URI_SCHEME;
    static toSvelteSchemeUri = toSvelteSchemeUri;
    static fromSvelteSchemeUri = fromSvelteSchemeUri;

    private disposed = false;
    private didChangeEmitter = new EventEmitter<Uri>();
    private subscriptions: Disposable[] = [];
    private watchedSourceUri = new Set<string>();

    get onDidChange() {
        return this.didChangeEmitter.event;
    }

    constructor(private getLanguageClient: () => LanguageClient) {
        this.subscriptions.push(
            workspace.onDidChangeTextDocument(
                debounce(async (changeEvent) => {
                    if (changeEvent.document.languageId !== 'svelte') {
                        return;
                    }

                    const srcUri = changeEvent.document.uri.toString();
                    if (this.watchedSourceUri.has(srcUri)) {
                        this.didChangeEmitter.fire(toSvelteSchemeUri(srcUri));
                    }
                }, 500)
            )
        );

        window.onDidChangeVisibleTextEditors((editors) => {
            const previewEditors = editors.filter(
                (editor) => editor?.document?.uri?.scheme === SVELTE_URI_SCHEME
            );
            this.watchedSourceUri = new Set(
                previewEditors.map((editor) => fromSvelteSchemeUri(editor.document.uri, true))
            );
        });
    }

    async provideTextDocumentContent(uri: Uri): Promise<string | undefined> {
        const srcUriStr = fromSvelteSchemeUri(uri, true);
        this.watchedSourceUri.add(srcUriStr);

        const resp = await this.getLanguageClient().sendRequest<CompiledCodeResp>(
            '$/getCompiledCode',
            srcUriStr
        );
        if (resp?.js?.code) {
            return resp.js.code;
        } else {
            window.setStatusBarMessage(`Svelte: fail to compile ${uri.path}`, 3000);
        }
    }

    dispose() {
        if (this.disposed) {
            return;
        }

        this.didChangeEmitter.dispose();
        this.subscriptions.forEach((d) => d.dispose());
        this.subscriptions.length = 0;
        this.disposed = true;
    }
}