Path: blob/main/src/vs/editor/contrib/find/browser/findWidgetSearchHistory.ts
3296 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { Emitter, Event } from '../../../../base/common/event.js';6import { IHistory } from '../../../../base/common/history.js';7import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';89export class FindWidgetSearchHistory implements IHistory<string> {10public static readonly FIND_HISTORY_KEY = 'workbench.find.history';11private inMemoryValues: Set<string> = new Set();12public onDidChange?: Event<string[]>;13private _onDidChangeEmitter: Emitter<string[]>;1415private static _instance: FindWidgetSearchHistory | null = null;1617static getOrCreate(18storageService: IStorageService,19): FindWidgetSearchHistory {20if (!FindWidgetSearchHistory._instance) {21FindWidgetSearchHistory._instance = new FindWidgetSearchHistory(storageService);22}23return FindWidgetSearchHistory._instance;24}2526constructor(27@IStorageService private readonly storageService: IStorageService,28) {29this._onDidChangeEmitter = new Emitter<string[]>();30this.onDidChange = this._onDidChangeEmitter.event;31this.load();32}3334delete(t: string): boolean {35const result = this.inMemoryValues.delete(t);36this.save();37return result;38}3940add(t: string): this {41this.inMemoryValues.add(t);42this.save();43return this;44}4546has(t: string): boolean {47return this.inMemoryValues.has(t);48}4950clear(): void {51this.inMemoryValues.clear();52this.save();53}5455forEach(callbackfn: (value: string, value2: string, set: Set<string>) => void, thisArg?: any): void {56// fetch latest from storage57this.load();58return this.inMemoryValues.forEach(callbackfn);59}60replace?(t: string[]): void {61this.inMemoryValues = new Set(t);62this.save();63}6465load() {66let result: [] | undefined;67const raw = this.storageService.get(68FindWidgetSearchHistory.FIND_HISTORY_KEY,69StorageScope.WORKSPACE70);7172if (raw) {73try {74result = JSON.parse(raw);75} catch (e) {76// Invalid data77}78}7980this.inMemoryValues = new Set(result || []);81}8283// Run saves async84save(): Promise<void> {85const elements: string[] = [];86this.inMemoryValues.forEach(e => elements.push(e));87return new Promise<void>(resolve => {88this.storageService.store(89FindWidgetSearchHistory.FIND_HISTORY_KEY,90JSON.stringify(elements),91StorageScope.WORKSPACE,92StorageTarget.USER,93);94this._onDidChangeEmitter.fire(elements);95resolve();96});97}98}99100101