hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 2, "code_window": [ "\t\tthis.portMappingProvider = this._register(new WebviewPortMappingProvider(tunnelService));\n", "\n", "\t\tconst sess = session.fromPartition(webviewPartitionId);\n", "\t\tsess.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n", "\t\t\treturn callback(false);\n", "\t\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsess.setPermissionRequestHandler((_webContents, permission, callback) => {\n", "\t\t\tif (permission === 'clipboard-read') {\n", "\t\t\t\treturn callback(true);\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts", "type": "replace", "edit_start_line_idx": 37 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.nls = void 0; const lazy = require("lazy.js"); const event_stream_1 = require("event-stream"); const File = require("vinyl"); const sm = require("source-map"); const path = require("path"); var CollectStepResult; (function (CollectStepResult) { CollectStepResult[CollectStepResult["Yes"] = 0] = "Yes"; CollectStepResult[CollectStepResult["YesAndRecurse"] = 1] = "YesAndRecurse"; CollectStepResult[CollectStepResult["No"] = 2] = "No"; CollectStepResult[CollectStepResult["NoAndRecurse"] = 3] = "NoAndRecurse"; })(CollectStepResult || (CollectStepResult = {})); function collect(ts, node, fn) { const result = []; function loop(node) { const stepResult = fn(node); if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) { result.push(node); } if (stepResult === CollectStepResult.YesAndRecurse || stepResult === CollectStepResult.NoAndRecurse) { ts.forEachChild(node, loop); } } loop(node); return result; } function clone(object) { const result = {}; for (const id in object) { result[id] = object[id]; } return result; } function template(lines) { let indent = '', wrap = ''; if (lines.length > 1) { indent = '\t'; wrap = '\n'; } return `/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ define([], [${wrap + lines.map(l => indent + l).join(',\n') + wrap}]);`; } /** * Returns a stream containing the patched JavaScript and source maps. */ function nls() { const input = event_stream_1.through(); const output = input.pipe(event_stream_1.through(function (f) { if (!f.sourceMap) { return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`)); } let source = f.sourceMap.sources[0]; if (!source) { return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`)); } const root = f.sourceMap.sourceRoot; if (root) { source = path.join(root, source); } const typescript = f.sourceMap.sourcesContent[0]; if (!typescript) { return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`)); } _nls.patchFiles(f, typescript).forEach(f => this.emit('data', f)); })); return event_stream_1.duplex(input, output); } exports.nls = nls; function isImportNode(ts, node) { return node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ImportEqualsDeclaration; } var _nls; (function (_nls) { function fileFrom(file, contents, path = file.path) { return new File({ contents: Buffer.from(contents), base: file.base, cwd: file.cwd, path: path }); } function mappedPositionFrom(source, lc) { return { source, line: lc.line + 1, column: lc.character }; } function lcFrom(position) { return { line: position.line - 1, character: position.column }; } class SingleFileServiceHost { constructor(ts, options, filename, contents) { this.options = options; this.filename = filename; this.getCompilationSettings = () => this.options; this.getScriptFileNames = () => [this.filename]; this.getScriptVersion = () => '1'; this.getScriptSnapshot = (name) => name === this.filename ? this.file : this.lib; this.getCurrentDirectory = () => ''; this.getDefaultLibFileName = () => 'lib.d.ts'; this.file = ts.ScriptSnapshot.fromString(contents); this.lib = ts.ScriptSnapshot.fromString(''); } } function isCallExpressionWithinTextSpanCollectStep(ts, textSpan, node) { if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) { return CollectStepResult.No; } return node.kind === ts.SyntaxKind.CallExpression ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse; } function analyze(ts, contents, options = {}) { const filename = 'file.ts'; const serviceHost = new SingleFileServiceHost(ts, Object.assign(clone(options), { noResolve: true }), filename, contents); const service = ts.createLanguageService(serviceHost); const sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true); // all imports const imports = lazy(collect(ts, sourceFile, n => isImportNode(ts, n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse)); // import nls = require('vs/nls'); const importEqualsDeclarations = imports .filter(n => n.kind === ts.SyntaxKind.ImportEqualsDeclaration) .map(n => n) .filter(d => d.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) .filter(d => d.moduleReference.expression.getText() === '\'vs/nls\''); // import ... from 'vs/nls'; const importDeclarations = imports .filter(n => n.kind === ts.SyntaxKind.ImportDeclaration) .map(n => n) .filter(d => d.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) .filter(d => d.moduleSpecifier.getText() === '\'vs/nls\'') .filter(d => !!d.importClause && !!d.importClause.namedBindings); const nlsExpressions = importEqualsDeclarations .map(d => d.moduleReference.expression) .concat(importDeclarations.map(d => d.moduleSpecifier)) .map(d => ({ start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd()) })); // `nls.localize(...)` calls const nlsLocalizeCallExpressions = importDeclarations .filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamespaceImport)) .map(d => d.importClause.namedBindings.name) .concat(importEqualsDeclarations.map(d => d.name)) // find read-only references to `nls` .map(n => service.getReferencesAtPosition(filename, n.pos + 1)) .flatten() .filter(r => !r.isWriteAccess) // find the deepest call expressions AST nodes that contain those references .map(r => collect(ts, sourceFile, n => isCallExpressionWithinTextSpanCollectStep(ts, r.textSpan, n))) .map(a => lazy(a).last()) .filter(n => !!n) .map(n => n) // only `localize` calls .filter(n => n.expression.kind === ts.SyntaxKind.PropertyAccessExpression && n.expression.name.getText() === 'localize'); // `localize` named imports const allLocalizeImportDeclarations = importDeclarations .filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports)) .map(d => [].concat(d.importClause.namedBindings.elements)) .flatten(); // `localize` read-only references const localizeReferences = allLocalizeImportDeclarations .filter(d => d.name.getText() === 'localize') .map(n => service.getReferencesAtPosition(filename, n.pos + 1)) .flatten() .filter(r => !r.isWriteAccess); // custom named `localize` read-only references const namedLocalizeReferences = allLocalizeImportDeclarations .filter(d => d.propertyName && d.propertyName.getText() === 'localize') .map(n => service.getReferencesAtPosition(filename, n.name.pos + 1)) .flatten() .filter(r => !r.isWriteAccess); // find the deepest call expressions AST nodes that contain those references const localizeCallExpressions = localizeReferences .concat(namedLocalizeReferences) .map(r => collect(ts, sourceFile, n => isCallExpressionWithinTextSpanCollectStep(ts, r.textSpan, n))) .map(a => lazy(a).last()) .filter(n => !!n) .map(n => n); // collect everything const localizeCalls = nlsLocalizeCallExpressions .concat(localizeCallExpressions) .map(e => e.arguments) .filter(a => a.length > 1) .sort((a, b) => a[0].getStart() - b[0].getStart()) .map(a => ({ keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) }, key: a[0].getText(), valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) }, value: a[1].getText() })); return { localizeCalls: localizeCalls.toArray(), nlsExpressions: nlsExpressions.toArray() }; } class TextModel { constructor(contents) { const regex = /\r\n|\r|\n/g; let index = 0; let match; this.lines = []; this.lineEndings = []; while (match = regex.exec(contents)) { this.lines.push(contents.substring(index, match.index)); this.lineEndings.push(match[0]); index = regex.lastIndex; } if (contents.length > 0) { this.lines.push(contents.substring(index, contents.length)); this.lineEndings.push(''); } } get(index) { return this.lines[index]; } set(index, line) { this.lines[index] = line; } get lineCount() { return this.lines.length; } /** * Applies patch(es) to the model. * Multiple patches must be ordered. * Does not support patches spanning multiple lines. */ apply(patch) { const startLineNumber = patch.span.start.line; const endLineNumber = patch.span.end.line; const startLine = this.lines[startLineNumber] || ''; const endLine = this.lines[endLineNumber] || ''; this.lines[startLineNumber] = [ startLine.substring(0, patch.span.start.character), patch.content, endLine.substring(patch.span.end.character) ].join(''); for (let i = startLineNumber + 1; i <= endLineNumber; i++) { this.lines[i] = ''; } } toString() { return lazy(this.lines).zip(this.lineEndings) .flatten().toArray().join(''); } } function patchJavascript(patches, contents, moduleId) { const model = new TextModel(contents); // patch the localize calls lazy(patches).reverse().each(p => model.apply(p)); // patch the 'vs/nls' imports const firstLine = model.get(0); const patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`); model.set(0, patchedFirstLine); return model.toString(); } function patchSourcemap(patches, rsm, smc) { const smg = new sm.SourceMapGenerator({ file: rsm.file, sourceRoot: rsm.sourceRoot }); patches = patches.reverse(); let currentLine = -1; let currentLineDiff = 0; let source = null; smc.eachMapping(m => { const patch = patches[patches.length - 1]; const original = { line: m.originalLine, column: m.originalColumn }; const generated = { line: m.generatedLine, column: m.generatedColumn }; if (currentLine !== generated.line) { currentLineDiff = 0; } currentLine = generated.line; generated.column += currentLineDiff; if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) { const originalLength = patch.span.end.character - patch.span.start.character; const modifiedLength = patch.content.length; const lengthDiff = modifiedLength - originalLength; currentLineDiff += lengthDiff; generated.column += lengthDiff; patches.pop(); } source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source; source = source.replace(/\\/g, '/'); smg.addMapping({ source, name: m.name, original, generated }); }, null, sm.SourceMapConsumer.GENERATED_ORDER); if (source) { smg.setSourceContent(source, smc.sourceContentFor(source)); } return JSON.parse(smg.toString()); } function patch(ts, moduleId, typescript, javascript, sourcemap) { const { localizeCalls, nlsExpressions } = analyze(ts, typescript); if (localizeCalls.length === 0) { return { javascript, sourcemap }; } const nlsKeys = template(localizeCalls.map(lc => lc.key)); const nls = template(localizeCalls.map(lc => lc.value)); const smc = new sm.SourceMapConsumer(sourcemap); const positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]); let i = 0; // build patches const patches = lazy(localizeCalls) .map(lc => ([ { range: lc.keySpan, content: '' + (i++) }, { range: lc.valueSpan, content: 'null' } ])) .flatten() .map(c => { const start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start))); const end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end))); return { span: { start, end }, content: c.content }; }) .toArray(); javascript = patchJavascript(patches, javascript, moduleId); // since imports are not within the sourcemap information, // we must do this MacGyver style if (nlsExpressions.length) { javascript = javascript.replace(/^define\(.*$/m, line => { return line.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`); }); } sourcemap = patchSourcemap(patches, sourcemap, smc); return { javascript, sourcemap, nlsKeys, nls }; } function patchFiles(javascriptFile, typescript) { const ts = require('typescript'); // hack? const moduleId = javascriptFile.relative .replace(/\.js$/, '') .replace(/\\/g, '/'); const { javascript, sourcemap, nlsKeys, nls } = patch(ts, moduleId, typescript, javascriptFile.contents.toString(), javascriptFile.sourceMap); const result = [fileFrom(javascriptFile, javascript)]; result[0].sourceMap = sourcemap; if (nlsKeys) { result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js'))); } if (nls) { result.push(fileFrom(javascriptFile, nls, javascriptFile.path.replace(/\.js$/, '.nls.js'))); } return result; } _nls.patchFiles = patchFiles; })(_nls || (_nls = {}));
build/lib/nls.js
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017753493739292026, 0.00017409160500392318, 0.00016638079250697047, 0.00017407347331754863, 0.000002522756631151424 ]
{ "id": 2, "code_window": [ "\t\tthis.portMappingProvider = this._register(new WebviewPortMappingProvider(tunnelService));\n", "\n", "\t\tconst sess = session.fromPartition(webviewPartitionId);\n", "\t\tsess.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => {\n", "\t\t\treturn callback(false);\n", "\t\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsess.setPermissionRequestHandler((_webContents, permission, callback) => {\n", "\t\t\tif (permission === 'clipboard-read') {\n", "\t\t\t\treturn callback(true);\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts", "type": "replace", "edit_start_line_idx": 37 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { IListService } from 'vs/platform/list/browser/listService'; import { OpenEditor, SortOrder } from 'vs/workbench/contrib/files/common/files'; import { EditorResourceAccessor, SideBySideEditor, IEditorIdentifier, EditorInput, IEditorInputFactory } from 'vs/workbench/common/editor'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel'; import { coalesce } from 'vs/base/common/arrays'; import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditableData } from 'vs/workbench/common/views'; import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ResourceFileEdit } from 'vs/editor/browser/services/bulkEditService'; import { ProgressLocation } from 'vs/platform/progress/common/progress'; import { FileEditorInput } from 'vs/workbench/contrib/files/common/editors/fileEditorInput'; import { isEqual } from 'vs/base/common/resources'; interface ISerializedFileEditorInput { resourceJSON: UriComponents; preferredResourceJSON?: UriComponents; name?: string; description?: string; encoding?: string; modeId?: string; } export class FileEditorInputFactory implements IEditorInputFactory { canSerialize(editorInput: EditorInput): boolean { return true; } serialize(editorInput: EditorInput): string { const fileEditorInput = <FileEditorInput>editorInput; const resource = fileEditorInput.resource; const preferredResource = fileEditorInput.preferredResource; const serializedFileEditorInput: ISerializedFileEditorInput = { resourceJSON: resource.toJSON(), preferredResourceJSON: isEqual(resource, preferredResource) ? undefined : preferredResource, // only storing preferredResource if it differs from the resource name: fileEditorInput.getPreferredName(), description: fileEditorInput.getPreferredDescription(), encoding: fileEditorInput.getEncoding(), modeId: fileEditorInput.getPreferredMode() // only using the preferred user associated mode here if available to not store redundant data }; return JSON.stringify(serializedFileEditorInput); } deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): FileEditorInput { return instantiationService.invokeFunction<FileEditorInput>(accessor => { const serializedFileEditorInput: ISerializedFileEditorInput = JSON.parse(serializedEditorInput); const resource = URI.revive(serializedFileEditorInput.resourceJSON); const preferredResource = URI.revive(serializedFileEditorInput.preferredResourceJSON); const name = serializedFileEditorInput.name; const description = serializedFileEditorInput.description; const encoding = serializedFileEditorInput.encoding; const mode = serializedFileEditorInput.modeId; const fileEditorInput = accessor.get(IEditorService).createEditorInput({ resource, label: name, description, encoding, mode, forceFile: true }) as FileEditorInput; if (preferredResource) { fileEditorInput.setPreferredResource(preferredResource); } return fileEditorInput; }); } } export interface IExplorerService { readonly _serviceBrand: undefined; readonly roots: ExplorerItem[]; readonly sortOrder: SortOrder; getContext(respectMultiSelection: boolean): ExplorerItem[]; hasViewFocus(): boolean; setEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>; getEditable(): { stat: ExplorerItem, data: IEditableData } | undefined; getEditableData(stat: ExplorerItem): IEditableData | undefined; // If undefined is passed checks if any element is currently being edited. isEditable(stat: ExplorerItem | undefined): boolean; findClosest(resource: URI): ExplorerItem | null; refresh(): Promise<void>; setToCopy(stats: ExplorerItem[], cut: boolean): Promise<void>; isCut(stat: ExplorerItem): boolean; applyBulkEdit(edit: ResourceFileEdit[], options: { undoLabel: string, progressLabel: string, confirmBeforeUndo?: boolean, progressLocation?: ProgressLocation.Explorer | ProgressLocation.Window }): Promise<void>; /** * Selects and reveal the file element provided by the given resource if its found in the explorer. * Will try to resolve the path in case the explorer is not yet expanded to the file yet. */ select(resource: URI, reveal?: boolean | string): Promise<void>; registerView(contextAndRefreshProvider: IExplorerView): void; } export const IExplorerService = createDecorator<IExplorerService>('explorerService'); export interface IExplorerView { getContext(respectMultiSelection: boolean): ExplorerItem[]; refresh(recursive: boolean, item?: ExplorerItem): Promise<void>; selectResource(resource: URI | undefined, reveal?: boolean | string): Promise<void>; setTreeInput(): Promise<void>; itemsCopied(tats: ExplorerItem[], cut: boolean, previousCut: ExplorerItem[] | undefined): void; setEditable(stat: ExplorerItem, isEditing: boolean): Promise<void>; focusNeighbourIfItemFocused(item: ExplorerItem): void; isItemVisible(item: ExplorerItem): boolean; hasFocus(): boolean; } function getFocus(listService: IListService): unknown | undefined { let list = listService.lastFocusedList; if (list?.getHTMLElement() === document.activeElement) { let focus: unknown; if (list instanceof List) { const focused = list.getFocusedElements(); if (focused.length) { focus = focused[0]; } } else if (list instanceof AsyncDataTree) { const focused = list.getFocus(); if (focused.length) { focus = focused[0]; } } return focus; } return undefined; } // Commands can get executed from a command palette, from a context menu or from some list using a keybinding // To cover all these cases we need to properly compute the resource on which the command is being executed export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined { if (URI.isUri(resource)) { return resource; } const focus = getFocus(listService); if (focus instanceof ExplorerItem) { return focus.resource; } else if (focus instanceof OpenEditor) { return focus.getResource(); } return EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY }); } export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> { const list = listService.lastFocusedList; if (list?.getHTMLElement() === document.activeElement) { // Explorer if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) { // Explorer const context = explorerService.getContext(true); if (context.length) { return context.map(c => c.resource); } } // Open editors view if (list instanceof List) { const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource())); const focusedElements = list.getFocusedElements(); const focus = focusedElements.length ? focusedElements[0] : undefined; let mainUriStr: string | undefined = undefined; if (URI.isUri(resource)) { mainUriStr = resource.toString(); } else if (focus instanceof OpenEditor) { const focusedResource = focus.getResource(); mainUriStr = focusedResource ? focusedResource.toString() : undefined; } // We only respect the selection if it contains the main element. if (selection.some(s => s.toString() === mainUriStr)) { return selection; } } } const result = getResourceForCommand(resource, listService, editorService); return !!result ? [result] : []; } export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined { const list = listService.lastFocusedList; if (list?.getHTMLElement() === document.activeElement) { // Open editors view if (list instanceof List) { const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor)); const focusedElements = list.getFocusedElements(); const focus = focusedElements.length ? focusedElements[0] : undefined; let mainEditor: IEditorIdentifier | undefined = undefined; if (focus instanceof OpenEditor) { mainEditor = focus; } // We only respect the selection if it contains the main element. if (selection.some(s => s === mainEditor)) { return selection; } } } return undefined; }
src/vs/workbench/contrib/files/browser/files.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00018783376435749233, 0.0001742811728036031, 0.0001687581097939983, 0.00017370257410220802, 0.0000035760467653744854 ]
{ "id": 3, "code_window": [ "\t\t\treturn callback(false);\n", "\t\t});\n", "\n", "\t\tsess.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n", "\t\t\treturn false;\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsess.setPermissionCheckHandler((_webContents, permission /* 'media' */) => {\n", "\t\t\treturn permission === 'clipboard-read';\n" ], "file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { session, WebContents, webContents } from 'electron'; import { Disposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITunnelService } from 'vs/platform/remote/common/tunnel'; import { IRequestService } from 'vs/platform/request/common/request'; import { webviewPartitionId } from 'vs/platform/webview/common/resourceLoader'; import { IWebviewManagerService, RegisterWebviewMetadata, WebviewManagerDidLoadResourceResponse, WebviewWebContentsId, WebviewWindowId } from 'vs/platform/webview/common/webviewManagerService'; import { WebviewPortMappingProvider } from 'vs/platform/webview/electron-main/webviewPortMappingProvider'; import { WebviewProtocolProvider } from 'vs/platform/webview/electron-main/webviewProtocolProvider'; import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows'; export class WebviewMainService extends Disposable implements IWebviewManagerService { declare readonly _serviceBrand: undefined; private readonly protocolProvider: WebviewProtocolProvider; private readonly portMappingProvider: WebviewPortMappingProvider; constructor( @IFileService fileService: IFileService, @ILogService logService: ILogService, @IRequestService requestService: IRequestService, @ITunnelService tunnelService: ITunnelService, @IWindowsMainService private readonly windowsMainService: IWindowsMainService, ) { super(); this.protocolProvider = this._register(new WebviewProtocolProvider(fileService, logService, requestService, windowsMainService)); this.portMappingProvider = this._register(new WebviewPortMappingProvider(tunnelService)); const sess = session.fromPartition(webviewPartitionId); sess.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => { return callback(false); }); sess.setPermissionCheckHandler((webContents, permission /* 'media' */) => { return false; }); } public async registerWebview(id: string, windowId: number, metadata: RegisterWebviewMetadata): Promise<void> { const extensionLocation = metadata.extensionLocation ? URI.from(metadata.extensionLocation) : undefined; this.protocolProvider.registerWebview(id, { ...metadata, windowId: windowId, extensionLocation, localResourceRoots: metadata.localResourceRoots.map(x => URI.from(x)) }); this.portMappingProvider.registerWebview(id, { extensionLocation, mappings: metadata.portMappings, resolvedAuthority: metadata.remoteConnectionData, }); } public async unregisterWebview(id: string): Promise<void> { this.protocolProvider.unregisterWebview(id); this.portMappingProvider.unregisterWebview(id); } public async updateWebviewMetadata(id: string, metaDataDelta: Partial<RegisterWebviewMetadata>): Promise<void> { const extensionLocation = metaDataDelta.extensionLocation ? URI.from(metaDataDelta.extensionLocation) : undefined; this.protocolProvider.updateWebviewMetadata(id, { ...metaDataDelta, extensionLocation, localResourceRoots: metaDataDelta.localResourceRoots?.map(x => URI.from(x)), }); this.portMappingProvider.updateWebviewMetadata(id, { ...metaDataDelta, extensionLocation, }); } public async setIgnoreMenuShortcuts(id: WebviewWebContentsId | WebviewWindowId, enabled: boolean): Promise<void> { let contents: WebContents | undefined; if (typeof (id as WebviewWindowId).windowId === 'number') { const { windowId } = (id as WebviewWindowId); const window = this.windowsMainService.getWindowById(windowId); if (!window?.win) { throw new Error(`Invalid windowId: ${windowId}`); } contents = window.win.webContents; } else { const { webContentsId } = (id as WebviewWebContentsId); contents = webContents.fromId(webContentsId); if (!contents) { throw new Error(`Invalid webContentsId: ${webContentsId}`); } } if (!contents.isDestroyed()) { contents.setIgnoreMenuShortcuts(enabled); } } public async didLoadResource(requestId: number, response: WebviewManagerDidLoadResourceResponse): Promise<void> { this.protocolProvider.didLoadResource(requestId, response); } }
src/vs/platform/webview/electron-main/webviewMainService.ts
1
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.05514134466648102, 0.005074113141745329, 0.0001646838936721906, 0.00017383915837854147, 0.015114602632820606 ]
{ "id": 3, "code_window": [ "\t\t\treturn callback(false);\n", "\t\t});\n", "\n", "\t\tsess.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n", "\t\t\treturn false;\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsess.setPermissionCheckHandler((_webContents, permission /* 'media' */) => {\n", "\t\t\treturn permission === 'clipboard-read';\n" ], "file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IDialogHandler, IDialogResult, IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { ILogService } from 'vs/platform/log/common/log'; import { IProductService } from 'vs/platform/product/common/productService'; import { Registry } from 'vs/platform/registry/common/platform'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IDialogsModel, IDialogViewItem } from 'vs/workbench/common/dialogs'; import { BrowserDialogHandler } from 'vs/workbench/browser/parts/dialogs/dialogHandler'; import { DialogService } from 'vs/workbench/services/dialogs/common/dialogService'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { Disposable } from 'vs/base/common/lifecycle'; export class DialogHandlerContribution extends Disposable implements IWorkbenchContribution { private readonly model: IDialogsModel; private readonly impl: IDialogHandler; private currentDialog: IDialogViewItem | undefined; constructor( @IDialogService private dialogService: IDialogService, @ILogService logService: ILogService, @ILayoutService layoutService: ILayoutService, @IThemeService themeService: IThemeService, @IKeybindingService keybindingService: IKeybindingService, @IProductService productService: IProductService, @IClipboardService clipboardService: IClipboardService ) { super(); this.impl = new BrowserDialogHandler(logService, layoutService, themeService, keybindingService, productService, clipboardService); this.model = (this.dialogService as DialogService).model; this._register(this.model.onDidShowDialog(() => { if (!this.currentDialog) { this.processDialogs(); } })); this.processDialogs(); } private async processDialogs(): Promise<void> { while (this.model.dialogs.length) { this.currentDialog = this.model.dialogs[0]; let result: IDialogResult | undefined = undefined; if (this.currentDialog.args.confirmArgs) { const args = this.currentDialog.args.confirmArgs; result = await this.impl.confirm(args.confirmation); } else if (this.currentDialog.args.inputArgs) { const args = this.currentDialog.args.inputArgs; result = await this.impl.input(args.severity, args.message, args.buttons, args.inputs, args.options); } else if (this.currentDialog.args.showArgs) { const args = this.currentDialog.args.showArgs; result = await this.impl.show(args.severity, args.message, args.buttons, args.options); } else { await this.impl.about(); } this.currentDialog.close(result); this.currentDialog = undefined; } } } const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); workbenchRegistry.registerWorkbenchContribution(DialogHandlerContribution, LifecyclePhase.Starting);
src/vs/workbench/browser/parts/dialogs/dialog.web.contribution.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017468536680098623, 0.00017036877397913486, 0.00016333040548488498, 0.0001717709528747946, 0.000003427855972404359 ]
{ "id": 3, "code_window": [ "\t\t\treturn callback(false);\n", "\t\t});\n", "\n", "\t\tsess.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n", "\t\t\treturn false;\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsess.setPermissionCheckHandler((_webContents, permission /* 'media' */) => {\n", "\t\t\treturn permission === 'clipboard-read';\n" ], "file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as arrays from 'vs/base/common/arrays'; import { IntervalTimer, TimeoutTimer } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode, Keybinding, ResolvedKeybinding } from 'vs/base/common/keyCodes'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IContextKeyService, IContextKeyServiceTarget } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingEvent, IKeybindingService, IKeyboardEvent, KeybindingsSchemaContribution } from 'vs/platform/keybinding/common/keybinding'; import { IResolveResult, KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver'; import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification } from 'vs/base/common/actions'; import { ILogService } from 'vs/platform/log/common/log'; interface CurrentChord { keypress: string; label: string | null; } export abstract class AbstractKeybindingService extends Disposable implements IKeybindingService { public _serviceBrand: undefined; protected readonly _onDidUpdateKeybindings: Emitter<IKeybindingEvent> = this._register(new Emitter<IKeybindingEvent>()); get onDidUpdateKeybindings(): Event<IKeybindingEvent> { return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : Event.None; // Sinon stubbing walks properties on prototype } private _currentChord: CurrentChord | null; private _currentChordChecker: IntervalTimer; private _currentChordStatusMessage: IDisposable | null; private _currentSingleModifier: null | string; private _currentSingleModifierClearTimeout: TimeoutTimer; protected _logging: boolean; public get inChordMode(): boolean { return !!this._currentChord; } constructor( private _contextKeyService: IContextKeyService, protected _commandService: ICommandService, protected _telemetryService: ITelemetryService, private _notificationService: INotificationService, protected _logService: ILogService, ) { super(); this._currentChord = null; this._currentChordChecker = new IntervalTimer(); this._currentChordStatusMessage = null; this._currentSingleModifier = null; this._currentSingleModifierClearTimeout = new TimeoutTimer(); this._logging = false; } public dispose(): void { super.dispose(); } protected abstract _getResolver(): KeybindingResolver; protected abstract _documentHasFocus(): boolean; public abstract resolveKeybinding(keybinding: Keybinding): ResolvedKeybinding[]; public abstract resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding; public abstract resolveUserBinding(userBinding: string): ResolvedKeybinding[]; public abstract registerSchemaContribution(contribution: KeybindingsSchemaContribution): void; public abstract _dumpDebugInfo(): string; public abstract _dumpDebugInfoJSON(): string; public getDefaultKeybindingsContent(): string { return ''; } public toggleLogging(): boolean { this._logging = !this._logging; return this._logging; } protected _log(str: string): void { if (this._logging) { this._logService.info(`[KeybindingService]: ${str}`); } } public getDefaultKeybindings(): readonly ResolvedKeybindingItem[] { return this._getResolver().getDefaultKeybindings(); } public getKeybindings(): readonly ResolvedKeybindingItem[] { return this._getResolver().getKeybindings(); } public customKeybindingsCount(): number { return 0; } public lookupKeybindings(commandId: string): ResolvedKeybinding[] { return arrays.coalesce( this._getResolver().lookupKeybindings(commandId).map(item => item.resolvedKeybinding) ); } public lookupKeybinding(commandId: string): ResolvedKeybinding | undefined { const result = this._getResolver().lookupPrimaryKeybinding(commandId); if (!result) { return undefined; } return result.resolvedKeybinding; } public dispatchEvent(e: IKeyboardEvent, target: IContextKeyServiceTarget): boolean { return this._dispatch(e, target); } public softDispatch(e: IKeyboardEvent, target: IContextKeyServiceTarget): IResolveResult | null { const keybinding = this.resolveKeyboardEvent(e); if (keybinding.isChord()) { console.warn('Unexpected keyboard event mapped to a chord'); return null; } const [firstPart,] = keybinding.getDispatchParts(); if (firstPart === null) { // cannot be dispatched, probably only modifier keys return null; } const contextValue = this._contextKeyService.getContext(target); const currentChord = this._currentChord ? this._currentChord.keypress : null; return this._getResolver().resolve(contextValue, currentChord, firstPart); } private _enterChordMode(firstPart: string, keypressLabel: string | null): void { this._currentChord = { keypress: firstPart, label: keypressLabel }; this._currentChordStatusMessage = this._notificationService.status(nls.localize('first.chord', "({0}) was pressed. Waiting for second key of chord...", keypressLabel)); const chordEnterTime = Date.now(); this._currentChordChecker.cancelAndSet(() => { if (!this._documentHasFocus()) { // Focus has been lost => leave chord mode this._leaveChordMode(); return; } if (Date.now() - chordEnterTime > 5000) { // 5 seconds elapsed => leave chord mode this._leaveChordMode(); } }, 500); } private _leaveChordMode(): void { if (this._currentChordStatusMessage) { this._currentChordStatusMessage.dispose(); this._currentChordStatusMessage = null; } this._currentChordChecker.cancel(); this._currentChord = null; } public dispatchByUserSettingsLabel(userSettingsLabel: string, target: IContextKeyServiceTarget): void { const keybindings = this.resolveUserBinding(userSettingsLabel); if (keybindings.length >= 1) { this._doDispatch(keybindings[0], target, /*isSingleModiferChord*/false); } } protected _dispatch(e: IKeyboardEvent, target: IContextKeyServiceTarget): boolean { return this._doDispatch(this.resolveKeyboardEvent(e), target, /*isSingleModiferChord*/false); } protected _singleModifierDispatch(e: IKeyboardEvent, target: IContextKeyServiceTarget): boolean { const keybinding = this.resolveKeyboardEvent(e); const [singleModifier,] = keybinding.getSingleModifierDispatchParts(); if (singleModifier !== null && this._currentSingleModifier === null) { // we have a valid `singleModifier`, store it for the next keyup, but clear it in 300ms this._log(`+ Storing single modifier for possible chord ${singleModifier}.`); this._currentSingleModifier = singleModifier; this._currentSingleModifierClearTimeout.cancelAndSet(() => { this._log(`+ Clearing single modifier due to 300ms elapsed.`); this._currentSingleModifier = null; }, 300); return false; } if (singleModifier !== null && singleModifier === this._currentSingleModifier) { // bingo! this._log(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`); this._currentSingleModifierClearTimeout.cancel(); this._currentSingleModifier = null; return this._doDispatch(keybinding, target, /*isSingleModiferChord*/true); } this._currentSingleModifierClearTimeout.cancel(); this._currentSingleModifier = null; return false; } private _doDispatch(keybinding: ResolvedKeybinding, target: IContextKeyServiceTarget, isSingleModiferChord = false): boolean { let shouldPreventDefault = false; if (keybinding.isChord()) { console.warn('Unexpected keyboard event mapped to a chord'); return false; } let firstPart: string | null = null; // the first keybinding i.e. Ctrl+K let currentChord: string | null = null;// the "second" keybinding i.e. Ctrl+K "Ctrl+D" if (isSingleModiferChord) { const [dispatchKeyname,] = keybinding.getSingleModifierDispatchParts(); firstPart = dispatchKeyname; currentChord = dispatchKeyname; } else { [firstPart,] = keybinding.getDispatchParts(); currentChord = this._currentChord ? this._currentChord.keypress : null; } if (firstPart === null) { this._log(`\\ Keyboard event cannot be dispatched in keydown phase.`); // cannot be dispatched, probably only modifier keys return shouldPreventDefault; } const contextValue = this._contextKeyService.getContext(target); const keypressLabel = keybinding.getLabel(); const resolveResult = this._getResolver().resolve(contextValue, currentChord, firstPart); this._logService.trace('KeybindingService#dispatch', keypressLabel, resolveResult?.commandId); if (resolveResult && resolveResult.enterChord) { shouldPreventDefault = true; this._enterChordMode(firstPart, keypressLabel); return shouldPreventDefault; } if (this._currentChord) { if (!resolveResult || !resolveResult.commandId) { this._notificationService.status(nls.localize('missing.chord', "The key combination ({0}, {1}) is not a command.", this._currentChord.label, keypressLabel), { hideAfter: 10 * 1000 /* 10s */ }); shouldPreventDefault = true; } } this._leaveChordMode(); if (resolveResult && resolveResult.commandId) { if (!resolveResult.bubble) { shouldPreventDefault = true; } if (typeof resolveResult.commandArgs === 'undefined') { this._commandService.executeCommand(resolveResult.commandId).then(undefined, err => this._notificationService.warn(err)); } else { this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(undefined, err => this._notificationService.warn(err)); } this._telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: resolveResult.commandId, from: 'keybinding' }); } return shouldPreventDefault; } mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey) { // ignore ctrl/cmd-combination but not shift/alt-combinatios return false; } // weak check for certain ranges. this is properly implemented in a subclass // with access to the KeyboardMapperFactory. if ((event.keyCode >= KeyCode.KEY_A && event.keyCode <= KeyCode.KEY_Z) || (event.keyCode >= KeyCode.KEY_0 && event.keyCode <= KeyCode.KEY_9)) { return true; } return false; } }
src/vs/platform/keybinding/common/abstractKeybindingService.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00018034171080216765, 0.00017076129734050483, 0.00016431763651780784, 0.000170290149981156, 0.000003066229282921995 ]
{ "id": 3, "code_window": [ "\t\t\treturn callback(false);\n", "\t\t});\n", "\n", "\t\tsess.setPermissionCheckHandler((webContents, permission /* 'media' */) => {\n", "\t\t\treturn false;\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsess.setPermissionCheckHandler((_webContents, permission /* 'media' */) => {\n", "\t\t\treturn permission === 'clipboard-read';\n" ], "file_path": "src/vs/platform/webview/electron-main/webviewMainService.ts", "type": "replace", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { UserDataAutoSyncEnablementService } from 'vs/platform/userDataSync/common/userDataAutoSyncService'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; export class WebUserDataAutoSyncEnablementService extends UserDataAutoSyncEnablementService { private get workbenchEnvironmentService(): IWorkbenchEnvironmentService { return <IWorkbenchEnvironmentService>this.environmentService; } private enabled: boolean | undefined = undefined; canToggleEnablement(): boolean { return this.isTrusted() && super.canToggleEnablement(); } isEnabled(): boolean { if (!this.isTrusted()) { return false; } if (this.enabled === undefined) { this.enabled = this.workbenchEnvironmentService.options?.settingsSyncOptions?.enabled; } if (this.enabled === undefined) { this.enabled = super.isEnabled(this.workbenchEnvironmentService.options?.enableSyncByDefault); } return this.enabled; } setEnablement(enabled: boolean) { if (this.canToggleEnablement()) { if (this.enabled !== enabled) { this.enabled = enabled; super.setEnablement(enabled); if (this.workbenchEnvironmentService.options?.settingsSyncOptions?.enablementHandler) { this.workbenchEnvironmentService.options.settingsSyncOptions.enablementHandler(this.enabled); } } } } private isTrusted(): boolean { return !!this.workbenchEnvironmentService.options?.workspaceProvider?.trusted; } }
src/vs/workbench/services/userDataSync/browser/userDataAutoSyncEnablementService.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017104687867686152, 0.00016832805704325438, 0.00016579371003899723, 0.00016739906277507544, 0.0000021834723611391382 ]
{ "id": 4, "code_window": [ "\n", "\t\t\t\tconst newFrame = document.createElement('iframe');\n", "\t\t\t\tnewFrame.setAttribute('id', 'pending-frame');\n", "\t\t\t\tnewFrame.setAttribute('frameborder', '0');\n", "\t\t\t\tnewFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads' : 'allow-same-origin allow-pointer-lock');\n", "\t\t\t\tif (host.fakeLoad) {\n", "\t\t\t\t\t// We should just be able to use srcdoc, but I wasn't\n", "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tnewFrame.setAttribute('allow', options.allowScripts ? 'clipboard-read; clipboard-write;' : '');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 510 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { release } from 'os'; import { statSync } from 'fs'; import { app, ipcMain, systemPreferences, contentTracing, protocol, BrowserWindow, dialog, session } from 'electron'; import { IProcessEnvironment, isWindows, isMacintosh, isLinux, isLinuxSnap } from 'vs/base/common/platform'; import { WindowsMainService } from 'vs/platform/windows/electron-main/windowsMainService'; import { IWindowOpenable } from 'vs/platform/windows/common/windows'; import { ILifecycleMainService, LifecycleMainPhase } from 'vs/platform/lifecycle/electron-main/lifecycleMainService'; import { resolveShellEnv } from 'vs/platform/environment/node/shellEnv'; import { IUpdateService } from 'vs/platform/update/common/update'; import { UpdateChannel } from 'vs/platform/update/common/updateIpc'; import { getDelayedChannel, StaticRouter, ProxyChannel } from 'vs/base/parts/ipc/common/ipc'; import { Server as ElectronIPCServer } from 'vs/base/parts/ipc/electron-main/ipc.electron'; import { Server as NodeIPCServer } from 'vs/base/parts/ipc/node/ipc.net'; import { Client as MessagePortClient } from 'vs/base/parts/ipc/electron-main/ipc.mp'; import { SharedProcess } from 'vs/platform/sharedProcess/electron-main/sharedProcess'; import { LaunchMainService, ILaunchMainService } from 'vs/platform/launch/electron-main/launchMainService'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { ILoggerService, ILogService } from 'vs/platform/log/common/log'; import { IStateService } from 'vs/platform/state/node/state'; import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IOpenURLOptions, IURLService } from 'vs/platform/url/common/url'; import { URLHandlerChannelClient, URLHandlerRouter } from 'vs/platform/url/common/urlIpc'; import { ITelemetryService, machineIdKey } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc'; import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService'; import { resolveCommonProperties } from 'vs/platform/telemetry/common/commonProperties'; import product from 'vs/platform/product/common/product'; import { ProxyAuthHandler } from 'vs/code/electron-main/auth'; import { FileProtocolHandler } from 'vs/code/electron-main/protocol'; import { Disposable } from 'vs/base/common/lifecycle'; import { IWindowsMainService, ICodeWindow, OpenContext, WindowError } from 'vs/platform/windows/electron-main/windows'; import { URI } from 'vs/base/common/uri'; import { hasWorkspaceFileExtension, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces'; import { WorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService'; import { getMachineId } from 'vs/base/node/id'; import { Win32UpdateService } from 'vs/platform/update/electron-main/updateService.win32'; import { LinuxUpdateService } from 'vs/platform/update/electron-main/updateService.linux'; import { DarwinUpdateService } from 'vs/platform/update/electron-main/updateService.darwin'; import { IssueMainService, IIssueMainService } from 'vs/platform/issue/electron-main/issueMainService'; import { LoggerChannel, LogLevelChannel } from 'vs/platform/log/common/logIpc'; import { setUnexpectedErrorHandler, onUnexpectedError } from 'vs/base/common/errors'; import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener'; import { serve as serveDriver } from 'vs/platform/driver/electron-main/driver'; import { IMenubarMainService, MenubarMainService } from 'vs/platform/menubar/electron-main/menubarMainService'; import { RunOnceScheduler } from 'vs/base/common/async'; import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu'; import { sep, posix, join, isAbsolute } from 'vs/base/common/path'; import { joinPath } from 'vs/base/common/resources'; import { localize } from 'vs/nls'; import { Schemas } from 'vs/base/common/network'; import { SnapUpdateService } from 'vs/platform/update/electron-main/updateService.snap'; import { IStorageMainService, StorageMainService } from 'vs/platform/storage/electron-main/storageMainService'; import { StorageDatabaseChannel } from 'vs/platform/storage/electron-main/storageIpc'; import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService'; import { IBackupMainService } from 'vs/platform/backup/electron-main/backup'; import { WorkspacesHistoryMainService, IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService'; import { NativeURLService } from 'vs/platform/url/common/urlService'; import { WorkspacesManagementMainService, IWorkspacesManagementMainService } from 'vs/platform/workspaces/electron-main/workspacesManagementMainService'; import { IDiagnosticsService } from 'vs/platform/diagnostics/common/diagnostics'; import { ElectronExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/electron-main/extensionHostDebugIpc'; import { INativeHostMainService, NativeHostMainService } from 'vs/platform/native/electron-main/nativeHostMainService'; import { IDialogMainService, DialogMainService } from 'vs/platform/dialogs/electron-main/dialogMainService'; import { withNullAsUndefined } from 'vs/base/common/types'; import { mnemonicButtonLabel, getPathLabel } from 'vs/base/common/labels'; import { WebviewMainService } from 'vs/platform/webview/electron-main/webviewMainService'; import { IWebviewManagerService } from 'vs/platform/webview/common/webviewManagerService'; import { IFileService } from 'vs/platform/files/common/files'; import { stripComments } from 'vs/base/common/json'; import { generateUuid } from 'vs/base/common/uuid'; import { VSBuffer } from 'vs/base/common/buffer'; import { EncryptionMainService, IEncryptionMainService } from 'vs/platform/encryption/electron-main/encryptionMainService'; import { ActiveWindowManager } from 'vs/platform/windows/node/windowTracker'; import { IKeyboardLayoutMainService, KeyboardLayoutMainService } from 'vs/platform/keyboardLayout/electron-main/keyboardLayoutMainService'; import { NativeParsedArgs } from 'vs/platform/environment/common/argv'; import { DisplayMainService, IDisplayMainService } from 'vs/platform/display/electron-main/displayMainService'; import { isLaunchedFromCli } from 'vs/platform/environment/node/argvHelper'; import { isEqualOrParent } from 'vs/base/common/extpath'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; import { IExtensionUrlTrustService } from 'vs/platform/extensionManagement/common/extensionUrlTrust'; import { ExtensionUrlTrustService } from 'vs/platform/extensionManagement/node/extensionUrlTrustService'; import { once } from 'vs/base/common/functional'; /** * The main VS Code application. There will only ever be one instance, * even if the user starts many instances (e.g. from the command line). */ export class CodeApplication extends Disposable { private windowsMainService: IWindowsMainService | undefined; private nativeHostMainService: INativeHostMainService | undefined; constructor( private readonly mainProcessNodeIpcServer: NodeIPCServer, private readonly userEnv: IProcessEnvironment, @IInstantiationService private readonly mainInstantiationService: IInstantiationService, @ILogService private readonly logService: ILogService, @IEnvironmentMainService private readonly environmentMainService: IEnvironmentMainService, @ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService, @IConfigurationService private readonly configurationService: IConfigurationService, @IStateService private readonly stateService: IStateService, @IFileService private readonly fileService: IFileService ) { super(); this.registerListeners(); } private registerListeners(): void { // We handle uncaught exceptions here to prevent electron from opening a dialog to the user setUnexpectedErrorHandler(err => this.onUnexpectedError(err)); process.on('uncaughtException', err => this.onUnexpectedError(err)); process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason)); // Dispose on shutdown this.lifecycleMainService.onWillShutdown(() => this.dispose()); // Contextmenu via IPC support registerContextMenuListener(); // Accessibility change event app.on('accessibility-support-changed', (event, accessibilitySupportEnabled) => { this.windowsMainService?.sendToAll('vscode:accessibilitySupportChanged', accessibilitySupportEnabled); }); // macOS dock activate app.on('activate', (event, hasVisibleWindows) => { this.logService.trace('app#activate'); // Mac only event: open new window when we get activated if (!hasVisibleWindows) { this.windowsMainService?.openEmptyWindow({ context: OpenContext.DOCK }); } }); //#region Security related measures (https://electronjs.org/docs/tutorial/security) // // !!! DO NOT CHANGE without consulting the documentation !!! // app.on('remote-require', (event, sender, module) => { this.logService.trace('app#on(remote-require): prevented'); event.preventDefault(); }); app.on('remote-get-global', (event, sender, module) => { this.logService.trace(`app#on(remote-get-global): prevented on ${module}`); event.preventDefault(); }); app.on('remote-get-builtin', (event, sender, module) => { this.logService.trace(`app#on(remote-get-builtin): prevented on ${module}`); if (module !== 'clipboard') { event.preventDefault(); } }); app.on('remote-get-current-window', event => { this.logService.trace(`app#on(remote-get-current-window): prevented`); event.preventDefault(); }); app.on('remote-get-current-web-contents', event => { if (this.environmentMainService.args.driver) { return; // the driver needs access to web contents } this.logService.trace(`app#on(remote-get-current-web-contents): prevented`); event.preventDefault(); }); app.on('web-contents-created', (event, contents) => { contents.on('will-attach-webview', (event, webPreferences, params) => { const isValidWebviewSource = (source: string | undefined): boolean => { if (!source) { return false; } const uri = URI.parse(source); if (uri.scheme === Schemas.vscodeWebview) { return uri.path === '/index.html' || uri.path === '/electron-browser/index.html'; } const srcUri = uri.fsPath.toLowerCase(); const rootUri = URI.file(this.environmentMainService.appRoot).fsPath.toLowerCase(); return srcUri.startsWith(rootUri + sep); }; // Ensure defaults delete webPreferences.preload; webPreferences.nodeIntegration = false; // Verify URLs being loaded // https://github.com/electron/electron/issues/21553 if (isValidWebviewSource(params.src) && isValidWebviewSource((webPreferences as { preloadURL: string }).preloadURL)) { return; } delete (webPreferences as { preloadURL: string | undefined }).preloadURL; // https://github.com/electron/electron/issues/21553 // Otherwise prevent loading this.logService.error('webContents#web-contents-created: Prevented webview attach'); event.preventDefault(); }); contents.on('will-navigate', event => { this.logService.error('webContents#will-navigate: Prevented webcontent navigation'); event.preventDefault(); }); contents.on('new-window', (event, url) => { event.preventDefault(); // prevent code that wants to open links this.nativeHostMainService?.openExternal(undefined, url); }); session.defaultSession.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => { return callback(false); }); session.defaultSession.setPermissionCheckHandler((webContents, permission /* 'media' */) => { return false; }); }); //#endregion let macOpenFileURIs: IWindowOpenable[] = []; let runningTimeout: NodeJS.Timeout | null = null; app.on('open-file', (event, path) => { this.logService.trace('app#open-file: ', path); event.preventDefault(); // Keep in array because more might come! macOpenFileURIs.push(this.getWindowOpenableFromPathSync(path)); // Clear previous handler if any if (runningTimeout !== null) { clearTimeout(runningTimeout); runningTimeout = null; } // Handle paths delayed in case more are coming! runningTimeout = setTimeout(() => { this.windowsMainService?.open({ context: OpenContext.DOCK /* can also be opening from finder while app is running */, cli: this.environmentMainService.args, urisToOpen: macOpenFileURIs, gotoLineMode: false, preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */ }); macOpenFileURIs = []; runningTimeout = null; }, 100); }); app.on('new-window-for-tab', () => { this.windowsMainService?.openEmptyWindow({ context: OpenContext.DESKTOP }); //macOS native tab "+" button }); //#region Bootstrap IPC Handlers let slowShellResolveWarningShown = false; ipcMain.on('vscode:fetchShellEnv', async event => { // DO NOT remove: not only usual windows are fetching the // shell environment but also shared process, issue reporter // etc, so we need to reply via `webContents` always const webContents = event.sender; let replied = false; function acceptShellEnv(env: NodeJS.ProcessEnv): void { clearTimeout(shellEnvSlowWarningHandle); clearTimeout(shellEnvTimeoutErrorHandle); if (!replied) { replied = true; if (!webContents.isDestroyed()) { webContents.send('vscode:acceptShellEnv', env); } } } // Handle slow shell environment resolve calls: // - a warning after 3s but continue to resolve (only once in active window) // - an error after 10s and stop trying to resolve (in every window where this happens) const cts = new CancellationTokenSource(); const shellEnvSlowWarningHandle = setTimeout(() => { if (!slowShellResolveWarningShown) { this.windowsMainService?.sendToFocused('vscode:showShellEnvSlowWarning', cts.token); slowShellResolveWarningShown = true; } }, 3000); const window = this.windowsMainService?.getWindowByWebContents(event.sender); // Note: this can be `undefined` for the shared process!! const shellEnvTimeoutErrorHandle = setTimeout(() => { cts.dispose(true); window?.sendWhenReady('vscode:showShellEnvTimeoutError', CancellationToken.None); acceptShellEnv({}); }, 10000); // Prefer to use the args and env from the target window // when resolving the shell env. It is possible that // a first window was opened from the UI but a second // from the CLI and that has implications for whether to // resolve the shell environment or not. // // Window can be undefined for e.g. the shared process // that is not part of our windows registry! let args: NativeParsedArgs; let env: NodeJS.ProcessEnv; if (window?.config) { args = window.config; env = { ...process.env, ...window.config.userEnv }; } else { args = this.environmentMainService.args; env = process.env; } // Resolve shell env const shellEnv = await resolveShellEnv(this.logService, args, env); acceptShellEnv(shellEnv); }); ipcMain.handle('vscode:writeNlsFile', async (event, path: unknown, data: unknown) => { const uri = this.validateNlsPath([path]); if (!uri || typeof data !== 'string') { throw new Error('Invalid operation (vscode:writeNlsFile)'); } return this.fileService.writeFile(uri, VSBuffer.fromString(data)); }); ipcMain.handle('vscode:readNlsFile', async (event, ...paths: unknown[]) => { const uri = this.validateNlsPath(paths); if (!uri) { throw new Error('Invalid operation (vscode:readNlsFile)'); } return (await this.fileService.readFile(uri)).value.toString(); }); ipcMain.on('vscode:toggleDevTools', event => event.sender.toggleDevTools()); ipcMain.on('vscode:openDevTools', event => event.sender.openDevTools()); ipcMain.on('vscode:reloadWindow', event => event.sender.reload()); //#endregion } private validateNlsPath(pathSegments: unknown[]): URI | undefined { let path: string | undefined = undefined; for (const pathSegment of pathSegments) { if (typeof pathSegment === 'string') { if (typeof path !== 'string') { path = pathSegment; } else { path = join(path, pathSegment); } } } if (typeof path !== 'string' || !isAbsolute(path) || !isEqualOrParent(path, this.environmentMainService.cachedLanguagesPath, !isLinux)) { return undefined; } return URI.file(path); } private onUnexpectedError(err: Error): void { if (err) { // take only the message and stack property const friendlyError = { message: `[uncaught exception in main]: ${err.message}`, stack: err.stack }; // handle on client side this.windowsMainService?.sendToFocused('vscode:reportError', JSON.stringify(friendlyError)); } this.logService.error(`[uncaught exception in main]: ${err}`); if (err.stack) { this.logService.error(err.stack); } } async startup(): Promise<void> { this.logService.debug('Starting VS Code'); this.logService.debug(`from: ${this.environmentMainService.appRoot}`); this.logService.debug('args:', this.environmentMainService.args); // Make sure we associate the program with the app user model id // This will help Windows to associate the running program with // any shortcut that is pinned to the taskbar and prevent showing // two icons in the taskbar for the same app. const win32AppUserModelId = product.win32AppUserModelId; if (isWindows && win32AppUserModelId) { app.setAppUserModelId(win32AppUserModelId); } // Fix native tabs on macOS 10.13 // macOS enables a compatibility patch for any bundle ID beginning with // "com.microsoft.", which breaks native tabs for VS Code when using this // identifier (from the official build). // Explicitly opt out of the patch here before creating any windows. // See: https://github.com/microsoft/vscode/issues/35361#issuecomment-399794085 try { if (isMacintosh && this.configurationService.getValue<boolean>('window.nativeTabs') === true && !systemPreferences.getUserDefault('NSUseImprovedLayoutPass', 'boolean')) { systemPreferences.setUserDefault('NSUseImprovedLayoutPass', 'boolean', true as any); } } catch (error) { this.logService.error(error); } // Setup Protocol Handler const fileProtocolHandler = this._register(this.mainInstantiationService.createInstance(FileProtocolHandler)); // Main process server (electron IPC based) const mainProcessElectronServer = new ElectronIPCServer(); // Resolve unique machine ID this.logService.trace('Resolving machine identifier...'); const machineId = await this.resolveMachineId(); this.logService.trace(`Resolved machine identifier: ${machineId}`); // Shared process const { sharedProcess, sharedProcessReady, sharedProcessClient } = this.setupSharedProcess(machineId); // Services const appInstantiationService = await this.initServices(machineId, sharedProcess, sharedProcessReady); // Create driver if (this.environmentMainService.driverHandle) { const server = await serveDriver(mainProcessElectronServer, this.environmentMainService.driverHandle, this.environmentMainService, appInstantiationService); this.logService.info('Driver started at:', this.environmentMainService.driverHandle); this._register(server); } // Setup Auth Handler this._register(appInstantiationService.createInstance(ProxyAuthHandler)); // Init Channels appInstantiationService.invokeFunction(accessor => this.initChannels(accessor, mainProcessElectronServer, sharedProcessClient)); // Open Windows const windows = appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor, mainProcessElectronServer, fileProtocolHandler)); // Post Open Windows Tasks appInstantiationService.invokeFunction(accessor => this.afterWindowOpen(accessor, sharedProcess)); // Tracing: Stop tracing after windows are ready if enabled if (this.environmentMainService.args.trace) { appInstantiationService.invokeFunction(accessor => this.stopTracingEventually(accessor, windows)); } } private async resolveMachineId(): Promise<string> { // We cache the machineId for faster lookups on startup // and resolve it only once initially if not cached or we need to replace the macOS iBridge device let machineId = this.stateService.getItem<string>(machineIdKey); if (!machineId || (isMacintosh && machineId === '6c9d2bc8f91b89624add29c0abeae7fb42bf539fa1cdb2e3e57cd668fa9bcead')) { machineId = await getMachineId(); this.stateService.setItem(machineIdKey, machineId); } return machineId; } private setupSharedProcess(machineId: string): { sharedProcess: SharedProcess, sharedProcessReady: Promise<MessagePortClient>, sharedProcessClient: Promise<MessagePortClient> } { const sharedProcess = this.mainInstantiationService.createInstance(SharedProcess, machineId, this.userEnv); const sharedProcessClient = (async () => { this.logService.trace('Main->SharedProcess#connect'); const port = await sharedProcess.connect(); this.logService.trace('Main->SharedProcess#connect: connection established'); return new MessagePortClient(port, 'main'); })(); const sharedProcessReady = (async () => { await sharedProcess.whenReady(); return sharedProcessClient; })(); // Spawn shared process after the first window has opened and 3s have passed this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen).then(() => { this._register(new RunOnceScheduler(async () => { sharedProcess.spawn(await resolveShellEnv(this.logService, this.environmentMainService.args, process.env)); }, 3000)).schedule(); }); return { sharedProcess, sharedProcessReady, sharedProcessClient }; } private async initServices(machineId: string, sharedProcess: SharedProcess, sharedProcessReady: Promise<MessagePortClient>): Promise<IInstantiationService> { const services = new ServiceCollection(); // Update switch (process.platform) { case 'win32': services.set(IUpdateService, new SyncDescriptor(Win32UpdateService)); break; case 'linux': if (isLinuxSnap) { services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env['SNAP'], process.env['SNAP_REVISION']])); } else { services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService)); } break; case 'darwin': services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService)); break; } // Windows services.set(IWindowsMainService, new SyncDescriptor(WindowsMainService, [machineId, this.userEnv])); // Dialogs services.set(IDialogMainService, new SyncDescriptor(DialogMainService)); // Launch services.set(ILaunchMainService, new SyncDescriptor(LaunchMainService)); // Diagnostics services.set(IDiagnosticsService, ProxyChannel.toService(getDelayedChannel(sharedProcessReady.then(client => client.getChannel('diagnostics'))))); // Issues services.set(IIssueMainService, new SyncDescriptor(IssueMainService, [machineId, this.userEnv])); // Encryption services.set(IEncryptionMainService, new SyncDescriptor(EncryptionMainService, [machineId])); // Keyboard Layout services.set(IKeyboardLayoutMainService, new SyncDescriptor(KeyboardLayoutMainService)); // Display services.set(IDisplayMainService, new SyncDescriptor(DisplayMainService)); // Native Host services.set(INativeHostMainService, new SyncDescriptor(NativeHostMainService, [sharedProcess])); // Webview Manager services.set(IWebviewManagerService, new SyncDescriptor(WebviewMainService)); // Workspaces services.set(IWorkspacesService, new SyncDescriptor(WorkspacesMainService)); services.set(IWorkspacesManagementMainService, new SyncDescriptor(WorkspacesManagementMainService)); services.set(IWorkspacesHistoryMainService, new SyncDescriptor(WorkspacesHistoryMainService)); // Menubar services.set(IMenubarMainService, new SyncDescriptor(MenubarMainService)); // Extension URL Trust services.set(IExtensionUrlTrustService, new SyncDescriptor(ExtensionUrlTrustService)); // Storage services.set(IStorageMainService, new SyncDescriptor(StorageMainService)); // Backups const backupMainService = new BackupMainService(this.environmentMainService, this.configurationService, this.logService); services.set(IBackupMainService, backupMainService); // URL handling services.set(IURLService, new SyncDescriptor(NativeURLService)); // Telemetry if (!this.environmentMainService.isExtensionDevelopment && !this.environmentMainService.args['disable-telemetry'] && !!product.enableTelemetry) { const channel = getDelayedChannel(sharedProcessReady.then(client => client.getChannel('telemetryAppender'))); const appender = new TelemetryAppenderClient(channel); const commonProperties = resolveCommonProperties(this.fileService, release(), process.arch, product.commit, product.version, machineId, product.msftInternalDomains, this.environmentMainService.installSourcePath); const piiPaths = [this.environmentMainService.appRoot, this.environmentMainService.extensionsPath]; const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths, sendErrorTelemetry: true }; services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config])); } else { services.set(ITelemetryService, NullTelemetryService); } // Init services that require it await backupMainService.initialize(); return this.mainInstantiationService.createChild(services); } private initChannels(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer, sharedProcessClient: Promise<MessagePortClient>): void { // Launch: this one is explicitly registered to the node.js // server because when a second instance starts up, that is // the only possible connection between the first and the // second instance. Electron IPC does not work across apps. const launchChannel = ProxyChannel.fromService(accessor.get(ILaunchMainService), { disableMarshalling: true }); this.mainProcessNodeIpcServer.registerChannel('launch', launchChannel); // Update const updateChannel = new UpdateChannel(accessor.get(IUpdateService)); mainProcessElectronServer.registerChannel('update', updateChannel); // Issues const issueChannel = ProxyChannel.fromService(accessor.get(IIssueMainService)); mainProcessElectronServer.registerChannel('issue', issueChannel); // Encryption const encryptionChannel = ProxyChannel.fromService(accessor.get(IEncryptionMainService)); mainProcessElectronServer.registerChannel('encryption', encryptionChannel); // Keyboard Layout const keyboardLayoutChannel = ProxyChannel.fromService(accessor.get(IKeyboardLayoutMainService)); mainProcessElectronServer.registerChannel('keyboardLayout', keyboardLayoutChannel); // Display const displayChannel = ProxyChannel.fromService(accessor.get(IDisplayMainService)); mainProcessElectronServer.registerChannel('display', displayChannel); // Native host (main & shared process) this.nativeHostMainService = accessor.get(INativeHostMainService); const nativeHostChannel = ProxyChannel.fromService(this.nativeHostMainService); mainProcessElectronServer.registerChannel('nativeHost', nativeHostChannel); sharedProcessClient.then(client => client.registerChannel('nativeHost', nativeHostChannel)); // Workspaces const workspacesChannel = ProxyChannel.fromService(accessor.get(IWorkspacesService)); mainProcessElectronServer.registerChannel('workspaces', workspacesChannel); // Menubar const menubarChannel = ProxyChannel.fromService(accessor.get(IMenubarMainService)); mainProcessElectronServer.registerChannel('menubar', menubarChannel); // URL handling const urlChannel = ProxyChannel.fromService(accessor.get(IURLService)); mainProcessElectronServer.registerChannel('url', urlChannel); // Extension URL Trust const extensionUrlTrustChannel = ProxyChannel.fromService(accessor.get(IExtensionUrlTrustService)); mainProcessElectronServer.registerChannel('extensionUrlTrust', extensionUrlTrustChannel); // Webview Manager const webviewChannel = ProxyChannel.fromService(accessor.get(IWebviewManagerService)); mainProcessElectronServer.registerChannel('webview', webviewChannel); // Storage (main & shared process) const storageChannel = this._register(new StorageDatabaseChannel(this.logService, accessor.get(IStorageMainService))); mainProcessElectronServer.registerChannel('storage', storageChannel); sharedProcessClient.then(client => client.registerChannel('storage', storageChannel)); // Log Level (main & shared process) const logLevelChannel = new LogLevelChannel(accessor.get(ILogService)); mainProcessElectronServer.registerChannel('logLevel', logLevelChannel); sharedProcessClient.then(client => client.registerChannel('logLevel', logLevelChannel)); // Logger const loggerChannel = new LoggerChannel(accessor.get(ILoggerService),); mainProcessElectronServer.registerChannel('logger', loggerChannel); // Extension Host Debug Broadcasting const electronExtensionHostDebugBroadcastChannel = new ElectronExtensionHostDebugBroadcastChannel(accessor.get(IWindowsMainService)); mainProcessElectronServer.registerChannel('extensionhostdebugservice', electronExtensionHostDebugBroadcastChannel); } private openFirstWindow(accessor: ServicesAccessor, mainProcessElectronServer: ElectronIPCServer, fileProtocolHandler: FileProtocolHandler): ICodeWindow[] { const windowsMainService = this.windowsMainService = accessor.get(IWindowsMainService); const urlService = accessor.get(IURLService); const nativeHostMainService = accessor.get(INativeHostMainService); // Signal phase: ready (services set) this.lifecycleMainService.phase = LifecycleMainPhase.Ready; // Forward windows main service to protocol handler fileProtocolHandler.injectWindowsMainService(this.windowsMainService); // Check for initial URLs to handle from protocol link invocations const pendingWindowOpenablesFromProtocolLinks: IWindowOpenable[] = []; const pendingProtocolLinksToHandle = [ // Windows/Linux: protocol handler invokes CLI with --open-url ...this.environmentMainService.args['open-url'] ? this.environmentMainService.args._urls || [] : [], // macOS: open-url events ...((<any>global).getOpenUrls() || []) as string[] ].map(url => { try { return { uri: URI.parse(url), url }; } catch { return null; } }).filter((obj): obj is { uri: URI, url: string } => { if (!obj) { return false; } // If URI should be blocked, filter it out if (this.shouldBlockURI(obj.uri)) { return false; } // Filter out any protocol link that wants to open as window so that // we open the right set of windows on startup and not restore the // previous workspace too. const windowOpenable = this.getWindowOpenableFromProtocolLink(obj.uri); if (windowOpenable) { pendingWindowOpenablesFromProtocolLinks.push(windowOpenable); return false; } return true; }); // Create a URL handler to open file URIs in the active window // or open new windows. The URL handler will be invoked from // protocol invocations outside of VSCode. const app = this; const environmentService = this.environmentMainService; urlService.registerHandler({ async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> { // If URI should be blocked, behave as if it's handled if (app.shouldBlockURI(uri)) { return true; } // Check for URIs to open in window const windowOpenableFromProtocolLink = app.getWindowOpenableFromProtocolLink(uri); if (windowOpenableFromProtocolLink) { const [window] = windowsMainService.open({ context: OpenContext.API, cli: { ...environmentService.args }, urisToOpen: [windowOpenableFromProtocolLink], gotoLineMode: true }); window.focus(); // this should help ensuring that the right window gets focus when multiple are opened return true; } // If we have not yet handled the URI and we have no window opened (macOS only) // we first open a window and then try to open that URI within that window if (isMacintosh && windowsMainService.getWindowCount() === 0) { const [window] = windowsMainService.open({ context: OpenContext.API, cli: { ...environmentService.args }, forceEmpty: true, gotoLineMode: true }); await window.ready(); return urlService.open(uri, options); } return false; } }); // Create a URL handler which forwards to the last active window const activeWindowManager = this._register(new ActiveWindowManager({ onDidOpenWindow: nativeHostMainService.onDidOpenWindow, onDidFocusWindow: nativeHostMainService.onDidFocusWindow, getActiveWindowId: () => nativeHostMainService.getActiveWindowId(-1) })); const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id)); const urlHandlerRouter = new URLHandlerRouter(activeWindowRouter); const urlHandlerChannel = mainProcessElectronServer.getChannel('urlHandler', urlHandlerRouter); urlService.registerHandler(new URLHandlerChannelClient(urlHandlerChannel)); // Watch Electron URLs and forward them to the UrlService this._register(new ElectronURLListener(pendingProtocolLinksToHandle, urlService, windowsMainService, this.environmentMainService)); // Open our first window const args = this.environmentMainService.args; const macOpenFiles: string[] = (<any>global).macOpenFiles; const context = isLaunchedFromCli(process.env) ? OpenContext.CLI : OpenContext.DESKTOP; const hasCliArgs = args._.length; const hasFolderURIs = !!args['folder-uri']; const hasFileURIs = !!args['file-uri']; const noRecentEntry = args['skip-add-to-recently-opened'] === true; const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined; // check for a pending window to open from URI // e.g. when running code with --open-uri from // a protocol handler if (pendingWindowOpenablesFromProtocolLinks.length > 0) { return windowsMainService.open({ context, cli: args, urisToOpen: pendingWindowOpenablesFromProtocolLinks, gotoLineMode: true, initialStartup: true }); } // new window if "-n" if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) { return windowsMainService.open({ context, cli: args, forceNewWindow: true, forceEmpty: true, noRecentEntry, waitMarkerFileURI, initialStartup: true }); } // mac: open-file event received on startup if (macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) { return windowsMainService.open({ context: OpenContext.DOCK, cli: args, urisToOpen: macOpenFiles.map(file => this.getWindowOpenableFromPathSync(file)), noRecentEntry, waitMarkerFileURI, initialStartup: true }); } // default: read paths from cli return windowsMainService.open({ context, cli: args, forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']), diffMode: args.diff, noRecentEntry, waitMarkerFileURI, gotoLineMode: args.goto, initialStartup: true }); } private shouldBlockURI(uri: URI): boolean { if (uri.authority === Schemas.file && isWindows) { const res = dialog.showMessageBoxSync({ title: product.nameLong, type: 'question', buttons: [ mnemonicButtonLabel(localize({ key: 'open', comment: ['&& denotes a mnemonic'] }, "&&Yes")), mnemonicButtonLabel(localize({ key: 'cancel', comment: ['&& denotes a mnemonic'] }, "&&No")), ], cancelId: 1, message: localize('confirmOpenMessage', "An external application wants to open '{0}' in {1}. Do you want to open this file or folder?", getPathLabel(uri.fsPath, this.environmentMainService), product.nameShort), detail: localize('confirmOpenDetail', "If you did not initiate this request, it may represent an attempted attack on your system. Unless you took an explicit action to initiate this request, you should press 'No'"), noLink: true }); if (res === 1) { return true; } } return false; } private getWindowOpenableFromProtocolLink(uri: URI): IWindowOpenable | undefined { if (!uri.path) { return undefined; } // File path if (uri.authority === Schemas.file) { // we configure as fileUri, but later validation will // make sure to open as folder or workspace if possible return { fileUri: URI.file(uri.fsPath) }; } // Remote path else if (uri.authority === Schemas.vscodeRemote) { // Example conversion: // From: vscode://vscode-remote/wsl+ubuntu/mnt/c/GitDevelopment/monaco // To: vscode-remote://wsl+ubuntu/mnt/c/GitDevelopment/monaco const secondSlash = uri.path.indexOf(posix.sep, 1 /* skip over the leading slash */); if (secondSlash !== -1) { const authority = uri.path.substring(1, secondSlash); const path = uri.path.substring(secondSlash); const remoteUri = URI.from({ scheme: Schemas.vscodeRemote, authority, path, query: uri.query, fragment: uri.fragment }); if (hasWorkspaceFileExtension(path)) { return { workspaceUri: remoteUri }; } else { return { folderUri: remoteUri }; } } } return undefined; } private getWindowOpenableFromPathSync(path: string): IWindowOpenable { try { const fileStat = statSync(path); if (fileStat.isDirectory()) { return { folderUri: URI.file(path) }; } if (hasWorkspaceFileExtension(path)) { return { workspaceUri: URI.file(path) }; } } catch (error) { // ignore errors } return { fileUri: URI.file(path) }; } private async afterWindowOpen(accessor: ServicesAccessor, sharedProcess: SharedProcess): Promise<void> { // Signal phase: after window open this.lifecycleMainService.phase = LifecycleMainPhase.AfterWindowOpen; // Observe shared process for errors const telemetryService = accessor.get(ITelemetryService); this._register(sharedProcess.onDidError(e => { // Logging onUnexpectedError(new Error(e.message)); // Telemetry type SharedProcessErrorClassification = { type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; }; type SharedProcessErrorEvent = { type: WindowError; }; telemetryService.publicLog2<SharedProcessErrorEvent, SharedProcessErrorClassification>('sharedprocesserror', { type: e.type }); })); // Windows: install mutex const win32MutexName = product.win32MutexName; if (isWindows && win32MutexName) { try { const WindowsMutex = (require.__$__nodeRequire('windows-mutex') as typeof import('windows-mutex')).Mutex; const mutex = new WindowsMutex(win32MutexName); once(this.lifecycleMainService.onWillShutdown)(() => mutex.release()); } catch (error) { this.logService.error(error); } } // Remote Authorities protocol.registerHttpProtocol(Schemas.vscodeRemoteResource, (request, callback) => { callback({ url: request.url.replace(/^vscode-remote-resource:/, 'http:'), method: request.method }); }); // Initialize update service const updateService = accessor.get(IUpdateService); if (updateService instanceof Win32UpdateService || updateService instanceof LinuxUpdateService || updateService instanceof DarwinUpdateService) { updateService.initialize(); } // Start to fetch shell environment (if needed) after window has opened resolveShellEnv(this.logService, this.environmentMainService.args, process.env); // If enable-crash-reporter argv is undefined then this is a fresh start, // based on telemetry.enableCrashreporter settings, generate a UUID which // will be used as crash reporter id and also update the json file. try { const argvContent = await this.fileService.readFile(this.environmentMainService.argvResource); const argvString = argvContent.value.toString(); const argvJSON = JSON.parse(stripComments(argvString)); if (argvJSON['enable-crash-reporter'] === undefined) { const enableCrashReporter = this.configurationService.getValue<boolean>('telemetry.enableCrashReporter') ?? true; const additionalArgvContent = [ '', ' // Allows to disable crash reporting.', ' // Should restart the app if the value is changed.', ` "enable-crash-reporter": ${enableCrashReporter},`, '', ' // Unique id used for correlating crash reports sent from this instance.', ' // Do not edit this value.', ` "crash-reporter-id": "${generateUuid()}"`, '}' ]; const newArgvString = argvString.substring(0, argvString.length - 2).concat(',\n', additionalArgvContent.join('\n')); await this.fileService.writeFile(this.environmentMainService.argvResource, VSBuffer.fromString(newArgvString)); } } catch (error) { this.logService.error(error); } } private stopTracingEventually(accessor: ServicesAccessor, windows: ICodeWindow[]): void { this.logService.info(`Tracing: waiting for windows to get ready...`); const dialogMainService = accessor.get(IDialogMainService); let recordingStopped = false; const stopRecording = async (timeout: boolean) => { if (recordingStopped) { return; } recordingStopped = true; // only once const path = await contentTracing.stopRecording(joinPath(this.environmentMainService.userHome, `${product.applicationName}-${Math.random().toString(16).slice(-4)}.trace.txt`).fsPath); if (!timeout) { dialogMainService.showMessageBox({ type: 'info', message: localize('trace.message', "Successfully created trace."), detail: localize('trace.detail', "Please create an issue and manually attach the following file:\n{0}", path), buttons: [localize('trace.ok', "OK")] }, withNullAsUndefined(BrowserWindow.getFocusedWindow())); } else { this.logService.info(`Tracing: data recorded (after 30s timeout) to ${path}`); } }; // Wait up to 30s before creating the trace anyways const timeoutHandle = setTimeout(() => stopRecording(true), 30000); // Wait for all windows to get ready and stop tracing then Promise.all(windows.map(window => window.ready())).then(() => { clearTimeout(timeoutHandle); stopRecording(false); }); } }
src/vs/code/electron-main/app.ts
1
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017579652194399387, 0.00017087755259126425, 0.00016360597510356456, 0.0001714454556349665, 0.0000031750967082189163 ]
{ "id": 4, "code_window": [ "\n", "\t\t\t\tconst newFrame = document.createElement('iframe');\n", "\t\t\t\tnewFrame.setAttribute('id', 'pending-frame');\n", "\t\t\t\tnewFrame.setAttribute('frameborder', '0');\n", "\t\t\t\tnewFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads' : 'allow-same-origin allow-pointer-lock');\n", "\t\t\t\tif (host.fakeLoad) {\n", "\t\t\t\t\t// We should just be able to use srcdoc, but I wasn't\n", "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tnewFrame.setAttribute('allow', options.allowScripts ? 'clipboard-read; clipboard-write;' : '');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 510 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { IItemAccessor, FuzzyScore, FuzzyScore2, IItemScore, prepareQuery, scoreFuzzy, scoreFuzzy2, scoreItemFuzzy, compareItemsByFuzzyScore, pieceToQuery } from 'vs/base/common/fuzzyScorer'; import { URI } from 'vs/base/common/uri'; import { basename, dirname, sep, posix, win32 } from 'vs/base/common/path'; import { isWindows } from 'vs/base/common/platform'; import { Schemas } from 'vs/base/common/network'; class ResourceAccessorClass implements IItemAccessor<URI> { getItemLabel(resource: URI): string { return basename(resource.fsPath); } getItemDescription(resource: URI): string { return dirname(resource.fsPath); } getItemPath(resource: URI): string { return resource.fsPath; } } const ResourceAccessor = new ResourceAccessorClass(); class ResourceWithSlashAccessorClass implements IItemAccessor<URI> { getItemLabel(resource: URI): string { return basename(resource.fsPath); } getItemDescription(resource: URI): string { return posix.normalize(dirname(resource.path)); } getItemPath(resource: URI): string { return posix.normalize(resource.path); } } const ResourceWithSlashAccessor = new ResourceWithSlashAccessorClass(); class ResourceWithBackslashAccessorClass implements IItemAccessor<URI> { getItemLabel(resource: URI): string { return basename(resource.fsPath); } getItemDescription(resource: URI): string { return win32.normalize(dirname(resource.path)); } getItemPath(resource: URI): string { return win32.normalize(resource.path); } } const ResourceWithBackslashAccessor = new ResourceWithBackslashAccessorClass(); class NullAccessorClass implements IItemAccessor<URI> { getItemLabel(resource: URI): string { return undefined!; } getItemDescription(resource: URI): string { return undefined!; } getItemPath(resource: URI): string { return undefined!; } } function _doScore(target: string, query: string, fuzzy: boolean): FuzzyScore { const preparedQuery = prepareQuery(query); return scoreFuzzy(target, preparedQuery.normalized, preparedQuery.normalizedLowercase, fuzzy); } function _doScore2(target: string, query: string, matchOffset: number = 0): FuzzyScore2 { const preparedQuery = prepareQuery(query); return scoreFuzzy2(target, preparedQuery, 0, matchOffset); } function scoreItem<T>(item: T, query: string, fuzzy: boolean, accessor: IItemAccessor<T>): IItemScore { return scoreItemFuzzy(item, prepareQuery(query), fuzzy, accessor, Object.create(null)); } function compareItemsByScore<T>(itemA: T, itemB: T, query: string, fuzzy: boolean, accessor: IItemAccessor<T>): number { return compareItemsByFuzzyScore(itemA, itemB, prepareQuery(query), fuzzy, accessor, Object.create(null)); } const NullAccessor = new NullAccessorClass(); suite('Fuzzy Scorer', () => { test('score (fuzzy)', function () { const target = 'HeLlo-World'; const scores: FuzzyScore[] = []; scores.push(_doScore(target, 'HelLo-World', true)); // direct case match scores.push(_doScore(target, 'hello-world', true)); // direct mix-case match scores.push(_doScore(target, 'HW', true)); // direct case prefix (multiple) scores.push(_doScore(target, 'hw', true)); // direct mix-case prefix (multiple) scores.push(_doScore(target, 'H', true)); // direct case prefix scores.push(_doScore(target, 'h', true)); // direct mix-case prefix scores.push(_doScore(target, 'W', true)); // direct case word prefix scores.push(_doScore(target, 'Ld', true)); // in-string case match (multiple) scores.push(_doScore(target, 'ld', true)); // in-string mix-case match (consecutive, avoids scattered hit) scores.push(_doScore(target, 'w', true)); // direct mix-case word prefix scores.push(_doScore(target, 'L', true)); // in-string case match scores.push(_doScore(target, 'l', true)); // in-string mix-case match scores.push(_doScore(target, '4', true)); // no match // Assert scoring order let sortedScores = scores.concat().sort((a, b) => b[0] - a[0]); assert.deepStrictEqual(scores, sortedScores); // Assert scoring positions // let positions = scores[0][1]; // assert.strictEqual(positions.length, 'HelLo-World'.length); // positions = scores[2][1]; // assert.strictEqual(positions.length, 'HW'.length); // assert.strictEqual(positions[0], 0); // assert.strictEqual(positions[1], 6); }); test('score (non fuzzy)', function () { const target = 'HeLlo-World'; assert.ok(_doScore(target, 'HelLo-World', false)[0] > 0); assert.strictEqual(_doScore(target, 'HelLo-World', false)[1].length, 'HelLo-World'.length); assert.ok(_doScore(target, 'hello-world', false)[0] > 0); assert.strictEqual(_doScore(target, 'HW', false)[0], 0); assert.ok(_doScore(target, 'h', false)[0] > 0); assert.ok(_doScore(target, 'ello', false)[0] > 0); assert.ok(_doScore(target, 'ld', false)[0] > 0); assert.strictEqual(_doScore(target, 'eo', false)[0], 0); }); test('scoreItem - matches are proper', function () { let res = scoreItem(null, 'something', true, ResourceAccessor); assert.ok(!res.score); const resource = URI.file('/xyz/some/path/someFile123.txt'); res = scoreItem(resource, 'something', true, NullAccessor); assert.ok(!res.score); // Path Identity const identityRes = scoreItem(resource, ResourceAccessor.getItemPath(resource), true, ResourceAccessor); assert.ok(identityRes.score); assert.strictEqual(identityRes.descriptionMatch!.length, 1); assert.strictEqual(identityRes.labelMatch!.length, 1); assert.strictEqual(identityRes.descriptionMatch![0].start, 0); assert.strictEqual(identityRes.descriptionMatch![0].end, ResourceAccessor.getItemDescription(resource).length); assert.strictEqual(identityRes.labelMatch![0].start, 0); assert.strictEqual(identityRes.labelMatch![0].end, ResourceAccessor.getItemLabel(resource).length); // Basename Prefix const basenamePrefixRes = scoreItem(resource, 'som', true, ResourceAccessor); assert.ok(basenamePrefixRes.score); assert.ok(!basenamePrefixRes.descriptionMatch); assert.strictEqual(basenamePrefixRes.labelMatch!.length, 1); assert.strictEqual(basenamePrefixRes.labelMatch![0].start, 0); assert.strictEqual(basenamePrefixRes.labelMatch![0].end, 'som'.length); // Basename Camelcase const basenameCamelcaseRes = scoreItem(resource, 'sF', true, ResourceAccessor); assert.ok(basenameCamelcaseRes.score); assert.ok(!basenameCamelcaseRes.descriptionMatch); assert.strictEqual(basenameCamelcaseRes.labelMatch!.length, 2); assert.strictEqual(basenameCamelcaseRes.labelMatch![0].start, 0); assert.strictEqual(basenameCamelcaseRes.labelMatch![0].end, 1); assert.strictEqual(basenameCamelcaseRes.labelMatch![1].start, 4); assert.strictEqual(basenameCamelcaseRes.labelMatch![1].end, 5); // Basename Match const basenameRes = scoreItem(resource, 'of', true, ResourceAccessor); assert.ok(basenameRes.score); assert.ok(!basenameRes.descriptionMatch); assert.strictEqual(basenameRes.labelMatch!.length, 2); assert.strictEqual(basenameRes.labelMatch![0].start, 1); assert.strictEqual(basenameRes.labelMatch![0].end, 2); assert.strictEqual(basenameRes.labelMatch![1].start, 4); assert.strictEqual(basenameRes.labelMatch![1].end, 5); // Path Match const pathRes = scoreItem(resource, 'xyz123', true, ResourceAccessor); assert.ok(pathRes.score); assert.ok(pathRes.descriptionMatch); assert.ok(pathRes.labelMatch); assert.strictEqual(pathRes.labelMatch!.length, 1); assert.strictEqual(pathRes.labelMatch![0].start, 8); assert.strictEqual(pathRes.labelMatch![0].end, 11); assert.strictEqual(pathRes.descriptionMatch!.length, 1); assert.strictEqual(pathRes.descriptionMatch![0].start, 1); assert.strictEqual(pathRes.descriptionMatch![0].end, 4); // No Match const noRes = scoreItem(resource, '987', true, ResourceAccessor); assert.ok(!noRes.score); assert.ok(!noRes.labelMatch); assert.ok(!noRes.descriptionMatch); // Verify Scores assert.ok(identityRes.score > basenamePrefixRes.score); assert.ok(basenamePrefixRes.score > basenameRes.score); assert.ok(basenameRes.score > pathRes.score); assert.ok(pathRes.score > noRes.score); }); test('scoreItem - multiple', function () { const resource = URI.file('/xyz/some/path/someFile123.txt'); let res1 = scoreItem(resource, 'xyz some', true, ResourceAccessor); assert.ok(res1.score); assert.strictEqual(res1.labelMatch?.length, 1); assert.strictEqual(res1.labelMatch![0].start, 0); assert.strictEqual(res1.labelMatch![0].end, 4); assert.strictEqual(res1.descriptionMatch?.length, 1); assert.strictEqual(res1.descriptionMatch![0].start, 1); assert.strictEqual(res1.descriptionMatch![0].end, 4); let res2 = scoreItem(resource, 'some xyz', true, ResourceAccessor); assert.ok(res2.score); assert.strictEqual(res1.score, res2.score); assert.strictEqual(res2.labelMatch?.length, 1); assert.strictEqual(res2.labelMatch![0].start, 0); assert.strictEqual(res2.labelMatch![0].end, 4); assert.strictEqual(res2.descriptionMatch?.length, 1); assert.strictEqual(res2.descriptionMatch![0].start, 1); assert.strictEqual(res2.descriptionMatch![0].end, 4); let res3 = scoreItem(resource, 'some xyz file file123', true, ResourceAccessor); assert.ok(res3.score); assert.ok(res3.score > res2.score); assert.strictEqual(res3.labelMatch?.length, 1); assert.strictEqual(res3.labelMatch![0].start, 0); assert.strictEqual(res3.labelMatch![0].end, 11); assert.strictEqual(res3.descriptionMatch?.length, 1); assert.strictEqual(res3.descriptionMatch![0].start, 1); assert.strictEqual(res3.descriptionMatch![0].end, 4); let res4 = scoreItem(resource, 'path z y', true, ResourceAccessor); assert.ok(res4.score); assert.ok(res4.score < res2.score); assert.strictEqual(res4.labelMatch?.length, 0); assert.strictEqual(res4.descriptionMatch?.length, 2); assert.strictEqual(res4.descriptionMatch![0].start, 2); assert.strictEqual(res4.descriptionMatch![0].end, 4); assert.strictEqual(res4.descriptionMatch![1].start, 10); assert.strictEqual(res4.descriptionMatch![1].end, 14); }); test('scoreItem - invalid input', function () { let res = scoreItem(null, null!, true, ResourceAccessor); assert.strictEqual(res.score, 0); res = scoreItem(null, 'null', true, ResourceAccessor); assert.strictEqual(res.score, 0); }); test('scoreItem - optimize for file paths', function () { const resource = URI.file('/xyz/others/spath/some/xsp/file123.txt'); // xsp is more relevant to the end of the file path even though it matches // fuzzy also in the beginning. we verify the more relevant match at the // end gets returned. const pathRes = scoreItem(resource, 'xspfile123', true, ResourceAccessor); assert.ok(pathRes.score); assert.ok(pathRes.descriptionMatch); assert.ok(pathRes.labelMatch); assert.strictEqual(pathRes.labelMatch!.length, 1); assert.strictEqual(pathRes.labelMatch![0].start, 0); assert.strictEqual(pathRes.labelMatch![0].end, 7); assert.strictEqual(pathRes.descriptionMatch!.length, 1); assert.strictEqual(pathRes.descriptionMatch![0].start, 23); assert.strictEqual(pathRes.descriptionMatch![0].end, 26); }); test('scoreItem - avoid match scattering (bug #36119)', function () { const resource = URI.file('projects/ui/cula/ats/target.mk'); const pathRes = scoreItem(resource, 'tcltarget.mk', true, ResourceAccessor); assert.ok(pathRes.score); assert.ok(pathRes.descriptionMatch); assert.ok(pathRes.labelMatch); assert.strictEqual(pathRes.labelMatch!.length, 1); assert.strictEqual(pathRes.labelMatch![0].start, 0); assert.strictEqual(pathRes.labelMatch![0].end, 9); }); test('scoreItem - prefers more compact matches', function () { const resource = URI.file('/1a111d1/11a1d1/something.txt'); // expect "ad" to be matched towards the end of the file because the // match is more compact const res = scoreItem(resource, 'ad', true, ResourceAccessor); assert.ok(res.score); assert.ok(res.descriptionMatch); assert.ok(!res.labelMatch!.length); assert.strictEqual(res.descriptionMatch!.length, 2); assert.strictEqual(res.descriptionMatch![0].start, 11); assert.strictEqual(res.descriptionMatch![0].end, 12); assert.strictEqual(res.descriptionMatch![1].start, 13); assert.strictEqual(res.descriptionMatch![1].end, 14); }); test('scoreItem - proper target offset', function () { const resource = URI.file('etem'); const res = scoreItem(resource, 'teem', true, ResourceAccessor); assert.ok(!res.score); }); test('scoreItem - proper target offset #2', function () { const resource = URI.file('ede'); const res = scoreItem(resource, 'de', true, ResourceAccessor); assert.strictEqual(res.labelMatch!.length, 1); assert.strictEqual(res.labelMatch![0].start, 1); assert.strictEqual(res.labelMatch![0].end, 3); }); test('scoreItem - proper target offset #3', function () { const resource = URI.file('/src/vs/editor/browser/viewParts/lineNumbers/flipped-cursor-2x.svg'); const res = scoreItem(resource, 'debug', true, ResourceAccessor); assert.strictEqual(res.descriptionMatch!.length, 3); assert.strictEqual(res.descriptionMatch![0].start, 9); assert.strictEqual(res.descriptionMatch![0].end, 10); assert.strictEqual(res.descriptionMatch![1].start, 36); assert.strictEqual(res.descriptionMatch![1].end, 37); assert.strictEqual(res.descriptionMatch![2].start, 40); assert.strictEqual(res.descriptionMatch![2].end, 41); assert.strictEqual(res.labelMatch!.length, 2); assert.strictEqual(res.labelMatch![0].start, 9); assert.strictEqual(res.labelMatch![0].end, 10); assert.strictEqual(res.labelMatch![1].start, 20); assert.strictEqual(res.labelMatch![1].end, 21); }); test('scoreItem - no match unless query contained in sequence', function () { const resource = URI.file('abcde'); const res = scoreItem(resource, 'edcda', true, ResourceAccessor); assert.ok(!res.score); }); test('scoreItem - match if using slash or backslash (local, remote resource)', function () { const localResource = URI.file('abcde/super/duper'); const remoteResource = URI.from({ scheme: Schemas.vscodeRemote, path: 'abcde/super/duper' }); for (const resource of [localResource, remoteResource]) { let res = scoreItem(resource, 'abcde\\super\\duper', true, ResourceAccessor); assert.ok(res.score); res = scoreItem(resource, 'abcde\\super\\duper', true, ResourceWithSlashAccessor); assert.ok(res.score); res = scoreItem(resource, 'abcde\\super\\duper', true, ResourceWithBackslashAccessor); assert.ok(res.score); res = scoreItem(resource, 'abcde/super/duper', true, ResourceAccessor); assert.ok(res.score); res = scoreItem(resource, 'abcde/super/duper', true, ResourceWithSlashAccessor); assert.ok(res.score); res = scoreItem(resource, 'abcde/super/duper', true, ResourceWithBackslashAccessor); assert.ok(res.score); } }); test('compareItemsByScore - identity', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileB.txt'); const resourceC = URI.file('/unrelated/some/path/other/fileC.txt'); // Full resource A path let query = ResourceAccessor.getItemPath(resourceA); let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); // Full resource B path query = ResourceAccessor.getItemPath(resourceB); res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - basename prefix', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileB.txt'); const resourceC = URI.file('/unrelated/some/path/other/fileC.txt'); // Full resource A basename let query = ResourceAccessor.getItemLabel(resourceA); let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); // Full resource B basename query = ResourceAccessor.getItemLabel(resourceB); res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - basename camelcase', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileB.txt'); const resourceC = URI.file('/unrelated/some/path/other/fileC.txt'); // resource A camelcase let query = 'fA'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); // resource B camelcase query = 'fB'; res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - basename scores', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileB.txt'); const resourceC = URI.file('/unrelated/some/path/other/fileC.txt'); // Resource A part of basename let query = 'fileA'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); // Resource B part of basename query = 'fileB'; res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - path scores', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileB.txt'); const resourceC = URI.file('/unrelated/some/path/other/fileC.txt'); // Resource A part of path let query = 'pathfileA'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); // Resource B part of path query = 'pathfileB'; res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - prefer shorter basenames', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileBLonger.txt'); const resourceC = URI.file('/unrelated/the/path/other/fileC.txt'); // Resource A part of path let query = 'somepath'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - prefer shorter basenames (match on basename)', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileBLonger.txt'); const resourceC = URI.file('/unrelated/the/path/other/fileC.txt'); // Resource A part of path let query = 'file'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceC); assert.strictEqual(res[2], resourceB); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceC); assert.strictEqual(res[2], resourceB); }); test('compareFilesByScore - prefer shorter paths', function () { const resourceA = URI.file('/some/path/fileA.txt'); const resourceB = URI.file('/some/path/other/fileB.txt'); const resourceC = URI.file('/unrelated/some/path/other/fileC.txt'); // Resource A part of path let query = 'somepath'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - prefer shorter paths (bug #17443)', function () { const resourceA = URI.file('config/test/t1.js'); const resourceB = URI.file('config/test.js'); const resourceC = URI.file('config/test/t2.js'); let query = 'co/te'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); assert.strictEqual(res[2], resourceC); }); test('compareFilesByScore - prefer matches in label over description if scores are otherwise equal', function () { const resourceA = URI.file('parts/quick/arrow-left-dark.svg'); const resourceB = URI.file('parts/quickopen/quickopen.ts'); let query = 'partsquick'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); }); test('compareFilesByScore - prefer camel case matches', function () { const resourceA = URI.file('config/test/NullPointerException.java'); const resourceB = URI.file('config/test/nopointerexception.java'); for (const query of ['npe', 'NPE']) { let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); } }); test('compareFilesByScore - prefer more compact camel case matches', function () { const resourceA = URI.file('config/test/openthisAnythingHandler.js'); const resourceB = URI.file('config/test/openthisisnotsorelevantforthequeryAnyHand.js'); let query = 'AH'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); }); test('compareFilesByScore - prefer more compact matches (label)', function () { const resourceA = URI.file('config/test/examasdaple.js'); const resourceB = URI.file('config/test/exampleasdaasd.ts'); let query = 'xp'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); }); test('compareFilesByScore - prefer more compact matches (path)', function () { const resourceA = URI.file('config/test/examasdaple/file.js'); const resourceB = URI.file('config/test/exampleasdaasd/file.ts'); let query = 'xp'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); }); test('compareFilesByScore - prefer more compact matches (label and path)', function () { const resourceA = URI.file('config/example/thisfile.ts'); const resourceB = URI.file('config/24234243244/example/file.js'); let query = 'exfile'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); }); test('compareFilesByScore - avoid match scattering (bug #34210)', function () { const resourceA = URI.file('node_modules1/bundle/lib/model/modules/ot1/index.js'); const resourceB = URI.file('node_modules1/bundle/lib/model/modules/un1/index.js'); const resourceC = URI.file('node_modules1/bundle/lib/model/modules/modu1/index.js'); const resourceD = URI.file('node_modules1/bundle/lib/model/modules/oddl1/index.js'); let query = isWindows ? 'modu1\\index.js' : 'modu1/index.js'; let res = [resourceA, resourceB, resourceC, resourceD].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceC); res = [resourceC, resourceB, resourceA, resourceD].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceC); query = isWindows ? 'un1\\index.js' : 'un1/index.js'; res = [resourceA, resourceB, resourceC, resourceD].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceC, resourceB, resourceA, resourceD].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #21019 1.)', function () { const resourceA = URI.file('app/containers/Services/NetworkData/ServiceDetails/ServiceLoad/index.js'); const resourceB = URI.file('app/containers/Services/NetworkData/ServiceDetails/ServiceDistribution/index.js'); const resourceC = URI.file('app/containers/Services/NetworkData/ServiceDetailTabs/ServiceTabs/StatVideo/index.js'); let query = 'StatVideoindex'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceC); }); test('compareFilesByScore - avoid match scattering (bug #21019 2.)', function () { const resourceA = URI.file('src/build-helper/store/redux.ts'); const resourceB = URI.file('src/repository/store/redux.ts'); let query = 'reproreduxts'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #26649)', function () { const resourceA = URI.file('photobook/src/components/AddPagesButton/index.js'); const resourceB = URI.file('photobook/src/components/ApprovalPageHeader/index.js'); const resourceC = URI.file('photobook/src/canvasComponents/BookPage/index.js'); let query = 'bookpageIndex'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceC); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceC); }); test('compareFilesByScore - avoid match scattering (bug #33247)', function () { const resourceA = URI.file('ui/src/utils/constants.js'); const resourceB = URI.file('ui/src/ui/Icons/index.js'); let query = isWindows ? 'ui\\icons' : 'ui/icons'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #33247 comment)', function () { const resourceA = URI.file('ui/src/components/IDInput/index.js'); const resourceB = URI.file('ui/src/ui/Input/index.js'); let query = isWindows ? 'ui\\input\\index' : 'ui/input/index'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #36166)', function () { const resourceA = URI.file('django/contrib/sites/locale/ga/LC_MESSAGES/django.mo'); const resourceB = URI.file('django/core/signals.py'); let query = 'djancosig'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #32918)', function () { const resourceA = URI.file('adsys/protected/config.php'); const resourceB = URI.file('adsys/protected/framework/smarty/sysplugins/smarty_internal_config.php'); const resourceC = URI.file('duowanVideo/wap/protected/config.php'); let query = 'protectedconfig.php'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceC); assert.strictEqual(res[2], resourceB); res = [resourceC, resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceC); assert.strictEqual(res[2], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #14879)', function () { const resourceA = URI.file('pkg/search/gradient/testdata/constraint_attrMatchString.yml'); const resourceB = URI.file('cmd/gradient/main.go'); let query = 'gradientmain'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #14727 1)', function () { const resourceA = URI.file('alpha-beta-cappa.txt'); const resourceB = URI.file('abc.txt'); let query = 'abc'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #14727 2)', function () { const resourceA = URI.file('xerxes-yak-zubba/index.js'); const resourceB = URI.file('xyz/index.js'); let query = 'xyz'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #18381)', function () { const resourceA = URI.file('AssymblyInfo.cs'); const resourceB = URI.file('IAsynchronousTask.java'); let query = 'async'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #35572)', function () { const resourceA = URI.file('static/app/source/angluar/-admin/-organization/-settings/layout/layout.js'); const resourceB = URI.file('static/app/source/angular/-admin/-project/-settings/_settings/settings.js'); let query = 'partisettings'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #36810)', function () { const resourceA = URI.file('Trilby.TrilbyTV.Web.Portal/Views/Systems/Index.cshtml'); const resourceB = URI.file('Trilby.TrilbyTV.Web.Portal/Areas/Admins/Views/Tips/Index.cshtml'); let query = 'tipsindex.cshtml'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - prefer shorter hit (bug #20546)', function () { const resourceA = URI.file('editor/core/components/tests/list-view-spec.js'); const resourceB = URI.file('editor/core/components/list-view.js'); let query = 'listview'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - avoid match scattering (bug #12095)', function () { const resourceA = URI.file('src/vs/workbench/contrib/files/common/explorerViewModel.ts'); const resourceB = URI.file('src/vs/workbench/contrib/files/browser/views/explorerView.ts'); const resourceC = URI.file('src/vs/workbench/contrib/files/browser/views/explorerViewer.ts'); let query = 'filesexplorerview.ts'; let res = [resourceA, resourceB, resourceC].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceA, resourceC, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - prefer case match (bug #96122)', function () { const resourceA = URI.file('lists.php'); const resourceB = URI.file('lib/Lists.php'); let query = 'Lists.php'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); }); test('compareFilesByScore - prefer shorter match (bug #103052) - foo bar', function () { const resourceA = URI.file('app/emails/foo.bar.js'); const resourceB = URI.file('app/emails/other-footer.other-bar.js'); for (const query of ['foo bar', 'foobar']) { let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); } }); test('compareFilesByScore - prefer shorter match (bug #103052) - payment model', function () { const resourceA = URI.file('app/components/payment/payment.model.js'); const resourceB = URI.file('app/components/online-payments-history/online-payments-history.model.js'); for (const query of ['payment model', 'paymentmodel']) { let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); } }); test('compareFilesByScore - prefer shorter match (bug #103052) - color', function () { const resourceA = URI.file('app/constants/color.js'); const resourceB = URI.file('app/components/model/input/pick-avatar-color.js'); for (const query of ['color js', 'colorjs']) { let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); } }); test('compareFilesByScore - prefer strict case prefix', function () { const resourceA = URI.file('app/constants/color.js'); const resourceB = URI.file('app/components/model/input/Color.js'); let query = 'Color'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); query = 'color'; res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); }); test('compareFilesByScore - prefer prefix (bug #103052)', function () { const resourceA = URI.file('test/smoke/src/main.ts'); const resourceB = URI.file('src/vs/editor/common/services/semantikTokensProviderStyling.ts'); let query = 'smoke main.ts'; let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceA); assert.strictEqual(res[1], resourceB); }); test('compareFilesByScore - boost better prefix match if multiple queries are used', function () { const resourceA = URI.file('src/vs/workbench/services/host/browser/browserHostService.ts'); const resourceB = URI.file('src/vs/workbench/browser/workbench.ts'); for (const query of ['workbench.ts browser', 'browser workbench.ts', 'browser workbench', 'workbench browser']) { let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); } }); test('compareFilesByScore - boost shorter prefix match if multiple queries are used', function () { const resourceA = URI.file('src/vs/workbench/browser/actions/windowActions.ts'); const resourceB = URI.file('src/vs/workbench/electron-browser/window.ts'); for (const query of ['window browser', 'window.ts browser']) { let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); } }); test('compareFilesByScore - boost shorter prefix match if multiple queries are used (#99171)', function () { const resourceA = URI.file('mesh_editor_lifetime_job.h'); const resourceB = URI.file('lifetime_job.h'); for (const query of ['m life, life m']) { let res = [resourceA, resourceB].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); res = [resourceB, resourceA].sort((r1, r2) => compareItemsByScore(r1, r2, query, true, ResourceAccessor)); assert.strictEqual(res[0], resourceB); assert.strictEqual(res[1], resourceA); } }); test('prepareQuery', () => { assert.strictEqual(prepareQuery(' f*a ').normalized, 'fa'); assert.strictEqual(prepareQuery('model Tester.ts').original, 'model Tester.ts'); assert.strictEqual(prepareQuery('model Tester.ts').originalLowercase, 'model Tester.ts'.toLowerCase()); assert.strictEqual(prepareQuery('model Tester.ts').normalized, 'modelTester.ts'); assert.strictEqual(prepareQuery('Model Tester.ts').normalizedLowercase, 'modeltester.ts'); assert.strictEqual(prepareQuery('ModelTester.ts').containsPathSeparator, false); assert.strictEqual(prepareQuery('Model' + sep + 'Tester.ts').containsPathSeparator, true); // with spaces let query = prepareQuery('He*llo World'); assert.strictEqual(query.original, 'He*llo World'); assert.strictEqual(query.normalized, 'HelloWorld'); assert.strictEqual(query.normalizedLowercase, 'HelloWorld'.toLowerCase()); assert.strictEqual(query.values?.length, 2); assert.strictEqual(query.values?.[0].original, 'He*llo'); assert.strictEqual(query.values?.[0].normalized, 'Hello'); assert.strictEqual(query.values?.[0].normalizedLowercase, 'Hello'.toLowerCase()); assert.strictEqual(query.values?.[1].original, 'World'); assert.strictEqual(query.values?.[1].normalized, 'World'); assert.strictEqual(query.values?.[1].normalizedLowercase, 'World'.toLowerCase()); let restoredQuery = pieceToQuery(query.values!); assert.strictEqual(restoredQuery.original, query.original); assert.strictEqual(restoredQuery.values?.length, query.values?.length); assert.strictEqual(restoredQuery.containsPathSeparator, query.containsPathSeparator); // with spaces that are empty query = prepareQuery(' Hello World '); assert.strictEqual(query.original, ' Hello World '); assert.strictEqual(query.originalLowercase, ' Hello World '.toLowerCase()); assert.strictEqual(query.normalized, 'HelloWorld'); assert.strictEqual(query.normalizedLowercase, 'HelloWorld'.toLowerCase()); assert.strictEqual(query.values?.length, 2); assert.strictEqual(query.values?.[0].original, 'Hello'); assert.strictEqual(query.values?.[0].originalLowercase, 'Hello'.toLowerCase()); assert.strictEqual(query.values?.[0].normalized, 'Hello'); assert.strictEqual(query.values?.[0].normalizedLowercase, 'Hello'.toLowerCase()); assert.strictEqual(query.values?.[1].original, 'World'); assert.strictEqual(query.values?.[1].originalLowercase, 'World'.toLowerCase()); assert.strictEqual(query.values?.[1].normalized, 'World'); assert.strictEqual(query.values?.[1].normalizedLowercase, 'World'.toLowerCase()); // Path related if (isWindows) { assert.strictEqual(prepareQuery('C:\\some\\path').pathNormalized, 'C:\\some\\path'); assert.strictEqual(prepareQuery('C:\\some\\path').normalized, 'C:\\some\\path'); assert.strictEqual(prepareQuery('C:\\some\\path').containsPathSeparator, true); assert.strictEqual(prepareQuery('C:/some/path').pathNormalized, 'C:\\some\\path'); assert.strictEqual(prepareQuery('C:/some/path').normalized, 'C:\\some\\path'); assert.strictEqual(prepareQuery('C:/some/path').containsPathSeparator, true); } else { assert.strictEqual(prepareQuery('/some/path').pathNormalized, '/some/path'); assert.strictEqual(prepareQuery('/some/path').normalized, '/some/path'); assert.strictEqual(prepareQuery('/some/path').containsPathSeparator, true); assert.strictEqual(prepareQuery('\\some\\path').pathNormalized, '/some/path'); assert.strictEqual(prepareQuery('\\some\\path').normalized, '/some/path'); assert.strictEqual(prepareQuery('\\some\\path').containsPathSeparator, true); } }); test('fuzzyScore2 (matching)', function () { const target = 'HeLlo-World'; for (const offset of [0, 3]) { let [score, matches] = _doScore2(offset === 0 ? target : `123${target}`, 'HeLlo-World', offset); assert.ok(score); assert.strictEqual(matches.length, 1); assert.strictEqual(matches[0].start, 0 + offset); assert.strictEqual(matches[0].end, target.length + offset); [score, matches] = _doScore2(offset === 0 ? target : `123${target}`, 'HW', offset); assert.ok(score); assert.strictEqual(matches.length, 2); assert.strictEqual(matches[0].start, 0 + offset); assert.strictEqual(matches[0].end, 1 + offset); assert.strictEqual(matches[1].start, 6 + offset); assert.strictEqual(matches[1].end, 7 + offset); } }); test('fuzzyScore2 (multiple queries)', function () { const target = 'HeLlo-World'; const [firstSingleScore, firstSingleMatches] = _doScore2(target, 'HelLo'); const [secondSingleScore, secondSingleMatches] = _doScore2(target, 'World'); const firstAndSecondSingleMatches = [...firstSingleMatches || [], ...secondSingleMatches || []]; let [multiScore, multiMatches] = _doScore2(target, 'HelLo World'); function assertScore() { assert.ok(multiScore ?? 0 >= ((firstSingleScore ?? 0) + (secondSingleScore ?? 0))); for (let i = 0; multiMatches && i < multiMatches.length; i++) { const multiMatch = multiMatches[i]; const firstAndSecondSingleMatch = firstAndSecondSingleMatches[i]; if (multiMatch && firstAndSecondSingleMatch) { assert.strictEqual(multiMatch.start, firstAndSecondSingleMatch.start); assert.strictEqual(multiMatch.end, firstAndSecondSingleMatch.end); } else { assert.fail(); } } } function assertNoScore() { assert.strictEqual(multiScore, undefined); assert.strictEqual(multiMatches.length, 0); } assertScore(); [multiScore, multiMatches] = _doScore2(target, 'World HelLo'); assertScore(); [multiScore, multiMatches] = _doScore2(target, 'World HelLo World'); assertScore(); [multiScore, multiMatches] = _doScore2(target, 'World HelLo Nothing'); assertNoScore(); [multiScore, multiMatches] = _doScore2(target, 'More Nothing'); assertNoScore(); }); test('fuzzyScore2 (#95716)', function () { const target = '# ❌ Wow'; const score = _doScore2(target, '❌'); assert.ok(score); assert.ok(typeof score[0] === 'number'); assert.ok(score[1].length > 0); }); });
src/vs/base/test/common/fuzzyScorer.test.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017815115279518068, 0.00017544839647598565, 0.0001693243539193645, 0.0001757861318765208, 0.000001683551090536639 ]
{ "id": 4, "code_window": [ "\n", "\t\t\t\tconst newFrame = document.createElement('iframe');\n", "\t\t\t\tnewFrame.setAttribute('id', 'pending-frame');\n", "\t\t\t\tnewFrame.setAttribute('frameborder', '0');\n", "\t\t\t\tnewFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads' : 'allow-same-origin allow-pointer-lock');\n", "\t\t\t\tif (host.fakeLoad) {\n", "\t\t\t\t\t// We should just be able to use srcdoc, but I wasn't\n", "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tnewFrame.setAttribute('allow', options.allowScripts ? 'clipboard-read; clipboard-write;' : '');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 510 }
.yarnrc
build/lib/watch/.gitignore
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.0001726736081764102, 0.0001726736081764102, 0.0001726736081764102, 0.0001726736081764102, 0 ]
{ "id": 4, "code_window": [ "\n", "\t\t\t\tconst newFrame = document.createElement('iframe');\n", "\t\t\t\tnewFrame.setAttribute('id', 'pending-frame');\n", "\t\t\t\tnewFrame.setAttribute('frameborder', '0');\n", "\t\t\t\tnewFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads' : 'allow-same-origin allow-pointer-lock');\n", "\t\t\t\tif (host.fakeLoad) {\n", "\t\t\t\t\t// We should just be able to use srcdoc, but I wasn't\n", "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tnewFrame.setAttribute('allow', options.allowScripts ? 'clipboard-read; clipboard-write;' : '');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 510 }
{ "version": "2.0.0", "tasks": [ { "type": "npm", "script": "compile", "problemMatcher": "$tsc-watch", "isBackground": true, "presentation": { "reveal": "never" }, "group": { "kind": "build", "isDefault": true } } ] }
extensions/css-language-features/.vscode/tasks.json
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017308043607044965, 0.00017165372264571488, 0.00017022699466906488, 0.00017165372264571488, 0.0000014267207006923854 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n", "\t\t\t\t\tnewFrame.src = `./fake.html?id=${ID}`;\n", "\t\t\t\t}\n", "\t\t\t\tnewFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';\n", "\t\t\t\tdocument.body.appendChild(newFrame);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t} else {\n", "\t\t\t\t\tnewFrame.src = `about:blank?webviewFrame`;\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 516 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { session, WebContents, webContents } from 'electron'; import { Disposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITunnelService } from 'vs/platform/remote/common/tunnel'; import { IRequestService } from 'vs/platform/request/common/request'; import { webviewPartitionId } from 'vs/platform/webview/common/resourceLoader'; import { IWebviewManagerService, RegisterWebviewMetadata, WebviewManagerDidLoadResourceResponse, WebviewWebContentsId, WebviewWindowId } from 'vs/platform/webview/common/webviewManagerService'; import { WebviewPortMappingProvider } from 'vs/platform/webview/electron-main/webviewPortMappingProvider'; import { WebviewProtocolProvider } from 'vs/platform/webview/electron-main/webviewProtocolProvider'; import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows'; export class WebviewMainService extends Disposable implements IWebviewManagerService { declare readonly _serviceBrand: undefined; private readonly protocolProvider: WebviewProtocolProvider; private readonly portMappingProvider: WebviewPortMappingProvider; constructor( @IFileService fileService: IFileService, @ILogService logService: ILogService, @IRequestService requestService: IRequestService, @ITunnelService tunnelService: ITunnelService, @IWindowsMainService private readonly windowsMainService: IWindowsMainService, ) { super(); this.protocolProvider = this._register(new WebviewProtocolProvider(fileService, logService, requestService, windowsMainService)); this.portMappingProvider = this._register(new WebviewPortMappingProvider(tunnelService)); const sess = session.fromPartition(webviewPartitionId); sess.setPermissionRequestHandler((webContents, permission /* 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal' */, callback) => { return callback(false); }); sess.setPermissionCheckHandler((webContents, permission /* 'media' */) => { return false; }); } public async registerWebview(id: string, windowId: number, metadata: RegisterWebviewMetadata): Promise<void> { const extensionLocation = metadata.extensionLocation ? URI.from(metadata.extensionLocation) : undefined; this.protocolProvider.registerWebview(id, { ...metadata, windowId: windowId, extensionLocation, localResourceRoots: metadata.localResourceRoots.map(x => URI.from(x)) }); this.portMappingProvider.registerWebview(id, { extensionLocation, mappings: metadata.portMappings, resolvedAuthority: metadata.remoteConnectionData, }); } public async unregisterWebview(id: string): Promise<void> { this.protocolProvider.unregisterWebview(id); this.portMappingProvider.unregisterWebview(id); } public async updateWebviewMetadata(id: string, metaDataDelta: Partial<RegisterWebviewMetadata>): Promise<void> { const extensionLocation = metaDataDelta.extensionLocation ? URI.from(metaDataDelta.extensionLocation) : undefined; this.protocolProvider.updateWebviewMetadata(id, { ...metaDataDelta, extensionLocation, localResourceRoots: metaDataDelta.localResourceRoots?.map(x => URI.from(x)), }); this.portMappingProvider.updateWebviewMetadata(id, { ...metaDataDelta, extensionLocation, }); } public async setIgnoreMenuShortcuts(id: WebviewWebContentsId | WebviewWindowId, enabled: boolean): Promise<void> { let contents: WebContents | undefined; if (typeof (id as WebviewWindowId).windowId === 'number') { const { windowId } = (id as WebviewWindowId); const window = this.windowsMainService.getWindowById(windowId); if (!window?.win) { throw new Error(`Invalid windowId: ${windowId}`); } contents = window.win.webContents; } else { const { webContentsId } = (id as WebviewWebContentsId); contents = webContents.fromId(webContentsId); if (!contents) { throw new Error(`Invalid webContentsId: ${webContentsId}`); } } if (!contents.isDestroyed()) { contents.setIgnoreMenuShortcuts(enabled); } } public async didLoadResource(requestId: number, response: WebviewManagerDidLoadResourceResponse): Promise<void> { this.protocolProvider.didLoadResource(requestId, response); } }
src/vs/platform/webview/electron-main/webviewMainService.ts
1
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.0001746751950122416, 0.00017196114640682936, 0.00016838873852975667, 0.0001731558731989935, 0.0000022346525838656817 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n", "\t\t\t\t\tnewFrame.src = `./fake.html?id=${ID}`;\n", "\t\t\t\t}\n", "\t\t\t\tnewFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';\n", "\t\t\t\tdocument.body.appendChild(newFrame);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t} else {\n", "\t\t\t\t\tnewFrame.src = `about:blank?webviewFrame`;\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 516 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check /** @typedef {import('webpack').Configuration} WebpackConfig **/ 'use strict'; const path = require('path'); const fs = require('fs'); const merge = require('merge-options'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const { NLSBundlePlugin } = require('vscode-nls-dev/lib/webpack-bundler'); const { DefinePlugin } = require('webpack'); function withNodeDefaults(/**@type WebpackConfig*/extConfig) { // Need to find the top-most `package.json` file const folderName = path.relative(__dirname, extConfig.context).split(/[\\\/]/)[0]; const pkgPath = path.join(__dirname, folderName, 'package.json'); const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); const id = `${pkg.publisher}.${pkg.name}`; /** @type WebpackConfig */ let defaultConfig = { mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production') target: 'node', // extensions run in a node context node: { __dirname: false // leave the __dirname-behaviour intact }, resolve: { mainFields: ['module', 'main'], extensions: ['.ts', '.js'] // support ts-files and js-files }, module: { rules: [{ test: /\.ts$/, exclude: /node_modules/, use: [{ // vscode-nls-dev loader: // * rewrite nls-calls loader: 'vscode-nls-dev/lib/webpack-loader', options: { base: path.join(extConfig.context, 'src') } }, { // configure TypeScript loader: // * enable sources maps for end-to-end source maps loader: 'ts-loader', options: { compilerOptions: { 'sourceMap': true, } } }] }] }, externals: { 'vscode': 'commonjs vscode', // ignored because it doesn't exist }, output: { // all output goes into `dist`. // packaging depends on that and this must always be like it filename: '[name].js', path: path.join(extConfig.context, 'dist'), libraryTarget: 'commonjs', }, // yes, really source maps devtool: 'source-map', plugins: [ new CopyWebpackPlugin({ patterns: [ { from: 'src', to: '.', globOptions: { ignore: ['**/test/**', '**/*.ts'] }, noErrorOnMissing: true } ] }), new NLSBundlePlugin(id) ], }; return merge(defaultConfig, extConfig); } function withBrowserDefaults(/**@type WebpackConfig*/extConfig) { /** @type WebpackConfig */ let defaultConfig = { mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production') target: 'webworker', // extensions run in a webworker context resolve: { mainFields: ['module', 'main'], extensions: ['.ts', '.js'], // support ts-files and js-files alias: { 'vscode-nls': path.resolve(__dirname, '../build/polyfills/vscode-nls.js'), 'vscode-extension-telemetry': path.resolve(__dirname, '../build/polyfills/vscode-extension-telemetry.js') } }, module: { rules: [{ test: /\.ts$/, exclude: /node_modules/, use: [{ // configure TypeScript loader: // * enable sources maps for end-to-end source maps loader: 'ts-loader', options: { compilerOptions: { 'sourceMap': true, } } }] }] }, externals: { 'vscode': 'commonjs vscode', // ignored because it doesn't exist }, performance: { hints: false }, output: { // all output goes into `dist`. // packaging depends on that and this must always be like it filename: '[name].js', path: path.join(extConfig.context, 'dist', 'browser'), libraryTarget: 'commonjs', }, // yes, really source maps devtool: 'source-map', plugins: [ new CopyWebpackPlugin({ patterns: [ { from: 'src', to: '.', globOptions: { ignore: ['**/test/**', '**/*.ts'] }, noErrorOnMissing: true } ] }), new DefinePlugin({ WEBWORKER: JSON.stringify(true) }) ] }; return merge(defaultConfig, extConfig); } module.exports = withNodeDefaults; module.exports.node = withNodeDefaults; module.exports.browser = withBrowserDefaults;
extensions/shared.webpack.config.js
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.0001742588065098971, 0.00017007185670081526, 0.00016395156853832304, 0.00016999845684040338, 0.000002785602646326879 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n", "\t\t\t\t\tnewFrame.src = `./fake.html?id=${ID}`;\n", "\t\t\t\t}\n", "\t\t\t\tnewFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';\n", "\t\t\t\tdocument.body.appendChild(newFrame);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t} else {\n", "\t\t\t\t\tnewFrame.src = `about:blank?webviewFrame`;\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 516 }
<svg width="14px" height="14px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <rect fill="#7F4E7E" x="0" y="0" width="100" height="100" rx="35" ry="35"/> <text x="50" y="75" font-size="75" text-anchor="middle" style="font-family: Menlo, Monaco, Consolas, &quot;Droid Sans Mono&quot;, &quot;Inconsolata&quot;, &quot;Courier New&quot;, monospace, &quot;Droid Sans Fallback&quot;;" fill="white"> C </text> </svg>
extensions/git/resources/icons/dark/status-conflict.svg
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017215180560015142, 0.00017215180560015142, 0.00017215180560015142, 0.00017215180560015142, 0 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t// seeing the service worker applying properly.\n", "\t\t\t\t\t// Fake load an empty on the correct origin and then write real html\n", "\t\t\t\t\t// into it to get around this.\n", "\t\t\t\t\tnewFrame.src = `./fake.html?id=${ID}`;\n", "\t\t\t\t}\n", "\t\t\t\tnewFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';\n", "\t\t\t\tdocument.body.appendChild(newFrame);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t} else {\n", "\t\t\t\t\tnewFrame.src = `about:blank?webviewFrame`;\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "add", "edit_start_line_idx": 516 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/activitybarpart'; import { localize } from 'vs/nls'; import { ActionsOrientation, ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { GLOBAL_ACTIVITY_ID, IActivity, ACCOUNTS_ACTIVITY_ID } from 'vs/workbench/common/activity'; import { Part } from 'vs/workbench/browser/part'; import { GlobalActivityActionViewItem, ViewContainerActivityAction, PlaceHolderToggleCompositePinnedAction, PlaceHolderViewContainerActivityAction, AccountsActivityActionViewItem } from 'vs/workbench/browser/parts/activitybar/activitybarActions'; import { IBadge, NumberBadge } from 'vs/workbench/services/activity/common/activity'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IDisposable, toDisposable, DisposableStore, Disposable } from 'vs/base/common/lifecycle'; import { ToggleActivityBarVisibilityAction, ToggleSidebarPositionAction } from 'vs/workbench/browser/actions/layoutActions'; import { IThemeService, IColorTheme, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ACTIVITY_BAR_BACKGROUND, ACTIVITY_BAR_BORDER, ACTIVITY_BAR_FOREGROUND, ACTIVITY_BAR_ACTIVE_BORDER, ACTIVITY_BAR_BADGE_BACKGROUND, ACTIVITY_BAR_BADGE_FOREGROUND, ACTIVITY_BAR_INACTIVE_FOREGROUND, ACTIVITY_BAR_ACTIVE_BACKGROUND, ACTIVITY_BAR_DRAG_AND_DROP_BORDER } from 'vs/workbench/common/theme'; import { contrastBorder } from 'vs/platform/theme/common/colorRegistry'; import { CompositeBar, ICompositeBarItem, CompositeDragAndDrop } from 'vs/workbench/browser/parts/compositeBar'; import { Dimension, createCSSRule, asCSSUrl, addDisposableListener, EventType } from 'vs/base/browser/dom'; import { IStorageService, StorageScope, IStorageValueChangeEvent, StorageTarget } from 'vs/platform/storage/common/storage'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ToggleCompositePinnedAction, ICompositeBarColors, ActivityAction, ICompositeActivity } from 'vs/workbench/browser/parts/compositeBarActions'; import { IViewDescriptorService, ViewContainer, IViewContainerModel, ViewContainerLocation, IViewsService, getEnabledViewContainerContextKey } from 'vs/workbench/common/views'; import { IContextKeyService, ContextKeyExpr, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { assertIsDefined, isString } from 'vs/base/common/types'; import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { CustomMenubarControl } from 'vs/workbench/browser/parts/titlebar/menubarControl'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { getMenuBarVisibility } from 'vs/platform/windows/common/windows'; import { isNative } from 'vs/base/common/platform'; import { Before2D } from 'vs/workbench/browser/dnd'; import { Codicon } from 'vs/base/common/codicons'; import { IAction, Separator, toAction } from 'vs/base/common/actions'; import { Event } from 'vs/base/common/event'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Action2, registerAction2 } from 'vs/platform/actions/common/actions'; import { CATEGORIES } from 'vs/workbench/common/actions'; import { registerIcon } from 'vs/platform/theme/common/iconRegistry'; import { StringSHA1 } from 'vs/base/common/hash'; interface IPlaceholderViewContainer { readonly id: string; readonly name?: string; readonly iconUrl?: UriComponents; readonly themeIcon?: ThemeIcon; readonly isBuiltin?: boolean; readonly views?: { when?: string; }[]; } interface IPinnedViewContainer { readonly id: string; readonly pinned: boolean; readonly order?: number; readonly visible: boolean; } interface ICachedViewContainer { readonly id: string; name?: string; icon?: URI | ThemeIcon; readonly pinned: boolean; readonly order?: number; visible: boolean; isBuiltin?: boolean; views?: { when?: string; }[]; } export class ActivitybarPart extends Part implements IActivityBarService { declare readonly _serviceBrand: undefined; private static readonly PINNED_VIEW_CONTAINERS = 'workbench.activity.pinnedViewlets2'; private static readonly PLACEHOLDER_VIEW_CONTAINERS = 'workbench.activity.placeholderViewlets'; private static readonly ACTION_HEIGHT = 48; private static readonly ACCOUNTS_ACTION_INDEX = 0; private static readonly GEAR_ICON = registerIcon('settings-view-bar-icon', Codicon.settingsGear, localize('settingsViewBarIcon', "Settings icon in the view bar.")); private static readonly ACCOUNTS_ICON = registerIcon('accounts-view-bar-icon', Codicon.account, localize('accountsViewBarIcon', "Accounts icon in the view bar.")); //#region IView readonly minimumWidth: number = 48; readonly maximumWidth: number = 48; readonly minimumHeight: number = 0; readonly maximumHeight: number = Number.POSITIVE_INFINITY; //#endregion private content: HTMLElement | undefined; private menuBar: CustomMenubarControl | undefined; private menuBarContainer: HTMLElement | undefined; private compositeBar: CompositeBar; private compositeBarContainer: HTMLElement | undefined; private globalActivityAction: ActivityAction | undefined; private globalActivityActionBar: ActionBar | undefined; private globalActivitiesContainer: HTMLElement | undefined; private readonly globalActivity: ICompositeActivity[] = []; private accountsActivityAction: ActivityAction | undefined; private readonly accountsActivity: ICompositeActivity[] = []; private readonly compositeActions = new Map<string, { activityAction: ViewContainerActivityAction, pinnedAction: ToggleCompositePinnedAction; }>(); private readonly viewContainerDisposables = new Map<string, IDisposable>(); private readonly keyboardNavigationDisposables = this._register(new DisposableStore()); private readonly location = ViewContainerLocation.Sidebar; private hasExtensionsRegistered: boolean = false; private readonly enabledViewContainersContextKeys: Map<string, IContextKey<boolean>> = new Map<string, IContextKey<boolean>>(); constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @IThemeService themeService: IThemeService, @IStorageService private readonly storageService: IStorageService, @IExtensionService private readonly extensionService: IExtensionService, @IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService, @IViewsService private readonly viewsService: IViewsService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IConfigurationService private readonly configurationService: IConfigurationService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, ) { super(Parts.ACTIVITYBAR_PART, { hasTitle: false }, themeService, storageService, layoutService); for (const cachedViewContainer of this.cachedViewContainers) { cachedViewContainer.visible = !this.shouldBeHidden(cachedViewContainer.id, cachedViewContainer); } this.compositeBar = this.createCompositeBar(); this.onDidRegisterViewContainers(this.getViewContainers()); this.registerListeners(); } private createCompositeBar() { const cachedItems = this.cachedViewContainers .map(container => ({ id: container.id, name: container.name, visible: container.visible, order: container.order, pinned: container.pinned })); return this._register(this.instantiationService.createInstance(CompositeBar, cachedItems, { icon: true, orientation: ActionsOrientation.VERTICAL, preventLoopNavigation: true, openComposite: compositeId => this.viewsService.openViewContainer(compositeId, true), getActivityAction: compositeId => this.getCompositeActions(compositeId).activityAction, getCompositePinnedAction: compositeId => this.getCompositeActions(compositeId).pinnedAction, getOnCompositeClickAction: compositeId => toAction({ id: compositeId, label: '', run: async () => this.viewsService.isViewContainerVisible(compositeId) ? this.viewsService.closeViewContainer(compositeId) : this.viewsService.openViewContainer(compositeId) }), fillExtraContextMenuActions: actions => { const topActions: IAction[] = []; // Menu const menuBarVisibility = getMenuBarVisibility(this.configurationService); if (menuBarVisibility === 'compact' || menuBarVisibility === 'hidden' || menuBarVisibility === 'toggle') { topActions.push({ id: 'toggleMenuVisibility', label: localize('menu', "Menu"), class: undefined, tooltip: localize('menu', "Menu"), checked: menuBarVisibility === 'compact', enabled: true, run: async () => this.configurationService.updateValue('window.menuBarVisibility', menuBarVisibility === 'compact' ? 'toggle' : 'compact'), dispose: () => { } }); } if (topActions.length) { actions.unshift(...topActions, new Separator()); } // Accounts actions.push(new Separator()); actions.push({ id: 'toggleAccountsVisibility', label: localize('accounts', "Accounts"), class: undefined, tooltip: localize('accounts', "Accounts"), checked: this.accountsVisibilityPreference, enabled: true, run: async () => this.accountsVisibilityPreference = !this.accountsVisibilityPreference, dispose: () => { } }); actions.push(new Separator()); // Toggle Sidebar actions.push(this.instantiationService.createInstance(ToggleSidebarPositionAction, ToggleSidebarPositionAction.ID, ToggleSidebarPositionAction.getLabel(this.layoutService))); // Toggle Activity Bar actions.push(toAction({ id: ToggleActivityBarVisibilityAction.ID, label: localize('hideActivitBar', "Hide Activity Bar"), run: async () => this.instantiationService.invokeFunction(accessor => new ToggleActivityBarVisibilityAction().run(accessor)) })); }, getContextMenuActionsForComposite: compositeId => this.getContextMenuActionsForComposite(compositeId), getDefaultCompositeId: () => this.viewDescriptorService.getDefaultViewContainer(this.location)!.id, hidePart: () => this.layoutService.setSideBarHidden(true), dndHandler: new CompositeDragAndDrop(this.viewDescriptorService, ViewContainerLocation.Sidebar, (id: string, focus?: boolean) => this.viewsService.openViewContainer(id, focus), (from: string, to: string, before?: Before2D) => this.compositeBar.move(from, to, before?.verticallyBefore), () => this.compositeBar.getCompositeBarItems(), ), compositeSize: 52, colors: (theme: IColorTheme) => this.getActivitybarItemColors(theme), overflowActionSize: ActivitybarPart.ACTION_HEIGHT })); } private getContextMenuActionsForComposite(compositeId: string): IAction[] { const actions: IAction[] = []; const viewContainer = this.viewDescriptorService.getViewContainerById(compositeId)!; const defaultLocation = this.viewDescriptorService.getDefaultViewContainerLocation(viewContainer)!; if (defaultLocation !== this.viewDescriptorService.getViewContainerLocation(viewContainer)) { actions.push(toAction({ id: 'resetLocationAction', label: localize('resetLocation', "Reset Location"), run: () => this.viewDescriptorService.moveViewContainerToLocation(viewContainer, defaultLocation) })); } else { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); if (viewContainerModel.allViewDescriptors.length === 1) { const viewToReset = viewContainerModel.allViewDescriptors[0]; const defaultContainer = this.viewDescriptorService.getDefaultContainerById(viewToReset.id)!; if (defaultContainer !== viewContainer) { actions.push(toAction({ id: 'resetLocationAction', label: localize('resetLocation', "Reset Location"), run: () => this.viewDescriptorService.moveViewsToContainer([viewToReset], defaultContainer) })); } } } return actions; } private registerListeners(): void { // View Container Changes this._register(this.viewDescriptorService.onDidChangeViewContainers(({ added, removed }) => this.onDidChangeViewContainers(added, removed))); this._register(this.viewDescriptorService.onDidChangeContainerLocation(({ viewContainer, from, to }) => this.onDidChangeViewContainerLocation(viewContainer, from, to))); // View Container Visibility Changes this._register(Event.filter(this.viewsService.onDidChangeViewContainerVisibility, e => e.location === this.location)(({ id, visible }) => this.onDidChangeViewContainerVisibility(id, visible))); // Extension registration let disposables = this._register(new DisposableStore()); this._register(this.extensionService.onDidRegisterExtensions(() => { disposables.clear(); this.onDidRegisterExtensions(); this.compositeBar.onDidChange(() => this.saveCachedViewContainers(), this, disposables); this.storageService.onDidChangeValue(e => this.onDidStorageValueChange(e), this, disposables); })); // Register for configuration changes this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('window.menuBarVisibility')) { if (getMenuBarVisibility(this.configurationService) === 'compact') { this.installMenubar(); } else { this.uninstallMenubar(); } } })); } private onDidChangeViewContainers(added: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation; }>, removed: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation; }>) { removed.filter(({ location }) => location === ViewContainerLocation.Sidebar).forEach(({ container }) => this.onDidDeregisterViewContainer(container)); this.onDidRegisterViewContainers(added.filter(({ location }) => location === ViewContainerLocation.Sidebar).map(({ container }) => container)); } private onDidChangeViewContainerLocation(container: ViewContainer, from: ViewContainerLocation, to: ViewContainerLocation) { if (from === this.location) { this.onDidDeregisterViewContainer(container); } if (to === this.location) { this.onDidRegisterViewContainers([container]); } } private onDidChangeViewContainerVisibility(id: string, visible: boolean) { if (visible) { // Activate view container action on opening of a view container this.onDidViewContainerVisible(id); } else { // Deactivate view container action on close this.compositeBar.deactivateComposite(id); } } private onDidRegisterExtensions(): void { this.hasExtensionsRegistered = true; // show/hide/remove composites for (const { id } of this.cachedViewContainers) { const viewContainer = this.getViewContainer(id); if (viewContainer) { this.showOrHideViewContainer(viewContainer); } else { if (this.viewDescriptorService.isViewContainerRemovedPermanently(id)) { this.removeComposite(id); } else { this.hideComposite(id); } } } this.saveCachedViewContainers(); } private onDidViewContainerVisible(id: string): void { const viewContainer = this.getViewContainer(id); if (viewContainer) { // Update the composite bar by adding this.addComposite(viewContainer); this.compositeBar.activateComposite(viewContainer.id); if (this.shouldBeHidden(viewContainer)) { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); if (viewContainerModel.activeViewDescriptors.length === 0) { // Update the composite bar by hiding this.hideComposite(viewContainer.id); } } } } showActivity(viewContainerOrActionId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { if (this.getViewContainer(viewContainerOrActionId)) { return this.compositeBar.showActivity(viewContainerOrActionId, badge, clazz, priority); } if (viewContainerOrActionId === GLOBAL_ACTIVITY_ID) { return this.showGlobalActivity(GLOBAL_ACTIVITY_ID, badge, clazz, priority); } if (viewContainerOrActionId === ACCOUNTS_ACTIVITY_ID) { return this.showGlobalActivity(ACCOUNTS_ACTIVITY_ID, badge, clazz, priority); } return Disposable.None; } private showGlobalActivity(activityId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable { if (typeof priority !== 'number') { priority = 0; } const activity: ICompositeActivity = { badge, clazz, priority }; const activityCache = activityId === GLOBAL_ACTIVITY_ID ? this.globalActivity : this.accountsActivity; for (let i = 0; i <= activityCache.length; i++) { if (i === activityCache.length) { activityCache.push(activity); break; } else if (activityCache[i].priority <= priority) { activityCache.splice(i, 0, activity); break; } } this.updateGlobalActivity(activityId); return toDisposable(() => this.removeGlobalActivity(activityId, activity)); } private removeGlobalActivity(activityId: string, activity: ICompositeActivity): void { const activityCache = activityId === GLOBAL_ACTIVITY_ID ? this.globalActivity : this.accountsActivity; const index = activityCache.indexOf(activity); if (index !== -1) { activityCache.splice(index, 1); this.updateGlobalActivity(activityId); } } private updateGlobalActivity(activityId: string): void { const activityAction = activityId === GLOBAL_ACTIVITY_ID ? this.globalActivityAction : this.accountsActivityAction; if (!activityAction) { return; } const activityCache = activityId === GLOBAL_ACTIVITY_ID ? this.globalActivity : this.accountsActivity; if (activityCache.length) { const [{ badge, clazz, priority }] = activityCache; if (badge instanceof NumberBadge && activityCache.length > 1) { const cumulativeNumberBadge = this.getCumulativeNumberBadge(activityCache, priority); activityAction.setBadge(cumulativeNumberBadge); } else { activityAction.setBadge(badge, clazz); } } else { activityAction.setBadge(undefined); } } private getCumulativeNumberBadge(activityCache: ICompositeActivity[], priority: number): NumberBadge { const numberActivities = activityCache.filter(activity => activity.badge instanceof NumberBadge && activity.priority === priority); const number = numberActivities.reduce((result, activity) => { return result + (<NumberBadge>activity.badge).number; }, 0); const descriptorFn = (): string => { return numberActivities.reduce((result, activity, index) => { result = result + (<NumberBadge>activity.badge).getDescription(); if (index < numberActivities.length - 1) { result = `${result}\n`; } return result; }, ''); }; return new NumberBadge(number, descriptorFn); } private uninstallMenubar() { if (this.menuBar) { this.menuBar.dispose(); this.menuBar = undefined; } if (this.menuBarContainer) { this.menuBarContainer.remove(); this.menuBarContainer = undefined; this.registerKeyboardNavigationListeners(); } } private installMenubar() { if (this.menuBar) { return; // prevent menu bar from installing twice #110720 } this.menuBarContainer = document.createElement('div'); this.menuBarContainer.classList.add('menubar'); const content = assertIsDefined(this.content); content.prepend(this.menuBarContainer); // Menubar: install a custom menu bar depending on configuration this.menuBar = this._register(this.instantiationService.createInstance(CustomMenubarControl)); this.menuBar.create(this.menuBarContainer); this.registerKeyboardNavigationListeners(); } createContentArea(parent: HTMLElement): HTMLElement { this.element = parent; this.content = document.createElement('div'); this.content.classList.add('content'); parent.appendChild(this.content); // Install menubar if compact if (getMenuBarVisibility(this.configurationService) === 'compact') { this.installMenubar(); } // View Containers action bar this.compositeBarContainer = this.compositeBar.create(this.content); // Global action bar this.globalActivitiesContainer = document.createElement('div'); this.content.appendChild(this.globalActivitiesContainer); this.createGlobalActivityActionBar(this.globalActivitiesContainer); // Keyboard Navigation this.registerKeyboardNavigationListeners(); return this.content; } private registerKeyboardNavigationListeners(): void { this.keyboardNavigationDisposables.clear(); // Up/Down arrow on compact menu if (this.menuBarContainer) { this.keyboardNavigationDisposables.add(addDisposableListener(this.menuBarContainer, EventType.KEY_DOWN, e => { const kbEvent = new StandardKeyboardEvent(e); if (kbEvent.equals(KeyCode.DownArrow) || kbEvent.equals(KeyCode.RightArrow)) { if (this.compositeBar) { this.compositeBar.focus(); } } })); } // Up/Down on Activity Icons if (this.compositeBarContainer) { this.keyboardNavigationDisposables.add(addDisposableListener(this.compositeBarContainer, EventType.KEY_DOWN, e => { const kbEvent = new StandardKeyboardEvent(e); if (kbEvent.equals(KeyCode.DownArrow) || kbEvent.equals(KeyCode.RightArrow)) { if (this.globalActivityActionBar) { this.globalActivityActionBar.focus(true); } } else if (kbEvent.equals(KeyCode.UpArrow) || kbEvent.equals(KeyCode.LeftArrow)) { if (this.menuBar) { this.menuBar.toggleFocus(); } } })); } // Up arrow on global icons if (this.globalActivitiesContainer) { this.keyboardNavigationDisposables.add(addDisposableListener(this.globalActivitiesContainer, EventType.KEY_DOWN, e => { const kbEvent = new StandardKeyboardEvent(e); if (kbEvent.equals(KeyCode.UpArrow) || kbEvent.equals(KeyCode.LeftArrow)) { if (this.compositeBar) { this.compositeBar.focus(this.getVisibleViewContainerIds().length - 1); } } })); } } private createGlobalActivityActionBar(container: HTMLElement): void { this.globalActivityActionBar = this._register(new ActionBar(container, { actionViewItemProvider: action => { if (action.id === 'workbench.actions.manage') { return this.instantiationService.createInstance(GlobalActivityActionViewItem, action as ActivityAction, () => this.compositeBar.getContextMenuActions(), (theme: IColorTheme) => this.getActivitybarItemColors(theme)); } if (action.id === 'workbench.actions.accounts') { return this.instantiationService.createInstance(AccountsActivityActionViewItem, action as ActivityAction, () => this.compositeBar.getContextMenuActions(), (theme: IColorTheme) => this.getActivitybarItemColors(theme)); } throw new Error(`No view item for action '${action.id}'`); }, orientation: ActionsOrientation.VERTICAL, ariaLabel: localize('manage', "Manage"), animated: false, preventLoopNavigation: true })); this.globalActivityAction = this._register(new ActivityAction({ id: 'workbench.actions.manage', name: localize('manage', "Manage"), cssClass: ThemeIcon.asClassName(ActivitybarPart.GEAR_ICON) })); if (this.accountsVisibilityPreference) { this.accountsActivityAction = this._register(new ActivityAction({ id: 'workbench.actions.accounts', name: localize('accounts', "Accounts"), cssClass: ThemeIcon.asClassName(ActivitybarPart.ACCOUNTS_ICON) })); this.globalActivityActionBar.push(this.accountsActivityAction, { index: ActivitybarPart.ACCOUNTS_ACTION_INDEX }); } this.globalActivityActionBar.push(this.globalActivityAction); } private toggleAccountsActivity() { if (this.globalActivityActionBar) { if (this.accountsActivityAction) { this.globalActivityActionBar.pull(ActivitybarPart.ACCOUNTS_ACTION_INDEX); this.accountsActivityAction = undefined; } else { this.accountsActivityAction = this._register(new ActivityAction({ id: 'workbench.actions.accounts', name: localize('accounts', "Accounts"), cssClass: Codicon.account.classNames })); this.globalActivityActionBar.push(this.accountsActivityAction, { index: ActivitybarPart.ACCOUNTS_ACTION_INDEX }); } } this.updateGlobalActivity(ACCOUNTS_ACTIVITY_ID); } private getCompositeActions(compositeId: string): { activityAction: ViewContainerActivityAction, pinnedAction: ToggleCompositePinnedAction; } { let compositeActions = this.compositeActions.get(compositeId); if (!compositeActions) { const viewContainer = this.getViewContainer(compositeId); if (viewContainer) { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); compositeActions = { activityAction: this.instantiationService.createInstance(ViewContainerActivityAction, this.toActivity(viewContainerModel)), pinnedAction: new ToggleCompositePinnedAction(this.toActivity(viewContainerModel), this.compositeBar) }; } else { const cachedComposite = this.cachedViewContainers.filter(c => c.id === compositeId)[0]; compositeActions = { activityAction: this.instantiationService.createInstance(PlaceHolderViewContainerActivityAction, ActivitybarPart.toActivity(compositeId, compositeId, cachedComposite?.icon, undefined)), pinnedAction: new PlaceHolderToggleCompositePinnedAction(compositeId, this.compositeBar) }; } this.compositeActions.set(compositeId, compositeActions); } return compositeActions; } private onDidRegisterViewContainers(viewContainers: ReadonlyArray<ViewContainer>): void { for (const viewContainer of viewContainers) { this.addComposite(viewContainer); // Pin it by default if it is new const cachedViewContainer = this.cachedViewContainers.filter(({ id }) => id === viewContainer.id)[0]; if (!cachedViewContainer) { this.compositeBar.pin(viewContainer.id); } // Active const visibleViewContainer = this.viewsService.getVisibleViewContainer(this.location); if (visibleViewContainer?.id === viewContainer.id) { this.compositeBar.activateComposite(viewContainer.id); } const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); this.updateActivity(viewContainer, viewContainerModel); this.showOrHideViewContainer(viewContainer); const disposables = new DisposableStore(); disposables.add(viewContainerModel.onDidChangeContainerInfo(() => this.updateActivity(viewContainer, viewContainerModel))); disposables.add(viewContainerModel.onDidChangeActiveViewDescriptors(() => this.showOrHideViewContainer(viewContainer))); this.viewContainerDisposables.set(viewContainer.id, disposables); } } private onDidDeregisterViewContainer(viewContainer: ViewContainer): void { const disposable = this.viewContainerDisposables.get(viewContainer.id); if (disposable) { disposable.dispose(); } this.viewContainerDisposables.delete(viewContainer.id); this.removeComposite(viewContainer.id); } private updateActivity(viewContainer: ViewContainer, viewContainerModel: IViewContainerModel): void { const activity: IActivity = this.toActivity(viewContainerModel); const { activityAction, pinnedAction } = this.getCompositeActions(viewContainer.id); activityAction.updateActivity(activity); if (pinnedAction instanceof PlaceHolderToggleCompositePinnedAction) { pinnedAction.setActivity(activity); } this.saveCachedViewContainers(); } private toActivity(viewContainerModel: IViewContainerModel): IActivity { return ActivitybarPart.toActivity(viewContainerModel.viewContainer.id, viewContainerModel.title, viewContainerModel.icon, viewContainerModel.keybindingId); } private static toActivity(id: string, name: string, icon: URI | ThemeIcon | undefined, keybindingId: string | undefined): IActivity { let cssClass: string | undefined = undefined; let iconUrl: URI | undefined = undefined; if (URI.isUri(icon)) { iconUrl = icon; const cssUrl = asCSSUrl(icon); const hash = new StringSHA1(); hash.update(cssUrl); cssClass = `activity-${id.replace(/\./g, '-')}-${hash.digest()}`; const iconClass = `.monaco-workbench .activitybar .monaco-action-bar .action-label.${cssClass}`; createCSSRule(iconClass, ` mask: ${cssUrl} no-repeat 50% 50%; mask-size: 24px; -webkit-mask: ${cssUrl} no-repeat 50% 50%; -webkit-mask-size: 24px; `); } else if (ThemeIcon.isThemeIcon(icon)) { cssClass = ThemeIcon.asClassName(icon); } return { id, name, cssClass, iconUrl, keybindingId }; } private showOrHideViewContainer(viewContainer: ViewContainer): void { let contextKey = this.enabledViewContainersContextKeys.get(viewContainer.id); if (!contextKey) { contextKey = this.contextKeyService.createKey(getEnabledViewContainerContextKey(viewContainer.id), false); this.enabledViewContainersContextKeys.set(viewContainer.id, contextKey); } if (this.shouldBeHidden(viewContainer)) { contextKey.set(false); this.hideComposite(viewContainer.id); } else { contextKey.set(true); this.addComposite(viewContainer); } } private shouldBeHidden(viewContainerOrId: string | ViewContainer, cachedViewContainer?: ICachedViewContainer): boolean { const viewContainer = isString(viewContainerOrId) ? this.getViewContainer(viewContainerOrId) : viewContainerOrId; const viewContainerId = isString(viewContainerOrId) ? viewContainerOrId : viewContainerOrId.id; if (viewContainer) { if (viewContainer.hideIfEmpty) { if (this.viewDescriptorService.getViewContainerModel(viewContainer).activeViewDescriptors.length > 0) { return false; } } else { return false; } } // Check cache only if extensions are not yet registered and current window is not native (desktop) remote connection window if (!this.hasExtensionsRegistered && !(this.environmentService.remoteAuthority && isNative)) { cachedViewContainer = cachedViewContainer || this.cachedViewContainers.find(({ id }) => id === viewContainerId); // Show builtin ViewContainer if not registered yet if (!viewContainer && cachedViewContainer?.isBuiltin) { return false; } if (cachedViewContainer?.views?.length) { return cachedViewContainer.views.every(({ when }) => !!when && !this.contextKeyService.contextMatchesRules(ContextKeyExpr.deserialize(when))); } } return true; } private addComposite(viewContainer: ViewContainer): void { this.compositeBar.addComposite({ id: viewContainer.id, name: viewContainer.title, order: viewContainer.order, requestedIndex: viewContainer.requestedIndex }); } private hideComposite(compositeId: string): void { this.compositeBar.hideComposite(compositeId); const compositeActions = this.compositeActions.get(compositeId); if (compositeActions) { compositeActions.activityAction.dispose(); compositeActions.pinnedAction.dispose(); this.compositeActions.delete(compositeId); } } private removeComposite(compositeId: string): void { this.compositeBar.removeComposite(compositeId); const compositeActions = this.compositeActions.get(compositeId); if (compositeActions) { compositeActions.activityAction.dispose(); compositeActions.pinnedAction.dispose(); this.compositeActions.delete(compositeId); } } getPinnedViewContainerIds(): string[] { const pinnedCompositeIds = this.compositeBar.getPinnedComposites().map(v => v.id); return this.getViewContainers() .filter(v => this.compositeBar.isPinned(v.id)) .sort((v1, v2) => pinnedCompositeIds.indexOf(v1.id) - pinnedCompositeIds.indexOf(v2.id)) .map(v => v.id); } getVisibleViewContainerIds(): string[] { return this.compositeBar.getVisibleComposites() .filter(v => this.viewsService.getVisibleViewContainer(this.location)?.id === v.id || this.compositeBar.isPinned(v.id)) .map(v => v.id); } focusActivityBar(): void { this.compositeBar.focus(); } updateStyles(): void { super.updateStyles(); const container = assertIsDefined(this.getContainer()); const background = this.getColor(ACTIVITY_BAR_BACKGROUND) || ''; container.style.backgroundColor = background; const borderColor = this.getColor(ACTIVITY_BAR_BORDER) || this.getColor(contrastBorder) || ''; container.classList.toggle('bordered', !!borderColor); container.style.borderColor = borderColor ? borderColor : ''; } private getActivitybarItemColors(theme: IColorTheme): ICompositeBarColors { return { activeForegroundColor: theme.getColor(ACTIVITY_BAR_FOREGROUND), inactiveForegroundColor: theme.getColor(ACTIVITY_BAR_INACTIVE_FOREGROUND), activeBorderColor: theme.getColor(ACTIVITY_BAR_ACTIVE_BORDER), activeBackground: theme.getColor(ACTIVITY_BAR_ACTIVE_BACKGROUND), badgeBackground: theme.getColor(ACTIVITY_BAR_BADGE_BACKGROUND), badgeForeground: theme.getColor(ACTIVITY_BAR_BADGE_FOREGROUND), dragAndDropBorder: theme.getColor(ACTIVITY_BAR_DRAG_AND_DROP_BORDER), activeBackgroundColor: undefined, inactiveBackgroundColor: undefined, activeBorderBottomColor: undefined, }; } layout(width: number, height: number): void { if (!this.layoutService.isVisible(Parts.ACTIVITYBAR_PART)) { return; } // Layout contents const contentAreaSize = super.layoutContents(width, height).contentSize; // Layout composite bar let availableHeight = contentAreaSize.height; if (this.menuBarContainer) { availableHeight -= this.menuBarContainer.clientHeight; } if (this.globalActivityActionBar) { availableHeight -= (this.globalActivityActionBar.viewItems.length * ActivitybarPart.ACTION_HEIGHT); // adjust height for global actions showing } this.compositeBar.layout(new Dimension(width, availableHeight)); } private getViewContainer(id: string): ViewContainer | undefined { const viewContainer = this.viewDescriptorService.getViewContainerById(id); return viewContainer && this.viewDescriptorService.getViewContainerLocation(viewContainer) === this.location ? viewContainer : undefined; } private getViewContainers(): ReadonlyArray<ViewContainer> { return this.viewDescriptorService.getViewContainersByLocation(this.location); } private onDidStorageValueChange(e: IStorageValueChangeEvent): void { if (e.key === ActivitybarPart.PINNED_VIEW_CONTAINERS && e.scope === StorageScope.GLOBAL && this.pinnedViewContainersValue !== this.getStoredPinnedViewContainersValue() /* This checks if current window changed the value or not */) { this._pinnedViewContainersValue = undefined; this._cachedViewContainers = undefined; const newCompositeItems: ICompositeBarItem[] = []; const compositeItems = this.compositeBar.getCompositeBarItems(); for (const cachedViewContainer of this.cachedViewContainers) { newCompositeItems.push({ id: cachedViewContainer.id, name: cachedViewContainer.name, order: cachedViewContainer.order, pinned: cachedViewContainer.pinned, visible: !!compositeItems.find(({ id }) => id === cachedViewContainer.id) }); } for (let index = 0; index < compositeItems.length; index++) { // Add items currently exists but does not exist in new. if (!newCompositeItems.some(({ id }) => id === compositeItems[index].id)) { newCompositeItems.splice(index, 0, compositeItems[index]); } } this.compositeBar.setCompositeBarItems(newCompositeItems); } if (e.key === AccountsActivityActionViewItem.ACCOUNTS_VISIBILITY_PREFERENCE_KEY && e.scope === StorageScope.GLOBAL) { this.toggleAccountsActivity(); } } private saveCachedViewContainers(): void { const state: ICachedViewContainer[] = []; const compositeItems = this.compositeBar.getCompositeBarItems(); for (const compositeItem of compositeItems) { const viewContainer = this.getViewContainer(compositeItem.id); if (viewContainer) { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); const views: { when: string | undefined; }[] = []; for (const { when } of viewContainerModel.allViewDescriptors) { views.push({ when: when ? when.serialize() : undefined }); } state.push({ id: compositeItem.id, name: viewContainerModel.title, icon: URI.isUri(viewContainerModel.icon) && this.environmentService.remoteAuthority && isNative ? undefined : viewContainerModel.icon, /* Donot cache uri icons in desktop with remote connection */ views, pinned: compositeItem.pinned, order: compositeItem.order, visible: compositeItem.visible, isBuiltin: !viewContainer.extensionId }); } else { state.push({ id: compositeItem.id, pinned: compositeItem.pinned, order: compositeItem.order, visible: false, isBuiltin: false }); } } this.storeCachedViewContainersState(state); } private _cachedViewContainers: ICachedViewContainer[] | undefined = undefined; private get cachedViewContainers(): ICachedViewContainer[] { if (this._cachedViewContainers === undefined) { this._cachedViewContainers = this.getPinnedViewContainers(); for (const placeholderViewContainer of this.getPlaceholderViewContainers()) { const cachedViewContainer = this._cachedViewContainers.filter(cached => cached.id === placeholderViewContainer.id)[0]; if (cachedViewContainer) { cachedViewContainer.name = placeholderViewContainer.name; cachedViewContainer.icon = placeholderViewContainer.themeIcon ? placeholderViewContainer.themeIcon : placeholderViewContainer.iconUrl ? URI.revive(placeholderViewContainer.iconUrl) : undefined; cachedViewContainer.views = placeholderViewContainer.views; cachedViewContainer.isBuiltin = placeholderViewContainer.isBuiltin; } } } return this._cachedViewContainers; } private storeCachedViewContainersState(cachedViewContainers: ICachedViewContainer[]): void { this.setPinnedViewContainers(cachedViewContainers.map(({ id, pinned, visible, order }) => (<IPinnedViewContainer>{ id, pinned, visible, order }))); this.setPlaceholderViewContainers(cachedViewContainers.map(({ id, icon, name, views, isBuiltin }) => (<IPlaceholderViewContainer>{ id, iconUrl: URI.isUri(icon) ? icon : undefined, themeIcon: ThemeIcon.isThemeIcon(icon) ? icon : undefined, name, isBuiltin, views }))); } private getPinnedViewContainers(): IPinnedViewContainer[] { return JSON.parse(this.pinnedViewContainersValue); } private setPinnedViewContainers(pinnedViewContainers: IPinnedViewContainer[]): void { this.pinnedViewContainersValue = JSON.stringify(pinnedViewContainers); } private _pinnedViewContainersValue: string | undefined; private get pinnedViewContainersValue(): string { if (!this._pinnedViewContainersValue) { this._pinnedViewContainersValue = this.getStoredPinnedViewContainersValue(); } return this._pinnedViewContainersValue; } private set pinnedViewContainersValue(pinnedViewContainersValue: string) { if (this.pinnedViewContainersValue !== pinnedViewContainersValue) { this._pinnedViewContainersValue = pinnedViewContainersValue; this.setStoredPinnedViewContainersValue(pinnedViewContainersValue); } } private getStoredPinnedViewContainersValue(): string { return this.storageService.get(ActivitybarPart.PINNED_VIEW_CONTAINERS, StorageScope.GLOBAL, '[]'); } private setStoredPinnedViewContainersValue(value: string): void { this.storageService.store(ActivitybarPart.PINNED_VIEW_CONTAINERS, value, StorageScope.GLOBAL, StorageTarget.USER); } private getPlaceholderViewContainers(): IPlaceholderViewContainer[] { return JSON.parse(this.placeholderViewContainersValue); } private setPlaceholderViewContainers(placeholderViewContainers: IPlaceholderViewContainer[]): void { this.placeholderViewContainersValue = JSON.stringify(placeholderViewContainers); } private _placeholderViewContainersValue: string | undefined; private get placeholderViewContainersValue(): string { if (!this._placeholderViewContainersValue) { this._placeholderViewContainersValue = this.getStoredPlaceholderViewContainersValue(); } return this._placeholderViewContainersValue; } private set placeholderViewContainersValue(placeholderViewContainesValue: string) { if (this.placeholderViewContainersValue !== placeholderViewContainesValue) { this._placeholderViewContainersValue = placeholderViewContainesValue; this.setStoredPlaceholderViewContainersValue(placeholderViewContainesValue); } } private getStoredPlaceholderViewContainersValue(): string { return this.storageService.get(ActivitybarPart.PLACEHOLDER_VIEW_CONTAINERS, StorageScope.GLOBAL, '[]'); } private setStoredPlaceholderViewContainersValue(value: string): void { this.storageService.store(ActivitybarPart.PLACEHOLDER_VIEW_CONTAINERS, value, StorageScope.GLOBAL, StorageTarget.MACHINE); } private get accountsVisibilityPreference(): boolean { return this.storageService.getBoolean(AccountsActivityActionViewItem.ACCOUNTS_VISIBILITY_PREFERENCE_KEY, StorageScope.GLOBAL, true); } private set accountsVisibilityPreference(value: boolean) { this.storageService.store(AccountsActivityActionViewItem.ACCOUNTS_VISIBILITY_PREFERENCE_KEY, value, StorageScope.GLOBAL, StorageTarget.USER); } toJSON(): object { return { type: Parts.ACTIVITYBAR_PART }; } } class FocusActivityBarAction extends Action2 { constructor() { super({ id: 'workbench.action.focusActivityBar', title: { value: localize('focusActivityBar', "Focus Activity Bar"), original: 'Focus Activity Bar' }, category: CATEGORIES.View, f1: true }); } async run(accessor: ServicesAccessor): Promise<void> { const activityBarService = accessor.get(IActivityBarService); const layoutService = accessor.get(IWorkbenchLayoutService); layoutService.setActivityBarHidden(false); activityBarService.focusActivityBar(); } } registerSingleton(IActivityBarService, ActivitybarPart); registerAction2(FocusActivityBarAction);
src/vs/workbench/browser/parts/activitybar/activitybarPart.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.0003156682359986007, 0.00017151668726000935, 0.00016347669588867575, 0.00017055292846634984, 0.000014512324923998676 ]
{ "id": 6, "code_window": [ "\t\t// Wait the end of the ctor when all listeners have been hooked up.\n", "\t\tconst element = document.createElement('iframe');\n", "\t\telement.className = `webview ${options.customClasses || ''}`;\n", "\t\telement.sandbox.add('allow-scripts', 'allow-same-origin', 'allow-forms', 'allow-pointer-lock', 'allow-downloads');\n", "\t\telement.style.border = 'none';\n", "\t\telement.style.width = '100%';\n", "\t\telement.style.height = '100%';\n", "\t\treturn element;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\telement.setAttribute('allow', 'clipboard-read; clipboard-write;');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/webviewElement.ts", "type": "add", "edit_start_line_idx": 94 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check /** * @typedef {{ * postMessage: (channel: string, data?: any) => void, * onMessage: (channel: string, handler: any) => void, * focusIframeOnCreate?: boolean, * ready?: Promise<void>, * onIframeLoaded?: (iframe: HTMLIFrameElement) => void, * fakeLoad?: boolean, * rewriteCSP: (existingCSP: string, endpoint?: string) => string, * onElectron?: boolean * }} WebviewHost */ (function () { 'use strict'; const isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 && navigator.userAgent && navigator.userAgent.indexOf('CriOS') === -1 && navigator.userAgent.indexOf('FxiOS') === -1; /** * Use polling to track focus of main webview and iframes within the webview * * @param {Object} handlers * @param {() => void} handlers.onFocus * @param {() => void} handlers.onBlur */ const trackFocus = ({ onFocus, onBlur }) => { const interval = 50; let isFocused = document.hasFocus(); setInterval(() => { const isCurrentlyFocused = document.hasFocus(); if (isCurrentlyFocused === isFocused) { return; } isFocused = isCurrentlyFocused; if (isCurrentlyFocused) { onFocus(); } else { onBlur(); } }, interval); }; const getActiveFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('active-frame')); }; const getPendingFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('pending-frame')); }; const defaultCssRules = ` html { scrollbar-color: var(--vscode-scrollbarSlider-background) var(--vscode-editor-background); } body { background-color: transparent; color: var(--vscode-editor-foreground); font-family: var(--vscode-font-family); font-weight: var(--vscode-font-weight); font-size: var(--vscode-font-size); margin: 0; padding: 0 20px; } img { max-width: 100%; max-height: 100%; } a { color: var(--vscode-textLink-foreground); } a:hover { color: var(--vscode-textLink-activeForeground); } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } code { color: var(--vscode-textPreformat-foreground); } blockquote { background: var(--vscode-textBlockQuote-background); border-color: var(--vscode-textBlockQuote-border); } kbd { color: var(--vscode-editor-foreground); border-radius: 3px; vertical-align: middle; padding: 1px 3px; background-color: hsla(0,0%,50%,.17); border: 1px solid rgba(71,71,71,.4); border-bottom-color: rgba(88,88,88,.4); box-shadow: inset 0 -1px 0 rgba(88,88,88,.4); } .vscode-light kbd { background-color: hsla(0,0%,87%,.5); border: 1px solid hsla(0,0%,80%,.7); border-bottom-color: hsla(0,0%,73%,.7); box-shadow: inset 0 -1px 0 hsla(0,0%,73%,.7); } ::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-corner { background-color: var(--vscode-editor-background); } ::-webkit-scrollbar-thumb { background-color: var(--vscode-scrollbarSlider-background); } ::-webkit-scrollbar-thumb:hover { background-color: var(--vscode-scrollbarSlider-hoverBackground); } ::-webkit-scrollbar-thumb:active { background-color: var(--vscode-scrollbarSlider-activeBackground); }`; /** * @param {boolean} allowMultipleAPIAcquire * @param {*} [state] * @return {string} */ function getVsCodeApiScript(allowMultipleAPIAcquire, state) { const encodedState = state ? encodeURIComponent(state) : undefined; return ` globalThis.acquireVsCodeApi = (function() { const originalPostMessage = window.parent.postMessage.bind(window.parent); const targetOrigin = '*'; let acquired = false; let state = ${state ? `JSON.parse(decodeURIComponent("${encodedState}"))` : undefined}; return () => { if (acquired && !${allowMultipleAPIAcquire}) { throw new Error('An instance of the VS Code API has already been acquired'); } acquired = true; return Object.freeze({ postMessage: function(msg) { return originalPostMessage({ command: 'onmessage', data: msg }, targetOrigin); }, setState: function(newState) { state = newState; originalPostMessage({ command: 'do-update-state', data: JSON.stringify(newState) }, targetOrigin); return newState; }, getState: function() { return state; } }); }; })(); delete window.parent; delete window.top; delete window.frameElement; `; } /** * @param {WebviewHost} host */ function createWebviewManager(host) { // state let firstLoad = true; let loadTimeout; let pendingMessages = []; const initData = { initialScrollProgress: undefined, }; /** * @param {HTMLDocument?} document * @param {HTMLElement?} body */ const applyStyles = (document, body) => { if (!document) { return; } if (body) { body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast'); body.classList.add(initData.activeTheme); body.dataset.vscodeThemeKind = initData.activeTheme; body.dataset.vscodeThemeName = initData.themeName || ''; } if (initData.styles) { const documentStyle = document.documentElement.style; // Remove stale properties for (let i = documentStyle.length - 1; i >= 0; i--) { const property = documentStyle[i]; // Don't remove properties that the webview might have added separately if (property && property.startsWith('--vscode-')) { documentStyle.removeProperty(property); } } // Re-add new properties for (const variable of Object.keys(initData.styles)) { documentStyle.setProperty(`--${variable}`, initData.styles[variable]); } } }; /** * @param {MouseEvent} event */ const handleInnerClick = (event) => { if (!event || !event.view || !event.view.document) { return; } let baseElement = event.view.document.getElementsByTagName('base')[0]; /** @type {any} */ let node = event.target; while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { if (node.getAttribute('href') === '#') { event.view.scrollTo(0, 0); } else if (node.hash && (node.getAttribute('href') === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) { let scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1)); if (scrollTarget) { scrollTarget.scrollIntoView(); } } else { host.postMessage('did-click-link', node.href.baseVal || node.href); } event.preventDefault(); break; } node = node.parentNode; } }; /** * @param {MouseEvent} event */ const handleAuxClick = (event) => { // Prevent middle clicks opening a broken link in the browser if (!event.view || !event.view.document) { return; } if (event.button === 1) { let node = /** @type {any} */ (event.target); while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { event.preventDefault(); break; } node = node.parentNode; } } }; /** * @param {KeyboardEvent} e */ const handleInnerKeydown = (e) => { // If the keypress would trigger a browser event, such as copy or paste, // make sure we block the browser from dispatching it. Instead VS Code // handles these events and will dispatch a copy/paste back to the webview // if needed if (isUndoRedo(e)) { e.preventDefault(); } else if (isCopyPasteOrCut(e)) { if (host.onElectron) { e.preventDefault(); } else { return; // let the browser handle this } } host.postMessage('did-keydown', { key: e.key, keyCode: e.keyCode, code: e.code, shiftKey: e.shiftKey, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, repeat: e.repeat }); }; /** * @param {KeyboardEvent} e * @return {boolean} */ function isCopyPasteOrCut(e) { const hasMeta = e.ctrlKey || e.metaKey; const shiftInsert = e.shiftKey && e.key.toLowerCase() === 'insert'; return (hasMeta && ['c', 'v', 'x'].includes(e.key.toLowerCase())) || shiftInsert; } /** * @param {KeyboardEvent} e * @return {boolean} */ function isUndoRedo(e) { const hasMeta = e.ctrlKey || e.metaKey; return hasMeta && ['z', 'y'].includes(e.key.toLowerCase()); } let isHandlingScroll = false; const handleWheel = (event) => { if (isHandlingScroll) { return; } host.postMessage('did-scroll-wheel', { deltaMode: event.deltaMode, deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ, detail: event.detail, type: event.type }); }; const handleInnerScroll = (event) => { if (!event.target || !event.target.body) { return; } if (isHandlingScroll) { return; } const progress = event.currentTarget.scrollY / event.target.body.clientHeight; if (isNaN(progress)) { return; } isHandlingScroll = true; window.requestAnimationFrame(() => { try { host.postMessage('did-scroll', progress); } catch (e) { // noop } isHandlingScroll = false; }); }; /** * @return {string} */ function toContentHtml(data) { const options = data.options; const text = data.contents; const newDocument = new DOMParser().parseFromString(text, 'text/html'); newDocument.querySelectorAll('a').forEach(a => { if (!a.title) { a.title = a.getAttribute('href'); } }); // apply default script if (options.allowScripts) { const defaultScript = newDocument.createElement('script'); defaultScript.id = '_vscodeApiScript'; defaultScript.textContent = getVsCodeApiScript(options.allowMultipleAPIAcquire, data.state); newDocument.head.prepend(defaultScript); } // apply default styles const defaultStyles = newDocument.createElement('style'); defaultStyles.id = '_defaultStyles'; defaultStyles.textContent = defaultCssRules; newDocument.head.prepend(defaultStyles); applyStyles(newDocument, newDocument.body); // Check for CSP const csp = newDocument.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (!csp) { host.postMessage('no-csp-found'); } else { try { csp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint)); } catch (e) { console.error(`Could not rewrite csp: ${e}`); } } // set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off // and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML; } document.addEventListener('DOMContentLoaded', () => { const idMatch = document.location.search.match(/\bid=([\w-]+)/); const ID = idMatch ? idMatch[1] : undefined; if (!document.body) { return; } host.onMessage('styles', (_event, data) => { initData.styles = data.styles; initData.activeTheme = data.activeTheme; initData.themeName = data.themeName; const target = getActiveFrame(); if (!target) { return; } if (target.contentDocument) { applyStyles(target.contentDocument, target.contentDocument.body); } }); // propagate focus host.onMessage('focus', () => { const activeFrame = getActiveFrame(); if (!activeFrame || !activeFrame.contentWindow) { // Focus the top level webview instead window.focus(); return; } if (document.activeElement === activeFrame) { // We are already focused on the iframe (or one of its children) so no need // to refocus. return; } activeFrame.contentWindow.focus(); }); // update iframe-contents let updateId = 0; host.onMessage('content', async (_event, data) => { const currentUpdateId = ++updateId; await host.ready; if (currentUpdateId !== updateId) { return; } const options = data.options; const newDocument = toContentHtml(data); const frame = getActiveFrame(); const wasFirstLoad = firstLoad; // keep current scrollY around and use later let setInitialScrollPosition; if (firstLoad) { firstLoad = false; setInitialScrollPosition = (body, window) => { if (!isNaN(initData.initialScrollProgress)) { if (window.scrollY === 0) { window.scroll(0, body.clientHeight * initData.initialScrollProgress); } } }; } else { const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? frame.contentWindow.scrollY : 0; setInitialScrollPosition = (body, window) => { if (window.scrollY === 0) { window.scroll(0, scrollY); } }; } // Clean up old pending frames and set current one as new one const previousPendingFrame = getPendingFrame(); if (previousPendingFrame) { previousPendingFrame.setAttribute('id', ''); document.body.removeChild(previousPendingFrame); } if (!wasFirstLoad) { pendingMessages = []; } const newFrame = document.createElement('iframe'); newFrame.setAttribute('id', 'pending-frame'); newFrame.setAttribute('frameborder', '0'); newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads' : 'allow-same-origin allow-pointer-lock'); if (host.fakeLoad) { // We should just be able to use srcdoc, but I wasn't // seeing the service worker applying properly. // Fake load an empty on the correct origin and then write real html // into it to get around this. newFrame.src = `./fake.html?id=${ID}`; } newFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden'; document.body.appendChild(newFrame); if (!host.fakeLoad) { // write new content onto iframe newFrame.contentDocument.open(); } /** * @param {Document} contentDocument */ function onFrameLoaded(contentDocument) { // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=978325 setTimeout(() => { if (host.fakeLoad) { contentDocument.open(); contentDocument.write(newDocument); contentDocument.close(); hookupOnLoadHandlers(newFrame); } if (contentDocument) { applyStyles(contentDocument, contentDocument.body); } }, 0); } if (host.fakeLoad && !options.allowScripts && isSafari) { // On Safari for iframes with scripts disabled, the `DOMContentLoaded` never seems to be fired. // Use polling instead. const interval = setInterval(() => { // If the frame is no longer mounted, loading has stopped if (!newFrame.parentElement) { clearInterval(interval); return; } if (newFrame.contentDocument.readyState !== 'loading') { clearInterval(interval); onFrameLoaded(newFrame.contentDocument); } }, 10); } else { newFrame.contentWindow.addEventListener('DOMContentLoaded', e => { const contentDocument = e.target ? (/** @type {HTMLDocument} */ (e.target)) : undefined; onFrameLoaded(contentDocument); }); } /** * @param {Document} contentDocument * @param {Window} contentWindow */ const onLoad = (contentDocument, contentWindow) => { if (contentDocument && contentDocument.body) { // Workaround for https://github.com/microsoft/vscode/issues/12865 // check new scrollY and reset if necessary setInitialScrollPosition(contentDocument.body, contentWindow); } const newFrame = getPendingFrame(); if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) { const oldActiveFrame = getActiveFrame(); if (oldActiveFrame) { document.body.removeChild(oldActiveFrame); } // Styles may have changed since we created the element. Make sure we re-style applyStyles(newFrame.contentDocument, newFrame.contentDocument.body); newFrame.setAttribute('id', 'active-frame'); newFrame.style.visibility = 'visible'; if (host.focusIframeOnCreate) { newFrame.contentWindow.focus(); } contentWindow.addEventListener('scroll', handleInnerScroll); contentWindow.addEventListener('wheel', handleWheel); if (document.hasFocus()) { contentWindow.focus(); } pendingMessages.forEach((data) => { contentWindow.postMessage(data, '*'); }); pendingMessages = []; } host.postMessage('did-load'); }; /** * @param {HTMLIFrameElement} newFrame */ function hookupOnLoadHandlers(newFrame) { clearTimeout(loadTimeout); loadTimeout = undefined; loadTimeout = setTimeout(() => { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(newFrame.contentDocument, newFrame.contentWindow); }, 200); newFrame.contentWindow.addEventListener('load', function (e) { const contentDocument = /** @type {Document} */ (e.target); if (loadTimeout) { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(contentDocument, this); } }); // Bubble out various events newFrame.contentWindow.addEventListener('click', handleInnerClick); newFrame.contentWindow.addEventListener('auxclick', handleAuxClick); newFrame.contentWindow.addEventListener('keydown', handleInnerKeydown); newFrame.contentWindow.addEventListener('contextmenu', e => e.preventDefault()); if (host.onIframeLoaded) { host.onIframeLoaded(newFrame); } } if (!host.fakeLoad) { hookupOnLoadHandlers(newFrame); } if (!host.fakeLoad) { newFrame.contentDocument.write(newDocument); newFrame.contentDocument.close(); } host.postMessage('did-set-content', undefined); }); // Forward message to the embedded iframe host.onMessage('message', (_event, data) => { const pending = getPendingFrame(); if (!pending) { const target = getActiveFrame(); if (target) { target.contentWindow.postMessage(data, '*'); return; } } pendingMessages.push(data); }); host.onMessage('initial-scroll-position', (_event, progress) => { initData.initialScrollProgress = progress; }); host.onMessage('execCommand', (_event, data) => { const target = getActiveFrame(); if (!target) { return; } target.contentDocument.execCommand(data); }); trackFocus({ onFocus: () => host.postMessage('did-focus'), onBlur: () => host.postMessage('did-blur') }); // signal ready host.postMessage('webview-ready', {}); }); } if (typeof module !== 'undefined') { module.exports = createWebviewManager; } else { (/** @type {any} */ (window)).createWebviewManager = createWebviewManager; } }());
src/vs/workbench/contrib/webview/browser/pre/main.js
1
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.0032610511407256126, 0.00024342267715837806, 0.00016081547073554248, 0.00016897745081223547, 0.00041496846824884415 ]
{ "id": 6, "code_window": [ "\t\t// Wait the end of the ctor when all listeners have been hooked up.\n", "\t\tconst element = document.createElement('iframe');\n", "\t\telement.className = `webview ${options.customClasses || ''}`;\n", "\t\telement.sandbox.add('allow-scripts', 'allow-same-origin', 'allow-forms', 'allow-pointer-lock', 'allow-downloads');\n", "\t\telement.style.border = 'none';\n", "\t\telement.style.width = '100%';\n", "\t\telement.style.height = '100%';\n", "\t\treturn element;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\telement.setAttribute('allow', 'clipboard-read; clipboard-write;');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/webviewElement.ts", "type": "add", "edit_start_line_idx": 94 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Registry } from 'vs/platform/registry/common/platform'; import { IQuickAccessRegistry, Extensions, IQuickAccessProvider, QuickAccessRegistry } from 'vs/platform/quickinput/common/quickAccess'; import { IQuickPick, IQuickPickItem, IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { TestServiceAccessor, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices'; import { DisposableStore, toDisposable, IDisposable } from 'vs/base/common/lifecycle'; import { timeout } from 'vs/base/common/async'; import { PickerQuickAccessProvider, FastAndSlowPicks } from 'vs/platform/quickinput/browser/pickerQuickAccess'; suite('QuickAccess', () => { let instantiationService: IInstantiationService; let accessor: TestServiceAccessor; let providerDefaultCalled = false; let providerDefaultCanceled = false; let providerDefaultDisposed = false; let provider1Called = false; let provider1Canceled = false; let provider1Disposed = false; let provider2Called = false; let provider2Canceled = false; let provider2Disposed = false; let provider3Called = false; let provider3Canceled = false; let provider3Disposed = false; class TestProviderDefault implements IQuickAccessProvider { constructor(@IQuickInputService private readonly quickInputService: IQuickInputService, disposables: DisposableStore) { } provide(picker: IQuickPick<IQuickPickItem>, token: CancellationToken): IDisposable { assert.ok(picker); providerDefaultCalled = true; token.onCancellationRequested(() => providerDefaultCanceled = true); // bring up provider #3 setTimeout(() => this.quickInputService.quickAccess.show(providerDescriptor3.prefix)); return toDisposable(() => providerDefaultDisposed = true); } } class TestProvider1 implements IQuickAccessProvider { provide(picker: IQuickPick<IQuickPickItem>, token: CancellationToken): IDisposable { assert.ok(picker); provider1Called = true; token.onCancellationRequested(() => provider1Canceled = true); return toDisposable(() => provider1Disposed = true); } } class TestProvider2 implements IQuickAccessProvider { provide(picker: IQuickPick<IQuickPickItem>, token: CancellationToken): IDisposable { assert.ok(picker); provider2Called = true; token.onCancellationRequested(() => provider2Canceled = true); return toDisposable(() => provider2Disposed = true); } } class TestProvider3 implements IQuickAccessProvider { provide(picker: IQuickPick<IQuickPickItem>, token: CancellationToken): IDisposable { assert.ok(picker); provider3Called = true; token.onCancellationRequested(() => provider3Canceled = true); // hide without picking setTimeout(() => picker.hide()); return toDisposable(() => provider3Disposed = true); } } const providerDescriptorDefault = { ctor: TestProviderDefault, prefix: '', helpEntries: [] }; const providerDescriptor1 = { ctor: TestProvider1, prefix: 'test', helpEntries: [] }; const providerDescriptor2 = { ctor: TestProvider2, prefix: 'test something', helpEntries: [] }; const providerDescriptor3 = { ctor: TestProvider3, prefix: 'changed', helpEntries: [] }; setup(() => { instantiationService = workbenchInstantiationService(); accessor = instantiationService.createInstance(TestServiceAccessor); }); test('registry', () => { const registry = (Registry.as<IQuickAccessRegistry>(Extensions.Quickaccess)); const restore = (registry as QuickAccessRegistry).clear(); assert.ok(!registry.getQuickAccessProvider('test')); const disposables = new DisposableStore(); disposables.add(registry.registerQuickAccessProvider(providerDescriptorDefault)); assert(registry.getQuickAccessProvider('') === providerDescriptorDefault); assert(registry.getQuickAccessProvider('test') === providerDescriptorDefault); const disposable = disposables.add(registry.registerQuickAccessProvider(providerDescriptor1)); assert(registry.getQuickAccessProvider('test') === providerDescriptor1); const providers = registry.getQuickAccessProviders(); assert(providers.some(provider => provider.prefix === 'test')); disposable.dispose(); assert(registry.getQuickAccessProvider('test') === providerDescriptorDefault); disposables.dispose(); assert.ok(!registry.getQuickAccessProvider('test')); restore(); }); test('provider', async () => { const registry = (Registry.as<IQuickAccessRegistry>(Extensions.Quickaccess)); const restore = (registry as QuickAccessRegistry).clear(); const disposables = new DisposableStore(); disposables.add(registry.registerQuickAccessProvider(providerDescriptorDefault)); disposables.add(registry.registerQuickAccessProvider(providerDescriptor1)); disposables.add(registry.registerQuickAccessProvider(providerDescriptor2)); disposables.add(registry.registerQuickAccessProvider(providerDescriptor3)); accessor.quickInputService.quickAccess.show('test'); assert.strictEqual(providerDefaultCalled, false); assert.strictEqual(provider1Called, true); assert.strictEqual(provider2Called, false); assert.strictEqual(provider3Called, false); assert.strictEqual(providerDefaultCanceled, false); assert.strictEqual(provider1Canceled, false); assert.strictEqual(provider2Canceled, false); assert.strictEqual(provider3Canceled, false); assert.strictEqual(providerDefaultDisposed, false); assert.strictEqual(provider1Disposed, false); assert.strictEqual(provider2Disposed, false); assert.strictEqual(provider3Disposed, false); provider1Called = false; accessor.quickInputService.quickAccess.show('test something'); assert.strictEqual(providerDefaultCalled, false); assert.strictEqual(provider1Called, false); assert.strictEqual(provider2Called, true); assert.strictEqual(provider3Called, false); assert.strictEqual(providerDefaultCanceled, false); assert.strictEqual(provider1Canceled, true); assert.strictEqual(provider2Canceled, false); assert.strictEqual(provider3Canceled, false); assert.strictEqual(providerDefaultDisposed, false); assert.strictEqual(provider1Disposed, true); assert.strictEqual(provider2Disposed, false); assert.strictEqual(provider3Disposed, false); provider2Called = false; provider1Canceled = false; provider1Disposed = false; accessor.quickInputService.quickAccess.show('usedefault'); assert.strictEqual(providerDefaultCalled, true); assert.strictEqual(provider1Called, false); assert.strictEqual(provider2Called, false); assert.strictEqual(provider3Called, false); assert.strictEqual(providerDefaultCanceled, false); assert.strictEqual(provider1Canceled, false); assert.strictEqual(provider2Canceled, true); assert.strictEqual(provider3Canceled, false); assert.strictEqual(providerDefaultDisposed, false); assert.strictEqual(provider1Disposed, false); assert.strictEqual(provider2Disposed, true); assert.strictEqual(provider3Disposed, false); await timeout(1); assert.strictEqual(providerDefaultCanceled, true); assert.strictEqual(providerDefaultDisposed, true); assert.strictEqual(provider3Called, true); await timeout(1); assert.strictEqual(provider3Canceled, true); assert.strictEqual(provider3Disposed, true); disposables.dispose(); restore(); }); let fastProviderCalled = false; let slowProviderCalled = false; let fastAndSlowProviderCalled = false; let slowProviderCanceled = false; let fastAndSlowProviderCanceled = false; class FastTestQuickPickProvider extends PickerQuickAccessProvider<IQuickPickItem> { constructor() { super('fast'); } protected getPicks(filter: string, disposables: DisposableStore, token: CancellationToken): Array<IQuickPickItem> { fastProviderCalled = true; return [{ label: 'Fast Pick' }]; } } class SlowTestQuickPickProvider extends PickerQuickAccessProvider<IQuickPickItem> { constructor() { super('slow'); } protected async getPicks(filter: string, disposables: DisposableStore, token: CancellationToken): Promise<Array<IQuickPickItem>> { slowProviderCalled = true; await timeout(1); if (token.isCancellationRequested) { slowProviderCanceled = true; } return [{ label: 'Slow Pick' }]; } } class FastAndSlowTestQuickPickProvider extends PickerQuickAccessProvider<IQuickPickItem> { constructor() { super('bothFastAndSlow'); } protected getPicks(filter: string, disposables: DisposableStore, token: CancellationToken): FastAndSlowPicks<IQuickPickItem> { fastAndSlowProviderCalled = true; return { picks: [{ label: 'Fast Pick' }], additionalPicks: (async () => { await timeout(1); if (token.isCancellationRequested) { fastAndSlowProviderCanceled = true; } return [{ label: 'Slow Pick' }]; })() }; } } const fastProviderDescriptor = { ctor: FastTestQuickPickProvider, prefix: 'fast', helpEntries: [] }; const slowProviderDescriptor = { ctor: SlowTestQuickPickProvider, prefix: 'slow', helpEntries: [] }; const fastAndSlowProviderDescriptor = { ctor: FastAndSlowTestQuickPickProvider, prefix: 'bothFastAndSlow', helpEntries: [] }; test('quick pick access', async () => { const registry = (Registry.as<IQuickAccessRegistry>(Extensions.Quickaccess)); const restore = (registry as QuickAccessRegistry).clear(); const disposables = new DisposableStore(); disposables.add(registry.registerQuickAccessProvider(fastProviderDescriptor)); disposables.add(registry.registerQuickAccessProvider(slowProviderDescriptor)); disposables.add(registry.registerQuickAccessProvider(fastAndSlowProviderDescriptor)); accessor.quickInputService.quickAccess.show('fast'); assert.strictEqual(fastProviderCalled, true); assert.strictEqual(slowProviderCalled, false); assert.strictEqual(fastAndSlowProviderCalled, false); fastProviderCalled = false; accessor.quickInputService.quickAccess.show('slow'); await timeout(2); assert.strictEqual(fastProviderCalled, false); assert.strictEqual(slowProviderCalled, true); assert.strictEqual(slowProviderCanceled, false); assert.strictEqual(fastAndSlowProviderCalled, false); slowProviderCalled = false; accessor.quickInputService.quickAccess.show('bothFastAndSlow'); await timeout(2); assert.strictEqual(fastProviderCalled, false); assert.strictEqual(slowProviderCalled, false); assert.strictEqual(fastAndSlowProviderCalled, true); assert.strictEqual(fastAndSlowProviderCanceled, false); fastAndSlowProviderCalled = false; accessor.quickInputService.quickAccess.show('slow'); accessor.quickInputService.quickAccess.show('bothFastAndSlow'); accessor.quickInputService.quickAccess.show('fast'); assert.strictEqual(fastProviderCalled, true); assert.strictEqual(slowProviderCalled, true); assert.strictEqual(fastAndSlowProviderCalled, true); await timeout(2); assert.strictEqual(slowProviderCanceled, true); assert.strictEqual(fastAndSlowProviderCanceled, true); disposables.dispose(); restore(); }); });
src/vs/workbench/test/browser/quickAccess.test.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017523621500004083, 0.00017082247359212488, 0.00016520197095815092, 0.00017175292305182666, 0.0000029285702112247236 ]
{ "id": 6, "code_window": [ "\t\t// Wait the end of the ctor when all listeners have been hooked up.\n", "\t\tconst element = document.createElement('iframe');\n", "\t\telement.className = `webview ${options.customClasses || ''}`;\n", "\t\telement.sandbox.add('allow-scripts', 'allow-same-origin', 'allow-forms', 'allow-pointer-lock', 'allow-downloads');\n", "\t\telement.style.border = 'none';\n", "\t\telement.style.width = '100%';\n", "\t\telement.style.height = '100%';\n", "\t\treturn element;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\telement.setAttribute('allow', 'clipboard-read; clipboard-write;');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/webviewElement.ts", "type": "add", "edit_start_line_idx": 94 }
[ { "c": "std::tuple_element<0, std::pair<pugi::xml_node, std::map<std::basic_string<char>, pugi::xml_node, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, pugi::xml_node> > > > >::type dnode", "t": "source.cpp", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "std::_Rb_tree_iterator<std::pair<const long, std::pair<pugi::xml_node, std::map<std::basic_string<char>, pugi::xml_node, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, pugi::xml_node> > > > > > dnode_it = dnodes_.find(uid.position)", "t": "source.cpp", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } } ]
extensions/vscode-colorize-tests/test/colorize-results/test-92369_cpp.json
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.0001726327755022794, 0.0001718515413813293, 0.0001706676121102646, 0.00017225426563527435, 8.513131319887179e-7 ]
{ "id": 6, "code_window": [ "\t\t// Wait the end of the ctor when all listeners have been hooked up.\n", "\t\tconst element = document.createElement('iframe');\n", "\t\telement.className = `webview ${options.customClasses || ''}`;\n", "\t\telement.sandbox.add('allow-scripts', 'allow-same-origin', 'allow-forms', 'allow-pointer-lock', 'allow-downloads');\n", "\t\telement.style.border = 'none';\n", "\t\telement.style.width = '100%';\n", "\t\telement.style.height = '100%';\n", "\t\treturn element;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\telement.setAttribute('allow', 'clipboard-read; clipboard-write;');\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/webviewElement.ts", "type": "add", "edit_start_line_idx": 94 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { IUserDataSyncStoreService, IUserDataSyncService, SyncResource, SyncStatus, PREVIEW_DIR_NAME, ISyncData, IResourcePreview } from 'vs/platform/userDataSync/common/userDataSync'; import { UserDataSyncClient, UserDataSyncTestServer } from 'vs/platform/userDataSync/test/common/userDataSyncClient'; import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; import { UserDataSyncService } from 'vs/platform/userDataSync/common/userDataSyncService'; import { IFileService } from 'vs/platform/files/common/files'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { VSBuffer } from 'vs/base/common/buffer'; import { SnippetsSynchroniser } from 'vs/platform/userDataSync/common/snippetsSync'; import { joinPath, dirname } from 'vs/base/common/resources'; import { IStringDictionary } from 'vs/base/common/collections'; import { URI } from 'vs/base/common/uri'; const tsSnippet1 = `{ // Place your snippets for TypeScript here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, Placeholders with the // same ids are connected. "Print to console": { // Example: "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console", } }`; const tsSnippet2 = `{ // Place your snippets for TypeScript here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, Placeholders with the // same ids are connected. "Print to console": { // Example: "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console always", } }`; const htmlSnippet1 = `{ /* // Place your snippets for HTML here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. // Example: "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } */ "Div": { "prefix": "div", "body": [ "<div>", "", "</div>" ], "description": "New div" } }`; const htmlSnippet2 = `{ /* // Place your snippets for HTML here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. // Example: "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } */ "Div": { "prefix": "div", "body": [ "<div>", "", "</div>" ], "description": "New div changed" } }`; const htmlSnippet3 = `{ /* // Place your snippets for HTML here. Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. // Example: "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } */ "Div": { "prefix": "div", "body": [ "<div>", "", "</div>" ], "description": "New div changed again" } }`; const globalSnippet = `{ // Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and // description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope // is left empty or omitted, the snippet gets applied to all languages. The prefix is what is // used to trigger the snippet and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, and {1: label}, { 2: another } for placeholders. // Placeholders with the same ids are connected. // Example: // "Print to console": { // "scope": "javascript,typescript", // "prefix": "log", // "body": [ // "console.log('$1');", // "$2" // ], // "description": "Log output to console" // } }`; suite('SnippetsSync', () => { const disposableStore = new DisposableStore(); const server = new UserDataSyncTestServer(); let testClient: UserDataSyncClient; let client2: UserDataSyncClient; let testObject: SnippetsSynchroniser; setup(async () => { testClient = disposableStore.add(new UserDataSyncClient(server)); await testClient.setUp(true); testObject = (testClient.instantiationService.get(IUserDataSyncService) as UserDataSyncService).getSynchroniser(SyncResource.Snippets) as SnippetsSynchroniser; disposableStore.add(toDisposable(() => testClient.instantiationService.get(IUserDataSyncStoreService).clear())); client2 = disposableStore.add(new UserDataSyncClient(server)); await client2.setUp(true); }); teardown(() => disposableStore.clear()); test('when snippets does not exist', async () => { const fileService = testClient.instantiationService.get(IFileService); const snippetsResource = testClient.instantiationService.get(IEnvironmentService).snippetsHome; assert.deepEqual(await testObject.getLastSyncUserData(), null); let manifest = await testClient.manifest(); server.reset(); await testObject.sync(manifest); assert.deepEqual(server.requests, [ { type: 'GET', url: `${server.url}/v1/resource/${testObject.resource}/latest`, headers: {} }, ]); assert.ok(!await fileService.exists(snippetsResource)); const lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.deepEqual(lastSyncUserData!.ref, remoteUserData.ref); assert.deepEqual(lastSyncUserData!.syncData, remoteUserData.syncData); assert.equal(lastSyncUserData!.syncData, null); manifest = await testClient.manifest(); server.reset(); await testObject.sync(manifest); assert.deepEqual(server.requests, []); manifest = await testClient.manifest(); server.reset(); await testObject.sync(manifest); assert.deepEqual(server.requests, []); }); test('when snippet is created after first sync', async () => { await testObject.sync(await testClient.manifest()); await updateSnippet('html.json', htmlSnippet1, testClient); let lastSyncUserData = await testObject.getLastSyncUserData(); const manifest = await testClient.manifest(); server.reset(); await testObject.sync(manifest); assert.deepEqual(server.requests, [ { type: 'POST', url: `${server.url}/v1/resource/${testObject.resource}`, headers: { 'If-Match': lastSyncUserData?.ref } }, ]); lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.deepEqual(lastSyncUserData!.ref, remoteUserData.ref); assert.deepEqual(lastSyncUserData!.syncData, remoteUserData.syncData); assert.deepEqual(lastSyncUserData!.syncData!.content, JSON.stringify({ 'html.json': htmlSnippet1 })); }); test('first time sync - outgoing to server (no snippets)', async () => { await updateSnippet('html.json', htmlSnippet1, testClient); await updateSnippet('typescript.json', tsSnippet1, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }); }); test('first time sync - incoming from server (no snippets)', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet1); const actual2 = await readSnippet('typescript.json', testClient); assert.equal(actual2, tsSnippet1); }); test('first time sync when snippets exists', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await updateSnippet('typescript.json', tsSnippet1, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet1); const actual2 = await readSnippet('typescript.json', testClient); assert.equal(actual2, tsSnippet1); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }); }); test('first time sync when snippets exists - has conflicts', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.HasConflicts); const environmentService = testClient.instantiationService.get(IEnvironmentService); const local = joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'); assertPreviews(testObject.conflicts, [local]); }); test('first time sync when snippets exists - has conflicts and accept conflicts', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await testObject.sync(await testClient.manifest()); const conflicts = testObject.conflicts; await testObject.accept(conflicts[0].previewResource, htmlSnippet1); await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet1); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet1 }); }); test('first time sync when snippets exists - has multiple conflicts', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.HasConflicts); const environmentService = testClient.instantiationService.get(IEnvironmentService); const local1 = joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'); const local2 = joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'); assertPreviews(testObject.conflicts, [local1, local2]); }); test('first time sync when snippets exists - has multiple conflicts and accept one conflict', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); await testObject.sync(await testClient.manifest()); let conflicts = testObject.conflicts; await testObject.accept(conflicts[0].previewResource, htmlSnippet2); conflicts = testObject.conflicts; assert.equal(testObject.status, SyncStatus.HasConflicts); const environmentService = testClient.instantiationService.get(IEnvironmentService); const local = joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'); assertPreviews(testObject.conflicts, [local]); }); test('first time sync when snippets exists - has multiple conflicts and accept all conflicts', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); await testObject.sync(await testClient.manifest()); const conflicts = testObject.conflicts; await testObject.accept(conflicts[0].previewResource, htmlSnippet2); await testObject.accept(conflicts[1].previewResource, tsSnippet1); await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet2); const actual2 = await readSnippet('typescript.json', testClient); assert.equal(actual2, tsSnippet1); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet2, 'typescript.json': tsSnippet1 }); }); test('sync adding a snippet', async () => { await updateSnippet('html.json', htmlSnippet1, testClient); await testObject.sync(await testClient.manifest()); await updateSnippet('typescript.json', tsSnippet1, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet1); const actual2 = await readSnippet('typescript.json', testClient); assert.equal(actual2, tsSnippet1); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet1, 'typescript.json': tsSnippet1 }); }); test('sync adding a snippet - accept', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet1); const actual2 = await readSnippet('typescript.json', testClient); assert.equal(actual2, tsSnippet1); }); test('sync updating a snippet', async () => { await updateSnippet('html.json', htmlSnippet1, testClient); await testObject.sync(await testClient.manifest()); await updateSnippet('html.json', htmlSnippet2, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet2); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet2 }); }); test('sync updating a snippet - accept', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await updateSnippet('html.json', htmlSnippet2, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet2); }); test('sync updating a snippet - conflict', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await updateSnippet('html.json', htmlSnippet2, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet3, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.HasConflicts); const environmentService = testClient.instantiationService.get(IEnvironmentService); const local = joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'); assertPreviews(testObject.conflicts, [local]); }); test('sync updating a snippet - resolve conflict', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await updateSnippet('html.json', htmlSnippet2, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet3, testClient); await testObject.sync(await testClient.manifest()); await testObject.accept(testObject.conflicts[0].previewResource, htmlSnippet2); await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet2); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet2 }); }); test('sync removing a snippet', async () => { await updateSnippet('html.json', htmlSnippet1, testClient); await updateSnippet('typescript.json', tsSnippet1, testClient); await testObject.sync(await testClient.manifest()); await removeSnippet('html.json', testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('typescript.json', testClient); assert.equal(actual1, tsSnippet1); const actual2 = await readSnippet('html.json', testClient); assert.equal(actual2, null); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'typescript.json': tsSnippet1 }); }); test('sync removing a snippet - accept', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await removeSnippet('html.json', client2); await client2.sync(); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('typescript.json', testClient); assert.equal(actual1, tsSnippet1); const actual2 = await readSnippet('html.json', testClient); assert.equal(actual2, null); }); test('sync removing a snippet locally and updating it remotely', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await updateSnippet('html.json', htmlSnippet2, client2); await client2.sync(); await removeSnippet('html.json', testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('typescript.json', testClient); assert.equal(actual1, tsSnippet1); const actual2 = await readSnippet('html.json', testClient); assert.equal(actual2, htmlSnippet2); }); test('sync removing a snippet - conflict', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await removeSnippet('html.json', client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.HasConflicts); const environmentService = testClient.instantiationService.get(IEnvironmentService); const local = joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'); assertPreviews(testObject.conflicts, [local]); }); test('sync removing a snippet - resolve conflict', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await removeSnippet('html.json', client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await testObject.sync(await testClient.manifest()); await testObject.accept(testObject.conflicts[0].previewResource, htmlSnippet3); await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('typescript.json', testClient); assert.equal(actual1, tsSnippet1); const actual2 = await readSnippet('html.json', testClient); assert.equal(actual2, htmlSnippet3); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'typescript.json': tsSnippet1, 'html.json': htmlSnippet3 }); }); test('sync removing a snippet - resolve conflict by removing', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); await removeSnippet('html.json', client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await testObject.sync(await testClient.manifest()); await testObject.accept(testObject.conflicts[0].previewResource, null); await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('typescript.json', testClient); assert.equal(actual1, tsSnippet1); const actual2 = await readSnippet('html.json', testClient); assert.equal(actual2, null); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'typescript.json': tsSnippet1 }); }); test('sync global and language snippet', async () => { await updateSnippet('global.code-snippets', globalSnippet, client2); await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('html.json', testClient); assert.equal(actual1, htmlSnippet1); const actual2 = await readSnippet('global.code-snippets', testClient); assert.equal(actual2, globalSnippet); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'html.json': htmlSnippet1, 'global.code-snippets': globalSnippet }); }); test('sync should ignore non snippets', async () => { await updateSnippet('global.code-snippets', globalSnippet, client2); await updateSnippet('html.html', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await testObject.sync(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Idle); assert.deepEqual(testObject.conflicts, []); const actual1 = await readSnippet('typescript.json', testClient); assert.equal(actual1, tsSnippet1); const actual2 = await readSnippet('global.code-snippets', testClient); assert.equal(actual2, globalSnippet); const actual3 = await readSnippet('html.html', testClient); assert.equal(actual3, null); const { content } = await testClient.read(testObject.resource); assert.ok(content !== null); const actual = parseSnippets(content!); assert.deepEqual(actual, { 'typescript.json': tsSnippet1, 'global.code-snippets': globalSnippet }); }); test('previews are reset after all conflicts resolved', async () => { await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await testObject.sync(await testClient.manifest()); let conflicts = testObject.conflicts; await testObject.accept(conflicts[0].previewResource, htmlSnippet2); await testObject.apply(false); const fileService = testClient.instantiationService.get(IFileService); assert.ok(!await fileService.exists(dirname(conflicts[0].previewResource))); }); test('merge when there are multiple snippets and only one snippet is merged', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.merge(preview!.resourcePreviews[0].localResource); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); }); test('merge when there are multiple snippets and all snippets are merged', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.merge(preview!.resourcePreviews[0].localResource); preview = await testObject.merge(preview!.resourcePreviews[1].localResource); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); }); test('merge when there are multiple snippets and all snippets are merged and applied', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.merge(preview!.resourcePreviews[0].localResource); preview = await testObject.merge(preview!.resourcePreviews[1].localResource); preview = await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.equal(preview, null); assert.deepEqual(testObject.conflicts, []); }); test('merge when there are multiple snippets and one snippet has no changes and one snippet is merged', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet1, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.merge(preview!.resourcePreviews[0].localResource); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), ]); assert.deepEqual(testObject.conflicts, []); }); test('merge when there are multiple snippets and one snippet has no changes and one snippet is merged and applied', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet1, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.merge(preview!.resourcePreviews[0].localResource); preview = await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.equal(preview, null); assert.deepEqual(testObject.conflicts, []); }); test('merge when there are multiple snippets with conflicts and only one snippet is merged', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.merge(preview!.resourcePreviews[0].previewResource); assert.equal(testObject.status, SyncStatus.HasConflicts); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assertPreviews(testObject.conflicts, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), ]); }); test('merge when there are multiple snippets with conflicts and all snippets are merged', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.merge(preview!.resourcePreviews[0].previewResource); preview = await testObject.merge(preview!.resourcePreviews[1].previewResource); assert.equal(testObject.status, SyncStatus.HasConflicts); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assertPreviews(testObject.conflicts, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); }); test('accept when there are multiple snippets with conflicts and only one snippet is accepted', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.accept(preview!.resourcePreviews[0].previewResource, htmlSnippet2); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); }); test('accept when there are multiple snippets with conflicts and all snippets are accepted', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.accept(preview!.resourcePreviews[0].previewResource, htmlSnippet2); preview = await testObject.accept(preview!.resourcePreviews[1].previewResource, tsSnippet2); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); }); test('accept when there are multiple snippets with conflicts and all snippets are accepted and applied', async () => { const environmentService = testClient.instantiationService.get(IEnvironmentService); await updateSnippet('html.json', htmlSnippet1, client2); await updateSnippet('typescript.json', tsSnippet1, client2); await client2.sync(); await updateSnippet('html.json', htmlSnippet2, testClient); await updateSnippet('typescript.json', tsSnippet2, testClient); let preview = await testObject.preview(await testClient.manifest()); assert.equal(testObject.status, SyncStatus.Syncing); assertPreviews(preview!.resourcePreviews, [ joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'html.json'), joinPath(environmentService.userDataSyncHome, testObject.resource, PREVIEW_DIR_NAME, 'typescript.json'), ]); assert.deepEqual(testObject.conflicts, []); preview = await testObject.accept(preview!.resourcePreviews[0].previewResource, htmlSnippet2); preview = await testObject.accept(preview!.resourcePreviews[1].previewResource, tsSnippet2); preview = await testObject.apply(false); assert.equal(testObject.status, SyncStatus.Idle); assert.equal(preview, null); assert.deepEqual(testObject.conflicts, []); }); function parseSnippets(content: string): IStringDictionary<string> { const syncData: ISyncData = JSON.parse(content); return JSON.parse(syncData.content); } async function updateSnippet(name: string, content: string, client: UserDataSyncClient): Promise<void> { const fileService = client.instantiationService.get(IFileService); const environmentService = client.instantiationService.get(IEnvironmentService); const snippetsResource = joinPath(environmentService.snippetsHome, name); await fileService.writeFile(snippetsResource, VSBuffer.fromString(content)); } async function removeSnippet(name: string, client: UserDataSyncClient): Promise<void> { const fileService = client.instantiationService.get(IFileService); const environmentService = client.instantiationService.get(IEnvironmentService); const snippetsResource = joinPath(environmentService.snippetsHome, name); await fileService.del(snippetsResource); } async function readSnippet(name: string, client: UserDataSyncClient): Promise<string | null> { const fileService = client.instantiationService.get(IFileService); const environmentService = client.instantiationService.get(IEnvironmentService); const snippetsResource = joinPath(environmentService.snippetsHome, name); if (await fileService.exists(snippetsResource)) { const content = await fileService.readFile(snippetsResource); return content.value.toString(); } return null; } function assertPreviews(actual: IResourcePreview[], expected: URI[]) { assert.deepEqual(actual.map(({ previewResource }) => previewResource.toString()), expected.map(uri => uri.toString())); } });
src/vs/platform/userDataSync/test/common/snippetsSync.test.ts
0
https://github.com/microsoft/vscode/commit/608e8791ff194e81a10ac0d963471922ddc9b6e0
[ 0.00017587181355338544, 0.00017289012612309307, 0.00016793592658359557, 0.00017333938740193844, 0.0000017993518213188509 ]
{ "id": 0, "code_window": [ " );\n", " });\n", "\n", " it('can use a url without path and with query params', () => {\n", " expect(constructUrl('http://localhost:9001?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url without path (buth slash) and with query params', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 23 }
import { toId } from '@storybook/csf'; import { constructUrl } from '../url'; jest.mock('@storybook/node-logger'); const id = toId('someKind', 'someStory'); describe('Construct URL for Storyshots', () => { it('can use a url without path and without query params', () => { expect(constructUrl('http://localhost:9001', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory' ); }); it('can use a url without path (but slash) and without query params', () => { expect(constructUrl('http://localhost:9001/', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory' ); }); it('can use a url without path and with query params', () => { expect(constructUrl('http://localhost:9001?hello=world', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url without path (buth slash) and with query params', () => { expect(constructUrl('http://localhost:9001/?hello=world', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with some path and query params', () => { expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual( 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with some path (slash) and query params', () => { expect(constructUrl('http://localhost:9001/nice-path/?hello=world', id)).toEqual( 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with file protocol', () => { expect(constructUrl('file://users/storybook', id)).toEqual( 'file://users/storybook/iframe.html?id=somekind--somestory' ); }); });
addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts
1
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.9887334108352661, 0.17473910748958588, 0.00016897227033041418, 0.013624640181660652, 0.3641608953475952 ]
{ "id": 0, "code_window": [ " );\n", " });\n", "\n", " it('can use a url without path and with query params', () => {\n", " expect(constructUrl('http://localhost:9001?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url without path (buth slash) and with query params', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 23 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Core / Story host styles With Args 1`] = ` <storybook-wrapper> <storybook-button-component _ngcontent-a-c21="" _nghost-a-c22="" ng-reflect-text="Button with custom styles" > <button _ngcontent-a-c22="" > Button with custom styles </button> </storybook-button-component> </storybook-wrapper> `; exports[`Storyshots Core / Story host styles With story template 1`] = ` <storybook-wrapper> <storybook-button-component _ngcontent-a-c19="" _nghost-a-c20="" ng-reflect-text="Button with custom styles" > <button _ngcontent-a-c20="" > Button with custom styles </button> </storybook-button-component> </storybook-wrapper> `;
examples/angular-cli/src/stories/core/styles/__snapshots__/story-styles.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017355490126647055, 0.00017061311518773437, 0.0001653811486903578, 0.00017175819084513932, 0.0000032624918731016805 ]
{ "id": 0, "code_window": [ " );\n", " });\n", "\n", " it('can use a url without path and with query params', () => {\n", " expect(constructUrl('http://localhost:9001?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url without path (buth slash) and with query params', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 23 }
#!/usr/bin/env node process.env.NODE_ENV = process.env.NODE_ENV || 'production'; require('../dist/cjs/server/build');
app/ember/bin/build.js
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00016864969802554697, 0.00016864969802554697, 0.00016864969802554697, 0.00016864969802554697, 0 ]
{ "id": 0, "code_window": [ " );\n", " });\n", "\n", " it('can use a url without path and with query params', () => {\n", " expect(constructUrl('http://localhost:9001?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url without path (buth slash) and with query params', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 23 }
import React from 'react'; import { storiesOf, setAddon } from '@storybook/react'; import { linkTo } from '@storybook/addon-links'; import { Welcome } from '@storybook/react/demo'; // Added deprecated setAddon tests setAddon({ aa() { console.log('aa'); }, }); setAddon({ bb() { console.log('bb'); }, }); storiesOf('Welcome', module) .addParameters({ component: Welcome, }) .aa() .bb() .add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);
examples/cra-react15/src/stories/welcome.stories.js
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017555247177369893, 0.00016885872173588723, 0.000165378165547736, 0.00016564549878239632, 0.000004734461072075646 ]
{ "id": 1, "code_window": [ "\n", " it('can use a url without path (buth slash) and with query params', () => {\n", " expect(constructUrl('http://localhost:9001/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 29 }
import { toId } from '@storybook/csf'; import { constructUrl } from '../url'; jest.mock('@storybook/node-logger'); const id = toId('someKind', 'someStory'); describe('Construct URL for Storyshots', () => { it('can use a url without path and without query params', () => { expect(constructUrl('http://localhost:9001', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory' ); }); it('can use a url without path (but slash) and without query params', () => { expect(constructUrl('http://localhost:9001/', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory' ); }); it('can use a url without path and with query params', () => { expect(constructUrl('http://localhost:9001?hello=world', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url without path (buth slash) and with query params', () => { expect(constructUrl('http://localhost:9001/?hello=world', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with some path and query params', () => { expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual( 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with some path (slash) and query params', () => { expect(constructUrl('http://localhost:9001/nice-path/?hello=world', id)).toEqual( 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with file protocol', () => { expect(constructUrl('file://users/storybook', id)).toEqual( 'file://users/storybook/iframe.html?id=somekind--somestory' ); }); });
addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts
1
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.8548471927642822, 0.2780834138393402, 0.00017255281272809952, 0.013696040026843548, 0.38342034816741943 ]
{ "id": 1, "code_window": [ "\n", " it('can use a url without path (buth slash) and with query params', () => {\n", " expect(constructUrl('http://localhost:9001/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 29 }
/* eslint-disable no-param-reassign */ import { Type } from '@angular/core'; import { DecoratorFunction, StoryContext } from '@storybook/addons'; import { computesTemplateFromComponent } from './angular-beta/ComputesTemplateFromComponent'; import { isComponent } from './angular-beta/utils/NgComponentAnalyzer'; import { ICollection, NgModuleMetadata, StoryFnAngularReturnType } from './types'; export const moduleMetadata = ( metadata: Partial<NgModuleMetadata> ): DecoratorFunction<StoryFnAngularReturnType> => (storyFn) => { const story = storyFn(); const storyMetadata = story.moduleMetadata || {}; metadata = metadata || {}; return { ...story, moduleMetadata: { declarations: [...(metadata.declarations || []), ...(storyMetadata.declarations || [])], entryComponents: [ ...(metadata.entryComponents || []), ...(storyMetadata.entryComponents || []), ], imports: [...(metadata.imports || []), ...(storyMetadata.imports || [])], schemas: [...(metadata.schemas || []), ...(storyMetadata.schemas || [])], providers: [...(metadata.providers || []), ...(storyMetadata.providers || [])], }, }; }; export const componentWrapperDecorator = ( element: Type<unknown> | ((story: string) => string), props?: ICollection | ((storyContext: StoryContext) => ICollection) ): DecoratorFunction<StoryFnAngularReturnType> => (storyFn, storyContext) => { const story = storyFn(); const currentProps = typeof props === 'function' ? (props(storyContext) as ICollection) : props; const template = isComponent(element) ? computesTemplateFromComponent(element, currentProps ?? {}, story.template) : element(story.template); return { ...story, template, ...(currentProps || story.props ? { props: { ...currentProps, ...story.props, }, } : {}), }; };
app/angular/src/client/preview/decorators.ts
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.0001779157028067857, 0.00017449678853154182, 0.00017073890194296837, 0.00017425185069441795, 0.0000023978843728400534 ]
{ "id": 1, "code_window": [ "\n", " it('can use a url without path (buth slash) and with query params', () => {\n", " expect(constructUrl('http://localhost:9001/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 29 }
import React from 'react'; import { storiesOf } from '@storybook/react'; import { styled } from '@storybook/theming'; import { Spaced } from './Spaced'; const PlaceholderBlock = styled.div(({ color }) => ({ background: color || 'hotpink', padding: 20, })); const PlaceholderInline = styled.span(({ color }) => ({ background: color || 'hotpink', display: 'inline-block', padding: 20, })); storiesOf('Basics/Spaced', module) .add('row', () => ( <div> <PlaceholderBlock color="silver" /> <Spaced row={1}> <PlaceholderBlock /> <PlaceholderBlock /> <PlaceholderBlock /> </Spaced> <PlaceholderBlock color="silver" /> </div> )) .add('row outer', () => ( <div> <PlaceholderBlock color="silver" /> <Spaced row={1} outer> <PlaceholderBlock /> <PlaceholderBlock /> <PlaceholderBlock /> </Spaced> <PlaceholderBlock color="silver" /> </div> )) .add('row multiply', () => ( <div> <PlaceholderBlock color="silver" /> <Spaced row={3} outer={0.5}> <PlaceholderBlock /> <PlaceholderBlock /> <PlaceholderBlock /> </Spaced> <PlaceholderBlock color="silver" /> </div> )) .add('col', () => ( <div> <PlaceholderInline color="silver" /> <Spaced col={1}> <PlaceholderInline /> <PlaceholderInline /> <PlaceholderInline /> </Spaced> <PlaceholderInline color="silver" /> </div> )) .add('col outer', () => ( <div> <PlaceholderInline color="silver" /> <Spaced col={1} outer> <PlaceholderInline /> <PlaceholderInline /> <PlaceholderInline /> </Spaced> <PlaceholderInline color="silver" /> </div> ));
lib/components/src/spaced/Spaced.stories.tsx
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017806896357797086, 0.00017362486687488854, 0.00016877711459528655, 0.00017405487596988678, 0.0000026361981326772366 ]
{ "id": 1, "code_window": [ "\n", " it('can use a url without path (buth slash) and with query params', () => {\n", " expect(constructUrl('http://localhost:9001/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 29 }
import React, { useState } from 'react'; import { NumberControl } from './Number'; export default { title: 'Controls/Number', component: NumberControl, }; export const Basic = () => { const [value, setValue] = useState(10); return ( <> <NumberControl name="number" value={value} onChange={(newVal) => setValue(newVal)} /> <p>{value}</p> </> ); }; export const Undefined = () => { const [value, setValue] = useState(undefined); return ( <> <NumberControl name="number" value={value} onChange={(newVal) => setValue(newVal)} /> <p>{value}</p> </> ); };
lib/components/src/controls/Number.stories.tsx
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017785718955565244, 0.00017484056297689676, 0.0001724794419715181, 0.00017418504285160452, 0.0000022438534870161675 ]
{ "id": 2, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 35 }
import { toId } from '@storybook/csf'; import { constructUrl } from '../url'; jest.mock('@storybook/node-logger'); const id = toId('someKind', 'someStory'); describe('Construct URL for Storyshots', () => { it('can use a url without path and without query params', () => { expect(constructUrl('http://localhost:9001', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory' ); }); it('can use a url without path (but slash) and without query params', () => { expect(constructUrl('http://localhost:9001/', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory' ); }); it('can use a url without path and with query params', () => { expect(constructUrl('http://localhost:9001?hello=world', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url without path (buth slash) and with query params', () => { expect(constructUrl('http://localhost:9001/?hello=world', id)).toEqual( 'http://localhost:9001/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with some path and query params', () => { expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual( 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with some path (slash) and query params', () => { expect(constructUrl('http://localhost:9001/nice-path/?hello=world', id)).toEqual( 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world' ); }); it('can use a url with file protocol', () => { expect(constructUrl('file://users/storybook', id)).toEqual( 'file://users/storybook/iframe.html?id=somekind--somestory' ); }); });
addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts
1
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.9955506324768066, 0.2119283527135849, 0.00017428456339985132, 0.022296443581581116, 0.35950955748558044 ]
{ "id": 2, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 35 }
# Standalone Preview This project demonstrates a preview running in standalone mode using `parcel`. To run the standalone preview: ``` yarn storybook ``` This starts a `parcel` dev server on port `1337`. To view the stories in the storybook UI: ``` cd ../official-storybook npm storybook -- --preview-url=http://localhost:1337/iframe.html # or yarn ``` This runs the Storybook dev server, but instead of showing `official-storybook`'s stories, it attaches to the `parcel` dev server, lists its stories in the navigation, and shows its stories in the preview iframe. > NOTE: This can be run from any working storybook, not just `official-storybook`!
examples/standalone-preview/README.md
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017107265011873096, 0.00016818998847156763, 0.00016512651927769184, 0.00016837076691444963, 0.0000024308615138579626 ]
{ "id": 2, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 35 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Legacy / Story with storiesOf() with some emoji 1`] = ` <storybook-wrapper> <storybook-button-component _nghost-a-c1="" ng-reflect-text="😀 😎 👍 💯" > <button _ngcontent-a-c1="" > 😀 😎 👍 💯 </button> </storybook-button-component><storybook-button-component _nghost-a-c1="" ng-reflect-text="😀 😎 👍 💯" > <button _ngcontent-a-c1="" > 😀 😎 👍 💯 </button> </storybook-button-component> </storybook-wrapper> `; exports[`Storyshots Legacy / Story with storiesOf() with text 1`] = ` <storybook-wrapper> <storybook-button-component _nghost-a-c0="" ng-reflect-text="Hello Button" > <button _ngcontent-a-c0="" > Hello Button </button> </storybook-button-component> </storybook-wrapper> `;
examples/angular-cli/src/stories/legacy/__snapshots__/storiesOf.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017705719801597297, 0.00017391024448443204, 0.0001699966669548303, 0.00017416711489204317, 0.0000022801966679253383 ]
{ "id": 2, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 35 }
```md <!-- MyComponent.stories.mdx ---> import { Canvas } from '@storybook/addon-docs/blocks'; <!--- This is your Story template function, shown here in React --> export const Template = (args) => <Badge {...args } />; <Canvas> <Story name="warning" args={{status: 'warning', label: 'Warning'}}> {Template.bind({})} </Story> <Story name="neutral" args={{status: 'neutral', label: 'Neutral' }}> {Template.bind({})} </Story> <Story name="error" args={{status: 'error', label: 'Error' }}> {Template.bind({})} </Story> </Canvas> ```
docs/snippets/common/mdx-canvas-multiple-stories.mdx.mdx
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017700738681014627, 0.00017574899538885802, 0.0001747713249642402, 0.00017546830349601805, 9.34197771584877e-7 ]
{ "id": 3, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path (slash) and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with file protocol', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 41 }
import { URL } from 'url'; export const constructUrl = (storybookUrl: string, id: string) => { const storyUrl = `/iframe.html?id=${id}`; const { protocol, host, pathname, search } = new URL(storybookUrl); const pname = pathname.replace(/\/$/, ''); // removes trailing / const query = search.replace('?', '&'); // convert leading ? to & return `${protocol}//${host}${pname}${storyUrl}${query}`; };
addons/storyshots/storyshots-puppeteer/src/url.ts
1
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.0009273854666389525, 0.0009273854666389525, 0.0009273854666389525, 0.0009273854666389525, 0 ]
{ "id": 3, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path (slash) and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with file protocol', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 41 }
on: label name: Dangerfile JS Label jobs: dangerJS: name: Danger JS runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Danger JS uses: danger/danger-js@main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: args: --dangerfile .ci/danger/dangerfile.ts
.github/workflows/label.yml
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017527365707792342, 0.0001733305398374796, 0.000171387437148951, 0.0001733305398374796, 0.0000019431099644862115 ]
{ "id": 3, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path (slash) and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with file protocol', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 41 }
export const PARAM_KEY = 'events'; export const ADDON_ID = 'storybook/events'; export const PANEL_ID = `${ADDON_ID}/panel`; export const EVENT_PREFIX = `${ADDON_ID}/event`; export const EVENTS = { ADD: 'add', EMIT: 'emit', };
addons/events/src/constants.ts
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.000170136772794649, 0.00017003990069497377, 0.00016994302859529853, 0.00017003990069497377, 9.687209967523813e-8 ]
{ "id": 3, "code_window": [ " );\n", " });\n", "\n", " it('can use a url with some path (slash) and query params', () => {\n", " expect(constructUrl('http://localhost:9001/nice-path/?hello=world', id)).toEqual(\n", " 'http://localhost:9001/nice-path/iframe.html?id=somekind--somestory&hello=world'\n", " );\n", " });\n", "\n", " it('can use a url with file protocol', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'http://localhost:9001/nice-path/iframe.html?hello=world&id=somekind--somestory'\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/__tests__/url.test.ts", "type": "replace", "edit_start_line_idx": 41 }
declare module 'global'; declare module 'markdown-to-jsx'; declare module '*.md'; declare module '@storybook/semver';
lib/components/src/typings.d.ts
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017324902000837028, 0.00017324902000837028, 0.00017324902000837028, 0.00017324902000837028, 0 ]
{ "id": 4, "code_window": [ "import { URL } from 'url';\n", "\n", "export const constructUrl = (storybookUrl: string, id: string) => {\n", " const storyUrl = `/iframe.html?id=${id}`;\n", " const { protocol, host, pathname, search } = new URL(storybookUrl);\n", " const pname = pathname.replace(/\\/$/, ''); // removes trailing /\n", " const query = search.replace('?', '&'); // convert leading ? to &\n", " return `${protocol}//${host}${pname}${storyUrl}${query}`;\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " const url = new URL(storybookUrl);\n", " url.pathname = url.pathname.replace(/\\/$/, '').concat('/iframe.html');\n", " url.searchParams.append('id', id);\n", " return url.toString();\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/url.ts", "type": "replace", "edit_start_line_idx": 3 }
import { URL } from 'url'; export const constructUrl = (storybookUrl: string, id: string) => { const storyUrl = `/iframe.html?id=${id}`; const { protocol, host, pathname, search } = new URL(storybookUrl); const pname = pathname.replace(/\/$/, ''); // removes trailing / const query = search.replace('?', '&'); // convert leading ? to & return `${protocol}//${host}${pname}${storyUrl}${query}`; };
addons/storyshots/storyshots-puppeteer/src/url.ts
1
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.9984704852104187, 0.9984704852104187, 0.9984704852104187, 0.9984704852104187, 0 ]
{ "id": 4, "code_window": [ "import { URL } from 'url';\n", "\n", "export const constructUrl = (storybookUrl: string, id: string) => {\n", " const storyUrl = `/iframe.html?id=${id}`;\n", " const { protocol, host, pathname, search } = new URL(storybookUrl);\n", " const pname = pathname.replace(/\\/$/, ''); // removes trailing /\n", " const query = search.replace('?', '&'); // convert leading ? to &\n", " return `${protocol}//${host}${pname}${storyUrl}${query}`;\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " const url = new URL(storybookUrl);\n", " url.pathname = url.pathname.replace(/\\/$/, '').concat('/iframe.html');\n", " url.searchParams.append('id', id);\n", " return url.toString();\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/url.ts", "type": "replace", "edit_start_line_idx": 3 }
function config(entry = [], { addDecorator = true } = {}) { const queryParamsConfig = []; if (addDecorator) { queryParamsConfig.push(require.resolve('./dist/esm/preset/addDecorator')); } return [...entry, ...queryParamsConfig]; } module.exports = { config };
addons/queryparams/preset.js
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017577742983121425, 0.00017577742983121425, 0.00017577742983121425, 0.00017577742983121425, 0 ]
{ "id": 4, "code_window": [ "import { URL } from 'url';\n", "\n", "export const constructUrl = (storybookUrl: string, id: string) => {\n", " const storyUrl = `/iframe.html?id=${id}`;\n", " const { protocol, host, pathname, search } = new URL(storybookUrl);\n", " const pname = pathname.replace(/\\/$/, ''); // removes trailing /\n", " const query = search.replace('?', '&'); // convert leading ? to &\n", " return `${protocol}//${host}${pname}${storyUrl}${query}`;\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " const url = new URL(storybookUrl);\n", " url.pathname = url.pathname.replace(/\\/$/, '').concat('/iframe.html');\n", " url.searchParams.append('id', id);\n", " return url.toString();\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/url.ts", "type": "replace", "edit_start_line_idx": 3 }
{ "title": "Demo", "stories": [ { "name": "Heading", "parameters": { "server": { "id": "demo/heading" } } }, { "name": "Headings", "parameters": { "server": { "id": "demo/headings" } } }, { "name": "Button", "parameters": { "server": { "id": "demo/button" } } } ] }
examples/server-kitchen-sink/stories/demo.stories.json
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017522551934234798, 0.00017457899230066687, 0.00017349682457279414, 0.0001750146329868585, 7.700361379647802e-7 ]
{ "id": 4, "code_window": [ "import { URL } from 'url';\n", "\n", "export const constructUrl = (storybookUrl: string, id: string) => {\n", " const storyUrl = `/iframe.html?id=${id}`;\n", " const { protocol, host, pathname, search } = new URL(storybookUrl);\n", " const pname = pathname.replace(/\\/$/, ''); // removes trailing /\n", " const query = search.replace('?', '&'); // convert leading ? to &\n", " return `${protocol}//${host}${pname}${storyUrl}${query}`;\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " const url = new URL(storybookUrl);\n", " url.pathname = url.pathname.replace(/\\/$/, '').concat('/iframe.html');\n", " url.searchParams.append('id', id);\n", " return url.toString();\n" ], "file_path": "addons/storyshots/storyshots-puppeteer/src/url.ts", "type": "replace", "edit_start_line_idx": 3 }
import React, { Component } from 'react'; import { styled, keyframes } from '@storybook/theming'; import { eventToShortcut, shortcutToHumanString, shortcutMatchesShortcut, } from '@storybook/api/shortcut'; import { Form, Icons } from '@storybook/components'; import SettingsFooter from './SettingsFooter'; const { Button, Input } = Form; const Header = styled.header(({ theme }) => ({ marginBottom: 20, fontSize: theme.typography.size.m3, fontWeight: theme.typography.weight.black, alignItems: 'center', display: 'flex', })); // Grid export const HeaderItem = styled.div(({ theme }) => ({ fontWeight: theme.typography.weight.bold, })); export const GridHeaderRow = styled.div({ alignSelf: 'flex-end', display: 'grid', margin: '10px 0', gridTemplateColumns: '1fr 1fr 12px', '& > *:last-of-type': { gridColumn: '2 / 2', justifySelf: 'flex-end', gridRow: '1', }, }); export const Row = styled.div(({ theme }) => ({ padding: '6px 0', borderTop: `1px solid ${theme.appBorderColor}`, display: 'grid', gridTemplateColumns: '1fr 1fr 0px', })); export const GridWrapper = styled.div({ display: 'grid', gridTemplateColumns: '1fr', gridAutoRows: 'minmax(auto, auto)', marginBottom: 20, }); // Form export const Description = styled.div({ alignSelf: 'center', }); export type ValidationStates = 'valid' | 'error' | 'warn'; export const TextInput = styled(Input)<{ valid: ValidationStates }>( ({ valid, theme }) => valid === 'error' ? { animation: `${theme.animation.jiggle} 700ms ease-out`, } : {}, { display: 'flex', width: 80, flexDirection: 'column', justifySelf: 'flex-end', paddingLeft: 4, paddingRight: 4, textAlign: 'center', } ); export const Fade = keyframes` 0%,100% { opacity: 0; } 50% { opacity: 1; } `; export const SuccessIcon = styled(Icons)<{ valid: string }>( ({ valid, theme }) => valid === 'valid' ? { color: theme.color.positive, animation: `${Fade} 2s ease forwards`, } : { opacity: 0, }, { alignSelf: 'center', display: 'flex', marginLeft: 10, height: 14, width: 14, } ); const Container = styled.div(({ theme }) => ({ fontSize: theme.typography.size.s2, padding: `3rem 20px`, maxWidth: 600, margin: '0 auto', })); const shortcutLabels = { fullScreen: 'Go full screen', togglePanel: 'Toggle addons', panelPosition: 'Toggle addons orientation', toggleNav: 'Toggle sidebar', toolbar: 'Toggle canvas toolbar', search: 'Focus search', focusNav: 'Focus sidebar', focusIframe: 'Focus canvas', focusPanel: 'Focus addons', prevComponent: 'Previous component', nextComponent: 'Next component', prevStory: 'Previous story', nextStory: 'Next story', shortcutsPage: 'Go to shortcuts page', aboutPage: 'Go to about page', collapseAll: 'Collapse all items on sidebar', expandAll: 'Expand all items on sidebar', }; export type Feature = keyof typeof shortcutLabels; // Shortcuts that cannot be configured const fixedShortcuts = ['escape']; function toShortcutState(shortcutKeys: ShortcutsScreenProps['shortcutKeys']) { return Object.entries(shortcutKeys).reduce( (acc, [feature, shortcut]: [Feature, string]) => fixedShortcuts.includes(feature) ? acc : { ...acc, [feature]: { shortcut, error: false } }, {} as Record<Feature, any> ); } export interface ShortcutsScreenState { activeFeature: Feature; successField: Feature; shortcutKeys: Record<Feature, any>; } export interface ShortcutsScreenProps { shortcutKeys: Record<Feature, any>; setShortcut: Function; restoreDefaultShortcut: Function; restoreAllDefaultShortcuts: Function; } class ShortcutsScreen extends Component<ShortcutsScreenProps, ShortcutsScreenState> { constructor(props: ShortcutsScreenProps) { super(props); this.state = { activeFeature: undefined, successField: undefined, // The initial shortcutKeys that come from props are the defaults/what was saved // As the user interacts with the page, the state stores the temporary, unsaved shortcuts // This object also includes the error attached to each shortcut shortcutKeys: toShortcutState(props.shortcutKeys), }; } onKeyDown = (e: KeyboardEvent) => { const { activeFeature, shortcutKeys } = this.state; if (e.key === 'Backspace') { return this.restoreDefault(); } const shortcut = eventToShortcut(e); // Keypress is not a potential shortcut if (!shortcut) { return false; } // Check we don't match any other shortcuts const error = !!Object.entries(shortcutKeys).find( ([feature, { shortcut: existingShortcut }]) => feature !== activeFeature && existingShortcut && shortcutMatchesShortcut(shortcut, existingShortcut) ); return this.setState({ shortcutKeys: { ...shortcutKeys, [activeFeature]: { shortcut, error } }, }); }; onFocus = (focusedInput: Feature) => () => { const { shortcutKeys } = this.state; this.setState({ activeFeature: focusedInput, shortcutKeys: { ...shortcutKeys, [focusedInput]: { shortcut: null, error: false }, }, }); }; onBlur = async () => { const { shortcutKeys, activeFeature } = this.state; if (shortcutKeys[activeFeature]) { const { shortcut, error } = shortcutKeys[activeFeature]; if (!shortcut || error) { return this.restoreDefault(); } return this.saveShortcut(); } return false; }; saveShortcut = async () => { const { activeFeature, shortcutKeys } = this.state; const { setShortcut } = this.props; await setShortcut(activeFeature, shortcutKeys[activeFeature].shortcut); this.setState({ successField: activeFeature }); }; restoreDefaults = async () => { const { restoreAllDefaultShortcuts } = this.props; const defaultShortcuts = await restoreAllDefaultShortcuts(); return this.setState({ shortcutKeys: toShortcutState(defaultShortcuts) }); }; restoreDefault = async () => { const { activeFeature, shortcutKeys } = this.state; const { restoreDefaultShortcut } = this.props; const defaultShortcut = await restoreDefaultShortcut(activeFeature); return this.setState({ shortcutKeys: { ...shortcutKeys, ...toShortcutState({ [activeFeature]: defaultShortcut } as Record<Feature, any>), }, }); }; displaySuccessMessage = (activeElement: Feature) => { const { successField, shortcutKeys } = this.state; return activeElement === successField && shortcutKeys[activeElement].error === false ? 'valid' : undefined; }; displayError = (activeElement: Feature): ValidationStates => { const { activeFeature, shortcutKeys } = this.state; return activeElement === activeFeature && shortcutKeys[activeElement].error === true ? 'error' : undefined; }; renderKeyInput = () => { const { shortcutKeys } = this.state; const arr = Object.entries(shortcutKeys).map(([feature, { shortcut }]: [Feature, any]) => ( <Row key={feature}> <Description>{shortcutLabels[feature]}</Description> <TextInput spellCheck="false" valid={this.displayError(feature)} className="modalInput" onBlur={this.onBlur} onFocus={this.onFocus(feature)} // @ts-ignore onKeyDown={this.onKeyDown} value={shortcut ? shortcutToHumanString(shortcut) : ''} placeholder="Type keys" readOnly /> <SuccessIcon valid={this.displaySuccessMessage(feature)} icon="check" /> </Row> )); return arr; }; renderKeyForm = () => ( <GridWrapper> <GridHeaderRow> <HeaderItem>Commands</HeaderItem> <HeaderItem>Shortcut</HeaderItem> </GridHeaderRow> {this.renderKeyInput()} </GridWrapper> ); render() { const layout = this.renderKeyForm(); return ( <Container> <Header>Keyboard shortcuts</Header> {layout} <Button tertiary small id="restoreDefaultsHotkeys" onClick={this.restoreDefaults}> Restore defaults </Button> <SettingsFooter /> </Container> ); } } export { ShortcutsScreen };
lib/ui/src/settings/shortcuts.tsx
0
https://github.com/storybookjs/storybook/commit/42f2a48defd7f096e839475aac62617e8eeb47f3
[ 0.00017889555601868778, 0.0001747142378007993, 0.00016657730157021433, 0.00017504981951788068, 0.0000022982965219853213 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "import { connect } from 'react-redux';\n", "import { bindActionCreators } from 'redux';\n", "import { createStructuredSelector } from 'reselect';\n", "import { pluginId } from 'app';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { withRouter } from 'react-router';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 10 }
/* * * ModelPage constants * */ export const ADD_ATTRIBUTE_RELATION_TO_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/ADD_ATTRIBUTE_RELATION_TO_CONTENT_TYPE'; export const ADD_ATTRIBUTE_TO_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/ADD_ATTRIBUTE_TO_CONTENT_TYPE'; export const EDIT_CONTENT_TYPE_ATTRIBUTE = 'ContentTypeBuilder/ModelPage/EDIT_CONTENT_TYPE_ATTRIBUTE'; export const EDIT_CONTENT_TYPE_ATTRIBUTE_RELATION = 'ContentTypeBuilder/ModelPage/EDIT_CONTENT_TYPE_ATTRIBUTE_RELATION'; export const CANCEL_CHANGES = 'ContentTypeBuilder/ModelPage/CANCEL_CHANGES'; export const DEFAULT_ACTION = 'ContentTypeBuilder/ModelPage/DEFAULT_ACTION'; export const DELETE_ATTRIBUTE = 'ContentTypeBuilder/ModelPage/DELETE_ATTRIBUTE'; export const MODEL_FETCH = 'ContentTypeBuilder/ModelPage/MODEL_FETCH'; export const MODEL_FETCH_SUCCEEDED = 'ContentTypeBuilder/ModelPage/MODEL_FETCH_SUCCEEDED'; export const POST_CONTENT_TYPE_SUCCEEDED = 'ContentTypeBuilder/ModelPage/POST_CONTENT_TYPE_SUCCEEDED'; export const SET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/SET_BUTTON_LOADER'; export const SUBMIT = 'ContentTypeBuilder/ModelPage/SUBMIT'; export const UPDATE_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/UPDATE_CONTENT_TYPE'; export const UNSET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/UNSET_BUTTON_LOADER'; export const RESET_SHOW_BUTTONS_PROPS = 'ContentTypeBuilder/ModelPage/RESET_SHOW_BUTTONS_PROPS';
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/constants.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0011680551106110215, 0.0005189861403778195, 0.0001718441490083933, 0.00021705917606595904, 0.0004593321355059743 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "import { connect } from 'react-redux';\n", "import { bindActionCreators } from 'redux';\n", "import { createStructuredSelector } from 'reselect';\n", "import { pluginId } from 'app';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { withRouter } from 'react-router';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 10 }
// import PluginLeftMenuSection from '../index'; import expect from 'expect'; // import { shallow } from 'enzyme'; // import React from 'react'; describe('<PluginLeftMenuSection />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
packages/strapi-plugin-settings-manager/admin/src/components/PluginLeftMenuSection/tests/index.test.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017452187603339553, 0.00017434757319279015, 0.00017417327035218477, 0.00017434757319279015, 1.7430284060537815e-7 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "import { connect } from 'react-redux';\n", "import { bindActionCreators } from 'redux';\n", "import { createStructuredSelector } from 'reselect';\n", "import { pluginId } from 'app';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { withRouter } from 'react-router';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 10 }
############################ # OS X ############################ .DS_Store .AppleDouble .LSOverride Icon .Spotlight-V100 .Trashes ._* ############################ # Linux ############################ *~ ############################ # Windows ############################ Thumbs.db ehthumbs.db Desktop.ini $RECYCLE.BIN/ *.cab *.msi *.msm *.msp ############################ # Packages ############################ *.7z *.csv *.dat *.dmg *.gz *.iso *.jar *.rar *.tar *.zip *.com *.class *.dll *.exe *.o *.seed *.so *.swo *.swp *.swn *.swm *.out *.pid ############################ # Logs and databases ############################ *.log *.sql *.sqlite ############################ # Misc. ############################ *# ssl .idea nbproject ############################ # Node.js ############################ lib-cov lcov.info pids logs results build node_modules .node_history ############################ # Tests ############################ test testApp coverage
packages/strapi-generate-policy/.npmignore
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017332303104922175, 0.0001699612766969949, 0.00016643473645672202, 0.00016979806241579354, 0.0000017627198758418672 ]
{ "id": 0, "code_window": [ "import React from 'react';\n", "import { connect } from 'react-redux';\n", "import { bindActionCreators } from 'redux';\n", "import { createStructuredSelector } from 'reselect';\n", "import { pluginId } from 'app';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { withRouter } from 'react-router';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 10 }
.jumbotron { padding: $jumbotron-padding ($jumbotron-padding / 2); margin-bottom: $jumbotron-padding; background-color: $jumbotron-bg; @include border-radius($border-radius-lg); @include media-breakpoint-up(sm) { padding: ($jumbotron-padding * 2) $jumbotron-padding; } } .jumbotron-hr { border-top-color: darken($jumbotron-bg, 10%); } .jumbotron-fluid { padding-right: 0; padding-left: 0; @include border-radius(0); }
packages/strapi-admin/files/public/app/styles/libs/bootstrap/_jumbotron.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001761196763254702, 0.00017533631762489676, 0.00017446129641029984, 0.00017542798013892025, 6.801262202316138e-7 ]
{ "id": 1, "code_window": [ "\n", "import styles from './styles.scss';\n", "import { modelsFetch } from './actions';\n", "import { makeSelectMenu } from './selectors';\n", "\n", "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "/* eslint-disable consistent-return */\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 21 }
import { LOCATION_CHANGE } from 'react-router-redux'; import { forEach, get, includes, map, replace, set, size, unset } from 'lodash'; import { takeLatest } from 'redux-saga'; import { call, take, put, fork, cancel, select } from 'redux-saga/effects'; import request from 'utils/request'; import { temporaryContentTypePosted } from 'containers/App/actions'; import { storeData } from '../../utils/storeData'; import { MODEL_FETCH, SUBMIT } from './constants'; import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions'; import { makeSelectModel } from './selectors'; export function* fetchModel(action) { try { const requestUrl = `/content-type-builder/models/${action.modelName}`; const data = yield call(request, requestUrl, { method: 'GET' }); yield put(modelFetchSucceeded(data)); yield put(unsetButtonLoader()); } catch(error) { window.Strapi.notification.error('An error occured'); } } export function* submitChanges() { try { // Show button loader yield put(setButtonLoader()); const modelName = get(storeData.getContentType(), 'name'); const body = yield select(makeSelectModel()); map(body.attributes, (attribute, index) => { // Remove the connection key from attributes if (attribute.connection) { unset(body.attributes[index], 'connection'); } forEach(attribute.params, (value, key) => { if (includes(key, 'Value')) { // Remove and set needed keys for params set(body.attributes[index].params, replace(key, 'Value', ''), value); unset(body.attributes[index].params, key); } if (!value) { unset(body.attributes[index].params, key); } }); }); const method = modelName === body.name ? 'POST' : 'PUT'; const baseUrl = '/content-type-builder/models/'; const requestUrl = method === 'POST' ? baseUrl : `${baseUrl}${body.name}`; const opts = { method, body }; yield call(request, requestUrl, opts); if (method === 'POST') { storeData.clearAppStorage(); yield put(temporaryContentTypePosted(size(get(body, 'attributes')))); yield put(postContentTypeSucceeded()); } yield new Promise(resolve => { setTimeout(() => { resolve(); }, 5000); }); yield put(resetShowButtonsProps()); // Remove loader yield put(unsetButtonLoader()); } catch(error) { console.log(error); } } export function* defaultSaga() { const loadModelWatcher = yield fork(takeLatest, MODEL_FETCH, fetchModel); // const deleteAttributeWatcher = yield fork(takeLatest, DELETE_ATTRIBUTE, attributeDelete); const loadSubmitChanges = yield fork(takeLatest, SUBMIT, submitChanges); yield take(LOCATION_CHANGE); yield cancel(loadModelWatcher); // yield cancel(deleteAttributeWatcher); yield cancel(loadSubmitChanges); } // All sagas to be loaded export default [ defaultSaga, ];
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00020332788699306548, 0.0001740796578815207, 0.00016505096573382616, 0.0001702584995655343, 0.00001017732938635163 ]
{ "id": 1, "code_window": [ "\n", "import styles from './styles.scss';\n", "import { modelsFetch } from './actions';\n", "import { makeSelectMenu } from './selectors';\n", "\n", "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "/* eslint-disable consistent-return */\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 21 }
{ "myCustomConfiguration": "This configuration is accessible through strapi.config.myCustomConfiguration" }
packages/strapi-generate-new/files/config/custom.json
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001728490460664034, 0.0001728490460664034, 0.0001728490460664034, 0.0001728490460664034, 0 ]
{ "id": 1, "code_window": [ "\n", "import styles from './styles.scss';\n", "import { modelsFetch } from './actions';\n", "import { makeSelectMenu } from './selectors';\n", "\n", "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "/* eslint-disable consistent-return */\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 21 }
.button { height: 3rem; position: relative; border-radius: 0.3rem; text-transform: capitalize; margin-right: 1.8rem; cursor: pointer; font-family: Lato; &:focus { outline: 0; } > i { margin-right: 1.3rem; } &:hover { &::after { position: absolute; width: 100%; height: 100%; top: 0; left: 0; border-radius: 0.3rem; content: ''; opacity: 0.1; background: #FFFFFF; } } } .buttonLg { width: 15rem; } .buttonMd { width: 10rem; } .primary { font-weight: 500; background: linear-gradient(315deg, #0097F6 0%, #005EEA 100%); -webkit-font-smoothing: antialiased; color: white; &:active { box-shadow: inset 1px 1px 3px rgba(0,0,0,.15); } } .secondary { // height: 32px !important; color: #F64D0A; border: 0.1rem solid #F64D0A; position: relative; border-radius: 3px; overflow: hidden; &:active { border: 0.15rem solid #F64D0A; } } .secondaryAddType { height: 2.6rem; color: #1C5DE7; line-height: 1.6rem; border: 0.1rem solid #1C5DE7; font-weight: 500; font-size: 1.3rem; padding-left: 1.6rem; padding-right: 1.6rem; }
packages/strapi-plugin-settings-manager/admin/src/components/Button/styles.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001762646425049752, 0.0001748269860399887, 0.00017370688146911561, 0.00017436851339880377, 8.773075705903466e-7 ]
{ "id": 1, "code_window": [ "\n", "import styles from './styles.scss';\n", "import { modelsFetch } from './actions';\n", "import { makeSelectMenu } from './selectors';\n", "\n", "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "/* eslint-disable consistent-return */\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 21 }
packages/strapi-plugin-settings-manager/admin/src/components/PluginLeftMenuLink/config.json
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001762633037287742, 0.0001762633037287742, 0.0001762633037287742, 0.0001762633037287742, 0 ]
{ "id": 2, "code_window": [ "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n", " }\n", "\n", " componentWillReceiveProps(nextProps) {\n", " if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.router.setRouteLeaveHook(this.props.route, () => {\n", " if (storeData.getContentType()) {\n", " return 'You have unsaved Content Type, are you sure you wan\\'t to leave?';\n", " }\n", " });\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 24 }
import { LOCATION_CHANGE } from 'react-router-redux'; import { forEach, get, includes, map, replace, set, size, unset } from 'lodash'; import { takeLatest } from 'redux-saga'; import { call, take, put, fork, cancel, select } from 'redux-saga/effects'; import request from 'utils/request'; import { temporaryContentTypePosted } from 'containers/App/actions'; import { storeData } from '../../utils/storeData'; import { MODEL_FETCH, SUBMIT } from './constants'; import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions'; import { makeSelectModel } from './selectors'; export function* fetchModel(action) { try { const requestUrl = `/content-type-builder/models/${action.modelName}`; const data = yield call(request, requestUrl, { method: 'GET' }); yield put(modelFetchSucceeded(data)); yield put(unsetButtonLoader()); } catch(error) { window.Strapi.notification.error('An error occured'); } } export function* submitChanges() { try { // Show button loader yield put(setButtonLoader()); const modelName = get(storeData.getContentType(), 'name'); const body = yield select(makeSelectModel()); map(body.attributes, (attribute, index) => { // Remove the connection key from attributes if (attribute.connection) { unset(body.attributes[index], 'connection'); } forEach(attribute.params, (value, key) => { if (includes(key, 'Value')) { // Remove and set needed keys for params set(body.attributes[index].params, replace(key, 'Value', ''), value); unset(body.attributes[index].params, key); } if (!value) { unset(body.attributes[index].params, key); } }); }); const method = modelName === body.name ? 'POST' : 'PUT'; const baseUrl = '/content-type-builder/models/'; const requestUrl = method === 'POST' ? baseUrl : `${baseUrl}${body.name}`; const opts = { method, body }; yield call(request, requestUrl, opts); if (method === 'POST') { storeData.clearAppStorage(); yield put(temporaryContentTypePosted(size(get(body, 'attributes')))); yield put(postContentTypeSucceeded()); } yield new Promise(resolve => { setTimeout(() => { resolve(); }, 5000); }); yield put(resetShowButtonsProps()); // Remove loader yield put(unsetButtonLoader()); } catch(error) { console.log(error); } } export function* defaultSaga() { const loadModelWatcher = yield fork(takeLatest, MODEL_FETCH, fetchModel); // const deleteAttributeWatcher = yield fork(takeLatest, DELETE_ATTRIBUTE, attributeDelete); const loadSubmitChanges = yield fork(takeLatest, SUBMIT, submitChanges); yield take(LOCATION_CHANGE); yield cancel(loadModelWatcher); // yield cancel(deleteAttributeWatcher); yield cancel(loadSubmitChanges); } // All sagas to be loaded export default [ defaultSaga, ];
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017754339205566794, 0.00017148569168057293, 0.0001672151411185041, 0.00017190331709571183, 0.0000026015698040282587 ]
{ "id": 2, "code_window": [ "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n", " }\n", "\n", " componentWillReceiveProps(nextProps) {\n", " if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.router.setRouteLeaveHook(this.props.route, () => {\n", " if (storeData.getContentType()) {\n", " return 'You have unsaved Content Type, are you sure you wan\\'t to leave?';\n", " }\n", " });\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 24 }
// Bootstrap Grid only // // Includes relevant variables and mixins for the flexbox grid // system, as well as the generated predefined classes (e.g., `.col-sm-4`). // // Box sizing, responsive, and more // @at-root { @-ms-viewport { width: device-width; } } html { box-sizing: border-box; -ms-overflow-style: scrollbar; } *, *::before, *::after { box-sizing: inherit; } // // Variables // @import "variables"; // // Grid mixins // @import "mixins/clearfix"; @import "mixins/breakpoints"; @import "mixins/grid-framework"; @import "mixins/grid"; @import "custom"; @import "grid";
packages/strapi-admin/files/public/app/styles/libs/bootstrap/bootstrap-grid.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017738027963787317, 0.00017249587108381093, 0.00016507788677699864, 0.0001745278568705544, 0.000004687793079938274 ]
{ "id": 2, "code_window": [ "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n", " }\n", "\n", " componentWillReceiveProps(nextProps) {\n", " if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.router.setRouteLeaveHook(this.props.route, () => {\n", " if (storeData.getContentType()) {\n", " return 'You have unsaved Content Type, are you sure you wan\\'t to leave?';\n", " }\n", " });\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 24 }
{ "connection": "<%= connection %>", "collectionName": "<%= collectionName || idPluralized %>", "info": { "name": "<%= id %>", "description": "<%= description %>" }, "attributes": { <%= attributes %> } }
packages/strapi-generate-api/templates/mongoose/model.settings.template
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017755627050064504, 0.00017636617121752352, 0.000175176071934402, 0.00017636617121752352, 0.0000011900992831215262 ]
{ "id": 2, "code_window": [ "class App extends React.Component {\n", " componentDidMount() {\n", " this.props.modelsFetch();\n", " }\n", "\n", " componentWillReceiveProps(nextProps) {\n", " if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) {\n", " this.props.modelsFetch();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.router.setRouteLeaveHook(this.props.route, () => {\n", " if (storeData.getContentType()) {\n", " return 'You have unsaved Content Type, are you sure you wan\\'t to leave?';\n", " }\n", " });\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 24 }
Copyright (c) 2015-2017 Strapi Solutions. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
packages/strapi-redis/LICENSE.md
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001730276271700859, 0.0001730276271700859, 0.0001730276271700859, 0.0001730276271700859, 0 ]
{ "id": 3, "code_window": [ " children: React.PropTypes.node,\n", " exposedComponents: React.PropTypes.object.isRequired,\n", " menu: React.PropTypes.array,\n", " modelsFetch: React.PropTypes.func,\n", " shouldRefetchContentType: React.PropTypes.bool,\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " route: React.PropTypes.object,\n", " router: React.PropTypes.object,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 64 }
/* * * ModelPage constants * */ export const ADD_ATTRIBUTE_RELATION_TO_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/ADD_ATTRIBUTE_RELATION_TO_CONTENT_TYPE'; export const ADD_ATTRIBUTE_TO_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/ADD_ATTRIBUTE_TO_CONTENT_TYPE'; export const EDIT_CONTENT_TYPE_ATTRIBUTE = 'ContentTypeBuilder/ModelPage/EDIT_CONTENT_TYPE_ATTRIBUTE'; export const EDIT_CONTENT_TYPE_ATTRIBUTE_RELATION = 'ContentTypeBuilder/ModelPage/EDIT_CONTENT_TYPE_ATTRIBUTE_RELATION'; export const CANCEL_CHANGES = 'ContentTypeBuilder/ModelPage/CANCEL_CHANGES'; export const DEFAULT_ACTION = 'ContentTypeBuilder/ModelPage/DEFAULT_ACTION'; export const DELETE_ATTRIBUTE = 'ContentTypeBuilder/ModelPage/DELETE_ATTRIBUTE'; export const MODEL_FETCH = 'ContentTypeBuilder/ModelPage/MODEL_FETCH'; export const MODEL_FETCH_SUCCEEDED = 'ContentTypeBuilder/ModelPage/MODEL_FETCH_SUCCEEDED'; export const POST_CONTENT_TYPE_SUCCEEDED = 'ContentTypeBuilder/ModelPage/POST_CONTENT_TYPE_SUCCEEDED'; export const SET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/SET_BUTTON_LOADER'; export const SUBMIT = 'ContentTypeBuilder/ModelPage/SUBMIT'; export const UPDATE_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/UPDATE_CONTENT_TYPE'; export const UNSET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/UNSET_BUTTON_LOADER'; export const RESET_SHOW_BUTTONS_PROPS = 'ContentTypeBuilder/ModelPage/RESET_SHOW_BUTTONS_PROPS';
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/constants.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0026306791696697474, 0.0010670843767002225, 0.000232918348046951, 0.00033765542320907116, 0.0011064549908041954 ]
{ "id": 3, "code_window": [ " children: React.PropTypes.node,\n", " exposedComponents: React.PropTypes.object.isRequired,\n", " menu: React.PropTypes.array,\n", " modelsFetch: React.PropTypes.func,\n", " shouldRefetchContentType: React.PropTypes.bool,\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " route: React.PropTypes.object,\n", " router: React.PropTypes.object,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 64 }
// scss-lint:disable QualifyingElement // Make the div behave like a button .btn-group, .btn-group-vertical { position: relative; display: inline-flex; vertical-align: middle; // match .btn alignment given font-size hack above > .btn { position: relative; flex: 0 1 auto; // Bring the hover, focused, and "active" buttons to the fron to overlay // the borders properly @include hover { z-index: 2; } &:focus, &:active, &.active { z-index: 2; } } // Prevent double borders when buttons are next to each other .btn + .btn, .btn + .btn-group, .btn-group + .btn, .btn-group + .btn-group { margin-left: -$input-btn-border-width; } } // Optional: Group multiple button groups together for a toolbar .btn-toolbar { display: flex; justify-content: flex-start; .input-group { width: auto; } } .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; } // Set corners individual because sometimes a single button can be in a .btn-group and we need :first-child and :last-child to both match .btn-group > .btn:first-child { margin-left: 0; &:not(:last-child):not(.dropdown-toggle) { @include border-right-radius(0); } } // Need .dropdown-toggle since :last-child doesn't apply given a .dropdown-menu immediately after it .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { @include border-left-radius(0); } // Custom edits for including btn-groups within btn-groups (useful for including dropdown buttons within a btn-group) .btn-group > .btn-group { float: left; } .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group > .btn-group:first-child:not(:last-child) { > .btn:last-child, > .dropdown-toggle { @include border-right-radius(0); } } .btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { @include border-left-radius(0); } // On active and open, don't show outline .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } // Sizing // // Remix the default button sizing classes into new ones for easier manipulation. .btn-group-sm > .btn { @extend .btn-sm; } .btn-group-lg > .btn { @extend .btn-lg; } // // Split button dropdowns // .btn + .dropdown-toggle-split { padding-right: $btn-padding-x * .75; padding-left: $btn-padding-x * .75; &::after { margin-left: 0; } } .btn-sm + .dropdown-toggle-split { padding-right: $btn-padding-x-sm * .75; padding-left: $btn-padding-x-sm * .75; } .btn-lg + .dropdown-toggle-split { padding-right: $btn-padding-x-lg * .75; padding-left: $btn-padding-x-lg * .75; } // The clickable button for toggling the menu // Remove the gradient and set the same inset shadow as the :active state .btn-group.open .dropdown-toggle { @include box-shadow($btn-active-box-shadow); // Show no shadow for `.btn-link` since it has no other button styles. &.btn-link { @include box-shadow(none); } } // // Vertical button groups // .btn-group-vertical { display: inline-flex; flex-direction: column; align-items: flex-start; justify-content: center; .btn, .btn-group { width: 100%; } > .btn + .btn, > .btn + .btn-group, > .btn-group + .btn, > .btn-group + .btn-group { margin-top: -$input-btn-border-width; margin-left: 0; } } .btn-group-vertical > .btn { &:not(:first-child):not(:last-child) { border-radius: 0; } &:first-child:not(:last-child) { @include border-bottom-radius(0); } &:last-child:not(:first-child) { @include border-top-radius(0); } } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group-vertical > .btn-group:first-child:not(:last-child) { > .btn:last-child, > .dropdown-toggle { @include border-bottom-radius(0); } } .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { @include border-top-radius(0); } // Checkbox and radio options // // In order to support the browser's form validation feedback, powered by the // `required` attribute, we have to "hide" the inputs via `clip`. We cannot use // `display: none;` or `visibility: hidden;` as that also hides the popover. // Simply visually hiding the inputs via `opacity` would leave them clickable in // certain cases which is prevented by using `clip` and `pointer-events`. // This way, we ensure a DOM element is visible to position the popover from. // // See https://github.com/twbs/bootstrap/pull/12794 and // https://github.com/twbs/bootstrap/pull/14559 for more information. [data-toggle="buttons"] { > .btn, > .btn-group > .btn { input[type="radio"], input[type="checkbox"] { position: absolute; clip: rect(0,0,0,0); pointer-events: none; } } }
packages/strapi-admin/files/public/app/styles/libs/bootstrap/_button-group.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017609480710234493, 0.00016978288476821035, 0.0001626873854547739, 0.00016979692736640573, 0.0000034250717817485565 ]
{ "id": 3, "code_window": [ " children: React.PropTypes.node,\n", " exposedComponents: React.PropTypes.object.isRequired,\n", " menu: React.PropTypes.array,\n", " modelsFetch: React.PropTypes.func,\n", " shouldRefetchContentType: React.PropTypes.bool,\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " route: React.PropTypes.object,\n", " router: React.PropTypes.object,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 64 }
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; export default class NotFound extends React.Component { render() { return ( <div> <div className="container"> <h1> <FormattedMessage id="settings-manager.pageNotFound" />. </h1> </div> </div> ); } }
packages/strapi-plugin-settings-manager/admin/src/containers/NotFoundPage/index.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.000171358507941477, 0.00016938547196332365, 0.0001668545592110604, 0.00016994336328934878, 0.000001880570266621362 ]
{ "id": 3, "code_window": [ " children: React.PropTypes.node,\n", " exposedComponents: React.PropTypes.object.isRequired,\n", " menu: React.PropTypes.array,\n", " modelsFetch: React.PropTypes.func,\n", " shouldRefetchContentType: React.PropTypes.bool,\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " route: React.PropTypes.object,\n", " router: React.PropTypes.object,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "add", "edit_start_line_idx": 64 }
const readline = require('readline'); /** * Adds an animated progress indicator * * @param {string} message The message to write next to the indicator */ const animateProgress = (message) => { const amountOfDots = 3; let i = 0; return setInterval(() => { readline.cursorTo(process.stdout, 0); i = (i + 1) % (amountOfDots + 1); const dots = new Array(i + 1).join('.'); process.stdout.write(message + dots); }, 500); } module.exports = animateProgress;
packages/strapi-helper-plugin/lib/internals/scripts/helpers/progress.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001733134558890015, 0.00017302333435509354, 0.0001727332128211856, 0.00017302333435509354, 2.901215339079499e-7 ]
{ "id": 4, "code_window": [ "});\n", "\n", "// Wrap the component to inject dispatch and state into it\n", "export default connect(mapStateToProps, mapDispatchToProps)(App);\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "replace", "edit_start_line_idx": 82 }
import { LOCATION_CHANGE } from 'react-router-redux'; import { forEach, get, includes, map, replace, set, size, unset } from 'lodash'; import { takeLatest } from 'redux-saga'; import { call, take, put, fork, cancel, select } from 'redux-saga/effects'; import request from 'utils/request'; import { temporaryContentTypePosted } from 'containers/App/actions'; import { storeData } from '../../utils/storeData'; import { MODEL_FETCH, SUBMIT } from './constants'; import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions'; import { makeSelectModel } from './selectors'; export function* fetchModel(action) { try { const requestUrl = `/content-type-builder/models/${action.modelName}`; const data = yield call(request, requestUrl, { method: 'GET' }); yield put(modelFetchSucceeded(data)); yield put(unsetButtonLoader()); } catch(error) { window.Strapi.notification.error('An error occured'); } } export function* submitChanges() { try { // Show button loader yield put(setButtonLoader()); const modelName = get(storeData.getContentType(), 'name'); const body = yield select(makeSelectModel()); map(body.attributes, (attribute, index) => { // Remove the connection key from attributes if (attribute.connection) { unset(body.attributes[index], 'connection'); } forEach(attribute.params, (value, key) => { if (includes(key, 'Value')) { // Remove and set needed keys for params set(body.attributes[index].params, replace(key, 'Value', ''), value); unset(body.attributes[index].params, key); } if (!value) { unset(body.attributes[index].params, key); } }); }); const method = modelName === body.name ? 'POST' : 'PUT'; const baseUrl = '/content-type-builder/models/'; const requestUrl = method === 'POST' ? baseUrl : `${baseUrl}${body.name}`; const opts = { method, body }; yield call(request, requestUrl, opts); if (method === 'POST') { storeData.clearAppStorage(); yield put(temporaryContentTypePosted(size(get(body, 'attributes')))); yield put(postContentTypeSucceeded()); } yield new Promise(resolve => { setTimeout(() => { resolve(); }, 5000); }); yield put(resetShowButtonsProps()); // Remove loader yield put(unsetButtonLoader()); } catch(error) { console.log(error); } } export function* defaultSaga() { const loadModelWatcher = yield fork(takeLatest, MODEL_FETCH, fetchModel); // const deleteAttributeWatcher = yield fork(takeLatest, DELETE_ATTRIBUTE, attributeDelete); const loadSubmitChanges = yield fork(takeLatest, SUBMIT, submitChanges); yield take(LOCATION_CHANGE); yield cancel(loadModelWatcher); // yield cancel(deleteAttributeWatcher); yield cancel(loadSubmitChanges); } // All sagas to be loaded export default [ defaultSaga, ];
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00023653644893784076, 0.00017802462389227003, 0.0001672240614425391, 0.00016979887732304633, 0.000019875042198691517 ]
{ "id": 4, "code_window": [ "});\n", "\n", "// Wrap the component to inject dispatch and state into it\n", "export default connect(mapStateToProps, mapDispatchToProps)(App);\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "replace", "edit_start_line_idx": 82 }
# strapi-knex [![npm version](https://img.shields.io/npm/v/strapi-knex.svg)](https://www.npmjs.org/package/strapi-knex) [![npm downloads](https://img.shields.io/npm/dm/strapi-knex.svg)](https://www.npmjs.org/package/strapi-knex) [![npm dependencies](https://david-dm.org/strapi/strapi-knex.svg)](https://david-dm.org/strapi/strapi-knex) [![Build status](https://travis-ci.org/strapi/strapi-knex.svg?branch=master)](https://travis-ci.org/strapi/strapi-knex) [![Slack status](http://strapi-slack.herokuapp.com/badge.svg)](http://slack.strapi.io) This built-in hook allows you to directly make SQL queries from your Strapi connections to your databases thanks to the [Knex node module](http://knexjs.org/). [Knex](http://knexjs.org/) is a "batteries included" SQL query builder for SQLite3, PostgreSQL, MySQL, MariaDB, Microsoft SQL Server and Oracle designed to be flexible, portable, and fun to use. It features both traditional Node.js style callbacks as well as a promise interface for cleaner async flow control, a stream interface, full featured query and schema builders, transaction support (with savepoints), connection pooling and standardized responses between different query clients and dialects. ## Resources - [MIT License](LICENSE.md) ## Links - [Strapi website](http://strapi.io/) - [Strapi community on Slack](http://slack.strapi.io) - [Strapi news on Twitter](https://twitter.com/strapijs)
packages/strapi-knex/README.md
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00016880527255125344, 0.00016600103117525578, 0.0001631734921829775, 0.00016602437244728208, 0.0000022992239792074542 ]
{ "id": 4, "code_window": [ "});\n", "\n", "// Wrap the component to inject dispatch and state into it\n", "export default connect(mapStateToProps, mapDispatchToProps)(App);\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "replace", "edit_start_line_idx": 82 }
<?xml version="1.0" encoding="UTF-8"?> <svg width="647px" height="240px" viewBox="0 0 647 240" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch --> <title>Group</title> <desc>Created with Sketch.</desc> <defs></defs> <g id="Pages" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" opacity="0.5"> <g id="Content-Type-Builder---Content-Type-view" transform="translate(-614.000000, -161.000000)"> <g id="Container"> <g id="Content"> <g id="Empty" transform="translate(614.000000, 149.000000)"> <g id="Background-image"> <g id="Group"> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="91" y="99" width="8" height="8" rx="4"></rect> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="21" y="149" width="4" height="4" rx="2"></rect> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="111" y="249" width="2" height="2" rx="1"></rect> <rect id="Rectangle-9" fill="#F0F0F3" x="0" y="228" width="12" height="12" rx="5"></rect> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="141" y="179" width="10" height="10" rx="5"></rect> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="531" y="189" width="12" height="12" rx="6"></rect> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="641" y="129" width="5" height="5" rx="2.5"></rect> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="441" y="229" width="3" height="3" rx="1.5"></rect> <rect id="Rectangle-9" fill="#F0F0F3" x="520" y="88" width="10" height="10" rx="5"></rect> <rect id="Rectangle-9" stroke="#E3E3E5" stroke-width="2" x="431" y="19" width="4" height="4" rx="2"></rect> <rect id="Rectangle-9" fill="#F0F0F3" x="220" y="208" width="9" height="9" rx="4.5"></rect> <g id="star" transform="translate(557.000000, 0.000000)" fill-rule="nonzero" fill="#E3E3E5"> <path d="M13.0016379,4.80529286 C13.0016379,4.91989063 12.933921,5.04490638 12.7984873,5.18034011 L9.96219251,7.94631356 L10.6341522,11.8530557 C10.6393612,11.8895186 10.6419656,11.9416085 10.6419656,12.0093254 C10.6419656,12.1187142 10.6146185,12.2111737 10.5599241,12.2867041 C10.5052297,12.3622344 10.4257926,12.3999996 10.3216128,12.3999996 C10.222642,12.3999996 10.1184622,12.3687457 10.0090734,12.3062378 L6.50081896,10.4622555 L2.9925645,12.3062378 C2.87796673,12.3687457 2.77378693,12.3999996 2.68002512,12.3999996 C2.57063634,12.3999996 2.48859476,12.3622344 2.43390037,12.2867041 C2.37920598,12.2111737 2.35185878,12.1187142 2.35185878,12.0093254 C2.35185878,11.9780715 2.35706777,11.9259816 2.36748575,11.8530557 L3.0394454,7.94631356 L0.195337108,5.18034011 C0.0651123693,5.03969739 0,4.91468164 0,4.80529286 C0,4.61256024 0.145851707,4.49275348 0.437555122,4.44587258 L4.35992425,3.87548822 L6.11795822,0.320352857 C6.21692903,0.106784286 6.34454927,0 6.50081896,0 C6.65708864,0 6.78470889,0.106784286 6.88367969,0.320352857 L8.64171366,3.87548822 L12.5640828,4.44587258 C12.8557862,4.49275348 13.0016379,4.61256024 13.0016379,4.80529286 Z" id="Shape"></path> </g> <g id="star" transform="translate(407.000000, 153.000000)" fill-rule="nonzero" fill="#E3E3E5"> <path d="M10,3.69591346 C10,3.78405449 9.94791667,3.88020833 9.84375,3.984375 L7.66225962,6.11177885 L8.17908654,9.11658654 C8.18309295,9.14463141 8.18509615,9.18469551 8.18509615,9.23677885 C8.18509615,9.32091346 8.1640625,9.39202724 8.12199519,9.45012019 C8.07992788,9.50821314 8.01883013,9.53725962 7.93870192,9.53725962 C7.86258013,9.53725962 7.78245192,9.51322115 7.69831731,9.46514423 L5,8.046875 L2.30168269,9.46514423 C2.21354167,9.51322115 2.13341346,9.53725962 2.06129808,9.53725962 C1.97716346,9.53725962 1.9140625,9.50821314 1.87199519,9.45012019 C1.82992788,9.39202724 1.80889423,9.32091346 1.80889423,9.23677885 C1.80889423,9.21274038 1.81290064,9.17267628 1.82091346,9.11658654 L2.33774038,6.11177885 L0.150240385,3.984375 C0.0500801282,3.87620192 0,3.78004808 0,3.69591346 C0,3.54767628 0.112179487,3.45552885 0.336538462,3.41947115 L3.35336538,2.98076923 L4.70552885,0.246394231 C4.78165064,0.0821314103 4.87980769,0 5,0 C5.12019231,0 5.21834936,0.0821314103 5.29447115,0.246394231 L6.64663462,2.98076923 L9.66346154,3.41947115 C9.88782051,3.45552885 10,3.54767628 10,3.69591346 Z" id="Shape"></path> </g> <g id="star" transform="translate(167.000000, 33.000000)" fill-rule="nonzero" fill="#E3E3E5"> <path d="M10,3.69591346 C10,3.78405449 9.94791667,3.88020833 9.84375,3.984375 L7.66225962,6.11177885 L8.17908654,9.11658654 C8.18309295,9.14463141 8.18509615,9.18469551 8.18509615,9.23677885 C8.18509615,9.32091346 8.1640625,9.39202724 8.12199519,9.45012019 C8.07992788,9.50821314 8.01883013,9.53725962 7.93870192,9.53725962 C7.86258013,9.53725962 7.78245192,9.51322115 7.69831731,9.46514423 L5,8.046875 L2.30168269,9.46514423 C2.21354167,9.51322115 2.13341346,9.53725962 2.06129808,9.53725962 C1.97716346,9.53725962 1.9140625,9.50821314 1.87199519,9.45012019 C1.82992788,9.39202724 1.80889423,9.32091346 1.80889423,9.23677885 C1.80889423,9.21274038 1.81290064,9.17267628 1.82091346,9.11658654 L2.33774038,6.11177885 L0.150240385,3.984375 C0.0500801282,3.87620192 0,3.78004808 0,3.69591346 C0,3.54767628 0.112179487,3.45552885 0.336538462,3.41947115 L3.35336538,2.98076923 L4.70552885,0.246394231 C4.78165064,0.0821314103 4.87980769,0 5,0 C5.12019231,0 5.21834936,0.0821314103 5.29447115,0.246394231 L6.64663462,2.98076923 L9.66346154,3.41947115 C9.88782051,3.45552885 10,3.54767628 10,3.69591346 Z" id="Shape"></path> </g> </g> </g> </g> </g> </g> </g> </g> </svg>
packages/strapi-plugin-content-type-builder/admin/src/assets/images/background_empty.svg
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0005003967089578509, 0.0002358337806072086, 0.00016489053086843342, 0.00016916329332161695, 0.00013232554192654788 ]
{ "id": 4, "code_window": [ "});\n", "\n", "// Wrap the component to inject dispatch and state into it\n", "export default connect(mapStateToProps, mapDispatchToProps)(App);\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js", "type": "replace", "edit_start_line_idx": 82 }
// Container widths // // Set the container width, and override it for fixed navbars in media queries. @if $enable-grid-classes { .container { @include make-container(); @include make-container-max-widths(); } } // Fluid container // // Utilizes the mixin meant for fixed width containers, but without any defined // width for fluid, full width layouts. @if $enable-grid-classes { .container-fluid { @include make-container(); } } // Row // // Rows contain and clear the floats of your columns. @if $enable-grid-classes { .row { @include make-row(); } // Remove the negative margin from default .row, then the horizontal padding // from all immediate children columns (to prevent runaway style inheritance). .no-gutters { margin-right: 0; margin-left: 0; > .col, > [class*="col-"] { padding-right: 0; padding-left: 0; } } } // Columns // // Common styles for small and large grid columns @if $enable-grid-classes { @include make-grid-columns(); }
packages/strapi-admin/files/public/app/styles/libs/bootstrap/_grid.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017515619401820004, 0.00017101236153393984, 0.0001670613419264555, 0.00017034885240718722, 0.000003011043872902519 ]
{ "id": 5, "code_window": [ " POST_CONTENT_TYPE_SUCCEEDED,\n", " SET_BUTTON_LOADER,\n", " SUBMIT,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 21 }
import { LOCATION_CHANGE } from 'react-router-redux'; import { forEach, get, includes, map, replace, set, size, unset } from 'lodash'; import { takeLatest } from 'redux-saga'; import { call, take, put, fork, cancel, select } from 'redux-saga/effects'; import request from 'utils/request'; import { temporaryContentTypePosted } from 'containers/App/actions'; import { storeData } from '../../utils/storeData'; import { MODEL_FETCH, SUBMIT } from './constants'; import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions'; import { makeSelectModel } from './selectors'; export function* fetchModel(action) { try { const requestUrl = `/content-type-builder/models/${action.modelName}`; const data = yield call(request, requestUrl, { method: 'GET' }); yield put(modelFetchSucceeded(data)); yield put(unsetButtonLoader()); } catch(error) { window.Strapi.notification.error('An error occured'); } } export function* submitChanges() { try { // Show button loader yield put(setButtonLoader()); const modelName = get(storeData.getContentType(), 'name'); const body = yield select(makeSelectModel()); map(body.attributes, (attribute, index) => { // Remove the connection key from attributes if (attribute.connection) { unset(body.attributes[index], 'connection'); } forEach(attribute.params, (value, key) => { if (includes(key, 'Value')) { // Remove and set needed keys for params set(body.attributes[index].params, replace(key, 'Value', ''), value); unset(body.attributes[index].params, key); } if (!value) { unset(body.attributes[index].params, key); } }); }); const method = modelName === body.name ? 'POST' : 'PUT'; const baseUrl = '/content-type-builder/models/'; const requestUrl = method === 'POST' ? baseUrl : `${baseUrl}${body.name}`; const opts = { method, body }; yield call(request, requestUrl, opts); if (method === 'POST') { storeData.clearAppStorage(); yield put(temporaryContentTypePosted(size(get(body, 'attributes')))); yield put(postContentTypeSucceeded()); } yield new Promise(resolve => { setTimeout(() => { resolve(); }, 5000); }); yield put(resetShowButtonsProps()); // Remove loader yield put(unsetButtonLoader()); } catch(error) { console.log(error); } } export function* defaultSaga() { const loadModelWatcher = yield fork(takeLatest, MODEL_FETCH, fetchModel); // const deleteAttributeWatcher = yield fork(takeLatest, DELETE_ATTRIBUTE, attributeDelete); const loadSubmitChanges = yield fork(takeLatest, SUBMIT, submitChanges); yield take(LOCATION_CHANGE); yield cancel(loadModelWatcher); // yield cancel(deleteAttributeWatcher); yield cancel(loadSubmitChanges); } // All sagas to be loaded export default [ defaultSaga, ];
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.914672315120697, 0.09050092846155167, 0.00016560175572521985, 0.00016942787624429911, 0.26159214973449707 ]
{ "id": 5, "code_window": [ " POST_CONTENT_TYPE_SUCCEEDED,\n", " SET_BUTTON_LOADER,\n", " SUBMIT,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 21 }
{ "welcome": "Bienvenue" }
packages/strapi-generate-new/files/config/locales/fr_FR.json
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017164304153993726, 0.00017164304153993726, 0.00017164304153993726, 0.00017164304153993726, 0 ]
{ "id": 5, "code_window": [ " POST_CONTENT_TYPE_SUCCEEDED,\n", " SET_BUTTON_LOADER,\n", " SUBMIT,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 21 }
'use strict'; /** * Module dependencies */ // Native const path = require('path'); // Externals const co = require('co'); const render = require('koa-ejs'); const _ = require('lodash'); /** * EJS hook */ module.exports = function (strapi) { const hook = { /** * Default options */ defaults: { root: path.join(strapi.config.appPath, strapi.config.paths.views), layout: 'layout', viewExt: 'ejs', cache: true, debug: true }, /** * Initialize the hook */ initialize: cb => { // Force cache mode in production if (strapi.config.environment === 'production') { strapi.config.hook.settings.ejs.cache = true; } render(strapi.app, strapi.config.hook.settings.ejs); strapi.app.context.render = co.wrap(strapi.app.context.render); cb(); } }; return hook; };
packages/strapi-ejs/lib/index.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017158004629891366, 0.00017047319852281362, 0.00016751514340285212, 0.00017121217388194054, 0.0000014296135759650497 ]
{ "id": 5, "code_window": [ " POST_CONTENT_TYPE_SUCCEEDED,\n", " SET_BUTTON_LOADER,\n", " SUBMIT,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 21 }
// "string" column named `<%= attribute %>` with optional length defaulting to `255`. table.string('<%= attribute %>', <%= details.length || 255 %>)
packages/strapi-generate-migrations/templates/builder/columns/types/string.template
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001711408403934911, 0.0001711408403934911, 0.0001711408403934911, 0.0001711408403934911, 0 ]
{ "id": 6, "code_window": [ " }\n", "}\n", "\n", "export function unsetButtonLoader() {\n", " return {\n", " type: UNSET_BUTTON_LOADER,\n", " };\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function submitActionSucceeded() {\n", " return {\n", " type: SUBMIT_ACTION_SUCCEEDED,\n", " };\n", "}\n", "\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 147 }
import { LOCATION_CHANGE } from 'react-router-redux'; import { forEach, get, includes, map, replace, set, size, unset } from 'lodash'; import { takeLatest } from 'redux-saga'; import { call, take, put, fork, cancel, select } from 'redux-saga/effects'; import request from 'utils/request'; import { temporaryContentTypePosted } from 'containers/App/actions'; import { storeData } from '../../utils/storeData'; import { MODEL_FETCH, SUBMIT } from './constants'; import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions'; import { makeSelectModel } from './selectors'; export function* fetchModel(action) { try { const requestUrl = `/content-type-builder/models/${action.modelName}`; const data = yield call(request, requestUrl, { method: 'GET' }); yield put(modelFetchSucceeded(data)); yield put(unsetButtonLoader()); } catch(error) { window.Strapi.notification.error('An error occured'); } } export function* submitChanges() { try { // Show button loader yield put(setButtonLoader()); const modelName = get(storeData.getContentType(), 'name'); const body = yield select(makeSelectModel()); map(body.attributes, (attribute, index) => { // Remove the connection key from attributes if (attribute.connection) { unset(body.attributes[index], 'connection'); } forEach(attribute.params, (value, key) => { if (includes(key, 'Value')) { // Remove and set needed keys for params set(body.attributes[index].params, replace(key, 'Value', ''), value); unset(body.attributes[index].params, key); } if (!value) { unset(body.attributes[index].params, key); } }); }); const method = modelName === body.name ? 'POST' : 'PUT'; const baseUrl = '/content-type-builder/models/'; const requestUrl = method === 'POST' ? baseUrl : `${baseUrl}${body.name}`; const opts = { method, body }; yield call(request, requestUrl, opts); if (method === 'POST') { storeData.clearAppStorage(); yield put(temporaryContentTypePosted(size(get(body, 'attributes')))); yield put(postContentTypeSucceeded()); } yield new Promise(resolve => { setTimeout(() => { resolve(); }, 5000); }); yield put(resetShowButtonsProps()); // Remove loader yield put(unsetButtonLoader()); } catch(error) { console.log(error); } } export function* defaultSaga() { const loadModelWatcher = yield fork(takeLatest, MODEL_FETCH, fetchModel); // const deleteAttributeWatcher = yield fork(takeLatest, DELETE_ATTRIBUTE, attributeDelete); const loadSubmitChanges = yield fork(takeLatest, SUBMIT, submitChanges); yield take(LOCATION_CHANGE); yield cancel(loadModelWatcher); // yield cancel(deleteAttributeWatcher); yield cancel(loadSubmitChanges); } // All sagas to be loaded export default [ defaultSaga, ];
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.9992780089378357, 0.3633860647678375, 0.00017053373449016362, 0.00022405847266782075, 0.480425626039505 ]
{ "id": 6, "code_window": [ " }\n", "}\n", "\n", "export function unsetButtonLoader() {\n", " return {\n", " type: UNSET_BUTTON_LOADER,\n", " };\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function submitActionSucceeded() {\n", " return {\n", " type: SUBMIT_ACTION_SUCCEEDED,\n", " };\n", "}\n", "\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 147 }
.popUpForm { /* stylelint-disable */ } .padded { padding: 0 15px 0 15px; } .defaultConnection { position: absolute; bottom: -5.4rem; left: 3rem; display: flex; color: #27B710; cursor: pointer; } .rounded { margin-top: .5rem; margin-left: 1rem; width: 1.2rem; height: 1.2rem; border-radius: 50%; padding-left: .1rem; padding-bottom: .1rem; border: 1px solid #27B710; font-size: .4rem; vertical-align: middle; display: flex; align-items: center; align-content: center; }
packages/strapi-plugin-settings-manager/admin/src/components/PopUpForm/styles.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001746988418744877, 0.0001730056101223454, 0.00017085534636862576, 0.00017323411884717643, 0.0000015970401818776736 ]
{ "id": 6, "code_window": [ " }\n", "}\n", "\n", "export function unsetButtonLoader() {\n", " return {\n", " type: UNSET_BUTTON_LOADER,\n", " };\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function submitActionSucceeded() {\n", " return {\n", " type: SUBMIT_ACTION_SUCCEEDED,\n", " };\n", "}\n", "\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 147 }
'use strict'; /** * Module dependencies */ // Node.js core. const path = require('path'); // Public node modules. const _ = require('lodash'); const fs = require('fs-extra'); // Logger. const logger = require('strapi-utils').logger; /** * This `before` function is run before generating targets. * Validate, configure defaults, get extra dependencies, etc. * * @param {Object} scope * @param {Function} cb */ module.exports = (scope, cb) => { // App info. _.defaults(scope, { name: scope.name === '.' || !scope.name ? scope.name : path.basename(process.cwd()), author: process.env.USER || 'A Strapi developer', email: process.env.EMAIL || '', year: (new Date()).getFullYear(), license: 'MIT' }); // Make changes to the rootPath where the Strapi project will be created. scope.rootPath = path.resolve(process.cwd(), scope.name || ''); // Ensure we aren't going to inadvertently delete any files. try { const files = fs.readdirSync(scope.rootPath); if (files.length) { return logger.error('`$ strapi new` can only be called in an empty directory.'); } } catch (err) { // ... } logger.info('Copying the dashboard...'); // Trigger callback with no error to proceed. return cb.success(); };
packages/strapi-generate-new/lib/before.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017353387374896556, 0.0001698595442576334, 0.00016668217722326517, 0.00016966258408501744, 0.0000024705170744709903 ]
{ "id": 6, "code_window": [ " }\n", "}\n", "\n", "export function unsetButtonLoader() {\n", " return {\n", " type: UNSET_BUTTON_LOADER,\n", " };\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function submitActionSucceeded() {\n", " return {\n", " type: SUBMIT_ACTION_SUCCEEDED,\n", " };\n", "}\n", "\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/actions.js", "type": "add", "edit_start_line_idx": 147 }
@mixin float-left { float: left !important; } @mixin float-right { float: right !important; } @mixin float-none { float: none !important; }
packages/strapi-admin/files/public/app/styles/libs/bootstrap/mixins/_float.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00016845890786498785, 0.00016845890786498785, 0.00016845890786498785, 0.00016845890786498785, 0 ]
{ "id": 7, "code_window": [ "export const POST_CONTENT_TYPE_SUCCEEDED = 'ContentTypeBuilder/ModelPage/POST_CONTENT_TYPE_SUCCEEDED';\n", "export const SET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/SET_BUTTON_LOADER';\n", "export const SUBMIT = 'ContentTypeBuilder/ModelPage/SUBMIT';\n", "export const UPDATE_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/UPDATE_CONTENT_TYPE';\n", "export const UNSET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/UNSET_BUTTON_LOADER';\n", "export const RESET_SHOW_BUTTONS_PROPS = 'ContentTypeBuilder/ModelPage/RESET_SHOW_BUTTONS_PROPS';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const SUBMIT_ACTION_SUCCEEDED = 'ContentTypeBuilder/ModelPage/SUBMIT_ACTION_SUCCEEDED';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/constants.js", "type": "add", "edit_start_line_idx": 18 }
/** * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * */ import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createStructuredSelector } from 'reselect'; import { pluginId } from 'app'; import { makeSelectShouldRefetchContentType } from 'containers/Form/selectors'; import { storeData } from '../../utils/storeData'; import styles from './styles.scss'; import { modelsFetch } from './actions'; import { makeSelectMenu } from './selectors'; class App extends React.Component { componentDidMount() { this.props.modelsFetch(); } componentWillReceiveProps(nextProps) { if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) { this.props.modelsFetch(); } } componentWillUnmount() { // Empty the app localStorage storeData.clearAppStorage(); } render() { // Assign plugin component to children const content = React.Children.map(this.props.children, child => React.cloneElement(child, { exposedComponents: this.props.exposedComponents, menu: this.props.menu, }) ); return ( <div className={`${pluginId} ${styles.app}`}> {React.Children.toArray(content)} </div> ); } } App.contextTypes = { router: React.PropTypes.object.isRequired, }; App.propTypes = { children: React.PropTypes.node, exposedComponents: React.PropTypes.object.isRequired, menu: React.PropTypes.array, modelsFetch: React.PropTypes.func, shouldRefetchContentType: React.PropTypes.bool, }; export function mapDispatchToProps(dispatch) { return bindActionCreators( { modelsFetch, }, dispatch ) } const mapStateToProps = createStructuredSelector({ menu: makeSelectMenu(), shouldRefetchContentType: makeSelectShouldRefetchContentType(), }); // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(App);
packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0008229040540754795, 0.0003681170928757638, 0.00019612057076301426, 0.00030625765793956816, 0.00018927933706436306 ]
{ "id": 7, "code_window": [ "export const POST_CONTENT_TYPE_SUCCEEDED = 'ContentTypeBuilder/ModelPage/POST_CONTENT_TYPE_SUCCEEDED';\n", "export const SET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/SET_BUTTON_LOADER';\n", "export const SUBMIT = 'ContentTypeBuilder/ModelPage/SUBMIT';\n", "export const UPDATE_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/UPDATE_CONTENT_TYPE';\n", "export const UNSET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/UNSET_BUTTON_LOADER';\n", "export const RESET_SHOW_BUTTONS_PROPS = 'ContentTypeBuilder/ModelPage/RESET_SHOW_BUTTONS_PROPS';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const SUBMIT_ACTION_SUCCEEDED = 'ContentTypeBuilder/ModelPage/SUBMIT_ACTION_SUCCEEDED';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/constants.js", "type": "add", "edit_start_line_idx": 18 }
// import RelationNaturePicker from '../index'; import expect from 'expect'; // import { shallow } from 'enzyme'; // import React from 'react'; describe('<RelationNaturePicker />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
packages/strapi-plugin-content-type-builder/admin/src/components/RelationNaturePicker/tests/index.test.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0019338660640642047, 0.001072216429747641, 0.0002105668099829927, 0.001072216429747641, 0.0008616496343165636 ]
{ "id": 7, "code_window": [ "export const POST_CONTENT_TYPE_SUCCEEDED = 'ContentTypeBuilder/ModelPage/POST_CONTENT_TYPE_SUCCEEDED';\n", "export const SET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/SET_BUTTON_LOADER';\n", "export const SUBMIT = 'ContentTypeBuilder/ModelPage/SUBMIT';\n", "export const UPDATE_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/UPDATE_CONTENT_TYPE';\n", "export const UNSET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/UNSET_BUTTON_LOADER';\n", "export const RESET_SHOW_BUTTONS_PROPS = 'ContentTypeBuilder/ModelPage/RESET_SHOW_BUTTONS_PROPS';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const SUBMIT_ACTION_SUCCEEDED = 'ContentTypeBuilder/ModelPage/SUBMIT_ACTION_SUCCEEDED';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/constants.js", "type": "add", "edit_start_line_idx": 18 }
/* * ModelPage Messages * * This contains all the text for the ModelPage component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.containers.ModelPage.header', defaultMessage: 'This is ModelPage container !', }, });
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/messages.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0011472463374957442, 0.0007617004448547959, 0.00037615455221384764, 0.0007617004448547959, 0.0003855458926409483 ]
{ "id": 7, "code_window": [ "export const POST_CONTENT_TYPE_SUCCEEDED = 'ContentTypeBuilder/ModelPage/POST_CONTENT_TYPE_SUCCEEDED';\n", "export const SET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/SET_BUTTON_LOADER';\n", "export const SUBMIT = 'ContentTypeBuilder/ModelPage/SUBMIT';\n", "export const UPDATE_CONTENT_TYPE = 'ContentTypeBuilder/ModelPage/UPDATE_CONTENT_TYPE';\n", "export const UNSET_BUTTON_LOADER = 'ContentTypeBuilder/ModelPage/UNSET_BUTTON_LOADER';\n", "export const RESET_SHOW_BUTTONS_PROPS = 'ContentTypeBuilder/ModelPage/RESET_SHOW_BUTTONS_PROPS';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const SUBMIT_ACTION_SUCCEEDED = 'ContentTypeBuilder/ModelPage/SUBMIT_ACTION_SUCCEEDED';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/constants.js", "type": "add", "edit_start_line_idx": 18 }
// Button variants // // Easily pump out default styles, as well as :hover, :focus, :active, // and disabled options for all buttons @mixin button-variant($color, $background, $border) { $active-background: darken($background, 10%); $active-border: darken($border, 12%); color: $color; background-color: $background; border-color: $border; @include box-shadow($btn-box-shadow); // Hover and focus styles are shared @include hover { color: $color; background-color: $active-background; border-color: $active-border; } &:focus, &.focus { // Avoid using mixin so we can pass custom focus shadow properly @if $enable-shadows { box-shadow: $btn-box-shadow, 0 0 0 2px rgba($border, .5); } @else { box-shadow: 0 0 0 2px rgba($border, .5); } } // Disabled comes first so active can properly restyle &.disabled, &:disabled { background-color: $background; border-color: $border; } &:active, &.active, .show > .dropdown-toggle { color: $color; background-color: $active-background; background-image: none; // Remove the gradient for the pressed/active state border-color: $active-border; @include box-shadow($btn-active-box-shadow); } } @mixin button-outline-variant($color, $color-hover: #fff) { color: $color; background-image: none; background-color: transparent; border-color: $color; @include hover { color: $color-hover; background-color: $color; border-color: $color; } &:focus, &.focus { box-shadow: 0 0 0 2px rgba($color, .5); } &.disabled, &:disabled { color: $color; background-color: transparent; } &:active, &.active, .show > .dropdown-toggle { color: $color-hover; background-color: $color; border-color: $color; } } // Button sizes @mixin button-size($padding-y, $padding-x, $font-size, $border-radius) { padding: $padding-y $padding-x; font-size: $font-size; @include border-radius($border-radius); }
packages/strapi-admin/files/public/app/styles/libs/bootstrap/mixins/_buttons.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0009231722797267139, 0.000656982883810997, 0.00041888750274665654, 0.0006800515111535788, 0.00015789807366672903 ]
{ "id": 8, "code_window": [ " MODEL_FETCH_SUCCEEDED,\n", " POST_CONTENT_TYPE_SUCCEEDED,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " SET_BUTTON_LOADER,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 21 }
/** * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * */ import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createStructuredSelector } from 'reselect'; import { pluginId } from 'app'; import { makeSelectShouldRefetchContentType } from 'containers/Form/selectors'; import { storeData } from '../../utils/storeData'; import styles from './styles.scss'; import { modelsFetch } from './actions'; import { makeSelectMenu } from './selectors'; class App extends React.Component { componentDidMount() { this.props.modelsFetch(); } componentWillReceiveProps(nextProps) { if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) { this.props.modelsFetch(); } } componentWillUnmount() { // Empty the app localStorage storeData.clearAppStorage(); } render() { // Assign plugin component to children const content = React.Children.map(this.props.children, child => React.cloneElement(child, { exposedComponents: this.props.exposedComponents, menu: this.props.menu, }) ); return ( <div className={`${pluginId} ${styles.app}`}> {React.Children.toArray(content)} </div> ); } } App.contextTypes = { router: React.PropTypes.object.isRequired, }; App.propTypes = { children: React.PropTypes.node, exposedComponents: React.PropTypes.object.isRequired, menu: React.PropTypes.array, modelsFetch: React.PropTypes.func, shouldRefetchContentType: React.PropTypes.bool, }; export function mapDispatchToProps(dispatch) { return bindActionCreators( { modelsFetch, }, dispatch ) } const mapStateToProps = createStructuredSelector({ menu: makeSelectMenu(), shouldRefetchContentType: makeSelectShouldRefetchContentType(), }); // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(App);
packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00018790076137520373, 0.00017083350394386798, 0.00016510352725163102, 0.0001693716476438567, 0.000006303016107267467 ]
{ "id": 8, "code_window": [ " MODEL_FETCH_SUCCEEDED,\n", " POST_CONTENT_TYPE_SUCCEEDED,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " SET_BUTTON_LOADER,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 21 }
{ "myCustomConfiguration": "This configuration is accessible through strapi.config.environments.development.myCustomConfiguration" }
packages/strapi-generate-new/files/config/environments/development/custom.json
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00016961748769972473, 0.00016961748769972473, 0.00016961748769972473, 0.00016961748769972473, 0 ]
{ "id": 8, "code_window": [ " MODEL_FETCH_SUCCEEDED,\n", " POST_CONTENT_TYPE_SUCCEEDED,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " SET_BUTTON_LOADER,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 21 }
'use strict'; /** * Module dependencies */ // Node.js core. const path = require('path'); /** * Favicon hook */ module.exports = strapi => { return { /** * Default options */ defaults: { favicon: { path: 'favicon.ico', maxAge: 86400000 } }, /** * Initialize the hook */ initialize: function(cb) { strapi.app.use( strapi.koaMiddlewares.favicon( path.resolve(strapi.config.appPath, strapi.config.middleware.settings.favicon.path), { maxAge: strapi.config.middleware.settings.favicon.maxAge } ) ); cb(); } }; };
packages/strapi/lib/middlewares/favicon/index.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017257846775464714, 0.00016995074111036956, 0.0001667592878220603, 0.00017076299991458654, 0.0000020179650164209306 ]
{ "id": 8, "code_window": [ " MODEL_FETCH_SUCCEEDED,\n", " POST_CONTENT_TYPE_SUCCEEDED,\n", " RESET_SHOW_BUTTONS_PROPS,\n", " SET_BUTTON_LOADER,\n", " UNSET_BUTTON_LOADER,\n", " UPDATE_CONTENT_TYPE,\n", "} from './constants';\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " SUBMIT_ACTION_SUCCEEDED,\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 21 }
$1 '{{language}}',
packages/strapi-helper-plugin/lib/internals/generators/language/app-locale.hbs
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00016977118502836674, 0.00016977118502836674, 0.00016977118502836674, 0.00016977118502836674, 0 ]
{ "id": 9, "code_window": [ " return state.set('showButtons', false);\n", " case SET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', true);\n", " case UNSET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', false);\n", " case UPDATE_CONTENT_TYPE:\n", " return state\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " case SUBMIT_ACTION_SUCCEEDED:\n", " return state.set('initialModel', state.get('model'));\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 114 }
/** * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * */ import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createStructuredSelector } from 'reselect'; import { pluginId } from 'app'; import { makeSelectShouldRefetchContentType } from 'containers/Form/selectors'; import { storeData } from '../../utils/storeData'; import styles from './styles.scss'; import { modelsFetch } from './actions'; import { makeSelectMenu } from './selectors'; class App extends React.Component { componentDidMount() { this.props.modelsFetch(); } componentWillReceiveProps(nextProps) { if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) { this.props.modelsFetch(); } } componentWillUnmount() { // Empty the app localStorage storeData.clearAppStorage(); } render() { // Assign plugin component to children const content = React.Children.map(this.props.children, child => React.cloneElement(child, { exposedComponents: this.props.exposedComponents, menu: this.props.menu, }) ); return ( <div className={`${pluginId} ${styles.app}`}> {React.Children.toArray(content)} </div> ); } } App.contextTypes = { router: React.PropTypes.object.isRequired, }; App.propTypes = { children: React.PropTypes.node, exposedComponents: React.PropTypes.object.isRequired, menu: React.PropTypes.array, modelsFetch: React.PropTypes.func, shouldRefetchContentType: React.PropTypes.bool, }; export function mapDispatchToProps(dispatch) { return bindActionCreators( { modelsFetch, }, dispatch ) } const mapStateToProps = createStructuredSelector({ menu: makeSelectMenu(), shouldRefetchContentType: makeSelectShouldRefetchContentType(), }); // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(App);
packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00018329420709051192, 0.0001706378534436226, 0.00016209433670155704, 0.0001706938201095909, 0.000005880895969312405 ]
{ "id": 9, "code_window": [ " return state.set('showButtons', false);\n", " case SET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', true);\n", " case UNSET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', false);\n", " case UPDATE_CONTENT_TYPE:\n", " return state\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " case SUBMIT_ACTION_SUCCEEDED:\n", " return state.set('initialModel', state.get('model'));\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 114 }
{ "name": "strapi-mongoose", "version": "3.0.0-alpha.5.5", "description": "Mongoose hook for the Strapi framework", "homepage": "http://strapi.io", "keywords": [ "mongoose", "hook", "orm", "nosql", "strapi" ], "directories": { "lib": "./lib" }, "main": "./lib", "dependencies": { "lodash": "^4.17.4", "mongoose": "^4.11.3", "mongoose-double": "0.0.1", "mongoose-float": "^1.0.2", "pluralize": "^6.0.0", "strapi-utils": "3.0.0-alpha.5.5" }, "strapi": { "isHook": true }, "author": { "email": "[email protected]", "name": "Strapi team", "url": "http://strapi.io" }, "maintainers": [ { "name": "Strapi team", "email": "[email protected]", "url": "http://strapi.io" } ], "repository": { "type": "git", "url": "git://github.com/strapi/strapi.git" }, "bugs": { "url": "https://github.com/strapi/strapi/issues" }, "engines": { "node": ">= 8.0.0", "npm": ">= 5.3.0" }, "license": "MIT" }
packages/strapi-mongoose/package.json
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017562713765073568, 0.00017277576262131333, 0.00016918330220505595, 0.00017300805484410375, 0.000002050378043350065 ]
{ "id": 9, "code_window": [ " return state.set('showButtons', false);\n", " case SET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', true);\n", " case UNSET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', false);\n", " case UPDATE_CONTENT_TYPE:\n", " return state\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " case SUBMIT_ACTION_SUCCEEDED:\n", " return state.set('initialModel', state.get('model'));\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 114 }
.tableListContainer { /* stylelint-disable */ padding: 2rem 0 0rem 0; background: #FFFFFF; font-family: Lato; } .headerContainer { width: 100%; padding: 0 1rem 0 3rem; display: flex; flex-direction: row; justify-content: space-between; } .titleContainer { color: #333740; font-size: 1.8rem; font-weight: bold; line-height: 2.2rem; } .ulContainer { margin-top: 1.6rem; width: 100%; > ul { margin: 0; padding: 0; list-style: none; > li:first-child { margin-top: 0rem; border-radius: 2px 2px 0 0; background-color: #F3F3F4; } > li:not(:first-child) { margin-top: 0!important; position: relative; height: 5.4rem; line-height: 5.4rem; cursor: pointer; &:hover { background-color: #F7F8F8; } } > li:nth-child(2) { height: 5.7rem; padding-top: .3rem; } > li:last-child { margin-bottom: 0; .liInnerContainer { border-bottom: none; } } } } .liHeaderContainer { height: 3rem; margin: 0; padding: 0 4.6rem .3rem 1.9rem; font-size: 1.3rem; line-height: 1.6rem; font-weight: 600; > div { padding: 0; align-self: center; } > div:last-child { text-align: right; } } .liInnerContainer { margin: 0 3.2rem 0 1.9rem ; padding: 0 1.4rem 0 0rem; border-bottom: 1px solid rgba(14,22,34,0.04); color: #333740; font-size: 1.3rem; > div { padding: 0; align-self: center; } > div:first-child{ padding-left: 1.4rem; } > div:last-child { text-align: right; } > div:nth-child(2) { font-weight: 600; } } .icContainer { display: flex; justify-content: flex-end; z-index: 9999; opacity: .75; > div { height: 100%; color: #0E1622; > i { z-index: 0; font-size: 1.1rem; } } > div:last-child { margin-left: 1.3rem; } } .italic { > span { font-style: italic; } }
packages/strapi-plugin-content-type-builder/admin/src/components/TableList/styles.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.000178498201421462, 0.0001725279144011438, 0.0001646165328565985, 0.00017398232012055814, 0.000004441405053512426 ]
{ "id": 9, "code_window": [ " return state.set('showButtons', false);\n", " case SET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', true);\n", " case UNSET_BUTTON_LOADER:\n", " return state.set('showButtonLoader', false);\n", " case UPDATE_CONTENT_TYPE:\n", " return state\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " case SUBMIT_ACTION_SUCCEEDED:\n", " return state.set('initialModel', state.get('model'));\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js", "type": "add", "edit_start_line_idx": 114 }
# Strapi built-in admin panel ## Description TODO ## Contribute ### Setup Create a new Strapi project: `strapi new myApp`. Go in your project: `cd myApp`. Remove the generated admin panel: `rm -rf admin`. Create a symlink in order to be able to easily develop the admin panel from your generated Strapi application: `ln -s /usr/local/lib/node_modules/strapi-generate-admin/files/admin admin` (supposing `/usr/local/lib/node_modules` is your global node modules folder). ### Development Start the React application: `cd myApp/admin/public`, then `npm start`. The admin panel should now be available at [http://localhost:4000](http://localhost:4000). ### Build In order to check your updates, you can build the admin panel: `cd myApp/admin/public`, then `npm run build`.
packages/strapi-generate-admin/README.md
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00016883279022295028, 0.00016750070790294558, 0.0001668295735726133, 0.00016683975991327316, 9.419335924576444e-7 ]
{ "id": 10, "code_window": [ "import { temporaryContentTypePosted } from 'containers/App/actions';\n", "\n", "import { storeData } from '../../utils/storeData';\n", "\n", "import { MODEL_FETCH, SUBMIT } from './constants';\n", "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions';\n", "import { makeSelectModel } from './selectors';\n", "\n", "export function* fetchModel(action) {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader, submitActionSucceeded } from './actions';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 12 }
import { LOCATION_CHANGE } from 'react-router-redux'; import { forEach, get, includes, map, replace, set, size, unset } from 'lodash'; import { takeLatest } from 'redux-saga'; import { call, take, put, fork, cancel, select } from 'redux-saga/effects'; import request from 'utils/request'; import { temporaryContentTypePosted } from 'containers/App/actions'; import { storeData } from '../../utils/storeData'; import { MODEL_FETCH, SUBMIT } from './constants'; import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions'; import { makeSelectModel } from './selectors'; export function* fetchModel(action) { try { const requestUrl = `/content-type-builder/models/${action.modelName}`; const data = yield call(request, requestUrl, { method: 'GET' }); yield put(modelFetchSucceeded(data)); yield put(unsetButtonLoader()); } catch(error) { window.Strapi.notification.error('An error occured'); } } export function* submitChanges() { try { // Show button loader yield put(setButtonLoader()); const modelName = get(storeData.getContentType(), 'name'); const body = yield select(makeSelectModel()); map(body.attributes, (attribute, index) => { // Remove the connection key from attributes if (attribute.connection) { unset(body.attributes[index], 'connection'); } forEach(attribute.params, (value, key) => { if (includes(key, 'Value')) { // Remove and set needed keys for params set(body.attributes[index].params, replace(key, 'Value', ''), value); unset(body.attributes[index].params, key); } if (!value) { unset(body.attributes[index].params, key); } }); }); const method = modelName === body.name ? 'POST' : 'PUT'; const baseUrl = '/content-type-builder/models/'; const requestUrl = method === 'POST' ? baseUrl : `${baseUrl}${body.name}`; const opts = { method, body }; yield call(request, requestUrl, opts); if (method === 'POST') { storeData.clearAppStorage(); yield put(temporaryContentTypePosted(size(get(body, 'attributes')))); yield put(postContentTypeSucceeded()); } yield new Promise(resolve => { setTimeout(() => { resolve(); }, 5000); }); yield put(resetShowButtonsProps()); // Remove loader yield put(unsetButtonLoader()); } catch(error) { console.log(error); } } export function* defaultSaga() { const loadModelWatcher = yield fork(takeLatest, MODEL_FETCH, fetchModel); // const deleteAttributeWatcher = yield fork(takeLatest, DELETE_ATTRIBUTE, attributeDelete); const loadSubmitChanges = yield fork(takeLatest, SUBMIT, submitChanges); yield take(LOCATION_CHANGE); yield cancel(loadModelWatcher); // yield cancel(deleteAttributeWatcher); yield cancel(loadSubmitChanges); } // All sagas to be loaded export default [ defaultSaga, ];
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.9918459057807922, 0.1544531136751175, 0.00016808394866529852, 0.0021399895194917917, 0.30028069019317627 ]
{ "id": 10, "code_window": [ "import { temporaryContentTypePosted } from 'containers/App/actions';\n", "\n", "import { storeData } from '../../utils/storeData';\n", "\n", "import { MODEL_FETCH, SUBMIT } from './constants';\n", "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions';\n", "import { makeSelectModel } from './selectors';\n", "\n", "export function* fetchModel(action) {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader, submitActionSucceeded } from './actions';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 12 }
/* * * List constants * */ export const SET_CURRENT_MODEL_NAME = 'app/List/SET_CURRENT_MODEL_NAME'; export const LOAD_RECORDS = 'app/List/LOAD_RECORDS'; export const LOADED_RECORDS = 'app/List/LOADED_RECORDS'; export const LOAD_COUNT = 'app/List/LOAD_COUNT'; export const LOADED_COUNT = 'app/List/LOADED_COUNT'; export const CHANGE_PAGE = 'app/List/CHANGE_PAGE'; export const CHANGE_SORT = 'app/List/CHANGE_SORT'; export const CHANGE_LIMIT = 'app/List/CHANGE_LIMIT';
packages/strapi-plugin-content-manager/admin/src/containers/List/constants.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00016694112855475396, 0.00016637446242384613, 0.0001658077962929383, 0.00016637446242384613, 5.666661309078336e-7 ]
{ "id": 10, "code_window": [ "import { temporaryContentTypePosted } from 'containers/App/actions';\n", "\n", "import { storeData } from '../../utils/storeData';\n", "\n", "import { MODEL_FETCH, SUBMIT } from './constants';\n", "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions';\n", "import { makeSelectModel } from './selectors';\n", "\n", "export function* fetchModel(action) {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader, submitActionSucceeded } from './actions';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 12 }
<?xml version="1.0" encoding="UTF-8"?> <svg width="41px" height="41px" viewBox="0 0 41 41" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch --> <title>One-to-one</title> <desc>Created with Sketch.</desc> <defs> <rect id="path-1" x="0" y="0" width="41" height="41" rx="2"></rect> </defs> <g id="Pages" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Content-Type-Builder---Content-Type-view" transform="translate(-706.000000, -389.000000)"> <g id="Container"> <g id="Content"> <g id="Popup---Add-New-Relation---Define-Relation" transform="translate(427.000000, 230.000000)"> <g id="One-to-one" transform="translate(279.000000, 159.000000)"> <g id="Rectangle-13"> <use fill="#FFFFFF" fill-rule="evenodd" xlink:href="#path-1"></use> <rect stroke="#1C5DE7" stroke-width="1" x="0.5" y="0.5" width="40" height="40" rx="2"></rect> </g> <rect id="Rectangle-15" stroke="#1C5DE7" x="14" y="21.25" width="14" height="1"></rect> <rect id="Rectangle-14" stroke="#1C5DE7" x="7.5" y="18.5" width="6" height="6" rx="3"></rect> <rect id="Rectangle-14" stroke="#1C5DE7" x="28.5" y="18.5" width="6" height="6" rx="3"></rect> </g> </g> </g> </g> </g> </g> </svg>
packages/strapi-plugin-content-type-builder/admin/src/assets/images/one_to_one_selected.svg
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017347630637232214, 0.00017125751764979213, 0.00016763659368734807, 0.00017265962378587574, 0.0000025819899747148156 ]
{ "id": 10, "code_window": [ "import { temporaryContentTypePosted } from 'containers/App/actions';\n", "\n", "import { storeData } from '../../utils/storeData';\n", "\n", "import { MODEL_FETCH, SUBMIT } from './constants';\n", "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader } from './actions';\n", "import { makeSelectModel } from './selectors';\n", "\n", "export function* fetchModel(action) {\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { modelFetchSucceeded, postContentTypeSucceeded, resetShowButtonsProps, setButtonLoader, unsetButtonLoader, submitActionSucceeded } from './actions';\n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 12 }
// Inline and block code styles code, kbd, pre, samp { font-family: $font-family-monospace; } // Inline code code { padding: $code-padding-y $code-padding-x; font-size: $code-font-size; color: $code-color; background-color: $code-bg; @include border-radius($border-radius); // Streamline the style when inside anchors to avoid broken underline and more a { padding: 0; color: inherit; background-color: inherit; } } // User input typically entered via keyboard kbd { padding: $code-padding-y $code-padding-x; font-size: $code-font-size; color: $kbd-color; background-color: $kbd-bg; @include border-radius($border-radius-sm); @include box-shadow($kbd-box-shadow); kbd { padding: 0; font-size: 100%; font-weight: $nested-kbd-font-weight; @include box-shadow(none); } } // Blocks of code pre { display: block; margin-top: 0; margin-bottom: 1rem; font-size: $code-font-size; color: $pre-color; // Account for some code outputs that place code tags in pre tags code { padding: 0; font-size: inherit; color: inherit; background-color: transparent; border-radius: 0; } } // Enable scrollable blocks of code .pre-scrollable { max-height: $pre-scrollable-max-height; overflow-y: scroll; }
packages/strapi-admin/files/public/app/styles/libs/bootstrap/_code.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001778846635716036, 0.00017461397510487586, 0.00017028952424880117, 0.00017575177480466664, 0.000002603256234579021 ]
{ "id": 11, "code_window": [ "\n", "\n", " yield call(request, requestUrl, opts);\n", "\n", " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield new Promise(resolve => {\n", " setTimeout(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 67 }
/* * * ModelPage reducer * */ import { fromJS, Map, List } from 'immutable'; import { get, size, differenceBy, findIndex } from 'lodash'; import { storeData } from '../../utils/storeData'; /* eslint-disable new-cap */ import { ADD_ATTRIBUTE_RELATION_TO_CONTENT_TYPE, ADD_ATTRIBUTE_TO_CONTENT_TYPE, EDIT_CONTENT_TYPE_ATTRIBUTE, EDIT_CONTENT_TYPE_ATTRIBUTE_RELATION, CANCEL_CHANGES, DELETE_ATTRIBUTE, MODEL_FETCH_SUCCEEDED, POST_CONTENT_TYPE_SUCCEEDED, RESET_SHOW_BUTTONS_PROPS, SET_BUTTON_LOADER, UNSET_BUTTON_LOADER, UPDATE_CONTENT_TYPE, } from './constants'; const initialState = fromJS({ initialModel: Map({ attributes: List(), }), model: Map({ attributes: List(), }), postContentTypeSuccess: false, showButtons: false, modelLoading: true, showButtonLoader: false, }); function modelPageReducer(state = initialState, action) { switch (action.type) { case ADD_ATTRIBUTE_RELATION_TO_CONTENT_TYPE: return state .updateIn(['model', 'attributes'], (list) => list.push(action.newAttribute, action.parallelAttribute)) .set('showButtons', true); case ADD_ATTRIBUTE_TO_CONTENT_TYPE: return state .updateIn(['model', 'attributes'], (list) => list.push(action.newAttribute)) .set('showButtons', true); case EDIT_CONTENT_TYPE_ATTRIBUTE: { if (action.shouldAddParralAttribute) { return state .set('showButtons', true) .updateIn(['model', 'attributes', action.attributePosition], () => action.modifiedAttribute) .updateIn(['model', 'attributes'], (list) => list.splice(action.attributePosition + 1, 0, action.parallelAttribute)); } return state .set('showButtons', true) .updateIn(['model', 'attributes', action.attributePosition], () => action.modifiedAttribute); } case EDIT_CONTENT_TYPE_ATTRIBUTE_RELATION: { if (action.shouldRemoveParallelAttribute) { return state .set('showButtons', true) .updateIn(['model', 'attributes', action.attributePosition], () => action.modifiedAttribute) .updateIn(['model', 'attributes'], (list) => list.splice(action.parallelAttributePosition, 1)); } return state .set('showButtons', true) .updateIn(['model', 'attributes', action.attributePosition], () => action.modifiedAttribute) .updateIn(['model', 'attributes', action.parallelAttributePosition], () => action.parallelAttribute); } case CANCEL_CHANGES: return state .set('showButtons', false) .set('model', state.get('initialModel')); case DELETE_ATTRIBUTE: { const contentTypeAttributes = state.getIn(['model', 'attributes']).toJS(); contentTypeAttributes.splice(action.position, 1); const updatedContentTypeAttributes = contentTypeAttributes; let showButtons = size(updatedContentTypeAttributes) !== size(state.getIn(['initialModel', 'attributes']).toJS()) || size(differenceBy(state.getIn(['initialModel', 'attributes']).toJS(), updatedContentTypeAttributes, 'name')) > 0; if (get(storeData.getContentType(), 'name') === state.getIn(['initialModel', 'name'])) { showButtons = size(get(storeData.getContentType(), 'attributes')) > 0; } if (action.shouldRemoveParallelAttribute) { const attributeKey = state.getIn(['model', 'attributes', action.position]).params.key; return state .set('showButtons', showButtons) .updateIn(['model', 'attributes'], (list) => list.splice(action.position, 1)) .updateIn(['model', 'attributes'], (list) => list.splice(findIndex(list.toJS(), ['name', attributeKey]), 1)); } return state .set('showButtons', showButtons) .updateIn(['model', 'attributes'], (list) => list.splice(action.position, 1)); } case MODEL_FETCH_SUCCEEDED: return state .set('modelLoading', false) .set('model', Map(action.model.model)) .set('initialModel', Map(action.model.model)) .setIn(['model', 'attributes'], List(action.model.model.attributes)) .setIn(['initialModel', 'attributes'], List(action.model.model.attributes)); case POST_CONTENT_TYPE_SUCCEEDED: return state.set('postContentTypeSuccess', !state.get('postContentTypeSuccess')); case RESET_SHOW_BUTTONS_PROPS: return state.set('showButtons', false); case SET_BUTTON_LOADER: return state.set('showButtonLoader', true); case UNSET_BUTTON_LOADER: return state.set('showButtonLoader', false); case UPDATE_CONTENT_TYPE: return state .set('model', Map(action.data)) .set('initialModel', Map(action.data)) .setIn(['model', 'attributes'], List(action.data.attributes)) .setIn(['initialModel', 'attributes'], List(action.data.attributes)); default: return state; } } export default modelPageReducer;
packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/reducer.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0005180179723538458, 0.00020334597502369434, 0.00016618591325823218, 0.00017227364878635854, 0.00009208417031913996 ]
{ "id": 11, "code_window": [ "\n", "\n", " yield call(request, requestUrl, opts);\n", "\n", " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield new Promise(resolve => {\n", " setTimeout(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 67 }
/** * * Notification * */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import styles from './styles.scss'; class Notification extends React.Component { // eslint-disable-line react/prefer-stateless-function onCloseClicked = () => { this.props.onHideNotification(this.props.notification.id); }; options = { success: { icon: 'ion-ios-checkmark-outline', title: 'Success', class: 'notificationSuccess', }, warning: { icon: 'ion-ios-information-outline', title: 'Warning', class: 'notificationWarning', }, error: { icon: 'ion-ios-close-outline', title: 'Error', class: 'notificationError', }, info: { icon: 'ion-ios-information-outline', title: 'Info', class: 'notificationInfo', }, }; render() { const options = this.options[this.props.notification.status] || this.options.info; return ( <li key={this.props.notification.id} className={`${styles.notification} ${styles[options.class]}`}> <icon className={`ion ${options.icon} ${styles.notificationIcon}`}></icon> <p className={styles.notificationContent}> <span className={styles.notificationTitle}>{options.title}: </span> <span><FormattedMessage id={this.props.notification.message} /></span> </p> <icon className={`ion ion-ios-close-empty pull-right ${styles.notificationClose}`} onClick={this.onCloseClicked}></icon> </li> ); } } Notification.propTypes = { notification: React.PropTypes.object, onHideNotification: React.PropTypes.func, }; export default Notification;
packages/strapi-admin/files/public/app/components/Notification/index.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.0001745386834954843, 0.00017227161151822656, 0.00016861336189322174, 0.0001733352692099288, 0.0000020894926819892135 ]
{ "id": 11, "code_window": [ "\n", "\n", " yield call(request, requestUrl, opts);\n", "\n", " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield new Promise(resolve => {\n", " setTimeout(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 67 }
/** * * EditFormSectionNested * */ import React from 'react'; import { has, map, forEach } from 'lodash'; // HOC import EditFormSectionSubNested from 'components/EditFormSectionSubNested'; import WithFormSection from 'components/WithFormSection'; class EditFormSectionNested extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { hasNestedInput: false, showNestedForm: false, inputWithNestedForm: '', }; } componentDidMount() { // check if there is inside a section an input that requires nested input to display it on the entire line // TODO add logic in withform section HOC if (this.props.section) { this.checkForNestedForm(this.props); } } componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.values) { this.checkForNestedForm(nextProps); } } checkForNestedForm(props) { forEach(props.section, (input) => { if (input.type === 'enum') { forEach(input.items, (item) => { if (has(item, 'items')) { this.setState({ hasNestedInput: true, inputWithNestedForm: input.target, section: item.items }); if (props.values[input.target] === item.value) { this.setState({ showNestedForm: true }); } else { this.setState({ showNestedForm: false }); } } }) } }); } render() { return ( <div className={`${this.props.styles.padded} ${this.props.styles.nesTedFormContainer}`}> <div className="row"> {map(this.props.section, (item, key) => { if (this.state.showNestedForm) { return ( <div key={key} style={{width: '100%'}}> {this.props.renderInput(item, key)} <EditFormSectionSubNested section={this.state.section} values={this.props.values} handleChange={this.props.handleChange} formErrors={this.props.formErrors} /> </div> ) } return this.props.renderInput(item, key) })} </div> </div> ); } } EditFormSectionNested.propTypes = { formErrors: React.PropTypes.array, handleChange: React.PropTypes.func, renderInput: React.PropTypes.func, section: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object, ]), styles: React.PropTypes.object, values: React.PropTypes.object, }; export default WithFormSection(EditFormSectionNested); // eslint-disable-line new-cap
packages/strapi-plugin-settings-manager/admin/src/components/EditFormSectionNested/index.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017458279035054147, 0.00017169157217722386, 0.00016764506290201098, 0.00017186150944326073, 0.0000020225695607223315 ]
{ "id": 11, "code_window": [ "\n", "\n", " yield call(request, requestUrl, opts);\n", "\n", " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield new Promise(resolve => {\n", " setTimeout(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "replace", "edit_start_line_idx": 67 }
.container { // margin-top: 1.7rem; // padding-top: .2rem; } .inputToggle { /* stylelint-disable */ margin-top: .2rem; > button { // display and box model width: 5.3rem; height: 3.4rem; padding: 0; line-height: 3.4rem; border: 1px solid #E3E9F3; margin-bottom: 2.8rem; // color color: #CED3DB; background-color: white; // text font-weight: 600; font-size: 1.2rem; letter-spacing: 0.1rem; font-family: Lato; cursor: pointer; &:first-of-type { border-right: none; // box-shadow: inset -1px 1 3px 0 rgba(0,0,0,0.1); } &:nth-of-type(2) { border-left: none; // box-shadow: inset -4px 0 0px -2px rgba(0,0,0,0.05), inset 0px -4px 0px -2px rgba(0,0,0,0.05), 0px -4px 0px -2px rgba(0,0,0,0.05); } &:hover { z-index: 0 !important; } &:focus { outline: 0; box-shadow: 0 0 0; } } } .gradientOff { background-image: linear-gradient( to bottom right, #F65A1D, #F68E0E ); color: white !important; box-shadow: inset -1px 1px 3px rgba(0,0,0,0.1); } .gradientOn { background-image: linear-gradient( to bottom right, #005EEA, #0097F6); color: white !important; box-shadow: inset 1px 1px 3px rgba(0,0,0,0.1); } .toggleLabel { font-weight: 500; margin-bottom: 1rem; font-size: 1.3rem; line-height: 1.6rem; }
packages/strapi-plugin-settings-manager/admin/src/components/InputToggle/styles.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017653527902439237, 0.00017421085794921964, 0.0001730160875013098, 0.00017383627709932625, 0.0000012056361811119132 ]
{ "id": 12, "code_window": [ " setTimeout(() => {\n", " resolve();\n", " }, 5000);\n", " });\n", "\n", " yield put(resetShowButtonsProps());\n", " // Remove loader\n", " yield put(unsetButtonLoader());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield put(submitActionSucceeded());\n", " \n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "add", "edit_start_line_idx": 79 }
/** * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * */ import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createStructuredSelector } from 'reselect'; import { pluginId } from 'app'; import { makeSelectShouldRefetchContentType } from 'containers/Form/selectors'; import { storeData } from '../../utils/storeData'; import styles from './styles.scss'; import { modelsFetch } from './actions'; import { makeSelectMenu } from './selectors'; class App extends React.Component { componentDidMount() { this.props.modelsFetch(); } componentWillReceiveProps(nextProps) { if (nextProps.shouldRefetchContentType !== this.props.shouldRefetchContentType) { this.props.modelsFetch(); } } componentWillUnmount() { // Empty the app localStorage storeData.clearAppStorage(); } render() { // Assign plugin component to children const content = React.Children.map(this.props.children, child => React.cloneElement(child, { exposedComponents: this.props.exposedComponents, menu: this.props.menu, }) ); return ( <div className={`${pluginId} ${styles.app}`}> {React.Children.toArray(content)} </div> ); } } App.contextTypes = { router: React.PropTypes.object.isRequired, }; App.propTypes = { children: React.PropTypes.node, exposedComponents: React.PropTypes.object.isRequired, menu: React.PropTypes.array, modelsFetch: React.PropTypes.func, shouldRefetchContentType: React.PropTypes.bool, }; export function mapDispatchToProps(dispatch) { return bindActionCreators( { modelsFetch, }, dispatch ) } const mapStateToProps = createStructuredSelector({ menu: makeSelectMenu(), shouldRefetchContentType: makeSelectShouldRefetchContentType(), }); // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(App);
packages/strapi-plugin-content-type-builder/admin/src/containers/App/index.js
1
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017402003868483007, 0.00016992127348203212, 0.00016679282998666167, 0.00016884422802831978, 0.0000026142354272451485 ]
{ "id": 12, "code_window": [ " setTimeout(() => {\n", " resolve();\n", " }, 5000);\n", " });\n", "\n", " yield put(resetShowButtonsProps());\n", " // Remove loader\n", " yield put(unsetButtonLoader());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield put(submitActionSucceeded());\n", " \n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "add", "edit_start_line_idx": 79 }
{ "gzip": { "enabled": false }, "responseTime": { "enabled": false } }
packages/strapi-generate-new/files/config/environments/test/response.json
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017512464546598494, 0.00017512464546598494, 0.00017512464546598494, 0.00017512464546598494, 0 ]
{ "id": 12, "code_window": [ " setTimeout(() => {\n", " resolve();\n", " }, 5000);\n", " });\n", "\n", " yield put(resetShowButtonsProps());\n", " // Remove loader\n", " yield put(unsetButtonLoader());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield put(submitActionSucceeded());\n", " \n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "add", "edit_start_line_idx": 79 }
'use strict'; /** * Custom responses hook */ const _ = require('lodash'); module.exports = () => { return { /** * Initialize the hook */ initialize: function(cb) { strapi.app.use(async (ctx, next) => { await next(); // Call custom responses. if (_.isFunction(_.get(strapi.config, `functions.responses.${ctx.status}`))) { await strapi.config.functions.responses[ctx.status].call(this, ctx); } // Set X-Powered-By header. if (_.get(strapi.config, 'X-Powered-By.enabled', true)) { ctx.set('X-Powered-By', 'Strapi <strapi.io>'); } }); cb(); } }; };
packages/strapi/lib/middlewares/responses/index.js
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00017613830277696252, 0.00017150971689261496, 0.00016798525757621974, 0.00017095764633268118, 0.0000029620252917084144 ]
{ "id": 12, "code_window": [ " setTimeout(() => {\n", " resolve();\n", " }, 5000);\n", " });\n", "\n", " yield put(resetShowButtonsProps());\n", " // Remove loader\n", " yield put(unsetButtonLoader());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (method === 'POST') {\n", " storeData.clearAppStorage();\n", " yield put(temporaryContentTypePosted(size(get(body, 'attributes'))));\n", " yield put(postContentTypeSucceeded());\n", " }\n", "\n", " yield put(submitActionSucceeded());\n", " \n" ], "file_path": "packages/strapi-plugin-content-type-builder/admin/src/containers/ModelPage/sagas.js", "type": "add", "edit_start_line_idx": 79 }
// Lists // Unstyled keeps list items block level, just removes default browser padding and list-style @mixin list-unstyled { padding-left: 0; list-style: none; }
packages/strapi-admin/files/public/app/styles/libs/bootstrap/mixins/_lists.scss
0
https://github.com/strapi/strapi/commit/1c0fc6850f58b3dfbf691ab004d9c5be84e928f1
[ 0.00016571801097597927, 0.00016571801097597927, 0.00016571801097597927, 0.00016571801097597927, 0 ]
{ "id": 0, "code_window": [ "\t\t);\n", "\t\ttokenSource.dispose();\n", "\t\tconst searchLength = Date.now() - searchStart;\n", "\t\tthis.logService.trace(`whole search time | ${searchLength}ms`);\n", "\t\treturn notebookResult ? { ...currentResult, ...notebookResult.completeData } : currentResult;\n", "\t}\n", "\n", "\tasync search(query: ITextQuery, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn {\n", "\t\t\tresults: currentResult.results.concat(notebookResult.completeData.results),\n", "\t\t\tmessages: currentResult.messages.concat(notebookResult.completeData.messages),\n", "\t\t\tlimitHit: currentResult.limitHit || notebookResult.completeData.limitHit,\n", "\t\t\texit: currentResult.exit,\n", "\t\t\tstats: currentResult.stats,\n", "\t\t};\n" ], "file_path": "src/vs/workbench/contrib/search/browser/searchModel.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as sinon from 'sinon'; import * as arrays from 'vs/base/common/arrays'; import { DeferredPromise, timeout } from 'vs/base/common/async'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; import { URI } from 'vs/base/common/uri'; import { Range } from 'vs/editor/common/core/range'; import { IModelService } from 'vs/editor/common/services/model'; import { ModelService } from 'vs/editor/common/services/modelService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, ISearchComplete, ISearchProgressItem, ISearchQuery, ISearchService, ITextSearchMatch, OneLineRange, QueryType, TextSearchMatch } from 'vs/workbench/services/search/common/search'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { CellMatch, MatchInNotebook, SearchModel } from 'vs/workbench/contrib/search/browser/searchModel'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { FileService } from 'vs/platform/files/common/fileService'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { ILabelService } from 'vs/platform/label/common/label'; import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { TestEditorGroupsService } from 'vs/workbench/test/browser/workbenchTestServices'; import { NotebookEditorWidgetService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl'; import { createFileUriFromPathFromRoot, getRootName } from 'vs/workbench/contrib/search/test/browser/searchTestCommon'; import { ICellMatch, IFileMatchWithCells, contentMatchesToTextSearchMatches, webviewMatchesToTextSearchMatches } from 'vs/workbench/contrib/search/browser/searchNotebookHelpers'; import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { FindMatch, IReadonlyTextBuffer } from 'vs/editor/common/model'; import { ResourceMap, ResourceSet } from 'vs/base/common/map'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { INotebookSearchService } from 'vs/workbench/contrib/search/browser/notebookSearch'; const nullEvent = new class { id: number = -1; topic!: string; name!: string; description!: string; data: any; startTime!: Date; stopTime!: Date; stop(): void { return; } timeTaken(): number { return -1; } }; const lineOneRange = new OneLineRange(1, 0, 1); suite('SearchModel', () => { let instantiationService: TestInstantiationService; const testSearchStats: IFileSearchStats = { fromCache: false, resultCount: 1, type: 'searchProcess', detailStats: { fileWalkTime: 0, cmdTime: 0, cmdResultCount: 0, directoriesWalked: 2, filesWalked: 3 } }; const folderQueries: IFolderQuery[] = [ { folder: createFileUriFromPathFromRoot() } ]; setup(() => { instantiationService = new TestInstantiationService(); instantiationService.stub(ITelemetryService, NullTelemetryService); instantiationService.stub(ILabelService, { getUriBasenameLabel: (uri: URI) => '' }); instantiationService.stub(INotebookService, { getNotebookTextModels: () => [] }); instantiationService.stub(IModelService, stubModelService(instantiationService)); instantiationService.stub(INotebookEditorService, stubNotebookEditorService(instantiationService)); instantiationService.stub(ISearchService, {}); instantiationService.stub(ISearchService, 'textSearch', Promise.resolve({ results: [] })); instantiationService.stub(IUriIdentityService, new UriIdentityService(new FileService(new NullLogService()))); instantiationService.stub(ILogService, new NullLogService()); }); teardown(() => sinon.restore()); function searchServiceWithResults(results: IFileMatch[], complete: ISearchComplete | null = null): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void, notebookURIs?: ResourceSet): Promise<ISearchComplete> { return new Promise(resolve => { queueMicrotask(() => { results.forEach(onProgress!); resolve(complete!); }); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return new Promise(resolve => { queueMicrotask(() => { resolve({ results: results, messages: [] }); }); }); } }; } function searchServiceWithError(error: Error): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> { return new Promise((resolve, reject) => { reject(error); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return new Promise((resolve, reject) => { queueMicrotask(() => { reject(error); }); }); } }; } function canceleableSearchService(tokenSource: CancellationTokenSource): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> { token?.onCancellationRequested(() => tokenSource.cancel()); return new Promise(resolve => { queueMicrotask(() => { resolve(<any>{}); }); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { token?.onCancellationRequested(() => tokenSource.cancel()); return new Promise(resolve => { queueMicrotask(() => { resolve(<any>{}); }); }); } }; } function notebookSearchServiceWithInfo(results: IFileMatchWithCells[], tokenSource: CancellationTokenSource | undefined): INotebookSearchService { return <INotebookSearchService>{ _serviceBrand: undefined, notebookSearch(query: ISearchQuery, token: CancellationToken, searchInstanceID: string, onProgress?: (result: ISearchProgressItem) => void, notebookURIs?: ResourceSet): Promise<{ completeData: ISearchComplete; scannedFiles: ResourceSet }> { token?.onCancellationRequested(() => tokenSource?.cancel()); const localResults = new ResourceMap<IFileMatchWithCells | null>(uri => uri.path); results.forEach(r => { localResults.set(r.resource, r); }); if (onProgress) { arrays.coalesce([...localResults.values()]).forEach(onProgress); } return Promise.resolve( { completeData: { messages: [], results: arrays.coalesce([...localResults.values()]), limitHit: false }, scannedFiles: new ResourceSet([...localResults.keys()]), }); } }; } test('Search Model: Search adds to results', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); const actual = testObject.searchResult.matches(); assert.strictEqual(2, actual.length); assert.strictEqual(URI.file(`${getRootName()}/1`).toString(), actual[0].resource.toString()); let actuaMatches = actual[0].matches(); assert.strictEqual(2, actuaMatches.length); assert.strictEqual('preview 1', actuaMatches[0].text()); assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range())); assert.strictEqual('preview 1', actuaMatches[1].text()); assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range())); actuaMatches = actual[1].matches(); assert.strictEqual(1, actuaMatches.length); assert.strictEqual('preview 2', actuaMatches[0].text()); assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range())); }); test('Search Model: Search can return notebook results', async () => { const notebookUri = createFileUriFromPathFromRoot('/1'); const results = [ aRawMatch('/2', new TextSearchMatch('test', new OneLineRange(1, 1, 5)), new TextSearchMatch('this is a test', new OneLineRange(1, 11, 15))), aRawMatch('/3', new TextSearchMatch('test', lineOneRange))]; const searchService = instantiationService.stub(ISearchService, searchServiceWithResults(results)); sinon.stub(CellMatch.prototype, 'addContext'); const textSearch = sinon.spy(searchService, 'textSearch'); const mdInputCell = { cellKind: CellKind.Markup, textBuffer: <IReadonlyTextBuffer>{ getLineContent(lineNumber: number): string { if (lineNumber === 1) { return '# Test'; } else { return ''; } } }, id: 'mdInputCell' } as ICellViewModel; const findMatchMds = [new FindMatch(new Range(1, 3, 1, 7), ['Test'])]; const codeCell = { cellKind: CellKind.Code, textBuffer: <IReadonlyTextBuffer>{ getLineContent(lineNumber: number): string { if (lineNumber === 1) { return 'print("test! testing!!")'; } else { return ''; } } }, id: 'codeCell' } as ICellViewModel; const findMatchCodeCells = [new FindMatch(new Range(1, 8, 1, 12), ['test']), new FindMatch(new Range(1, 14, 1, 18), ['test']), ]; const webviewMatches = [{ index: 0, searchPreviewInfo: { line: 'test! testing!!', range: { start: 1, end: 5 } } }, { index: 1, searchPreviewInfo: { line: 'test! testing!!', range: { start: 7, end: 11 } } } ]; const cellMatchMd: ICellMatch = { cell: mdInputCell, index: 0, contentResults: contentMatchesToTextSearchMatches(findMatchMds, mdInputCell), webviewResults: [] }; const cellMatchCode: ICellMatch = { cell: codeCell, index: 1, contentResults: contentMatchesToTextSearchMatches(findMatchCodeCells, codeCell), webviewResults: webviewMatchesToTextSearchMatches(webviewMatches), }; const notebookSearchService = instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([aRawMatchWithCells('/1', cellMatchMd, cellMatchCode)], undefined)); const notebookSearch = sinon.spy(notebookSearchService, "notebookSearch"); const model: SearchModel = instantiationService.createInstance(SearchModel); await model.search({ contentPattern: { pattern: 'test' }, type: QueryType.Text, folderQueries }); const actual = model.searchResult.matches(); assert(notebookSearch.calledOnce); assert(textSearch.getCall(0).args[3]?.size === 1); assert(textSearch.getCall(0).args[3]?.has(notebookUri)); // ensure that the textsearch knows not to re-source the notebooks assert.strictEqual(3, actual.length); assert.strictEqual(URI.file(`${getRootName()}/1`).toString(), actual[0].resource.toString()); const notebookFileMatches = actual[0].matches(); assert.ok(notebookFileMatches[0].range().equalsRange(new Range(1, 3, 1, 7))); assert.ok(notebookFileMatches[1].range().equalsRange(new Range(1, 8, 1, 12))); assert.ok(notebookFileMatches[2].range().equalsRange(new Range(1, 14, 1, 18))); assert.ok(notebookFileMatches[3].range().equalsRange(new Range(1, 2, 1, 6))); assert.ok(notebookFileMatches[4].range().equalsRange(new Range(1, 8, 1, 12))); notebookFileMatches.forEach(match => match instanceof MatchInNotebook); // assert(notebookFileMatches[0] instanceof MatchInNotebook); assert((notebookFileMatches[0] as MatchInNotebook).cell.id === 'mdInputCell'); assert((notebookFileMatches[1] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[2] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[3] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[4] as MatchInNotebook).cell.id === 'codeCell'); const mdCellMatchProcessed = (notebookFileMatches[0] as MatchInNotebook).cellParent; const codeCellMatchProcessed = (notebookFileMatches[1] as MatchInNotebook).cellParent; assert(mdCellMatchProcessed.contentMatches.length === 1); assert(codeCellMatchProcessed.contentMatches.length === 2); assert(codeCellMatchProcessed.webviewMatches.length === 2); assert(mdCellMatchProcessed.contentMatches[0] === notebookFileMatches[0]); assert(codeCellMatchProcessed.contentMatches[0] === notebookFileMatches[1]); assert(codeCellMatchProcessed.contentMatches[1] === notebookFileMatches[2]); assert(codeCellMatchProcessed.webviewMatches[0] === notebookFileMatches[3]); assert(codeCellMatchProcessed.webviewMatches[1] === notebookFileMatches[4]); assert.strictEqual(URI.file(`${getRootName()}/2`).toString(), actual[1].resource.toString()); assert.strictEqual(URI.file(`${getRootName()}/3`).toString(), actual[2].resource.toString()); }); test('Search Model: Search reports telemetry on search completed', async () => { const target = instantiationService.spy(ITelemetryService, 'publicLog'); const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(target.calledThrice); assert.ok(target.calledWith('searchResultsFirstRender')); assert.ok(target.calledWith('searchResultsFinished')); }); test('Search Model: Search reports timed telemetry on search when progress is not called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithResults([])); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); }); }); }); test('Search Model: Search reports timed telemetry on search when progress is called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithResults( [aRawMatch('/1', new TextSearchMatch('some preview', lineOneRange))], { results: [], stats: testSearchStats, messages: [] })); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { return timeout(1).then(() => { // timeout because promise handlers may run in a different order. We only care that these // are fired at some point. assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.strictEqual(1, target2.callCount); }); }); }); test('Search Model: Search reports timed telemetry on search when error is called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithError(new Error('error'))); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { }, () => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.ok(target2.calledOnce); }); }); }); test('Search Model: Search reports timed telemetry on search when error is cancelled error', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); const deferredPromise = new DeferredPromise<ISearchComplete>(); instantiationService.stub(ISearchService, 'textSearch', deferredPromise.p); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); deferredPromise.cancel(); return result.then(() => { }, () => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.ok(target2.calledOnce); }); }); }); test('Search Model: Search results are cleared during search', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(!testObject.searchResult.isEmpty()); instantiationService.stub(ISearchService, searchServiceWithResults([])); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(testObject.searchResult.isEmpty()); }); test('Search Model: Previous search is cancelled when new search is called', async () => { const tokenSource = new CancellationTokenSource(); instantiationService.stub(ISearchService, canceleableSearchService(tokenSource)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], tokenSource)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); instantiationService.stub(ISearchService, searchServiceWithResults([])); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(tokenSource.token.isCancellationRequested); }); test('getReplaceString returns proper replace string for regExpressions', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11)))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 're' }, type: QueryType.Text, folderQueries }); testObject.replaceString = 'hello'; let match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 're', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 're(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); testObject.replaceString = 'hello$1'; match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('helloe', match.replaceString); }); function aRawMatch(resource: string, ...results: ITextSearchMatch[]): IFileMatch { return { resource: createFileUriFromPathFromRoot(resource), results }; } function aRawMatchWithCells(resource: string, ...cells: ICellMatch[]) { return { resource: createFileUriFromPathFromRoot(resource), cellResults: cells }; } function stubModelService(instantiationService: TestInstantiationService): IModelService { instantiationService.stub(IThemeService, new TestThemeService()); const config = new TestConfigurationService(); config.setUserConfiguration('search', { searchOnType: true }); instantiationService.stub(IConfigurationService, config); return instantiationService.createInstance(ModelService); } function stubNotebookEditorService(instantiationService: TestInstantiationService): INotebookEditorService { instantiationService.stub(IEditorGroupsService, new TestEditorGroupsService()); return instantiationService.createInstance(NotebookEditorWidgetService); } });
src/vs/workbench/contrib/search/test/browser/searchModel.test.ts
1
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.984486997127533, 0.12852263450622559, 0.00016489681729581207, 0.0002508343895897269, 0.29288753867149353 ]
{ "id": 0, "code_window": [ "\t\t);\n", "\t\ttokenSource.dispose();\n", "\t\tconst searchLength = Date.now() - searchStart;\n", "\t\tthis.logService.trace(`whole search time | ${searchLength}ms`);\n", "\t\treturn notebookResult ? { ...currentResult, ...notebookResult.completeData } : currentResult;\n", "\t}\n", "\n", "\tasync search(query: ITextQuery, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn {\n", "\t\t\tresults: currentResult.results.concat(notebookResult.completeData.results),\n", "\t\t\tmessages: currentResult.messages.concat(notebookResult.completeData.messages),\n", "\t\t\tlimitHit: currentResult.limitHit || notebookResult.completeData.limitHit,\n", "\t\t\texit: currentResult.exit,\n", "\t\t\tstats: currentResult.stats,\n", "\t\t};\n" ], "file_path": "src/vs/workbench/contrib/search/browser/searchModel.ts", "type": "replace", "edit_start_line_idx": 1000 }
{ "information_for_contributors": [ "This file has been converted from https://github.com/textmate/html.tmbundle/blob/master/Syntaxes/HTML%20%28Derivative%29.tmLanguage", "If you want to provide a fix or improvement, please create a pull request against the original repository.", "Once accepted there, we are happy to receive an update request." ], "version": "https://github.com/textmate/html.tmbundle/commit/390c8870273a2ae80244dae6db6ba064a802f407", "name": "HTML (Derivative)", "scopeName": "text.html.derivative", "injections": { "R:text.html - (comment.block, text.html meta.embedded, meta.tag.*.*.html, meta.tag.*.*.*.html, meta.tag.*.*.*.*.html)": { "comment": "Uses R: to ensure this matches after any other injections.", "patterns": [ { "match": "<", "name": "invalid.illegal.bad-angle-bracket.html" } ] } }, "patterns": [ { "include": "text.html.basic#core-minus-invalid" }, { "begin": "(</?)(\\w[^\\s>]*)(?<!/)", "beginCaptures": { "1": { "name": "punctuation.definition.tag.begin.html" }, "2": { "name": "entity.name.tag.html" } }, "end": "((?: ?/)?>)", "endCaptures": { "1": { "name": "punctuation.definition.tag.end.html" } }, "name": "meta.tag.other.unrecognized.html.derivative", "patterns": [ { "include": "text.html.basic#attribute" } ] } ] }
extensions/html/syntaxes/html-derivative.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.0001776001154212281, 0.00017553730867803097, 0.000174425367731601, 0.0001751820818753913, 0.0000011308623015793273 ]
{ "id": 0, "code_window": [ "\t\t);\n", "\t\ttokenSource.dispose();\n", "\t\tconst searchLength = Date.now() - searchStart;\n", "\t\tthis.logService.trace(`whole search time | ${searchLength}ms`);\n", "\t\treturn notebookResult ? { ...currentResult, ...notebookResult.completeData } : currentResult;\n", "\t}\n", "\n", "\tasync search(query: ITextQuery, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn {\n", "\t\t\tresults: currentResult.results.concat(notebookResult.completeData.results),\n", "\t\t\tmessages: currentResult.messages.concat(notebookResult.completeData.messages),\n", "\t\t\tlimitHit: currentResult.limitHit || notebookResult.completeData.limitHit,\n", "\t\t\texit: currentResult.exit,\n", "\t\t\tstats: currentResult.stats,\n", "\t\t};\n" ], "file_path": "src/vs/workbench/contrib/search/browser/searchModel.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ use super::errors::{wrap, WrappedError}; use super::io::ReportCopyProgress; use std::fs::{self, File}; use std::io; use std::path::Path; use std::path::PathBuf; use zip::read::ZipFile; use zip::{self, ZipArchive}; // Borrowed and modified from https://github.com/zip-rs/zip/blob/master/examples/extract.rs /// Returns whether all files in the archive start with the same path segment. /// If so, it's an indication we should skip that segment when extracting. fn should_skip_first_segment(archive: &mut ZipArchive<File>) -> bool { let first_name = { let file = archive .by_index_raw(0) .expect("expected not to have an empty archive"); let path = file .enclosed_name() .expect("expected to have path") .iter() .next() .expect("expected to have non-empty name"); path.to_owned() }; for i in 1..archive.len() { if let Ok(file) = archive.by_index_raw(i) { if let Some(name) = file.enclosed_name() { if name.iter().next() != Some(&first_name) { return false; } } } } archive.len() > 1 // prefix removal is invalid if there's only a single file } pub fn unzip_file<T>(path: &Path, parent_path: &Path, mut reporter: T) -> Result<(), WrappedError> where T: ReportCopyProgress, { let file = fs::File::open(path) .map_err(|e| wrap(e, format!("unable to open file {}", path.display())))?; let mut archive = zip::ZipArchive::new(file) .map_err(|e| wrap(e, format!("failed to open zip archive {}", path.display())))?; let skip_segments_no = usize::from(should_skip_first_segment(&mut archive)); for i in 0..archive.len() { reporter.report_progress(i as u64, archive.len() as u64); let mut file = archive .by_index(i) .map_err(|e| wrap(e, format!("could not open zip entry {}", i)))?; let outpath: PathBuf = match file.enclosed_name() { Some(path) => { let mut full_path = PathBuf::from(parent_path); full_path.push(PathBuf::from_iter(path.iter().skip(skip_segments_no))); full_path } None => continue, }; if file.is_dir() || file.name().ends_with('/') { fs::create_dir_all(&outpath) .map_err(|e| wrap(e, format!("could not create dir for {}", outpath.display())))?; apply_permissions(&file, &outpath)?; continue; } if let Some(p) = outpath.parent() { fs::create_dir_all(p) .map_err(|e| wrap(e, format!("could not create dir for {}", outpath.display())))?; } #[cfg(unix)] { use libc::S_IFLNK; use std::io::Read; use std::os::unix::ffi::OsStringExt; #[cfg(target_os = "macos")] const S_IFLINK_32: u32 = S_IFLNK as u32; #[cfg(target_os = "linux")] const S_IFLINK_32: u32 = S_IFLNK; if matches!(file.unix_mode(), Some(mode) if mode & S_IFLINK_32 == S_IFLINK_32) { let mut link_to = Vec::new(); file.read_to_end(&mut link_to).map_err(|e| { wrap( e, format!("could not read symlink linkpath {}", outpath.display()), ) })?; let link_path = PathBuf::from(std::ffi::OsString::from_vec(link_to)); std::os::unix::fs::symlink(link_path, &outpath).map_err(|e| { wrap(e, format!("could not create symlink {}", outpath.display())) })?; continue; } } let mut outfile = fs::File::create(&outpath).map_err(|e| { wrap( e, format!( "unable to open file to write {} (from {:?})", outpath.display(), file.enclosed_name().map(|p| p.to_string_lossy()), ), ) })?; io::copy(&mut file, &mut outfile) .map_err(|e| wrap(e, format!("error copying file {}", outpath.display())))?; apply_permissions(&file, &outpath)?; } reporter.report_progress(archive.len() as u64, archive.len() as u64); Ok(()) } #[cfg(unix)] fn apply_permissions(file: &ZipFile, outpath: &Path) -> Result<(), WrappedError> { use std::os::unix::fs::PermissionsExt; if let Some(mode) = file.unix_mode() { fs::set_permissions(outpath, fs::Permissions::from_mode(mode)).map_err(|e| { wrap( e, format!("error setting permissions on {}", outpath.display()), ) })?; } Ok(()) } #[cfg(windows)] fn apply_permissions(_file: &ZipFile, _outpath: &Path) -> Result<(), WrappedError> { Ok(()) }
cli/src/util/zipper.rs
0
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.00018003038712777197, 0.00017699504678603262, 0.00017258356092497706, 0.00017694849520921707, 0.0000020268207663320936 ]
{ "id": 0, "code_window": [ "\t\t);\n", "\t\ttokenSource.dispose();\n", "\t\tconst searchLength = Date.now() - searchStart;\n", "\t\tthis.logService.trace(`whole search time | ${searchLength}ms`);\n", "\t\treturn notebookResult ? { ...currentResult, ...notebookResult.completeData } : currentResult;\n", "\t}\n", "\n", "\tasync search(query: ITextQuery, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn {\n", "\t\t\tresults: currentResult.results.concat(notebookResult.completeData.results),\n", "\t\t\tmessages: currentResult.messages.concat(notebookResult.completeData.messages),\n", "\t\t\tlimitHit: currentResult.limitHit || notebookResult.completeData.limitHit,\n", "\t\t\texit: currentResult.exit,\n", "\t\t\tstats: currentResult.stats,\n", "\t\t};\n" ], "file_path": "src/vs/workbench/contrib/search/browser/searchModel.ts", "type": "replace", "edit_start_line_idx": 1000 }
{ "displayName": "Reference Search View", "description": "Reference Search results as separate, stable view in the sidebar", "config.references.preferredLocation": "Controls whether 'Peek References' or 'Find References' is invoked when selecting CodeLens references.", "config.references.preferredLocation.peek": "Show references in peek editor.", "config.references.preferredLocation.view": "Show references in separate view.", "container.title": "References", "view.title": "Reference Search Results", "cmd.category.references": "References", "cmd.references-view.findReferences": "Find All References", "cmd.references-view.findImplementations": "Find All Implementations", "cmd.references-view.clearHistory": "Clear History", "cmd.references-view.clear": "Clear", "cmd.references-view.refresh": "Refresh", "cmd.references-view.pickFromHistory": "Show History", "cmd.references-view.removeReferenceItem": "Dismiss", "cmd.references-view.copy": "Copy", "cmd.references-view.copyAll": "Copy All", "cmd.references-view.copyPath": "Copy Path", "cmd.references-view.refind": "Rerun", "cmd.references-view.showCallHierarchy": "Show Call Hierarchy", "cmd.references-view.showOutgoingCalls": "Show Outgoing Calls", "cmd.references-view.showIncomingCalls": "Show Incoming Calls", "cmd.references-view.removeCallItem": "Dismiss", "cmd.references-view.next": "Go to Next Reference", "cmd.references-view.prev": "Go to Previous Reference", "cmd.references-view.showTypeHierarchy": "Show Type Hierarchy", "cmd.references-view.showSupertypes": "Show Supertypes", "cmd.references-view.showSubtypes": "Show Subtypes", "cmd.references-view.removeTypeItem": "Dismiss" }
extensions/references-view/package.nls.json
0
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.00017803536320570856, 0.0001759184815455228, 0.000174794826307334, 0.00017542188288643956, 0.0000012487296316976426 ]
{ "id": 1, "code_window": [ "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)),\n", "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))),\n", "\t\t\taRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))];\n", "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results));\n", "\t\tinstantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined));\n", "\n", "\t\tconst testObject: SearchModel = instantiationService.createInstance(SearchModel);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results, { limitHit: false, messages: [], results }));\n" ], "file_path": "src/vs/workbench/contrib/search/test/browser/searchModel.test.ts", "type": "replace", "edit_start_line_idx": 192 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as sinon from 'sinon'; import * as arrays from 'vs/base/common/arrays'; import { DeferredPromise, timeout } from 'vs/base/common/async'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; import { URI } from 'vs/base/common/uri'; import { Range } from 'vs/editor/common/core/range'; import { IModelService } from 'vs/editor/common/services/model'; import { ModelService } from 'vs/editor/common/services/modelService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, ISearchComplete, ISearchProgressItem, ISearchQuery, ISearchService, ITextSearchMatch, OneLineRange, QueryType, TextSearchMatch } from 'vs/workbench/services/search/common/search'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { CellMatch, MatchInNotebook, SearchModel } from 'vs/workbench/contrib/search/browser/searchModel'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { FileService } from 'vs/platform/files/common/fileService'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { ILabelService } from 'vs/platform/label/common/label'; import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { TestEditorGroupsService } from 'vs/workbench/test/browser/workbenchTestServices'; import { NotebookEditorWidgetService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl'; import { createFileUriFromPathFromRoot, getRootName } from 'vs/workbench/contrib/search/test/browser/searchTestCommon'; import { ICellMatch, IFileMatchWithCells, contentMatchesToTextSearchMatches, webviewMatchesToTextSearchMatches } from 'vs/workbench/contrib/search/browser/searchNotebookHelpers'; import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { FindMatch, IReadonlyTextBuffer } from 'vs/editor/common/model'; import { ResourceMap, ResourceSet } from 'vs/base/common/map'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { INotebookSearchService } from 'vs/workbench/contrib/search/browser/notebookSearch'; const nullEvent = new class { id: number = -1; topic!: string; name!: string; description!: string; data: any; startTime!: Date; stopTime!: Date; stop(): void { return; } timeTaken(): number { return -1; } }; const lineOneRange = new OneLineRange(1, 0, 1); suite('SearchModel', () => { let instantiationService: TestInstantiationService; const testSearchStats: IFileSearchStats = { fromCache: false, resultCount: 1, type: 'searchProcess', detailStats: { fileWalkTime: 0, cmdTime: 0, cmdResultCount: 0, directoriesWalked: 2, filesWalked: 3 } }; const folderQueries: IFolderQuery[] = [ { folder: createFileUriFromPathFromRoot() } ]; setup(() => { instantiationService = new TestInstantiationService(); instantiationService.stub(ITelemetryService, NullTelemetryService); instantiationService.stub(ILabelService, { getUriBasenameLabel: (uri: URI) => '' }); instantiationService.stub(INotebookService, { getNotebookTextModels: () => [] }); instantiationService.stub(IModelService, stubModelService(instantiationService)); instantiationService.stub(INotebookEditorService, stubNotebookEditorService(instantiationService)); instantiationService.stub(ISearchService, {}); instantiationService.stub(ISearchService, 'textSearch', Promise.resolve({ results: [] })); instantiationService.stub(IUriIdentityService, new UriIdentityService(new FileService(new NullLogService()))); instantiationService.stub(ILogService, new NullLogService()); }); teardown(() => sinon.restore()); function searchServiceWithResults(results: IFileMatch[], complete: ISearchComplete | null = null): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void, notebookURIs?: ResourceSet): Promise<ISearchComplete> { return new Promise(resolve => { queueMicrotask(() => { results.forEach(onProgress!); resolve(complete!); }); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return new Promise(resolve => { queueMicrotask(() => { resolve({ results: results, messages: [] }); }); }); } }; } function searchServiceWithError(error: Error): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> { return new Promise((resolve, reject) => { reject(error); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return new Promise((resolve, reject) => { queueMicrotask(() => { reject(error); }); }); } }; } function canceleableSearchService(tokenSource: CancellationTokenSource): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> { token?.onCancellationRequested(() => tokenSource.cancel()); return new Promise(resolve => { queueMicrotask(() => { resolve(<any>{}); }); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { token?.onCancellationRequested(() => tokenSource.cancel()); return new Promise(resolve => { queueMicrotask(() => { resolve(<any>{}); }); }); } }; } function notebookSearchServiceWithInfo(results: IFileMatchWithCells[], tokenSource: CancellationTokenSource | undefined): INotebookSearchService { return <INotebookSearchService>{ _serviceBrand: undefined, notebookSearch(query: ISearchQuery, token: CancellationToken, searchInstanceID: string, onProgress?: (result: ISearchProgressItem) => void, notebookURIs?: ResourceSet): Promise<{ completeData: ISearchComplete; scannedFiles: ResourceSet }> { token?.onCancellationRequested(() => tokenSource?.cancel()); const localResults = new ResourceMap<IFileMatchWithCells | null>(uri => uri.path); results.forEach(r => { localResults.set(r.resource, r); }); if (onProgress) { arrays.coalesce([...localResults.values()]).forEach(onProgress); } return Promise.resolve( { completeData: { messages: [], results: arrays.coalesce([...localResults.values()]), limitHit: false }, scannedFiles: new ResourceSet([...localResults.keys()]), }); } }; } test('Search Model: Search adds to results', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); const actual = testObject.searchResult.matches(); assert.strictEqual(2, actual.length); assert.strictEqual(URI.file(`${getRootName()}/1`).toString(), actual[0].resource.toString()); let actuaMatches = actual[0].matches(); assert.strictEqual(2, actuaMatches.length); assert.strictEqual('preview 1', actuaMatches[0].text()); assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range())); assert.strictEqual('preview 1', actuaMatches[1].text()); assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range())); actuaMatches = actual[1].matches(); assert.strictEqual(1, actuaMatches.length); assert.strictEqual('preview 2', actuaMatches[0].text()); assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range())); }); test('Search Model: Search can return notebook results', async () => { const notebookUri = createFileUriFromPathFromRoot('/1'); const results = [ aRawMatch('/2', new TextSearchMatch('test', new OneLineRange(1, 1, 5)), new TextSearchMatch('this is a test', new OneLineRange(1, 11, 15))), aRawMatch('/3', new TextSearchMatch('test', lineOneRange))]; const searchService = instantiationService.stub(ISearchService, searchServiceWithResults(results)); sinon.stub(CellMatch.prototype, 'addContext'); const textSearch = sinon.spy(searchService, 'textSearch'); const mdInputCell = { cellKind: CellKind.Markup, textBuffer: <IReadonlyTextBuffer>{ getLineContent(lineNumber: number): string { if (lineNumber === 1) { return '# Test'; } else { return ''; } } }, id: 'mdInputCell' } as ICellViewModel; const findMatchMds = [new FindMatch(new Range(1, 3, 1, 7), ['Test'])]; const codeCell = { cellKind: CellKind.Code, textBuffer: <IReadonlyTextBuffer>{ getLineContent(lineNumber: number): string { if (lineNumber === 1) { return 'print("test! testing!!")'; } else { return ''; } } }, id: 'codeCell' } as ICellViewModel; const findMatchCodeCells = [new FindMatch(new Range(1, 8, 1, 12), ['test']), new FindMatch(new Range(1, 14, 1, 18), ['test']), ]; const webviewMatches = [{ index: 0, searchPreviewInfo: { line: 'test! testing!!', range: { start: 1, end: 5 } } }, { index: 1, searchPreviewInfo: { line: 'test! testing!!', range: { start: 7, end: 11 } } } ]; const cellMatchMd: ICellMatch = { cell: mdInputCell, index: 0, contentResults: contentMatchesToTextSearchMatches(findMatchMds, mdInputCell), webviewResults: [] }; const cellMatchCode: ICellMatch = { cell: codeCell, index: 1, contentResults: contentMatchesToTextSearchMatches(findMatchCodeCells, codeCell), webviewResults: webviewMatchesToTextSearchMatches(webviewMatches), }; const notebookSearchService = instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([aRawMatchWithCells('/1', cellMatchMd, cellMatchCode)], undefined)); const notebookSearch = sinon.spy(notebookSearchService, "notebookSearch"); const model: SearchModel = instantiationService.createInstance(SearchModel); await model.search({ contentPattern: { pattern: 'test' }, type: QueryType.Text, folderQueries }); const actual = model.searchResult.matches(); assert(notebookSearch.calledOnce); assert(textSearch.getCall(0).args[3]?.size === 1); assert(textSearch.getCall(0).args[3]?.has(notebookUri)); // ensure that the textsearch knows not to re-source the notebooks assert.strictEqual(3, actual.length); assert.strictEqual(URI.file(`${getRootName()}/1`).toString(), actual[0].resource.toString()); const notebookFileMatches = actual[0].matches(); assert.ok(notebookFileMatches[0].range().equalsRange(new Range(1, 3, 1, 7))); assert.ok(notebookFileMatches[1].range().equalsRange(new Range(1, 8, 1, 12))); assert.ok(notebookFileMatches[2].range().equalsRange(new Range(1, 14, 1, 18))); assert.ok(notebookFileMatches[3].range().equalsRange(new Range(1, 2, 1, 6))); assert.ok(notebookFileMatches[4].range().equalsRange(new Range(1, 8, 1, 12))); notebookFileMatches.forEach(match => match instanceof MatchInNotebook); // assert(notebookFileMatches[0] instanceof MatchInNotebook); assert((notebookFileMatches[0] as MatchInNotebook).cell.id === 'mdInputCell'); assert((notebookFileMatches[1] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[2] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[3] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[4] as MatchInNotebook).cell.id === 'codeCell'); const mdCellMatchProcessed = (notebookFileMatches[0] as MatchInNotebook).cellParent; const codeCellMatchProcessed = (notebookFileMatches[1] as MatchInNotebook).cellParent; assert(mdCellMatchProcessed.contentMatches.length === 1); assert(codeCellMatchProcessed.contentMatches.length === 2); assert(codeCellMatchProcessed.webviewMatches.length === 2); assert(mdCellMatchProcessed.contentMatches[0] === notebookFileMatches[0]); assert(codeCellMatchProcessed.contentMatches[0] === notebookFileMatches[1]); assert(codeCellMatchProcessed.contentMatches[1] === notebookFileMatches[2]); assert(codeCellMatchProcessed.webviewMatches[0] === notebookFileMatches[3]); assert(codeCellMatchProcessed.webviewMatches[1] === notebookFileMatches[4]); assert.strictEqual(URI.file(`${getRootName()}/2`).toString(), actual[1].resource.toString()); assert.strictEqual(URI.file(`${getRootName()}/3`).toString(), actual[2].resource.toString()); }); test('Search Model: Search reports telemetry on search completed', async () => { const target = instantiationService.spy(ITelemetryService, 'publicLog'); const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(target.calledThrice); assert.ok(target.calledWith('searchResultsFirstRender')); assert.ok(target.calledWith('searchResultsFinished')); }); test('Search Model: Search reports timed telemetry on search when progress is not called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithResults([])); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); }); }); }); test('Search Model: Search reports timed telemetry on search when progress is called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithResults( [aRawMatch('/1', new TextSearchMatch('some preview', lineOneRange))], { results: [], stats: testSearchStats, messages: [] })); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { return timeout(1).then(() => { // timeout because promise handlers may run in a different order. We only care that these // are fired at some point. assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.strictEqual(1, target2.callCount); }); }); }); test('Search Model: Search reports timed telemetry on search when error is called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithError(new Error('error'))); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { }, () => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.ok(target2.calledOnce); }); }); }); test('Search Model: Search reports timed telemetry on search when error is cancelled error', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); const deferredPromise = new DeferredPromise<ISearchComplete>(); instantiationService.stub(ISearchService, 'textSearch', deferredPromise.p); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); deferredPromise.cancel(); return result.then(() => { }, () => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.ok(target2.calledOnce); }); }); }); test('Search Model: Search results are cleared during search', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(!testObject.searchResult.isEmpty()); instantiationService.stub(ISearchService, searchServiceWithResults([])); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(testObject.searchResult.isEmpty()); }); test('Search Model: Previous search is cancelled when new search is called', async () => { const tokenSource = new CancellationTokenSource(); instantiationService.stub(ISearchService, canceleableSearchService(tokenSource)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], tokenSource)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); instantiationService.stub(ISearchService, searchServiceWithResults([])); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(tokenSource.token.isCancellationRequested); }); test('getReplaceString returns proper replace string for regExpressions', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11)))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 're' }, type: QueryType.Text, folderQueries }); testObject.replaceString = 'hello'; let match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 're', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 're(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); testObject.replaceString = 'hello$1'; match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('helloe', match.replaceString); }); function aRawMatch(resource: string, ...results: ITextSearchMatch[]): IFileMatch { return { resource: createFileUriFromPathFromRoot(resource), results }; } function aRawMatchWithCells(resource: string, ...cells: ICellMatch[]) { return { resource: createFileUriFromPathFromRoot(resource), cellResults: cells }; } function stubModelService(instantiationService: TestInstantiationService): IModelService { instantiationService.stub(IThemeService, new TestThemeService()); const config = new TestConfigurationService(); config.setUserConfiguration('search', { searchOnType: true }); instantiationService.stub(IConfigurationService, config); return instantiationService.createInstance(ModelService); } function stubNotebookEditorService(instantiationService: TestInstantiationService): INotebookEditorService { instantiationService.stub(IEditorGroupsService, new TestEditorGroupsService()); return instantiationService.createInstance(NotebookEditorWidgetService); } });
src/vs/workbench/contrib/search/test/browser/searchModel.test.ts
1
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.9981762170791626, 0.10782330483198166, 0.00016306493489537388, 0.0003284746780991554, 0.28074511885643005 ]
{ "id": 1, "code_window": [ "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)),\n", "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))),\n", "\t\t\taRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))];\n", "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results));\n", "\t\tinstantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined));\n", "\n", "\t\tconst testObject: SearchModel = instantiationService.createInstance(SearchModel);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results, { limitHit: false, messages: [], results }));\n" ], "file_path": "src/vs/workbench/contrib/search/test/browser/searchModel.test.ts", "type": "replace", "edit_start_line_idx": 192 }
[ { "c": "<", "t": "text.html.derivative meta.tag.structure.html.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "html", "t": "text.html.derivative meta.tag.structure.html.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.tag.structure.html.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "type", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html entity.other.attribute-name.html", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #E50000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #E50000", "hc_black": "entity.other.attribute-name: #9CDCFE", "dark_modern": "entity.other.attribute-name: #9CDCFE", "hc_light": "entity.other.attribute-name: #264F78", "light_modern": "entity.other.attribute-name: #E50000" } }, { "c": "=", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html punctuation.separator.key-value.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html punctuation.definition.string.begin.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "text/html", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html punctuation.definition.string.end.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "\t", "t": "text.html.derivative meta.embedded.block.html text.html.basic", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "div", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "class", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html entity.other.attribute-name.html", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #E50000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #E50000", "hc_black": "entity.other.attribute-name: #9CDCFE", "dark_modern": "entity.other.attribute-name: #9CDCFE", "hc_light": "entity.other.attribute-name: #264F78", "light_modern": "entity.other.attribute-name: #E50000" } }, { "c": "=", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html punctuation.separator.key-value.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html string.quoted.single.html punctuation.definition.string.begin.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "foo", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html string.quoted.single.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html string.quoted.single.html punctuation.definition.string.end.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "</", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "div", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html text.html.basic", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "/", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "type", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html entity.other.attribute-name.html", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #E50000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #E50000", "hc_black": "entity.other.attribute-name: #9CDCFE", "dark_modern": "entity.other.attribute-name: #9CDCFE", "hc_light": "entity.other.attribute-name: #264F78", "light_modern": "entity.other.attribute-name: #E50000" } }, { "c": "=", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html punctuation.separator.key-value.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html punctuation.definition.string.begin.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "module", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html punctuation.definition.string.end.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "\t", "t": "text.html.derivative meta.embedded.block.html source.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "var", "t": "text.html.derivative meta.embedded.block.html source.js meta.var.expr.js storage.type.js", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6", "dark_modern": "storage.type: #569CD6", "hc_light": "storage.type: #0F4A85", "light_modern": "storage.type: #0000FF" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html source.js meta.var.expr.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "x", "t": "text.html.derivative meta.embedded.block.html source.js meta.var.expr.js meta.var-single-variable.expr.js meta.definition.variable.js variable.other.readwrite.js", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE", "dark_modern": "variable: #9CDCFE", "hc_light": "variable: #001080", "light_modern": "variable: #001080" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html source.js meta.var.expr.js meta.var-single-variable.expr.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "=", "t": "text.html.derivative meta.embedded.block.html source.js meta.var.expr.js keyword.operator.assignment.js", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4", "dark_modern": "keyword.operator: #D4D4D4", "hc_light": "keyword.operator: #000000", "light_modern": "keyword.operator: #000000" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html source.js meta.var.expr.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "9", "t": "text.html.derivative meta.embedded.block.html source.js meta.var.expr.js constant.numeric.decimal.js", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #098658", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #098658", "hc_black": "constant.numeric: #B5CEA8", "dark_modern": "constant.numeric: #B5CEA8", "hc_light": "constant.numeric: #096D48", "light_modern": "constant.numeric: #098658" } }, { "c": ";", "t": "text.html.derivative meta.embedded.block.html source.js punctuation.terminator.statement.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html source.js-ignored-vscode", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "/", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "type", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html entity.other.attribute-name.html", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #E50000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #E50000", "hc_black": "entity.other.attribute-name: #9CDCFE", "dark_modern": "entity.other.attribute-name: #9CDCFE", "hc_light": "entity.other.attribute-name: #264F78", "light_modern": "entity.other.attribute-name: #E50000" } }, { "c": "=", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html punctuation.separator.key-value.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html punctuation.definition.string.begin.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "text/ng-template", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.single.html punctuation.definition.string.end.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "\t", "t": "text.html.derivative meta.embedded.block.html text.html.basic", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "div", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "class", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html entity.other.attribute-name.html", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #E50000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #E50000", "hc_black": "entity.other.attribute-name: #9CDCFE", "dark_modern": "entity.other.attribute-name: #9CDCFE", "hc_light": "entity.other.attribute-name: #264F78", "light_modern": "entity.other.attribute-name: #E50000" } }, { "c": "=", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html punctuation.separator.key-value.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_modern": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_modern": "meta.embedded: #000000" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html string.quoted.single.html punctuation.definition.string.begin.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "foo", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html string.quoted.single.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html meta.attribute.class.html string.quoted.single.html punctuation.definition.string.end.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "</", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "div", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html text.html.basic meta.tag.structure.div.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html text.html.basic", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "/", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "<", "t": "text.html.derivative meta.tag.structure.body.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "body", "t": "text.html.derivative meta.tag.structure.body.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": " ", "t": "text.html.derivative meta.tag.structure.body.start.html", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_modern": "default: #CCCCCC", "hc_light": "default: #292929", "light_modern": "default: #3B3B3B" } }, { "c": "class", "t": "text.html.derivative meta.tag.structure.body.start.html meta.attribute.class.html entity.other.attribute-name.html", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #E50000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #E50000", "hc_black": "entity.other.attribute-name: #9CDCFE", "dark_modern": "entity.other.attribute-name: #9CDCFE", "hc_light": "entity.other.attribute-name: #264F78", "light_modern": "entity.other.attribute-name: #E50000" } }, { "c": "=", "t": "text.html.derivative meta.tag.structure.body.start.html meta.attribute.class.html punctuation.separator.key-value.html", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_modern": "default: #CCCCCC", "hc_light": "default: #292929", "light_modern": "default: #3B3B3B" } }, { "c": "'", "t": "text.html.derivative meta.tag.structure.body.start.html meta.attribute.class.html string.quoted.single.html punctuation.definition.string.begin.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "bar", "t": "text.html.derivative meta.tag.structure.body.start.html meta.attribute.class.html string.quoted.single.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": "'", "t": "text.html.derivative meta.tag.structure.body.start.html meta.attribute.class.html string.quoted.single.html punctuation.definition.string.end.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.single.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.single.html: #0000FF", "hc_black": "string: #CE9178", "dark_modern": "string: #CE9178", "hc_light": "string.quoted.single.html: #0F4A85", "light_modern": "string.quoted.single.html: #0000FF" } }, { "c": ">", "t": "text.html.derivative meta.tag.structure.body.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "</", "t": "text.html.derivative meta.tag.structure.body.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "body", "t": "text.html.derivative meta.tag.structure.body.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.tag.structure.body.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "</", "t": "text.html.derivative meta.tag.structure.html.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } }, { "c": "html", "t": "text.html.derivative meta.tag.structure.html.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_modern": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_modern": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.tag.structure.html.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_modern": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_modern": "punctuation.definition.tag: #800000" } } ]
extensions/vscode-colorize-tests/test/colorize-results/25920_html.json
0
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.0001773861877154559, 0.00017443577235098928, 0.0001707805786281824, 0.00017441072850488126, 0.000001690082740424259 ]
{ "id": 1, "code_window": [ "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)),\n", "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))),\n", "\t\t\taRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))];\n", "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results));\n", "\t\tinstantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined));\n", "\n", "\t\tconst testObject: SearchModel = instantiationService.createInstance(SearchModel);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results, { limitHit: false, messages: [], results }));\n" ], "file_path": "src/vs/workbench/contrib/search/test/browser/searchModel.test.ts", "type": "replace", "edit_start_line_idx": 192 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ShutdownReason, ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { ILogService } from 'vs/platform/log/common/log'; import { AbstractLifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycleService'; import { localize } from 'vs/nls'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IDisposable } from 'vs/base/common/lifecycle'; import { addDisposableListener, EventType } from 'vs/base/browser/dom'; import { IStorageService, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { CancellationToken } from 'vs/base/common/cancellation'; export class BrowserLifecycleService extends AbstractLifecycleService { private beforeUnloadListener: IDisposable | undefined = undefined; private unloadListener: IDisposable | undefined = undefined; private ignoreBeforeUnload = false; private didUnload = false; constructor( @ILogService logService: ILogService, @IStorageService storageService: IStorageService ) { super(logService, storageService); this.registerListeners(); } private registerListeners(): void { // Listen to `beforeUnload` to support to veto this.beforeUnloadListener = addDisposableListener(window, EventType.BEFORE_UNLOAD, (e: BeforeUnloadEvent) => this.onBeforeUnload(e)); // Listen to `pagehide` to support orderly shutdown // We explicitly do not listen to `unload` event // which would disable certain browser caching. // We currently do not handle the `persisted` property // (https://github.com/microsoft/vscode/issues/136216) this.unloadListener = addDisposableListener(window, EventType.PAGE_HIDE, () => this.onUnload()); } private onBeforeUnload(event: BeforeUnloadEvent): void { // Before unload ignored (once) if (this.ignoreBeforeUnload) { this.logService.info('[lifecycle] onBeforeUnload triggered but ignored once'); this.ignoreBeforeUnload = false; } // Before unload with veto support else { this.logService.info('[lifecycle] onBeforeUnload triggered and handled with veto support'); this.doShutdown(() => this.vetoBeforeUnload(event)); } } private vetoBeforeUnload(event: BeforeUnloadEvent): void { event.preventDefault(); event.returnValue = localize('lifecycleVeto', "Changes that you made may not be saved. Please check press 'Cancel' and try again."); } withExpectedShutdown(reason: ShutdownReason): Promise<void>; withExpectedShutdown(reason: { disableShutdownHandling: true }, callback: Function): void; withExpectedShutdown(reason: ShutdownReason | { disableShutdownHandling: true }, callback?: Function): Promise<void> | void { // Standard shutdown if (typeof reason === 'number') { this.shutdownReason = reason; // Ensure UI state is persisted return this.storageService.flush(WillSaveStateReason.SHUTDOWN); } // Before unload handling ignored for duration of callback else { this.ignoreBeforeUnload = true; try { callback?.(); } finally { this.ignoreBeforeUnload = false; } } } async shutdown(): Promise<void> { this.logService.info('[lifecycle] shutdown triggered'); // An explicit shutdown renders our unload // event handlers disabled, so dispose them. this.beforeUnloadListener?.dispose(); this.unloadListener?.dispose(); // Ensure UI state is persisted await this.storageService.flush(WillSaveStateReason.SHUTDOWN); // Handle shutdown without veto support this.doShutdown(); } private doShutdown(vetoShutdown?: () => void): void { const logService = this.logService; // Optimistically trigger a UI state flush // without waiting for it. The browser does // not guarantee that this is being executed // but if a dialog opens, we have a chance // to succeed. this.storageService.flush(WillSaveStateReason.SHUTDOWN); let veto = false; function handleVeto(vetoResult: boolean | Promise<boolean>, id: string) { if (typeof vetoShutdown !== 'function') { return; // veto handling disabled } if (vetoResult instanceof Promise) { logService.error(`[lifecycle] Long running operations before shutdown are unsupported in the web (id: ${id})`); veto = true; // implicitly vetos since we cannot handle promises in web } if (vetoResult === true) { logService.info(`[lifecycle]: Unload was prevented (id: ${id})`); veto = true; } } // Before Shutdown this._onBeforeShutdown.fire({ reason: ShutdownReason.QUIT, veto(value, id) { handleVeto(value, id); }, finalVeto(valueFn, id) { handleVeto(valueFn(), id); // in browser, trigger instantly because we do not support async anyway } }); // Veto: handle if provided if (veto && typeof vetoShutdown === 'function') { return vetoShutdown(); } // No veto, continue to shutdown return this.onUnload(); } private onUnload(): void { if (this.didUnload) { return; // only once } this.didUnload = true; // Register a late `pageshow` listener specifically on unload this._register(addDisposableListener(window, EventType.PAGE_SHOW, (e: PageTransitionEvent) => this.onLoadAfterUnload(e))); // First indicate will-shutdown const logService = this.logService; this._onWillShutdown.fire({ reason: ShutdownReason.QUIT, joiners: () => [], // Unsupported in web token: CancellationToken.None, // Unsupported in web join(promise, joiner) { logService.error(`[lifecycle] Long running operations during shutdown are unsupported in the web (id: ${joiner.id})`); }, force: () => { /* No-Op in web */ }, }); // Finally end with did-shutdown this._onDidShutdown.fire(); } private onLoadAfterUnload(event: PageTransitionEvent): void { // We only really care about page-show events // where the browser indicates to us that the // page was restored from cache and not freshly // loaded. const wasRestoredFromCache = event.persisted; if (!wasRestoredFromCache) { return; } // At this point, we know that the page was restored from // cache even though it was unloaded before, // so in order to get back to a functional workbench, we // currently can only reload the window // Docs: https://web.dev/bfcache/#optimize-your-pages-for-bfcache // Refs: https://github.com/microsoft/vscode/issues/136035 this.withExpectedShutdown({ disableShutdownHandling: true }, () => window.location.reload()); } } registerSingleton(ILifecycleService, BrowserLifecycleService, InstantiationType.Eager);
src/vs/workbench/services/lifecycle/browser/lifecycleService.ts
0
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.00017587783804628998, 0.0001725561887724325, 0.0001663106813794002, 0.0001729834038997069, 0.0000022750591597286984 ]
{ "id": 1, "code_window": [ "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)),\n", "\t\t\t\tnew TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))),\n", "\t\t\taRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))];\n", "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results));\n", "\t\tinstantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined));\n", "\n", "\t\tconst testObject: SearchModel = instantiationService.createInstance(SearchModel);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tinstantiationService.stub(ISearchService, searchServiceWithResults(results, { limitHit: false, messages: [], results }));\n" ], "file_path": "src/vs/workbench/contrib/search/test/browser/searchModel.test.ts", "type": "replace", "edit_start_line_idx": 192 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import * as nls from 'vs/nls'; export interface ITelemetryData { readonly from?: string; readonly target?: string; [key: string]: unknown; } export type WorkbenchActionExecutedClassification = { id: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The identifier of the action that was run.' }; from: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The name of the component the action was run from.' }; detail?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Optional details about how the action was run, e.g which keybinding was used.' }; owner: 'bpasero'; comment: 'Provides insight into actions that are executed within the workbench.'; }; export type WorkbenchActionExecutedEvent = { id: string; from: string; detail?: string; }; export interface IAction { readonly id: string; label: string; tooltip: string; class: string | undefined; enabled: boolean; checked?: boolean; run(...args: unknown[]): unknown; } export interface IActionRunner extends IDisposable { readonly onDidRun: Event<IRunEvent>; readonly onWillRun: Event<IRunEvent>; run(action: IAction, context?: unknown): unknown; } export interface IActionChangeEvent { readonly label?: string; readonly tooltip?: string; readonly class?: string; readonly enabled?: boolean; readonly checked?: boolean; } export class Action extends Disposable implements IAction { protected _onDidChange = this._register(new Emitter<IActionChangeEvent>()); readonly onDidChange = this._onDidChange.event; protected readonly _id: string; protected _label: string; protected _tooltip: string | undefined; protected _cssClass: string | undefined; protected _enabled: boolean = true; protected _checked?: boolean; protected readonly _actionCallback?: (event?: unknown) => unknown; constructor(id: string, label: string = '', cssClass: string = '', enabled: boolean = true, actionCallback?: (event?: unknown) => unknown) { super(); this._id = id; this._label = label; this._cssClass = cssClass; this._enabled = enabled; this._actionCallback = actionCallback; } get id(): string { return this._id; } get label(): string { return this._label; } set label(value: string) { this._setLabel(value); } private _setLabel(value: string): void { if (this._label !== value) { this._label = value; this._onDidChange.fire({ label: value }); } } get tooltip(): string { return this._tooltip || ''; } set tooltip(value: string) { this._setTooltip(value); } protected _setTooltip(value: string): void { if (this._tooltip !== value) { this._tooltip = value; this._onDidChange.fire({ tooltip: value }); } } get class(): string | undefined { return this._cssClass; } set class(value: string | undefined) { this._setClass(value); } protected _setClass(value: string | undefined): void { if (this._cssClass !== value) { this._cssClass = value; this._onDidChange.fire({ class: value }); } } get enabled(): boolean { return this._enabled; } set enabled(value: boolean) { this._setEnabled(value); } protected _setEnabled(value: boolean): void { if (this._enabled !== value) { this._enabled = value; this._onDidChange.fire({ enabled: value }); } } get checked(): boolean | undefined { return this._checked; } set checked(value: boolean | undefined) { this._setChecked(value); } protected _setChecked(value: boolean | undefined): void { if (this._checked !== value) { this._checked = value; this._onDidChange.fire({ checked: value }); } } async run(event?: unknown, data?: ITelemetryData): Promise<void> { if (this._actionCallback) { await this._actionCallback(event); } } } export interface IRunEvent { readonly action: IAction; readonly error?: Error; } export class ActionRunner extends Disposable implements IActionRunner { private readonly _onWillRun = this._register(new Emitter<IRunEvent>()); readonly onWillRun = this._onWillRun.event; private readonly _onDidRun = this._register(new Emitter<IRunEvent>()); readonly onDidRun = this._onDidRun.event; async run(action: IAction, context?: unknown): Promise<void> { if (!action.enabled) { return; } this._onWillRun.fire({ action }); let error: Error | undefined = undefined; try { await this.runAction(action, context); } catch (e) { error = e; } this._onDidRun.fire({ action, error }); } protected async runAction(action: IAction, context?: unknown): Promise<void> { await action.run(context); } } export class Separator implements IAction { /** * Joins all non-empty lists of actions with separators. */ public static join(...actionLists: readonly IAction[][]) { let out: IAction[] = []; for (const list of actionLists) { if (!list.length) { // skip } else if (out.length) { out = [...out, new Separator(), ...list]; } else { out = list; } } return out; } static readonly ID = 'vs.actions.separator'; readonly id: string = Separator.ID; readonly label: string = ''; readonly tooltip: string = ''; readonly class: string = 'separator'; readonly enabled: boolean = false; readonly checked: boolean = false; async run() { } } export class SubmenuAction implements IAction { readonly id: string; readonly label: string; readonly class: string | undefined; readonly tooltip: string = ''; readonly enabled: boolean = true; readonly checked: undefined = undefined; private readonly _actions: readonly IAction[]; get actions(): readonly IAction[] { return this._actions; } constructor(id: string, label: string, actions: readonly IAction[], cssClass?: string) { this.id = id; this.label = label; this.class = cssClass; this._actions = actions; } async run(): Promise<void> { } } export class EmptySubmenuAction extends Action { static readonly ID = 'vs.actions.empty'; constructor() { super(EmptySubmenuAction.ID, nls.localize('submenu.empty', '(empty)'), undefined, false); } } export function toAction(props: { id: string; label: string; enabled?: boolean; checked?: boolean; run: Function }): IAction { return { id: props.id, label: props.label, class: undefined, enabled: props.enabled ?? true, checked: props.checked ?? false, run: async () => props.run(), tooltip: props.label }; }
src/vs/base/common/actions.ts
0
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.0001799936726456508, 0.00017453763575758785, 0.0001683526352280751, 0.00017454974295105785, 0.000002124434786310303 ]
{ "id": 2, "code_window": [ "\t\t\taRawMatch('/2',\n", "\t\t\t\tnew TextSearchMatch('test', new OneLineRange(1, 1, 5)),\n", "\t\t\t\tnew TextSearchMatch('this is a test', new OneLineRange(1, 11, 15))),\n", "\t\t\taRawMatch('/3', new TextSearchMatch('test', lineOneRange))];\n", "\t\tconst searchService = instantiationService.stub(ISearchService, searchServiceWithResults(results));\n", "\t\tsinon.stub(CellMatch.prototype, 'addContext');\n", "\n", "\t\tconst textSearch = sinon.spy(searchService, 'textSearch');\n", "\t\tconst mdInputCell = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst searchService = instantiationService.stub(ISearchService, searchServiceWithResults(results, { limitHit: false, messages: [], results }));\n" ], "file_path": "src/vs/workbench/contrib/search/test/browser/searchModel.test.ts", "type": "replace", "edit_start_line_idx": 225 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as sinon from 'sinon'; import * as arrays from 'vs/base/common/arrays'; import { DeferredPromise, timeout } from 'vs/base/common/async'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; import { URI } from 'vs/base/common/uri'; import { Range } from 'vs/editor/common/core/range'; import { IModelService } from 'vs/editor/common/services/model'; import { ModelService } from 'vs/editor/common/services/modelService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, ISearchComplete, ISearchProgressItem, ISearchQuery, ISearchService, ITextSearchMatch, OneLineRange, QueryType, TextSearchMatch } from 'vs/workbench/services/search/common/search'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { CellMatch, MatchInNotebook, SearchModel } from 'vs/workbench/contrib/search/browser/searchModel'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { FileService } from 'vs/platform/files/common/fileService'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { ILabelService } from 'vs/platform/label/common/label'; import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { TestEditorGroupsService } from 'vs/workbench/test/browser/workbenchTestServices'; import { NotebookEditorWidgetService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl'; import { createFileUriFromPathFromRoot, getRootName } from 'vs/workbench/contrib/search/test/browser/searchTestCommon'; import { ICellMatch, IFileMatchWithCells, contentMatchesToTextSearchMatches, webviewMatchesToTextSearchMatches } from 'vs/workbench/contrib/search/browser/searchNotebookHelpers'; import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { FindMatch, IReadonlyTextBuffer } from 'vs/editor/common/model'; import { ResourceMap, ResourceSet } from 'vs/base/common/map'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { INotebookSearchService } from 'vs/workbench/contrib/search/browser/notebookSearch'; const nullEvent = new class { id: number = -1; topic!: string; name!: string; description!: string; data: any; startTime!: Date; stopTime!: Date; stop(): void { return; } timeTaken(): number { return -1; } }; const lineOneRange = new OneLineRange(1, 0, 1); suite('SearchModel', () => { let instantiationService: TestInstantiationService; const testSearchStats: IFileSearchStats = { fromCache: false, resultCount: 1, type: 'searchProcess', detailStats: { fileWalkTime: 0, cmdTime: 0, cmdResultCount: 0, directoriesWalked: 2, filesWalked: 3 } }; const folderQueries: IFolderQuery[] = [ { folder: createFileUriFromPathFromRoot() } ]; setup(() => { instantiationService = new TestInstantiationService(); instantiationService.stub(ITelemetryService, NullTelemetryService); instantiationService.stub(ILabelService, { getUriBasenameLabel: (uri: URI) => '' }); instantiationService.stub(INotebookService, { getNotebookTextModels: () => [] }); instantiationService.stub(IModelService, stubModelService(instantiationService)); instantiationService.stub(INotebookEditorService, stubNotebookEditorService(instantiationService)); instantiationService.stub(ISearchService, {}); instantiationService.stub(ISearchService, 'textSearch', Promise.resolve({ results: [] })); instantiationService.stub(IUriIdentityService, new UriIdentityService(new FileService(new NullLogService()))); instantiationService.stub(ILogService, new NullLogService()); }); teardown(() => sinon.restore()); function searchServiceWithResults(results: IFileMatch[], complete: ISearchComplete | null = null): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void, notebookURIs?: ResourceSet): Promise<ISearchComplete> { return new Promise(resolve => { queueMicrotask(() => { results.forEach(onProgress!); resolve(complete!); }); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return new Promise(resolve => { queueMicrotask(() => { resolve({ results: results, messages: [] }); }); }); } }; } function searchServiceWithError(error: Error): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> { return new Promise((resolve, reject) => { reject(error); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return new Promise((resolve, reject) => { queueMicrotask(() => { reject(error); }); }); } }; } function canceleableSearchService(tokenSource: CancellationTokenSource): ISearchService { return <ISearchService>{ textSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete> { token?.onCancellationRequested(() => tokenSource.cancel()); return new Promise(resolve => { queueMicrotask(() => { resolve(<any>{}); }); }); }, fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { token?.onCancellationRequested(() => tokenSource.cancel()); return new Promise(resolve => { queueMicrotask(() => { resolve(<any>{}); }); }); } }; } function notebookSearchServiceWithInfo(results: IFileMatchWithCells[], tokenSource: CancellationTokenSource | undefined): INotebookSearchService { return <INotebookSearchService>{ _serviceBrand: undefined, notebookSearch(query: ISearchQuery, token: CancellationToken, searchInstanceID: string, onProgress?: (result: ISearchProgressItem) => void, notebookURIs?: ResourceSet): Promise<{ completeData: ISearchComplete; scannedFiles: ResourceSet }> { token?.onCancellationRequested(() => tokenSource?.cancel()); const localResults = new ResourceMap<IFileMatchWithCells | null>(uri => uri.path); results.forEach(r => { localResults.set(r.resource, r); }); if (onProgress) { arrays.coalesce([...localResults.values()]).forEach(onProgress); } return Promise.resolve( { completeData: { messages: [], results: arrays.coalesce([...localResults.values()]), limitHit: false }, scannedFiles: new ResourceSet([...localResults.keys()]), }); } }; } test('Search Model: Search adds to results', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); const actual = testObject.searchResult.matches(); assert.strictEqual(2, actual.length); assert.strictEqual(URI.file(`${getRootName()}/1`).toString(), actual[0].resource.toString()); let actuaMatches = actual[0].matches(); assert.strictEqual(2, actuaMatches.length); assert.strictEqual('preview 1', actuaMatches[0].text()); assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range())); assert.strictEqual('preview 1', actuaMatches[1].text()); assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range())); actuaMatches = actual[1].matches(); assert.strictEqual(1, actuaMatches.length); assert.strictEqual('preview 2', actuaMatches[0].text()); assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range())); }); test('Search Model: Search can return notebook results', async () => { const notebookUri = createFileUriFromPathFromRoot('/1'); const results = [ aRawMatch('/2', new TextSearchMatch('test', new OneLineRange(1, 1, 5)), new TextSearchMatch('this is a test', new OneLineRange(1, 11, 15))), aRawMatch('/3', new TextSearchMatch('test', lineOneRange))]; const searchService = instantiationService.stub(ISearchService, searchServiceWithResults(results)); sinon.stub(CellMatch.prototype, 'addContext'); const textSearch = sinon.spy(searchService, 'textSearch'); const mdInputCell = { cellKind: CellKind.Markup, textBuffer: <IReadonlyTextBuffer>{ getLineContent(lineNumber: number): string { if (lineNumber === 1) { return '# Test'; } else { return ''; } } }, id: 'mdInputCell' } as ICellViewModel; const findMatchMds = [new FindMatch(new Range(1, 3, 1, 7), ['Test'])]; const codeCell = { cellKind: CellKind.Code, textBuffer: <IReadonlyTextBuffer>{ getLineContent(lineNumber: number): string { if (lineNumber === 1) { return 'print("test! testing!!")'; } else { return ''; } } }, id: 'codeCell' } as ICellViewModel; const findMatchCodeCells = [new FindMatch(new Range(1, 8, 1, 12), ['test']), new FindMatch(new Range(1, 14, 1, 18), ['test']), ]; const webviewMatches = [{ index: 0, searchPreviewInfo: { line: 'test! testing!!', range: { start: 1, end: 5 } } }, { index: 1, searchPreviewInfo: { line: 'test! testing!!', range: { start: 7, end: 11 } } } ]; const cellMatchMd: ICellMatch = { cell: mdInputCell, index: 0, contentResults: contentMatchesToTextSearchMatches(findMatchMds, mdInputCell), webviewResults: [] }; const cellMatchCode: ICellMatch = { cell: codeCell, index: 1, contentResults: contentMatchesToTextSearchMatches(findMatchCodeCells, codeCell), webviewResults: webviewMatchesToTextSearchMatches(webviewMatches), }; const notebookSearchService = instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([aRawMatchWithCells('/1', cellMatchMd, cellMatchCode)], undefined)); const notebookSearch = sinon.spy(notebookSearchService, "notebookSearch"); const model: SearchModel = instantiationService.createInstance(SearchModel); await model.search({ contentPattern: { pattern: 'test' }, type: QueryType.Text, folderQueries }); const actual = model.searchResult.matches(); assert(notebookSearch.calledOnce); assert(textSearch.getCall(0).args[3]?.size === 1); assert(textSearch.getCall(0).args[3]?.has(notebookUri)); // ensure that the textsearch knows not to re-source the notebooks assert.strictEqual(3, actual.length); assert.strictEqual(URI.file(`${getRootName()}/1`).toString(), actual[0].resource.toString()); const notebookFileMatches = actual[0].matches(); assert.ok(notebookFileMatches[0].range().equalsRange(new Range(1, 3, 1, 7))); assert.ok(notebookFileMatches[1].range().equalsRange(new Range(1, 8, 1, 12))); assert.ok(notebookFileMatches[2].range().equalsRange(new Range(1, 14, 1, 18))); assert.ok(notebookFileMatches[3].range().equalsRange(new Range(1, 2, 1, 6))); assert.ok(notebookFileMatches[4].range().equalsRange(new Range(1, 8, 1, 12))); notebookFileMatches.forEach(match => match instanceof MatchInNotebook); // assert(notebookFileMatches[0] instanceof MatchInNotebook); assert((notebookFileMatches[0] as MatchInNotebook).cell.id === 'mdInputCell'); assert((notebookFileMatches[1] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[2] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[3] as MatchInNotebook).cell.id === 'codeCell'); assert((notebookFileMatches[4] as MatchInNotebook).cell.id === 'codeCell'); const mdCellMatchProcessed = (notebookFileMatches[0] as MatchInNotebook).cellParent; const codeCellMatchProcessed = (notebookFileMatches[1] as MatchInNotebook).cellParent; assert(mdCellMatchProcessed.contentMatches.length === 1); assert(codeCellMatchProcessed.contentMatches.length === 2); assert(codeCellMatchProcessed.webviewMatches.length === 2); assert(mdCellMatchProcessed.contentMatches[0] === notebookFileMatches[0]); assert(codeCellMatchProcessed.contentMatches[0] === notebookFileMatches[1]); assert(codeCellMatchProcessed.contentMatches[1] === notebookFileMatches[2]); assert(codeCellMatchProcessed.webviewMatches[0] === notebookFileMatches[3]); assert(codeCellMatchProcessed.webviewMatches[1] === notebookFileMatches[4]); assert.strictEqual(URI.file(`${getRootName()}/2`).toString(), actual[1].resource.toString()); assert.strictEqual(URI.file(`${getRootName()}/3`).toString(), actual[2].resource.toString()); }); test('Search Model: Search reports telemetry on search completed', async () => { const target = instantiationService.spy(ITelemetryService, 'publicLog'); const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(target.calledThrice); assert.ok(target.calledWith('searchResultsFirstRender')); assert.ok(target.calledWith('searchResultsFinished')); }); test('Search Model: Search reports timed telemetry on search when progress is not called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithResults([])); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); }); }); }); test('Search Model: Search reports timed telemetry on search when progress is called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithResults( [aRawMatch('/1', new TextSearchMatch('some preview', lineOneRange))], { results: [], stats: testSearchStats, messages: [] })); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { return timeout(1).then(() => { // timeout because promise handlers may run in a different order. We only care that these // are fired at some point. assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.strictEqual(1, target2.callCount); }); }); }); test('Search Model: Search reports timed telemetry on search when error is called', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); instantiationService.stub(ISearchService, searchServiceWithError(new Error('error'))); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); return result.then(() => { }, () => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.ok(target2.calledOnce); }); }); }); test('Search Model: Search reports timed telemetry on search when error is cancelled error', () => { const target2 = sinon.spy(); sinon.stub(nullEvent, 'stop').callsFake(target2); const target1 = sinon.stub().returns(nullEvent); instantiationService.stub(ITelemetryService, 'publicLog', target1); const deferredPromise = new DeferredPromise<ISearchComplete>(); instantiationService.stub(ISearchService, 'textSearch', deferredPromise.p); const testObject = instantiationService.createInstance(SearchModel); const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); deferredPromise.cancel(); return result.then(() => { }, () => { return timeout(1).then(() => { assert.ok(target1.calledWith('searchResultsFirstRender')); assert.ok(target1.calledWith('searchResultsFinished')); // assert.ok(target2.calledOnce); }); }); }); test('Search Model: Search results are cleared during search', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11))), aRawMatch('/2', new TextSearchMatch('preview 2', lineOneRange))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(!testObject.searchResult.isEmpty()); instantiationService.stub(ISearchService, searchServiceWithResults([])); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(testObject.searchResult.isEmpty()); }); test('Search Model: Previous search is cancelled when new search is called', async () => { const tokenSource = new CancellationTokenSource(); instantiationService.stub(ISearchService, canceleableSearchService(tokenSource)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], tokenSource)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); instantiationService.stub(ISearchService, searchServiceWithResults([])); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); testObject.search({ contentPattern: { pattern: 'somestring' }, type: QueryType.Text, folderQueries }); assert.ok(tokenSource.token.isCancellationRequested); }); test('getReplaceString returns proper replace string for regExpressions', async () => { const results = [ aRawMatch('/1', new TextSearchMatch('preview 1', new OneLineRange(1, 1, 4)), new TextSearchMatch('preview 1', new OneLineRange(1, 4, 11)))]; instantiationService.stub(ISearchService, searchServiceWithResults(results)); instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); const testObject: SearchModel = instantiationService.createInstance(SearchModel); await testObject.search({ contentPattern: { pattern: 're' }, type: QueryType.Text, folderQueries }); testObject.replaceString = 'hello'; let match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 're', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 're(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('hello', match.replaceString); await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: QueryType.Text, folderQueries }); testObject.replaceString = 'hello$1'; match = testObject.searchResult.matches()[0].matches()[0]; assert.strictEqual('helloe', match.replaceString); }); function aRawMatch(resource: string, ...results: ITextSearchMatch[]): IFileMatch { return { resource: createFileUriFromPathFromRoot(resource), results }; } function aRawMatchWithCells(resource: string, ...cells: ICellMatch[]) { return { resource: createFileUriFromPathFromRoot(resource), cellResults: cells }; } function stubModelService(instantiationService: TestInstantiationService): IModelService { instantiationService.stub(IThemeService, new TestThemeService()); const config = new TestConfigurationService(); config.setUserConfiguration('search', { searchOnType: true }); instantiationService.stub(IConfigurationService, config); return instantiationService.createInstance(ModelService); } function stubNotebookEditorService(instantiationService: TestInstantiationService): INotebookEditorService { instantiationService.stub(IEditorGroupsService, new TestEditorGroupsService()); return instantiationService.createInstance(NotebookEditorWidgetService); } });
src/vs/workbench/contrib/search/test/browser/searchModel.test.ts
1
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.9984026551246643, 0.18175166845321655, 0.00016306103498209268, 0.0005012194742448628, 0.3629128634929657 ]
{ "id": 2, "code_window": [ "\t\t\taRawMatch('/2',\n", "\t\t\t\tnew TextSearchMatch('test', new OneLineRange(1, 1, 5)),\n", "\t\t\t\tnew TextSearchMatch('this is a test', new OneLineRange(1, 11, 15))),\n", "\t\t\taRawMatch('/3', new TextSearchMatch('test', lineOneRange))];\n", "\t\tconst searchService = instantiationService.stub(ISearchService, searchServiceWithResults(results));\n", "\t\tsinon.stub(CellMatch.prototype, 'addContext');\n", "\n", "\t\tconst textSearch = sinon.spy(searchService, 'textSearch');\n", "\t\tconst mdInputCell = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst searchService = instantiationService.stub(ISearchService, searchServiceWithResults(results, { limitHit: false, messages: [], results }));\n" ], "file_path": "src/vs/workbench/contrib/search/test/browser/searchModel.test.ts", "type": "replace", "edit_start_line_idx": 225 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { $ } from 'vs/base/browser/dom'; import { GridView, IView, Orientation, Sizing } from 'vs/base/browser/ui/grid/gridview'; import { nodesToArrays, TestView } from './util'; suite('Gridview', function () { let gridview: GridView; setup(function () { gridview = new GridView(); const container = $('.container'); container.style.position = 'absolute'; container.style.width = `${200}px`; container.style.height = `${200}px`; container.appendChild(gridview.element); }); test('empty gridview is empty', function () { assert.deepStrictEqual(nodesToArrays(gridview.getView()), []); gridview.dispose(); }); test('gridview addView', function () { const view = new TestView(20, 20, 20, 20); assert.throws(() => gridview.addView(view, 200, []), 'empty location'); assert.throws(() => gridview.addView(view, 200, [1]), 'index overflow'); assert.throws(() => gridview.addView(view, 200, [0, 0]), 'hierarchy overflow'); const views = [ new TestView(20, 20, 20, 20), new TestView(20, 20, 20, 20), new TestView(20, 20, 20, 20) ]; gridview.addView(views[0], 200, [0]); gridview.addView(views[1], 200, [1]); gridview.addView(views[2], 200, [2]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), views); gridview.dispose(); }); test('gridview addView nested', function () { const views = [ new TestView(20, 20, 20, 20), [ new TestView(20, 20, 20, 20), new TestView(20, 20, 20, 20) ] ]; gridview.addView(views[0] as IView, 200, [0]); gridview.addView((views[1] as TestView[])[0] as IView, 200, [1]); gridview.addView((views[1] as TestView[])[1] as IView, 200, [1, 1]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), views); gridview.dispose(); }); test('gridview addView deep nested', function () { const view1 = new TestView(20, 20, 20, 20); gridview.addView(view1 as IView, 200, [0]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1]); const view2 = new TestView(20, 20, 20, 20); gridview.addView(view2 as IView, 200, [1]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1, view2]); const view3 = new TestView(20, 20, 20, 20); gridview.addView(view3 as IView, 200, [1, 0]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1, [view3, view2]]); const view4 = new TestView(20, 20, 20, 20); gridview.addView(view4 as IView, 200, [1, 0, 0]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1, [[view4, view3], view2]]); const view5 = new TestView(20, 20, 20, 20); gridview.addView(view5 as IView, 200, [1, 0]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1, [view5, [view4, view3], view2]]); const view6 = new TestView(20, 20, 20, 20); gridview.addView(view6 as IView, 200, [2]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1, [view5, [view4, view3], view2], view6]); const view7 = new TestView(20, 20, 20, 20); gridview.addView(view7 as IView, 200, [1, 1]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1, [view5, view7, [view4, view3], view2], view6]); const view8 = new TestView(20, 20, 20, 20); gridview.addView(view8 as IView, 200, [1, 1, 0]); assert.deepStrictEqual(nodesToArrays(gridview.getView()), [view1, [view5, [view8, view7], [view4, view3], view2], view6]); gridview.dispose(); }); test('simple layout', function () { gridview.layout(800, 600); const view1 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view1, 200, [0]); assert.deepStrictEqual(view1.size, [800, 600]); assert.deepStrictEqual(gridview.getViewSize([0]), { width: 800, height: 600 }); const view2 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view2, 200, [0]); assert.deepStrictEqual(view1.size, [800, 400]); assert.deepStrictEqual(gridview.getViewSize([1]), { width: 800, height: 400 }); assert.deepStrictEqual(view2.size, [800, 200]); assert.deepStrictEqual(gridview.getViewSize([0]), { width: 800, height: 200 }); const view3 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view3, 200, [1, 1]); assert.deepStrictEqual(view1.size, [600, 400]); assert.deepStrictEqual(gridview.getViewSize([1, 0]), { width: 600, height: 400 }); assert.deepStrictEqual(view2.size, [800, 200]); assert.deepStrictEqual(gridview.getViewSize([0]), { width: 800, height: 200 }); assert.deepStrictEqual(view3.size, [200, 400]); assert.deepStrictEqual(gridview.getViewSize([1, 1]), { width: 200, height: 400 }); const view4 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view4, 200, [0, 0]); assert.deepStrictEqual(view1.size, [600, 400]); assert.deepStrictEqual(gridview.getViewSize([1, 0]), { width: 600, height: 400 }); assert.deepStrictEqual(view2.size, [600, 200]); assert.deepStrictEqual(gridview.getViewSize([0, 1]), { width: 600, height: 200 }); assert.deepStrictEqual(view3.size, [200, 400]); assert.deepStrictEqual(gridview.getViewSize([1, 1]), { width: 200, height: 400 }); assert.deepStrictEqual(view4.size, [200, 200]); assert.deepStrictEqual(gridview.getViewSize([0, 0]), { width: 200, height: 200 }); const view5 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view5, 100, [1, 0, 1]); assert.deepStrictEqual(view1.size, [600, 300]); assert.deepStrictEqual(gridview.getViewSize([1, 0, 0]), { width: 600, height: 300 }); assert.deepStrictEqual(view2.size, [600, 200]); assert.deepStrictEqual(gridview.getViewSize([0, 1]), { width: 600, height: 200 }); assert.deepStrictEqual(view3.size, [200, 400]); assert.deepStrictEqual(gridview.getViewSize([1, 1]), { width: 200, height: 400 }); assert.deepStrictEqual(view4.size, [200, 200]); assert.deepStrictEqual(gridview.getViewSize([0, 0]), { width: 200, height: 200 }); assert.deepStrictEqual(view5.size, [600, 100]); assert.deepStrictEqual(gridview.getViewSize([1, 0, 1]), { width: 600, height: 100 }); }); test('simple layout with automatic size distribution', function () { gridview.layout(800, 600); const view1 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view1, Sizing.Distribute, [0]); assert.deepStrictEqual(view1.size, [800, 600]); assert.deepStrictEqual(gridview.getViewSize([0]), { width: 800, height: 600 }); const view2 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view2, Sizing.Distribute, [0]); assert.deepStrictEqual(view1.size, [800, 300]); assert.deepStrictEqual(view2.size, [800, 300]); const view3 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view3, Sizing.Distribute, [1, 1]); assert.deepStrictEqual(view1.size, [400, 300]); assert.deepStrictEqual(view2.size, [800, 300]); assert.deepStrictEqual(view3.size, [400, 300]); const view4 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view4, Sizing.Distribute, [0, 0]); assert.deepStrictEqual(view1.size, [400, 300]); assert.deepStrictEqual(view2.size, [400, 300]); assert.deepStrictEqual(view3.size, [400, 300]); assert.deepStrictEqual(view4.size, [400, 300]); const view5 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view5, Sizing.Distribute, [1, 0, 1]); assert.deepStrictEqual(view1.size, [400, 150]); assert.deepStrictEqual(view2.size, [400, 300]); assert.deepStrictEqual(view3.size, [400, 300]); assert.deepStrictEqual(view4.size, [400, 300]); assert.deepStrictEqual(view5.size, [400, 150]); }); test('addviews before layout call 1', function () { const view1 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view1, 200, [0]); const view2 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view2, 200, [0]); const view3 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view3, 200, [1, 1]); gridview.layout(800, 600); assert.deepStrictEqual(view1.size, [400, 300]); assert.deepStrictEqual(view2.size, [800, 300]); assert.deepStrictEqual(view3.size, [400, 300]); }); test('addviews before layout call 2', function () { const view1 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view1, 200, [0]); const view2 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view2, 200, [0]); const view3 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view3, 200, [0, 0]); gridview.layout(800, 600); assert.deepStrictEqual(view1.size, [800, 300]); assert.deepStrictEqual(view2.size, [400, 300]); assert.deepStrictEqual(view3.size, [400, 300]); }); test('flipping orientation should preserve absolute offsets', function () { const view1 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view1, 200, [0]); const view2 = new TestView(50, Number.POSITIVE_INFINITY, 50, Number.POSITIVE_INFINITY); gridview.addView(view2, 200, [1]); gridview.layout(800, 600, 100, 200); assert.deepStrictEqual([view1.top, view1.left], [100, 200]); assert.deepStrictEqual([view2.top, view2.left], [100 + 300, 200]); gridview.orientation = Orientation.HORIZONTAL; assert.deepStrictEqual([view1.top, view1.left], [100, 200]); assert.deepStrictEqual([view2.top, view2.left], [100, 200 + 400]); }); });
src/vs/base/test/browser/ui/grid/gridview.test.ts
0
https://github.com/microsoft/vscode/commit/2bf46260dca5d91b7ac6a1933f37ef25dc0368ca
[ 0.00017742865020409226, 0.00017482369730714709, 0.00017127192404586822, 0.000175016131834127, 0.0000015018088106444338 ]