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": 11, "code_window": [ "test('refresh button', async () => {\n", " render(<ApiReport />)\n", " await waitFor(() => expect(get).toBeCalled())\n", " get.mockReset()\n", " userEvent.click(await screen.findByText(/Refresh/))\n", " await waitFor(() => expect(get).toBeCalled())\n", "})" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(screen.findByText(/Refreshing/)).resolves.toThrow()\n" ], "file_path": "studio/tests/pages/projects/reports/api-report.test.js", "type": "add", "edit_start_line_idx": 24 }
import { useRouter } from 'next/router' import { useEffect } from 'react' import RefEducationSection from '~/components/reference/RefEducationSection' import RefFunctionSection from '~/components/reference/RefFunctionSection' import RefSubLayout from '~/layouts/ref/RefSubLayout' import ApiOperationSection from './ApiOperationSection' import CliCommandSection from './CLICommandSection' import { IAPISpec, ICommonFunc, IRefStaticDoc, ISpec, TypeSpec } from './Reference.types' interface RefSectionHandlerProps { sections: ICommonFunc[] spec?: ISpec | IAPISpec typeSpec?: TypeSpec pageProps: { docs: IRefStaticDoc[] } type: 'client-lib' | 'cli' | 'api' } const RefSectionHandler = (props: RefSectionHandlerProps) => { const router = useRouter() const slug = router.query.slug[0] // When user lands on a url like http://supabase.com/docs/reference/javascript/sign-up // find the #sign-up element and scroll to that useEffect(() => { if (document && slug !== 'start') { document.querySelector(`#${slug}`) && document.querySelector(`#${slug}`).scrollIntoView() } }) return ( <RefSubLayout> {props.sections.map((x, i) => { switch (x.type) { case 'markdown': const markdownData = props.pageProps.docs.find((doc) => doc.id === x.id) return <RefEducationSection key={x.id + i} item={x} markdownContent={markdownData} /> break case 'function': return ( <RefFunctionSection key={x.id + i} funcData={x} commonFuncData={x} spec={props.spec} typeSpec={props.typeSpec} /> ) case 'cli-command': return <CliCommandSection key={x.id + i} funcData={x} commonFuncData={x} /> break case 'operation': return ( <ApiOperationSection key={x.id + i} funcData={x} commonFuncData={x} spec={props.spec} /> ) default: return ( <RefFunctionSection key={x.id + i} funcData={x} commonFuncData={x} spec={props.spec} typeSpec={props.typeSpec} /> ) break } })} </RefSubLayout> ) } export default RefSectionHandler
apps/docs/components/reference/RefSectionHandler.tsx
0
https://github.com/supabase/supabase/commit/cea06f9ad73769533866782557bf9840dcf10123
[ 0.0001762792671797797, 0.0001718425628496334, 0.00016757825505919755, 0.00017251924145966768, 0.0000029981511033838615 ]
{ "id": 11, "code_window": [ "test('refresh button', async () => {\n", " render(<ApiReport />)\n", " await waitFor(() => expect(get).toBeCalled())\n", " get.mockReset()\n", " userEvent.click(await screen.findByText(/Refresh/))\n", " await waitFor(() => expect(get).toBeCalled())\n", "})" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(screen.findByText(/Refreshing/)).resolves.toThrow()\n" ], "file_path": "studio/tests/pages/projects/reports/api-report.test.js", "type": "add", "edit_start_line_idx": 24 }
import { Organization } from 'types' import { IRootStore } from '../RootStore' import PostgresMetaInterface from '../common/PostgresMetaInterface' export default class OrganizationStore extends PostgresMetaInterface<Organization> { constructor( rootStore: IRootStore, dataUrl: string, headers?: { [prop: string]: any }, options?: { identifier: string } ) { super(rootStore, dataUrl, headers, options) } }
studio/stores/app/OrganizationStore.ts
0
https://github.com/supabase/supabase/commit/cea06f9ad73769533866782557bf9840dcf10123
[ 0.0001757422141963616, 0.00017558099352754653, 0.00017541978741064668, 0.00017558099352754653, 1.6121339285746217e-7 ]
{ "id": 0, "code_window": [ "a {\n", "\tcolor: #4080D0;\n", "\ttext-decoration: none;\n", "}\n", "\n", "hr {\n", "\tborder: 0;\n", "\theight: 2px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "a:focus,\n", "input:focus,\n", "select:focus,\n", "textarea:focus {\n", "\toutline: 2px auto -webkit-focus-ring-color;\n", "\toutline-offset: -2px;\n", "}\n", "\n" ], "file_path": "src/vs/languages/markdown/common/markdown.css", "type": "add", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/iframeeditor'; import nls = require('vs/nls'); import {Promise, TPromise} from 'vs/base/common/winjs.base'; import URI from 'vs/base/common/uri'; import {Dimension, Builder, $} from 'vs/base/browser/builder'; import DOM = require('vs/base/browser/dom'); import errors = require('vs/base/common/errors'); import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {EditorInputAction, BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {IFrameEditorInput} from 'vs/workbench/common/editor/iframeEditorInput'; import {IFrameEditorModel} from 'vs/workbench/common/editor/iframeEditorModel'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class IFrameEditor extends BaseEditor { public static ID = 'workbench.editors.iFrameEditor'; private static RESOURCE_PROPERTY = 'resource'; private iframeContainer: Builder; private iframeBuilder: Builder; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IStorageService private storageService: IStorageService ) { super(IFrameEditor.ID, telemetryService); } public getTitle(): string { return this.getInput() ? this.getInput().getName() : nls.localize('iframeEditor', "IFrame Viewer"); } public createEditor(parent: Builder): void { // Container for IFrame let iframeContainerElement = document.createElement('div'); iframeContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme this.iframeContainer = $(iframeContainerElement); this.iframeContainer.tabindex(0); // enable focus support // IFrame this.iframeBuilder = $(this.iframeContainer).element('iframe').addClass('iframe'); this.iframeBuilder.attr({ 'frameborder': '0' }); this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); parent.getHTMLElement().appendChild(iframeContainerElement); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { let oldInput = this.getInput(); super.setInput(input, options); // Detect options let forceOpen = options && options.forceOpen; // Same Input if (!forceOpen && input.matches(oldInput)) { return TPromise.as<void>(null); } // Assert Input if (!(input instanceof IFrameEditorInput)) { return TPromise.wrapError<void>('Invalid editor input. IFrame editor requires an input instance of IFrameEditorInput.'); } // Different Input (Reload) return this.doSetInput(input, true /* isNewInput */); } private doSetInput(input: EditorInput, isNewInput?: boolean): TPromise<void> { return this.editorService.resolveEditorModel(input, true /* Reload */).then((resolvedModel) => { // Assert Model interface if (!(resolvedModel instanceof IFrameEditorModel)) { return TPromise.wrapError<void>('Invalid editor input. IFrame editor requires a model instance of IFrameEditorModel.'); } // Assert that the current input is still the one we expect. This prevents a race condition when loading takes long and another input was set meanwhile if (!this.getInput() || this.getInput() !== input) { return null; } // Set IFrame contents let iframeModel = <IFrameEditorModel>resolvedModel; let isUpdate = !isNewInput && !!this.iframeBuilder.getProperty(IFrameEditor.RESOURCE_PROPERTY); let contents = iframeModel.getContents(); // Crazy hack to get keybindings to bubble out of the iframe to us contents.body = contents.body + this.enableKeybindings(); // Set Contents try { this.setFrameContents(iframeModel.resource, isUpdate ? contents.body : [contents.head, contents.body, contents.tail].join('\n'), isUpdate /* body only */); } catch (error) { setTimeout(() => this.reload(true /* clear */), 1000); // retry in case of an error which indicates the iframe (only) might be on a different URL } }); } private setFrameContents(resource: URI, contents: string, isUpdate: boolean): void { let iframeWindow = (<HTMLIFrameElement>this.iframeBuilder.getHTMLElement()).contentWindow; // Update body only if this is an update of the same resource (preserves scroll position and does not flicker) if (isUpdate) { iframeWindow.document.body.innerHTML = contents; } // Write directly to iframe document replacing any previous content else { iframeWindow.document.open('text/html', 'replace'); iframeWindow.document.write(contents); iframeWindow.document.close(); // Reset scroll iframeWindow.scrollTo(0, 0); // Associate resource with iframe this.iframeBuilder.setProperty(IFrameEditor.RESOURCE_PROPERTY, resource.toString()); } } private enableKeybindings(): string { return [ '<script>', 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [67 /* c */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', '</script>' ].join('\n'); } public clearInput(): void { // Reset IFrame this.clearIFrame(); super.clearInput(); } private clearIFrame(): void { this.iframeBuilder.src('about:blank'); this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); } public layout(dimension: Dimension): void { // Pass on to IFrame Container and IFrame this.iframeContainer.size(dimension.width, dimension.height); this.iframeBuilder.size(dimension.width, dimension.height); } public focus(): void { this.iframeContainer.domFocus(); } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => this.reload(true)); } public supportsSplitEditor(): boolean { return true; } /** * Reloads the contents of the iframe in this editor by reapplying the input. */ public reload(clearIFrame?: boolean): void { if (this.input) { if (clearIFrame) { this.clearIFrame(); } this.doSetInput(this.input).done(null, errors.onUnexpectedError); } } public dispose(): void { // Destroy Container this.iframeContainer.destroy(); super.dispose(); } }
src/vs/workbench/browser/parts/editor/iframeEditor.ts
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017488251614850014, 0.00016964567475952208, 0.00016438595775980502, 0.00016917710308916867, 0.000003041704303541337 ]
{ "id": 0, "code_window": [ "a {\n", "\tcolor: #4080D0;\n", "\ttext-decoration: none;\n", "}\n", "\n", "hr {\n", "\tborder: 0;\n", "\theight: 2px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "a:focus,\n", "input:focus,\n", "select:focus,\n", "textarea:focus {\n", "\toutline: 2px auto -webkit-focus-ring-color;\n", "\toutline-offset: -2px;\n", "}\n", "\n" ], "file_path": "src/vs/languages/markdown/common/markdown.css", "type": "add", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*global require, ts */ require.config({ shim: { 'vs/languages/typescript/common/lib/raw.typescriptServices': { exports: function () { return this.ts; } } } }); define(['./raw.typescriptServices', 'vs/text!./lib.d.ts'], function (ts) { return ts; });
src/vs/languages/typescript/common/lib/typescriptServices.js
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.0001763066538842395, 0.00017239339649677277, 0.0001684801245573908, 0.00017239339649677277, 0.000003913264663424343 ]
{ "id": 0, "code_window": [ "a {\n", "\tcolor: #4080D0;\n", "\ttext-decoration: none;\n", "}\n", "\n", "hr {\n", "\tborder: 0;\n", "\theight: 2px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "a:focus,\n", "input:focus,\n", "select:focus,\n", "textarea:focus {\n", "\toutline: 2px auto -webkit-focus-ring-color;\n", "\toutline-offset: -2px;\n", "}\n", "\n" ], "file_path": "src/vs/languages/markdown/common/markdown.css", "type": "add", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import types = require('vs/base/common/types'); import {ICodeEditor} from 'vs/editor/browser/editorBrowser'; import {IEditorOptions, IEditorViewState} from 'vs/editor/common/editorCommon'; import {DefaultConfig} from 'vs/editor/common/config/defaultConfig'; import {EditorConfiguration} from 'vs/editor/common/config/commonEditorConfig'; import {TextEditorOptions, EditorModel, EditorInput, EditorOptions} from 'vs/workbench/common/editor'; import {BaseTextEditorModel} from 'vs/workbench/common/editor/textEditorModel'; import {LogEditorInput} from 'vs/workbench/common/editor/logEditorInput'; import {UntitledEditorInput} from 'vs/workbench/common/editor/untitledEditorInput'; import {BaseTextEditor} from 'vs/workbench/browser/parts/editor/textEditor'; import {UntitledEditorEvent, EventType} from 'vs/workbench/common/events'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService'; import {IStorageService} from 'vs/platform/storage/common/storage'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IEventService} from 'vs/platform/event/common/event'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IMessageService} from 'vs/platform/message/common/message'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IModeService} from 'vs/editor/common/services/modeService'; /** * An editor implementation that is capable of showing string inputs or promise inputs that resolve to a string. * Uses the Monaco TextEditor widget to show the contents. */ export class StringEditor extends BaseTextEditor { public static ID = 'workbench.editors.stringEditor'; private defaultWrappingColumn: number; private defaultLineNumbers: boolean; private mapResourceToEditorViewState: { [resource: string]: IEditorViewState; }; constructor( @ITelemetryService telemetryService: ITelemetryService, @IInstantiationService instantiationService: IInstantiationService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IStorageService storageService: IStorageService, @IMessageService messageService: IMessageService, @IConfigurationService configurationService: IConfigurationService, @IEventService eventService: IEventService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IModeService modeService: IModeService ) { super(StringEditor.ID, telemetryService, instantiationService, contextService, storageService, messageService, configurationService, eventService, editorService, modeService); this.defaultWrappingColumn = DefaultConfig.editor.wrappingColumn; this.defaultLineNumbers = DefaultConfig.editor.lineNumbers; this.mapResourceToEditorViewState = Object.create(null); this.toUnbind.push(this.eventService.addListener(EventType.UNTITLED_FILE_DELETED, (e: UntitledEditorEvent) => this.onUntitledDeletedEvent(e))); } private onUntitledDeletedEvent(e: UntitledEditorEvent): void { delete this.mapResourceToEditorViewState[e.resource.toString()]; } public getTitle(): string { if (this.input) { return this.input.getName(); } return nls.localize('textEditor', "Text Editor"); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { let oldInput = this.getInput(); super.setInput(input, options); // Detect options let forceOpen = options && options.forceOpen; // Same Input if (!forceOpen && input.matches(oldInput)) { // TextOptions (avoiding instanceof here for a reason, do not change!) let textOptions = <TextEditorOptions>options; if (textOptions && types.isFunction(textOptions.apply)) { textOptions.apply(this.getControl()); } return TPromise.as<void>(null); } // Remember view settings if input changes if (oldInput instanceof UntitledEditorInput) { this.mapResourceToEditorViewState[oldInput.getResource().toString()] = this.getControl().saveViewState(); } // Different Input (Reload) return this.editorService.resolveEditorModel(input, true /* Reload */).then((resolvedModel: EditorModel) => { // Assert Model instance if (!(resolvedModel instanceof BaseTextEditorModel)) { return TPromise.wrapError<void>('Invalid editor input. String editor requires a model instance of BaseTextEditorModel.'); } // Assert that the current input is still the one we expect. This prevents a race condition when loading takes long and another input was set meanwhile if (!this.getInput() || this.getInput() !== input) { return null; } // Set Editor Model let textEditor = this.getControl(); let textEditorModel = (<BaseTextEditorModel>resolvedModel).textEditorModel; textEditor.setModel(textEditorModel); // Apply Options from TextOptions let optionsGotApplied = false; let textOptions = <TextEditorOptions>options; if (textOptions && types.isFunction(textOptions.apply)) { optionsGotApplied = textOptions.apply(textEditor); } // Otherwise restore View State if (!optionsGotApplied && input instanceof UntitledEditorInput) { let viewState = this.mapResourceToEditorViewState[input.getResource().toString()]; if (viewState) { textEditor.restoreViewState(viewState); } } // Apply options again because input has changed textEditor.updateOptions(this.getCodeEditorOptions()); // Auto reveal last line for log editors if (input instanceof LogEditorInput) { this.revealLastLine(); } }); } protected applyConfiguration(configuration: any): void { // Remember some settings that we overwrite from #getCodeEditorOptions() let editorConfig = configuration && configuration[EditorConfiguration.EDITOR_SECTION]; if (editorConfig) { this.defaultWrappingColumn = editorConfig.wrappingColumn; this.defaultLineNumbers = editorConfig.lineNumbers; } super.applyConfiguration(configuration); } protected getCodeEditorOptions(): IEditorOptions { let options = super.getCodeEditorOptions(); let input = this.getInput(); let isLog = input instanceof LogEditorInput; let isUntitled = input instanceof UntitledEditorInput; options.readOnly = !isUntitled; // all string editors are readonly except for the untitled one if (isLog) { options.wrappingColumn = 0; // all log editors wrap options.lineNumbers = false; // all log editors hide line numbers } else { options.wrappingColumn = this.defaultWrappingColumn; // otherwise make sure to restore the defaults options.lineNumbers = this.defaultLineNumbers; // otherwise make sure to restore the defaults } return options; } /** * Reveals the last line of this editor if it has a model set. */ public revealLastLine(): void { let codeEditor = <ICodeEditor>this.getControl(); let model = codeEditor.getModel(); if (model) { let lastLine = model.getLineCount(); codeEditor.revealLine(lastLine); } } public supportsSplitEditor(): boolean { return true; } public focus(): void { super.focus(); // Auto reveal last line for log editors if (this.getInput() instanceof LogEditorInput) { this.revealLastLine(); } } public clearInput(): void { // Keep editor view state in settings to restore when coming back if (this.input instanceof UntitledEditorInput) { this.mapResourceToEditorViewState[(<UntitledEditorInput>this.input).getResource().toString()] = this.getControl().saveViewState(); } // Clear Model this.getControl().setModel(null); super.clearInput(); } }
src/vs/workbench/browser/parts/editor/stringEditor.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017802398360799998, 0.0001706992188701406, 0.00016625915304757655, 0.00017080752877518535, 0.000002820912186507485 ]
{ "id": 0, "code_window": [ "a {\n", "\tcolor: #4080D0;\n", "\ttext-decoration: none;\n", "}\n", "\n", "hr {\n", "\tborder: 0;\n", "\theight: 2px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "a:focus,\n", "input:focus,\n", "select:focus,\n", "textarea:focus {\n", "\toutline: 2px auto -webkit-focus-ring-color;\n", "\toutline-offset: -2px;\n", "}\n", "\n" ], "file_path": "src/vs/languages/markdown/common/markdown.css", "type": "add", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {OverviewRulerImpl} from 'vs/editor/browser/viewParts/overviewRuler/overviewRulerImpl'; import {ViewEventHandler} from 'vs/editor/common/viewModel/viewEventHandler'; import EditorBrowser = require('vs/editor/browser/editorBrowser'); import EditorCommon = require('vs/editor/common/editorCommon'); export class OverviewRuler extends ViewEventHandler implements EditorBrowser.IOverviewRuler { private _context:EditorBrowser.IViewContext; private _overviewRuler:OverviewRulerImpl; constructor(context:EditorBrowser.IViewContext, cssClassName:string, scrollHeight:number, minimumHeight:number, maximumHeight:number, getVerticalOffsetForLine:(lineNumber:number)=>number) { super(); this._context = context; this._overviewRuler = new OverviewRulerImpl(0, cssClassName, scrollHeight, this._context.configuration.editor.lineHeight, minimumHeight, maximumHeight, getVerticalOffsetForLine); this._context.addEventHandler(this); } public destroy(): void { this.dispose(); } public dispose(): void { this._context.removeEventHandler(this); this._overviewRuler.dispose(); } public onConfigurationChanged(e:EditorCommon.IConfigurationChangedEvent): boolean { if (e.lineHeight) { this._overviewRuler.setLineHeight(this._context.configuration.editor.lineHeight, true); return true; } return false; } public onZonesChanged(): boolean { return true; } public onModelFlushed(): boolean { return true; } public onScrollHeightChanged(scrollHeight:number): boolean { this._overviewRuler.setScrollHeight(scrollHeight, true); return true; } public getDomNode(): HTMLElement { return this._overviewRuler.getDomNode(); } public setLayout(position:EditorCommon.IOverviewRulerPosition): void { this._overviewRuler.setLayout(position, true); } public setZones(zones:EditorBrowser.IOverviewRulerZone[]): void { this._overviewRuler.setZones(zones, true); } }
src/vs/editor/browser/viewParts/overviewRuler/overviewRuler.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.0002060062251985073, 0.0001761790772434324, 0.00016791959933470935, 0.00017048674635589123, 0.000012541379874164704 ]
{ "id": 1, "code_window": [ "\tprivate enableKeybindings(): string {\n", "\t\treturn [\n", "\t\t\t'<script>',\n", "\t\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t\t'\ttry {',\n", "\t\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/iframeeditor'; import nls = require('vs/nls'); import {Promise, TPromise} from 'vs/base/common/winjs.base'; import URI from 'vs/base/common/uri'; import {Dimension, Builder, $} from 'vs/base/browser/builder'; import DOM = require('vs/base/browser/dom'); import errors = require('vs/base/common/errors'); import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {EditorInputAction, BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {IFrameEditorInput} from 'vs/workbench/common/editor/iframeEditorInput'; import {IFrameEditorModel} from 'vs/workbench/common/editor/iframeEditorModel'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class IFrameEditor extends BaseEditor { public static ID = 'workbench.editors.iFrameEditor'; private static RESOURCE_PROPERTY = 'resource'; private iframeContainer: Builder; private iframeBuilder: Builder; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IStorageService private storageService: IStorageService ) { super(IFrameEditor.ID, telemetryService); } public getTitle(): string { return this.getInput() ? this.getInput().getName() : nls.localize('iframeEditor', "IFrame Viewer"); } public createEditor(parent: Builder): void { // Container for IFrame let iframeContainerElement = document.createElement('div'); iframeContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme this.iframeContainer = $(iframeContainerElement); this.iframeContainer.tabindex(0); // enable focus support // IFrame this.iframeBuilder = $(this.iframeContainer).element('iframe').addClass('iframe'); this.iframeBuilder.attr({ 'frameborder': '0' }); this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); parent.getHTMLElement().appendChild(iframeContainerElement); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { let oldInput = this.getInput(); super.setInput(input, options); // Detect options let forceOpen = options && options.forceOpen; // Same Input if (!forceOpen && input.matches(oldInput)) { return TPromise.as<void>(null); } // Assert Input if (!(input instanceof IFrameEditorInput)) { return TPromise.wrapError<void>('Invalid editor input. IFrame editor requires an input instance of IFrameEditorInput.'); } // Different Input (Reload) return this.doSetInput(input, true /* isNewInput */); } private doSetInput(input: EditorInput, isNewInput?: boolean): TPromise<void> { return this.editorService.resolveEditorModel(input, true /* Reload */).then((resolvedModel) => { // Assert Model interface if (!(resolvedModel instanceof IFrameEditorModel)) { return TPromise.wrapError<void>('Invalid editor input. IFrame editor requires a model instance of IFrameEditorModel.'); } // Assert that the current input is still the one we expect. This prevents a race condition when loading takes long and another input was set meanwhile if (!this.getInput() || this.getInput() !== input) { return null; } // Set IFrame contents let iframeModel = <IFrameEditorModel>resolvedModel; let isUpdate = !isNewInput && !!this.iframeBuilder.getProperty(IFrameEditor.RESOURCE_PROPERTY); let contents = iframeModel.getContents(); // Crazy hack to get keybindings to bubble out of the iframe to us contents.body = contents.body + this.enableKeybindings(); // Set Contents try { this.setFrameContents(iframeModel.resource, isUpdate ? contents.body : [contents.head, contents.body, contents.tail].join('\n'), isUpdate /* body only */); } catch (error) { setTimeout(() => this.reload(true /* clear */), 1000); // retry in case of an error which indicates the iframe (only) might be on a different URL } }); } private setFrameContents(resource: URI, contents: string, isUpdate: boolean): void { let iframeWindow = (<HTMLIFrameElement>this.iframeBuilder.getHTMLElement()).contentWindow; // Update body only if this is an update of the same resource (preserves scroll position and does not flicker) if (isUpdate) { iframeWindow.document.body.innerHTML = contents; } // Write directly to iframe document replacing any previous content else { iframeWindow.document.open('text/html', 'replace'); iframeWindow.document.write(contents); iframeWindow.document.close(); // Reset scroll iframeWindow.scrollTo(0, 0); // Associate resource with iframe this.iframeBuilder.setProperty(IFrameEditor.RESOURCE_PROPERTY, resource.toString()); } } private enableKeybindings(): string { return [ '<script>', 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [67 /* c */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', '</script>' ].join('\n'); } public clearInput(): void { // Reset IFrame this.clearIFrame(); super.clearInput(); } private clearIFrame(): void { this.iframeBuilder.src('about:blank'); this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); } public layout(dimension: Dimension): void { // Pass on to IFrame Container and IFrame this.iframeContainer.size(dimension.width, dimension.height); this.iframeBuilder.size(dimension.width, dimension.height); } public focus(): void { this.iframeContainer.domFocus(); } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => this.reload(true)); } public supportsSplitEditor(): boolean { return true; } /** * Reloads the contents of the iframe in this editor by reapplying the input. */ public reload(clearIFrame?: boolean): void { if (this.input) { if (clearIFrame) { this.clearIFrame(); } this.doSetInput(this.input).done(null, errors.onUnexpectedError); } } public dispose(): void { // Destroy Container this.iframeContainer.destroy(); super.dispose(); } }
src/vs/workbench/browser/parts/editor/iframeEditor.ts
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.9987989664077759, 0.11558438092470169, 0.00016151298768818378, 0.00017243807087652385, 0.31881996989250183 ]
{ "id": 1, "code_window": [ "\tprivate enableKeybindings(): string {\n", "\t\treturn [\n", "\t\t\t'<script>',\n", "\t\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t\t'\ttry {',\n", "\t\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var es = require('event-stream'); function handleDeletions() { return es.mapSync(function (f) { if (!f.contents) { f.contents = new Buffer(''); f.stat = { mtime: new Date() }; } return f; }); } var watch = process.platform === 'win32' ? require('./watch-win32') : require('gulp-watch'); module.exports = function () { return watch.apply(null, arguments) .pipe(handleDeletions()); };
build/lib/watch/index.js
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.0001749352231854573, 0.00017017840582411736, 0.0001639562688069418, 0.00017164369637612253, 0.000004600339707394596 ]
{ "id": 1, "code_window": [ "\tprivate enableKeybindings(): string {\n", "\t\treturn [\n", "\t\t\t'<script>',\n", "\t\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t\t'\ttry {',\n", "\t\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 141 }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>comment</key> <string>http://chriskempson.com</string> <key>name</key> <string>Tomorrow Night - Blue</string> <key>settings</key> <array> <dict> <key>settings</key> <dict> <key>background</key> <string>#002451</string> <key>caret</key> <string>#FFFFFF</string> <key>foreground</key> <string>#FFFFFF</string> <key>invisibles</key> <string>#404F7D</string> <key>lineHighlight</key> <string>#00346E</string> <key>selection</key> <string>#003F8E</string> </dict> </dict> <dict> <key>name</key> <string>Comment</string> <key>scope</key> <string>comment</string> <key>settings</key> <dict> <key>foreground</key> <string>#7285B7</string> </dict> </dict> <dict> <key>name</key> <string>Foreground, Operator</string> <key>scope</key> <string>keyword.operator.class, keyword.operator, constant.other, source.php.embedded.line</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#FFFFFF</string> </dict> </dict> <dict> <key>name</key> <string>Variable, String Link, Regular Expression, Tag Name, GitGutter deleted</string> <key>scope</key> <string>variable, support.other.variable, string.other.link, string.regexp, entity.name.tag, entity.other.attribute-name, meta.tag, declaration.tag, markup.deleted.git_gutter</string> <key>settings</key> <dict> <key>foreground</key> <string>#FF9DA4</string> </dict> </dict> <dict> <key>name</key> <string>Number, Constant, Function Argument, Tag Attribute, Embedded</string> <key>scope</key> <string>constant.numeric, constant.language, support.constant, constant.character, variable.parameter, punctuation.section.embedded, keyword.other.unit</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#FFC58F</string> </dict> </dict> <dict> <key>name</key> <string>Class, Support</string> <key>scope</key> <string>entity.name.class, entity.name.type.class, support.type, support.class</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#FFEEAD</string> </dict> </dict> <dict> <key>name</key> <string>String, Symbols, Inherited Class, Markup Heading, GitGutter inserted</string> <key>scope</key> <string>string, constant.other.symbol, entity.other.inherited-class, markup.heading, markup.inserted.git_gutter</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#D1F1A9</string> </dict> </dict> <dict> <key>name</key> <string>Operator, Misc</string> <key>scope</key> <string>keyword.operator, constant.other.color</string> <key>settings</key> <dict> <key>foreground</key> <string>#99FFFF</string> </dict> </dict> <dict> <key>name</key> <string>Function, Special Method, Block Level, GitGutter changed</string> <key>scope</key> <string>entity.name.function, meta.function-call, support.function, keyword.other.special-method, meta.block-level, markup.changed.git_gutter</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#BBDAFF</string> </dict> </dict> <dict> <key>name</key> <string>Keyword, Storage</string> <key>scope</key> <string>keyword, storage, storage.type, entity.name.tag.css</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#EBBBFF</string> </dict> </dict> <dict> <key>name</key> <string>Invalid</string> <key>scope</key> <string>invalid</string> <key>settings</key> <dict> <key>background</key> <string>#F99DA5</string> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#FFFFFF</string> </dict> </dict> <dict> <key>name</key> <string>Separator</string> <key>scope</key> <string>meta.separator</string> <key>settings</key> <dict> <key>background</key> <string>#BBDAFE</string> <key>foreground</key> <string>#FFFFFF</string> </dict> </dict> <dict> <key>name</key> <string>Deprecated</string> <key>scope</key> <string>invalid.deprecated</string> <key>settings</key> <dict> <key>background</key> <string>#EBBBFF</string> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#FFFFFF</string> </dict> </dict> <dict> <key>name</key> <string>Diff foreground</string> <key>scope</key> <string>markup.inserted.diff, markup.deleted.diff, meta.diff.header.to-file, meta.diff.header.from-file</string> <key>settings</key> <dict> <key>foreground</key> <string>#FFFFFF</string> </dict> </dict> <dict> <key>name</key> <string>Diff insertion</string> <key>scope</key> <string>markup.inserted.diff, meta.diff.header.to-file</string> <key>settings</key> <dict> <key>foreground</key> <string>#718c00</string> </dict> </dict> <dict> <key>name</key> <string>Diff deletion</string> <key>scope</key> <string>markup.deleted.diff, meta.diff.header.from-file</string> <key>settings</key> <dict> <key>foreground</key> <string>#c82829</string> </dict> </dict> <dict> <key>name</key> <string>Diff header</string> <key>scope</key> <string>meta.diff.header.from-file, meta.diff.header.to-file</string> <key>settings</key> <dict> <key>foreground</key> <string>#FFFFFF</string> <key>background</key> <string>#4271ae</string> </dict> </dict> <dict> <key>name</key> <string>Diff range</string> <key>scope</key> <string>meta.diff.range</string> <key>settings</key> <dict> <key>fontStyle</key> <string>italic</string> <key>foreground</key> <string>#3e999f</string> </dict> </dict> </array> <key>uuid</key> <string>3F4BB232-3C3A-4396-99C0-06A9573715E9</string> </dict> </plist>
extensions/theme-tomorrow-night-blue/themes/Tomorrow-Night-Blue.tmTheme
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00021810246107634157, 0.00017222609312739223, 0.00016382952162530273, 0.0001708612107904628, 0.00000953408107307041 ]
{ "id": 1, "code_window": [ "\tprivate enableKeybindings(): string {\n", "\t\treturn [\n", "\t\t\t'<script>',\n", "\t\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t\t'\ttry {',\n", "\t\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 141 }
{ "editor.insertSpaces": false, "files.trimTrailingWhitespace": true, "files.exclude": { ".git": true, "**/.DS_Store": true, "**/coverage": true }, "search.exclude": { "**/node_modules/**": true, "**/bower_components": true, ".build/**": true, "out*/**": true, "extensions/**/out/**": true }, "tslint.rulesDirectory": "node_modules/tslint-microsoft-contrib" }
.vscode/settings.json
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017460242088418454, 0.00017336299060843885, 0.0001721235748846084, 0.00017336299060843885, 0.0000012394229997880757 ]
{ "id": 2, "code_window": [ "\t\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n", "\t\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t\t'',\n", "\t\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 155 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {ResourceEditorModel} from 'vs/workbench/common/editor/resourceEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.tabIndex = 0; iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel(input).then(model => { if (model instanceof ResourceEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [67 /* c */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } export function defaultStyle(element: HTMLElement): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize} }`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.9988610744476318, 0.1379641592502594, 0.0001627630990697071, 0.00017141604621428996, 0.34235629439353943 ]
{ "id": 2, "code_window": [ "\t\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n", "\t\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t\t'',\n", "\t\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 155 }
{ "id": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "$schema": "http://json-schema.org/draft-04/schema#", "title": "Template", "description": "An Azure deployment template", "type": "object", "properties": { "$schema": { "type": "string", "description": "JSON schema reference" }, "contentVersion": { "type": "string", "pattern": "(^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$)", "description": "A 4 number format for the version number of this template file. For example, 1.0.0.0" }, "variables": { "type": "object", "description": "Variable definitions" }, "parameters": { "type": "object", "description": "Input parameter definitions", "additionalProperties": { "$ref": "#/definitions/parameter" } }, "resources": { "type": "array", "description": "Collection of resources to be deployed", "items": { "oneOf": [ { "allOf": [ { "$ref": "#/definitions/resourceBase" }, { "oneOf": [ { "$ref": "http://schema.management.azure.com/schemas/2014-06-01/Microsoft.Web.json#/definitions/certificates" }, { "$ref": "http://schema.management.azure.com/schemas/2014-06-01/Microsoft.Web.json#/definitions/serverfarms" } ] } ] }, { "allOf": [ { "$ref": "#/definitions/resourceBaseForParentResources" }, { "oneOf": [ { "$ref": "http://schema.management.azure.com/schemas/2014-06-01/Microsoft.Web.json#/definitions/sites" }, { "$ref": "http://schema.management.azure.com/schemas/2014-04-01-preview/Microsoft.Sql.json#/definitions/servers" }, { "$ref": "http://schema.management.azure.com/schemas/2015-08-01/Microsoft.Compute.json#/resourceDefinitions/virtualMachines" } ] } ] }, { "allOf": [ { "$ref": "#/definitions/resourceBaseExternal" }, { "oneOf": [ { "$ref": "http://schema.management.azure.com/schemas/2014-04-01/SuccessBricks.ClearDB.json#/definitions/databases" } ] } ] }, { "allOf": [ { "$ref": "#/definitions/ARMResourceBase" }, { "oneOf": [ { "$ref": "http://schema.management.azure.com/schemas/2015-01-01/Microsoft.Resources.json#/definitions/deployments" }, { "$ref": "http://schema.management.azure.com/schemas/2015-01-01/Microsoft.Resources.json#/definitions/links" }, { "$ref": "http://schema.management.azure.com/schemas/2015-01-01/Microsoft.Authorization.json#/definitions/locks" } ] } ] } ] }, "minItems": 1 }, "outputs": { "type": "object", "description": "Output parameter definitions", "additionalProperties": { "$ref": "#/definitions/output" } } }, "additionalProperties": false, "required": [ "$schema", "contentVersion", "resources" ], "definitions": { "resourceBase": { "allOf": [ { "$ref": "#/definitions/resourceBaseForParentResources" }, { "properties": { "resources": { "$ref": "#/definitions/childResources" } } } ] }, "ARMResourceBase": { "type": "object", "properties": { "name": { "type": "string", "description": "Name of the resource" }, "type": { "type": "string", "description": "Resource type" }, "apiVersion": { "type": "string", "description": "API Version of the resource type" }, "dependsOn": { "type": "array", "items": { "type": "string" }, "description": "Collection of resources this resource depends on" } }, "required": [ "name", "type", "apiVersion" ] }, "proxyResourceBase": { "allOf": [ { "$ref": "#/definitions/ARMResourceBase" }, { "properties": { "resources": { "$ref": "#/definitions/childResources" }, "location": { "$ref": "#/definitions/resourceLocations", "description": "Location to deploy resource to" } } } ] }, "resourceBaseForParentResources": { "allOf": [ { "$ref": "#/definitions/ARMResourceBase" }, { "properties": { "kind": { "type": "string", "maxLength": 64, "pattern": "(^[a-zA-Z0-9_.()-]+$)", "description": "Kind of resource" }, "location": { "$ref": "#/definitions/resourceLocations", "description": "Location to deploy resource to" }, "tags": { "type": "object", "description": "Name-value pairs to add to the resource" }, "plan": { "$ref": "#/definitions/resourcePlan" } }, "required": [ "location" ] } ] }, "resourceBaseExternal": { "$ref": "#/definitions/resourceBase", "required": [ "plan" ] }, "childResources": { "type": "array", "items": { "$ref": "#/definitions/ARMChildResources" } }, "ARMChildResources": { "oneOf": [ { "$ref": "http://schema.management.azure.com/schemas/2015-01-01/Microsoft.Authorization.json#/definitions/locks" }, { "$ref": "http://schema.management.azure.com/schemas/2015-01-01/Microsoft.Resources.json#/definitions/links" } ] }, "resourcePlan": { "type": "object", "properties": { "name": { "type": "string", "description": "Name of the plan" }, "promotionCode": { "type": "string", "description": "Plan promotion code" }, "publisher": { "type": "string", "description": "Name of the publisher" }, "product": { "type": "string", "description": "Name of the product" } }, "required": [ "name" ], "description": "Plan of the resource" }, "resourceLocations": { "anyOf": [ { "type": "string" }, { "enum": [ "East Asia", "Southeast Asia", "Central US", "East US", "East US 2", "West US", "North Central US", "South Central US", "North Europe", "West Europe", "Japan West", "Japan East", "Brazil South", "Australia East", "Australia Southeast", "Central India", "West India", "South India" ] } ] }, "parameter": { "type": "object", "properties": { "type": { "$ref": "#/definitions/parameterTypes", "description": "Type of input parameter" }, "defaultValue": { "$ref": "#/definitions/parameterValueTypes", "description": "Default value to be used if one is not provided" }, "allowedValues": { "type": "array", "description": "Value can only be one of these values" }, "minLength": { "type": "integer", "description": "Minimum number of characters that must be used" }, "maxLength": { "type": "integer", "description": "Maximum number of characters that can be used" }, "metadata": { "type": "object", "description": "Metadata for the parameter" } }, "required": [ "type" ], "description": "Input parameter definitions" }, "output": { "type": "object", "properties": { "type": { "$ref": "#/definitions/parameterTypes", "description": "Type of output value" }, "value": { "$ref": "#/definitions/parameterValueTypes", "description": "Value assigned for output" } }, "required": [ "type", "value" ], "description": "Set of output parameters" }, "parameterTypes": { "enum": [ "string", "securestring", "int", "bool", "object", "array" ] }, "parameterValueTypes": { "type": [ "string", "boolean", "integer", "number", "object", "array", "null" ] }, "expression": { "type": "string", "pattern": "^\\[(concat|parameters|variables|reference|resourceId|resourceGroup|subscription|listKeys|listPackage|base64|providers|copyIndex|padLeft)\\(.*\\).*\\]$", "description": "Deployment template expression. Expressions are enclosed in [] and must start with a function of concat(), parameters(), variables(), reference(), resourceId(), resourceGroup(), subscription(), listKeys(), listPackage(), base64(), providers(), copyIndex(), padLeft()" }, "Iso8601Duration": { "type": "string", "pattern": "^P(\\d+Y)?(\\d+M)?(\\d+D)?(T(((\\d+H)(\\d+M)?(\\d+(\\.\\d{1,2})?S)?)|((\\d+M)(\\d+(\\.\\d{1,2})?S)?)|((\\d+(\\.\\d{1,2})?S))))?$" }, "UTC": { "type": "string", "pattern": "^\\d{4}(-(0[1-9]|1[0-2])(-([012]\\d|3[01])(T((([01]\\d|2[0123]):[0-5]\\d)|(24:00))(:(([0-5]\\d)|60)(\\.\\d{1,}){0,1}){0,1}){0,1}((Z)|([+-]((([01]\\d|2[0123]):[0-5]\\d)|(24:00)))){0,1}){0,1}){0,1}$" }, "apiVersion": { "type": "string", "pattern": "(^((\\d\\d\\d\\d-\\d\\d-\\d\\d)|([0-9]+(\\.[0-9]+)?))(-[a-zA-Z][a-zA-Z0-9]*)?$)", "description": "API version of the resource type" } } }
src/vs/languages/json/test/common/fixtures/deploymentTemplate.json
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.0001746442139847204, 0.0001713041856419295, 0.00016693315410520881, 0.00017174880485981703, 0.0000019241369955125265 ]
{ "id": 2, "code_window": [ "\t\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n", "\t\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t\t'',\n", "\t\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 155 }
{ "nameShort": "Code [OSS Build]", "nameLong": "Code [OSS Build]", "win32MutexName": "vscodeoss", "companyName": "Microsoft Corporation", "copyright": "Copyright (C) 2015 Microsoft. All rights reserved", "licenseUrl": "https://github.com/Microsoft/vscode/blob/master/LICENSE.txt", "darwinBundleIdentifier": "com.visualstudio.code.oss", "darwinApplicationCategoryType": "public.app-category.developer-tools", "darwinBundleDocumentTypes": [{ "name": "Code OSS Build document", "role": "Editor", "ostypes": ["TEXT", "utxt", "TUTX", "****"], "extensions": ["ascx", "asp", "aspx", "bash", "bash_login", "bash_logout", "bash_profile", "bashrc", "bat", "bowerrc", "c", "cc", "clj", "cljs", "cljx", "clojure", "cmd", "coffee", "config", "cpp", "cs", "cshtml", "csproj", "css", "csx", "ctp", "cxx", "dockerfile", "dot", "dtd", "editorconfig", "edn", "eyaml", "eyml", "fs", "fsi", "fsscript", "fsx", "gemspec", "gitattributes", "gitconfig", "gitignore", "go", "h", "handlebars", "hbs", "hh", "hpp", "htm", "html", "hxx", "ini", "jade", "jav", "java", "js", "jscsrc", "jshintrc", "jshtm", "json", "jsp", "less", "lua", "m", "makefile", "markdown", "md", "mdoc", "mdown", "mdtext", "mdtxt", "mdwn", "mkd", "mkdn", "ml", "mli", "nqp", "p6", "php", "phtml", "pl", "pl6", "pm", "pm6", "pod", "pp", "profile", "properties", "ps1", "psd1", "psgi", "psm1", "py", "r", "rb", "rhistory", "rprofile", "rs", "rt", "scss", "sh", "shtml", "sql", "svg", "svgz", "t", "ts", "txt", "vb", "wxi", "wxl", "wxs", "xaml", "xml", "yaml", "yml", "zsh"], "iconFile": "resources/darwin/code_file.icns" }], "icons": { "application": { "png": "resources/linux/code.png", "icns": "resources/darwin/code.icns", "ico": "resources/win32/code.ico" }, "file": { "icns": "resources/darwin/code_file.icns", "ico": "resources/win32/code_file.ico" } } }
product.json
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017352560826111585, 0.0001693459926173091, 0.00016364593466278166, 0.00017086642037611455, 0.000004174188234173926 ]
{ "id": 2, "code_window": [ "\t\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n", "\t\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t\t'',\n", "\t\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t\t'\t\t\t}',\n", "\t\t\t'\t\t}',\n", "\t\t\t'',\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 155 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Assert = require('vs/base/common/assert'); import { IDisposable, combinedDispose } from 'vs/base/common/lifecycle'; import arrays = require('vs/base/common/arrays'); import { INavigator } from 'vs/base/common/iterator'; import Events = require('vs/base/common/eventEmitter'); import WinJS = require('vs/base/common/winjs.base'); import _ = require('./tree'); interface IMap<T> { [id: string]: T; } interface IItemMap extends IMap<Item> {} interface ITraitMap extends IMap<IItemMap> {} export class LockData extends Events.EventEmitter { private _item: Item; constructor(item: Item) { super(); this._item = item; } public get item(): Item { return this._item; } public dispose(): void { this.emit('unlock'); super.dispose(); } } export class Lock { /* When refreshing tree items, the tree's structured can be altered, by inserting and removing sub-items. This lock helps to manage several possibly-structure-changing calls. API-wise, there are two possibly-structure-changing: refresh(...), expand(...) and collapse(...). All these calls must call Lock#run(...). Any call to Lock#run(...) needs to provide the affecting item and a callback to execute when unlocked. It must also return a promise which fulfills once the operation ends. Once it is called, there are three possibilities: - Nothing is currently running. The affecting item is remembered, and the callback is executed. - Or, there are on-going operations. There are two outcomes: - The affecting item intersects with any other affecting items of on-going run calls. In such a case, the given callback should be executed only when the on-going one completes. - Or, it doesn't. In such a case, both operations can be run in parallel. Note: two items A and B intersect if A is a descendant of B, or vice-versa. */ private locks: { [id: string]: LockData; }; constructor() { this.locks = Object.create({}); } public isLocked(item: Item): boolean { return !!this.locks[item.id]; } public run(item: Item, fn: () => WinJS.Promise): WinJS.Promise { var lock = this.getLock(item); if (lock) { var unbindListener: Events.ListenerUnbind; return new WinJS.Promise((c, e) => { unbindListener = lock.addOneTimeListener('unlock', () => { return this.run(item, fn).then(c, e); }); }, () => unbindListener()); } var result: WinJS.Promise; return new WinJS.Promise((c, e) => { if (item.isDisposed()) { return e(new Error('Item is disposed.')); } var lock = this.locks[item.id] = new LockData(item); result = fn().then((r) => { delete this.locks[item.id]; lock.dispose(); return r; }).then(c, e); return result; }, () => result.cancel()); } private getLock(item: Item): LockData { var key: string; for (key in this.locks) { var lock = this.locks[key]; if (item.intersects(lock.item)) { return lock; } } return null; } } export class ItemRegistry extends Events.EventEmitter { private items: IMap<{ item: Item; disposable: IDisposable; }>; constructor() { super(); this.items = {}; } public register(item: Item): void { Assert.ok(!this.isRegistered(item.id), 'item already registered: ' + item.id); this.items[item.id] = { item, disposable: this.addEmitter2(item) }; } public deregister(item: Item): void { Assert.ok(this.isRegistered(item.id), 'item not registered: ' + item.id); this.items[item.id].disposable.dispose(); delete this.items[item.id]; } public isRegistered(id: string): boolean { return this.items.hasOwnProperty(id); } public getItem(id: string): Item { const result = this.items[id]; return result ? result.item : null; } public dispose(): void { super.dispose(); delete this.items; } } export interface IBaseItemEvent { item: Item; } export interface IItemRefreshEvent extends IBaseItemEvent { } export interface IItemExpandEvent extends IBaseItemEvent { } export interface IItemCollapseEvent extends IBaseItemEvent { } export interface IItemDisposeEvent extends IBaseItemEvent { } export interface IItemTraitEvent extends IBaseItemEvent { trait: string; } export interface IItemRevealEvent extends IBaseItemEvent { relativeTop: number; } export interface IItemChildrenRefreshEvent extends IBaseItemEvent { isNested: boolean; } export class Item extends Events.EventEmitter { private registry: ItemRegistry; private context: _.ITreeContext; private element: any; private lock: Lock; public id: string; private needsChildrenRefresh: boolean; private doesHaveChildren: boolean; public parent: Item; public previous: Item; public next: Item; public firstChild: Item; public lastChild: Item; private userContent: HTMLElement; private height: number; private depth: number; private visible: boolean; private expanded: boolean; private traits: { [trait: string]: boolean; }; private _isDisposed: boolean; constructor(id: string, registry: ItemRegistry, context: _.ITreeContext, lock: Lock, element: any) { super(); this.registry = registry; this.context = context; this.lock = lock; this.element = element; this.id = id; this.registry.register(this); this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element); this.needsChildrenRefresh = true; this.parent = null; this.previous = null; this.next = null; this.firstChild = null; this.lastChild = null; this.userContent = null; this.traits = {}; this.depth = 0; this.expanded = false; this.emit('item:create', { item: this }); this.visible = this._isVisible(); this.height = this._getHeight(); this._isDisposed = false; } public getElement(): any { return this.element; } public hasChildren(): boolean { return this.doesHaveChildren; } public getDepth(): number { return this.depth; } public isVisible(): boolean { return this.visible; } public setVisible(value: boolean): void { this.visible = value; } public isExpanded(): boolean { return this.expanded; } /* protected */ public _setExpanded(value: boolean): void { this.expanded = value; } public reveal(relativeTop: number = null): void { var eventData: IItemRevealEvent = { item: this, relativeTop: relativeTop }; this.emit('item:reveal', eventData); } public expand(): WinJS.Promise { if (this.isExpanded() || !this.doesHaveChildren || this.lock.isLocked(this)) { return WinJS.Promise.as(false); } var result = this.lock.run(this, () => { var eventData: IItemExpandEvent = { item: this }; var result: WinJS.Promise; this.emit('item:expanding', eventData); if (this.needsChildrenRefresh) { result = this.refreshChildren(false, true, true); } else { result = WinJS.Promise.as(null); } return result.then(() => { this._setExpanded(true); this.emit('item:expanded', eventData); return true; }); }); return result.then((r) => { if (this.isDisposed()) { return false; } // Auto expand single child folders if (this.context.options.autoExpandSingleChildren && r && this.firstChild !== null && this.firstChild === this.lastChild && this.firstChild.isVisible()) { return this.firstChild.expand().then(() => { return true; }); } return r; }); } public collapse(recursive: boolean = false): WinJS.Promise { if (recursive) { var collapseChildrenPromise = WinJS.Promise.as(null); this.forEachChild((child) => { collapseChildrenPromise = collapseChildrenPromise.then(() => child.collapse(true)); }); return collapseChildrenPromise.then(() => { return this.collapse(false); }); } else { if (!this.isExpanded() || this.lock.isLocked(this)) { return WinJS.Promise.as(false); } return this.lock.run(this, () => { var eventData: IItemCollapseEvent = { item: this }; this.emit('item:collapsing', eventData); this._setExpanded(false); this.emit('item:collapsed', eventData); return WinJS.Promise.as(true); }); } } public addTrait(trait: string): void { var eventData: IItemTraitEvent = { item: this, trait: trait }; this.traits[trait] = true; this.emit('item:addTrait', eventData); } public removeTrait(trait: string): void { var eventData: IItemTraitEvent = { item: this, trait: trait }; delete this.traits[trait]; this.emit('item:removeTrait', eventData); } public hasTrait(trait: string): boolean { return this.traits[trait] || false; } public getAllTraits(): string[] { var result: string[] = []; var trait: string; for (trait in this.traits) { if (this.traits.hasOwnProperty(trait) && this.traits[trait]) { result.push(trait); } } return result; } public getHeight(): number { return this.height; } private refreshChildren(recursive: boolean, safe: boolean = false, force: boolean = false): WinJS.Promise { if (!force && !this.isExpanded()) { this.needsChildrenRefresh = true; return WinJS.Promise.as(this); } this.needsChildrenRefresh = false; var doRefresh = () => { var eventData: IItemChildrenRefreshEvent = { item: this, isNested: safe }; this.emit('item:childrenRefreshing', eventData); var childrenPromise: WinJS.Promise; if (this.doesHaveChildren) { childrenPromise = this.context.dataSource.getChildren(this.context.tree, this.element); } else { childrenPromise = WinJS.Promise.as([]); } return childrenPromise.then((elements: any[]) => { elements = !elements ? [] : elements.slice(0); elements = this.sort(elements); var staleItems: IItemMap = {}; while (this.firstChild !== null) { staleItems[this.firstChild.id] = this.firstChild; this.removeChild(this.firstChild); } for (var i = 0, len = elements.length; i < len; i++) { var element = elements[i]; var id = this.context.dataSource.getId(this.context.tree, element); var item = staleItems[id] || new Item(id, this.registry, this.context, this.lock, element); item.element = element; if (recursive) { item.needsChildrenRefresh = recursive; } delete staleItems[id]; this.addChild(item); } for (var staleItemId in staleItems) { if (staleItems.hasOwnProperty(staleItemId)) { staleItems[staleItemId].dispose(); } } if (recursive) { return WinJS.Promise.join(this.mapEachChild((child) => { return child.doRefresh(recursive, true); })); } else { return WinJS.Promise.as(null); } }).then(() => { this.emit('item:childrenRefreshed', eventData); }); }; return safe ? doRefresh() : this.lock.run(this, doRefresh); } private doRefresh(recursive: boolean, safe: boolean = false): WinJS.Promise { var eventData: IItemRefreshEvent = { item: this }; this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element); this.height = this._getHeight(); this.setVisible(this._isVisible()); this.emit('item:refresh', eventData); return this.refreshChildren(recursive, safe); } public refresh(recursive: boolean): WinJS.Promise { return this.doRefresh(recursive); } public getNavigator(): INavigator<Item> { return new TreeNavigator(this); } public intersects(other: Item): boolean { return this.isAncestorOf(other) || other.isAncestorOf(this); } public getHierarchy(): Item[] { var result: Item[] = []; var node: Item = this; do { result.push(node); node = node.parent; } while (node); result.reverse(); return result; } private isAncestorOf(item: Item): boolean { while (item) { if (item.id === this.id) { return true; } item = item.parent; } return false; } private addChild(item: Item, afterItem: Item = this.lastChild): void { var isEmpty = this.firstChild === null; var atHead = afterItem === null; var atTail = afterItem === this.lastChild; if (isEmpty) { this.firstChild = this.lastChild = item; item.next = item.previous = null; } else if (atHead) { this.firstChild.previous = item; item.next = this.firstChild; item.previous = null; this.firstChild = item; } else if (atTail) { this.lastChild.next = item; item.next = null; item.previous = this.lastChild; this.lastChild = item; } else { item.previous = afterItem; item.next = afterItem.next; afterItem.next.previous = item; afterItem.next = item; } item.parent = this; item.depth = this.depth + 1; } private removeChild(item: Item): void { var isFirstChild = this.firstChild === item; var isLastChild = this.lastChild === item; if (isFirstChild && isLastChild) { this.firstChild = this.lastChild = null; } else if (isFirstChild) { item.next.previous = null; this.firstChild = item.next; } else if (isLastChild) { item.previous.next = null; this.lastChild = item.previous; } else { item.next.previous = item.previous; item.previous.next = item.next; } item.parent = null; item.depth = null; } private forEachChild(fn: (child: Item) => void): void { var child = this.firstChild, next: Item; while (child) { next = child.next; fn(child); child = next; } } private mapEachChild<T>(fn: (child: Item) => T): T[] { var result = []; this.forEachChild((child) => { result.push(fn(child)); }); return result; } private sort(elements: any[]): any[] { if (this.context.sorter) { return elements.sort((element, otherElement) => { return this.context.sorter.compare(this.context.tree, element, otherElement); }); } return elements; } /* protected */ public _getHeight(): number { return this.context.renderer.getHeight(this.context.tree, this.element); } /* protected */ public _isVisible(): boolean { return this.context.filter.isVisible(this.context.tree, this.element); } public isDisposed(): boolean { return this._isDisposed; } public dispose(): void { this.forEachChild((child) => child.dispose()); delete this.parent; delete this.previous; delete this.next; delete this.firstChild; delete this.lastChild; var eventData: IItemDisposeEvent = { item: this }; this.emit('item:dispose', eventData); this.registry.deregister(this); super.dispose(); this._isDisposed = true; } } class RootItem extends Item { constructor(id: string, registry: ItemRegistry, context: _.ITreeContext, lock: Lock, element: any) { super(id, registry, context, lock, element); } public isVisible(): boolean { return false; } public setVisible(value: boolean): void { // no-op } public isExpanded(): boolean { return true; } /* protected */ public _setExpanded(value: boolean): void { // no-op } public render(): void { // no-op } /* protected */ public _getHeight(): number { return 0; } /* protected */ public _isVisible(): boolean { return false; } } export class TreeNavigator implements INavigator<Item> { private start: Item; private item: Item; static lastDescendantOf(item: Item): Item { if (!item) { return null; } else { if (!item.isVisible() || !item.isExpanded() || item.lastChild === null) { return item; } else { return TreeNavigator.lastDescendantOf(item.lastChild); } } } constructor(item: Item, subTreeOnly: boolean = true) { this.item = item; this.start = subTreeOnly ? item : null; } public current(): Item { return this.item || null; } public next(): Item { if (this.item) { do { if ((this.item instanceof RootItem || (this.item.isVisible() && this.item.isExpanded())) && this.item.firstChild) { this.item = this.item.firstChild; } else if (this.item === this.start) { this.item = null; } else { // select next brother, next uncle, next great-uncle, etc... while (this.item && this.item !== this.start && !this.item.next) { this.item = this.item.parent; } if (this.item === this.start) { this.item = null; } this.item = !this.item ? null : this.item.next; } } while (this.item && !this.item.isVisible()); } return this.item || null; } public previous(): Item { if (this.item) { do { var previous = TreeNavigator.lastDescendantOf(this.item.previous); if (previous) { this.item = previous; } else if (this.item.parent && this.item.parent !== this.start && this.item.parent.isVisible()) { this.item = this.item.parent; } else { this.item = null; } } while (this.item && !this.item.isVisible()); } return this.item || null; } public parent(): Item { if (this.item) { var parent = this.item.parent; if (parent && parent !== this.start && parent.isVisible()) { this.item = parent; } else { this.item = null; } } return this.item || null; } public first(): Item { this.item = this.start; this.next(); return this.item || null; } public last(): Item { if (this.start && this.start.isExpanded()) { this.item = this.start.lastChild; if (this.item && !this.item.isVisible()) { this.previous(); } } return this.item || null; } } function getRange(one: Item, other: Item): Item[] { var oneHierarchy = one.getHierarchy(); var otherHierarchy = other.getHierarchy(); var length = arrays.commonPrefixLength(oneHierarchy, otherHierarchy); var item = oneHierarchy[length - 1]; var nav = item.getNavigator(); var oneIndex: number = null; var otherIndex: number = null; var index = 0; var result: Item[] = []; while (item && (oneIndex === null || otherIndex === null)) { result.push(item); if (item === one) { oneIndex = index; } if (item === other) { otherIndex = index; } index++; item = nav.next(); } if (oneIndex === null || otherIndex === null) { return []; } var min = Math.min(oneIndex, otherIndex); var max = Math.max(oneIndex, otherIndex); return result.slice(min, max + 1); } export interface IBaseEvent { item: Item; } export interface IInputEvent extends IBaseEvent { } export interface IRefreshEvent extends IBaseEvent { recursive: boolean; } export class TreeModel extends Events.EventEmitter { private context: _.ITreeContext; private lock: Lock; private input: Item; private registry: ItemRegistry; private registryDisposable: IDisposable; private traitsToItems: ITraitMap; constructor(context: _.ITreeContext) { super(); this.context = context; this.input = null; this.traitsToItems = {}; } public setInput(element: any): WinJS.Promise { var eventData: IInputEvent = { item: this.input }; this.emit('clearingInput', eventData); this.setSelection([]); this.setFocus(); this.setHighlight(); this.lock = new Lock(); if (this.input) { this.input.dispose(); } if (this.registry) { this.registry.dispose(); this.registryDisposable.dispose(); } this.registry = new ItemRegistry(); this.registryDisposable = combinedDispose( this.addEmitter2(this.registry), this.registry.addListener2('item:dispose', (event: IItemDisposeEvent) => { event.item.getAllTraits() .forEach(trait => delete this.traitsToItems[trait][event.item.id]); }) ); var id = this.context.dataSource.getId(this.context.tree, element); this.input = new RootItem(id, this.registry, this.context, this.lock, element); eventData = { item: this.input }; this.emit('setInput', eventData); return this.refresh(this.input); } public getInput(): any { return this.input ? this.input.getElement() : null; } public refresh(element: any = null, recursive: boolean = true): WinJS.Promise { var item = this.getItem(element); if (!item) { return WinJS.Promise.as(null); } var eventData: IRefreshEvent = { item: item, recursive: recursive }; this.emit('refreshing', eventData); return item.refresh(recursive).then(() => { this.emit('refreshed', eventData); }); } public refreshAll(elements: any[], recursive: boolean = true): WinJS.Promise { var promises = []; this.deferredEmit(() => { for (var i = 0, len = elements.length; i < len; i++) { promises.push(this.refresh(elements[i], recursive)); } }); return WinJS.Promise.join(promises); } public expand(element: any): WinJS.Promise { var item = this.getItem(element); if (!item) { return WinJS.Promise.as(false); } return item.expand(); } public expandAll(elements?: any[]): WinJS.Promise { if (!elements) { elements = []; var item: Item; var nav = this.getNavigator(); while (item = nav.next()) { elements.push(item); } } var promises = []; for (var i = 0, len = elements.length; i < len; i++) { promises.push(this.expand(elements[i])); } return WinJS.Promise.join(promises); } public collapse(element: any, recursive: boolean = false): WinJS.Promise { var item = this.getItem(element); if (!item) { return WinJS.Promise.as(false); } return item.collapse(recursive); } public collapseAll(elements: any[] = null, recursive: boolean = false): WinJS.Promise { if (!elements) { elements = [this.input]; recursive = true; } var promises = []; for (var i = 0, len = elements.length; i < len; i++) { promises.push(this.collapse(elements[i], recursive)); } return WinJS.Promise.join(promises); } public toggleExpansion(element: any): WinJS.Promise { return this.isExpanded(element) ? this.collapse(element) : this.expand(element); } public toggleExpansionAll(elements: any[]): WinJS.Promise { var promises = []; for (var i = 0, len = elements.length; i < len; i++) { promises.push(this.toggleExpansion(elements[i])); } return WinJS.Promise.join(promises); } public isExpanded(element: any): boolean { var item = this.getItem(element); if (!item) { return false; } return item.isExpanded(); } public getExpandedElements(): any[] { var result: any[] = []; var item: Item; var nav = this.getNavigator(); while (item = nav.next()) { if (item.isExpanded()) { result.push(item.getElement()); } } return result; } public reveal(element: any, relativeTop: number = null): WinJS.Promise { return this.resolveUnknownParentChain(element).then((chain: any[]) => { var result = WinJS.Promise.as(null); chain.forEach((e) => { result = result.then(() => this.expand(e)); }); return result; }).then(() => { var item = this.getItem(element); if (item) { return item.reveal(relativeTop); } }); } private resolveUnknownParentChain(element: any): WinJS.Promise { return this.context.dataSource.getParent(this.context.tree, element).then((parent) => { if (!parent) { return WinJS.Promise.as([]); } return this.resolveUnknownParentChain(parent).then((result) => { result.push(parent); return result; }); }); } public setHighlight(element?: any, eventPayload?: any): void { this.setTraits('highlighted', element ? [element] : []); var eventData: _.IHighlightEvent = { highlight: this.getHighlight(), payload: eventPayload }; this.emit('highlight', eventData); } public getHighlight(includeHidden?: boolean): any { var result = this.getElementsWithTrait('highlighted', includeHidden); return result.length === 0 ? null : result[0]; } public isHighlighted(element: any): boolean { var item = this.getItem(element); if (!item) { return false; } return item.hasTrait('highlighted'); } public select(element: any, eventPayload?: any): void { this.selectAll([element], eventPayload); } public selectRange(fromElement: any, toElement: any, eventPayload?: any): void { var fromItem = this.getItem(fromElement); var toItem = this.getItem(toElement); if (!fromItem || !toItem) { return; } this.selectAll(getRange(fromItem, toItem), eventPayload); } public deselectRange(fromElement: any, toElement: any, eventPayload?: any): void { var fromItem = this.getItem(fromElement); var toItem = this.getItem(toElement); if (!fromItem || !toItem) { return; } this.deselectAll(getRange(fromItem, toItem), eventPayload); } public selectAll(elements: any[], eventPayload?: any): void { this.addTraits('selected', elements); var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload }; this.emit('selection', eventData); } public deselect(element: any, eventPayload?: any): void { this.deselectAll([element], eventPayload); } public deselectAll(elements: any[], eventPayload?: any): void { this.removeTraits('selected', elements); var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload }; this.emit('selection', eventData); } public setSelection(elements: any[], eventPayload?: any): void { this.setTraits('selected', elements); var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload }; this.emit('selection', eventData); } public toggleSelection(element: any, eventPayload?: any): void { this.toggleTrait('selected', element); var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload }; this.emit('selection', eventData); } public isSelected(element: any): boolean { var item = this.getItem(element); if (!item) { return false; } return item.hasTrait('selected'); } public getSelection(includeHidden?: boolean): any[] { return this.getElementsWithTrait('selected', includeHidden); } public selectNext(count: number = 1, clearSelection: boolean = true, eventPayload?: any): void { var selection = this.getSelection(); var item: Item = selection.length > 0 ? selection[0] : this.input; var nextItem: Item; var nav = this.getNavigator(item, false); for (var i = 0; i < count; i++) { nextItem = nav.next(); if (!nextItem) { break; } item = nextItem; } if (clearSelection) { this.setSelection([item], eventPayload); } else { this.select(item, eventPayload); } } public selectPrevious(count: number = 1, clearSelection: boolean = true, eventPayload?: any): void { var selection = this.getSelection(), item: Item = null, previousItem: Item = null; if (selection.length === 0) { var nav = this.getNavigator(this.input); while (item = nav.next()) { previousItem = item; } item = previousItem; } else { item = selection[0]; var nav = this.getNavigator(item, false); for (var i = 0; i < count; i++) { previousItem = nav.previous(); if (!previousItem) { break; } item = previousItem; } } if (clearSelection) { this.setSelection([item], eventPayload); } else { this.select(item, eventPayload); } } public selectParent(eventPayload?: any, clearSelection: boolean = true): void { var selection = this.getSelection(); var item: Item = selection.length > 0 ? selection[0] : this.input; var nav = this.getNavigator(item, false); var parent = nav.parent(); if (parent) { if (clearSelection) { this.setSelection([parent], eventPayload); } else { this.select(parent, eventPayload); } } } public setFocus(element?: any, eventPayload?: any): void { this.setTraits('focused', element ? [element] : []); var eventData: _.IFocusEvent = { focus: this.getFocus(), payload: eventPayload }; this.emit('focus', eventData); } public isFocused(element: any): boolean { var item = this.getItem(element); if (!item) { return false; } return item.hasTrait('focused'); } public getFocus(includeHidden?: boolean): any { var result = this.getElementsWithTrait('focused', includeHidden); return result.length === 0 ? null : result[0]; } public focusNext(count: number = 1, eventPayload?: any): void { var item: Item = this.getFocus() || this.input; var nextItem: Item; var nav = this.getNavigator(item, false); for (var i = 0; i < count; i++) { nextItem = nav.next(); if (!nextItem) { break; } item = nextItem; } this.setFocus(item, eventPayload); } public focusPrevious(count: number = 1, eventPayload?: any): void { var item: Item = this.getFocus() || this.input; var previousItem: Item; var nav = this.getNavigator(item, false); for (var i = 0; i < count; i++) { previousItem = nav.previous(); if (!previousItem) { break; } item = previousItem; } this.setFocus(item, eventPayload); } public focusParent(eventPayload?: any): void { var item: Item = this.getFocus() || this.input; var nav = this.getNavigator(item, false); var parent = nav.parent(); if (parent) { this.setFocus(parent, eventPayload); } } public focusFirst(eventPayload?: any): void { this.focusNth(0, eventPayload); } public focusNth(index: number, eventPayload?: any): void { var nav = this.getNavigator(this.input); var item = nav.first(); for (var i = 0; i < index; i++) { item = nav.next(); } if (item) { this.setFocus(item, eventPayload); } } public focusLast(eventPayload?: any): void { var nav = this.getNavigator(this.input); var item = nav.last(); if (item) { this.setFocus(item, eventPayload); } } public getNavigator(element: any = null, subTreeOnly: boolean = true): INavigator<Item> { return new TreeNavigator(this.getItem(element), subTreeOnly); } private getItem(element: any = null): Item { if (element === null) { return this.input; } else if (element instanceof Item) { return element; } else if (typeof element === 'string') { return this.registry.getItem(element); } else { return this.registry.getItem(this.context.dataSource.getId(this.context.tree, element)); } } public addTraits(trait: string, elements: any[]): void { var items: IItemMap = this.traitsToItems[trait] || <IItemMap> {}; var item: Item; for (var i = 0, len = elements.length; i < len; i++) { item = this.getItem(elements[i]); if (item) { item.addTrait(trait); items[item.id] = item; } } this.traitsToItems[trait] = items; } public removeTraits(trait: string, elements: any[]): void { var items: IItemMap = this.traitsToItems[trait] || <IItemMap> {}; var item: Item; var id: string; if (elements.length === 0) { for (id in items) { if (items.hasOwnProperty(id)) { item = items[id]; item.removeTrait(trait); } } delete this.traitsToItems[trait]; } else { for (var i = 0, len = elements.length; i < len; i++) { item = this.getItem(elements[i]); if (item) { item.removeTrait(trait); delete items[item.id]; } } } } public hasTrait(trait: string, element: any): boolean { var item = this.getItem(element); return item && item.hasTrait(trait); } private toggleTrait(trait: string, element: any): void { var item = this.getItem(element); if (!item) { return; } if (item.hasTrait(trait)) { this.removeTraits(trait, [element]); } else { this.addTraits(trait, [element]); } } private setTraits(trait: string, elements: any[]): void { if (elements.length === 0) { this.removeTraits(trait, elements); } else { var items: { [id: string]: Item; } = {}; var item: Item; for (var i = 0, len = elements.length; i < len; i++) { item = this.getItem(elements[i]); if (item) { items[item.id] = item; } } var traitItems: IItemMap = this.traitsToItems[trait] || <IItemMap> {}; var itemsToRemoveTrait: Item[] = []; var id: string; for (id in traitItems) { if (traitItems.hasOwnProperty(id)) { if (items.hasOwnProperty(id)) { delete items[id]; } else { itemsToRemoveTrait.push(traitItems[id]); } } } for (var i = 0, len = itemsToRemoveTrait.length; i < len; i++) { item = itemsToRemoveTrait[i]; item.removeTrait(trait); delete traitItems[item.id]; } for (id in items) { if (items.hasOwnProperty(id)) { item = items[id]; item.addTrait(trait); traitItems[id] = item; } } this.traitsToItems[trait] = traitItems; } } private getElementsWithTrait(trait: string, includeHidden: boolean): any[] { var elements = []; var items = this.traitsToItems[trait] || {}; var id: string; for (id in items) { if (items.hasOwnProperty(id) && (items[id].isVisible() || includeHidden)) { elements.push(items[id].getElement()); } } return elements; } public dispose(): void { if (this.registry) { this.registry.dispose(); this.registry = null; } super.dispose(); } }
src/vs/base/parts/tree/browser/treeModel.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017511796613689512, 0.00017022683459799737, 0.00016050539852585644, 0.00017076601216103882, 0.0000025172973892040318 ]
{ "id": 3, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", ".monaco-workbench .iframe-container .iframe {\n", "\t-webkit-box-sizing:\tborder-box;\n", "\t-o-box-sizing:\t\tborder-box;\n", "\t-moz-box-sizing:\tborder-box;\n", "\t-ms-box-sizing:\t\tborder-box;\n", "\tbox-sizing:\t\t\tborder-box;\n", "}\n", "\n", ".monaco-workbench .iframe-container.ipad-touch-enabled {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t-o-box-sizing:\t\t\tborder-box;\n", "\t-moz-box-sizing:\t\tborder-box;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/media/iframeeditor.css", "type": "replace", "edit_start_line_idx": 7 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ body { font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 14px; padding-left: 12px; line-height: 22px; } img { max-width: 100%; max-height: 100%; } a { color: #4080D0; text-decoration: none; } hr { border: 0; height: 2px; border-bottom: 2px solid; } h1 { padding-bottom: 0.3em; line-height: 1.2; border-bottom-width: 1px; border-bottom-style: solid; } h1, h2, h3 { font-weight: normal; } a:hover { color: #4080D0; text-decoration: underline; } table { border-collapse: collapse; } table > thead > tr > th { text-align: left; border-bottom: 1px solid; } table > thead > tr > th, table > thead > tr > td, table > tbody > tr > th, table > tbody > tr > td { padding: 5px 10px; } table > tbody > tr + tr > td { border-top: 1px solid; } blockquote { margin: 0 0 0 5px; padding-left: 10px; border-left: 5px solid; } code { font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback"; font-size: 14px; line-height: 19px; } .mac code { font-size: 12px; line-height: 18px; } code > div { padding: 16px; border-radius: 3px; overflow: auto; } /** Theming */ .vs { color: rgb(30, 30, 30); } .vs-dark { color: #DDD; } .hc-black { color: white; } .vs code { color: #A31515; } .vs-dark code { color: #D7BA7D; } .vs code > div { background-color: rgba(220, 220, 220, 0.4); } .vs-dark code > div { background-color: rgba(10, 10, 10, 0.4); } .hc-black code > div { background-color: rgb(0, 0, 0); } .hc-black h1 { border-color: rgb(0, 0, 0); } .vs table > thead > tr > th { border-color: rgba(0, 0, 0, 0.69); } .vs-dark table > thead > tr > th { border-color: rgba(255, 255, 255, 0.69); } .vs h1, .vs hr, .vs table > tbody > tr + tr > td { border-color: rgba(0, 0, 0, 0.18); } .vs-dark h1, .vs-dark hr, .vs-dark table > tbody > tr + tr > td { border-color: rgba(255, 255, 255, 0.18); } .vs blockquote, .vs-dark blockquote { background: rgba(127, 127, 127, 0.1); border-color: rgba(0, 122, 204, 0.5); } .hc-black blockquote { background: transparent; border-color: #fff; }
src/vs/languages/markdown/common/markdown.css
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017160312563646585, 0.00016715278616175056, 0.0001599159004399553, 0.00016716166283003986, 0.000003400331479497254 ]
{ "id": 3, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", ".monaco-workbench .iframe-container .iframe {\n", "\t-webkit-box-sizing:\tborder-box;\n", "\t-o-box-sizing:\t\tborder-box;\n", "\t-moz-box-sizing:\tborder-box;\n", "\t-ms-box-sizing:\t\tborder-box;\n", "\tbox-sizing:\t\t\tborder-box;\n", "}\n", "\n", ".monaco-workbench .iframe-container.ipad-touch-enabled {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t-o-box-sizing:\t\t\tborder-box;\n", "\t-moz-box-sizing:\t\tborder-box;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/media/iframeeditor.css", "type": "replace", "edit_start_line_idx": 7 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" enable-background="new 0 0 16 16" height="16" width="16"><circle fill="#424242" cx="8" cy="8" r="4"/></svg>
src/vs/workbench/parts/files/browser/media/action-close-dirty.svg
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017011082672979683, 0.00017011082672979683, 0.00017011082672979683, 0.00017011082672979683, 0 ]
{ "id": 3, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", ".monaco-workbench .iframe-container .iframe {\n", "\t-webkit-box-sizing:\tborder-box;\n", "\t-o-box-sizing:\t\tborder-box;\n", "\t-moz-box-sizing:\tborder-box;\n", "\t-ms-box-sizing:\t\tborder-box;\n", "\tbox-sizing:\t\t\tborder-box;\n", "}\n", "\n", ".monaco-workbench .iframe-container.ipad-touch-enabled {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t-o-box-sizing:\t\t\tborder-box;\n", "\t-moz-box-sizing:\t\tborder-box;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/media/iframeeditor.css", "type": "replace", "edit_start_line_idx": 7 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import languageDef = require('vs/editor/standalone-languages/bat'); import T = require('vs/editor/standalone-languages/test/testUtil'); var Bracket = { Open: 1, Close: -1 }; T.testTokenization('bat', languageDef.language, [ // support.functions [{ line: '@echo off title Selfhost', tokens: [ { startIndex: 0, type: 'support.function.bat' }, { startIndex: 1, type: 'support.function.echo.bat' }, { startIndex: 5, type: '' }, { startIndex: 10, type: 'support.function.title.bat' }, { startIndex: 15, type: '' } ]}], // Comments - single line [{ line: 'REM', tokens: [ { startIndex: 0, type: 'comment.bat' } ]}], [{ line: ' REM a comment', tokens: [ { startIndex: 0, type: '' }, { startIndex: 4, type: 'comment.bat' } ]}], [{ line: 'REM a comment', tokens: [ { startIndex: 0, type: 'comment.bat' } ]}], [{ line: 'REMnot a comment', tokens: [ { startIndex: 0, type: '' } ]}], // constant.numerics [{ line: '0', tokens: [ { startIndex: 0, type: 'constant.numeric.bat' } ]}], [{ line: '0.0', tokens: [ { startIndex: 0, type: 'constant.numeric.float.bat' } ]}], [{ line: '0x123', tokens: [ { startIndex: 0, type: 'constant.numeric.hex.bat' } ]}], [{ line: '23.5', tokens: [ { startIndex: 0, type: 'constant.numeric.float.bat' } ]}], [{ line: '23.5e3', tokens: [ { startIndex: 0, type: 'constant.numeric.float.bat' } ]}], [{ line: '23.5E3', tokens: [ { startIndex: 0, type: 'constant.numeric.float.bat' } ]}], [{ line: '1.72e-3', tokens: [ { startIndex: 0, type: 'constant.numeric.float.bat' } ]}], [{ line: '0+0', tokens: [ { startIndex: 0, type: 'constant.numeric.bat' }, { startIndex: 1, type: 'punctuation.bat' }, { startIndex: 2, type: 'constant.numeric.bat' } ]}], [{ line: '100+10', tokens: [ { startIndex: 0, type: 'constant.numeric.bat' }, { startIndex: 3, type: 'punctuation.bat' }, { startIndex: 4, type: 'constant.numeric.bat' } ]}], [{ line: '0 + 0', tokens: [ { startIndex: 0, type: 'constant.numeric.bat' }, { startIndex: 1, type: '' }, { startIndex: 2, type: 'punctuation.bat' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'constant.numeric.bat' } ]}], // Strings [{ line: 'set s = "string"', tokens: [ { startIndex: 0, type: 'support.function.set.bat' }, { startIndex: 3, type: '' }, { startIndex: 6, type: 'punctuation.bat' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'string.bat' } ]}], [{ line: '"use strict";', tokens: [ { startIndex: 0, type: 'string.bat' }, { startIndex: 12, type: 'punctuation.bat' } ]}], // Tags [{ line: 'setlocal endlocal', tokens: [ { startIndex: 0, type: 'support.function.tag-setlocal.bat' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'support.function.tag-setlocal.bat' } ]}], [{ line: 'setlocal ENDLOCAL', tokens: [ { startIndex: 0, type: 'support.function.tag-setlocal.bat' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'support.function.tag-setlocal.bat' } ]}], [{ line: 'SETLOCAL endlocal', tokens: [ { startIndex: 0, type: 'support.function.tag-setlocal.bat' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'support.function.tag-setlocal.bat' } ]}], [{ line: 'setlocal setlocal endlocal', tokens: [ { startIndex: 0, type: 'support.function.tag-setlocal.bat' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'support.function.tag-setlocal.bat' }, { startIndex: 17, type: '' }, { startIndex: 18, type: 'support.function.tag-setlocal.bat' } ]}], // Monarch generated [{ line: 'rem asdf', tokens: [ { startIndex: 0, type: 'comment.bat' } ]}, { line: '', tokens: [ ]}, { line: 'REM', tokens: [ { startIndex: 0, type: 'comment.bat' } ]}, { line: '', tokens: [ ]}, { line: 'REMOVED not a comment really', tokens: [ { startIndex: 0, type: '' }, { startIndex: 8, type: 'support.function.not.bat' }, { startIndex: 11, type: '' } ]}, { line: '', tokens: [ ]}, { line: 'echo cool', tokens: [ { startIndex: 0, type: 'support.function.echo.bat' }, { startIndex: 4, type: '' } ]}, { line: '@echo off', tokens: [ { startIndex: 0, type: 'support.function.bat' }, { startIndex: 1, type: 'support.function.echo.bat' }, { startIndex: 5, type: '' } ]}, { line: '', tokens: [ ]}, { line: 'setlocAL', tokens: [ { startIndex: 0, type: 'support.function.tag-setlocal.bat' } ]}, { line: ' asdf', tokens: [ { startIndex: 0, type: '' } ]}, { line: ' asdf', tokens: [ { startIndex: 0, type: '' } ]}, { line: 'endLocaL', tokens: [ { startIndex: 0, type: 'support.function.tag-setlocal.bat' } ]}, { line: '', tokens: [ ]}, { line: 'call', tokens: [ { startIndex: 0, type: 'support.function.call.bat' } ]}, { line: '', tokens: [ ]}, { line: ':MyLabel', tokens: [ { startIndex: 0, type: 'metatag.bat' } ]}, { line: 'some command', tokens: [ { startIndex: 0, type: '' } ]}, { line: '', tokens: [ ]}, { line: '%sdfsdf% ', tokens: [ { startIndex: 0, type: 'variable.bat' }, { startIndex: 8, type: '' } ]}, { line: '', tokens: [ ]}, { line: 'this is "a string %sdf% asdf"', tokens: [ { startIndex: 0, type: '' }, { startIndex: 8, type: 'string.bat' }, { startIndex: 18, type: 'variable.bat' }, { startIndex: 23, type: 'string.bat' } ]}, { line: '', tokens: [ ]}, { line: '', tokens: [ ]}, { line: 'FOR %%A IN (1 2 3) DO (', tokens: [ { startIndex: 0, type: 'support.function.for.bat' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'variable.bat' }, { startIndex: 7, type: '' }, { startIndex: 11, type: 'punctuation.parenthesis.bat' }, { startIndex: 12, type: 'constant.numeric.bat' }, { startIndex: 13, type: '' }, { startIndex: 14, type: 'constant.numeric.bat' }, { startIndex: 15, type: '' }, { startIndex: 16, type: 'constant.numeric.bat' }, { startIndex: 17, type: 'punctuation.parenthesis.bat' }, { startIndex: 18, type: '' }, { startIndex: 22, type: 'punctuation.parenthesis.bat' } ]}, { line: ' SET VAR1=%VAR1%%%A', tokens: [ { startIndex: 0, type: '' }, { startIndex: 1, type: 'support.function.set.bat' }, { startIndex: 4, type: '' }, { startIndex: 9, type: 'punctuation.bat' }, { startIndex: 10, type: 'variable.bat' } ]}, { line: ' SET VAR2=%VAR2%%%A', tokens: [ { startIndex: 0, type: '' }, { startIndex: 1, type: 'support.function.set.bat' }, { startIndex: 4, type: '' }, { startIndex: 9, type: 'punctuation.bat' }, { startIndex: 10, type: 'variable.bat' } ]}, { line: ' use \'string %%a asdf asdf\'', tokens: [ { startIndex: 0, type: '' }, { startIndex: 5, type: 'string.bat' }, { startIndex: 13, type: 'variable.bat' }, { startIndex: 16, type: 'string.bat' } ]}, { line: ' non terminated "string %%aaa sdf', tokens: [ { startIndex: 0, type: '' }, { startIndex: 16, type: 'string.bat' }, { startIndex: 24, type: 'variable.bat' }, { startIndex: 29, type: 'string.bat' } ]}, { line: ' this shold NOT BE red', tokens: [ { startIndex: 0, type: '' }, { startIndex: 12, type: 'support.function.not.bat' }, { startIndex: 15, type: '' } ]}, { line: ')', tokens: [ { startIndex: 0, type: 'punctuation.parenthesis.bat' } ]}] ]); T.testOnEnter('bat', languageDef.language, (assertOnEnter) => { assertOnEnter.nothing('', ' a', ''); assertOnEnter.indents('', ' {', ''); assertOnEnter.indents('', '( ', ''); assertOnEnter.indents('', ' [ ', ''); assertOnEnter.indentsOutdents('', ' { ', ' } '); });
src/vs/editor/standalone-languages/test/bat.test.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017442072567064315, 0.00017135364760179073, 0.00016707202303223312, 0.00017111946363002062, 0.00000169271481809119 ]
{ "id": 3, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", ".monaco-workbench .iframe-container .iframe {\n", "\t-webkit-box-sizing:\tborder-box;\n", "\t-o-box-sizing:\t\tborder-box;\n", "\t-moz-box-sizing:\tborder-box;\n", "\t-ms-box-sizing:\t\tborder-box;\n", "\tbox-sizing:\t\t\tborder-box;\n", "}\n", "\n", ".monaco-workbench .iframe-container.ipad-touch-enabled {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t-o-box-sizing:\t\t\tborder-box;\n", "\t-moz-box-sizing:\t\tborder-box;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/media/iframeeditor.css", "type": "replace", "edit_start_line_idx": 7 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import Schedulers = require('vs/base/common/async'); import EditorCommon = require('vs/editor/common/editorCommon'); import Modes = require('vs/editor/common/modes'); import {IModeService} from 'vs/editor/common/services/modeService'; import {IRenderLineOutput, renderLine} from 'vs/editor/common/viewLayout/viewLineRenderer'; export interface IColorizerOptions { tabSize?: number; } export interface IColorizerElementOptions extends IColorizerOptions { theme?: string; mimeType?: string; } export function colorizeElement(modeService:IModeService, domNode:HTMLElement, options:IColorizerElementOptions): TPromise<void> { options = options || {}; var theme = options.theme || 'vs'; var mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang'); if (!mimeType) { console.error('Mode not detected'); return; } var text = domNode.firstChild.nodeValue; domNode.className += 'monaco-editor ' + theme; var render = (str:string) => { domNode.innerHTML = str; }; return colorize(modeService, text, mimeType, options).then(render, (err) => console.error(err), render); } export function colorize(modeService:IModeService, text:string, mimeType:string, options:IColorizerOptions): TPromise<string> { options = options || {}; if (typeof options.tabSize === 'undefined') { options.tabSize = 4; } var lines = text.split('\n'), c: (v:string)=>void, e: (err:any)=>void, p: (v:string)=>void, isCancelled = false, mode: Modes.IMode; var result = new TPromise<string>((_c, _e, _p) => { c = _c; e = _e; p = _p; }, () => { isCancelled = true; }); var colorize = new Schedulers.RunOnceScheduler(() => { if (isCancelled) { return; } var r = actualColorize(lines, mode, options.tabSize); if (r.retokenize.length > 0) { // There are retokenization requests r.retokenize.forEach((p) => p.then(scheduleColorize)); p(r.result); } else { // There are no (more) retokenization requests c(r.result); } }, 0); var scheduleColorize = () => colorize.schedule(); modeService.getOrCreateMode(mimeType).then((_mode) => { if (!_mode) { e('Mode not found: "' + mimeType + '".'); return; } if (!_mode.tokenizationSupport) { e('Mode found ("' + _mode.getId() + '"), but does not support tokenization.'); return; } mode = _mode; scheduleColorize(); }); return result; } export function colorizeLine(line:string, tokens:EditorCommon.ILineToken[], tabSize:number = 4): string { var renderResult = renderLine({ lineContent: line, parts: tokens, stopRenderingLineAfter: -1, renderWhitespace: false, tabSize: tabSize }); return renderResult.output.join(''); } export function colorizeModelLine(model:EditorCommon.IModel, lineNumber:number, tabSize:number = 4): string { var content = model.getLineContent(lineNumber); var tokens = model.getLineTokens(lineNumber, false); var inflatedTokens = EditorCommon.LineTokensBinaryEncoding.inflateArr(tokens.getBinaryEncodedTokensMap(), tokens.getBinaryEncodedTokens()); return colorizeLine(content, inflatedTokens, tabSize); } interface IActualColorizeResult { result:string; retokenize:TPromise<void>[]; } function actualColorize(lines:string[], mode:Modes.IMode, tabSize:number): IActualColorizeResult { var tokenization = mode.tokenizationSupport, html:string[] = [], state = tokenization.getInitialState(), i:number, length:number, line: string, tokenizeResult: Modes.ILineTokens, renderResult: IRenderLineOutput, retokenize: TPromise<void>[] = []; for (i = 0, length = lines.length; i < length; i++) { line = lines[i]; tokenizeResult = tokenization.tokenize(line, state); if (tokenizeResult.retokenize) { retokenize.push(tokenizeResult.retokenize); } renderResult = renderLine({ lineContent: line, parts: tokenizeResult.tokens, stopRenderingLineAfter: -1, renderWhitespace: false, tabSize: tabSize }); html = html.concat(renderResult.output); html.push('<br/>'); state = tokenizeResult.endState; } return { result: html.join(''), retokenize: retokenize }; }
src/vs/editor/browser/standalone/colorizer.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017395633039996028, 0.00017000437946990132, 0.00016655967920087278, 0.0001698430860415101, 0.0000019082808648818173 ]
{ "id": 4, "code_window": [ "\n", "\t'use strict';\n", "\n", "\tconst scriptSource = [\n", "\t\t'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 204 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {ResourceEditorModel} from 'vs/workbench/common/editor/resourceEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.tabIndex = 0; iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel(input).then(model => { if (model instanceof ResourceEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [67 /* c */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } export function defaultStyle(element: HTMLElement): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize} }`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.999174177646637, 0.1034182459115982, 0.00016341671289410442, 0.0001742483291309327, 0.3039455711841583 ]
{ "id": 4, "code_window": [ "\n", "\t'use strict';\n", "\n", "\tconst scriptSource = [\n", "\t\t'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 204 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .quick-open-widget .extension { padding: 0 14px 0 0; height: 48px; } .quick-open-widget .extension .row { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; height: 24px; } .quick-open-widget .extension .row .actions { float: right; } .quick-open-widget .extension .description { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; opacity: 0.6; } .quick-open-widget .extension .installCount:not(:empty) { margin-left: 6px; padding: 1px 3px; border-radius: 3px; background-color: rgba(132, 132, 132, 0.3); font-size: smaller; opacity: 0.7; } .quick-open-widget .extension .installCount:not(:empty):before { margin-right: 2px; } .quick-open-widget .extension .published { float: right; opacity: 0.6; font-size: smaller; } .quick-open-widget .extension .published > .version { opacity: 0.6; margin-right: 0.5em; } @keyframes move-background { to { background-position: 8px 0; } } .quick-open-widget .extension .actions .action-item:not(.disabled) { display: none; } .quick-open-widget .monaco-tree-row:hover .extension .actions .action-item, .quick-open-widget .monaco-tree-row.focused .extension .actions .action-item { display: inherit; } .quick-open-widget .extension .actions .action-item:not(:first-child) { margin-left: 2px; } .quick-open-widget .extension .actions .action-item { line-height: 12px; } .quick-open-widget .extension .actions .action-label { width: 12px; height: 12px; font-size: smaller; border: 1px solid rgba(132, 132, 132, 0.5); border-radius: 2px; padding: 1px; vertical-align: text-bottom; text-transform: uppercase; color: rgb(0, 157, 255); border-color: rgb(0, 157, 255); } .quick-open-widget .extension .actions .action-label:not(.icon) { padding: 1px 3px; display: inline-block; width: auto; font-size: x-small; } .quick-open-widget .extension .actions .action-item.disabled .action-label { animation: move-background 0.5s linear infinite; background-color: rgba(132, 132, 132, 0.5); background-size: 8px; background-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.5) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.5) 50%, rgba(255, 255, 255, 0.5) 75%, transparent 75%, transparent); color: rgb(0, 0, 0); border-color: rgb(0, 0, 0); } .quick-open-widget .extension .actions .action-item .action-label:hover { text-decoration: none; } .quick-open-widget .extension .actions .action-item:not(.disabled) .action-label:hover { color: inherit; background: rgba(132, 132, 132, 0.2); border-color: #CCC; } .quick-open-widget .extension .actions .action-item:not(.disabled) .action-label:active { background: rgba(132, 132, 132, 0.5); } .quick-open-widget .extension .actions .action-item:active { -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; } /* Status bar */ .monaco-shell .extensions-statusbar { padding: 0 5px 0 25px; line-height: 22px; background: url('extensions-status.svg') center center no-repeat; background-size: 14px; background-position: 4px 50%; }
src/vs/workbench/parts/extensions/electron-browser/media/extensions.css
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017789298726711422, 0.0001742102176649496, 0.0001704877067822963, 0.00017422271776013076, 0.0000021831478989042807 ]
{ "id": 4, "code_window": [ "\n", "\t'use strict';\n", "\n", "\tconst scriptSource = [\n", "\t\t'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 204 }
{ "name": "theme-tomorrow-night-blue", "version": "0.1.0", "publisher": "vscode", "engines": { "vscode": "*" }, "contributes": { "themes": [ { "label": "Tomorrow Night Blue", "uiTheme": "vs-dark", "path": "./themes/Tomorrow-Night-Blue.tmTheme" } ] } }
extensions/theme-tomorrow-night-blue/package.json
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017692842811811715, 0.00017635434051044285, 0.00017578026745468378, 0.00017635434051044285, 5.740803317166865e-7 ]
{ "id": 4, "code_window": [ "\n", "\t'use strict';\n", "\n", "\tconst scriptSource = [\n", "\t\t'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n", "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 204 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; export interface IIterator<T> { next(): T; } export class ArrayIterator<T> implements IIterator<T> { private items: T[]; private start: number; private end: number; private index: number; constructor(items: T[], start: number = 0, end: number = items.length) { this.items = items; this.start = start; this.end = end; this.index = start - 1; } public next(): T { this.index = Math.min(this.index + 1, this.end); if (this.index === this.end) { return null; } return this.items[this.index]; } } export class MappedIterator<T, R> implements IIterator<R> { constructor(protected iterator: IIterator<T>, protected fn: (item:T)=>R) { // noop } next() { return this.fn(this.iterator.next()); } } export interface INavigator<T> extends IIterator<T> { current(): T; previous(): T; parent(): T; first(): T; last(): T; } export class MappedNavigator<T, R> extends MappedIterator<T, R> implements INavigator<R> { constructor(protected navigator: INavigator<T>, fn: (item:T)=>R) { super(navigator, fn); } current() { return this.fn(this.navigator.current()); } previous() { return this.fn(this.navigator.previous()); } parent() { return this.fn(this.navigator.parent()); } first() { return this.fn(this.navigator.first()); } last() { return this.fn(this.navigator.last()); } }
src/vs/base/common/iterator.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.0001764612243277952, 0.00017314452270511538, 0.00016873059212230146, 0.00017340501653961837, 0.0000025852618819044437 ]
{ "id": 5, "code_window": [ "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t'\ttry {',\n", "\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 206 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {ResourceEditorModel} from 'vs/workbench/common/editor/resourceEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.tabIndex = 0; iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel(input).then(model => { if (model instanceof ResourceEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [67 /* c */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } export function defaultStyle(element: HTMLElement): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize} }`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.9980879426002502, 0.06899142265319824, 0.00016094493912532926, 0.00017161652795039117, 0.2525715231895447 ]
{ "id": 5, "code_window": [ "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t'\ttry {',\n", "\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 206 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import {EditorModel} from 'vs/workbench/common/editor'; import {BaseTextEditorModel} from 'vs/workbench/common/editor/textEditorModel'; import {TextDiffEditorModel} from 'vs/workbench/common/editor/textDiffEditorModel'; import {DiffEditorInput} from 'vs/workbench/common/editor/diffEditorInput'; import {StringEditorInput} from 'vs/workbench/common/editor/stringEditorInput'; import {StringEditorModel} from 'vs/workbench/common/editor/stringEditorModel'; import * as InstantiationService from 'vs/platform/instantiation/common/instantiationService'; import {createMockModelService, createMockModeService} from 'vs/editor/test/common/servicesTestUtils'; class MyEditorModel extends EditorModel { } class MyTextEditorModel extends BaseTextEditorModel { } suite("Workbench - EditorModel", () => { test("EditorModel", function(done) { let m = new MyEditorModel(); m.load().then(function(model) { assert(model === m); assert.strictEqual(m.isResolved(), true); }).done(() => done()); }); test("BaseTextEditorModel", function(done) { let modelService = createMockModelService(); let modeService = createMockModeService(); let m = new MyTextEditorModel(modelService, modeService); m.load().then(function(model: any) { assert(model === m); return model.createTextEditorModel("foo", null, "text/plain").then(function() { assert.strictEqual(m.isResolved(), true); }); }).done(() => { m.dispose(); done(); }); }); test("TextDiffEditorModel", function(done) { let inst = InstantiationService.create({ modeService: createMockModeService(), modelService: createMockModelService(), }); let input = inst.createInstance(StringEditorInput, "name", 'description', "value", "text/plain", false); let otherInput = inst.createInstance(StringEditorInput, "name2", 'description', "value2", "text/plain", false); let diffInput = new DiffEditorInput("name", "description", input, otherInput); diffInput.resolve(true).then(function(model: any) { assert(model); assert(model instanceof TextDiffEditorModel); let diffEditorModel = model.textDiffEditorModel; assert(diffEditorModel.original); assert(diffEditorModel.modified); return diffInput.resolve(true).then(function(model: any) { assert(model.isResolved()); assert(diffEditorModel !== model.textDiffEditorModel); diffInput.dispose(); assert(!model.textDiffEditorModel); }); }).done(() => { done(); }); }); });
src/vs/workbench/test/browser/parts/editor/editorModel.test.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017686752835288644, 0.00017418099741917104, 0.00017155156820081174, 0.00017424288671463728, 0.0000018080766039929586 ]
{ "id": 5, "code_window": [ "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t'\ttry {',\n", "\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 206 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Lifecycle = require('vs/base/common/lifecycle'); import Strings = require('vs/base/common/strings'); import EventEmitter = require('vs/base/common/eventEmitter'); import Git = require('vs/workbench/parts/git/common/git'); export class FileStatus implements Git.IFileStatus { private id: string; private pathComponents: string[]; constructor( private path: string, private mimetype: string, private status: Git.Status, private rename?: string, isModifiedInIndex?: boolean ) { this.id = FileStatus.typeOf(status) + ':' + path + (rename ? ':' + rename : '') + (isModifiedInIndex ? '$' : ''); this.pathComponents = path.split('/'); } public getPath(): string { return this.path; } public getPathComponents(): string[] { return this.pathComponents.slice(0); } public getMimetype(): string { return this.mimetype; } public getStatus(): Git.Status { return this.status; } public getRename(): string { return this.rename; } public getId(): string { return this.id; } public getType(): Git.StatusType { switch (FileStatus.typeOf(this.status)) { case 'index': return Git.StatusType.INDEX; case 'workingTree': return Git.StatusType.WORKING_TREE; default: return Git.StatusType.MERGE; } } public clone(): Git.IFileStatus { return new FileStatus(this.path, this.mimetype, this.status, this.rename); } public update(other: FileStatus): void { this.status = other.getStatus(); this.rename = other.getRename(); } static typeOf(s: Git.Status): string { switch (s) { case Git.Status.INDEX_MODIFIED: case Git.Status.INDEX_ADDED: case Git.Status.INDEX_DELETED: case Git.Status.INDEX_RENAMED: case Git.Status.INDEX_COPIED: return 'index'; case Git.Status.MODIFIED: case Git.Status.DELETED: case Git.Status.UNTRACKED: case Git.Status.IGNORED: return 'workingTree'; default: return 'merge'; } } } interface IStatusSet { [path: string]: Git.IFileStatus; } export class StatusGroup extends EventEmitter.EventEmitter implements Git.IStatusGroup { private type: Git.StatusType; private statusSet: IStatusSet; private statusList: Git.IFileStatus[]; private statusByName: IStatusSet; private statusByRename: IStatusSet; constructor(type: Git.StatusType) { super(); this.type = type; this.statusSet = Object.create(null); this.statusList = []; this.statusByName = Object.create(null); this.statusByRename = Object.create(null); } public getType(): Git.StatusType { return this.type; } public update(statusList: FileStatus[]): void { var toDelete: IStatusSet = Object.create(null); var id: string, path: string, rename: string; var status: Git.IFileStatus; for (id in this.statusSet) { toDelete[id] = this.statusSet[id]; } for (var i = 0; i < statusList.length; i++) { status = statusList[i]; id = status.getId(); path = status.getPath(); rename = status.getRename(); if (toDelete[id]) { this.statusSet[id].update(status); toDelete[id] = null; } else { this.statusSet[id] = status; } } for (id in toDelete) { if (status = toDelete[id]) { this.emit('fileStatus:dispose', status); delete this.statusSet[id]; } } this.statusList = []; this.statusByName = Object.create(null); this.statusByRename = Object.create(null); for (id in this.statusSet) { status = this.statusSet[id]; this.statusList.push(status); if (status.getRename()) { this.statusByRename[status.getPath()] = status; } else { this.statusByName[status.getPath()] = status; } } } public all(): Git.IFileStatus[] { return this.statusList; } public find(path: string): Git.IFileStatus { return this.statusByName[path] || this.statusByRename[path] || null; } public dispose(): void { this.type = null; this.statusSet = null; this.statusList = null; this.statusByName = null; this.statusByRename = null; super.dispose(); } } export class StatusModel extends EventEmitter.EventEmitter implements Git.IStatusModel { private indexStatus: StatusGroup; private workingTreeStatus: StatusGroup; private mergeStatus: StatusGroup; private toDispose: Lifecycle.IDisposable[]; constructor() { super(); this.indexStatus = new StatusGroup(Git.StatusType.INDEX); this.workingTreeStatus = new StatusGroup(Git.StatusType.WORKING_TREE); this.mergeStatus = new StatusGroup(Git.StatusType.MERGE); this.toDispose = [ this.addEmitter2(this.indexStatus), this.addEmitter2(this.workingTreeStatus), this.addEmitter2(this.mergeStatus) ]; } public getSummary(): Git.IStatusSummary { return { hasWorkingTreeChanges: this.getWorkingTreeStatus().all().length > 0, hasIndexChanges: this.getIndexStatus().all().length > 0, hasMergeChanges: this.getMergeStatus().all().length > 0 }; } public update(status: Git.IRawFileStatus[]): void { var index: FileStatus[] = []; var workingTree: FileStatus[] = []; var merge: FileStatus[] = []; status.forEach(raw => { switch(raw.x + raw.y) { case '??': return workingTree.push(new FileStatus(raw.path, raw.mimetype, Git.Status.UNTRACKED)); case '!!': return workingTree.push(new FileStatus(raw.path, raw.mimetype, Git.Status.IGNORED)); case 'DD': return merge.push(new FileStatus(raw.path, raw.mimetype, Git.Status.BOTH_DELETED)); case 'AU': return merge.push(new FileStatus(raw.path, raw.mimetype, Git.Status.ADDED_BY_US)); case 'UD': return merge.push(new FileStatus(raw.path, raw.mimetype, Git.Status.DELETED_BY_THEM)); case 'UA': return merge.push(new FileStatus(raw.path, raw.mimetype, Git.Status.ADDED_BY_THEM)); case 'DU': return merge.push(new FileStatus(raw.path, raw.mimetype, Git.Status.DELETED_BY_US)); case 'AA': return merge.push(new FileStatus(raw.path, raw.mimetype, Git.Status.BOTH_ADDED)); case 'UU': return merge.push(new FileStatus(raw.path, raw.mimetype, Git.Status.BOTH_MODIFIED)); } let isModifiedInIndex = false; switch (raw.x) { case 'M': index.push(new FileStatus(raw.path, raw.mimetype, Git.Status.INDEX_MODIFIED)); isModifiedInIndex = true; break; case 'A': index.push(new FileStatus(raw.path, raw.mimetype, Git.Status.INDEX_ADDED)); break; case 'D': index.push(new FileStatus(raw.path, raw.mimetype, Git.Status.INDEX_DELETED)); break; case 'R': index.push(new FileStatus(raw.path, raw.mimetype, Git.Status.INDEX_RENAMED, raw.rename)); break; case 'C': index.push(new FileStatus(raw.path, raw.mimetype, Git.Status.INDEX_COPIED)); break; } switch (raw.y) { case 'M': workingTree.push(new FileStatus(raw.path, raw.mimetype, Git.Status.MODIFIED, raw.rename, isModifiedInIndex)); break; case 'D': workingTree.push(new FileStatus(raw.path, raw.mimetype, Git.Status.DELETED, raw.rename)); break; } }); this.indexStatus.update(index); this.workingTreeStatus.update(workingTree); this.mergeStatus.update(merge); this.emit(Git.ModelEvents.STATUS_MODEL_UPDATED); } public getIndexStatus(): Git.IStatusGroup { return this.indexStatus; } public getWorkingTreeStatus(): Git.IStatusGroup { return this.workingTreeStatus; } public getMergeStatus(): Git.IStatusGroup { return this.mergeStatus; } public getGroups(): Git.IStatusGroup[] { return [ this.mergeStatus, this.indexStatus, this.workingTreeStatus ]; } public find(path: string, type: Git.StatusType): Git.IFileStatus { var group: Git.IStatusGroup; switch (type) { case Git.StatusType.INDEX: group = this.indexStatus; break; case Git.StatusType.WORKING_TREE: group = this.workingTreeStatus; break; case Git.StatusType.MERGE: group = this.mergeStatus; break; default: return null; } return group.find(path); } public dispose(): void { this.toDispose = Lifecycle.disposeAll(this.toDispose); if (this.indexStatus) { this.indexStatus.dispose(); this.indexStatus = null; } if (this.workingTreeStatus) { this.workingTreeStatus.dispose(); this.workingTreeStatus = null; } if (this.mergeStatus) { this.mergeStatus.dispose(); this.mergeStatus = null; } super.dispose(); } } export class Model extends EventEmitter.EventEmitter implements Git.IModel { private repositoryRoot: string; private status: Git.IStatusModel; private HEAD: Git.IBranch; private heads: Git.IBranch[]; private tags: Git.ITag[]; private remotes: Git.IRemote[]; private toDispose: Lifecycle.IDisposable[]; constructor() { super(); this.toDispose = []; this.repositoryRoot = null; this.status = new StatusModel(); this.toDispose.push(this.addEmitter2(this.status)); this.HEAD = null; this.heads = []; this.tags = []; this.remotes = []; } public getRepositoryRoot(): string { return this.repositoryRoot; } public getStatus(): Git.IStatusModel { return this.status; } public getHEAD(): Git.IBranch { return this.HEAD; } public getHeads(): Git.IBranch[] { return this.heads; } public getTags(): Git.ITag[] { return this.tags; } public getRemotes(): Git.IRemote[] { return this.remotes; } public update(status: Git.IRawStatus): void { if (!status) { status = { repositoryRoot: null, status: [], HEAD: null, heads: [], tags: [], remotes: [] }; } this.repositoryRoot = status.repositoryRoot; this.status.update(status.status); this.HEAD = status.HEAD; this.emit(Git.ModelEvents.HEAD_UPDATED); this.heads = status.heads; this.emit(Git.ModelEvents.HEADS_UPDATED); this.tags = status.tags; this.emit(Git.ModelEvents.TAGS_UPDATED); this.remotes = status.remotes; this.emit(Git.ModelEvents.REMOTES_UPDATED); this.emit(Git.ModelEvents.MODEL_UPDATED); } public getStatusSummary(): Git.IStatusSummary { var status = this.getStatus(); return { hasWorkingTreeChanges: status.getWorkingTreeStatus().all().length > 0, hasIndexChanges: status.getIndexStatus().all().length > 0, hasMergeChanges: status.getMergeStatus().all().length > 0 }; } public getPS1(): string { if (!this.HEAD) { return ''; } var label = this.HEAD.name || this.HEAD.commit.substr(0, 8); var statusSummary = this.getStatus().getSummary(); return Strings.format('{0}{1}{2}{3}', label, statusSummary.hasWorkingTreeChanges ? '*' : '', statusSummary.hasIndexChanges ? '+' : '', statusSummary.hasMergeChanges ? '!' : '' ); } public dispose(): void { this.toDispose = Lifecycle.disposeAll(this.toDispose); super.dispose(); } }
src/vs/workbench/parts/git/common/gitModel.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.0010763664031401277, 0.0001965661213034764, 0.00016877338930498809, 0.00017547665629535913, 0.00013741618022322655 ]
{ "id": 5, "code_window": [ "\t\t'var ignoredCtrlCmdKeys = [67 /* c */];',\n", "\t\t'window.document.body.addEventListener(\"keydown\", function(event) {',\t\t// Listen to keydown events in the iframe\n", "\t\t'\ttry {',\n", "\t\t'\t\tif (ignoredKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some single keys to be supported (e.g. Page Down for scrolling)\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'var ignoredShiftKeys = [9 /* tab */];',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 206 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {CompletionItemProvider, CompletionItem, CompletionItemKind, CancellationToken, TextDocument, Range, Position} from 'vscode'; import phpGlobals = require('./phpGlobals'); export default class PHPCompletionItemProvider implements CompletionItemProvider { public triggerCharacters = ['.', ':', '$']; public provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): Promise<CompletionItem[]> { let result: CompletionItem[] = []; var range = document.getWordRangeAtPosition(position); var prefix = range ? document.getText(range) : ''; var added : any = {}; var createNewProposal = function(kind: CompletionItemKind, name: string, entry: phpGlobals.IEntry) : CompletionItem { var proposal : CompletionItem = new CompletionItem(name); proposal.kind = kind; if (entry) { if (entry.description) { proposal.documentation= entry.description; } if (entry.signature) { proposal.detail = entry.signature; } } return proposal; }; var matches = (name:string) => { return prefix.length === 0 || name.length > prefix.length && name.substr(0, prefix.length) === prefix; } for (var name in phpGlobals.globalvariables) { if (phpGlobals.globalvariables.hasOwnProperty(name) && matches(name)) { added[name] = true; result.push(createNewProposal(CompletionItemKind.Variable, name, phpGlobals.globalvariables[name])); } } for (var name in phpGlobals.globalfunctions) { if (phpGlobals.globalfunctions.hasOwnProperty(name) && matches(name)) { added[name] = true; result.push(createNewProposal(CompletionItemKind.Function, name, phpGlobals.globalfunctions[name])); } } for (var name in phpGlobals.compiletimeconstants) { if (phpGlobals.compiletimeconstants.hasOwnProperty(name) && matches(name)) { added[name] = true; result.push(createNewProposal(CompletionItemKind.Field, name, phpGlobals.compiletimeconstants[name])); } } for (var name in phpGlobals.keywords) { if (phpGlobals.keywords.hasOwnProperty(name) && matches(name)) { added[name] = true; result.push(createNewProposal(CompletionItemKind.Keyword, name, phpGlobals.keywords[name])); } } var text = document.getText(); if (matches('$')) { var variableMatch = /\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/g; var match : RegExpExecArray = null; while (match = variableMatch.exec(text)) { var word = match[0]; if (!added[word]) { added[word] = true; result.push(createNewProposal(CompletionItemKind.Variable, word, null)); } } } var functionMatch = /function\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/g; var match : RegExpExecArray = null; while (match = functionMatch.exec(text)) { var word = match[1]; if (!added[word]) { added[word] = true; result.push(createNewProposal(CompletionItemKind.Function, word, null)); } } return Promise.resolve(result); } }
extensions/php/src/features/completionItemProvider.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.0001776842982508242, 0.00017429905710741878, 0.00016604448319412768, 0.00017533899517729878, 0.0000032570060284342617 ]
{ "id": 6, "code_window": [ "\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n", "\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t'',\n", "\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n", "\t\t'\t\tObject.defineProperty(fakeEvent, \"keyCode\", {',\t\t\t\t\t\t// we need to set some properties that Chrome wants\n", "\t\t'\t\t\tget : function() {',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 220 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {ResourceEditorModel} from 'vs/workbench/common/editor/resourceEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.tabIndex = 0; iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel(input).then(model => { if (model instanceof ResourceEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [67 /* c */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } export function defaultStyle(element: HTMLElement): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize} }`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.9986984729766846, 0.1376524567604065, 0.00016179661906789988, 0.00017238965665455908, 0.34258636832237244 ]
{ "id": 6, "code_window": [ "\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n", "\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t'',\n", "\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n", "\t\t'\t\tObject.defineProperty(fakeEvent, \"keyCode\", {',\t\t\t\t\t\t// we need to set some properties that Chrome wants\n", "\t\t'\t\t\tget : function() {',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 220 }
<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="#E89208"><circle cx="8" cy="8" r="5"/></g></g></svg>
src/vs/workbench/parts/debug/browser/media/breakpoint-conditional.svg
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017266671056859195, 0.00017266671056859195, 0.00017266671056859195, 0.00017266671056859195, 0 ]
{ "id": 6, "code_window": [ "\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n", "\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t'',\n", "\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n", "\t\t'\t\tObject.defineProperty(fakeEvent, \"keyCode\", {',\t\t\t\t\t\t// we need to set some properties that Chrome wants\n", "\t\t'\t\t\tget : function() {',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 220 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import EventEmitter = require('vs/base/common/eventEmitter'); import EditorCommon = require('vs/editor/common/editorCommon'); export class ViewEventHandler { public shouldRender:boolean; constructor() { this.shouldRender = true; } // --- begin event handlers public onLineMappingChanged(): boolean { return false; } public onModelFlushed(): boolean { return false; } public onModelDecorationsChanged(e:EditorCommon.IViewDecorationsChangedEvent): boolean { return false; } public onModelLinesDeleted(e:EditorCommon.IViewLinesDeletedEvent): boolean { return false; } public onModelLineChanged(e:EditorCommon.IViewLineChangedEvent): boolean { return false; } public onModelLinesInserted(e:EditorCommon.IViewLinesInsertedEvent): boolean { return false; } public onModelTokensChanged(e:EditorCommon.IViewTokensChangedEvent): boolean { return false; } public onCursorPositionChanged(e:EditorCommon.IViewCursorPositionChangedEvent): boolean { return false; } public onCursorSelectionChanged(e:EditorCommon.IViewCursorSelectionChangedEvent): boolean { return false; } public onCursorRevealRange(e:EditorCommon.IViewRevealRangeEvent): boolean { return false; } public onCursorScrollRequest(e:EditorCommon.IViewScrollRequestEvent): boolean { return false; } public onConfigurationChanged(e:EditorCommon.IConfigurationChangedEvent): boolean { return false; } public onLayoutChanged(layoutInfo:EditorCommon.IEditorLayoutInfo): boolean { return false; } public onScrollChanged(e:EditorCommon.IScrollEvent): boolean { return false; } public onZonesChanged(): boolean { return false; } public onScrollWidthChanged(scrollWidth:number): boolean { return false; } public onScrollHeightChanged(scrollHeight:number): boolean { return false; } public onViewFocusChanged(isFocused:boolean): boolean { return false; } // --- end event handlers public handleEvents(events:EventEmitter.IEmitterEvent[]): void { var i:number, len:number, e:EventEmitter.IEmitterEvent, data:any; for (i = 0, len = events.length; i < len; i++) { e = events[i]; data = e.getData(); switch (e.getType()) { case EditorCommon.ViewEventNames.LineMappingChangedEvent: this.shouldRender = this.onLineMappingChanged() || this.shouldRender; break; case EditorCommon.ViewEventNames.ModelFlushedEvent: this.shouldRender = this.onModelFlushed() || this.shouldRender; break; case EditorCommon.ViewEventNames.LinesDeletedEvent: this.shouldRender = this.onModelLinesDeleted(<EditorCommon.IViewLinesDeletedEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.LinesInsertedEvent: this.shouldRender = this.onModelLinesInserted(<EditorCommon.IViewLinesInsertedEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.LineChangedEvent: this.shouldRender = this.onModelLineChanged(<EditorCommon.IViewLineChangedEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.TokensChangedEvent: this.shouldRender = this.onModelTokensChanged(<EditorCommon.IViewTokensChangedEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.DecorationsChangedEvent: this.shouldRender = this.onModelDecorationsChanged(<EditorCommon.IViewDecorationsChangedEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.CursorPositionChangedEvent: this.shouldRender = this.onCursorPositionChanged(<EditorCommon.IViewCursorPositionChangedEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.CursorSelectionChangedEvent: this.shouldRender = this.onCursorSelectionChanged(<EditorCommon.IViewCursorSelectionChangedEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.RevealRangeEvent: this.shouldRender = this.onCursorRevealRange(<EditorCommon.IViewRevealRangeEvent>data) || this.shouldRender; break; case EditorCommon.ViewEventNames.ScrollRequestEvent: this.shouldRender = this.onCursorScrollRequest(<EditorCommon.IViewScrollRequestEvent>data) || this.shouldRender; break; case EditorCommon.EventType.ConfigurationChanged: this.shouldRender = this.onConfigurationChanged(<EditorCommon.IConfigurationChangedEvent>data) || this.shouldRender; break; case EditorCommon.EventType.ViewLayoutChanged: this.shouldRender = this.onLayoutChanged(<EditorCommon.IEditorLayoutInfo>data) || this.shouldRender; break; case EditorCommon.EventType.ViewScrollChanged: this.shouldRender = this.onScrollChanged(<EditorCommon.IScrollEvent>data) || this.shouldRender; break; case EditorCommon.EventType.ViewZonesChanged: this.shouldRender = this.onZonesChanged() || this.shouldRender; break; case EditorCommon.EventType.ViewScrollWidthChanged: this.shouldRender = this.onScrollWidthChanged(<number>data) || this.shouldRender; break; case EditorCommon.EventType.ViewScrollHeightChanged: this.shouldRender = this.onScrollHeightChanged(<number>data) || this.shouldRender; break; case EditorCommon.EventType.ViewFocusChanged: this.shouldRender = this.onViewFocusChanged(<boolean>data) || this.shouldRender; break; default: console.info('View received unknown event: '); console.info(e); } } } }
src/vs/editor/common/viewModel/viewEventHandler.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017675271374173462, 0.00017092550115194172, 0.0001640278787817806, 0.00017188511264976114, 0.0000032551952244830318 ]
{ "id": 6, "code_window": [ "\t\t'\t\t\tif (event.ctrlKey || event.metaKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n", "\t\t'\t\tevent.preventDefault();',\t\t\t\t\t\t\t\t\t\t\t// very important to not get duplicate actions when this one bubbles up!\n", "\t\t'',\n", "\t\t'\t\tvar fakeEvent = document.createEvent(\"KeyboardEvent\");',\t\t\t// create a keyboard event\n", "\t\t'\t\tObject.defineProperty(fakeEvent, \"keyCode\", {',\t\t\t\t\t\t// we need to set some properties that Chrome wants\n", "\t\t'\t\t\tget : function() {',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'\t\tif (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {',\n", "\t\t'\t\t\tif (event.shiftKey) {',\n", "\t\t'\t\t\t\treturn;',\t\t\t\t\t\t\t\t\t\t\t\t\t// we want some shift keys to be supported (e.g. Shift+Tab for copy)\n", "\t\t'\t\t\t}',\n", "\t\t'\t\t}',\n", "\t\t'',\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 220 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import {setUnexpectedErrorHandler, errorHandler} from 'vs/base/common/errors'; import {create} from 'vs/base/common/types'; import URI from 'vs/base/common/uri'; import * as types from 'vs/workbench/api/node/extHostTypes'; import {Range as CodeEditorRange} from 'vs/editor/common/core/range'; import * as EditorCommon from 'vs/editor/common/editorCommon'; import {Model as EditorModel} from 'vs/editor/common/model/model'; import {TestThreadService} from './testThreadService' import {create as createInstantiationService} from 'vs/platform/instantiation/common/instantiationService'; import {MarkerService} from 'vs/platform/markers/common/markerService'; import {IMarkerService} from 'vs/platform/markers/common/markers'; import {IThreadService} from 'vs/platform/thread/common/thread'; import {ExtHostLanguageFeatures, MainThreadLanguageFeatures} from 'vs/workbench/api/node/extHostLanguageFeatures'; import {ExtHostCommands, MainThreadCommands} from 'vs/workbench/api/node/extHostCommands'; import {ExtHostModelService} from 'vs/workbench/api/node/extHostDocuments'; import {OutlineRegistry, getOutlineEntries} from 'vs/editor/contrib/quickOpen/common/quickOpen'; import {getCodeLensData} from 'vs/editor/contrib/codelens/common/codelens'; import {getDeclarationsAtPosition} from 'vs/editor/contrib/goToDeclaration/common/goToDeclaration'; import {getExtraInfoAtPosition} from 'vs/editor/contrib/hover/common/hover'; import {getOccurrencesAtPosition} from 'vs/editor/contrib/wordHighlighter/common/wordHighlighter'; import {findReferences} from 'vs/editor/contrib/referenceSearch/common/referenceSearch'; import {getQuickFixes} from 'vs/editor/contrib/quickFix/common/quickFix'; import {getNavigateToItems} from 'vs/workbench/parts/search/common/search'; import {rename} from 'vs/editor/contrib/rename/common/rename'; import {getParameterHints} from 'vs/editor/contrib/parameterHints/common/parameterHints'; import {suggest} from 'vs/editor/contrib/suggest/common/suggest'; import {formatDocument, formatRange, formatAfterKeystroke} from 'vs/editor/contrib/format/common/format'; const defaultSelector = { scheme: 'far' }; const model: EditorCommon.IModel = new EditorModel( [ 'This is the first line', 'This is the second line', 'This is the third line', ].join('\n'), undefined, URI.parse('far://testing/file.a')); let extHost: ExtHostLanguageFeatures; let mainThread: MainThreadLanguageFeatures; let disposables: vscode.Disposable[] = []; let threadService: TestThreadService; let originalErrorHandler: (e: any) => any; suite('ExtHostLanguageFeatures', function() { suiteSetup(() => { let instantiationService = createInstantiationService(); threadService = new TestThreadService(instantiationService); instantiationService.addSingleton(IMarkerService, new MarkerService(threadService)); instantiationService.addSingleton(IThreadService, threadService); originalErrorHandler = errorHandler.getUnexpectedErrorHandler(); setUnexpectedErrorHandler(() => { }); threadService.getRemotable(ExtHostModelService)._acceptModelAdd({ isDirty: false, versionId: model.getVersionId(), modeId: model.getModeId(), url: model.getAssociatedResource(), value: { EOL: model.getEOL(), lines: model.getValue().split(model.getEOL()), BOM: '', length: -1 }, }); threadService.getRemotable(ExtHostCommands); threadService.getRemotable(MainThreadCommands); mainThread = threadService.getRemotable(MainThreadLanguageFeatures); extHost = threadService.getRemotable(ExtHostLanguageFeatures); }); suiteTeardown(() => { setUnexpectedErrorHandler(originalErrorHandler); model.dispose(); }); teardown(function(done) { while (disposables.length) { disposables.pop().dispose(); } threadService.sync() .then(() => done(), err => done(err)); }); // --- outline test('DocumentSymbols, register/deregister', function(done) { assert.equal(OutlineRegistry.all(model).length, 0); let d1 = extHost.registerDocumentSymbolProvider(defaultSelector, <vscode.DocumentSymbolProvider>{ provideDocumentSymbols() { return []; } }); threadService.sync().then(() => { assert.equal(OutlineRegistry.all(model).length, 1); d1.dispose(); threadService.sync().then(() => { done(); }); }); }); test('DocumentSymbols, evil provider', function(done) { disposables.push(extHost.registerDocumentSymbolProvider(defaultSelector, <vscode.DocumentSymbolProvider>{ provideDocumentSymbols(): any { throw new Error('evil document symbol provider'); } })); disposables.push(extHost.registerDocumentSymbolProvider(defaultSelector, <vscode.DocumentSymbolProvider>{ provideDocumentSymbols(): any { return [new types.SymbolInformation('test', types.SymbolKind.Field, new types.Range(0, 0, 0, 0))]; } })); threadService.sync().then(() => { getOutlineEntries(model).then(value => { assert.equal(value.entries.length, 1); done(); }, err => { done(err); }); }); }); test('DocumentSymbols, data conversion', function(done) { disposables.push(extHost.registerDocumentSymbolProvider(defaultSelector, <vscode.DocumentSymbolProvider>{ provideDocumentSymbols(): any { return [new types.SymbolInformation('test', types.SymbolKind.Field, new types.Range(0, 0, 0, 0))]; } })); threadService.sync().then(() => { getOutlineEntries(model).then(value => { assert.equal(value.entries.length, 1); let entry = value.entries[0]; assert.equal(entry.label, 'test'); assert.deepEqual(entry.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }); done(); }, err => { done(err); }); }); }); // --- code lens test('CodeLens, evil provider', function(done) { disposables.push(extHost.registerCodeLensProvider(defaultSelector, <vscode.CodeLensProvider>{ provideCodeLenses(): any { throw new Error('evil') } })); disposables.push(extHost.registerCodeLensProvider(defaultSelector, <vscode.CodeLensProvider>{ provideCodeLenses() { return [new types.CodeLens(new types.Range(0, 0, 0, 0))]; } })); threadService.sync().then(() => { getCodeLensData(model).then(value => { assert.equal(value.length, 1); done(); }); }); }); test('CodeLens, do not resolve a resolved lens', function(done) { disposables.push(extHost.registerCodeLensProvider(defaultSelector, <vscode.CodeLensProvider>{ provideCodeLenses(): any { return [new types.CodeLens( new types.Range(0, 0, 0, 0), { command: 'id', title: 'Title' })]; }, resolveCodeLens(): any { assert.ok(false, 'do not resolve'); } })); threadService.sync().then(() => { getCodeLensData(model).then(value => { assert.equal(value.length, 1); let data = value[0]; data.support.resolveCodeLensSymbol(model.getAssociatedResource(), data.symbol).then(symbol => { assert.equal(symbol.command.id, 'id'); assert.equal(symbol.command.title, 'Title'); done(); }); }); }); }); test('CodeLens, missing command', function(done) { disposables.push(extHost.registerCodeLensProvider(defaultSelector, <vscode.CodeLensProvider>{ provideCodeLenses() { return [new types.CodeLens(new types.Range(0, 0, 0, 0))]; } })); threadService.sync().then(() => { getCodeLensData(model).then(value => { assert.equal(value.length, 1); let data = value[0]; data.support.resolveCodeLensSymbol(model.getAssociatedResource(), data.symbol).then(symbol => { assert.equal(symbol.command.id, 'missing'); assert.equal(symbol.command.title, '<<MISSING COMMAND>>'); done(); }); }); }); }); // --- definition test('Definition, data conversion', function(done) { disposables.push(extHost.registerDefinitionProvider(defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(): any { return [new types.Location(model.getAssociatedResource(), new types.Range(1, 2, 3, 4))]; } })); threadService.sync().then(() => { getDeclarationsAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 1); let [entry] = value; assert.deepEqual(entry.range, { startLineNumber: 2, startColumn: 3, endLineNumber: 4, endColumn: 5 }); assert.equal(entry.resource.toString(), model.getAssociatedResource().toString()); done(); }, err => { done(err); }); }); }); test('Definition, one or many', function(done) { disposables.push(extHost.registerDefinitionProvider(defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(): any { return [new types.Location(model.getAssociatedResource(), new types.Range(1, 1, 1, 1))]; } })); disposables.push(extHost.registerDefinitionProvider(defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(): any { return new types.Location(model.getAssociatedResource(), new types.Range(1, 1, 1, 1)); } })); threadService.sync().then(() => { getDeclarationsAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 2); done(); }, err => { done(err); }); }); }); test('Definition, registration order', function(done) { disposables.push(extHost.registerDefinitionProvider(defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(): any { return [new types.Location(URI.parse('far://first'), new types.Range(2, 3, 4, 5))]; } })); setTimeout(function() { // registration time matters disposables.push(extHost.registerDefinitionProvider(defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(): any { return new types.Location(URI.parse('far://second'), new types.Range(1, 2, 3, 4)); } })); threadService.sync().then(() => { getDeclarationsAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 2); // let [first, second] = value; assert.equal(value[0].resource.authority, 'second'); assert.equal(value[1].resource.authority, 'first'); done(); }, err => { done(err); }); }); }, 5); }); test('Definition, evil provider', function(done) { disposables.push(extHost.registerDefinitionProvider(defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(): any { throw new Error('evil provider') } })); disposables.push(extHost.registerDefinitionProvider(defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(): any { return new types.Location(model.getAssociatedResource(), new types.Range(1, 1, 1, 1)); } })); threadService.sync().then(() => { getDeclarationsAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 1); done(); }, err => { done(err); }); }); }); // --- extra info test('ExtraInfo, word range at pos', function(done) { disposables.push(extHost.registerHoverProvider(defaultSelector, <vscode.HoverProvider>{ provideHover(): any { return new types.Hover('Hello') } })); threadService.sync().then(() => { getExtraInfoAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 1); let [entry] = value; assert.deepEqual(entry.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 5 }); done(); }); }); }); test('ExtraInfo, given range', function(done) { disposables.push(extHost.registerHoverProvider(defaultSelector, <vscode.HoverProvider>{ provideHover(): any { return new types.Hover('Hello', new types.Range(3, 0, 8, 7)); } })); threadService.sync().then(() => { getExtraInfoAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 1); let [entry] = value; assert.deepEqual(entry.range, { startLineNumber: 4, startColumn: 1, endLineNumber: 9, endColumn: 8 }); done(); }); }); }); test('ExtraInfo, registration order', function(done) { disposables.push(extHost.registerHoverProvider(defaultSelector, <vscode.HoverProvider>{ provideHover(): any { return new types.Hover('registered first'); } })); setTimeout(function() { disposables.push(extHost.registerHoverProvider(defaultSelector, <vscode.HoverProvider>{ provideHover(): any { return new types.Hover('registered second'); } })); threadService.sync().then(() => { getExtraInfoAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 2); let [first, second] = value; assert.equal(first.htmlContent[0].formattedText, 'registered second'); assert.equal(second.htmlContent[0].formattedText, 'registered first'); done(); }); }); }, 5); }); test('ExtraInfo, evil provider', function(done) { disposables.push(extHost.registerHoverProvider(defaultSelector, <vscode.HoverProvider>{ provideHover(): any { throw new Error('evil') } })); disposables.push(extHost.registerHoverProvider(defaultSelector, <vscode.HoverProvider>{ provideHover(): any { return new types.Hover('Hello') } })); threadService.sync().then(() => { getExtraInfoAtPosition(model, { lineNumber: 1, column: 1 }).then(value => { assert.equal(value.length, 1); done(); }); }); }); // --- occurrences test('Occurrences, data conversion', function(done) { disposables.push(extHost.registerDocumentHighlightProvider(defaultSelector, <vscode.DocumentHighlightProvider>{ provideDocumentHighlights(): any { return [new types.DocumentHighlight(new types.Range(0, 0, 0, 4))] } })); threadService.sync().then(() => { getOccurrencesAtPosition(model, { lineNumber: 1, column: 2 }).then(value => { assert.equal(value.length, 1); let [entry] = value; assert.deepEqual(entry.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 5 }); assert.equal(entry.kind, 'text'); done(); }); }); }); test('Occurrences, order 1/2', function(done) { disposables.push(extHost.registerDocumentHighlightProvider(defaultSelector, <vscode.DocumentHighlightProvider>{ provideDocumentHighlights(): any { return [] } })); disposables.push(extHost.registerDocumentHighlightProvider('*', <vscode.DocumentHighlightProvider>{ provideDocumentHighlights(): any { return [new types.DocumentHighlight(new types.Range(0, 0, 0, 4))] } })); threadService.sync().then(() => { getOccurrencesAtPosition(model, { lineNumber: 1, column: 2 }).then(value => { assert.equal(value.length, 1); let [entry] = value; assert.deepEqual(entry.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 5 }); assert.equal(entry.kind, 'text'); done(); }); }); }); test('Occurrences, order 2/2', function(done) { disposables.push(extHost.registerDocumentHighlightProvider(defaultSelector, <vscode.DocumentHighlightProvider>{ provideDocumentHighlights(): any { return [new types.DocumentHighlight(new types.Range(0, 0, 0, 2))] } })); disposables.push(extHost.registerDocumentHighlightProvider('*', <vscode.DocumentHighlightProvider>{ provideDocumentHighlights(): any { return [new types.DocumentHighlight(new types.Range(0, 0, 0, 4))] } })); threadService.sync().then(() => { getOccurrencesAtPosition(model, { lineNumber: 1, column: 2 }).then(value => { assert.equal(value.length, 1); let [entry] = value; assert.deepEqual(entry.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 3 }); assert.equal(entry.kind, 'text'); done(); }); }); }); test('Occurrences, evil provider', function(done) { disposables.push(extHost.registerDocumentHighlightProvider(defaultSelector, <vscode.DocumentHighlightProvider>{ provideDocumentHighlights(): any { throw new Error('evil'); } })); disposables.push(extHost.registerDocumentHighlightProvider(defaultSelector, <vscode.DocumentHighlightProvider>{ provideDocumentHighlights(): any { return [new types.DocumentHighlight(new types.Range(0, 0, 0, 4))] } })); threadService.sync().then(() => { getOccurrencesAtPosition(model, { lineNumber: 1, column: 2 }).then(value => { assert.equal(value.length, 1); done(); }); }); }); // --- references test('References, registration order', function(done) { disposables.push(extHost.registerReferenceProvider(defaultSelector, <vscode.ReferenceProvider>{ provideReferences(): any { return [new types.Location(URI.parse('far://register/first'), new types.Range(0, 0, 0, 0))]; } })); setTimeout(function() { disposables.push(extHost.registerReferenceProvider(defaultSelector, <vscode.ReferenceProvider>{ provideReferences(): any { return [new types.Location(URI.parse('far://register/second'), new types.Range(0, 0, 0, 0))]; } })); threadService.sync().then(() => { findReferences(model, { lineNumber: 1, column: 2 }).then(value => { assert.equal(value.length, 2); let [first, second] = value; assert.equal(first.resource.path, '/second'); assert.equal(second.resource.path, '/first'); done(); }); }); }, 5); }); test('References, data conversion', function(done) { disposables.push(extHost.registerReferenceProvider(defaultSelector, <vscode.ReferenceProvider>{ provideReferences(): any { return [new types.Location(model.getAssociatedResource(), new types.Position(0, 0))]; } })); threadService.sync().then(() => { findReferences(model, { lineNumber: 1, column: 2 }).then(value => { assert.equal(value.length, 1); let [item] = value; assert.deepEqual(item.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }); assert.equal(item.resource.toString(), model.getAssociatedResource().toString()); done(); }); }); }); test('References, evil provider', function(done) { disposables.push(extHost.registerReferenceProvider(defaultSelector, <vscode.ReferenceProvider>{ provideReferences(): any { throw new Error('evil'); } })); disposables.push(extHost.registerReferenceProvider(defaultSelector, <vscode.ReferenceProvider>{ provideReferences(): any { return [new types.Location(model.getAssociatedResource(), new types.Range(0, 0, 0, 0))]; } })); threadService.sync().then(() => { findReferences(model, { lineNumber: 1, column: 2 }).then(value => { assert.equal(value.length, 1); done(); }); }); }); // --- quick fix test('Quick Fix, data conversion', function(done) { disposables.push(extHost.registerCodeActionProvider(defaultSelector, <vscode.CodeActionProvider>{ provideCodeActions(): any { return [ <vscode.Command>{ command: 'test1', title: 'Testing1' }, <vscode.Command>{ command: 'test2', title: 'Testing2' } ]; } })); threadService.sync().then(() => { getQuickFixes(model, model.getFullModelRange()).then(value => { assert.equal(value.length, 2); let [first, second] = value; assert.equal(first.command.title, 'Testing1'); assert.equal(first.command.id, 'test1'); assert.equal(second.command.title, 'Testing2'); assert.equal(second.command.id, 'test2'); done(); }); }); }); test('Quick Fix, invoke command+args', function(done) { let actualArgs: any; let commands = threadService.getRemotable(ExtHostCommands); disposables.push(commands.registerCommand('test1', function(...args: any[]) { actualArgs = args; })); disposables.push(extHost.registerCodeActionProvider(defaultSelector, <vscode.CodeActionProvider>{ provideCodeActions(): any { return [<vscode.Command>{ command: 'test1', title: 'Testing', arguments: [true, 1, { bar: 'boo', foo: 'far' }, null] }]; } })); threadService.sync().then(() => { getQuickFixes(model, model.getFullModelRange()).then(value => { assert.equal(value.length, 1); let [entry] = value; entry.support.runQuickFixAction(model.getAssociatedResource(), model.getFullModelRange(), entry).then(value => { assert.equal(value, undefined); assert.equal(actualArgs.length, 4); assert.equal(actualArgs[0], true) assert.equal(actualArgs[1], 1) assert.deepEqual(actualArgs[2], { bar: 'boo', foo: 'far' }); assert.equal(actualArgs[3], null) done(); }); }); }); }); test('Quick Fix, evil provider', function(done) { disposables.push(extHost.registerCodeActionProvider(defaultSelector, <vscode.CodeActionProvider>{ provideCodeActions(): any { throw new Error('evil'); } })); disposables.push(extHost.registerCodeActionProvider(defaultSelector, <vscode.CodeActionProvider>{ provideCodeActions(): any { return [<vscode.Command>{ command: 'test', title: 'Testing' }]; } })); threadService.sync().then(() => { getQuickFixes(model, model.getFullModelRange()).then(value => { assert.equal(value.length, 1); done(); }); }); }); // --- navigate types test('Navigate types, evil provider', function(done) { disposables.push(extHost.registerWorkspaceSymbolProvider(<vscode.WorkspaceSymbolProvider>{ provideWorkspaceSymbols(): any { throw new Error('evil'); } })); disposables.push(extHost.registerWorkspaceSymbolProvider(<vscode.WorkspaceSymbolProvider>{ provideWorkspaceSymbols(): any { return [new types.SymbolInformation('testing', types.SymbolKind.Array, new types.Range(0, 0, 1, 1))] } })); threadService.sync().then(() => { getNavigateToItems('').then(value => { assert.equal(value.length, 1); done(); }); }); }); // --- rename test('Rename, evil provider 1/2', function(done) { disposables.push(extHost.registerRenameProvider(defaultSelector, <vscode.RenameProvider>{ provideRenameEdits(): any { throw Error('evil'); } })); threadService.sync().then(() => { rename(model, { lineNumber: 1, column: 1 }, 'newName').then(value => { done(new Error('')); }, err => { done(); // expected }); }); }); test('Rename, evil provider 2/2', function(done) { disposables.push(extHost.registerRenameProvider('*', <vscode.RenameProvider>{ provideRenameEdits(): any { throw Error('evil'); } })); disposables.push(extHost.registerRenameProvider(defaultSelector, <vscode.RenameProvider>{ provideRenameEdits(): any { let edit = new types.WorkspaceEdit(); edit.replace(model.getAssociatedResource(), new types.Range(0, 0, 0, 0), 'testing'); return edit; } })); threadService.sync().then(() => { rename(model, { lineNumber: 1, column: 1 }, 'newName').then(value => { assert.equal(value.edits.length, 1); done(); }); }); }); test('Rename, ordering', function(done) { disposables.push(extHost.registerRenameProvider('*', <vscode.RenameProvider>{ provideRenameEdits(): any { let edit = new types.WorkspaceEdit(); edit.replace(model.getAssociatedResource(), new types.Range(0, 0, 0, 0), 'testing'); edit.replace(model.getAssociatedResource(), new types.Range(1, 0, 1, 0), 'testing'); return edit; } })); disposables.push(extHost.registerRenameProvider(defaultSelector, <vscode.RenameProvider>{ provideRenameEdits(): any { return; } })); threadService.sync().then(() => { rename(model, { lineNumber: 1, column: 1 }, 'newName').then(value => { assert.equal(value.edits.length, 2); // least relevant renamer done(); }); }); }); // --- parameter hints test('Parameter Hints, evil provider', function(done) { disposables.push(extHost.registerSignatureHelpProvider(defaultSelector, <vscode.SignatureHelpProvider>{ provideSignatureHelp(): any { throw new Error('evil'); } }, [])); threadService.sync().then(() => { getParameterHints(model, { lineNumber: 1, column: 1 }, '(').then(value => { done(new Error('error expeted')); }, err => { assert.equal(err.message, 'evil'); done(); }) }); }); // --- suggestions test('Suggest, order 1/3', function(done) { disposables.push(extHost.registerCompletionItemProvider('*', <vscode.CompletionItemProvider>{ provideCompletionItems(): any { return [new types.CompletionItem('testing1')]; } }, [])); disposables.push(extHost.registerCompletionItemProvider(defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { return [new types.CompletionItem('testing2')]; } }, [])); threadService.sync().then(() => { suggest(model, { lineNumber: 1, column: 1 }, ',').then(value => { assert.equal(value.length, 1); let [[first]] = value; assert.equal(first.suggestions.length, 1) assert.equal(first.suggestions[0].codeSnippet, 'testing2') done(); }); }); }); test('Suggest, order 2/3', function(done) { disposables.push(extHost.registerCompletionItemProvider('*', <vscode.CompletionItemProvider>{ provideCompletionItems(): any { return [new types.CompletionItem('weak-selector')]; // weaker selector but result } }, [])); disposables.push(extHost.registerCompletionItemProvider(defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { return []; // stronger selector but not a good result; } }, [])); threadService.sync().then(() => { suggest(model, { lineNumber: 1, column: 1 }, ',').then(value => { assert.equal(value.length, 1); let [[first]] = value; assert.equal(first.suggestions.length, 1) assert.equal(first.suggestions[0].codeSnippet, 'weak-selector') done(); }); }); }) test('Suggest, order 2/3', function(done) { disposables.push(extHost.registerCompletionItemProvider(defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { return [new types.CompletionItem('strong-1')]; } }, [])); setTimeout(function() { disposables.push(extHost.registerCompletionItemProvider(defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { return [new types.CompletionItem('strong-2')]; } }, [])); threadService.sync().then(() => { suggest(model, { lineNumber: 1, column: 1 }, ',').then(value => { assert.equal(value.length, 2); let [[first], [second]] = value; assert.equal(first.suggestions.length, 1) assert.equal(first.suggestions[0].codeSnippet, 'strong-2') // last wins assert.equal(second.suggestions[0].codeSnippet, 'strong-1') done(); }); }); }, 5); }) test('Suggest, evil provider', function(done) { disposables.push(extHost.registerCompletionItemProvider(defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { throw new Error('evil'); } }, [])); disposables.push(extHost.registerCompletionItemProvider(defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { return [new types.CompletionItem('testing')]; } }, [])); threadService.sync().then(() => { suggest(model, { lineNumber: 1, column: 1 }, ',').then(value => { assert.equal(value.length, 1); done(); }); }); }); // --- format test('Format Doc, data conversion', function(done) { disposables.push(extHost.registerDocumentFormattingEditProvider(defaultSelector, <vscode.DocumentFormattingEditProvider>{ provideDocumentFormattingEdits(): any { return [new types.TextEdit(new types.Range(0, 0, 1, 1), 'testing')]; } })); threadService.sync().then(() => { formatDocument(model, { insertSpaces: true, tabSize: 4 }).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.text, 'testing'); assert.deepEqual(first.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 2 }); done(); }); }); }); test('Format Doc, evil provider', function(done) { disposables.push(extHost.registerDocumentFormattingEditProvider(defaultSelector, <vscode.DocumentFormattingEditProvider>{ provideDocumentFormattingEdits(): any { throw new Error('evil'); } })); threadService.sync().then(() => { formatDocument(model, { insertSpaces: true, tabSize: 4 }).then(undefined, err => done()); }); }); test('Format Range, data conversion', function(done) { disposables.push(extHost.registerDocumentRangeFormattingEditProvider(defaultSelector, <vscode.DocumentRangeFormattingEditProvider>{ provideDocumentRangeFormattingEdits(): any { return [new types.TextEdit(new types.Range(0, 0, 1, 1), 'testing')]; } })); threadService.sync().then(() => { formatRange(model, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, { insertSpaces: true, tabSize: 4 }).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.text, 'testing'); assert.deepEqual(first.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 2 }); done(); }); }); }) test('Format Range, + format_doc', function(done) { disposables.push(extHost.registerDocumentRangeFormattingEditProvider(defaultSelector, <vscode.DocumentRangeFormattingEditProvider>{ provideDocumentRangeFormattingEdits(): any { return [new types.TextEdit(new types.Range(0, 0, 1, 1), 'range')]; } })); disposables.push(extHost.registerDocumentFormattingEditProvider(defaultSelector, <vscode.DocumentFormattingEditProvider>{ provideDocumentFormattingEdits(): any { return [new types.TextEdit(new types.Range(0, 0, 1, 1), 'doc')]; } })); threadService.sync().then(() => { formatRange(model, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, { insertSpaces: true, tabSize: 4 }).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.text, 'range'); done(); }); }); }); test('Format Range, evil provider', function(done) { disposables.push(extHost.registerDocumentRangeFormattingEditProvider(defaultSelector, <vscode.DocumentRangeFormattingEditProvider>{ provideDocumentRangeFormattingEdits(): any { throw new Error('evil'); } })); threadService.sync().then(() => { formatRange(model, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, { insertSpaces: true, tabSize: 4 }).then(undefined, err => done()); }); }) test('Format on Type, data conversion', function(done) { disposables.push(extHost.registerOnTypeFormattingEditProvider(defaultSelector, <vscode.OnTypeFormattingEditProvider>{ provideOnTypeFormattingEdits(): any { return [new types.TextEdit(new types.Range(0, 0, 0, 0), arguments[2])]; } }, [';'])); threadService.sync().then(() => { formatAfterKeystroke(model, { lineNumber: 1, column: 1 }, ';', { insertSpaces: true, tabSize: 2 }).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.text, ';'); assert.deepEqual(first.range, { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }); done(); }); }); }); });
src/vs/workbench/test/common/api/extHostLanguageFeatures.test.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017633859533816576, 0.0001711429940769449, 0.00015886023174971342, 0.00017172204388771206, 0.000003124587010461255 ]
{ "id": 7, "code_window": [ "\t\t'});',\n", "\t\t'window.document.body.addEventListener(\"drop\", function (e) {',\n", "\t\t'\te.preventDefault();',\n", "\t\t'});',\n", "\t];\n", "\n", "\texport function defaultHtml() {\n", "\t\tlet all = [\n", "\t\t\t'<html><head></head><body><script>',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'});'\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 257 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {ResourceEditorModel} from 'vs/workbench/common/editor/resourceEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.tabIndex = 0; iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel(input).then(model => { if (model instanceof ResourceEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [67 /* c */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } export function defaultStyle(element: HTMLElement): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize} }`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.9987310767173767, 0.0722392275929451, 0.0001642105053178966, 0.00017146703612525016, 0.2524319887161255 ]
{ "id": 7, "code_window": [ "\t\t'});',\n", "\t\t'window.document.body.addEventListener(\"drop\", function (e) {',\n", "\t\t'\te.preventDefault();',\n", "\t\t'});',\n", "\t];\n", "\n", "\texport function defaultHtml() {\n", "\t\tlet all = [\n", "\t\t\t'<html><head></head><body><script>',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'});'\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 257 }
/** * The singleton meta class for the default client of the client. This class is used to setup/start and configure * the auto-collection behavior of the application insights module. */ declare module ApplicationInsights { var client: any; /** * Initializes a client with the given instrumentation key, if this is not specified, the value will be * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY * @returns {ApplicationInsights/Client} a new client */ function getClient(instrumentationKey?: string): any /*Client*/; /** * Initializes the default client of the client and sets the default configuration * @param instrumentationKey the instrumentation key to use. Optional, if this is not specified, the value will be * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY * @returns {ApplicationInsights} this class */ function setup(instrumentationKey?: string): typeof ApplicationInsights; /** * Starts automatic collection of telemetry. Prior to calling start no telemetry will be collected * @returns {ApplicationInsights} this class */ function start(): typeof ApplicationInsights; /** * Sets the state of console tracking (enabled by default) * @param value if true console activity will be sent to Application Insights * @returns {ApplicationInsights} this class */ function setAutoCollectConsole(value: boolean): typeof ApplicationInsights; /** * Sets the state of exception tracking (enabled by default) * @param value if true uncaught exceptions will be sent to Application Insights * @returns {ApplicationInsights} this class */ function setAutoCollectExceptions(value: boolean): typeof ApplicationInsights; /** * Sets the state of performance tracking (enabled by default) * @param value if true performance counters will be collected every second and sent to Application Insights * @returns {ApplicationInsights} this class */ function setAutoCollectPerformance(value: boolean): typeof ApplicationInsights; /** * Sets the state of request tracking (enabled by default) * @param value if true requests will be sent to Application Insights * @returns {ApplicationInsights} this class */ function setAutoCollectRequests(value: boolean): typeof ApplicationInsights; /** * Sets the state of enabling offline mode to cache event when client is offline (disabled by default) * @param value if true events that happen while client is offline will be cahced on disk, * client will retry to send events when back online * @returns {ApplicationInsights} this class */ function setOfflineMode(value: boolean): typeof ApplicationInsights; /** * Enables verbose debug logging * @returns {ApplicationInsights} this class */ function enableVerboseLogging(): typeof ApplicationInsights; } declare module 'applicationinsights' { export = ApplicationInsights; }
src/typings/applicationInsights.d.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00029925035778433084, 0.00019244516442995518, 0.0001683643349679187, 0.00017014505283441395, 0.0000447426937171258 ]
{ "id": 7, "code_window": [ "\t\t'});',\n", "\t\t'window.document.body.addEventListener(\"drop\", function (e) {',\n", "\t\t'\te.preventDefault();',\n", "\t\t'});',\n", "\t];\n", "\n", "\texport function defaultHtml() {\n", "\t\tlet all = [\n", "\t\t\t'<html><head></head><body><script>',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'});'\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 257 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import assert = require('assert'); import uri from 'vs/base/common/uri'; import { Source } from 'vs/workbench/parts/debug/common/debugSource'; suite('Debug - Source', () => { test('from raw source', () => { const rawSource = { name: 'zz', path: '/xx/yy/zz', sourceReference: 0 }; const source = new Source(rawSource); assert.equal(source.available, true); assert.equal(source.name, rawSource.name); assert.equal(source.inMemory, false); assert.equal(source.reference, rawSource.sourceReference); assert.equal(source.uri.toString(), uri.file(rawSource.path).toString()); }); test('from raw internal source', () => { const rawSource = { name: 'internalModule.js', sourceReference: 11 }; const source = new Source(rawSource); assert.equal(source.available, true); assert.equal(source.name, rawSource.name); assert.equal(source.inMemory, true); assert.equal(source.reference, rawSource.sourceReference); }); });
src/vs/workbench/parts/debug/test/common/debugSource.test.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017511994519736618, 0.00017383461818099022, 0.00017104865401051939, 0.00017458492948208004, 0.0000016355612615370774 ]
{ "id": 7, "code_window": [ "\t\t'});',\n", "\t\t'window.document.body.addEventListener(\"drop\", function (e) {',\n", "\t\t'\te.preventDefault();',\n", "\t\t'});',\n", "\t];\n", "\n", "\texport function defaultHtml() {\n", "\t\tlet all = [\n", "\t\t\t'<html><head></head><body><script>',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t'});'\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 257 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {IStream} from 'vs/editor/common/modes'; export class LineStream implements IStream { static STRING_TO_ARRAY_CACHE:{ [key:string]:boolean[]; } = {}; /*protected*/ _source:string; private sourceLength:number; /*protected*/ _pos:number; private whitespace:string; private whitespaceArr:boolean[]; private separators:string; private separatorsArr:boolean[]; private tokenStart:number; private tokenEnd:number; constructor(source:string) { this._source = source; this.sourceLength = source.length; this._pos = 0; this.whitespace = '\t \u00a0'; this.whitespaceArr = this.stringToArray(this.whitespace); this.separators = ''; this.separatorsArr = this.stringToArray(this.separators); this.tokenStart = -1; this.tokenEnd = -1; } private stringToArray(str:string):boolean[] { if (!LineStream.STRING_TO_ARRAY_CACHE.hasOwnProperty(str)) { LineStream.STRING_TO_ARRAY_CACHE[str] = this.actualStringToArray(str); } return LineStream.STRING_TO_ARRAY_CACHE[str]; } private actualStringToArray(str:string):boolean[] { let maxCharCode = 0; for (let i = 0; i < str.length; i++) { maxCharCode = Math.max(maxCharCode, str.charCodeAt(i)); } let r:boolean[] = []; for (let i = 0; i <= maxCharCode; i++) { r[i] = false; } for (let i = 0; i < str.length; i++) { r[str.charCodeAt(i)] = true; } return r; } public pos():number { return this._pos; } public eos() { return this._pos >= this.sourceLength; } public peek():string { // Check EOS if (this._pos >= this.sourceLength) { throw new Error('Stream is at the end'); } return this._source[this._pos]; } public next():string { // Check EOS if (this._pos >= this.sourceLength) { throw new Error('Stream is at the end'); } // Reset peeked token this.tokenStart = -1; this.tokenEnd = -1; return this._source[this._pos++]; } public next2(): void { // Check EOS if (this._pos >= this.sourceLength) { throw new Error('Stream is at the end'); } // Reset peeked token this.tokenStart = -1; this.tokenEnd = -1; this._pos++; } public advance(n: number): string { if (n === 0) { return ''; } var oldPos = this._pos; this._pos += n; // Reset peeked token this.tokenStart = -1; this.tokenEnd = -1; return this._source.substring(oldPos, this._pos); } private _advance2(n: number): number { if (n === 0) { return n; } this._pos += n; // Reset peeked token this.tokenStart = -1; this.tokenEnd = -1; return n; } public advanceToEOS():string { var oldPos = this._pos; this._pos = this.sourceLength; this.resetPeekedToken(); return this._source.substring(oldPos, this._pos); } public goBack(n:number) { this._pos -= n; this.resetPeekedToken(); } private createPeeker(condition:any):()=>number { if (condition instanceof RegExp) { return () => { var result = condition.exec(this._source.substr(this._pos)); if (result === null) { return 0; } else if (result.index !== 0) { throw new Error('Regular expression must begin with the character "^"'); } return result[0].length; }; } else if ((condition instanceof String || (typeof condition) === 'string') && condition) { return () => { var len = (<String> condition).length, match = this._pos + len <= this.sourceLength; for (var i = 0; match && i < len; i++) { match = this._source.charCodeAt(this._pos + i) === (<String> condition).charCodeAt(i); } return match ? len : 0; }; } throw new Error('Condition must be either a regular expression, function or a non-empty string'); } // --- BEGIN `_advanceIfStringCaseInsensitive` private _advanceIfStringCaseInsensitive(condition:string): number { var oldPos = this._pos, source = this._source, len = condition.length, i:number; if (len < 1 || oldPos + len > this.sourceLength) { return 0; } for (i = 0; i < len; i++) { if (source.charAt(oldPos + i).toLowerCase() !== condition.charAt(i).toLowerCase()) { return 0; } } return len; } public advanceIfStringCaseInsensitive(condition: string): string { return this.advance(this._advanceIfStringCaseInsensitive(condition)); } public advanceIfStringCaseInsensitive2(condition: string): number { return this._advance2(this._advanceIfStringCaseInsensitive(condition)); } // --- END // --- BEGIN `advanceIfString` private _advanceIfString(condition: string): number { var oldPos = this._pos, source = this._source, len = condition.length, i:number; if (len < 1 || oldPos + len > this.sourceLength) { return 0; } for (i = 0; i < len; i++) { if (source.charCodeAt(oldPos + i) !== condition.charCodeAt(i)) { return 0; } } return len; } public advanceIfString(condition:string): string { return this.advance(this._advanceIfString(condition)); } public advanceIfString2(condition: string): number { return this._advance2(this._advanceIfString(condition)); } // --- END // --- BEGIN `advanceIfString` private _advanceIfCharCode(charCode:number): number { if (this._pos < this.sourceLength && this._source.charCodeAt(this._pos) === charCode) { return 1; } return 0; } public advanceIfCharCode(charCode: number): string { return this.advance(this._advanceIfCharCode(charCode)); } public advanceIfCharCode2(charCode: number): number { return this._advance2(this._advanceIfCharCode(charCode)); } // --- END // --- BEGIN `advanceIfRegExp` private _advanceIfRegExp(condition:RegExp): number { if (this._pos >= this.sourceLength) { return 0; } if (!condition.test(this._source.substr(this._pos))) { return 0; } return RegExp.lastMatch.length; } public advanceIfRegExp(condition: RegExp): string { return this.advance(this._advanceIfRegExp(condition)); } public advanceIfRegExp2(condition: RegExp): number { return this._advance2(this._advanceIfRegExp(condition)); } // --- END private advanceLoop(condition:any, isWhile:boolean, including:boolean):string { if (this.eos()) { return ''; } var peeker = this.createPeeker(condition); var oldPos = this._pos; var n = 0; var f = null; if (isWhile) { f = (n) => { return n > 0; }; } else { f = (n) => { return n === 0; }; } while (!this.eos() && f(n = peeker())) { if (n > 0) { this.advance(n); } else { this.next(); } } if (including && !this.eos()) { this.advance(n); } return this._source.substring(oldPos, this._pos); } public advanceWhile(condition:any):string { return this.advanceLoop(condition, true, false); } public advanceUntil(condition:any, including:boolean):string { return this.advanceLoop(condition, false, including); } // --- BEGIN `advanceUntilString` private _advanceUntilString(condition: string, including: boolean): number { if (this.eos() || condition.length === 0) { return 0; } var oldPos = this._pos; var index = this._source.indexOf(condition, oldPos); if (index === -1) { // String was not found => advanced to `eos` return (this.sourceLength - oldPos); } if (including) { // String was found => advance to include `condition` return (index + condition.length - oldPos); } // String was found => advance right before `condition` return (index - oldPos); } public advanceUntilString(condition: string, including: boolean): string { return this.advance(this._advanceUntilString(condition, including)); } public advanceUntilString2(condition: string, including: boolean): number { return this._advance2(this._advanceUntilString(condition, including)); } // --- END private resetPeekedToken() { this.tokenStart = -1; this.tokenEnd = -1; } public setTokenRules(separators:string, whitespace:string):void { if (this.separators !== separators || this.whitespace !== whitespace) { this.separators = separators; this.separatorsArr = this.stringToArray(this.separators); this.whitespace = whitespace; this.whitespaceArr = this.stringToArray(this.whitespace); this.resetPeekedToken(); } } // --- tokens public peekToken():string { if (this.tokenStart !== -1) { return this._source.substring(this.tokenStart, this.tokenEnd); } var source = this._source, sourceLength = this.sourceLength, whitespaceArr = this.whitespaceArr, separatorsArr = this.separatorsArr, tokenStart = this._pos; // Check EOS if (tokenStart >= sourceLength) { throw new Error('Stream is at the end'); } // Skip whitespace while (whitespaceArr[source.charCodeAt(tokenStart)] && tokenStart < sourceLength) { tokenStart++; } var tokenEnd = tokenStart; // If a separator is hit, it is a token if (separatorsArr[source.charCodeAt(tokenEnd)] && tokenEnd < sourceLength) { tokenEnd++; } else { // Advance until a separator or a whitespace is hit while (!separatorsArr[source.charCodeAt(tokenEnd)] && !whitespaceArr[source.charCodeAt(tokenEnd)] && tokenEnd < sourceLength) { tokenEnd++; } } // Cache peeked token this.tokenStart = tokenStart; this.tokenEnd = tokenEnd; return source.substring(tokenStart, tokenEnd); } public nextToken():string { // Check EOS if (this._pos >= this.sourceLength) { throw new Error('Stream is at the end'); } // Peek token if necessary var result:string; if (this.tokenStart === -1) { result = this.peekToken(); } else { result = this._source.substring(this.tokenStart, this.tokenEnd); } // Advance to tokenEnd this._pos = this.tokenEnd; // Reset peeked token this.tokenStart = -1; this.tokenEnd = -1; return result; } // -- whitespace public peekWhitespace():string { var source = this._source, sourceLength = this.sourceLength, whitespaceArr = this.whitespaceArr, peek = this._pos; while (whitespaceArr[source.charCodeAt(peek)] && peek < sourceLength) { peek++; } return source.substring(this._pos, peek); } // --- BEGIN `advanceIfRegExp` private _skipWhitespace(): number { var source = this._source, sourceLength = this.sourceLength, whitespaceArr = this.whitespaceArr, oldPos = this._pos, peek = this._pos; while (whitespaceArr[source.charCodeAt(peek)] && peek < sourceLength) { peek++; } return (peek - oldPos); } public skipWhitespace(): string { return this.advance(this._skipWhitespace()); } public skipWhitespace2(): number { return this._advance2(this._skipWhitespace()); } // --- END }
src/vs/editor/common/modes/lineStream.ts
0
https://github.com/microsoft/vscode/commit/4089296e91405d35930e8a1c3397037a108f2886
[ 0.00017715446301735938, 0.00017138863040599972, 0.0001637364475755021, 0.00017178221605718136, 0.0000023802458599675447 ]
{ "id": 0, "code_window": [ "import { IWorkbenchUIElementFactory } from 'vs/editor/browser/widget/multiDiffEditorWidget/workbenchUIElementFactory';\n", "import { Event } from 'vs/base/common/event';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IDiffEditor } from 'vs/editor/common/editorCommon';\n", "import { ICodeEditor } from 'vs/editor/browser/editorBrowser';\n", "\n", "export class MultiDiffEditorWidget extends Disposable {\n", "\tprivate readonly _dimension = observableValue<Dimension | undefined>(this, undefined);\n", "\tprivate readonly _viewModel = observableValue<MultiDiffEditorViewModel | undefined>(this, undefined);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditor/diffEditorWidget';\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "add", "edit_start_line_idx": 20 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Codicon } from 'vs/base/common/codicons'; import { Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { IObservable, observableFromEvent } from 'vs/base/common/observable'; import { URI } from 'vs/base/common/uri'; import { localize, localize2 } from 'vs/nls'; import { Action2, MenuId } from 'vs/platform/actions/common/actions'; import { ContextKeyExpr, ContextKeyValue } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IMultiDiffSourceResolver, IMultiDiffSourceResolverService, IResolvedMultiDiffSource, MultiDiffEditorItem } from 'vs/workbench/contrib/multiDiffEditor/browser/multiDiffSourceResolverService'; import { ISCMResourceGroup, ISCMService } from 'vs/workbench/contrib/scm/common/scm'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; export class ScmMultiDiffSourceResolver implements IMultiDiffSourceResolver { private static readonly _scheme = 'scm-multi-diff-source'; public static getMultiDiffSourceUri(repositoryUri: string, groupId: string): URI { return URI.from({ scheme: ScmMultiDiffSourceResolver._scheme, query: JSON.stringify({ repositoryUri, groupId } satisfies UriFields), }); } private static parseUri(uri: URI): { repositoryUri: URI; groupId: string } | undefined { if (uri.scheme !== ScmMultiDiffSourceResolver._scheme) { return undefined; } let query: any; try { query = JSON.parse(uri.query) as UriFields; } catch (e) { return undefined; } if (typeof query !== 'object' || query === null) { return undefined; } const { repositoryUri, groupId } = query; if (typeof repositoryUri !== 'string' || typeof groupId !== 'string') { return undefined; } return { repositoryUri: URI.parse(repositoryUri), groupId }; } constructor( @ISCMService private readonly _scmService: ISCMService, ) { } canHandleUri(uri: URI): boolean { return ScmMultiDiffSourceResolver.parseUri(uri) !== undefined; } async resolveDiffSource(uri: URI): Promise<IResolvedMultiDiffSource> { const { repositoryUri, groupId } = ScmMultiDiffSourceResolver.parseUri(uri)!; const repository = await promiseFromEventState( this._scmService.onDidAddRepository, () => { const repository = [...this._scmService.repositories].find(r => r.provider.rootUri?.toString() === repositoryUri.toString()); return repository ?? false; } ); const group = await promiseFromEventState( repository.provider.onDidChangeResourceGroups, () => { const group = repository.provider.groups.find(g => g.id === groupId); return group ?? false; } ); const resources = observableFromEvent<MultiDiffEditorItem[]>(group.onDidChangeResources, () => group.resources.map(e => { return { original: e.multiDiffEditorOriginalUri, modified: e.multiDiffEditorModifiedUri }; })); return new ScmResolvedMultiDiffSource(resources, { scmResourceGroup: groupId, scmProvider: repository.provider.contextValue, }); } } class ScmResolvedMultiDiffSource implements IResolvedMultiDiffSource { get resources(): readonly MultiDiffEditorItem[] { return this._resources.get(); } public readonly onDidChange = Event.fromObservableLight(this._resources); constructor( private readonly _resources: IObservable<readonly MultiDiffEditorItem[]>, public readonly contextKeys: Record<string, ContextKeyValue> | undefined, ) { } } interface UriFields { repositoryUri: string; groupId: string; } function promiseFromEventState<T>(event: Event<any>, checkState: () => T | false): Promise<T> { const state = checkState(); if (state) { return Promise.resolve(state); } return new Promise<T>(resolve => { const listener = event(() => { const state = checkState(); if (state) { listener.dispose(); resolve(state); } }); }); } export class ScmMultiDiffSourceResolverContribution extends Disposable { static readonly ID = 'workbench.contrib.scmMultiDiffSourceResolver'; constructor( @IInstantiationService instantiationService: IInstantiationService, @IMultiDiffSourceResolverService multiDiffSourceResolverService: IMultiDiffSourceResolverService, ) { super(); this._register(multiDiffSourceResolverService.registerResolver(instantiationService.createInstance(ScmMultiDiffSourceResolver))); } } export class OpenScmGroupAction extends Action2 { constructor() { super({ id: 'multiDiffEditor.openScmDiff', title: localize2('viewChanges', 'View Changes'), icon: Codicon.diffMultiple, menu: { when: ContextKeyExpr.and( ContextKeyExpr.has('config.multiDiffEditor.experimental.enabled'), ContextKeyExpr.has('multiDiffEditorEnableViewChanges'), ), id: MenuId.SCMResourceGroupContext, group: 'inline', }, f1: false, }); } async run(accessor: ServicesAccessor, group: ISCMResourceGroup): Promise<void> { const editorService = accessor.get(IEditorService); if (!group.provider.rootUri) { return; } const multiDiffSource = ScmMultiDiffSourceResolver.getMultiDiffSourceUri(group.provider.rootUri.toString(), group.id); const label = localize('scmDiffLabel', '{0}: {1}', group.provider.label, group.label); await editorService.openEditor({ label, multiDiffSource }); } }
src/vs/workbench/contrib/multiDiffEditor/browser/scmMultiDiffSourceResolver.ts
1
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.2779681980609894, 0.029191097244620323, 0.00016284693265333772, 0.00021135366114322096, 0.08179750293493271 ]
{ "id": 0, "code_window": [ "import { IWorkbenchUIElementFactory } from 'vs/editor/browser/widget/multiDiffEditorWidget/workbenchUIElementFactory';\n", "import { Event } from 'vs/base/common/event';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IDiffEditor } from 'vs/editor/common/editorCommon';\n", "import { ICodeEditor } from 'vs/editor/browser/editorBrowser';\n", "\n", "export class MultiDiffEditorWidget extends Disposable {\n", "\tprivate readonly _dimension = observableValue<Dimension | undefined>(this, undefined);\n", "\tprivate readonly _viewModel = observableValue<MultiDiffEditorViewModel | undefined>(this, undefined);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditor/diffEditorWidget';\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "add", "edit_start_line_idx": 20 }
<svg width="14px" height="14px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <rect fill="#2d883e" 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"> A </text> </svg>
extensions/git/resources/icons/light/status-added.svg
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017347878019791096, 0.00017347878019791096, 0.00017347878019791096, 0.00017347878019791096, 0 ]
{ "id": 0, "code_window": [ "import { IWorkbenchUIElementFactory } from 'vs/editor/browser/widget/multiDiffEditorWidget/workbenchUIElementFactory';\n", "import { Event } from 'vs/base/common/event';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IDiffEditor } from 'vs/editor/common/editorCommon';\n", "import { ICodeEditor } from 'vs/editor/browser/editorBrowser';\n", "\n", "export class MultiDiffEditorWidget extends Disposable {\n", "\tprivate readonly _dimension = observableValue<Dimension | undefined>(this, undefined);\n", "\tprivate readonly _viewModel = observableValue<MultiDiffEditorViewModel | undefined>(this, undefined);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditor/diffEditorWidget';\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "add", "edit_start_line_idx": 20 }
FROM mcr.microsoft.com/devcontainers/typescript-node:18-bookworm ADD install-vscode.sh /root/ RUN /root/install-vscode.sh RUN git config --system codespaces-theme.hide-status 1 USER node RUN npm install -g node-gyp RUN YARN_CACHE="$(yarn cache dir)" && rm -rf "$YARN_CACHE" && ln -s /vscode-dev/yarn-cache "$YARN_CACHE" RUN echo 'export DISPLAY="${DISPLAY:-:1}"' | tee -a ~/.bashrc >> ~/.zshrc USER root CMD chown node:node /vscode-dev && sudo -u node mkdir -p /vscode-dev/yarn-cache && sleep inf
.devcontainer/Dockerfile
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017078187374863774, 0.00016794222756288946, 0.0001651025959290564, 0.00016794222756288946, 0.0000028396391371643404 ]
{ "id": 0, "code_window": [ "import { IWorkbenchUIElementFactory } from 'vs/editor/browser/widget/multiDiffEditorWidget/workbenchUIElementFactory';\n", "import { Event } from 'vs/base/common/event';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IDiffEditor } from 'vs/editor/common/editorCommon';\n", "import { ICodeEditor } from 'vs/editor/browser/editorBrowser';\n", "\n", "export class MultiDiffEditorWidget extends Disposable {\n", "\tprivate readonly _dimension = observableValue<Dimension | undefined>(this, undefined);\n", "\tprivate readonly _viewModel = observableValue<MultiDiffEditorViewModel | undefined>(this, undefined);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditor/diffEditorWidget';\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "add", "edit_start_line_idx": 20 }
test/** cgmanifest.json
extensions/yaml/.vscodeignore
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.000172613697941415, 0.000172613697941415, 0.000172613697941415, 0.000172613697941415, 0 ]
{ "id": 1, "code_window": [ "\n", "\tprivate readonly _activeControl = derived(this, (reader) => this._widgetImpl.read(reader).activeControl.read(reader));\n", "\n", "\tpublic getActiveControl(): any | undefined {\n", "\t\treturn this._activeControl.get();\n", "\t}\n", "\n", "\tpublic readonly onDidChangeActiveControl = Event.fromObservableLight(this._activeControl);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getActiveControl(): DiffEditorWidget | undefined {\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "replace", "edit_start_line_idx": 60 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension } from 'vs/base/browser/dom'; import { Disposable } from 'vs/base/common/lifecycle'; import { derived, derivedWithStore, observableValue, recomputeInitiallyAndOnChange } from 'vs/base/common/observable'; import { readHotReloadableExport } from 'vs/editor/browser/widget/diffEditor/utils'; import { IMultiDiffEditorModel } from 'vs/editor/browser/widget/multiDiffEditorWidget/model'; import { IMultiDiffEditorViewState, MultiDiffEditorWidgetImpl } from 'vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidgetImpl'; import { MultiDiffEditorViewModel } from './multiDiffEditorViewModel'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import './colors'; import { DiffEditorItemTemplate } from 'vs/editor/browser/widget/multiDiffEditorWidget/diffEditorItemTemplate'; import { IWorkbenchUIElementFactory } from 'vs/editor/browser/widget/multiDiffEditorWidget/workbenchUIElementFactory'; import { Event } from 'vs/base/common/event'; import { URI } from 'vs/base/common/uri'; import { IDiffEditor } from 'vs/editor/common/editorCommon'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; export class MultiDiffEditorWidget extends Disposable { private readonly _dimension = observableValue<Dimension | undefined>(this, undefined); private readonly _viewModel = observableValue<MultiDiffEditorViewModel | undefined>(this, undefined); private readonly _widgetImpl = derivedWithStore(this, (reader, store) => { readHotReloadableExport(DiffEditorItemTemplate, reader); return store.add(this._instantiationService.createInstance(( readHotReloadableExport(MultiDiffEditorWidgetImpl, reader)), this._element, this._dimension, this._viewModel, this._workbenchUIElementFactory, )); }); constructor( private readonly _element: HTMLElement, private readonly _workbenchUIElementFactory: IWorkbenchUIElementFactory, @IInstantiationService private readonly _instantiationService: IInstantiationService, ) { super(); this._register(recomputeInitiallyAndOnChange(this._widgetImpl)); } public createViewModel(model: IMultiDiffEditorModel): MultiDiffEditorViewModel { return new MultiDiffEditorViewModel(model, this._instantiationService); } public setViewModel(viewModel: MultiDiffEditorViewModel | undefined): void { this._viewModel.set(viewModel, undefined); } public layout(dimension: Dimension): void { this._dimension.set(dimension, undefined); } private readonly _activeControl = derived(this, (reader) => this._widgetImpl.read(reader).activeControl.read(reader)); public getActiveControl(): any | undefined { return this._activeControl.get(); } public readonly onDidChangeActiveControl = Event.fromObservableLight(this._activeControl); public getViewState(): IMultiDiffEditorViewState { return this._widgetImpl.get().getViewState(); } public setViewState(viewState: IMultiDiffEditorViewState): void { this._widgetImpl.get().setViewState(viewState); } public tryGetCodeEditor(resource: URI): { diffEditor: IDiffEditor; editor: ICodeEditor } | undefined { return this._widgetImpl.get().tryGetCodeEditor(resource); } }
src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts
1
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.9977890253067017, 0.2502000331878662, 0.0001617384550627321, 0.00036910356720909476, 0.43159374594688416 ]
{ "id": 1, "code_window": [ "\n", "\tprivate readonly _activeControl = derived(this, (reader) => this._widgetImpl.read(reader).activeControl.read(reader));\n", "\n", "\tpublic getActiveControl(): any | undefined {\n", "\t\treturn this._activeControl.get();\n", "\t}\n", "\n", "\tpublic readonly onDidChangeActiveControl = Event.fromObservableLight(this._activeControl);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getActiveControl(): DiffEditorWidget | undefined {\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "replace", "edit_start_line_idx": 60 }
{ "original": { "content": "[\n\t{\n\t\t\"identifier\": {\n\t\t\t\"id\": \"pflannery.vscode-versionlens\",\n\t\t\t\"uuid\": \"07fc4a0a-11fc-4121-ba9a-f0d534c729d8\"\n\t\t},\n\t\t\"preRelease\": false,\n\t\t\"version\": \"1.0.9\",\n\t\t\"installed\": true\n\t},\n\t{\n\t\t\"identifier\": {\n\t\t\t\"id\": \"sumneko.lua\",\n\t\t\t\"uuid\": \"3a15b5a7-be12-47e3-8445-88ee3eabc8b2\"\n\t\t},\n\t\t\"preRelease\": false,\n\t\t\"version\": \"3.5.6\",\n\t\t\"installed\": true\n\t},\n\t{\n\t\t\"identifier\": {\n\t\t\t\"id\": \"vscode.bat\",\n\t\t\t\"uuid\": \"5ef96c58-076f-4167-8e40-62c9deb00496\"\n\t\t},\n\t\t\"preRelease\": false,\n\t\t\"version\": \"1.0.0\"\n\t}\n]", "fileName": "./1.tst" }, "modified": { "content": "[\n\t{\n\t\t\"identifier\": {\n\t\t\t\"id\": \"pflannery.vscode-versionlens\",\n\t\t\t\"uuid\": \"07fc4a0a-11fc-4121-ba9a-f0d534c729d8\"\n\t\t},\n\t\t\"preRelease\": false,\n\t\t\"version\": \"1.0.9\",\n\t\t\"installed\": true\n\t},\n\t{\n\t\t\"identifier\": {\n\t\t\t\"id\": \"vscode.bat\",\n\t\t\t\"uuid\": \"5ef96c58-076f-4167-8e40-62c9deb00496\"\n\t\t},\n\t\t\"preRelease\": false,\n\t\t\"version\": \"1.0.0\"\n\t}\n]", "fileName": "./2.tst" }, "diffs": [ { "originalRange": "[11,20)", "modifiedRange": "[11,11)", "innerChanges": [ { "originalRange": "[11,1 -> 20,1]", "modifiedRange": "[11,1 -> 11,1]" } ] } ] }
src/vs/editor/test/node/diffing/fixtures/ts-shifting/advanced.expected.diff.json
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017898870282806456, 0.00017424618999939412, 0.00016856110596563667, 0.00017518879030831158, 0.000004308909410610795 ]
{ "id": 1, "code_window": [ "\n", "\tprivate readonly _activeControl = derived(this, (reader) => this._widgetImpl.read(reader).activeControl.read(reader));\n", "\n", "\tpublic getActiveControl(): any | undefined {\n", "\t\treturn this._activeControl.get();\n", "\t}\n", "\n", "\tpublic readonly onDidChangeActiveControl = Event.fromObservableLight(this._activeControl);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getActiveControl(): DiffEditorWidget | undefined {\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "replace", "edit_start_line_idx": 60 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/perl/yarn.lock
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017321945051662624, 0.00017321945051662624, 0.00017321945051662624, 0.00017321945051662624, 0 ]
{ "id": 1, "code_window": [ "\n", "\tprivate readonly _activeControl = derived(this, (reader) => this._widgetImpl.read(reader).activeControl.read(reader));\n", "\n", "\tpublic getActiveControl(): any | undefined {\n", "\t\treturn this._activeControl.get();\n", "\t}\n", "\n", "\tpublic readonly onDidChangeActiveControl = Event.fromObservableLight(this._activeControl);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getActiveControl(): DiffEditorWidget | undefined {\n" ], "file_path": "src/vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget.ts", "type": "replace", "edit_start_line_idx": 60 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as glob from 'vs/base/common/glob'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { posix } from 'vs/base/common/path'; import { basename } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { workbenchConfigurationNodeBase } from 'vs/workbench/common/configuration'; import { Extensions as ConfigurationExtensions, IConfigurationNode, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { IResourceEditorInput, ITextResourceEditorInput } from 'vs/platform/editor/common/editor'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { Registry } from 'vs/platform/registry/common/platform'; import { EditorInputWithOptions, EditorInputWithOptionsAndGroup, IResourceDiffEditorInput, IResourceMultiDiffEditorInput, IResourceMergeEditorInput, IUntitledTextResourceEditorInput, IUntypedEditorInput } from 'vs/workbench/common/editor'; import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService'; import { PreferredGroup } from 'vs/workbench/services/editor/common/editorService'; import { AtLeastOne } from 'vs/base/common/types'; export const IEditorResolverService = createDecorator<IEditorResolverService>('editorResolverService'); //#region Editor Associations // Static values for registered editors export type EditorAssociation = { readonly viewType: string; readonly filenamePattern?: string; }; export type EditorAssociations = readonly EditorAssociation[]; export const editorsAssociationsSettingId = 'workbench.editorAssociations'; const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); const editorAssociationsConfigurationNode: IConfigurationNode = { ...workbenchConfigurationNodeBase, properties: { 'workbench.editorAssociations': { type: 'object', markdownDescription: localize('editor.editorAssociations', "Configure [glob patterns](https://aka.ms/vscode-glob-patterns) to editors (for example `\"*.hex\": \"hexEditor.hexedit\"`). These have precedence over the default behavior."), additionalProperties: { type: 'string' } } } }; export interface IEditorType { readonly id: string; readonly displayName: string; readonly providerDisplayName: string; } configurationRegistry.registerConfiguration(editorAssociationsConfigurationNode); //#endregion //#region EditorResolverService types export enum RegisteredEditorPriority { builtin = 'builtin', option = 'option', exclusive = 'exclusive', default = 'default' } /** * If we didn't resolve an editor dictates what to do with the opening state * ABORT = Do not continue with opening the editor * NONE = Continue as if the resolution has been disabled as the service could not resolve one */ export const enum ResolvedStatus { ABORT = 1, NONE = 2, } export type ResolvedEditor = EditorInputWithOptionsAndGroup | ResolvedStatus; export type RegisteredEditorOptions = { /** * If your editor cannot be opened in multiple groups for the same resource */ singlePerResource?: boolean | (() => boolean); /** * Whether or not you can support opening the given resource. * If omitted we assume you can open everything */ canSupportResource?: (resource: URI) => boolean; }; export type RegisteredEditorInfo = { id: string; label: string; detail?: string; priority: RegisteredEditorPriority; }; type EditorInputFactoryResult = EditorInputWithOptions | Promise<EditorInputWithOptions>; export type EditorInputFactoryFunction = (editorInput: IResourceEditorInput | ITextResourceEditorInput, group: IEditorGroup) => EditorInputFactoryResult; export type UntitledEditorInputFactoryFunction = (untitledEditorInput: IUntitledTextResourceEditorInput, group: IEditorGroup) => EditorInputFactoryResult; export type DiffEditorInputFactoryFunction = (diffEditorInput: IResourceDiffEditorInput, group: IEditorGroup) => EditorInputFactoryResult; export type DiffListEditorInputFactoryFunction = (diffEditorInput: IResourceMultiDiffEditorInput, group: IEditorGroup) => EditorInputFactoryResult; export type MergeEditorInputFactoryFunction = (mergeEditorInput: IResourceMergeEditorInput, group: IEditorGroup) => EditorInputFactoryResult; type EditorInputFactories = { createEditorInput?: EditorInputFactoryFunction; createUntitledEditorInput?: UntitledEditorInputFactoryFunction; createDiffEditorInput?: DiffEditorInputFactoryFunction; createMultiDiffEditorInput?: DiffListEditorInputFactoryFunction; createMergeEditorInput?: MergeEditorInputFactoryFunction; }; export type EditorInputFactoryObject = AtLeastOne<EditorInputFactories>; export interface IEditorResolverService { readonly _serviceBrand: undefined; /** * Given a resource finds the editor associations that match it from the user's settings * @param resource The resource to match * @return The matching associations */ getAssociationsForResource(resource: URI): EditorAssociations; /** * Updates the user's association to include a specific editor ID as a default for the given glob pattern * @param globPattern The glob pattern (must be a string as settings don't support relative glob) * @param editorID The ID of the editor to make a user default */ updateUserAssociations(globPattern: string, editorID: string): void; /** * Emitted when an editor is registered or unregistered. */ readonly onDidChangeEditorRegistrations: Event<void>; /** * Given a callback, run the callback pausing the registration emitter */ bufferChangeEvents(callback: Function): void; /** * Registers a specific editor. Editors with the same glob pattern and ID will be grouped together by the resolver. * This allows for registration of the factories in different locations * @param globPattern The glob pattern for this registration * @param editorInfo Information about the registration * @param options Specific options which apply to this registration * @param editorFactoryObject The editor input factory functions */ registerEditor( globPattern: string | glob.IRelativePattern, editorInfo: RegisteredEditorInfo, options: RegisteredEditorOptions, editorFactoryObject: EditorInputFactoryObject ): IDisposable; /** * Given an editor resolves it to the suitable ResolvedEitor based on user extensions, settings, and built-in editors * @param editor The editor to resolve * @param preferredGroup The group you want to open the editor in * @returns An EditorInputWithOptionsAndGroup if there is an available editor or a status of how to proceed */ resolveEditor(editor: IUntypedEditorInput, preferredGroup: PreferredGroup | undefined): Promise<ResolvedEditor>; /** * Given a resource returns all the editor ids that match that resource. If there is exclusive editor we return an empty array * @param resource The resource * @returns A list of editor ids */ getEditors(resource: URI): RegisteredEditorInfo[]; /** * A set of all the editors that are registered to the editor resolver. */ getEditors(): RegisteredEditorInfo[]; /** * Get a complete list of editor associations. */ getAllUserAssociations(): EditorAssociations; } //#endregion //#region Util functions export function priorityToRank(priority: RegisteredEditorPriority): number { switch (priority) { case RegisteredEditorPriority.exclusive: return 5; case RegisteredEditorPriority.default: return 4; case RegisteredEditorPriority.builtin: return 3; // Text editor is priority 2 case RegisteredEditorPriority.option: default: return 1; } } export function globMatchesResource(globPattern: string | glob.IRelativePattern, resource: URI): boolean { const excludedSchemes = new Set([ Schemas.extension, Schemas.webviewPanel, Schemas.vscodeWorkspaceTrust, Schemas.vscodeSettings ]); // We want to say that the above schemes match no glob patterns if (excludedSchemes.has(resource.scheme)) { return false; } const matchOnPath = typeof globPattern === 'string' && globPattern.indexOf(posix.sep) >= 0; const target = matchOnPath ? `${resource.scheme}:${resource.path}` : basename(resource); return glob.match(typeof globPattern === 'string' ? globPattern.toLowerCase() : globPattern, target.toLowerCase()); } //#endregion
src/vs/workbench/services/editor/common/editorResolverService.ts
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.005270060617476702, 0.0003950619720853865, 0.00016622284601908177, 0.00017332419520244002, 0.001039358670823276 ]
{ "id": 2, "code_window": [ "\n", "\toverride getControl(): ICompositeControl | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getActiveControl();\n", "\t}\n", "\n", "\tprotected override computeEditorViewState(resource: URI): IMultiDiffEditorViewState | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getViewState();\n", "\t}\n", "\n", "\tprotected override tracksEditorViewState(input: EditorInput): boolean {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toverride focus(): void {\n", "\t\tsuper.focus();\n", "\n", "\t\tthis._multiDiffEditorWidget?.getActiveControl()?.focus();\n", "\t}\n", "\n", "\toverride hasFocus(): boolean {\n", "\t\treturn this._multiDiffEditorWidget?.getActiveControl()?.hasTextFocus() || super.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditor.ts", "type": "add", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Codicon } from 'vs/base/common/codicons'; import { Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { IObservable, observableFromEvent } from 'vs/base/common/observable'; import { URI } from 'vs/base/common/uri'; import { localize, localize2 } from 'vs/nls'; import { Action2, MenuId } from 'vs/platform/actions/common/actions'; import { ContextKeyExpr, ContextKeyValue } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IMultiDiffSourceResolver, IMultiDiffSourceResolverService, IResolvedMultiDiffSource, MultiDiffEditorItem } from 'vs/workbench/contrib/multiDiffEditor/browser/multiDiffSourceResolverService'; import { ISCMResourceGroup, ISCMService } from 'vs/workbench/contrib/scm/common/scm'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; export class ScmMultiDiffSourceResolver implements IMultiDiffSourceResolver { private static readonly _scheme = 'scm-multi-diff-source'; public static getMultiDiffSourceUri(repositoryUri: string, groupId: string): URI { return URI.from({ scheme: ScmMultiDiffSourceResolver._scheme, query: JSON.stringify({ repositoryUri, groupId } satisfies UriFields), }); } private static parseUri(uri: URI): { repositoryUri: URI; groupId: string } | undefined { if (uri.scheme !== ScmMultiDiffSourceResolver._scheme) { return undefined; } let query: any; try { query = JSON.parse(uri.query) as UriFields; } catch (e) { return undefined; } if (typeof query !== 'object' || query === null) { return undefined; } const { repositoryUri, groupId } = query; if (typeof repositoryUri !== 'string' || typeof groupId !== 'string') { return undefined; } return { repositoryUri: URI.parse(repositoryUri), groupId }; } constructor( @ISCMService private readonly _scmService: ISCMService, ) { } canHandleUri(uri: URI): boolean { return ScmMultiDiffSourceResolver.parseUri(uri) !== undefined; } async resolveDiffSource(uri: URI): Promise<IResolvedMultiDiffSource> { const { repositoryUri, groupId } = ScmMultiDiffSourceResolver.parseUri(uri)!; const repository = await promiseFromEventState( this._scmService.onDidAddRepository, () => { const repository = [...this._scmService.repositories].find(r => r.provider.rootUri?.toString() === repositoryUri.toString()); return repository ?? false; } ); const group = await promiseFromEventState( repository.provider.onDidChangeResourceGroups, () => { const group = repository.provider.groups.find(g => g.id === groupId); return group ?? false; } ); const resources = observableFromEvent<MultiDiffEditorItem[]>(group.onDidChangeResources, () => group.resources.map(e => { return { original: e.multiDiffEditorOriginalUri, modified: e.multiDiffEditorModifiedUri }; })); return new ScmResolvedMultiDiffSource(resources, { scmResourceGroup: groupId, scmProvider: repository.provider.contextValue, }); } } class ScmResolvedMultiDiffSource implements IResolvedMultiDiffSource { get resources(): readonly MultiDiffEditorItem[] { return this._resources.get(); } public readonly onDidChange = Event.fromObservableLight(this._resources); constructor( private readonly _resources: IObservable<readonly MultiDiffEditorItem[]>, public readonly contextKeys: Record<string, ContextKeyValue> | undefined, ) { } } interface UriFields { repositoryUri: string; groupId: string; } function promiseFromEventState<T>(event: Event<any>, checkState: () => T | false): Promise<T> { const state = checkState(); if (state) { return Promise.resolve(state); } return new Promise<T>(resolve => { const listener = event(() => { const state = checkState(); if (state) { listener.dispose(); resolve(state); } }); }); } export class ScmMultiDiffSourceResolverContribution extends Disposable { static readonly ID = 'workbench.contrib.scmMultiDiffSourceResolver'; constructor( @IInstantiationService instantiationService: IInstantiationService, @IMultiDiffSourceResolverService multiDiffSourceResolverService: IMultiDiffSourceResolverService, ) { super(); this._register(multiDiffSourceResolverService.registerResolver(instantiationService.createInstance(ScmMultiDiffSourceResolver))); } } export class OpenScmGroupAction extends Action2 { constructor() { super({ id: 'multiDiffEditor.openScmDiff', title: localize2('viewChanges', 'View Changes'), icon: Codicon.diffMultiple, menu: { when: ContextKeyExpr.and( ContextKeyExpr.has('config.multiDiffEditor.experimental.enabled'), ContextKeyExpr.has('multiDiffEditorEnableViewChanges'), ), id: MenuId.SCMResourceGroupContext, group: 'inline', }, f1: false, }); } async run(accessor: ServicesAccessor, group: ISCMResourceGroup): Promise<void> { const editorService = accessor.get(IEditorService); if (!group.provider.rootUri) { return; } const multiDiffSource = ScmMultiDiffSourceResolver.getMultiDiffSourceUri(group.provider.rootUri.toString(), group.id); const label = localize('scmDiffLabel', '{0}: {1}', group.provider.label, group.label); await editorService.openEditor({ label, multiDiffSource }); } }
src/vs/workbench/contrib/multiDiffEditor/browser/scmMultiDiffSourceResolver.ts
1
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.004553253762423992, 0.0004901383654214442, 0.00016529350250493735, 0.00017673795809969306, 0.0009977812878787518 ]
{ "id": 2, "code_window": [ "\n", "\toverride getControl(): ICompositeControl | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getActiveControl();\n", "\t}\n", "\n", "\tprotected override computeEditorViewState(resource: URI): IMultiDiffEditorViewState | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getViewState();\n", "\t}\n", "\n", "\tprotected override tracksEditorViewState(input: EditorInput): boolean {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toverride focus(): void {\n", "\t\tsuper.focus();\n", "\n", "\t\tthis._multiDiffEditorWidget?.getActiveControl()?.focus();\n", "\t}\n", "\n", "\toverride hasFocus(): boolean {\n", "\t\treturn this._multiDiffEditorWidget?.getActiveControl()?.hasTextFocus() || super.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditor.ts", "type": "add", "edit_start_line_idx": 98 }
private doAddView(view: IView<TLayoutContext>, size: number | Sizing, index = this.viewItems.length, skipLayout?: boolean): void { if (this.state !== State.Idle) { throw new Error('Cant modify splitview'); } this.state = State.Busy; // Add view const container = $('.split-view-view'); if (index === this.viewItems.length) { this.viewContainer.appendChild(container); } else { this.viewContainer.insertBefore(container, this.viewContainer.children.item(index)); } const onChangeDisposable = view.onDidChange(size => this.onViewChange(item, size)); const containerDisposable = toDisposable(() => this.viewContainer.removeChild(container)); const disposable = combinedDisposable(onChangeDisposable, containerDisposable); let viewSize: ViewItemSize; if (typeof size === 'number') { viewSize = size; } else { if (size.type === 'auto') { if (this.areViewsDistributed()) { size = { type: 'distribute' }; } else { size = { type: 'split', index: size.index }; } } if (size.type === 'split') { viewSize = this.getViewSize(size.index) / 2; } else if (size.type === 'invisible') { viewSize = { cachedVisibleSize: size.cachedVisibleSize }; } else { viewSize = view.minimumSize; } } const item = this.orientation === Orientation.VERTICAL ? new VerticalViewItem(container, view, viewSize, disposable) : new HorizontalViewItem(container, view, viewSize, disposable); this.viewItems.splice(index, 0, item);
src/vs/editor/test/node/diffing/fixtures/issue-185779/2.txt
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017501362890470773, 0.0001722597808111459, 0.00016979417705442756, 0.0001715823309496045, 0.000002117594021910918 ]
{ "id": 2, "code_window": [ "\n", "\toverride getControl(): ICompositeControl | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getActiveControl();\n", "\t}\n", "\n", "\tprotected override computeEditorViewState(resource: URI): IMultiDiffEditorViewState | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getViewState();\n", "\t}\n", "\n", "\tprotected override tracksEditorViewState(input: EditorInput): boolean {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toverride focus(): void {\n", "\t\tsuper.focus();\n", "\n", "\t\tthis._multiDiffEditorWidget?.getActiveControl()?.focus();\n", "\t}\n", "\n", "\toverride hasFocus(): boolean {\n", "\t\treturn this._multiDiffEditorWidget?.getActiveControl()?.hasTextFocus() || super.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditor.ts", "type": "add", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * 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 { timeout } from 'vs/base/common/async'; import { bufferedStreamToBuffer, bufferToReadable, bufferToStream, decodeBase64, encodeBase64, newWriteableBufferStream, readableToBuffer, streamToBuffer, VSBuffer } from 'vs/base/common/buffer'; import { peekStream } from 'vs/base/common/stream'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; suite('Buffer', () => { ensureNoDisposablesAreLeakedInTestSuite(); test('issue #71993 - VSBuffer#toString returns numbers', () => { const data = new Uint8Array([1, 2, 3, 'h'.charCodeAt(0), 'i'.charCodeAt(0), 4, 5]).buffer; const buffer = VSBuffer.wrap(new Uint8Array(data, 3, 2)); assert.deepStrictEqual(buffer.toString(), 'hi'); }); test('bufferToReadable / readableToBuffer', () => { const content = 'Hello World'; const readable = bufferToReadable(VSBuffer.fromString(content)); assert.strictEqual(readableToBuffer(readable).toString(), content); }); test('bufferToStream / streamToBuffer', async () => { const content = 'Hello World'; const stream = bufferToStream(VSBuffer.fromString(content)); assert.strictEqual((await streamToBuffer(stream)).toString(), content); }); test('bufferedStreamToBuffer', async () => { const content = 'Hello World'; const stream = await peekStream(bufferToStream(VSBuffer.fromString(content)), 1); assert.strictEqual((await bufferedStreamToBuffer(stream)).toString(), content); }); test('bufferWriteableStream - basics (no error)', async () => { const stream = newWriteableBufferStream(); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 2); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(chunks[1].toString(), 'World'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - basics (error)', async () => { const stream = newWriteableBufferStream(); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); stream.end(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 1); }); test('bufferWriteableStream - buffers data when no listener', async () => { const stream = newWriteableBufferStream(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'HelloWorld'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - buffers errors when no listener', async () => { const stream = newWriteableBufferStream(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); let ended = false; stream.on('end', () => { ended = true; }); stream.end(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 1); }); test('bufferWriteableStream - buffers end when no listener', async () => { const stream = newWriteableBufferStream(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); let ended = false; stream.on('end', () => { ended = true; }); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'HelloWorld'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - nothing happens after end()', async () => { const stream = newWriteableBufferStream(); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); let dataCalledAfterEnd = false; stream.on('data', data => { dataCalledAfterEnd = true; }); let errorCalledAfterEnd = false; stream.on('error', error => { errorCalledAfterEnd = true; }); let endCalledAfterEnd = false; stream.on('end', () => { endCalledAfterEnd = true; }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(dataCalledAfterEnd, false); assert.strictEqual(errorCalledAfterEnd, false); assert.strictEqual(endCalledAfterEnd, false); assert.strictEqual(chunks.length, 2); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(chunks[1].toString(), 'World'); }); test('bufferWriteableStream - pause/resume (simple)', async () => { const stream = newWriteableBufferStream(); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); stream.pause(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 0); assert.strictEqual(errors.length, 0); assert.strictEqual(ended, false); stream.resume(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'HelloWorld'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - pause/resume (pause after first write)', async () => { const stream = newWriteableBufferStream(); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); await timeout(0); stream.write(VSBuffer.fromString('Hello')); stream.pause(); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(errors.length, 0); assert.strictEqual(ended, false); stream.resume(); assert.strictEqual(chunks.length, 2); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(chunks[1].toString(), 'World'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 0); }); test('bufferWriteableStream - pause/resume (error)', async () => { const stream = newWriteableBufferStream(); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); stream.pause(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.error(new Error()); stream.end(); assert.strictEqual(chunks.length, 0); assert.strictEqual(ended, false); assert.strictEqual(errors.length, 0); stream.resume(); assert.strictEqual(chunks.length, 1); assert.strictEqual(chunks[0].toString(), 'Hello'); assert.strictEqual(ended, true); assert.strictEqual(errors.length, 1); }); test('bufferWriteableStream - destroy', async () => { const stream = newWriteableBufferStream(); const chunks: VSBuffer[] = []; stream.on('data', data => { chunks.push(data); }); let ended = false; stream.on('end', () => { ended = true; }); const errors: Error[] = []; stream.on('error', error => { errors.push(error); }); stream.destroy(); await timeout(0); stream.write(VSBuffer.fromString('Hello')); await timeout(0); stream.end(VSBuffer.fromString('World')); assert.strictEqual(chunks.length, 0); assert.strictEqual(ended, false); assert.strictEqual(errors.length, 0); }); test('Performance issue with VSBuffer#slice #76076', function () { // TODO@alexdima this test seems to fail in web (https://github.com/microsoft/vscode/issues/114042) // Buffer#slice creates a view if (typeof Buffer !== 'undefined') { const buff = Buffer.from([10, 20, 30, 40]); const b2 = buff.slice(1, 3); assert.strictEqual(buff[1], 20); assert.strictEqual(b2[0], 20); buff[1] = 17; // modify buff AND b2 assert.strictEqual(buff[1], 17); assert.strictEqual(b2[0], 17); } // TypedArray#slice creates a copy { const unit = new Uint8Array([10, 20, 30, 40]); const u2 = unit.slice(1, 3); assert.strictEqual(unit[1], 20); assert.strictEqual(u2[0], 20); unit[1] = 17; // modify unit, NOT b2 assert.strictEqual(unit[1], 17); assert.strictEqual(u2[0], 20); } // TypedArray#subarray creates a view { const unit = new Uint8Array([10, 20, 30, 40]); const u2 = unit.subarray(1, 3); assert.strictEqual(unit[1], 20); assert.strictEqual(u2[0], 20); unit[1] = 17; // modify unit AND b2 assert.strictEqual(unit[1], 17); assert.strictEqual(u2[0], 17); } }); test('indexOf', () => { const haystack = VSBuffer.fromString('abcaabbccaaabbbccc'); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('')), 0); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('a'.repeat(100))), -1); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('a')), 0); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('c')), 2); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('abcaa')), 0); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('caaab')), 8); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('ccc')), 15); assert.strictEqual(haystack.indexOf(VSBuffer.fromString('cccb')), -1); }); suite('base64', () => { /* Generated with: const crypto = require('crypto'); for (let i = 0; i < 16; i++) { const buf = crypto.randomBytes(i); console.log(`[new Uint8Array([${Array.from(buf).join(', ')}]), '${buf.toString('base64')}'],`) } */ const testCases: [Uint8Array, string][] = [ [new Uint8Array([]), ''], [new Uint8Array([56]), 'OA=='], [new Uint8Array([209, 4]), '0QQ='], [new Uint8Array([19, 57, 119]), 'Ezl3'], [new Uint8Array([199, 237, 207, 112]), 'x+3PcA=='], [new Uint8Array([59, 193, 173, 26, 242]), 'O8GtGvI='], [new Uint8Array([81, 226, 95, 231, 116, 126]), 'UeJf53R+'], [new Uint8Array([11, 164, 253, 85, 8, 6, 56]), 'C6T9VQgGOA=='], [new Uint8Array([164, 16, 88, 88, 224, 173, 144, 114]), 'pBBYWOCtkHI='], [new Uint8Array([0, 196, 99, 12, 21, 229, 78, 101, 13]), 'AMRjDBXlTmUN'], [new Uint8Array([167, 114, 225, 116, 226, 83, 51, 48, 88, 114]), 'p3LhdOJTMzBYcg=='], [new Uint8Array([75, 33, 118, 10, 77, 5, 168, 194, 59, 47, 59]), 'SyF2Ck0FqMI7Lzs='], [new Uint8Array([203, 182, 165, 51, 208, 27, 123, 223, 112, 198, 127, 147]), 'y7alM9Abe99wxn+T'], [new Uint8Array([154, 93, 222, 41, 117, 234, 250, 85, 95, 144, 16, 94, 18]), 'ml3eKXXq+lVfkBBeEg=='], [new Uint8Array([246, 186, 88, 105, 192, 57, 25, 168, 183, 164, 103, 162, 243, 56]), '9rpYacA5Gai3pGei8zg='], [new Uint8Array([149, 240, 155, 96, 30, 55, 162, 172, 191, 187, 33, 124, 169, 183, 254]), 'lfCbYB43oqy/uyF8qbf+'], ]; test('encodes', () => { for (const [bytes, expected] of testCases) { assert.strictEqual(encodeBase64(VSBuffer.wrap(bytes)), expected); } }); test('decodes', () => { for (const [expected, encoded] of testCases) { assert.deepStrictEqual(new Uint8Array(decodeBase64(encoded).buffer), expected); } }); test('throws error on invalid encoding', () => { assert.throws(() => decodeBase64('invalid!')); }); }); });
src/vs/base/test/common/buffer.test.ts
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00018013118824455887, 0.00017667346401140094, 0.0001705642935121432, 0.0001767299690982327, 0.000001843898417064338 ]
{ "id": 2, "code_window": [ "\n", "\toverride getControl(): ICompositeControl | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getActiveControl();\n", "\t}\n", "\n", "\tprotected override computeEditorViewState(resource: URI): IMultiDiffEditorViewState | undefined {\n", "\t\treturn this._multiDiffEditorWidget!.getViewState();\n", "\t}\n", "\n", "\tprotected override tracksEditorViewState(input: EditorInput): boolean {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toverride focus(): void {\n", "\t\tsuper.focus();\n", "\n", "\t\tthis._multiDiffEditorWidget?.getActiveControl()?.focus();\n", "\t}\n", "\n", "\toverride hasFocus(): boolean {\n", "\t\treturn this._multiDiffEditorWidget?.getActiveControl()?.hasTextFocus() || super.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditor.ts", "type": "add", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { Schemas, matchesSomeScheme } from 'vs/base/common/network'; import { dirname, isEqual } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { FileKind } from 'vs/platform/files/common/files'; import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { BreadcrumbsConfig } from 'vs/workbench/browser/parts/editor/breadcrumbs'; import { IEditorPane } from 'vs/workbench/common/editor'; import { IOutline, IOutlineService, OutlineTarget } from 'vs/workbench/services/outline/browser/outline'; export class FileElement { constructor( readonly uri: URI, readonly kind: FileKind ) { } } type FileInfo = { path: FileElement[]; folder?: IWorkspaceFolder }; export class OutlineElement2 { constructor( readonly element: IOutline<any> | any, readonly outline: IOutline<any> ) { } } export class BreadcrumbsModel { private readonly _disposables = new DisposableStore(); private _fileInfo: FileInfo; private readonly _cfgFilePath: BreadcrumbsConfig<'on' | 'off' | 'last'>; private readonly _cfgSymbolPath: BreadcrumbsConfig<'on' | 'off' | 'last'>; private readonly _currentOutline = new MutableDisposable<IOutline<any>>(); private readonly _outlineDisposables = new DisposableStore(); private readonly _onDidUpdate = new Emitter<this>(); readonly onDidUpdate: Event<this> = this._onDidUpdate.event; constructor( readonly resource: URI, editor: IEditorPane | undefined, @IConfigurationService configurationService: IConfigurationService, @IWorkspaceContextService private readonly _workspaceService: IWorkspaceContextService, @IOutlineService private readonly _outlineService: IOutlineService, ) { this._cfgFilePath = BreadcrumbsConfig.FilePath.bindTo(configurationService); this._cfgSymbolPath = BreadcrumbsConfig.SymbolPath.bindTo(configurationService); this._disposables.add(this._cfgFilePath.onDidChange(_ => this._onDidUpdate.fire(this))); this._disposables.add(this._cfgSymbolPath.onDidChange(_ => this._onDidUpdate.fire(this))); this._workspaceService.onDidChangeWorkspaceFolders(this._onDidChangeWorkspaceFolders, this, this._disposables); this._fileInfo = this._initFilePathInfo(resource); if (editor) { this._bindToEditor(editor); this._disposables.add(_outlineService.onDidChange(() => this._bindToEditor(editor))); this._disposables.add(editor.onDidChangeControl(() => this._bindToEditor(editor))); } this._onDidUpdate.fire(this); } dispose(): void { this._disposables.dispose(); this._cfgFilePath.dispose(); this._cfgSymbolPath.dispose(); this._currentOutline.dispose(); this._outlineDisposables.dispose(); this._onDidUpdate.dispose(); } isRelative(): boolean { return Boolean(this._fileInfo.folder); } getElements(): ReadonlyArray<FileElement | OutlineElement2> { let result: (FileElement | OutlineElement2)[] = []; // file path elements if (this._cfgFilePath.getValue() === 'on') { result = result.concat(this._fileInfo.path); } else if (this._cfgFilePath.getValue() === 'last' && this._fileInfo.path.length > 0) { result = result.concat(this._fileInfo.path.slice(-1)); } if (this._cfgSymbolPath.getValue() === 'off') { return result; } if (!this._currentOutline.value) { return result; } const breadcrumbsElements = this._currentOutline.value.config.breadcrumbsDataSource.getBreadcrumbElements(); for (let i = this._cfgSymbolPath.getValue() === 'last' && breadcrumbsElements.length > 0 ? breadcrumbsElements.length - 1 : 0; i < breadcrumbsElements.length; i++) { result.push(new OutlineElement2(breadcrumbsElements[i], this._currentOutline.value)); } if (breadcrumbsElements.length === 0 && !this._currentOutline.value.isEmpty) { result.push(new OutlineElement2(this._currentOutline.value, this._currentOutline.value)); } return result; } private _initFilePathInfo(uri: URI): FileInfo { if (matchesSomeScheme(uri, Schemas.untitled, Schemas.data)) { return { folder: undefined, path: [] }; } const info: FileInfo = { folder: this._workspaceService.getWorkspaceFolder(uri) ?? undefined, path: [] }; let uriPrefix: URI | null = uri; while (uriPrefix && uriPrefix.path !== '/') { if (info.folder && isEqual(info.folder.uri, uriPrefix)) { break; } info.path.unshift(new FileElement(uriPrefix, info.path.length === 0 ? FileKind.FILE : FileKind.FOLDER)); const prevPathLength = uriPrefix.path.length; uriPrefix = dirname(uriPrefix); if (uriPrefix.path.length === prevPathLength) { break; } } if (info.folder && this._workspaceService.getWorkbenchState() === WorkbenchState.WORKSPACE) { info.path.unshift(new FileElement(info.folder.uri, FileKind.ROOT_FOLDER)); } return info; } private _onDidChangeWorkspaceFolders() { this._fileInfo = this._initFilePathInfo(this.resource); this._onDidUpdate.fire(this); } private _bindToEditor(editor: IEditorPane): void { const newCts = new CancellationTokenSource(); this._currentOutline.clear(); this._outlineDisposables.clear(); this._outlineDisposables.add(toDisposable(() => newCts.dispose(true))); this._outlineService.createOutline(editor, OutlineTarget.Breadcrumbs, newCts.token).then(outline => { if (newCts.token.isCancellationRequested) { // cancelled: dispose new outline and reset outline?.dispose(); outline = undefined; } this._currentOutline.value = outline; this._onDidUpdate.fire(this); if (outline) { this._outlineDisposables.add(outline.onDidChange(() => this._onDidUpdate.fire(this))); } }).catch(err => { this._onDidUpdate.fire(this); onUnexpectedError(err); }); } }
src/vs/workbench/browser/parts/editor/breadcrumbsModel.ts
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.0001781015598680824, 0.00017301359912380576, 0.00016608534497208893, 0.00017278821906074882, 0.0000033693727345962543 ]
{ "id": 3, "code_window": [ "\t\t\treturn undefined;\n", "\t\t}\n", "\n", "\t\tlet query: any;\n", "\t\ttry {\n", "\t\t\tquery = JSON.parse(uri.query) as UriFields;\n", "\t\t} catch (e) {\n", "\t\t\treturn undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet query: UriFields;\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/scmMultiDiffSourceResolver.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as DOM from 'vs/base/browser/dom'; import { CancellationToken } from 'vs/base/common/cancellation'; import { MultiDiffEditorWidget } from 'vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidget'; import { IResourceLabel, IWorkbenchUIElementFactory } from 'vs/editor/browser/widget/multiDiffEditorWidget/workbenchUIElementFactory'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration'; import { IEditorOptions } from 'vs/platform/editor/common/editor'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ResourceLabel } from 'vs/workbench/browser/labels'; import { AbstractEditorWithViewState } from 'vs/workbench/browser/parts/editor/editorWithViewState'; import { ICompositeControl } from 'vs/workbench/common/composite'; import { IEditorOpenContext } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { MultiDiffEditorInput } from 'vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditorInput'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { URI } from 'vs/base/common/uri'; import { MultiDiffEditorViewModel } from 'vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorViewModel'; import { IMultiDiffEditorViewState } from 'vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorWidgetImpl'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IDiffEditor } from 'vs/editor/common/editorCommon'; export class MultiDiffEditor extends AbstractEditorWithViewState<IMultiDiffEditorViewState> { static readonly ID = 'multiDiffEditor'; private _multiDiffEditorWidget: MultiDiffEditorWidget | undefined = undefined; private _viewModel: MultiDiffEditorViewModel | undefined; public get viewModel(): MultiDiffEditorViewModel | undefined { return this._viewModel; } constructor( @IInstantiationService instantiationService: InstantiationService, @ITelemetryService telemetryService: ITelemetryService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IEditorService editorService: IEditorService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService, ) { super( MultiDiffEditor.ID, 'multiDiffEditor', telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService ); } protected createEditor(parent: HTMLElement): void { this._multiDiffEditorWidget = this._register(this.instantiationService.createInstance( MultiDiffEditorWidget, parent, this.instantiationService.createInstance(WorkbenchUIElementFactory), )); this._register(this._multiDiffEditorWidget.onDidChangeActiveControl(() => { this._onDidChangeControl.fire(); })); } override async setInput(input: MultiDiffEditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { await super.setInput(input, options, context, token); this._viewModel = await input.getViewModel(); this._multiDiffEditorWidget!.setViewModel(this._viewModel); const viewState = this.loadEditorViewState(input, context); if (viewState) { this._multiDiffEditorWidget!.setViewState(viewState); } } override async clearInput(): Promise<void> { await super.clearInput(); this._multiDiffEditorWidget!.setViewModel(undefined); } layout(dimension: DOM.Dimension): void { this._multiDiffEditorWidget!.layout(dimension); } override getControl(): ICompositeControl | undefined { return this._multiDiffEditorWidget!.getActiveControl(); } protected override computeEditorViewState(resource: URI): IMultiDiffEditorViewState | undefined { return this._multiDiffEditorWidget!.getViewState(); } protected override tracksEditorViewState(input: EditorInput): boolean { return input instanceof MultiDiffEditorInput; } protected override toEditorViewStateResource(input: EditorInput): URI | undefined { return (input as MultiDiffEditorInput).resource; } public tryGetCodeEditor(resource: URI): { diffEditor: IDiffEditor; editor: ICodeEditor } | undefined { return this._multiDiffEditorWidget!.tryGetCodeEditor(resource); } } class WorkbenchUIElementFactory implements IWorkbenchUIElementFactory { constructor( @IInstantiationService private readonly _instantiationService: IInstantiationService, ) { } createResourceLabel(element: HTMLElement): IResourceLabel { const label = this._instantiationService.createInstance(ResourceLabel, element, {}); return { setUri(uri, options = {}) { if (!uri) { label.element.clear(); } else { label.element.setFile(uri, { strikethrough: options.strikethrough }); } }, dispose() { label.dispose(); } }; } }
src/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditor.ts
1
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.0009407229954376817, 0.0002433324552839622, 0.0001663435105001554, 0.00017331921844743192, 0.00019592182070482522 ]
{ "id": 3, "code_window": [ "\t\t\treturn undefined;\n", "\t\t}\n", "\n", "\t\tlet query: any;\n", "\t\ttry {\n", "\t\t\tquery = JSON.parse(uri.query) as UriFields;\n", "\t\t} catch (e) {\n", "\t\t\treturn undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet query: UriFields;\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/scmMultiDiffSourceResolver.ts", "type": "replace", "edit_start_line_idx": 33 }
{ "extends": "../tsconfig.base.json", "compilerOptions": { "outDir": "./out", "typeRoots": [ "node_modules/@types" ] }, "include": [ "src/**/*", "../../src/vscode-dts/vscode.d.ts" ] }
extensions/extension-editing/tsconfig.json
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017454200133215636, 0.00017230970843229443, 0.0001700774155324325, 0.00017230970843229443, 0.000002232292899861932 ]
{ "id": 3, "code_window": [ "\t\t\treturn undefined;\n", "\t\t}\n", "\n", "\t\tlet query: any;\n", "\t\ttry {\n", "\t\t\tquery = JSON.parse(uri.query) as UriFields;\n", "\t\t} catch (e) {\n", "\t\t\treturn undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet query: UriFields;\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/scmMultiDiffSourceResolver.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; const withDefaults = require('../shared.webpack.config'); module.exports = withDefaults({ context: __dirname, resolve: { mainFields: ['module', 'main'] }, entry: { extension: './src/extension.ts', } });
extensions/search-result/extension.webpack.config.js
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017500779358670115, 0.00017222209135070443, 0.00016722979489713907, 0.0001744287001201883, 0.0000035379978271521395 ]
{ "id": 3, "code_window": [ "\t\t\treturn undefined;\n", "\t\t}\n", "\n", "\t\tlet query: any;\n", "\t\ttry {\n", "\t\t\tquery = JSON.parse(uri.query) as UriFields;\n", "\t\t} catch (e) {\n", "\t\t\treturn undefined;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet query: UriFields;\n" ], "file_path": "src/vs/workbench/contrib/multiDiffEditor/browser/scmMultiDiffSourceResolver.ts", "type": "replace", "edit_start_line_idx": 33 }
{ "original": { "content": "import { IChange, IDiffComputationResult } from 'vs/editor/common/diff/diffComputer';", "fileName": "./1.txt" }, "modified": { "content": "import { IDocumentDiffProviderOptions } from 'vs/editor/common/diff/documentDiffProvider';\nimport { IChange } from 'vs/editor/common/diff/smartLinesDiffComputer';", "fileName": "./2.txt" }, "diffs": [ { "originalRange": "[1,2)", "modifiedRange": "[1,3)", "innerChanges": [ { "originalRange": "[1,11 -> 1,20]", "modifiedRange": "[1,11 -> 1,77]" }, { "originalRange": "[1,24 -> 1,41]", "modifiedRange": "[1,81 -> 2,17]" }, { "originalRange": "[1,72 -> 1,73]", "modifiedRange": "[2,48 -> 2,59]" } ] } ] }
src/vs/editor/test/node/diffing/fixtures/penalize-fragmentation/legacy.expected.diff.json
0
https://github.com/microsoft/vscode/commit/3f52e5efd6eee98a355a221044f92b9620d24238
[ 0.00017442854004912078, 0.00017226938507519662, 0.00016964967653620988, 0.00017249968368560076, 0.0000017352313079754822 ]
{ "id": 0, "code_window": [ "\n", " p.buildExploreQuery = function(type, withKey, withMeasurementFilter) {\n", " var query;\n", " var measurement;\n", "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 44 }
define([ 'lodash' ], function (_) { 'use strict'; function InfluxQueryBuilder(target, database) { this.target = target; this.database = database; } function renderTagCondition (tag, index) { var str = ""; var operator = tag.operator; var value = tag.value; if (index > 0) { str = (tag.condition || 'AND') + ' '; } if (!operator) { if (/^\/.*\/$/.test(tag.value)) { operator = '=~'; } else { operator = '='; } } // quote value unless regex or number if (operator !== '=~' && operator !== '!~' && isNaN(+value)) { value = "'" + value + "'"; } return str + '"' + tag.key + '" ' + operator + ' ' + value; } var p = InfluxQueryBuilder.prototype; p.build = function() { return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery(); }; p.buildExploreQuery = function(type, withKey, withMeasurementFilter) { var query; var measurement; if (type === 'TAG_KEYS') { query = 'SHOW TAG KEYS'; measurement = this.target.measurement; } else if (type === 'TAG_VALUES') { query = 'SHOW TAG VALUES'; measurement = this.target.measurement; } else if (type === 'MEASUREMENTS') { query = 'SHOW MEASUREMENTS'; if (withMeasurementFilter) { query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/'; } } else if (type === 'FIELDS') { if (!this.target.measurement.match('^/.*/')) { return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"'; } else { return 'SHOW FIELD KEYS FROM ' + this.target.measurement; } } else if (type === 'RETENTION POLICIES') { query = 'SHOW RETENTION POLICIES on "' + this.database + '"'; return query; } if (measurement) { if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) { measurement = '"' + measurement+ '"'; } query += ' FROM ' + measurement; } if (withKey) { query += ' WITH KEY = "' + withKey + '"'; } if (this.target.tags && this.target.tags.length > 0) { var whereConditions = _.reduce(this.target.tags, function(memo, tag) { // do not add a condition for the key we want to explore for if (tag.key === withKey) { return memo; } memo.push(renderTagCondition(tag, memo.length)); return memo; }, []); if (whereConditions.length > 0) { query += ' WHERE ' + whereConditions.join(' '); } } if (type === 'MEASUREMENTS') { query += ' LIMIT 100'; //Solve issue #2524 by limiting the number of measurements returned //LIMIT must be after WITH MEASUREMENT and WHERE clauses //This also could be used for TAG KEYS and TAG VALUES, if desired } return query; }; return InfluxQueryBuilder; });
public/app/plugins/datasource/influxdb/query_builder.js
1
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.9988483190536499, 0.5869572162628174, 0.0001687320473138243, 0.9858438968658447, 0.46631309390068054 ]
{ "id": 0, "code_window": [ "\n", " p.buildExploreQuery = function(type, withKey, withMeasurementFilter) {\n", " var query;\n", " var measurement;\n", "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 44 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package thrift type TServer interface { ProcessorFactory() TProcessorFactory ServerTransport() TServerTransport InputTransportFactory() TTransportFactory OutputTransportFactory() TTransportFactory InputProtocolFactory() TProtocolFactory OutputProtocolFactory() TProtocolFactory // Starts the server Serve() error // Stops the server. This is optional on a per-implementation basis. Not // all servers are required to be cleanly stoppable. Stop() error }
vendor/github.com/apache/thrift/lib/go/thrift/server.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.0001786262437235564, 0.00017236015992239118, 0.00016500549099873751, 0.000172904459759593, 0.00000560004673388903 ]
{ "id": 0, "code_window": [ "\n", " p.buildExploreQuery = function(type, withKey, withMeasurementFilter) {\n", " var query;\n", " var measurement;\n", "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 44 }
// Copyright 2016 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package builder import "fmt" // Like defines like condition type Like [2]string var _ Cond = Like{"", ""} // WriteTo write SQL to Writer func (like Like) WriteTo(w Writer) error { if _, err := fmt.Fprintf(w, "%s LIKE ?", like[0]); err != nil { return err } // FIXME: if use other regular express, this will be failed. but for compitable, keep this if like[1][0] == '%' || like[1][len(like[1])-1] == '%' { w.Append(like[1]) } else { w.Append("%" + like[1] + "%") } return nil } // And implements And with other conditions func (like Like) And(conds ...Cond) Cond { return And(like, And(conds...)) } // Or implements Or with other conditions func (like Like) Or(conds ...Cond) Cond { return Or(like, Or(conds...)) } // IsValid tests if this condition is valid func (like Like) IsValid() bool { return len(like[0]) > 0 && len(like[1]) > 0 }
vendor/github.com/go-xorm/builder/cond_like.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017856628983281553, 0.00017372486763633788, 0.00016466206579934806, 0.00017600903811398894, 0.000005177290404390078 ]
{ "id": 0, "code_window": [ "\n", " p.buildExploreQuery = function(type, withKey, withMeasurementFilter) {\n", " var query;\n", " var measurement;\n", "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 44 }
// Copyright 2011 Aaron Jacobs. All Rights Reserved. // Author: [email protected] (Aaron Jacobs) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package oglematchers import ( "fmt" "reflect" ) // GreaterOrEqual returns a matcher that matches integer, floating point, or // strings values v such that v >= x. Comparison is not defined between numeric // and string types, but is defined between all integer and floating point // types. // // x must itself be an integer, floating point, or string type; otherwise, // GreaterOrEqual will panic. func GreaterOrEqual(x interface{}) Matcher { desc := fmt.Sprintf("greater than or equal to %v", x) // Special case: make it clear that strings are strings. if reflect.TypeOf(x).Kind() == reflect.String { desc = fmt.Sprintf("greater than or equal to \"%s\"", x) } return transformDescription(Not(LessThan(x)), desc) }
vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017860323714558035, 0.00017676971037872136, 0.0001754784898366779, 0.00017649854999035597, 0.0000013226941746324883 ]
{ "id": 1, "code_window": [ "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n", " measurement = this.target.measurement;\n", " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 48 }
define([ 'lodash' ], function (_) { 'use strict'; function InfluxQueryBuilder(target, database) { this.target = target; this.database = database; } function renderTagCondition (tag, index) { var str = ""; var operator = tag.operator; var value = tag.value; if (index > 0) { str = (tag.condition || 'AND') + ' '; } if (!operator) { if (/^\/.*\/$/.test(tag.value)) { operator = '=~'; } else { operator = '='; } } // quote value unless regex or number if (operator !== '=~' && operator !== '!~' && isNaN(+value)) { value = "'" + value + "'"; } return str + '"' + tag.key + '" ' + operator + ' ' + value; } var p = InfluxQueryBuilder.prototype; p.build = function() { return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery(); }; p.buildExploreQuery = function(type, withKey, withMeasurementFilter) { var query; var measurement; if (type === 'TAG_KEYS') { query = 'SHOW TAG KEYS'; measurement = this.target.measurement; } else if (type === 'TAG_VALUES') { query = 'SHOW TAG VALUES'; measurement = this.target.measurement; } else if (type === 'MEASUREMENTS') { query = 'SHOW MEASUREMENTS'; if (withMeasurementFilter) { query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/'; } } else if (type === 'FIELDS') { if (!this.target.measurement.match('^/.*/')) { return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"'; } else { return 'SHOW FIELD KEYS FROM ' + this.target.measurement; } } else if (type === 'RETENTION POLICIES') { query = 'SHOW RETENTION POLICIES on "' + this.database + '"'; return query; } if (measurement) { if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) { measurement = '"' + measurement+ '"'; } query += ' FROM ' + measurement; } if (withKey) { query += ' WITH KEY = "' + withKey + '"'; } if (this.target.tags && this.target.tags.length > 0) { var whereConditions = _.reduce(this.target.tags, function(memo, tag) { // do not add a condition for the key we want to explore for if (tag.key === withKey) { return memo; } memo.push(renderTagCondition(tag, memo.length)); return memo; }, []); if (whereConditions.length > 0) { query += ' WHERE ' + whereConditions.join(' '); } } if (type === 'MEASUREMENTS') { query += ' LIMIT 100'; //Solve issue #2524 by limiting the number of measurements returned //LIMIT must be after WITH MEASUREMENT and WHERE clauses //This also could be used for TAG KEYS and TAG VALUES, if desired } return query; }; return InfluxQueryBuilder; });
public/app/plugins/datasource/influxdb/query_builder.js
1
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.9986929297447205, 0.3635706901550293, 0.00022900027397554368, 0.01312144286930561, 0.4749601483345032 ]
{ "id": 1, "code_window": [ "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n", " measurement = this.target.measurement;\n", " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 48 }
// Icon Sizes // ------------------------- /* makes the font 33% larger relative to the icon container */ .#{$fa-css-prefix}-lg { font-size: (4em / 3); line-height: (3em / 4); vertical-align: -15%; } .#{$fa-css-prefix}-2x { font-size: 2em; } .#{$fa-css-prefix}-3x { font-size: 3em; } .#{$fa-css-prefix}-4x { font-size: 4em; } .#{$fa-css-prefix}-5x { font-size: 5em; }
public/sass/base/font-awesome/_larger.scss
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017529386968817562, 0.00017460121307522058, 0.00017390857101418078, 0.00017460121307522058, 6.926493369974196e-7 ]
{ "id": 1, "code_window": [ "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n", " measurement = this.target.measurement;\n", " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 48 }
package pq import ( "encoding/hex" "fmt" ) // decodeUUIDBinary interprets the binary format of a uuid, returning it in text format. func decodeUUIDBinary(src []byte) ([]byte, error) { if len(src) != 16 { return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src)) } dst := make([]byte, 36) dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-' hex.Encode(dst[0:], src[0:4]) hex.Encode(dst[9:], src[4:6]) hex.Encode(dst[14:], src[6:8]) hex.Encode(dst[19:], src[8:10]) hex.Encode(dst[24:], src[10:16]) return dst, nil }
vendor/github.com/lib/pq/uuid.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017573787772562355, 0.00017147709149867296, 0.0001645923766773194, 0.00017410102009307593, 0.000004913878001389094 ]
{ "id": 1, "code_window": [ "\n", " if (type === 'TAG_KEYS') {\n", " query = 'SHOW TAG KEYS';\n", " measurement = this.target.measurement;\n", " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 48 }
package procfs import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) // CPUStat shows how much time the cpu spend in various stages. type CPUStat struct { User float64 Nice float64 System float64 Idle float64 Iowait float64 IRQ float64 SoftIRQ float64 Steal float64 Guest float64 GuestNice float64 } // SoftIRQStat represent the softirq statistics as exported in the procfs stat file. // A nice introduction can be found at https://0xax.gitbooks.io/linux-insides/content/interrupts/interrupts-9.html // It is possible to get per-cpu stats by reading /proc/softirqs type SoftIRQStat struct { Hi uint64 Timer uint64 NetTx uint64 NetRx uint64 Block uint64 BlockIoPoll uint64 Tasklet uint64 Sched uint64 Hrtimer uint64 Rcu uint64 } // Stat represents kernel/system statistics. type Stat struct { // Boot time in seconds since the Epoch. BootTime uint64 // Summed up cpu statistics. CPUTotal CPUStat // Per-CPU statistics. CPU []CPUStat // Number of times interrupts were handled, which contains numbered and unnumbered IRQs. IRQTotal uint64 // Number of times a numbered IRQ was triggered. IRQ []uint64 // Number of times a context switch happened. ContextSwitches uint64 // Number of times a process was created. ProcessCreated uint64 // Number of processes currently running. ProcessesRunning uint64 // Number of processes currently blocked (waiting for IO). ProcessesBlocked uint64 // Number of times a softirq was scheduled. SoftIRQTotal uint64 // Detailed softirq statistics. SoftIRQ SoftIRQStat } // NewStat returns kernel/system statistics read from /proc/stat. func NewStat() (Stat, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return Stat{}, err } return fs.NewStat() } // Parse a cpu statistics line and returns the CPUStat struct plus the cpu id (or -1 for the overall sum). func parseCPUStat(line string) (CPUStat, int64, error) { cpuStat := CPUStat{} var cpu string count, err := fmt.Sscanf(line, "%s %f %f %f %f %f %f %f %f %f %f", &cpu, &cpuStat.User, &cpuStat.Nice, &cpuStat.System, &cpuStat.Idle, &cpuStat.Iowait, &cpuStat.IRQ, &cpuStat.SoftIRQ, &cpuStat.Steal, &cpuStat.Guest, &cpuStat.GuestNice) if err != nil && err != io.EOF { return CPUStat{}, -1, fmt.Errorf("couldn't parse %s (cpu): %s", line, err) } if count == 0 { return CPUStat{}, -1, fmt.Errorf("couldn't parse %s (cpu): 0 elements parsed", line) } cpuStat.User /= userHZ cpuStat.Nice /= userHZ cpuStat.System /= userHZ cpuStat.Idle /= userHZ cpuStat.Iowait /= userHZ cpuStat.IRQ /= userHZ cpuStat.SoftIRQ /= userHZ cpuStat.Steal /= userHZ cpuStat.Guest /= userHZ cpuStat.GuestNice /= userHZ if cpu == "cpu" { return cpuStat, -1, nil } cpuID, err := strconv.ParseInt(cpu[3:], 10, 64) if err != nil { return CPUStat{}, -1, fmt.Errorf("couldn't parse %s (cpu/cpuid): %s", line, err) } return cpuStat, cpuID, nil } // Parse a softirq line. func parseSoftIRQStat(line string) (SoftIRQStat, uint64, error) { softIRQStat := SoftIRQStat{} var total uint64 var prefix string _, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d", &prefix, &total, &softIRQStat.Hi, &softIRQStat.Timer, &softIRQStat.NetTx, &softIRQStat.NetRx, &softIRQStat.Block, &softIRQStat.BlockIoPoll, &softIRQStat.Tasklet, &softIRQStat.Sched, &softIRQStat.Hrtimer, &softIRQStat.Rcu) if err != nil { return SoftIRQStat{}, 0, fmt.Errorf("couldn't parse %s (softirq): %s", line, err) } return softIRQStat, total, nil } // NewStat returns an information about current kernel/system statistics. func (fs FS) NewStat() (Stat, error) { // See https://www.kernel.org/doc/Documentation/filesystems/proc.txt f, err := os.Open(fs.Path("stat")) if err != nil { return Stat{}, err } defer f.Close() stat := Stat{} scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() parts := strings.Fields(scanner.Text()) // require at least <key> <value> if len(parts) < 2 { continue } switch { case parts[0] == "btime": if stat.BootTime, err = strconv.ParseUint(parts[1], 10, 64); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s (btime): %s", parts[1], err) } case parts[0] == "intr": if stat.IRQTotal, err = strconv.ParseUint(parts[1], 10, 64); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s (intr): %s", parts[1], err) } numberedIRQs := parts[2:] stat.IRQ = make([]uint64, len(numberedIRQs)) for i, count := range numberedIRQs { if stat.IRQ[i], err = strconv.ParseUint(count, 10, 64); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s (intr%d): %s", count, i, err) } } case parts[0] == "ctxt": if stat.ContextSwitches, err = strconv.ParseUint(parts[1], 10, 64); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s (ctxt): %s", parts[1], err) } case parts[0] == "processes": if stat.ProcessCreated, err = strconv.ParseUint(parts[1], 10, 64); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s (processes): %s", parts[1], err) } case parts[0] == "procs_running": if stat.ProcessesRunning, err = strconv.ParseUint(parts[1], 10, 64); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s (procs_running): %s", parts[1], err) } case parts[0] == "procs_blocked": if stat.ProcessesBlocked, err = strconv.ParseUint(parts[1], 10, 64); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s (procs_blocked): %s", parts[1], err) } case parts[0] == "softirq": softIRQStats, total, err := parseSoftIRQStat(line) if err != nil { return Stat{}, err } stat.SoftIRQTotal = total stat.SoftIRQ = softIRQStats case strings.HasPrefix(parts[0], "cpu"): cpuStat, cpuID, err := parseCPUStat(line) if err != nil { return Stat{}, err } if cpuID == -1 { stat.CPUTotal = cpuStat } else { for int64(len(stat.CPU)) <= cpuID { stat.CPU = append(stat.CPU, CPUStat{}) } stat.CPU[cpuID] = cpuStat } } } if err := scanner.Err(); err != nil { return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err) } return stat, nil }
vendor/github.com/prometheus/procfs/stat.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.003665392054244876, 0.0003315109061077237, 0.00016686633171048015, 0.00017276068683713675, 0.0007275205571204424 ]
{ "id": 2, "code_window": [ " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n", " } else if (type === 'MEASUREMENTS') {\n", " query = 'SHOW MEASUREMENTS';\n", " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 51 }
define([ 'lodash' ], function (_) { 'use strict'; function InfluxQueryBuilder(target, database) { this.target = target; this.database = database; } function renderTagCondition (tag, index) { var str = ""; var operator = tag.operator; var value = tag.value; if (index > 0) { str = (tag.condition || 'AND') + ' '; } if (!operator) { if (/^\/.*\/$/.test(tag.value)) { operator = '=~'; } else { operator = '='; } } // quote value unless regex or number if (operator !== '=~' && operator !== '!~' && isNaN(+value)) { value = "'" + value + "'"; } return str + '"' + tag.key + '" ' + operator + ' ' + value; } var p = InfluxQueryBuilder.prototype; p.build = function() { return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery(); }; p.buildExploreQuery = function(type, withKey, withMeasurementFilter) { var query; var measurement; if (type === 'TAG_KEYS') { query = 'SHOW TAG KEYS'; measurement = this.target.measurement; } else if (type === 'TAG_VALUES') { query = 'SHOW TAG VALUES'; measurement = this.target.measurement; } else if (type === 'MEASUREMENTS') { query = 'SHOW MEASUREMENTS'; if (withMeasurementFilter) { query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/'; } } else if (type === 'FIELDS') { if (!this.target.measurement.match('^/.*/')) { return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"'; } else { return 'SHOW FIELD KEYS FROM ' + this.target.measurement; } } else if (type === 'RETENTION POLICIES') { query = 'SHOW RETENTION POLICIES on "' + this.database + '"'; return query; } if (measurement) { if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) { measurement = '"' + measurement+ '"'; } query += ' FROM ' + measurement; } if (withKey) { query += ' WITH KEY = "' + withKey + '"'; } if (this.target.tags && this.target.tags.length > 0) { var whereConditions = _.reduce(this.target.tags, function(memo, tag) { // do not add a condition for the key we want to explore for if (tag.key === withKey) { return memo; } memo.push(renderTagCondition(tag, memo.length)); return memo; }, []); if (whereConditions.length > 0) { query += ' WHERE ' + whereConditions.join(' '); } } if (type === 'MEASUREMENTS') { query += ' LIMIT 100'; //Solve issue #2524 by limiting the number of measurements returned //LIMIT must be after WITH MEASUREMENT and WHERE clauses //This also could be used for TAG KEYS and TAG VALUES, if desired } return query; }; return InfluxQueryBuilder; });
public/app/plugins/datasource/influxdb/query_builder.js
1
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.9975155591964722, 0.446022629737854, 0.0001684099406702444, 0.0062873391434550285, 0.4865759313106537 ]
{ "id": 2, "code_window": [ " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n", " } else if (type === 'MEASUREMENTS') {\n", " query = 'SHOW MEASUREMENTS';\n", " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 51 }
foo[].bar[].[baz, qux]
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-463
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017598671547602862, 0.00017598671547602862, 0.00017598671547602862, 0.00017598671547602862, 0 ]
{ "id": 2, "code_window": [ " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n", " } else if (type === 'MEASUREMENTS') {\n", " query = 'SHOW MEASUREMENTS';\n", " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 51 }
package api import ( "testing" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" . "github.com/smartystreets/goconvey/convey" ) func TestUserApiEndpoint(t *testing.T) { Convey("Given a user is logged in", t, func() { mockResult := models.SearchUserQueryResult{ Users: []*models.UserSearchHitDTO{ {Name: "user1"}, {Name: "user2"}, }, TotalCount: 2, } loggedInUserScenario("When calling GET on", "/api/users", func(sc *scenarioContext) { var sentLimit int var sendPage int bus.AddHandler("test", func(query *models.SearchUsersQuery) error { query.Result = mockResult sentLimit = query.Limit sendPage = query.Page return nil }) sc.handlerFunc = SearchUsers sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() So(sentLimit, ShouldEqual, 1000) So(sendPage, ShouldEqual, 1) respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes()) So(err, ShouldBeNil) So(len(respJSON.MustArray()), ShouldEqual, 2) }) loggedInUserScenario("When calling GET with page and limit querystring parameters on", "/api/users", func(sc *scenarioContext) { var sentLimit int var sendPage int bus.AddHandler("test", func(query *models.SearchUsersQuery) error { query.Result = mockResult sentLimit = query.Limit sendPage = query.Page return nil }) sc.handlerFunc = SearchUsers sc.fakeReqWithParams("GET", sc.url, map[string]string{"perpage": "10", "page": "2"}).exec() So(sentLimit, ShouldEqual, 10) So(sendPage, ShouldEqual, 2) }) loggedInUserScenario("When calling GET on", "/api/users/search", func(sc *scenarioContext) { var sentLimit int var sendPage int bus.AddHandler("test", func(query *models.SearchUsersQuery) error { query.Result = mockResult sentLimit = query.Limit sendPage = query.Page return nil }) sc.handlerFunc = SearchUsersWithPaging sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() So(sentLimit, ShouldEqual, 1000) So(sendPage, ShouldEqual, 1) respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes()) So(err, ShouldBeNil) So(respJSON.Get("totalCount").MustInt(), ShouldEqual, 2) So(len(respJSON.Get("users").MustArray()), ShouldEqual, 2) }) loggedInUserScenario("When calling GET with page and perpage querystring parameters on", "/api/users/search", func(sc *scenarioContext) { var sentLimit int var sendPage int bus.AddHandler("test", func(query *models.SearchUsersQuery) error { query.Result = mockResult sentLimit = query.Limit sendPage = query.Page return nil }) sc.handlerFunc = SearchUsersWithPaging sc.fakeReqWithParams("GET", sc.url, map[string]string{"perpage": "10", "page": "2"}).exec() So(sentLimit, ShouldEqual, 10) So(sendPage, ShouldEqual, 2) }) }) }
pkg/api/user_test.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00035422371001914144, 0.0002104669256368652, 0.00016450011753477156, 0.00017101310368161649, 0.0000662249221932143 ]
{ "id": 2, "code_window": [ " } else if (type === 'TAG_VALUES') {\n", " query = 'SHOW TAG VALUES';\n", " measurement = this.target.measurement;\n", " } else if (type === 'MEASUREMENTS') {\n", " query = 'SHOW MEASUREMENTS';\n", " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " policy = this.target.policy;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 51 }
package redis import ( "fmt" "strconv" "strings" "time" "gopkg.in/bufio.v1" ) var ( _ Cmder = (*Cmd)(nil) _ Cmder = (*SliceCmd)(nil) _ Cmder = (*StatusCmd)(nil) _ Cmder = (*IntCmd)(nil) _ Cmder = (*DurationCmd)(nil) _ Cmder = (*BoolCmd)(nil) _ Cmder = (*StringCmd)(nil) _ Cmder = (*FloatCmd)(nil) _ Cmder = (*StringSliceCmd)(nil) _ Cmder = (*BoolSliceCmd)(nil) _ Cmder = (*StringStringMapCmd)(nil) _ Cmder = (*ZSliceCmd)(nil) _ Cmder = (*ScanCmd)(nil) ) type Cmder interface { args() []string parseReply(*bufio.Reader) error setErr(error) writeTimeout() *time.Duration readTimeout() *time.Duration Err() error String() string } func setCmdsErr(cmds []Cmder, e error) { for _, cmd := range cmds { cmd.setErr(e) } } func cmdString(cmd Cmder, val interface{}) string { s := strings.Join(cmd.args(), " ") if err := cmd.Err(); err != nil { return s + ": " + err.Error() } if val != nil { return s + ": " + fmt.Sprint(val) } return s } //------------------------------------------------------------------------------ type baseCmd struct { _args []string err error _writeTimeout, _readTimeout *time.Duration } func newBaseCmd(args ...string) *baseCmd { return &baseCmd{ _args: args, } } func (cmd *baseCmd) Err() error { if cmd.err != nil { return cmd.err } return nil } func (cmd *baseCmd) args() []string { return cmd._args } func (cmd *baseCmd) readTimeout() *time.Duration { return cmd._readTimeout } func (cmd *baseCmd) setReadTimeout(d time.Duration) { cmd._readTimeout = &d } func (cmd *baseCmd) writeTimeout() *time.Duration { return cmd._writeTimeout } func (cmd *baseCmd) setWriteTimeout(d time.Duration) { cmd._writeTimeout = &d } func (cmd *baseCmd) setErr(e error) { cmd.err = e } //------------------------------------------------------------------------------ type Cmd struct { *baseCmd val interface{} } func NewCmd(args ...string) *Cmd { return &Cmd{ baseCmd: newBaseCmd(args...), } } func (cmd *Cmd) Val() interface{} { return cmd.val } func (cmd *Cmd) Result() (interface{}, error) { return cmd.val, cmd.err } func (cmd *Cmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *Cmd) parseReply(rd *bufio.Reader) error { cmd.val, cmd.err = parseReply(rd, parseSlice) return cmd.err } //------------------------------------------------------------------------------ type SliceCmd struct { *baseCmd val []interface{} } func NewSliceCmd(args ...string) *SliceCmd { return &SliceCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *SliceCmd) Val() []interface{} { return cmd.val } func (cmd *SliceCmd) Result() ([]interface{}, error) { return cmd.val, cmd.err } func (cmd *SliceCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *SliceCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, parseSlice) if err != nil { cmd.err = err return err } cmd.val = v.([]interface{}) return nil } //------------------------------------------------------------------------------ type StatusCmd struct { *baseCmd val string } func NewStatusCmd(args ...string) *StatusCmd { return &StatusCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *StatusCmd) Val() string { return cmd.val } func (cmd *StatusCmd) Result() (string, error) { return cmd.val, cmd.err } func (cmd *StatusCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *StatusCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, nil) if err != nil { cmd.err = err return err } cmd.val = v.(string) return nil } //------------------------------------------------------------------------------ type IntCmd struct { *baseCmd val int64 } func NewIntCmd(args ...string) *IntCmd { return &IntCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *IntCmd) Val() int64 { return cmd.val } func (cmd *IntCmd) Result() (int64, error) { return cmd.val, cmd.err } func (cmd *IntCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *IntCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, nil) if err != nil { cmd.err = err return err } cmd.val = v.(int64) return nil } //------------------------------------------------------------------------------ type DurationCmd struct { *baseCmd val time.Duration precision time.Duration } func NewDurationCmd(precision time.Duration, args ...string) *DurationCmd { return &DurationCmd{ baseCmd: newBaseCmd(args...), precision: precision, } } func (cmd *DurationCmd) Val() time.Duration { return cmd.val } func (cmd *DurationCmd) Result() (time.Duration, error) { return cmd.val, cmd.err } func (cmd *DurationCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *DurationCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, nil) if err != nil { cmd.err = err return err } cmd.val = time.Duration(v.(int64)) * cmd.precision return nil } //------------------------------------------------------------------------------ type BoolCmd struct { *baseCmd val bool } func NewBoolCmd(args ...string) *BoolCmd { return &BoolCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *BoolCmd) Val() bool { return cmd.val } func (cmd *BoolCmd) Result() (bool, error) { return cmd.val, cmd.err } func (cmd *BoolCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *BoolCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, nil) if err != nil { cmd.err = err return err } cmd.val = v.(int64) == 1 return nil } //------------------------------------------------------------------------------ type StringCmd struct { *baseCmd val string } func NewStringCmd(args ...string) *StringCmd { return &StringCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *StringCmd) Val() string { return cmd.val } func (cmd *StringCmd) Result() (string, error) { return cmd.val, cmd.err } func (cmd *StringCmd) Int64() (int64, error) { if cmd.err != nil { return 0, cmd.err } return strconv.ParseInt(cmd.val, 10, 64) } func (cmd *StringCmd) Uint64() (uint64, error) { if cmd.err != nil { return 0, cmd.err } return strconv.ParseUint(cmd.val, 10, 64) } func (cmd *StringCmd) Float64() (float64, error) { if cmd.err != nil { return 0, cmd.err } return strconv.ParseFloat(cmd.val, 64) } func (cmd *StringCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *StringCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, nil) if err != nil { cmd.err = err return err } cmd.val = v.(string) return nil } //------------------------------------------------------------------------------ type FloatCmd struct { *baseCmd val float64 } func NewFloatCmd(args ...string) *FloatCmd { return &FloatCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *FloatCmd) Val() float64 { return cmd.val } func (cmd *FloatCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *FloatCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, nil) if err != nil { cmd.err = err return err } cmd.val, cmd.err = strconv.ParseFloat(v.(string), 64) return cmd.err } //------------------------------------------------------------------------------ type StringSliceCmd struct { *baseCmd val []string } func NewStringSliceCmd(args ...string) *StringSliceCmd { return &StringSliceCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *StringSliceCmd) Val() []string { return cmd.val } func (cmd *StringSliceCmd) Result() ([]string, error) { return cmd.Val(), cmd.Err() } func (cmd *StringSliceCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *StringSliceCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, parseStringSlice) if err != nil { cmd.err = err return err } cmd.val = v.([]string) return nil } //------------------------------------------------------------------------------ type BoolSliceCmd struct { *baseCmd val []bool } func NewBoolSliceCmd(args ...string) *BoolSliceCmd { return &BoolSliceCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *BoolSliceCmd) Val() []bool { return cmd.val } func (cmd *BoolSliceCmd) Result() ([]bool, error) { return cmd.val, cmd.err } func (cmd *BoolSliceCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *BoolSliceCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, parseBoolSlice) if err != nil { cmd.err = err return err } cmd.val = v.([]bool) return nil } //------------------------------------------------------------------------------ type StringStringMapCmd struct { *baseCmd val map[string]string } func NewStringStringMapCmd(args ...string) *StringStringMapCmd { return &StringStringMapCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *StringStringMapCmd) Val() map[string]string { return cmd.val } func (cmd *StringStringMapCmd) Result() (map[string]string, error) { return cmd.val, cmd.err } func (cmd *StringStringMapCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *StringStringMapCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, parseStringStringMap) if err != nil { cmd.err = err return err } cmd.val = v.(map[string]string) return nil } //------------------------------------------------------------------------------ type ZSliceCmd struct { *baseCmd val []Z } func NewZSliceCmd(args ...string) *ZSliceCmd { return &ZSliceCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *ZSliceCmd) Val() []Z { return cmd.val } func (cmd *ZSliceCmd) Result() ([]Z, error) { return cmd.val, cmd.err } func (cmd *ZSliceCmd) String() string { return cmdString(cmd, cmd.val) } func (cmd *ZSliceCmd) parseReply(rd *bufio.Reader) error { v, err := parseReply(rd, parseZSlice) if err != nil { cmd.err = err return err } cmd.val = v.([]Z) return nil } //------------------------------------------------------------------------------ type ScanCmd struct { *baseCmd cursor int64 keys []string } func NewScanCmd(args ...string) *ScanCmd { return &ScanCmd{ baseCmd: newBaseCmd(args...), } } func (cmd *ScanCmd) Val() (int64, []string) { return cmd.cursor, cmd.keys } func (cmd *ScanCmd) Result() (int64, []string, error) { return cmd.cursor, cmd.keys, cmd.err } func (cmd *ScanCmd) String() string { return cmdString(cmd, cmd.keys) } func (cmd *ScanCmd) parseReply(rd *bufio.Reader) error { vi, err := parseReply(rd, parseSlice) if err != nil { cmd.err = err return cmd.err } v := vi.([]interface{}) cmd.cursor, cmd.err = strconv.ParseInt(v[0].(string), 10, 64) if cmd.err != nil { return cmd.err } keys := v[1].([]interface{}) for _, keyi := range keys { cmd.keys = append(cmd.keys, keyi.(string)) } return nil }
vendor/gopkg.in/redis.v2/command.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.0005624235491268337, 0.00018529333465266973, 0.00015937229909468442, 0.0001692938240012154, 0.00006261590169742703 ]
{ "id": 3, "code_window": [ " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n", " }\n", " } else if (type === 'FIELDS') {\n", " if (!this.target.measurement.match('^/.*/')) {\n", " return 'SHOW FIELD KEYS FROM \"' + this.target.measurement + '\"';\n", " } else {\n", " return 'SHOW FIELD KEYS FROM ' + this.target.measurement;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " measurement = this.target.measurement;\n", " policy = this.target.policy;\n", " if (!measurement.match('^/.*/')) {\n", " measurement = '\"' + measurement + '\"';\n", " if (policy) {\n", " if (!policy.match('^/.*/')) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "replace", "edit_start_line_idx": 58 }
define([ 'lodash' ], function (_) { 'use strict'; function InfluxQueryBuilder(target, database) { this.target = target; this.database = database; } function renderTagCondition (tag, index) { var str = ""; var operator = tag.operator; var value = tag.value; if (index > 0) { str = (tag.condition || 'AND') + ' '; } if (!operator) { if (/^\/.*\/$/.test(tag.value)) { operator = '=~'; } else { operator = '='; } } // quote value unless regex or number if (operator !== '=~' && operator !== '!~' && isNaN(+value)) { value = "'" + value + "'"; } return str + '"' + tag.key + '" ' + operator + ' ' + value; } var p = InfluxQueryBuilder.prototype; p.build = function() { return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery(); }; p.buildExploreQuery = function(type, withKey, withMeasurementFilter) { var query; var measurement; if (type === 'TAG_KEYS') { query = 'SHOW TAG KEYS'; measurement = this.target.measurement; } else if (type === 'TAG_VALUES') { query = 'SHOW TAG VALUES'; measurement = this.target.measurement; } else if (type === 'MEASUREMENTS') { query = 'SHOW MEASUREMENTS'; if (withMeasurementFilter) { query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/'; } } else if (type === 'FIELDS') { if (!this.target.measurement.match('^/.*/')) { return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"'; } else { return 'SHOW FIELD KEYS FROM ' + this.target.measurement; } } else if (type === 'RETENTION POLICIES') { query = 'SHOW RETENTION POLICIES on "' + this.database + '"'; return query; } if (measurement) { if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) { measurement = '"' + measurement+ '"'; } query += ' FROM ' + measurement; } if (withKey) { query += ' WITH KEY = "' + withKey + '"'; } if (this.target.tags && this.target.tags.length > 0) { var whereConditions = _.reduce(this.target.tags, function(memo, tag) { // do not add a condition for the key we want to explore for if (tag.key === withKey) { return memo; } memo.push(renderTagCondition(tag, memo.length)); return memo; }, []); if (whereConditions.length > 0) { query += ' WHERE ' + whereConditions.join(' '); } } if (type === 'MEASUREMENTS') { query += ' LIMIT 100'; //Solve issue #2524 by limiting the number of measurements returned //LIMIT must be after WITH MEASUREMENT and WHERE clauses //This also could be used for TAG KEYS and TAG VALUES, if desired } return query; }; return InfluxQueryBuilder; });
public/app/plugins/datasource/influxdb/query_builder.js
1
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.9976907968521118, 0.11207414418458939, 0.00016696563397999853, 0.001974566141143441, 0.28424784541130066 ]
{ "id": 3, "code_window": [ " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n", " }\n", " } else if (type === 'FIELDS') {\n", " if (!this.target.measurement.match('^/.*/')) {\n", " return 'SHOW FIELD KEYS FROM \"' + this.target.measurement + '\"';\n", " } else {\n", " return 'SHOW FIELD KEYS FROM ' + this.target.measurement;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " measurement = this.target.measurement;\n", " policy = this.target.policy;\n", " if (!measurement.match('^/.*/')) {\n", " measurement = '\"' + measurement + '\"';\n", " if (policy) {\n", " if (!policy.match('^/.*/')) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "replace", "edit_start_line_idx": 58 }
///<reference path="../../../headers/common.d.ts" /> import kbn from 'app/core/utils/kbn'; export class AxesEditorCtrl { panel: any; panelCtrl: any; unitFormats: any; logScales: any; dataFormats: any; /** @ngInject */ constructor($scope, uiSegmentSrv) { $scope.editor = this; this.panelCtrl = $scope.ctrl; this.panel = this.panelCtrl.panel; this.unitFormats = kbn.getUnitFormats(); this.logScales = { 'linear': 1, 'log (base 2)': 2, 'log (base 10)': 10, 'log (base 32)': 32, 'log (base 1024)': 1024 }; this.dataFormats = { 'Time series': 'timeseries', 'Time series buckets': 'tsbuckets' }; } setUnitFormat(subItem) { this.panel.yAxis.format = subItem.value; this.panelCtrl.render(); } } /** @ngInject */ export function axesEditor() { 'use strict'; return { restrict: 'E', scope: true, templateUrl: 'public/app/plugins/panel/heatmap/partials/axes_editor.html', controller: AxesEditorCtrl, }; }
public/app/plugins/panel/heatmap/axes_editor.ts
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017356382159050554, 0.00016736473480705172, 0.00016179599333554506, 0.00016729471099097282, 0.0000037359716316132108 ]
{ "id": 3, "code_window": [ " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n", " }\n", " } else if (type === 'FIELDS') {\n", " if (!this.target.measurement.match('^/.*/')) {\n", " return 'SHOW FIELD KEYS FROM \"' + this.target.measurement + '\"';\n", " } else {\n", " return 'SHOW FIELD KEYS FROM ' + this.target.measurement;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " measurement = this.target.measurement;\n", " policy = this.target.policy;\n", " if (!measurement.match('^/.*/')) {\n", " measurement = '\"' + measurement + '\"';\n", " if (policy) {\n", " if (!policy.match('^/.*/')) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "replace", "edit_start_line_idx": 58 }
"?"
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-316
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00016523897647857666, 0.00016523897647857666, 0.00016523897647857666, 0.00016523897647857666, 0 ]
{ "id": 3, "code_window": [ " if (withMeasurementFilter)\n", " {\n", " query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';\n", " }\n", " } else if (type === 'FIELDS') {\n", " if (!this.target.measurement.match('^/.*/')) {\n", " return 'SHOW FIELD KEYS FROM \"' + this.target.measurement + '\"';\n", " } else {\n", " return 'SHOW FIELD KEYS FROM ' + this.target.measurement;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " measurement = this.target.measurement;\n", " policy = this.target.policy;\n", " if (!measurement.match('^/.*/')) {\n", " measurement = '\"' + measurement + '\"';\n", " if (policy) {\n", " if (!policy.match('^/.*/')) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "replace", "edit_start_line_idx": 58 }
hvu
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-257
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00016692615463398397, 0.00016692615463398397, 0.00016692615463398397, 0.00016692615463398397, 0 ]
{ "id": 4, "code_window": [ " }\n", " } else if (type === 'RETENTION POLICIES') {\n", " query = 'SHOW RETENTION POLICIES on \"' + this.database + '\"';\n", " return query;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return 'SHOW FIELD KEYS FROM ' + measurement;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 63 }
define([ 'lodash' ], function (_) { 'use strict'; function InfluxQueryBuilder(target, database) { this.target = target; this.database = database; } function renderTagCondition (tag, index) { var str = ""; var operator = tag.operator; var value = tag.value; if (index > 0) { str = (tag.condition || 'AND') + ' '; } if (!operator) { if (/^\/.*\/$/.test(tag.value)) { operator = '=~'; } else { operator = '='; } } // quote value unless regex or number if (operator !== '=~' && operator !== '!~' && isNaN(+value)) { value = "'" + value + "'"; } return str + '"' + tag.key + '" ' + operator + ' ' + value; } var p = InfluxQueryBuilder.prototype; p.build = function() { return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery(); }; p.buildExploreQuery = function(type, withKey, withMeasurementFilter) { var query; var measurement; if (type === 'TAG_KEYS') { query = 'SHOW TAG KEYS'; measurement = this.target.measurement; } else if (type === 'TAG_VALUES') { query = 'SHOW TAG VALUES'; measurement = this.target.measurement; } else if (type === 'MEASUREMENTS') { query = 'SHOW MEASUREMENTS'; if (withMeasurementFilter) { query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/'; } } else if (type === 'FIELDS') { if (!this.target.measurement.match('^/.*/')) { return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"'; } else { return 'SHOW FIELD KEYS FROM ' + this.target.measurement; } } else if (type === 'RETENTION POLICIES') { query = 'SHOW RETENTION POLICIES on "' + this.database + '"'; return query; } if (measurement) { if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) { measurement = '"' + measurement+ '"'; } query += ' FROM ' + measurement; } if (withKey) { query += ' WITH KEY = "' + withKey + '"'; } if (this.target.tags && this.target.tags.length > 0) { var whereConditions = _.reduce(this.target.tags, function(memo, tag) { // do not add a condition for the key we want to explore for if (tag.key === withKey) { return memo; } memo.push(renderTagCondition(tag, memo.length)); return memo; }, []); if (whereConditions.length > 0) { query += ' WHERE ' + whereConditions.join(' '); } } if (type === 'MEASUREMENTS') { query += ' LIMIT 100'; //Solve issue #2524 by limiting the number of measurements returned //LIMIT must be after WITH MEASUREMENT and WHERE clauses //This also could be used for TAG KEYS and TAG VALUES, if desired } return query; }; return InfluxQueryBuilder; });
public/app/plugins/datasource/influxdb/query_builder.js
1
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.9975358247756958, 0.1153523400425911, 0.000166361263836734, 0.003786171553656459, 0.28226354718208313 ]
{ "id": 4, "code_window": [ " }\n", " } else if (type === 'RETENTION POLICIES') {\n", " query = 'SHOW RETENTION POLICIES on \"' + this.database + '\"';\n", " return query;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return 'SHOW FIELD KEYS FROM ' + measurement;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 63 }
package main import ( "fmt" "os" "github.com/go-xorm/xorm" _ "github.com/mattn/go-sqlite3" ) func main() { if len(os.Args) < 2 { fmt.Println("need db path") return } orm, err := xorm.NewEngine("sqlite3", os.Args[1]) if err != nil { fmt.Println(err) return } defer orm.Close() orm.ShowSQL = true tables, err := orm.DBMetas() if err != nil { fmt.Println(err) return } for _, table := range tables { fmt.Println(table.Name) } }
vendor/github.com/go-xorm/xorm/examples/tables.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017150268831755966, 0.0001679487177170813, 0.0001659224508330226, 0.00016718488768674433, 0.000002277589601362706 ]
{ "id": 4, "code_window": [ " }\n", " } else if (type === 'RETENTION POLICIES') {\n", " query = 'SHOW RETENTION POLICIES on \"' + this.database + '\"';\n", " return query;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return 'SHOW FIELD KEYS FROM ' + measurement;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 63 }
Hostname "{{ HOST_NAME }}" FQDNLookup false Interval {{ COLLECT_INTERVAL | default("10") }} Timeout 2 ReadThreads 5 LoadPlugin cpu LoadPlugin df LoadPlugin load LoadPlugin memory LoadPlugin disk LoadPlugin interface LoadPlugin uptime LoadPlugin swap LoadPlugin write_graphite LoadPlugin processes LoadPlugin aggregation LoadPlugin match_regex # LoadPlugin memcached <Plugin df> # expose host's mounts into container using -v /:/host:ro (location inside container does not matter much) # ignore rootfs; else, the root file-system would appear twice, causing # one of the updates to fail and spam the log FSType rootfs # ignore the usual virtual / temporary file-systems FSType sysfs FSType proc FSType devtmpfs FSType devpts FSType tmpfs FSType fusectl FSType cgroup FSType overlay FSType debugfs FSType pstore FSType securityfs FSType hugetlbfs FSType squashfs FSType mqueue MountPoint "/etc/resolv.conf" MountPoint "/etc/hostname" MountPoint "/etc/hosts" IgnoreSelected true ReportByDevice false ReportReserved true ReportInodes true ValuesAbsolute true ValuesPercentage true ReportInodes true </Plugin> <Plugin "disk"> Disk "/^[hs]d[a-z]/" IgnoreSelected false </Plugin> <Plugin "aggregation"> <Aggregation> Plugin "cpu" Type "cpu" GroupBy "Host" GroupBy "TypeInstance" CalculateAverage true </Aggregation> </Plugin> <Plugin interface> Interface "lo" Interface "/^veth.*/" Interface "/^docker.*/" IgnoreSelected true </Plugin> # <Plugin "memcached"> # Host "memcached" # Port "11211" # </Plugin> <Chain "PostCache"> <Rule> <Match regex> Plugin "^cpu$" PluginInstance "^[0-9]+$" </Match> <Target write> Plugin "aggregation" </Target> Target stop </Rule> Target "write" </Chain> <Plugin "write_graphite"> <Carbon> Host "{{ GRAPHITE_HOST }}" Port "{{ GRAPHITE_PORT | default("2003") }}" Prefix "{{ GRAPHITE_PREFIX | default("collectd.") }}" EscapeCharacter "_" SeparateInstances true StoreRates true AlwaysAppendDS false </Carbon> </Plugin>
docker/blocks/collectd/collectd.conf.tpl
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017499559908173978, 0.00017075720825232565, 0.00016766983026172966, 0.00016916975437197834, 0.0000025897325031110086 ]
{ "id": 4, "code_window": [ " }\n", " } else if (type === 'RETENTION POLICIES') {\n", " query = 'SHOW RETENTION POLICIES on \"' + this.database + '\"';\n", " return query;\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return 'SHOW FIELD KEYS FROM ' + measurement;\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 63 }
package plugins import ( "path/filepath" "testing" "github.com/grafana/grafana/pkg/setting" . "github.com/smartystreets/goconvey/convey" "gopkg.in/ini.v1" ) func TestPluginScans(t *testing.T) { Convey("When scaning for plugins", t, func() { setting.StaticRootPath, _ = filepath.Abs("../../public/") setting.Cfg = ini.Empty() err := Init() So(err, ShouldBeNil) So(len(DataSources), ShouldBeGreaterThan, 1) So(len(Panels), ShouldBeGreaterThan, 1) Convey("Should set module automatically", func() { So(DataSources["graphite"].Module, ShouldEqual, "app/plugins/datasource/graphite/module") }) }) Convey("When reading app plugin definition", t, func() { setting.Cfg = ini.Empty() sec, _ := setting.Cfg.NewSection("plugin.nginx-app") sec.NewKey("path", "../../tests/test-app") err := Init() So(err, ShouldBeNil) So(len(Apps), ShouldBeGreaterThan, 0) So(Apps["test-app"].Info.Logos.Large, ShouldEqual, "public/plugins/test-app/img/logo_large.png") So(Apps["test-app"].Info.Screenshots[1].Path, ShouldEqual, "public/plugins/test-app/img/screenshot2.png") }) }
pkg/plugins/plugins_test.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017925446445588022, 0.00017219301662407815, 0.0001649414625717327, 0.00017184758326038718, 0.0000046194841161195654 ]
{ "id": 5, "code_window": [ " if (measurement) {\n", " if (!measurement.match('^/.*/') && !measurement.match(/^merge\\(.*\\)/)) {\n", " measurement = '\"' + measurement+ '\"';\n", " }\n", " query += ' FROM ' + measurement;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (policy) {\n", " if (!policy.match('^/.*/') && !policy.match(/^merge\\(.*\\)/)) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 72 }
define([ 'lodash' ], function (_) { 'use strict'; function InfluxQueryBuilder(target, database) { this.target = target; this.database = database; } function renderTagCondition (tag, index) { var str = ""; var operator = tag.operator; var value = tag.value; if (index > 0) { str = (tag.condition || 'AND') + ' '; } if (!operator) { if (/^\/.*\/$/.test(tag.value)) { operator = '=~'; } else { operator = '='; } } // quote value unless regex or number if (operator !== '=~' && operator !== '!~' && isNaN(+value)) { value = "'" + value + "'"; } return str + '"' + tag.key + '" ' + operator + ' ' + value; } var p = InfluxQueryBuilder.prototype; p.build = function() { return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery(); }; p.buildExploreQuery = function(type, withKey, withMeasurementFilter) { var query; var measurement; if (type === 'TAG_KEYS') { query = 'SHOW TAG KEYS'; measurement = this.target.measurement; } else if (type === 'TAG_VALUES') { query = 'SHOW TAG VALUES'; measurement = this.target.measurement; } else if (type === 'MEASUREMENTS') { query = 'SHOW MEASUREMENTS'; if (withMeasurementFilter) { query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/'; } } else if (type === 'FIELDS') { if (!this.target.measurement.match('^/.*/')) { return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"'; } else { return 'SHOW FIELD KEYS FROM ' + this.target.measurement; } } else if (type === 'RETENTION POLICIES') { query = 'SHOW RETENTION POLICIES on "' + this.database + '"'; return query; } if (measurement) { if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) { measurement = '"' + measurement+ '"'; } query += ' FROM ' + measurement; } if (withKey) { query += ' WITH KEY = "' + withKey + '"'; } if (this.target.tags && this.target.tags.length > 0) { var whereConditions = _.reduce(this.target.tags, function(memo, tag) { // do not add a condition for the key we want to explore for if (tag.key === withKey) { return memo; } memo.push(renderTagCondition(tag, memo.length)); return memo; }, []); if (whereConditions.length > 0) { query += ' WHERE ' + whereConditions.join(' '); } } if (type === 'MEASUREMENTS') { query += ' LIMIT 100'; //Solve issue #2524 by limiting the number of measurements returned //LIMIT must be after WITH MEASUREMENT and WHERE clauses //This also could be used for TAG KEYS and TAG VALUES, if desired } return query; }; return InfluxQueryBuilder; });
public/app/plugins/datasource/influxdb/query_builder.js
1
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.996981680393219, 0.2561255395412445, 0.0001668940094532445, 0.00114090193528682, 0.41582077741622925 ]
{ "id": 5, "code_window": [ " if (measurement) {\n", " if (!measurement.match('^/.*/') && !measurement.match(/^merge\\(.*\\)/)) {\n", " measurement = '\"' + measurement+ '\"';\n", " }\n", " query += ' FROM ' + measurement;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (policy) {\n", " if (!policy.match('^/.*/') && !policy.match(/^merge\\(.*\\)/)) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 72 }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudwatch import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/protocol/query" ) // CloudWatch provides the API operation methods for making requests to // Amazon CloudWatch. See this package's package overview docs // for details on the service. // // CloudWatch methods are safe to use concurrently. It is not safe to // modify mutate any of the struct's properties though. type CloudWatch struct { *client.Client } // Used for custom client initialization logic var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) // Service information constants const ( ServiceName = "monitoring" // Service endpoint prefix API calls made to. EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. ) // New creates a new instance of the CloudWatch client with a session. // If additional configuration is needed for the client instance use the optional // aws.Config parameter to add your extra config. // // Example: // // Create a CloudWatch client from just a session. // svc := cloudwatch.New(mySession) // // // Create a CloudWatch client with additional configuration // svc := cloudwatch.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *CloudWatch { c := p.ClientConfig(EndpointsID, cfgs...) return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) } // newClient creates, initializes and returns a new service client instance. func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *CloudWatch { svc := &CloudWatch{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, APIVersion: "2010-08-01", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(query.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc } // newRequest creates a new request for a CloudWatch operation and runs any // custom request initialization. func (c *CloudWatch) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
vendor/github.com/aws/aws-sdk-go/service/cloudwatch/service.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.0003107061784248799, 0.00018208481196779758, 0.00016216574294958264, 0.0001670762139838189, 0.00004305482070776634 ]
{ "id": 5, "code_window": [ " if (measurement) {\n", " if (!measurement.match('^/.*/') && !measurement.match(/^merge\\(.*\\)/)) {\n", " measurement = '\"' + measurement+ '\"';\n", " }\n", " query += ' FROM ' + measurement;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (policy) {\n", " if (!policy.match('^/.*/') && !policy.match(/^merge\\(.*\\)/)) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 72 }
package tracing import "testing" func TestGroupSplit(t *testing.T) { tests := []struct { input string expected map[string]string }{ { input: "tag1:value1,tag2:value2", expected: map[string]string{ "tag1": "value1", "tag2": "value2", }, }, { input: "", expected: map[string]string{}, }, { input: "tag1", expected: map[string]string{}, }, } for _, test := range tests { tags := splitTagSettings(test.input) for k, v := range test.expected { value, exists := tags[k] if !exists || value != v { t.Errorf("tags does not match %v ", test) } } } }
pkg/tracing/tracing_test.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017517323431093246, 0.0001741320884320885, 0.0001737192942528054, 0.00017381791258230805, 6.053409720152558e-7 ]
{ "id": 5, "code_window": [ " if (measurement) {\n", " if (!measurement.match('^/.*/') && !measurement.match(/^merge\\(.*\\)/)) {\n", " measurement = '\"' + measurement+ '\"';\n", " }\n", " query += ' FROM ' + measurement;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (policy) {\n", " if (!policy.match('^/.*/') && !policy.match(/^merge\\(.*\\)/)) {\n", " policy = '\"' + policy + '\"';\n", " }\n", " measurement = policy + '.' + measurement;\n", " }\n" ], "file_path": "public/app/plugins/datasource/influxdb/query_builder.js", "type": "add", "edit_start_line_idx": 72 }
Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
vendor/golang.org/x/sys/LICENSE
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017289949755650014, 0.00016866682562977076, 0.0001611442567082122, 0.00017195673717651516, 0.000005333169156074291 ]
{ "id": 6, "code_window": [ " var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n", " it('should switch to regex operator in tag condition', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " tags: [{key: 'host', value: '/server.*/'}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it ('should select from policy correctly if policy is specified', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " policy: 'one_week',\n", " tags: [{key: 'app', value: 'email'},\n", " {key: 'host', value: 'server1'}]\n", " });\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"one_week\".\"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n" ], "file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts", "type": "add", "edit_start_line_idx": 75 }
define([ 'lodash' ], function (_) { 'use strict'; function InfluxQueryBuilder(target, database) { this.target = target; this.database = database; } function renderTagCondition (tag, index) { var str = ""; var operator = tag.operator; var value = tag.value; if (index > 0) { str = (tag.condition || 'AND') + ' '; } if (!operator) { if (/^\/.*\/$/.test(tag.value)) { operator = '=~'; } else { operator = '='; } } // quote value unless regex or number if (operator !== '=~' && operator !== '!~' && isNaN(+value)) { value = "'" + value + "'"; } return str + '"' + tag.key + '" ' + operator + ' ' + value; } var p = InfluxQueryBuilder.prototype; p.build = function() { return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery(); }; p.buildExploreQuery = function(type, withKey, withMeasurementFilter) { var query; var measurement; if (type === 'TAG_KEYS') { query = 'SHOW TAG KEYS'; measurement = this.target.measurement; } else if (type === 'TAG_VALUES') { query = 'SHOW TAG VALUES'; measurement = this.target.measurement; } else if (type === 'MEASUREMENTS') { query = 'SHOW MEASUREMENTS'; if (withMeasurementFilter) { query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/'; } } else if (type === 'FIELDS') { if (!this.target.measurement.match('^/.*/')) { return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"'; } else { return 'SHOW FIELD KEYS FROM ' + this.target.measurement; } } else if (type === 'RETENTION POLICIES') { query = 'SHOW RETENTION POLICIES on "' + this.database + '"'; return query; } if (measurement) { if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) { measurement = '"' + measurement+ '"'; } query += ' FROM ' + measurement; } if (withKey) { query += ' WITH KEY = "' + withKey + '"'; } if (this.target.tags && this.target.tags.length > 0) { var whereConditions = _.reduce(this.target.tags, function(memo, tag) { // do not add a condition for the key we want to explore for if (tag.key === withKey) { return memo; } memo.push(renderTagCondition(tag, memo.length)); return memo; }, []); if (whereConditions.length > 0) { query += ' WHERE ' + whereConditions.join(' '); } } if (type === 'MEASUREMENTS') { query += ' LIMIT 100'; //Solve issue #2524 by limiting the number of measurements returned //LIMIT must be after WITH MEASUREMENT and WHERE clauses //This also could be used for TAG KEYS and TAG VALUES, if desired } return query; }; return InfluxQueryBuilder; });
public/app/plugins/datasource/influxdb/query_builder.js
1
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.9645044803619385, 0.25691771507263184, 0.0001756846031639725, 0.0029294269625097513, 0.4026277959346771 ]
{ "id": 6, "code_window": [ " var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n", " it('should switch to regex operator in tag condition', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " tags: [{key: 'host', value: '/server.*/'}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it ('should select from policy correctly if policy is specified', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " policy: 'one_week',\n", " tags: [{key: 'app', value: 'email'},\n", " {key: 'host', value: 'server1'}]\n", " });\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"one_week\".\"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n" ], "file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts", "type": "add", "edit_start_line_idx": 75 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="70px" height="70px" viewBox="15 -15 70 70" xml:space="preserve"> <g> <path fill="#F79520" d="M41.39,43.607l1.908-1.91l3.677,3.678l-1.91,1.91L41.39,43.607z M21.635,23.795l1.91-1.91l3.677,3.678 l-1.91,1.91L21.635,23.795z M47.8-4.9l1.9-1.9c-1.3-1.2-2.8-2.2-4.3-3l-2,2C45-7,46.4-6.1,47.8-4.9z M35.7-9.5c2,0,4,0.3,5.8,1 l2.1-2.1c-1.9-0.8-3.8-1.3-5.9-1.5l-2.6,2.6H35.7z M17.7,8.6V8l-2.6,2.6c0.2,2,0.7,4,1.5,5.9l2.1-2.1C18,12.6,17.7,10.6,17.7,8.6z M23-4.2c2.6-2.6,5.8-4.3,9.4-5l3-3c-3.7,0.1-7.2,1.1-10.3,3L18-2.1C16.1,1,15.1,4.5,15,8.2l3-3C18.7,1.7,20.4-1.6,23-4.2z M19.4,16.2l-2,2c0.8,1.5,1.8,3,3,4.3l1.9-1.9C21.1,19.3,20.1,17.8,19.4,16.2z M36.433,38.6l1.91-1.908l3.676,3.677l-1.91,1.908 L36.433,38.6z M82.4,8.6c0,0.5,0,0.9-0.1,1.4L85,7.3c-0.1-2.1-0.6-4.1-1.3-6l-2.1,2.1C82.1,5,82.4,6.8,82.4,8.6z M85,9.8L81.8,13 c-0.8,3.1-2.4,6-4.7,8.3L50,48.4l-1.8-1.8l-1.9,1.9l3.7,3.7l29.9-29.9C83,18.8,84.7,14.4,85,9.8z M26.59,28.8l1.91-1.908 l3.677,3.677l-1.91,1.908L26.59,28.8z M31.477,33.737l1.91-1.91l3.676,3.677l-1.91,1.91L31.477,33.737z M70.9-8.2l2-2 c-1.8-0.8-3.7-1.4-5.7-1.7l-2.5,2.5C66.9-9.4,69-9,70.9-8.2z M50-2.7l1.5-1.5c2.9-2.9,6.6-4.7,10.6-5.2l2.8-2.8h-0.6 c-3,0-5.8,0.6-8.5,1.8l-6.7,6.7L50-2.7z M76.9-4.4l1.9-1.9c-1.3-1.2-2.7-2.3-4.2-3.2l-2,2C74.2-6.6,75.6-5.6,76.9-4.4z M80.9,1.5 l2-2c-0.8-1.6-1.7-3.1-2.9-4.4L78.1-3C79.3-1.7,80.2-0.1,80.9,1.5z M26.8-0.4c-2.4,2.4-3.7,5.6-3.7,9c0,0.5,0,0.9,0.1,1.3l14-14 c-0.4,0-0.9-0.1-1.3-0.1C32.4-4.1,29.2-2.8,26.8-0.4z M23.5,12c0.5,1.7,1.4,3.4,2.6,4.8L44-1.1c-1.4-1.2-3-2.1-4.8-2.6L23.5,12z M73.3,17.6c2.4-2.4,3.7-5.6,3.7-9V8L47.1,37.9l2.9,2.9C50,40.8,73.3,17.6,73.3,17.6z M37.2,28l3.7,3.7L73.1-0.5 c-1.3-1.3-2.9-2.2-4.5-2.8L37.2,28z M57.4-2L32.3,23.1l3.7,3.7L66.6-3.8C65.9-3.9,65.1-4,64.3-4C61.8-4.1,59.4-3.4,57.4-2z M42.1,32.9l3.7,3.7L76.6,5.8c-0.4-1.8-1.2-3.5-2.4-5L42.1,32.9z M46.2,1.1l-0.9-0.9l-18,17.9l3.7,3.7l17.9-18L48.1,3"/> </g> </svg>
public/img/warn.svg
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017227233911398798, 0.00017012136231642216, 0.00016762972518336028, 0.00017046203720383346, 0.0000019105859792034607 ]
{ "id": 6, "code_window": [ " var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n", " it('should switch to regex operator in tag condition', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " tags: [{key: 'host', value: '/server.*/'}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it ('should select from policy correctly if policy is specified', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " policy: 'one_week',\n", " tags: [{key: 'app', value: 'email'},\n", " {key: 'host', value: 'server1'}]\n", " });\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"one_week\".\"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n" ], "file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts", "type": "add", "edit_start_line_idx": 75 }
.dashlist-section-header { margin-bottom: $spacer; color: $text-color-weak; } .dashlist-section { margin-bottom: $spacer; } .dashlist-link { display: block; margin: 5px; padding: 7px; background-color: $tight-form-bg; .fa { float: right; padding-top: 3px; } .fa-star { color: $orange; } &:hover { background-color: $tight-form-func-bg; } }
public/sass/components/_panel_dashlist.scss
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.00017284393834415823, 0.0001712354860501364, 0.00017018285871017724, 0.00017067964654415846, 0.00000115529223876365 ]
{ "id": 6, "code_window": [ " var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n", " it('should switch to regex operator in tag condition', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " tags: [{key: 'host', value: '/server.*/'}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it ('should select from policy correctly if policy is specified', function() {\n", " var builder = new InfluxQueryBuilder({\n", " measurement: 'cpu',\n", " policy: 'one_week',\n", " tags: [{key: 'app', value: 'email'},\n", " {key: 'host', value: 'server1'}]\n", " });\n", " var query = builder.buildExploreQuery('TAG_VALUES', 'app');\n", " expect(query).to.be('SHOW TAG VALUES FROM \"one_week\".\"cpu\" WITH KEY = \"app\" WHERE \"host\" = \\'server1\\'');\n", " });\n", "\n" ], "file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts", "type": "add", "edit_start_line_idx": 75 }
package assertions import ( "errors" "fmt" "math" "reflect" "strings" "github.com/smartystreets/assertions/internal/oglematchers" "github.com/smartystreets/assertions/internal/go-render/render" ) // default acceptable delta for ShouldAlmostEqual const defaultDelta = 0.0000000001 // ShouldEqual receives exactly two parameters and does an equality check. func ShouldEqual(actual interface{}, expected ...interface{}) string { if message := need(1, expected); message != success { return message } return shouldEqual(actual, expected[0]) } func shouldEqual(actual, expected interface{}) (message string) { defer func() { if r := recover(); r != nil { message = serializer.serialize(expected, actual, fmt.Sprintf(shouldHaveBeenEqual, expected, actual)) return } }() if matchError := oglematchers.Equals(expected).Matches(actual); matchError != nil { expectedSyntax := fmt.Sprintf("%v", expected) actualSyntax := fmt.Sprintf("%v", actual) if expectedSyntax == actualSyntax && reflect.TypeOf(expected) != reflect.TypeOf(actual) { message = fmt.Sprintf(shouldHaveBeenEqualTypeMismatch, expected, expected, actual, actual) } else { message = fmt.Sprintf(shouldHaveBeenEqual, expected, actual) } message = serializer.serialize(expected, actual, message) return } return success } // ShouldNotEqual receives exactly two parameters and does an inequality check. func ShouldNotEqual(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } else if ShouldEqual(actual, expected[0]) == success { return fmt.Sprintf(shouldNotHaveBeenEqual, actual, expected[0]) } return success } // ShouldAlmostEqual makes sure that two parameters are close enough to being equal. // The acceptable delta may be specified with a third argument, // or a very small default delta will be used. func ShouldAlmostEqual(actual interface{}, expected ...interface{}) string { actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) if err != "" { return err } if math.Abs(actualFloat-expectedFloat) <= deltaFloat { return success } else { return fmt.Sprintf(shouldHaveBeenAlmostEqual, actualFloat, expectedFloat) } } // ShouldNotAlmostEqual is the inverse of ShouldAlmostEqual func ShouldNotAlmostEqual(actual interface{}, expected ...interface{}) string { actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) if err != "" { return err } if math.Abs(actualFloat-expectedFloat) > deltaFloat { return success } else { return fmt.Sprintf(shouldHaveNotBeenAlmostEqual, actualFloat, expectedFloat) } } func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64, float64, float64, string) { deltaFloat := 0.0000000001 if len(expected) == 0 { return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided neither)" } else if len(expected) == 2 { delta, err := getFloat(expected[1]) if err != nil { return 0.0, 0.0, 0.0, "delta must be a numerical type" } deltaFloat = delta } else if len(expected) > 2 { return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided more values)" } actualFloat, err := getFloat(actual) if err != nil { return 0.0, 0.0, 0.0, err.Error() } expectedFloat, err := getFloat(expected[0]) if err != nil { return 0.0, 0.0, 0.0, err.Error() } return actualFloat, expectedFloat, deltaFloat, "" } // returns the float value of any real number, or error if it is not a numerical type func getFloat(num interface{}) (float64, error) { numValue := reflect.ValueOf(num) numKind := numValue.Kind() if numKind == reflect.Int || numKind == reflect.Int8 || numKind == reflect.Int16 || numKind == reflect.Int32 || numKind == reflect.Int64 { return float64(numValue.Int()), nil } else if numKind == reflect.Uint || numKind == reflect.Uint8 || numKind == reflect.Uint16 || numKind == reflect.Uint32 || numKind == reflect.Uint64 { return float64(numValue.Uint()), nil } else if numKind == reflect.Float32 || numKind == reflect.Float64 { return numValue.Float(), nil } else { return 0.0, errors.New("must be a numerical type, but was " + numKind.String()) } } // ShouldResemble receives exactly two parameters and does a deep equal check (see reflect.DeepEqual) func ShouldResemble(actual interface{}, expected ...interface{}) string { if message := need(1, expected); message != success { return message } if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil { return serializer.serializeDetailed(expected[0], actual, fmt.Sprintf(shouldHaveResembled, render.Render(expected[0]), render.Render(actual))) } return success } // ShouldNotResemble receives exactly two parameters and does an inverse deep equal check (see reflect.DeepEqual) func ShouldNotResemble(actual interface{}, expected ...interface{}) string { if message := need(1, expected); message != success { return message } else if ShouldResemble(actual, expected[0]) == success { return fmt.Sprintf(shouldNotHaveResembled, render.Render(actual), render.Render(expected[0])) } return success } // ShouldPointTo receives exactly two parameters and checks to see that they point to the same address. func ShouldPointTo(actual interface{}, expected ...interface{}) string { if message := need(1, expected); message != success { return message } return shouldPointTo(actual, expected[0]) } func shouldPointTo(actual, expected interface{}) string { actualValue := reflect.ValueOf(actual) expectedValue := reflect.ValueOf(expected) if ShouldNotBeNil(actual) != success { return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "nil") } else if ShouldNotBeNil(expected) != success { return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "nil") } else if actualValue.Kind() != reflect.Ptr { return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "not") } else if expectedValue.Kind() != reflect.Ptr { return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "not") } else if ShouldEqual(actualValue.Pointer(), expectedValue.Pointer()) != success { actualAddress := reflect.ValueOf(actual).Pointer() expectedAddress := reflect.ValueOf(expected).Pointer() return serializer.serialize(expectedAddress, actualAddress, fmt.Sprintf(shouldHavePointedTo, actual, actualAddress, expected, expectedAddress)) } return success } // ShouldNotPointTo receives exactly two parameters and checks to see that they point to different addresess. func ShouldNotPointTo(actual interface{}, expected ...interface{}) string { if message := need(1, expected); message != success { return message } compare := ShouldPointTo(actual, expected[0]) if strings.HasPrefix(compare, shouldBePointers) { return compare } else if compare == success { return fmt.Sprintf(shouldNotHavePointedTo, actual, expected[0], reflect.ValueOf(actual).Pointer()) } return success } // ShouldBeNil receives a single parameter and ensures that it is nil. func ShouldBeNil(actual interface{}, expected ...interface{}) string { if fail := need(0, expected); fail != success { return fail } else if actual == nil { return success } else if interfaceHasNilValue(actual) { return success } return fmt.Sprintf(shouldHaveBeenNil, actual) } func interfaceHasNilValue(actual interface{}) bool { value := reflect.ValueOf(actual) kind := value.Kind() nilable := kind == reflect.Slice || kind == reflect.Chan || kind == reflect.Func || kind == reflect.Ptr || kind == reflect.Map // Careful: reflect.Value.IsNil() will panic unless it's an interface, chan, map, func, slice, or ptr // Reference: http://golang.org/pkg/reflect/#Value.IsNil return nilable && value.IsNil() } // ShouldNotBeNil receives a single parameter and ensures that it is not nil. func ShouldNotBeNil(actual interface{}, expected ...interface{}) string { if fail := need(0, expected); fail != success { return fail } else if ShouldBeNil(actual) == success { return fmt.Sprintf(shouldNotHaveBeenNil, actual) } return success } // ShouldBeTrue receives a single parameter and ensures that it is true. func ShouldBeTrue(actual interface{}, expected ...interface{}) string { if fail := need(0, expected); fail != success { return fail } else if actual != true { return fmt.Sprintf(shouldHaveBeenTrue, actual) } return success } // ShouldBeFalse receives a single parameter and ensures that it is false. func ShouldBeFalse(actual interface{}, expected ...interface{}) string { if fail := need(0, expected); fail != success { return fail } else if actual != false { return fmt.Sprintf(shouldHaveBeenFalse, actual) } return success } // ShouldBeZeroValue receives a single parameter and ensures that it is // the Go equivalent of the default value, or "zero" value. func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string { if fail := need(0, expected); fail != success { return fail } zeroVal := reflect.Zero(reflect.TypeOf(actual)).Interface() if !reflect.DeepEqual(zeroVal, actual) { return serializer.serialize(zeroVal, actual, fmt.Sprintf(shouldHaveBeenZeroValue, actual)) } return success }
vendor/github.com/smartystreets/assertions/equality.go
0
https://github.com/grafana/grafana/commit/209f2debe6bdcdb063a5634e6b1b682863dc47f7
[ 0.0001769405644154176, 0.0001715283578960225, 0.0001627322199055925, 0.00017270127136725932, 0.0000036178648770146538 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n", "import { Options } from 'html-minifier';\n", "import { Middleware } from 'koa';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { Options as HtmlMinifierOptions } from 'html-minifier';\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 6 }
// Type definitions for koa-html-minifier 1.0 // Project: https://github.com/koajs/html-minifier // Definitions by: Romain Faust <https://github.com/romain-faust> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Options } from 'html-minifier'; import { Middleware } from 'koa'; declare function minifier(options?: Options): Middleware; declare namespace minifier {} export = minifier;
types/koa-html-minifier/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.08746066689491272, 0.04441084340214729, 0.0013610214227810502, 0.04441084340214729, 0.04304982349276543 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n", "import { Options } from 'html-minifier';\n", "import { Middleware } from 'koa';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { Options as HtmlMinifierOptions } from 'html-minifier';\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 6 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class IoIosPaw extends React.Component<IconBaseProps> { }
types/react-icons/io/ios-paw.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017219106666743755, 0.00017219106666743755, 0.00017219106666743755, 0.00017219106666743755, 0 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n", "import { Options } from 'html-minifier';\n", "import { Middleware } from 'koa';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { Options as HtmlMinifierOptions } from 'html-minifier';\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 6 }
{ "extends": "dtslint/dt.json" }
types/dargs/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017247284995391965, 0.00017247284995391965, 0.00017247284995391965, 0.00017247284995391965, 0 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n", "import { Options } from 'html-minifier';\n", "import { Middleware } from 'koa';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "import { Options as HtmlMinifierOptions } from 'html-minifier';\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 6 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "user-home-tests.ts" ] }
types/user-home/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017286369984503835, 0.00017026846762746572, 0.00016858955495990813, 0.00016935213352553546, 0.000001861329792518518 ]
{ "id": 1, "code_window": [ "import { Middleware } from 'koa';\n", "\n", "declare function minifier(options?: Options): Middleware;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "declare function minifier(options?: minifier.Options): Middleware;\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 9 }
import Koa = require('koa'); import KoaHtmlMinifier = require('koa-html-minifier'); const app = new Koa(); app.use(KoaHtmlMinifier()); app.use(KoaHtmlMinifier({ collapseWhitespace: true }));
types/koa-html-minifier/koa-html-minifier-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.9887369275093079, 0.9887369275093079, 0.9887369275093079, 0.9887369275093079, 0 ]
{ "id": 1, "code_window": [ "import { Middleware } from 'koa';\n", "\n", "declare function minifier(options?: Options): Middleware;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "declare function minifier(options?: minifier.Options): Middleware;\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 9 }
import Koa = require('koa'); import session = require('koa-session'); import * as ContextSession from "koa-session/lib/context"; import { encode, decode, hash, } from "koa-session/lib/util"; encode({ a: "b" }); decode("123"); hash("abc"); const app = new Koa(); app.use(session({ valid: (ctx, sess) => { const { session: s } = ctx; if (s) { s.sess = "validated"; s.save(); return true; } return false; }, store: { get: async (key) => { return "abc"; }, set: (key, val) => { console.log(key, val); }, destroy: (key) => { console.log(key); }, }, }, app)); app.use((ctx, next) => { // reset the session ctx.session = null; return next(); }); app.listen(3000);
types/koa-session/koa-session-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017140850832220167, 0.00016901353956200182, 0.00016659620450809598, 0.00016956072067841887, 0.000001975681925614481 ]
{ "id": 1, "code_window": [ "import { Middleware } from 'koa';\n", "\n", "declare function minifier(options?: Options): Middleware;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "declare function minifier(options?: minifier.Options): Middleware;\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 9 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts" ] }
types/lodash.flowright/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017726275837048888, 0.00017119456606451422, 0.00016776852135080844, 0.00016855243302416056, 0.000004302774414099986 ]
{ "id": 1, "code_window": [ "import { Middleware } from 'koa';\n", "\n", "declare function minifier(options?: Options): Middleware;\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "declare function minifier(options?: minifier.Options): Middleware;\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 9 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class FaModx extends React.Component<IconBaseProps> { }
types/react-icons/fa/modx.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017200628644786775, 0.00017200628644786775, 0.00017200628644786775, 0.00017200628644786775, 0 ]
{ "id": 2, "code_window": [ "\n", "declare namespace minifier {}\n", "\n", "export = minifier;" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "declare namespace minifier {\n", " type Options = HtmlMinifierOptions;\n", "}\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
// Type definitions for koa-html-minifier 1.0 // Project: https://github.com/koajs/html-minifier // Definitions by: Romain Faust <https://github.com/romain-faust> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Options } from 'html-minifier'; import { Middleware } from 'koa'; declare function minifier(options?: Options): Middleware; declare namespace minifier {} export = minifier;
types/koa-html-minifier/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.9973902106285095, 0.5900078415870667, 0.18262551724910736, 0.5900078415870667, 0.4073823392391205 ]
{ "id": 2, "code_window": [ "\n", "declare namespace minifier {}\n", "\n", "export = minifier;" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "declare namespace minifier {\n", " type Options = HtmlMinifierOptions;\n", "}\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts" ] }
types/lodash.every/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.0001775706623448059, 0.00017197125998791307, 0.00016907299868762493, 0.00016927010437939316, 0.0000039601964090252295 ]
{ "id": 2, "code_window": [ "\n", "declare namespace minifier {}\n", "\n", "export = minifier;" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "declare namespace minifier {\n", " type Options = HtmlMinifierOptions;\n", "}\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
// Type definitions for uuid-js 0.7 // Project: https://github.com/pnegri/uuid-js // Definitions by: Mohamed Hegazy <https://github.com/mhegazy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = uuid; declare class uuid { equals(uuid: uuid): boolean; fromParts(timeLow: any, timeMid: any, timeHiAndVersion: any, clockSeqHiAndReserved: any, clockSeqLow: any, node: any): uuid; toBytes(): any[]; toString(): string; toURN(): string; static create(version?: number): uuid; static firstFromTime(time: number): uuid; static fromBinary(binary: any): uuid; static fromBytes(ints: number[]): uuid; static fromTime(time: number, last?: boolean): uuid; static fromURN(strId: any): uuid; static getTimeFieldValues(time: any): any; static lastFromTime(time: any): uuid; static limitUI04: number; static limitUI06: number; static limitUI08: number; static limitUI12: number; static limitUI14: number; static limitUI16: number; static limitUI32: number; static limitUI40: number; static limitUI48: number; static maxFromBits(bits: number): uuid; static newTS(): uuid; static paddedString(string: any, length: any, z: any): uuid; static randomUI04(): uuid; static randomUI06(): uuid; static randomUI08(): uuid; static randomUI12(): uuid; static randomUI14(): uuid; static randomUI16(): uuid; static randomUI32(): uuid; static randomUI40(): uuid; static randomUI48(): uuid; }
types/uuid-js/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.007025240920484066, 0.0015425208257511258, 0.00016804822371341288, 0.0001735495898174122, 0.0027413612697273493 ]
{ "id": 2, "code_window": [ "\n", "declare namespace minifier {}\n", "\n", "export = minifier;" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "declare namespace minifier {\n", " type Options = HtmlMinifierOptions;\n", "}\n" ], "file_path": "types/koa-html-minifier/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
{ "extends": "dtslint/dt.json" }
types/cordova-plugin-canvascamera/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017208830104209483, 0.00017208830104209483, 0.00017208830104209483, 0.00017208830104209483, 0 ]
{ "id": 3, "code_window": [ "import Koa = require('koa');\n", "import KoaHtmlMinifier = require('koa-html-minifier');\n", "\n", "const app = new Koa();\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "import koaHtmlMinifier = require('koa-html-minifier');\n" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 1 }
import Koa = require('koa'); import KoaHtmlMinifier = require('koa-html-minifier'); const app = new Koa(); app.use(KoaHtmlMinifier()); app.use(KoaHtmlMinifier({ collapseWhitespace: true }));
types/koa-html-minifier/koa-html-minifier-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.9981387853622437, 0.9981387853622437, 0.9981387853622437, 0.9981387853622437, 0 ]
{ "id": 3, "code_window": [ "import Koa = require('koa');\n", "import KoaHtmlMinifier = require('koa-html-minifier');\n", "\n", "const app = new Koa();\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "import koaHtmlMinifier = require('koa-html-minifier');\n" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 1 }
{ "extends": "dtslint/dt.json", "rules": { "unified-signatures": false } }
types/d3-time/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.0001743736647767946, 0.0001743736647767946, 0.0001743736647767946, 0.0001743736647767946, 0 ]
{ "id": 3, "code_window": [ "import Koa = require('koa');\n", "import KoaHtmlMinifier = require('koa-html-minifier');\n", "\n", "const app = new Koa();\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "import koaHtmlMinifier = require('koa-html-minifier');\n" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 1 }
{ "extends": "dtslint/dt.json", "rules": { "no-empty-interface": false, "unified-signatures": false } }
types/semantic-ui-popup/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.0001730588119244203, 0.0001730588119244203, 0.0001730588119244203, 0.0001730588119244203, 0 ]
{ "id": 3, "code_window": [ "import Koa = require('koa');\n", "import KoaHtmlMinifier = require('koa-html-minifier');\n", "\n", "const app = new Koa();\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "import koaHtmlMinifier = require('koa-html-minifier');\n" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 1 }
import AutolinkerCJS = require('autolinker'); () => { let linkedText1 = Autolinker.link( "Check out google.com" ); new Autolinker(); let autolinker1 = new Autolinker( { className: "myLink" } ); let textToAutoLink = 'text'; let linkedText2 = autolinker1.link( textToAutoLink ); let linkedText3 = Autolinker.link( "Check out google.com", { className: "myLink" } ); let linkedText4 = Autolinker.link( "Check out google.com", { newWindow: false } ); let linkedText5 = Autolinker.link( "http://www.yahoo.com/some/long/path/to/a/file", { truncate: 25, newWindow: false } ); let myTextEl = document.getElementById( 'text' ); myTextEl.innerHTML = Autolinker.link( myTextEl.innerHTML ); let autolinker2 = new Autolinker( { newWindow: false, truncate: 25 } ); autolinker2.link( "Check out http://www.yahoo.com/some/long/path/to/a/file" ); // Produces: "Check out <a href="http://www.yahoo.com/some/long/path/to/a/file">yahoo.com/some/long/pat..</a>" autolinker2.link( "Go to www.google.com" ); // Produces: "Go to <a href="http://www.google.com">google.com</a>" let input = "..."; // string with URLs, Email Addresses, Twitter Handles, and Hashtags let linkedText6 = Autolinker.link( input, { replaceFn : function( autolinker, match ) { console.log( "href = ", match.getAnchorHref() ); console.log( "text = ", match.getAnchorText() ); switch( match.getType() ) { case 'url' : console.log( "url: ", match.getUrl() ); if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) { let tag = autolinker.getTagBuilder().build( match ); // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes tag.setAttr( 'rel', 'nofollow' ); tag.addClass( 'external-link' ); return tag; } else { return true; // let Autolinker perform its normal anchor tag replacement } case 'email' : let email = match.getEmail(); console.log( "email: ", email ); if( email === "[email protected]" ) { return false; // don't auto-link this particular email address; leave as-is } else { return; // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`) } case 'phone' : let phoneNumber = match.getPhoneNumber(); console.log( phoneNumber ); return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>'; case 'twitter' : let twitterHandle = match.getTwitterHandle(); console.log( twitterHandle ); return '<a href="http://newplace.to.link.twitter.handles.to/">' + twitterHandle + '</a>'; case 'hashtag' : let hashtag = match.getHashtag(); console.log( hashtag ); return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>'; } } } ); } () => { let linkedText1 = AutolinkerCJS.link( "Check out google.com" ); new AutolinkerCJS(); let autolinker1 = new AutolinkerCJS( { className: "myLink" } ); let textToAutoLink = 'text'; let linkedText2 = autolinker1.link( textToAutoLink ); let linkedText3 = AutolinkerCJS.link( "Check out google.com", { className: "myLink" } ); let linkedText4 = AutolinkerCJS.link( "Check out google.com", { newWindow: false } ); let linkedText5 = AutolinkerCJS.link( "http://www.yahoo.com/some/long/path/to/a/file", { truncate: 25, newWindow: false } ); let myTextEl = document.getElementById( 'text' ); myTextEl.innerHTML = AutolinkerCJS.link( myTextEl.innerHTML ); let autolinker2 = new AutolinkerCJS( { newWindow: false, truncate: 25 } ); autolinker2.link( "Check out http://www.yahoo.com/some/long/path/to/a/file" ); // Produces: "Check out <a href="http://www.yahoo.com/some/long/path/to/a/file">yahoo.com/some/long/pat..</a>" autolinker2.link( "Go to www.google.com" ); // Produces: "Go to <a href="http://www.google.com">google.com</a>" let input = "..."; // string with URLs, Email Addresses, Twitter Handles, and Hashtags let linkedText6 = AutolinkerCJS.link( input, { replaceFn : function( autolinker, match ) { console.log( "href = ", match.getAnchorHref() ); console.log( "text = ", match.getAnchorText() ); switch( match.getType() ) { case 'url' : console.log( "url: ", match.getUrl() ); if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) { let tag = autolinker.getTagBuilder().build( match ); // returns an `AutolinkerCJS.HtmlTag` instance, which provides mutator methods for easy changes tag.setAttr( 'rel', 'nofollow' ); tag.addClass( 'external-link' ); return tag; } else { return true; // let AutolinkerCJS perform its normal anchor tag replacement } case 'email' : let email = match.getEmail(); console.log( "email: ", email ); if( email === "[email protected]" ) { return false; // don't auto-link this particular email address; leave as-is } else { return; // no return value will have AutolinkerCJS perform its normal anchor tag replacement (same as returning `true`) } case 'phone' : let phoneNumber = match.getPhoneNumber(); console.log( phoneNumber ); return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>'; case 'twitter' : let twitterHandle = match.getTwitterHandle(); console.log( twitterHandle ); return '<a href="http://newplace.to.link.twitter.handles.to/">' + twitterHandle + '</a>'; case 'hashtag' : let hashtag = match.getHashtag(); console.log( hashtag ); return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>'; } } } ); }
types/autolinker/autolinker-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.0001808029628591612, 0.00016941665671765804, 0.00016592878091614693, 0.0001685293100308627, 0.0000037968397919030394 ]
{ "id": 4, "code_window": [ "\n", "const app = new Koa();\n", "app.use(KoaHtmlMinifier());\n", "app.use(KoaHtmlMinifier({ collapseWhitespace: true }));\n" ], "labels": [ "keep", "keep", "replace", "replace" ], "after_edit": [ "app.use(koaHtmlMinifier());\n", "app.use(koaHtmlMinifier({ collapseWhitespace: true }));" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 4 }
import Koa = require('koa'); import KoaHtmlMinifier = require('koa-html-minifier'); const app = new Koa(); app.use(KoaHtmlMinifier()); app.use(KoaHtmlMinifier({ collapseWhitespace: true }));
types/koa-html-minifier/koa-html-minifier-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.9981505274772644, 0.9981505274772644, 0.9981505274772644, 0.9981505274772644, 0 ]
{ "id": 4, "code_window": [ "\n", "const app = new Koa();\n", "app.use(KoaHtmlMinifier());\n", "app.use(KoaHtmlMinifier({ collapseWhitespace: true }));\n" ], "labels": [ "keep", "keep", "replace", "replace" ], "after_edit": [ "app.use(koaHtmlMinifier());\n", "app.use(koaHtmlMinifier({ collapseWhitespace: true }));" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 4 }
import { nthArg } from "lodash"; export default nthArg;
types/lodash-es/nthArg.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.0001775955461198464, 0.0001775955461198464, 0.0001775955461198464, 0.0001775955461198464, 0 ]
{ "id": 4, "code_window": [ "\n", "const app = new Koa();\n", "app.use(KoaHtmlMinifier());\n", "app.use(KoaHtmlMinifier({ collapseWhitespace: true }));\n" ], "labels": [ "keep", "keep", "replace", "replace" ], "after_edit": [ "app.use(koaHtmlMinifier());\n", "app.use(koaHtmlMinifier({ collapseWhitespace: true }));" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 4 }
{ "private": true, "dependencies": { "@babel/types": "^7.0.0-beta.54" } }
types/babel__traverse/package.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017242220928892493, 0.00017242220928892493, 0.00017242220928892493, 0.00017242220928892493, 0 ]
{ "id": 4, "code_window": [ "\n", "const app = new Koa();\n", "app.use(KoaHtmlMinifier());\n", "app.use(KoaHtmlMinifier({ collapseWhitespace: true }));\n" ], "labels": [ "keep", "keep", "replace", "replace" ], "after_edit": [ "app.use(koaHtmlMinifier());\n", "app.use(koaHtmlMinifier({ collapseWhitespace: true }));" ], "file_path": "types/koa-html-minifier/koa-html-minifier-tests.ts", "type": "replace", "edit_start_line_idx": 4 }
import shift = require("stream-shift"); import { createReadStream, createWriteStream } from "fs"; const stream = createReadStream(__filename); const x: Buffer | string | null = shift(stream);
types/stream-shift/stream-shift-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ab16ad9748e9dd73e5860e6d6bbe05c1eadb1a2f
[ 0.00017496207146905363, 0.00017496207146905363, 0.00017496207146905363, 0.00017496207146905363, 0 ]
{ "id": 0, "code_window": [ "tests/cases/compiler/a.js(1,10): error TS8016: 'type assertion expressions' can only be used in a .ts file.\n", "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "tests/cases/compiler/a.js(1,27): error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
/// <reference path="fourslash.ts" /> // @allowNonTsExtensions: true // @Filename: a.js //// var v = <string>undefined; verify.getSemanticDiagnostics(`[ { "message": "'type assertion expressions' can only be used in a .ts file.", "start": 9, "length": 6, "category": "error", "code": 8016 } ]`);
tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts
1
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0003368227044120431, 0.00028492161072790623, 0.0002330205315956846, 0.00028492161072790623, 0.000051901082770200446 ]
{ "id": 0, "code_window": [ "tests/cases/compiler/a.js(1,10): error TS8016: 'type assertion expressions' can only be used in a .ts file.\n", "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "tests/cases/compiler/a.js(1,27): error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
class Foo { constructor(s: string); constructor(n: number); constructor(x: any) { } constructor(x: any) { } bar1() { /*WScript.Echo("bar1");*/ } bar2() { /*WScript.Echo("bar1");*/ } } var f1 = new Foo("hey"); var f2 = new Foo(0); var f3 = new Foo(f1); var f4 = new Foo([f1,f2,f3]); f1.bar1(); f1.bar2();
tests/cases/compiler/constructorOverloads1.ts
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00018457765690982342, 0.0001746361522236839, 0.00016703219444025308, 0.0001722986198728904, 0.0000073511391747160815 ]