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": 6, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"imageContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"image\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The docker image that will be used to create the container.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 153 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/peekViewWidget'; import * as dom from 'vs/base/browser/dom'; import { IMouseEvent } from 'vs/base/browser/mouseEvent'; import { ActionBar, IActionBarOptions } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { Color } from 'vs/base/common/color'; import { Emitter } from 'vs/base/common/event'; import * as objects from 'vs/base/common/objects'; import * as strings from 'vs/base/common/strings'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { EmbeddedCodeEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { IOptions, IStyles, ZoneWidget } from 'vs/editor/contrib/zoneWidget/zoneWidget'; import * as nls from 'vs/nls'; import { ContextKeyExpr, RawContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor, createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IDisposable } from 'vs/base/common/lifecycle'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { registerColor, contrastBorder, activeContrastBorder } from 'vs/platform/theme/common/colorRegistry'; export const IPeekViewService = createDecorator<IPeekViewService>('IPeekViewService'); export interface IPeekViewService { _serviceBrand: undefined; addExclusiveWidget(editor: ICodeEditor, widget: PeekViewWidget): void; } registerSingleton(IPeekViewService, class implements IPeekViewService { _serviceBrand: undefined; private readonly _widgets = new Map<ICodeEditor, { widget: PeekViewWidget, listener: IDisposable; }>(); addExclusiveWidget(editor: ICodeEditor, widget: PeekViewWidget): void { const existing = this._widgets.get(editor); if (existing) { existing.listener.dispose(); existing.widget.dispose(); } const remove = () => { const data = this._widgets.get(editor); if (data && data.widget === widget) { data.listener.dispose(); this._widgets.delete(editor); } }; this._widgets.set(editor, { widget, listener: widget.onDidClose(remove) }); } }); export namespace PeekContext { export const inPeekEditor = new RawContextKey<boolean>('inReferenceSearchEditor', true); export const notInPeekEditor: ContextKeyExpr = inPeekEditor.toNegated(); } class PeekContextController implements IEditorContribution { static readonly ID = 'editor.contrib.referenceController'; constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { if (editor instanceof EmbeddedCodeEditorWidget) { PeekContext.inPeekEditor.bindTo(contextKeyService); } } dispose(): void { } } registerEditorContribution(PeekContextController.ID, PeekContextController); export function getOuterEditor(accessor: ServicesAccessor): ICodeEditor | null { let editor = accessor.get(ICodeEditorService).getFocusedCodeEditor(); if (editor instanceof EmbeddedCodeEditorWidget) { return editor.getParentEditor(); } return editor; } export interface IPeekViewStyles extends IStyles { headerBackgroundColor?: Color; primaryHeadingColor?: Color; secondaryHeadingColor?: Color; } export type IPeekViewOptions = IOptions & IPeekViewStyles; const defaultOptions: IPeekViewOptions = { headerBackgroundColor: Color.white, primaryHeadingColor: Color.fromHex('#333333'), secondaryHeadingColor: Color.fromHex('#6c6c6cb3') }; export abstract class PeekViewWidget extends ZoneWidget { _serviceBrand: undefined; private readonly _onDidClose = new Emitter<PeekViewWidget>(); readonly onDidClose = this._onDidClose.event; protected _headElement?: HTMLDivElement; protected _primaryHeading?: HTMLElement; protected _secondaryHeading?: HTMLElement; protected _metaHeading?: HTMLElement; protected _actionbarWidget?: ActionBar; protected _bodyElement?: HTMLDivElement; constructor(editor: ICodeEditor, options: IPeekViewOptions = {}) { super(editor, options); objects.mixin(this.options, defaultOptions, false); } dispose(): void { super.dispose(); this._onDidClose.fire(this); } style(styles: IPeekViewStyles): void { let options = <IPeekViewOptions>this.options; if (styles.headerBackgroundColor) { options.headerBackgroundColor = styles.headerBackgroundColor; } if (styles.primaryHeadingColor) { options.primaryHeadingColor = styles.primaryHeadingColor; } if (styles.secondaryHeadingColor) { options.secondaryHeadingColor = styles.secondaryHeadingColor; } super.style(styles); } protected _applyStyles(): void { super._applyStyles(); let options = <IPeekViewOptions>this.options; if (this._headElement && options.headerBackgroundColor) { this._headElement.style.backgroundColor = options.headerBackgroundColor.toString(); } if (this._primaryHeading && options.primaryHeadingColor) { this._primaryHeading.style.color = options.primaryHeadingColor.toString(); } if (this._secondaryHeading && options.secondaryHeadingColor) { this._secondaryHeading.style.color = options.secondaryHeadingColor.toString(); } if (this._bodyElement && options.frameColor) { this._bodyElement.style.borderColor = options.frameColor.toString(); } } protected _fillContainer(container: HTMLElement): void { this.setCssClass('peekview-widget'); this._headElement = dom.$<HTMLDivElement>('.head'); this._bodyElement = dom.$<HTMLDivElement>('.body'); this._fillHead(this._headElement); this._fillBody(this._bodyElement); container.appendChild(this._headElement); container.appendChild(this._bodyElement); } protected _fillHead(container: HTMLElement): void { const titleElement = dom.$('.peekview-title'); dom.append(this._headElement!, titleElement); dom.addStandardDisposableListener(titleElement, 'click', event => this._onTitleClick(event)); this._fillTitleIcon(titleElement); this._primaryHeading = dom.$('span.filename'); this._secondaryHeading = dom.$('span.dirname'); this._metaHeading = dom.$('span.meta'); dom.append(titleElement, this._primaryHeading, this._secondaryHeading, this._metaHeading); const actionsContainer = dom.$('.peekview-actions'); dom.append(this._headElement!, actionsContainer); const actionBarOptions = this._getActionBarOptions(); this._actionbarWidget = new ActionBar(actionsContainer, actionBarOptions); this._disposables.add(this._actionbarWidget); this._actionbarWidget.push(new Action('peekview.close', nls.localize('label.close', "Close"), 'codicon-close', true, () => { this.dispose(); return Promise.resolve(); }), { label: false, icon: true }); } protected _fillTitleIcon(container: HTMLElement): void { } protected _getActionBarOptions(): IActionBarOptions { return {}; } protected _onTitleClick(event: IMouseEvent): void { // implement me } setTitle(primaryHeading: string, secondaryHeading?: string): void { if (this._primaryHeading && this._secondaryHeading) { this._primaryHeading.innerHTML = strings.escape(primaryHeading); this._primaryHeading.setAttribute('aria-label', primaryHeading); if (secondaryHeading) { this._secondaryHeading.innerHTML = strings.escape(secondaryHeading); } else { dom.clearNode(this._secondaryHeading); } } } setMetaTitle(value: string): void { if (this._metaHeading) { if (value) { this._metaHeading.innerHTML = strings.escape(value); dom.show(this._metaHeading); } else { dom.hide(this._metaHeading); } } } protected abstract _fillBody(container: HTMLElement): void; protected _doLayout(heightInPixel: number, widthInPixel: number): void { if (!this._isShowing && heightInPixel < 0) { // Looks like the view zone got folded away! this.dispose(); return; } const headHeight = Math.ceil(this.editor.getOption(EditorOption.lineHeight) * 1.2); const bodyHeight = Math.round(heightInPixel - (headHeight + 2 /* the border-top/bottom width*/)); this._doLayoutHead(headHeight, widthInPixel); this._doLayoutBody(bodyHeight, widthInPixel); } protected _doLayoutHead(heightInPixel: number, widthInPixel: number): void { if (this._headElement) { this._headElement.style.height = `${heightInPixel}px`; this._headElement.style.lineHeight = this._headElement.style.height; } } protected _doLayoutBody(heightInPixel: number, widthInPixel: number): void { if (this._bodyElement) { this._bodyElement.style.height = `${heightInPixel}px`; } } } export const peekViewTitleBackground = registerColor('peekViewTitle.background', { dark: '#1E1E1E', light: '#FFFFFF', hc: '#0C141F' }, nls.localize('peekViewTitleBackground', 'Background color of the peek view title area.')); export const peekViewTitleForeground = registerColor('peekViewTitleLabel.foreground', { dark: '#FFFFFF', light: '#333333', hc: '#FFFFFF' }, nls.localize('peekViewTitleForeground', 'Color of the peek view title.')); export const peekViewTitleInfoForeground = registerColor('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#616161e6', hc: '#FFFFFF99' }, nls.localize('peekViewTitleInfoForeground', 'Color of the peek view title info.')); export const peekViewBorder = registerColor('peekView.border', { dark: '#007acc', light: '#007acc', hc: contrastBorder }, nls.localize('peekViewBorder', 'Color of the peek view borders and arrow.')); export const peekViewResultsBackground = registerColor('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hc: Color.black }, nls.localize('peekViewResultsBackground', 'Background color of the peek view result list.')); export const peekViewResultsMatchForeground = registerColor('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hc: Color.white }, nls.localize('peekViewResultsMatchForeground', 'Foreground color for line nodes in the peek view result list.')); export const peekViewResultsFileForeground = registerColor('peekViewResult.fileForeground', { dark: Color.white, light: '#1E1E1E', hc: Color.white }, nls.localize('peekViewResultsFileForeground', 'Foreground color for file nodes in the peek view result list.')); export const peekViewResultsSelectionBackground = registerColor('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hc: null }, nls.localize('peekViewResultsSelectionBackground', 'Background color of the selected entry in the peek view result list.')); export const peekViewResultsSelectionForeground = registerColor('peekViewResult.selectionForeground', { dark: Color.white, light: '#6C6C6C', hc: Color.white }, nls.localize('peekViewResultsSelectionForeground', 'Foreground color of the selected entry in the peek view result list.')); export const peekViewEditorBackground = registerColor('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hc: Color.black }, nls.localize('peekViewEditorBackground', 'Background color of the peek view editor.')); export const peekViewEditorGutterBackground = registerColor('peekViewEditorGutter.background', { dark: peekViewEditorBackground, light: peekViewEditorBackground, hc: peekViewEditorBackground }, nls.localize('peekViewEditorGutterBackground', 'Background color of the gutter in the peek view editor.')); export const peekViewResultsMatchHighlight = registerColor('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hc: null }, nls.localize('peekViewResultsMatchHighlight', 'Match highlight color in the peek view result list.')); export const peekViewEditorMatchHighlight = registerColor('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hc: null }, nls.localize('peekViewEditorMatchHighlight', 'Match highlight color in the peek view editor.')); export const peekViewEditorMatchHighlightBorder = registerColor('peekViewEditor.matchHighlightBorder', { dark: null, light: null, hc: activeContrastBorder }, nls.localize('peekViewEditorMatchHighlightBorder', 'Match highlight border in the peek view editor.'));
src/vs/editor/contrib/peekView/peekView.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.000410153967095539, 0.0001867167593445629, 0.0001620162947801873, 0.0001697456173133105, 0.00005219117156229913 ]
{ "id": 6, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"imageContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"image\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The docker image that will be used to create the container.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 153 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { name: '00000415', id: '', text: 'Polish (Programmers)' }, secondaryLayouts: [], mapping: { Sleep: [], WakeUp: [], KeyA: ['a', 'A', 'ą', 'Ą', 0, 'VK_A'], KeyB: ['b', 'B', '', '', 0, 'VK_B'], KeyC: ['c', 'C', 'ć', 'Ć', 0, 'VK_C'], KeyD: ['d', 'D', '', '', 0, 'VK_D'], KeyE: ['e', 'E', 'ę', 'Ę', 0, 'VK_E'], KeyF: ['f', 'F', '', '', 0, 'VK_F'], KeyG: ['g', 'G', '', '', 0, 'VK_G'], KeyH: ['h', 'H', '', '', 0, 'VK_H'], KeyI: ['i', 'I', '', '', 0, 'VK_I'], KeyJ: ['j', 'J', '', '', 0, 'VK_J'], KeyK: ['k', 'K', '', '', 0, 'VK_K'], KeyL: ['l', 'L', 'ł', 'Ł', 0, 'VK_L'], KeyM: ['m', 'M', '', '', 0, 'VK_M'], KeyN: ['n', 'N', 'ń', 'Ń', 0, 'VK_N'], KeyO: ['o', 'O', 'ó', 'Ó', 0, 'VK_O'], KeyP: ['p', 'P', '', '', 0, 'VK_P'], KeyQ: ['q', 'Q', '', '', 0, 'VK_Q'], KeyR: ['r', 'R', '', '', 0, 'VK_R'], KeyS: ['s', 'S', 'ś', 'Ś', 0, 'VK_S'], KeyT: ['t', 'T', '', '', 0, 'VK_T'], KeyU: ['u', 'U', '€', '', 0, 'VK_U'], KeyV: ['v', 'V', '', '', 0, 'VK_V'], KeyW: ['w', 'W', '', '', 0, 'VK_W'], KeyX: ['x', 'X', 'ź', 'Ź', 0, 'VK_X'], KeyY: ['y', 'Y', '', '', 0, 'VK_Y'], KeyZ: ['z', 'Z', 'ż', 'Ż', 0, 'VK_Z'], Digit1: ['1', '!', '', '', 0, 'VK_1'], Digit2: ['2', '@', '', '', 0, 'VK_2'], Digit3: ['3', '#', '', '', 0, 'VK_3'], Digit4: ['4', '$', '', '', 0, 'VK_4'], Digit5: ['5', '%', '', '', 0, 'VK_5'], Digit6: ['6', '^', '', '', 0, 'VK_6'], Digit7: ['7', '&', '', '', 0, 'VK_7'], Digit8: ['8', '*', '', '', 0, 'VK_8'], Digit9: ['9', '(', '', '', 0, 'VK_9'], Digit0: ['0', ')', '', '', 0, 'VK_0'], Enter: [], Escape: [], Backspace: [], Tab: [], Space: [' ', ' ', '', '', 0, 'VK_SPACE'], Minus: ['-', '_', '', '', 0, 'VK_OEM_MINUS'], Equal: ['=', '+', '', '', 0, 'VK_OEM_PLUS'], BracketLeft: ['[', '{', '', '', 0, 'VK_OEM_4'], BracketRight: [']', '}', '', '', 0, 'VK_OEM_6'], Backslash: ['\\', '|', '', '', 0, 'VK_OEM_5'], Semicolon: [';', ':', '', '', 0, 'VK_OEM_1'], Quote: ['\'', '"', '', '', 0, 'VK_OEM_7'], Backquote: ['`', '~', '', '', 0, 'VK_OEM_3'], Comma: [',', '<', '', '', 0, 'VK_OEM_COMMA'], Period: ['.', '>', '', '', 0, 'VK_OEM_PERIOD'], Slash: ['/', '?', '', '', 0, 'VK_OEM_2'], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], PrintScreen: [], ScrollLock: [], Pause: [], Insert: [], Home: [], PageUp: [], Delete: [], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: ['/', '/', '', '', 0, 'VK_DIVIDE'], NumpadMultiply: ['*', '*', '', '', 0, 'VK_MULTIPLY'], NumpadSubtract: ['-', '-', '', '', 0, 'VK_SUBTRACT'], NumpadAdd: ['+', '+', '', '', 0, 'VK_ADD'], NumpadEnter: [], Numpad1: [], Numpad2: [], Numpad3: [], Numpad4: [], Numpad5: [], Numpad6: [], Numpad7: [], Numpad8: [], Numpad9: [], Numpad0: [], NumpadDecimal: [], IntlBackslash: ['\\', '|', '', '', 0, 'VK_OEM_102'], ContextMenu: [], Power: [], NumpadEqual: [], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], F21: [], F22: [], F23: [], F24: [], Help: [], Undo: [], Cut: [], Copy: [], Paste: [], AudioVolumeMute: [], AudioVolumeUp: [], AudioVolumeDown: [], NumpadComma: [], IntlRo: [], KanaMode: [], IntlYen: [], Convert: [], NonConvert: [], Lang1: [], Lang2: [], Lang3: [], Lang4: [], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: [], MetaRight: [], MediaTrackNext: [], MediaTrackPrevious: [], MediaStop: [], Eject: [], MediaPlayPause: [], MediaSelect: [], LaunchMail: [], LaunchApp2: [], LaunchApp1: [], BrowserSearch: [], BrowserHome: [], BrowserBack: [], BrowserForward: [], BrowserStop: [], BrowserRefresh: [], BrowserFavorites: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/pl.win.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017487067088950425, 0.00017066219879779965, 0.0001662001886870712, 0.00017065979773178697, 0.000002472418600518722 ]
{ "id": 7, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"composeContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerComposeFile\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"string\",\n", "\t\t\t\t\t\t\"array\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 166 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Defines a dev container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "devContainerCommon": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "A name to show for the workspace folder." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "postCreateCommand": { "type": [ "string", "array" ], "description": "A command to run after creating the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } }, "devPort": { "type": "integer", "description": "The port VS Code can use to connect to its backend." } } }, "nonComposeBase": { "type": "object", "additionalProperties": false, "properties": { "appPort": { "type": [ "integer", "string", "array" ], "description": "Application ports that are exposed by the container. This can be a single port or an array of ports. Each port can be a number or a string. A number is mapped to the same port on the host. A string is passed to Docker unchanged and can be used to map ports differently, e.g. \"8000:8010\".", "items": { "type": [ "integer", "string" ] } }, "containerEnv": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Container environment variables." }, "containerUser": { "type": "string", "description": "The user the container will be started with. The default is the user on the Docker image." }, "updateRemoteUserUID": { "type": "boolean", "description": "Controls whether on Linux the container's user should be updated with the local user's UID and GID. On by default." }, "mounts": { "type": "array", "description": "Mount points to set up when creating the container. See Docker's documentation for the --mount option for the supported syntax.", "items": { "type": "string" } }, "runArgs": { "type": "array", "description": "The arguments required when starting in the container.", "items": { "type": "string" } }, "shutdownAction": { "type": "string", "enum": [ "none", "stopContainer" ], "description": "Action to take when the VS Code window is closed. The default is to stop the container." }, "overrideCommand": { "type": "boolean", "description": "Whether to overwrite the command specified in the image. The default is true." }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "workspaceMount": { "type": "string", "description": "The --mount parameter for docker run. The default is to mount the project folder at /workspaces/$project." } } }, "dockerFileContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerFile": { "type": "string", "description": "The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file." }, "context": { "type": "string", "description": "The location of the context folder for building the Docker image. The path is relative to the folder containing the `devcontainer.json` file." } }, "required": [ "dockerFile" ] }, "imageContainer": { "type": "object", "additionalProperties": false, "properties": { "image": { "type": "string", "description": "The docker image that will be used to create the container." } }, "required": [ "image" ] }, "composeContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerComposeFile": { "type": [ "string", "array" ], "description": "The name of the docker-compose file(s) used to start the services.", "items": { "type": "string" } }, "service": { "type": "string", "description": "The service you want to work on." }, "runServices": { "type": "array", "description": "An array of services that should be started and stopped.", "items": { "type": "string" } }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "shutdownAction": { "type": "string", "enum": [ "none", "stopCompose" ], "description": "Action to take when the VS Code window is closed. The default is to stop the containers." } }, "required": [ "dockerComposeFile", "service", "workspaceFolder" ] } }, "allOf": [ { "oneOf": [ { "allOf": [ { "oneOf": [ { "$ref": "#/definitions/dockerFileContainer" }, { "$ref": "#/definitions/imageContainer" } ] }, { "$ref": "#/definitions/nonComposeBase" } ] }, { "$ref": "#/definitions/composeContainer" } ] }, { "$ref": "#/definitions/devContainerCommon" } ] }
extensions/configuration-editing/schemas/devContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.980613112449646, 0.04110003635287285, 0.0001643253053771332, 0.00021681477664969862, 0.1959020346403122 ]
{ "id": 7, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"composeContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerComposeFile\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"string\",\n", "\t\t\t\t\t\t\"array\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 166 }
{ "name": "Quiet Light", "tokenColors": [ { "settings": { "foreground": "#333333" } }, { "scope": [ "meta.embedded", "source.groovy.embedded" ], "settings": { "foreground": "#333333" } }, { "name": "Comments", "scope": [ "comment", "punctuation.definition.comment" ], "settings": { "fontStyle": "italic", "foreground": "#AAAAAA" } }, { "name": "Comments: Preprocessor", "scope": "comment.block.preprocessor", "settings": { "fontStyle": "", "foreground": "#AAAAAA" } }, { "name": "Comments: Documentation", "scope": [ "comment.documentation", "comment.block.documentation", "comment.block.documentation punctuation.definition.comment " ], "settings": { "foreground": "#448C27" } }, { "name": "Invalid - Illegal", "scope": "invalid.illegal", "settings": { "foreground": "#660000" } }, { "name": "Operators", "scope": "keyword.operator", "settings": { "foreground": "#777777" } }, { "name": "Keywords", "scope": [ "keyword", "storage" ], "settings": { "foreground": "#4B69C6" } }, { "name": "Types", "scope": [ "storage.type", "support.type" ], "settings": { "foreground": "#7A3E9D" } }, { "name": "Language Constants", "scope": [ "constant.language", "support.constant", "variable.language" ], "settings": { "foreground": "#9C5D27" } }, { "name": "Variables", "scope": [ "variable", "support.variable" ], "settings": { "foreground": "#7A3E9D" } }, { "name": "Functions", "scope": [ "entity.name.function", "support.function" ], "settings": { "fontStyle": "bold", "foreground": "#AA3731" } }, { "name": "Classes", "scope": [ "entity.name.type", "entity.name.namespace", "entity.name.scope-resolution", "entity.other.inherited-class", "support.class" ], "settings": { "fontStyle": "bold", "foreground": "#7A3E9D" } }, { "name": "Exceptions", "scope": "entity.name.exception", "settings": { "foreground": "#660000" } }, { "name": "Sections", "scope": "entity.name.section", "settings": { "fontStyle": "bold" } }, { "name": "Numbers, Characters", "scope": [ "constant.numeric", "constant.character", "constant" ], "settings": { "foreground": "#9C5D27" } }, { "name": "Strings", "scope": "string", "settings": { "foreground": "#448C27" } }, { "name": "Strings: Escape Sequences", "scope": "constant.character.escape", "settings": { "foreground": "#777777" } }, { "name": "Strings: Regular Expressions", "scope": "string.regexp", "settings": { "foreground": "#4B69C6" } }, { "name": "Strings: Symbols", "scope": "constant.other.symbol", "settings": { "foreground": "#9C5D27" } }, { "name": "Punctuation", "scope": "punctuation", "settings": { "foreground": "#777777" } }, { "name": "HTML: Doctype Declaration", "scope": [ "meta.tag.sgml.doctype", "meta.tag.sgml.doctype string", "meta.tag.sgml.doctype entity.name.tag", "meta.tag.sgml punctuation.definition.tag.html" ], "settings": { "foreground": "#AAAAAA" } }, { "name": "HTML: Tags", "scope": [ "meta.tag", "punctuation.definition.tag.html", "punctuation.definition.tag.begin.html", "punctuation.definition.tag.end.html" ], "settings": { "foreground": "#91B3E0" } }, { "name": "HTML: Tag Names", "scope": "entity.name.tag", "settings": { "foreground": "#4B69C6" } }, { "name": "HTML: Attribute Names", "scope": [ "meta.tag entity.other.attribute-name", "entity.other.attribute-name.html" ], "settings": { "fontStyle": "italic", "foreground": "#8190A0" } }, { "name": "HTML: Entities", "scope": [ "constant.character.entity", "punctuation.definition.entity" ], "settings": { "foreground": "#9C5D27" } }, { "name": "CSS: Selectors", "scope": [ "meta.selector", "meta.selector entity", "meta.selector entity punctuation", "entity.name.tag.css" ], "settings": { "foreground": "#7A3E9D" } }, { "name": "CSS: Property Names", "scope": [ "meta.property-name", "support.type.property-name" ], "settings": { "foreground": "#9C5D27" } }, { "name": "CSS: Property Values", "scope": [ "meta.property-value", "meta.property-value constant.other", "support.constant.property-value" ], "settings": { "foreground": "#448C27" } }, { "name": "CSS: Important Keyword", "scope": "keyword.other.important", "settings": { "fontStyle": "bold" } }, { "name": "Markup: Changed", "scope": "markup.changed", "settings": { "foreground": "#000000" } }, { "name": "Markup: Deletion", "scope": "markup.deleted", "settings": { "foreground": "#000000" } }, { "name": "Markup: Emphasis", "scope": "markup.italic", "settings": { "fontStyle": "italic" } }, { "name": "Markup: Error", "scope": "markup.error", "settings": { "foreground": "#660000" } }, { "name": "Markup: Insertion", "scope": "markup.inserted", "settings": { "foreground": "#000000" } }, { "name": "Markup: Link", "scope": "meta.link", "settings": { "foreground": "#4B69C6" } }, { "name": "Markup: Output", "scope": [ "markup.output", "markup.raw" ], "settings": { "foreground": "#777777" } }, { "name": "Markup: Prompt", "scope": "markup.prompt", "settings": { "foreground": "#777777" } }, { "name": "Markup: Heading", "scope": "markup.heading", "settings": { "foreground": "#AA3731" } }, { "name": "Markup: Strong", "scope": "markup.bold", "settings": { "fontStyle": "bold" } }, { "name": "Markup: Traceback", "scope": "markup.traceback", "settings": { "foreground": "#660000" } }, { "name": "Markup: Underline", "scope": "markup.underline", "settings": { "fontStyle": "underline" } }, { "name": "Markup Quote", "scope": "markup.quote", "settings": { "foreground": "#7A3E9D" } }, { "name": "Markup Lists", "scope": "markup.list", "settings": { "foreground": "#4B69C6" } }, { "name": "Markup Styling", "scope": [ "markup.bold", "markup.italic" ], "settings": { "foreground": "#448C27" } }, { "name": "Markup Inline", "scope": "markup.inline.raw", "settings": { "fontStyle": "", "foreground": "#9C5D27" } }, { "name": "Extra: Diff Range", "scope": [ "meta.diff.range", "meta.diff.index", "meta.separator" ], "settings": { "foreground": "#434343" } }, { "name": "Extra: Diff From", "scope": "meta.diff.header.from-file", "settings": { "foreground": "#434343" } }, { "name": "Extra: Diff To", "scope": "meta.diff.header.to-file", "settings": { "foreground": "#434343" } }, { "name": "JSX: Tags", "scope": [ "punctuation.definition.tag.js", "punctuation.definition.tag.begin.js", "punctuation.definition.tag.end.js" ], "settings": { "foreground": "#91B3E0" } }, { "name": "JSX: InnerText", "scope": "meta.jsx.children.js", "settings": { "foreground": "#333333ff" } } ], "colors": { "focusBorder": "#A6B39B", "pickerGroup.foreground": "#A6B39B", "pickerGroup.border": "#749351", "list.activeSelectionForeground": "#6c6c6c", "list.focusBackground": "#CADEB9", "list.hoverBackground": "#e0e0e0", "list.activeSelectionBackground": "#c4d9b1", "list.inactiveSelectionBackground": "#d3dbcd", "list.highlightForeground": "#9769dc", "selection.background": "#C9D0D9", "editor.background": "#F5F5F5", "editorWhitespace.foreground": "#AAAAAA", "editor.lineHighlightBackground": "#E4F6D4", "editorLineNumber.activeForeground": "#9769dc", "editor.selectionBackground": "#C9D0D9", "minimap.selectionHighlight": "#C9D0D9", "panel.background": "#F5F5F5", "sideBar.background": "#F2F2F2", "sideBarSectionHeader.background": "#ede8ef", "editorLineNumber.foreground": "#6D705B", "editorCursor.foreground": "#54494B", "inputOption.activeBorder": "#adafb7", "dropdown.background": "#F5F5F5", "editor.findMatchBackground": "#BF9CAC", "editor.findMatchHighlightBackground": "#edc9d8", "peekViewEditor.matchHighlightBackground": "#C2DFE3", "peekViewTitle.background": "#F2F8FC", "peekViewEditor.background": "#F2F8FC", "peekViewResult.background": "#F2F8FC", "peekView.border": "#705697", "peekViewResult.matchHighlightBackground": "#93C6D6", "statusBar.background": "#705697", "statusBar.noFolderBackground": "#705697", "statusBar.debuggingBackground": "#705697", "statusBarItem.remoteBackground": "#4e3c69", "activityBar.background": "#EDEDF5", "activityBar.foreground": "#705697", "activityBarBadge.background": "#705697", "titleBar.activeBackground": "#c4b7d7", "button.background": "#705697", "editorGroup.dropBackground": "#C9D0D988", "inputValidation.infoBorder": "#4ec1e5", "inputValidation.infoBackground": "#f2fcff", "inputValidation.warningBackground": "#fffee2", "inputValidation.warningBorder": "#ffe055", "inputValidation.errorBackground": "#ffeaea", "inputValidation.errorBorder": "#f1897f", "errorForeground": "#f1897f", "badge.background": "#705697AA", "progressBar.background": "#705697", "walkThrough.embeddedEditorBackground": "#00000014", "editorIndentGuide.background": "#aaaaaa60", "editorIndentGuide.activeBackground": "#777777b0" } }
extensions/theme-quietlight/themes/quietlight-color-theme.json
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017461391689721495, 0.00017056867363862693, 0.00016586534911766648, 0.0001706925977487117, 0.0000017176542996821809 ]
{ "id": 7, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"composeContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerComposeFile\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"string\",\n", "\t\t\t\t\t\t\"array\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 166 }
// from https://msdn.microsoft.com/en-us/library/dd233160.aspx // The declaration creates a constructor that takes two values, name and age. type Person(name:string, age:int) = let mutable internalAge = age new(name:string) = Person(name, 0) member this.Name = name // A read/write property. member this.Age with get() = internalAge and set(value) = internalAge <- value member this.HasABirthday () = internalAge <- internalAge + 1 member this.IsOfAge targetAge = internalAge >= targetAge override this.ToString () = "Name: " + name + "\n" + "Age: " + (string)internalAge
extensions/fsharp/test/colorize-fixtures/test.fs
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017148026381619275, 0.00016962087829597294, 0.0001677614782238379, 0.00016962087829597294, 0.000001859392796177417 ]
{ "id": 7, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"composeContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerComposeFile\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"string\",\n", "\t\t\t\t\t\t\"array\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 166 }
[ { "c": "/**", "t": "source.ts comment.block.documentation.ts punctuation.definition.comment.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " * ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "@", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc punctuation.definition.block.tag.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": "typedef", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": " ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "{", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc punctuation.definition.bracket.curly.begin.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": "{", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * id: number,", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * fn: !Function,", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * context: (!Object|undefined)", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * }", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": "}", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc punctuation.definition.bracket.curly.end.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "@", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc punctuation.definition.block.tag.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": "private", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": " ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "*/", "t": "source.ts comment.block.documentation.ts punctuation.definition.comment.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "goog", "t": "source.ts variable.other.object.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ".", "t": "source.ts punctuation.accessor.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "dom", "t": "source.ts variable.other.object.property.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ".", "t": "source.ts punctuation.accessor.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "animationFrame", "t": "source.ts variable.other.object.property.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ".", "t": "source.ts punctuation.accessor.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Task_", "t": "source.ts variable.other.property.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ";", "t": "source.ts punctuation.terminator.statement.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "/**", "t": "source.ts comment.block.documentation.ts punctuation.definition.comment.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": " * ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "@", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc punctuation.definition.block.tag.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": "typedef", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": " ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "{", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc punctuation.definition.bracket.curly.begin.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": "{", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * measureTask: goog.dom.animationFrame.Task_,", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * mutateTask: goog.dom.animationFrame.Task_,", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * state: (!Object|undefined),", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * args: (!Array|undefined),", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * isScheduled: boolean", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * }", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": "}", "t": "source.ts comment.block.documentation.ts entity.name.type.instance.jsdoc punctuation.definition.bracket.curly.end.jsdoc", "r": { "dark_plus": "entity.name.type: #4EC9B0", "light_plus": "entity.name.type: #267F99", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "entity.name.type: #4EC9B0" } }, { "c": " * ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "@", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc punctuation.definition.block.tag.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": "private", "t": "source.ts comment.block.documentation.ts storage.type.class.jsdoc", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": " ", "t": "source.ts comment.block.documentation.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "*/", "t": "source.ts comment.block.documentation.ts punctuation.definition.comment.ts", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668" } }, { "c": "goog", "t": "source.ts variable.other.object.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ".", "t": "source.ts punctuation.accessor.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "dom", "t": "source.ts variable.other.object.property.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ".", "t": "source.ts punctuation.accessor.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "animationFrame", "t": "source.ts variable.other.object.property.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ".", "t": "source.ts punctuation.accessor.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "TaskSet_", "t": "source.ts variable.other.property.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ";", "t": "source.ts punctuation.terminator.statement.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } } ]
extensions/typescript-basics/test/colorize-results/test-jsdoc-multiline-type_ts.json
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0001730467629386112, 0.00017004659457597882, 0.00016354375111404806, 0.00017039329395629466, 0.000002082378841805621 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " onAddPermission: (item: NewDashboardAclItem) => void;\n", " onCancel: () => void;\n", "}\n", "\n", "export interface TeamSelectedAction {\n", " action: string;\n", "}\n", "\n", "class AddPermissions extends Component<Props, NewDashboardAclItem> {\n", " constructor(props) {\n", " super(props);\n", " this.state = this.getCleanState();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 19 }
import React, { PureComponent } from 'react'; import DescriptionPicker from 'app/core/components/Picker/DescriptionPicker'; import { dashboardPermissionLevels, DashboardAcl, PermissionLevel } from 'app/types/acl'; import { FolderInfo } from 'app/types'; const setClassNameHelper = inherited => { return inherited ? 'gf-form-disabled' : ''; }; function ItemAvatar({ item }) { if (item.userAvatarUrl) { return <img className="filter-table__avatar" src={item.userAvatarUrl} />; } if (item.teamAvatarUrl) { return <img className="filter-table__avatar" src={item.teamAvatarUrl} />; } if (item.role === 'Editor') { return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-editor" />; } return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-viewer" />; } function ItemDescription({ item }) { if (item.userId) { return <span className="filter-table__weak-italic">(User)</span>; } if (item.teamId) { return <span className="filter-table__weak-italic">(Team)</span>; } return <span className="filter-table__weak-italic">(Role)</span>; } interface Props { item: DashboardAcl; onRemoveItem: (item: DashboardAcl) => void; onPermissionChanged: (item: DashboardAcl, level: PermissionLevel) => void; folderInfo?: FolderInfo; } export default class PermissionsListItem extends PureComponent<Props> { onPermissionChanged = option => { this.props.onPermissionChanged(this.props.item, option.value as PermissionLevel); }; onRemoveItem = () => { this.props.onRemoveItem(this.props.item); }; render() { const { item, folderInfo } = this.props; const inheritedFromRoot = item.dashboardId === -1 && !item.inherited; return ( <tr className={setClassNameHelper(item.inherited)}> <td style={{ width: '1%' }}> <ItemAvatar item={item} /> </td> <td style={{ width: '90%' }}> {item.name} <ItemDescription item={item} /> </td> <td> {item.inherited && folderInfo && ( <em className="muted no-wrap"> Inherited from folder{' '} <a className="text-link" href={`${folderInfo.url}/permissions`}> {folderInfo.title} </a>{' '} </em> )} {inheritedFromRoot && <em className="muted no-wrap">Default Permission</em>} </td> <td className="query-keyword">Can</td> <td> <div className="gf-form"> <DescriptionPicker optionsWithDesc={dashboardPermissionLevels} onSelected={this.onPermissionChanged} value={item.permission} disabled={item.inherited} className={'gf-form-select2__control--menu-right'} /> </div> </td> <td> {!item.inherited ? ( <a className="btn btn-danger btn-small" onClick={this.onRemoveItem}> <i className="fa fa-remove" /> </a> ) : ( <button className="btn btn-inverse btn-small"> <i className="fa fa-lock" /> </button> )} </td> </tr> ); } }
public/app/core/components/PermissionList/PermissionListItem.tsx
1
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.9876571893692017, 0.09159017354249954, 0.00016826018691062927, 0.00025482679484412074, 0.28338608145713806 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " onAddPermission: (item: NewDashboardAclItem) => void;\n", " onCancel: () => void;\n", "}\n", "\n", "export interface TeamSelectedAction {\n", " action: string;\n", "}\n", "\n", "class AddPermissions extends Component<Props, NewDashboardAclItem> {\n", " constructor(props) {\n", " super(props);\n", " this.state = this.getCleanState();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 19 }
package migrations import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator" func addDashboardVersionMigration(mg *Migrator) { dashboardVersionV1 := Table{ Name: "dashboard_version", Columns: []*Column{ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true}, {Name: "dashboard_id", Type: DB_BigInt}, {Name: "parent_version", Type: DB_Int, Nullable: false}, {Name: "restored_from", Type: DB_Int, Nullable: false}, {Name: "version", Type: DB_Int, Nullable: false}, {Name: "created", Type: DB_DateTime, Nullable: false}, {Name: "created_by", Type: DB_BigInt, Nullable: false}, {Name: "message", Type: DB_Text, Nullable: false}, {Name: "data", Type: DB_Text, Nullable: false}, }, Indices: []*Index{ {Cols: []string{"dashboard_id"}}, {Cols: []string{"dashboard_id", "version"}, Type: UniqueIndex}, }, } mg.AddMigration("create dashboard_version table v1", NewAddTableMigration(dashboardVersionV1)) mg.AddMigration("add index dashboard_version.dashboard_id", NewAddIndexMigration(dashboardVersionV1, dashboardVersionV1.Indices[0])) mg.AddMigration("add unique index dashboard_version.dashboard_id and dashboard_version.version", NewAddIndexMigration(dashboardVersionV1, dashboardVersionV1.Indices[1])) // before new dashboards where created with version 0, now they are always inserted with version 1 const setVersionTo1WhereZeroSQL = `UPDATE dashboard SET version = 1 WHERE version = 0` mg.AddMigration("Set dashboard version to 1 where 0", NewRawSqlMigration(setVersionTo1WhereZeroSQL)) const rawSQL = `INSERT INTO dashboard_version ( dashboard_id, version, parent_version, restored_from, created, created_by, message, data ) SELECT dashboard.id, dashboard.version, dashboard.version, dashboard.version, dashboard.updated, COALESCE(dashboard.updated_by, -1), '', dashboard.data FROM dashboard;` mg.AddMigration("save existing dashboard data in dashboard_version table v1", NewRawSqlMigration(rawSQL)) // change column type of dashboard_version.data mg.AddMigration("alter dashboard_version.data to mediumtext v1", NewRawSqlMigration(""). Mysql("ALTER TABLE dashboard_version MODIFY data MEDIUMTEXT;")) }
pkg/services/sqlstore/migrations/dashboard_version_mig.go
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.004857875872403383, 0.0009959543822333217, 0.00016351848898921162, 0.00017890112940222025, 0.0017296430887654424 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " onAddPermission: (item: NewDashboardAclItem) => void;\n", " onCancel: () => void;\n", "}\n", "\n", "export interface TeamSelectedAction {\n", " action: string;\n", "}\n", "\n", "class AddPermissions extends Component<Props, NewDashboardAclItem> {\n", " constructor(props) {\n", " super(props);\n", " this.state = this.getCleanState();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 19 }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:generate go run makexml.go -output xml.go // Package cldr provides a parser for LDML and related XML formats. // This package is intended to be used by the table generation tools // for the various internationalization-related packages. // As the XML types are generated from the CLDR DTD, and as the CLDR standard // is periodically amended, this package may change considerably over time. // This mostly means that data may appear and disappear between versions. // That is, old code should keep compiling for newer versions, but data // may have moved or changed. // CLDR version 22 is the first version supported by this package. // Older versions may not work. package cldr // import "golang.org/x/text/unicode/cldr" import ( "fmt" "sort" ) // CLDR provides access to parsed data of the Unicode Common Locale Data Repository. type CLDR struct { parent map[string][]string locale map[string]*LDML resolved map[string]*LDML bcp47 *LDMLBCP47 supp *SupplementalData } func makeCLDR() *CLDR { return &CLDR{ parent: make(map[string][]string), locale: make(map[string]*LDML), resolved: make(map[string]*LDML), bcp47: &LDMLBCP47{}, supp: &SupplementalData{}, } } // BCP47 returns the parsed BCP47 LDML data. If no such data was parsed, nil is returned. func (cldr *CLDR) BCP47() *LDMLBCP47 { return nil } // Draft indicates the draft level of an element. type Draft int const ( Approved Draft = iota Contributed Provisional Unconfirmed ) var drafts = []string{"unconfirmed", "provisional", "contributed", "approved", ""} // ParseDraft returns the Draft value corresponding to the given string. The // empty string corresponds to Approved. func ParseDraft(level string) (Draft, error) { if level == "" { return Approved, nil } for i, s := range drafts { if level == s { return Unconfirmed - Draft(i), nil } } return Approved, fmt.Errorf("cldr: unknown draft level %q", level) } func (d Draft) String() string { return drafts[len(drafts)-1-int(d)] } // SetDraftLevel sets which draft levels to include in the evaluated LDML. // Any draft element for which the draft level is higher than lev will be excluded. // If multiple draft levels are available for a single element, the one with the // lowest draft level will be selected, unless preferDraft is true, in which case // the highest draft will be chosen. // It is assumed that the underlying LDML is canonicalized. func (cldr *CLDR) SetDraftLevel(lev Draft, preferDraft bool) { // TODO: implement cldr.resolved = make(map[string]*LDML) } // RawLDML returns the LDML XML for id in unresolved form. // id must be one of the strings returned by Locales. func (cldr *CLDR) RawLDML(loc string) *LDML { return cldr.locale[loc] } // LDML returns the fully resolved LDML XML for loc, which must be one of // the strings returned by Locales. func (cldr *CLDR) LDML(loc string) (*LDML, error) { return cldr.resolve(loc) } // Supplemental returns the parsed supplemental data. If no such data was parsed, // nil is returned. func (cldr *CLDR) Supplemental() *SupplementalData { return cldr.supp } // Locales returns the locales for which there exist files. // Valid sublocales for which there is no file are not included. // The root locale is always sorted first. func (cldr *CLDR) Locales() []string { loc := []string{"root"} hasRoot := false for l, _ := range cldr.locale { if l == "root" { hasRoot = true continue } loc = append(loc, l) } sort.Strings(loc[1:]) if !hasRoot { return loc[1:] } return loc } // Get fills in the fields of x based on the XPath path. func Get(e Elem, path string) (res Elem, err error) { return walkXPath(e, path) }
vendor/golang.org/x/text/unicode/cldr/cldr.go
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.0003948615922126919, 0.00018656525935512036, 0.00016558897914364934, 0.00017032172763720155, 0.00005784737004432827 ]
{ "id": 0, "code_window": [ "export interface Props {\n", " onAddPermission: (item: NewDashboardAclItem) => void;\n", " onCancel: () => void;\n", "}\n", "\n", "export interface TeamSelectedAction {\n", " action: string;\n", "}\n", "\n", "class AddPermissions extends Component<Props, NewDashboardAclItem> {\n", " constructor(props) {\n", " super(props);\n", " this.state = this.getCleanState();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 19 }
--- page_title: Graphite + Grafana + StatsD - Stack Setup Guide page_description: Installation and configuration guide & how to for Grafana, Graphite & StatsD page_keywords: grafana, tutorials, graphite, statsd, setup, configuration, howto, installation author: Torkel Ödegaard --- # Stack Setup & Config Guide: Graphite + Grafana + StatsD This lengthy article will guide you through installation, configuration and getting started with the amazing metric stack that is composed of Graphite, Grafana and StatsD. Graphite is still king when it comes to time series databases due to its simple data model, ingestion with integrated aggregation & rollups, amazing query features and speed. No other time series database has yet to match Graphite's query flexibility and analytics potential. Graphite has a reputation for being tricky to install and scale. This guide aims to show that is not really the case, or, at least, that it is a lot better than you expect. > This guides does not only aim to be only be an install guide but to also teach you > of the mechanics of metric collection, aggregation and querying. How Graphite > stores and aggregates data is very important to understand in order to not > get mislead by graphs. ## Installation - Ubuntu To begin with we are going to install the 3 main components that define our metric stack. Later in the guide we will install StatsD, but that is optional. - Carbon is the graphite ingestion daemon responsible for receiving metrics and storing them. - Graphite-api is light weight version of graphite-web with only the HTTP api and is responsible for executing metric queries. - Grafana as the frontend to visualize metrics and the tool to help you build metric queries that will make the most out of your collected metrics. ### Carbon Graphite & Carbon are written in python, so we will start by installing python packages. ``` apt-get install \ git \ build-essential \ libffi-dev libcairo2-dev \ python-django \ python-django-tagging \ python-simplejson \ python-memcache \ python-ldap \ python-cairo \ python-twisted \ python-pysqlite2 \ python-support \ python-dev \ python-pip ``` Next we will clone carbon and whisper and install these components. Whisper is just a lib used by carbon to write metrics to disk. cd /usr/local/src git clone https://github.com/graphite-project/carbon.git git clone https://github.com/graphite-project/whisper.git cd whisper && python setup.py install && cd .. cd carbon && python setup.py install && cd .. ### Configure carbon.conf Copy example carbon config: ``` cp /opt/graphite/conf/carbon.conf.example /opt/graphite/conf/carbon.conf ``` Edit the config file `/opt/graphite/conf/carbon.conf`, find line `ENABLE_UPD_LISTENER` and change this setting to `True`. ### Configure storage-schemas.conf Create a new file at `/opt/graphite/conf/storage-schemas.conf` with the following content: ``` [carbon] pattern = ^carbon\..* retentions = 1m:30d,10m:1y,1h:5y [default] pattern = .* retentions = 10s:1d,1m:7d,10m:1y ``` This config specifies the resolution of metrics and the retention periods. For example for all metrics beginning with the word `carbon` receive metrics every minute and store for 30 days, then roll them up into 10 minute buckets and store those for 1 year, then roll those up into 1 hour buckets and store those for 5 years. For all other metrics the default rule will be applied with other retention periods. This configuration is very important, as the first retention period must match the rate of which you send metrics. The default rule has 10 seconds as its first resolution so when configuring StatsD we should configure it to send metrics every 10 seconds. > If you send values more frequently than the highest resolution, for example if you send data every second but > the storage schema rules defines the highest resolution to be 10 seconds, then the values you send will just > overwrite each other and the last value sent during every 10 second period will be saved. StatsD can work around this > problem. ### Configure storage-aggregation.conf Copy the default config and open it in an editor. ``` cp /opt/graphite/conf/storage-aggregation.conf.example /opt/graphite/conf/storage-aggregation.conf ``` Example config: ``` [min] pattern = \.min$ xFilesFactor = 0.1 aggregationMethod = min [max] pattern = \.max$ xFilesFactor = 0.1 aggregationMethod = max [sum] pattern = \.count$ xFilesFactor = 0 aggregationMethod = sum [default_average] pattern = .* xFilesFactor = 0.5 aggregationMethod = average ``` You do not really need to change the default config, but is very important to understand what the config controls and what implications that it has. Graphite does rollups as part of the metric ingestion according to the rules defined in `storage-schemas.conf`. For example, given storage schema rule `10s:1d,1m:7d`, when aggregating 6 values (each representing 10 seconds) into a 1min bucket graphite will use an `aggregationMethod` like for example `average`. What method to use will be determined by the rules specified in `storage-aggregation.conf`. The default rules all look at the metric path ending. Does it end with `.count` then use `sum` when doing rollups, does it end with `max` then use `max` function, and if it does not end with max, min or count then use average. This means that naming metrics is very important! But don't worry if you use StatsD it will send the correct names to graphite. ### Start carbon Lets install supervisord and let it start carbon. `apt-get install supervisor` Create a new file in `/etc/supervisor/conf.d/carbon.conf` with the following: ``` [program:carbon-cache] command = /opt/graphite/bin/carbon-cache.py --debug start stdout_logfile = /var/log/supervisor/%(program_name)s.log stderr_logfile = /var/log/supervisor/%(program_name)s.log autorestart = true stopsignal = QUIT ``` ``` supervisorctl reload ``` ### Graphite-api Graphite api is a light weight version of graphite-web with only the api component (no web ui). It is dead simple to install. ``` pip install gunicorn graphite-api ``` You should now have a graphite-api daemon running with an open HTTP api port of 8888. ### Configuring Graphite-api Create a file `/etc/graphite-api.yaml` with an editor and set it's content to: ``` search_index: /opt/graphite/storage/index finders: - graphite_api.finders.whisper.WhisperFinder functions: - graphite_api.functions.SeriesFunctions - graphite_api.functions.PieFunctions whisper: directories: - /opt/graphite/storage/whisper time_zone: UTC ``` Lets create a supervisor file for graphite-api at `/etc/supervisor/graphite-api.conf` ``` [program:graphite-api] command = gunicorn -b 0.0.0.0:8888 -w 2 --log-level info graphite_api.app:app stdout_logfile = /var/log/supervisor/%(program_name)s.log stderr_logfile = /var/log/supervisor/%(program_name)s.log autorestart = true stopsignal = QUIT ``` Reload supervisor supervisorctl reload A carbon-cache daemon and graphite-api should now be running. Type `supervisorctl status` to verify that they are running. You can also open `http://your_server_ip:8888/metrics/find?query?*` in your browser. You should see a json snippet. ### Install Grafana cd /tmp/ wget https://grafanarel.s3.amazonaws.com/builds/grafana_2.1.1_amd64.deb sudo dpkg -i grafana_2.1.1_amd64.deb sudo service grafana-server start Grafana should now be running with default config on port 3000. ## Grafana - first steps ### Add data source Open http://your_server_ip:3000 in your browser and login with the default user and password (`admin/admin`). - Click on `Data Sources` on the side menu. - Click on `Add new` in the top menu - Specify name `graphite` and check the `Default ` checkbox - Specify Url `http://localhost:8888` and Access `proxy` - Click `Add ` button ### Your first dashboard - Click on `Dashboards` - Click on `Home` button in the top menu, this should open the dashboard search dropdown - Click on `New` button in the bottom of this dropdown ### Add a graph - Click on the green icon to the left to open the row menu - Select `Add Panel` > `Graph` from the row menu - An empty graph panel should appear with title `no title (click here)`. Click on this title and then `Edit` - This will open the graph in edit mode and take you to the metrics tab. - There is one query already added (assigned letter A) but it is empty. - Click on `select metric` to pick the first graphite metric node. A new `select metric` link will appear until you reached a leaf node. - Try picking the metric paths for `carbon.agents.<server name>.cpuUsage`, you should now see a line appear in the graph! ## Writing metrics to Graphite Graphite has the simplest metric write protocol imaginable. Something that has surely contributed to its wide adoption by metric frameworks and numerous integrations. prod.server1.requests.count 10 1398969187 <metric.name.and.path> <metric value> <unix_epoch_time_stamp_in_seconds> There are hundreds of tools and instrumentation frameworks that can send metrics using this protocol. ### Installing StatsD StatsD is a metrics aggregation daemon that makes it easy for apps on many machines to send measurements like timings and counters and have them aggregated or percentiles calculated. ### Sending metrics to StatsD
docs/sources/tutorials/stack_guide_graphite.md
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.00017601909348741174, 0.0001708924100967124, 0.00016315263928845525, 0.00017161063442472368, 0.0000032707150694477605 ]
{ "id": 1, "code_window": [ "\n", " onUserSelected = (user: User) => {\n", " this.setState({ userId: user && !Array.isArray(user) ? user.id : 0 });\n", " };\n", "\n", " onTeamSelected = (team: Team, info: TeamSelectedAction) => {\n", " this.setState({ teamId: team && !Array.isArray(team) ? team.id : 0 });\n", " };\n", "\n", " onPermissionChanged = (permission: OptionWithDescription) => {\n", " this.setState({ permission: permission.value });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onTeamSelected = (team: Team) => {\n" ], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 59 }
import React, { PureComponent } from 'react'; import DescriptionPicker from 'app/core/components/Picker/DescriptionPicker'; import { dashboardPermissionLevels, DashboardAcl, PermissionLevel } from 'app/types/acl'; import { FolderInfo } from 'app/types'; const setClassNameHelper = inherited => { return inherited ? 'gf-form-disabled' : ''; }; function ItemAvatar({ item }) { if (item.userAvatarUrl) { return <img className="filter-table__avatar" src={item.userAvatarUrl} />; } if (item.teamAvatarUrl) { return <img className="filter-table__avatar" src={item.teamAvatarUrl} />; } if (item.role === 'Editor') { return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-editor" />; } return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-viewer" />; } function ItemDescription({ item }) { if (item.userId) { return <span className="filter-table__weak-italic">(User)</span>; } if (item.teamId) { return <span className="filter-table__weak-italic">(Team)</span>; } return <span className="filter-table__weak-italic">(Role)</span>; } interface Props { item: DashboardAcl; onRemoveItem: (item: DashboardAcl) => void; onPermissionChanged: (item: DashboardAcl, level: PermissionLevel) => void; folderInfo?: FolderInfo; } export default class PermissionsListItem extends PureComponent<Props> { onPermissionChanged = option => { this.props.onPermissionChanged(this.props.item, option.value as PermissionLevel); }; onRemoveItem = () => { this.props.onRemoveItem(this.props.item); }; render() { const { item, folderInfo } = this.props; const inheritedFromRoot = item.dashboardId === -1 && !item.inherited; return ( <tr className={setClassNameHelper(item.inherited)}> <td style={{ width: '1%' }}> <ItemAvatar item={item} /> </td> <td style={{ width: '90%' }}> {item.name} <ItemDescription item={item} /> </td> <td> {item.inherited && folderInfo && ( <em className="muted no-wrap"> Inherited from folder{' '} <a className="text-link" href={`${folderInfo.url}/permissions`}> {folderInfo.title} </a>{' '} </em> )} {inheritedFromRoot && <em className="muted no-wrap">Default Permission</em>} </td> <td className="query-keyword">Can</td> <td> <div className="gf-form"> <DescriptionPicker optionsWithDesc={dashboardPermissionLevels} onSelected={this.onPermissionChanged} value={item.permission} disabled={item.inherited} className={'gf-form-select2__control--menu-right'} /> </div> </td> <td> {!item.inherited ? ( <a className="btn btn-danger btn-small" onClick={this.onRemoveItem}> <i className="fa fa-remove" /> </a> ) : ( <button className="btn btn-inverse btn-small"> <i className="fa fa-lock" /> </button> )} </td> </tr> ); } }
public/app/core/components/PermissionList/PermissionListItem.tsx
1
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.9961888194084167, 0.17983515560626984, 0.00016731146024540067, 0.00017182677402161062, 0.3795803487300873 ]
{ "id": 1, "code_window": [ "\n", " onUserSelected = (user: User) => {\n", " this.setState({ userId: user && !Array.isArray(user) ? user.id : 0 });\n", " };\n", "\n", " onTeamSelected = (team: Team, info: TeamSelectedAction) => {\n", " this.setState({ teamId: team && !Array.isArray(team) ? team.id : 0 });\n", " };\n", "\n", " onPermissionChanged = (permission: OptionWithDescription) => {\n", " this.setState({ permission: permission.value });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onTeamSelected = (team: Team) => {\n" ], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 59 }
+++ title = "Alerting" type = "docs" [menu.docs] identifier = "alerting" parent = "features" weight = 6 +++
docs/sources/alerting/index.md
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.00017542747082188725, 0.00017542747082188725, 0.00017542747082188725, 0.00017542747082188725, 0 ]
{ "id": 1, "code_window": [ "\n", " onUserSelected = (user: User) => {\n", " this.setState({ userId: user && !Array.isArray(user) ? user.id : 0 });\n", " };\n", "\n", " onTeamSelected = (team: Team, info: TeamSelectedAction) => {\n", " this.setState({ teamId: team && !Array.isArray(team) ? team.id : 0 });\n", " };\n", "\n", " onPermissionChanged = (permission: OptionWithDescription) => {\n", " this.setState({ permission: permission.value });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onTeamSelected = (team: Team) => {\n" ], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 59 }
package middleware import ( "net/url" "strings" "gopkg.in/macaron.v1" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/session" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) type AuthOptions struct { ReqGrafanaAdmin bool ReqSignedIn bool } func getRequestUserId(c *m.ReqContext) int64 { userID := c.Session.Get(session.SESS_KEY_USERID) if userID != nil { return userID.(int64) } return 0 } func getApiKey(c *m.ReqContext) string { header := c.Req.Header.Get("Authorization") parts := strings.SplitN(header, " ", 2) if len(parts) == 2 && parts[0] == "Bearer" { key := parts[1] return key } username, password, err := util.DecodeBasicAuthHeader(header) if err == nil && username == "api_key" { return password } return "" } func accessForbidden(c *m.ReqContext) { if c.IsApiRequest() { c.JsonApiErr(403, "Permission denied", nil) return } c.Redirect(setting.AppSubUrl + "/") } func notAuthorized(c *m.ReqContext) { if c.IsApiRequest() { c.JsonApiErr(401, "Unauthorized", nil) return } c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/", nil, false, true) c.Redirect(setting.AppSubUrl + "/login") } func RoleAuth(roles ...m.RoleType) macaron.Handler { return func(c *m.ReqContext) { ok := false for _, role := range roles { if role == c.OrgRole { ok = true break } } if !ok { accessForbidden(c) } } } func Auth(options *AuthOptions) macaron.Handler { return func(c *m.ReqContext) { if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous { notAuthorized(c) return } if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin { accessForbidden(c) return } } }
pkg/middleware/auth.go
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.00032694279798306525, 0.00018686064868234098, 0.00016277939721476287, 0.0001669651101110503, 0.00004808512676390819 ]
{ "id": 1, "code_window": [ "\n", " onUserSelected = (user: User) => {\n", " this.setState({ userId: user && !Array.isArray(user) ? user.id : 0 });\n", " };\n", "\n", " onTeamSelected = (team: Team, info: TeamSelectedAction) => {\n", " this.setState({ teamId: team && !Array.isArray(team) ? team.id : 0 });\n", " };\n", "\n", " onPermissionChanged = (permission: OptionWithDescription) => {\n", " this.setState({ permission: permission.value });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onTeamSelected = (team: Team) => {\n" ], "file_path": "public/app/core/components/PermissionList/AddPermission.tsx", "type": "replace", "edit_start_line_idx": 59 }
// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. // https://github.com/sergi/go-diff // See the included LICENSE file for license details. // // go-diff is a Go implementation of Google's Diff, Match, and Patch library // Original library is Copyright (c) 2006 Google Inc. // http://code.google.com/p/google-diff-match-patch/ package diffmatchpatch import ( "strings" "unicode/utf8" ) // unescaper unescapes selected chars for compatibility with JavaScript's encodeURI. // In speed critical applications this could be dropped since the receiving application will certainly decode these fine. Note that this function is case-sensitive. Thus "%3F" would not be unescaped. But this is ok because it is only called with the output of HttpUtility.UrlEncode which returns lowercase hex. Example: "%3f" -> "?", "%24" -> "$", etc. var unescaper = strings.NewReplacer( "%21", "!", "%7E", "~", "%27", "'", "%28", "(", "%29", ")", "%3B", ";", "%2F", "/", "%3F", "?", "%3A", ":", "%40", "@", "%26", "&", "%3D", "=", "%2B", "+", "%24", "$", "%2C", ",", "%23", "#", "%2A", "*") // indexOf returns the first index of pattern in str, starting at str[i]. func indexOf(str string, pattern string, i int) int { if i > len(str)-1 { return -1 } if i <= 0 { return strings.Index(str, pattern) } ind := strings.Index(str[i:], pattern) if ind == -1 { return -1 } return ind + i } // lastIndexOf returns the last index of pattern in str, starting at str[i]. func lastIndexOf(str string, pattern string, i int) int { if i < 0 { return -1 } if i >= len(str) { return strings.LastIndex(str, pattern) } _, size := utf8.DecodeRuneInString(str[i:]) return strings.LastIndex(str[:i+size], pattern) } // runesIndexOf returns the index of pattern in target, starting at target[i]. func runesIndexOf(target, pattern []rune, i int) int { if i > len(target)-1 { return -1 } if i <= 0 { return runesIndex(target, pattern) } ind := runesIndex(target[i:], pattern) if ind == -1 { return -1 } return ind + i } func runesEqual(r1, r2 []rune) bool { if len(r1) != len(r2) { return false } for i, c := range r1 { if c != r2[i] { return false } } return true } // runesIndex is the equivalent of strings.Index for rune slices. func runesIndex(r1, r2 []rune) int { last := len(r1) - len(r2) for i := 0; i <= last; i++ { if runesEqual(r1[i:i+len(r2)], r2) { return i } } return -1 }
vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.00017589479102753103, 0.00017296025180257857, 0.00017067200678866357, 0.00017270325042773038, 0.000001812362370401388 ]
{ "id": 2, "code_window": [ " <td>\n", " <div className=\"gf-form\">\n", " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={() => {}}\n", " value={item.permission}\n", " disabled={true}\n", " className={'gf-form-input--form-dropdown-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/DisabledPermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 28 }
import React, { PureComponent } from 'react'; import DescriptionPicker from 'app/core/components/Picker/DescriptionPicker'; import { dashboardPermissionLevels, DashboardAcl, PermissionLevel } from 'app/types/acl'; import { FolderInfo } from 'app/types'; const setClassNameHelper = inherited => { return inherited ? 'gf-form-disabled' : ''; }; function ItemAvatar({ item }) { if (item.userAvatarUrl) { return <img className="filter-table__avatar" src={item.userAvatarUrl} />; } if (item.teamAvatarUrl) { return <img className="filter-table__avatar" src={item.teamAvatarUrl} />; } if (item.role === 'Editor') { return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-editor" />; } return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-viewer" />; } function ItemDescription({ item }) { if (item.userId) { return <span className="filter-table__weak-italic">(User)</span>; } if (item.teamId) { return <span className="filter-table__weak-italic">(Team)</span>; } return <span className="filter-table__weak-italic">(Role)</span>; } interface Props { item: DashboardAcl; onRemoveItem: (item: DashboardAcl) => void; onPermissionChanged: (item: DashboardAcl, level: PermissionLevel) => void; folderInfo?: FolderInfo; } export default class PermissionsListItem extends PureComponent<Props> { onPermissionChanged = option => { this.props.onPermissionChanged(this.props.item, option.value as PermissionLevel); }; onRemoveItem = () => { this.props.onRemoveItem(this.props.item); }; render() { const { item, folderInfo } = this.props; const inheritedFromRoot = item.dashboardId === -1 && !item.inherited; return ( <tr className={setClassNameHelper(item.inherited)}> <td style={{ width: '1%' }}> <ItemAvatar item={item} /> </td> <td style={{ width: '90%' }}> {item.name} <ItemDescription item={item} /> </td> <td> {item.inherited && folderInfo && ( <em className="muted no-wrap"> Inherited from folder{' '} <a className="text-link" href={`${folderInfo.url}/permissions`}> {folderInfo.title} </a>{' '} </em> )} {inheritedFromRoot && <em className="muted no-wrap">Default Permission</em>} </td> <td className="query-keyword">Can</td> <td> <div className="gf-form"> <DescriptionPicker optionsWithDesc={dashboardPermissionLevels} onSelected={this.onPermissionChanged} value={item.permission} disabled={item.inherited} className={'gf-form-select2__control--menu-right'} /> </div> </td> <td> {!item.inherited ? ( <a className="btn btn-danger btn-small" onClick={this.onRemoveItem}> <i className="fa fa-remove" /> </a> ) : ( <button className="btn btn-inverse btn-small"> <i className="fa fa-lock" /> </button> )} </td> </tr> ); } }
public/app/core/components/PermissionList/PermissionListItem.tsx
1
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.15869440138339996, 0.01634574681520462, 0.00016434006101917475, 0.0015917056007310748, 0.04507264494895935 ]
{ "id": 2, "code_window": [ " <td>\n", " <div className=\"gf-form\">\n", " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={() => {}}\n", " value={item.permission}\n", " disabled={true}\n", " className={'gf-form-input--form-dropdown-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/DisabledPermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 28 }
import _ from 'lodash'; import coreModule from 'app/core/core_module'; import config from 'app/core/config'; import { importPluginModule } from './plugin_loader'; export class DatasourceSrv { datasources: any; /** @ngInject */ constructor(private $q, private $injector, private $rootScope, private templateSrv) { this.init(); } init() { this.datasources = {}; } get(name?) { if (!name) { return this.get(config.defaultDatasource); } name = this.templateSrv.replace(name); if (name === 'default') { return this.get(config.defaultDatasource); } if (this.datasources[name]) { return this.$q.when(this.datasources[name]); } return this.loadDatasource(name); } loadDatasource(name) { const dsConfig = config.datasources[name]; if (!dsConfig) { return this.$q.reject({ message: 'Datasource named ' + name + ' was not found' }); } const deferred = this.$q.defer(); const pluginDef = dsConfig.meta; importPluginModule(pluginDef.module) .then(plugin => { // check if its in cache now if (this.datasources[name]) { deferred.resolve(this.datasources[name]); return; } // plugin module needs to export a constructor function named Datasource if (!plugin.Datasource) { throw new Error('Plugin module is missing Datasource constructor'); } const instance = this.$injector.instantiate(plugin.Datasource, { instanceSettings: dsConfig }); instance.meta = pluginDef; instance.name = name; this.datasources[name] = instance; deferred.resolve(instance); }) .catch(err => { this.$rootScope.appEvent('alert-error', [dsConfig.name + ' plugin failed', err.toString()]); }); return deferred.promise; } getAll() { return config.datasources; } getAnnotationSources() { const sources = []; this.addDataSourceVariables(sources); _.each(config.datasources, value => { if (value.meta && value.meta.annotations) { sources.push(value); } }); return sources; } getExploreSources() { const { datasources } = config; const es = Object.keys(datasources) .map(name => datasources[name]) .filter(ds => ds.meta && ds.meta.explore); return _.sortBy(es, ['name']); } getMetricSources(options) { const metricSources = []; _.each(config.datasources, (value, key) => { if (value.meta && value.meta.metrics) { let metricSource = { value: key, name: key, meta: value.meta, sort: key }; //Make sure grafana and mixed are sorted at the bottom if (value.meta.id === 'grafana') { metricSource.sort = String.fromCharCode(253); } else if (value.meta.id === 'mixed') { metricSource.sort = String.fromCharCode(254); } metricSources.push(metricSource); if (key === config.defaultDatasource) { metricSource = { value: null, name: 'default', meta: value.meta, sort: key }; metricSources.push(metricSource); } } }); if (!options || !options.skipVariables) { this.addDataSourceVariables(metricSources); } metricSources.sort((a, b) => { if (a.sort.toLowerCase() > b.sort.toLowerCase()) { return 1; } if (a.sort.toLowerCase() < b.sort.toLowerCase()) { return -1; } return 0; }); return metricSources; } addDataSourceVariables(list) { // look for data source variables for (let i = 0; i < this.templateSrv.variables.length; i++) { const variable = this.templateSrv.variables[i]; if (variable.type !== 'datasource') { continue; } let first = variable.current.value; if (first === 'default') { first = config.defaultDatasource; } const ds = config.datasources[first]; if (ds) { const key = `$${variable.name}`; list.push({ name: key, value: key, meta: ds.meta, sort: key, }); } } } } coreModule.service('datasourceSrv', DatasourceSrv); export default DatasourceSrv;
public/app/features/plugins/datasource_srv.ts
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.0001786783686839044, 0.00017345149535685778, 0.00016855580906849355, 0.00017368054250255227, 0.000002573441634012852 ]
{ "id": 2, "code_window": [ " <td>\n", " <div className=\"gf-form\">\n", " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={() => {}}\n", " value={item.permission}\n", " disabled={true}\n", " className={'gf-form-input--form-dropdown-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/DisabledPermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 28 }
import $ from 'jquery'; import { coreModule } from 'app/core/core'; const template = ` <span class="panel-title"> <span class="icon-gf panel-alert-icon"></span> <span class="panel-title-text">{{ctrl.panel.title | interpolateTemplateVars:this}}</span> <span class="panel-menu-container dropdown"> <span class="fa fa-caret-down panel-menu-toggle" data-toggle="dropdown"></span> <ul class="dropdown-menu dropdown-menu--menu panel-menu" role="menu"> <li> <a ng-click="ctrl.addDataQuery(datasource);"> <i class="fa fa-cog"></i> Edit <span class="dropdown-menu-item-shortcut">e</span> </a> </li> <li class="dropdown-submenu"> <a ng-click="ctrl.addDataQuery(datasource);"><i class="fa fa-cube"></i> Actions</a> <ul class="dropdown-menu panel-menu"> <li><a ng-click="ctrl.addDataQuery(datasource);"><i class="fa fa-flash"></i> Add Annotation</a></li> <li><a ng-click="ctrl.addDataQuery(datasource);"><i class="fa fa-bullseye"></i> Toggle Legend</a></li> <li><a ng-click="ctrl.addDataQuery(datasource);"><i class="fa fa-download"></i> Export to CSV</a></li> <li><a ng-click="ctrl.addDataQuery(datasource);"><i class="fa fa-eye"></i> View JSON</a></li> </ul> </li> <li><a ng-click="ctrl.addDataQuery(datasource);"><i class="fa fa-trash"></i> Remove</a></li> </ul> </span> <span class="panel-time-info" ng-if="ctrl.timeInfo"><i class="fa fa-clock-o"></i> {{ctrl.timeInfo}}</span> </span>`; function renderMenuItem(item, ctrl) { let html = ''; let listItemClass = ''; if (item.divider) { return '<li class="divider"></li>'; } if (item.submenu) { listItemClass = 'dropdown-submenu'; } html += `<li class="${listItemClass}"><a `; if (item.click) { html += ` ng-click="${item.click}"`; } if (item.href) { html += ` href="${item.href}"`; } html += `><i class="${item.icon}"></i>`; html += `<span class="dropdown-item-text">${item.text}</span>`; if (item.shortcut) { html += `<span class="dropdown-menu-item-shortcut">${item.shortcut}</span>`; } html += `</a>`; if (item.submenu) { html += '<ul class="dropdown-menu dropdown-menu--menu panel-menu">'; for (const subitem of item.submenu) { html += renderMenuItem(subitem, ctrl); } html += '</ul>'; } html += `</li>`; return html; } function createMenuTemplate(ctrl) { let html = ''; for (const item of ctrl.getMenu()) { html += renderMenuItem(item, ctrl); } return html; } /** @ngInject */ function panelHeader($compile) { return { restrict: 'E', template: template, link: (scope, elem, attrs) => { const menuElem = elem.find('.panel-menu'); let menuScope; let isDragged; elem.click(evt => { const targetClass = evt.target.className; // remove existing scope if (menuScope) { menuScope.$destroy(); } menuScope = scope.$new(); const menuHtml = createMenuTemplate(scope.ctrl); menuElem.html(menuHtml); $compile(menuElem)(menuScope); if (targetClass.indexOf('panel-title-text') >= 0 || targetClass.indexOf('panel-title') >= 0) { togglePanelMenu(evt); } }); elem.find('.panel-menu-toggle').click(() => { togglePanelStackPosition(); }); function togglePanelMenu(e) { if (!isDragged) { e.stopPropagation(); togglePanelStackPosition(); elem.find('[data-toggle=dropdown]').dropdown('toggle'); } } /** * Hack for adding special class 'dropdown-menu-open' to the panel. * This class sets z-index for panel and prevents menu overlapping. */ function togglePanelStackPosition() { const menuOpenClass = 'dropdown-menu-open'; const panelGridClass = '.react-grid-item.panel'; let panelElem = elem .find('[data-toggle=dropdown]') .parentsUntil('.panel') .parent(); const menuElem = elem.find('[data-toggle=dropdown]').parent(); panelElem = panelElem && panelElem.length ? panelElem[0] : undefined; if (panelElem) { panelElem = $(panelElem); $(panelGridClass).removeClass(menuOpenClass); const state = !menuElem.hasClass('open'); panelElem.toggleClass(menuOpenClass, state); } } let mouseX, mouseY; elem.mousedown(e => { mouseX = e.pageX; mouseY = e.pageY; }); elem.mouseup(e => { if (mouseX === e.pageX && mouseY === e.pageY) { isDragged = false; } else { isDragged = true; } }); }, }; } coreModule.directive('panelHeader', panelHeader);
public/app/features/panel/panel_header.ts
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.0012873925734311342, 0.00024088351347018033, 0.0001628991012694314, 0.00016827686340548098, 0.0002632873074617237 ]
{ "id": 2, "code_window": [ " <td>\n", " <div className=\"gf-form\">\n", " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={() => {}}\n", " value={item.permission}\n", " disabled={true}\n", " className={'gf-form-input--form-dropdown-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/DisabledPermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 28 }
package protocol import ( "io" "io/ioutil" "net/http" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" ) // PayloadUnmarshaler provides the interface for unmarshaling a payload's // reader into a SDK shape. type PayloadUnmarshaler interface { UnmarshalPayload(io.Reader, interface{}) error } // HandlerPayloadUnmarshal implements the PayloadUnmarshaler from a // HandlerList. This provides the support for unmarshaling a payload reader to // a shape without needing a SDK request first. type HandlerPayloadUnmarshal struct { Unmarshalers request.HandlerList } // UnmarshalPayload unmarshals the io.Reader payload into the SDK shape using // the Unmarshalers HandlerList provided. Returns an error if unable // unmarshaling fails. func (h HandlerPayloadUnmarshal) UnmarshalPayload(r io.Reader, v interface{}) error { req := &request.Request{ HTTPRequest: &http.Request{}, HTTPResponse: &http.Response{ StatusCode: 200, Header: http.Header{}, Body: ioutil.NopCloser(r), }, Data: v, } h.Unmarshalers.Run(req) return req.Error } // PayloadMarshaler provides the interface for marshaling a SDK shape into and // io.Writer. type PayloadMarshaler interface { MarshalPayload(io.Writer, interface{}) error } // HandlerPayloadMarshal implements the PayloadMarshaler from a HandlerList. // This provides support for marshaling a SDK shape into an io.Writer without // needing a SDK request first. type HandlerPayloadMarshal struct { Marshalers request.HandlerList } // MarshalPayload marshals the SDK shape into the io.Writer using the // Marshalers HandlerList provided. Returns an error if unable if marshal // fails. func (h HandlerPayloadMarshal) MarshalPayload(w io.Writer, v interface{}) error { req := request.New( aws.Config{}, metadata.ClientInfo{}, request.Handlers{}, nil, &request.Operation{HTTPMethod: "GET"}, v, nil, ) h.Marshalers.Run(req) if req.Error != nil { return req.Error } io.Copy(w, req.GetBody()) return nil }
vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.0003052269748877734, 0.00018442735017742962, 0.00016360581503249705, 0.00017075355572160333, 0.00004285021350369789 ]
{ "id": 3, "code_window": [ " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={this.onPermissionChanged}\n", " value={item.permission}\n", " disabled={item.inherited}\n", " className={'gf-form-select2__control--menu-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/PermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 79 }
import React, { PureComponent } from 'react'; import DescriptionPicker from 'app/core/components/Picker/DescriptionPicker'; import { dashboardPermissionLevels, DashboardAcl, PermissionLevel } from 'app/types/acl'; import { FolderInfo } from 'app/types'; const setClassNameHelper = inherited => { return inherited ? 'gf-form-disabled' : ''; }; function ItemAvatar({ item }) { if (item.userAvatarUrl) { return <img className="filter-table__avatar" src={item.userAvatarUrl} />; } if (item.teamAvatarUrl) { return <img className="filter-table__avatar" src={item.teamAvatarUrl} />; } if (item.role === 'Editor') { return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-editor" />; } return <i style={{ width: '25px', height: '25px' }} className="gicon gicon-viewer" />; } function ItemDescription({ item }) { if (item.userId) { return <span className="filter-table__weak-italic">(User)</span>; } if (item.teamId) { return <span className="filter-table__weak-italic">(Team)</span>; } return <span className="filter-table__weak-italic">(Role)</span>; } interface Props { item: DashboardAcl; onRemoveItem: (item: DashboardAcl) => void; onPermissionChanged: (item: DashboardAcl, level: PermissionLevel) => void; folderInfo?: FolderInfo; } export default class PermissionsListItem extends PureComponent<Props> { onPermissionChanged = option => { this.props.onPermissionChanged(this.props.item, option.value as PermissionLevel); }; onRemoveItem = () => { this.props.onRemoveItem(this.props.item); }; render() { const { item, folderInfo } = this.props; const inheritedFromRoot = item.dashboardId === -1 && !item.inherited; return ( <tr className={setClassNameHelper(item.inherited)}> <td style={{ width: '1%' }}> <ItemAvatar item={item} /> </td> <td style={{ width: '90%' }}> {item.name} <ItemDescription item={item} /> </td> <td> {item.inherited && folderInfo && ( <em className="muted no-wrap"> Inherited from folder{' '} <a className="text-link" href={`${folderInfo.url}/permissions`}> {folderInfo.title} </a>{' '} </em> )} {inheritedFromRoot && <em className="muted no-wrap">Default Permission</em>} </td> <td className="query-keyword">Can</td> <td> <div className="gf-form"> <DescriptionPicker optionsWithDesc={dashboardPermissionLevels} onSelected={this.onPermissionChanged} value={item.permission} disabled={item.inherited} className={'gf-form-select2__control--menu-right'} /> </div> </td> <td> {!item.inherited ? ( <a className="btn btn-danger btn-small" onClick={this.onRemoveItem}> <i className="fa fa-remove" /> </a> ) : ( <button className="btn btn-inverse btn-small"> <i className="fa fa-lock" /> </button> )} </td> </tr> ); } }
public/app/core/components/PermissionList/PermissionListItem.tsx
1
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.9747565984725952, 0.09279049187898636, 0.00016686155868228525, 0.0034640126395970583, 0.27893903851509094 ]
{ "id": 3, "code_window": [ " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={this.onPermissionChanged}\n", " value={item.permission}\n", " disabled={item.inherited}\n", " className={'gf-form-select2__control--menu-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/PermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 79 }
// mksyscall.pl -tags linux,sparc64 syscall_linux.go syscall_linux_sparc64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,sparc64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return }
vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.00023349712137132883, 0.0001692800724413246, 0.00015913161041680723, 0.0001687743642833084, 0.00000788442230259534 ]
{ "id": 3, "code_window": [ " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={this.onPermissionChanged}\n", " value={item.permission}\n", " disabled={item.inherited}\n", " className={'gf-form-select2__control--menu-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/PermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 79 }
// Copyright 2013 The Go 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 cldr import ( "bufio" "encoding/xml" "errors" "fmt" "strconv" "strings" "unicode" "unicode/utf8" ) // RuleProcessor can be passed to Collator's Process method, which // parses the rules and calls the respective method for each rule found. type RuleProcessor interface { Reset(anchor string, before int) error Insert(level int, str, context, extend string) error Index(id string) } const ( // cldrIndex is a Unicode-reserved sentinel value used to mark the start // of a grouping within an index. // We ignore any rule that starts with this rune. // See http://unicode.org/reports/tr35/#Collation_Elements for details. cldrIndex = "\uFDD0" // specialAnchor is the format in which to represent logical reset positions, // such as "first tertiary ignorable". specialAnchor = "<%s/>" ) // Process parses the rules for the tailorings of this collation // and calls the respective methods of p for each rule found. func (c Collation) Process(p RuleProcessor) (err error) { if len(c.Cr) > 0 { if len(c.Cr) > 1 { return fmt.Errorf("multiple cr elements, want 0 or 1") } return processRules(p, c.Cr[0].Data()) } if c.Rules.Any != nil { return c.processXML(p) } return errors.New("no tailoring data") } // processRules parses rules in the Collation Rule Syntax defined in // http://www.unicode.org/reports/tr35/tr35-collation.html#Collation_Tailorings. func processRules(p RuleProcessor, s string) (err error) { chk := func(s string, e error) string { if err == nil { err = e } return s } i := 0 // Save the line number for use after the loop. scanner := bufio.NewScanner(strings.NewReader(s)) for ; scanner.Scan() && err == nil; i++ { for s := skipSpace(scanner.Text()); s != "" && s[0] != '#'; s = skipSpace(s) { level := 5 var ch byte switch ch, s = s[0], s[1:]; ch { case '&': // followed by <anchor> or '[' <key> ']' if s = skipSpace(s); consume(&s, '[') { s = chk(parseSpecialAnchor(p, s)) } else { s = chk(parseAnchor(p, 0, s)) } case '<': // sort relation '<'{1,4}, optionally followed by '*'. for level = 1; consume(&s, '<'); level++ { } if level > 4 { err = fmt.Errorf("level %d > 4", level) } fallthrough case '=': // identity relation, optionally followed by *. if consume(&s, '*') { s = chk(parseSequence(p, level, s)) } else { s = chk(parseOrder(p, level, s)) } default: chk("", fmt.Errorf("illegal operator %q", ch)) break } } } if chk("", scanner.Err()); err != nil { return fmt.Errorf("%d: %v", i, err) } return nil } // parseSpecialAnchor parses the anchor syntax which is either of the form // ['before' <level>] <anchor> // or // [<label>] // The starting should already be consumed. func parseSpecialAnchor(p RuleProcessor, s string) (tail string, err error) { i := strings.IndexByte(s, ']') if i == -1 { return "", errors.New("unmatched bracket") } a := strings.TrimSpace(s[:i]) s = s[i+1:] if strings.HasPrefix(a, "before ") { l, err := strconv.ParseUint(skipSpace(a[len("before "):]), 10, 3) if err != nil { return s, err } return parseAnchor(p, int(l), s) } return s, p.Reset(fmt.Sprintf(specialAnchor, a), 0) } func parseAnchor(p RuleProcessor, level int, s string) (tail string, err error) { anchor, s, err := scanString(s) if err != nil { return s, err } return s, p.Reset(anchor, level) } func parseOrder(p RuleProcessor, level int, s string) (tail string, err error) { var value, context, extend string if value, s, err = scanString(s); err != nil { return s, err } if strings.HasPrefix(value, cldrIndex) { p.Index(value[len(cldrIndex):]) return } if consume(&s, '|') { if context, s, err = scanString(s); err != nil { return s, errors.New("missing string after context") } } if consume(&s, '/') { if extend, s, err = scanString(s); err != nil { return s, errors.New("missing string after extension") } } return s, p.Insert(level, value, context, extend) } // scanString scans a single input string. func scanString(s string) (str, tail string, err error) { if s = skipSpace(s); s == "" { return s, s, errors.New("missing string") } buf := [16]byte{} // small but enough to hold most cases. value := buf[:0] for s != "" { if consume(&s, '\'') { i := strings.IndexByte(s, '\'') if i == -1 { return "", "", errors.New(`unmatched single quote`) } if i == 0 { value = append(value, '\'') } else { value = append(value, s[:i]...) } s = s[i+1:] continue } r, sz := utf8.DecodeRuneInString(s) if unicode.IsSpace(r) || strings.ContainsRune("&<=#", r) { break } value = append(value, s[:sz]...) s = s[sz:] } return string(value), skipSpace(s), nil } func parseSequence(p RuleProcessor, level int, s string) (tail string, err error) { if s = skipSpace(s); s == "" { return s, errors.New("empty sequence") } last := rune(0) for s != "" { r, sz := utf8.DecodeRuneInString(s) s = s[sz:] if r == '-' { // We have a range. The first element was already written. if last == 0 { return s, errors.New("range without starter value") } r, sz = utf8.DecodeRuneInString(s) s = s[sz:] if r == utf8.RuneError || r < last { return s, fmt.Errorf("invalid range %q-%q", last, r) } for i := last + 1; i <= r; i++ { if err := p.Insert(level, string(i), "", ""); err != nil { return s, err } } last = 0 continue } if unicode.IsSpace(r) || unicode.IsPunct(r) { break } // normal case if err := p.Insert(level, string(r), "", ""); err != nil { return s, err } last = r } return s, nil } func skipSpace(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) } // consumes returns whether the next byte is ch. If so, it gobbles it by // updating s. func consume(s *string, ch byte) (ok bool) { if *s == "" || (*s)[0] != ch { return false } *s = (*s)[1:] return true } // The following code parses Collation rules of CLDR version 24 and before. var lmap = map[byte]int{ 'p': 1, 's': 2, 't': 3, 'i': 5, } type rulesElem struct { Rules struct { Common Any []*struct { XMLName xml.Name rule } `xml:",any"` } `xml:"rules"` } type rule struct { Value string `xml:",chardata"` Before string `xml:"before,attr"` Any []*struct { XMLName xml.Name rule } `xml:",any"` } var emptyValueError = errors.New("cldr: empty rule value") func (r *rule) value() (string, error) { // Convert hexadecimal Unicode codepoint notation to a string. s := charRe.ReplaceAllStringFunc(r.Value, replaceUnicode) r.Value = s if s == "" { if len(r.Any) != 1 { return "", emptyValueError } r.Value = fmt.Sprintf(specialAnchor, r.Any[0].XMLName.Local) r.Any = nil } else if len(r.Any) != 0 { return "", fmt.Errorf("cldr: XML elements found in collation rule: %v", r.Any) } return r.Value, nil } func (r rule) process(p RuleProcessor, name, context, extend string) error { v, err := r.value() if err != nil { return err } switch name { case "p", "s", "t", "i": if strings.HasPrefix(v, cldrIndex) { p.Index(v[len(cldrIndex):]) return nil } if err := p.Insert(lmap[name[0]], v, context, extend); err != nil { return err } case "pc", "sc", "tc", "ic": level := lmap[name[0]] for _, s := range v { if err := p.Insert(level, string(s), context, extend); err != nil { return err } } default: return fmt.Errorf("cldr: unsupported tag: %q", name) } return nil } // processXML parses the format of CLDR versions 24 and older. func (c Collation) processXML(p RuleProcessor) (err error) { // Collation is generated and defined in xml.go. var v string for _, r := range c.Rules.Any { switch r.XMLName.Local { case "reset": level := 0 switch r.Before { case "primary", "1": level = 1 case "secondary", "2": level = 2 case "tertiary", "3": level = 3 case "": default: return fmt.Errorf("cldr: unknown level %q", r.Before) } v, err = r.value() if err == nil { err = p.Reset(v, level) } case "x": var context, extend string for _, r1 := range r.Any { v, err = r1.value() switch r1.XMLName.Local { case "context": context = v case "extend": extend = v } } for _, r1 := range r.Any { if t := r1.XMLName.Local; t == "context" || t == "extend" { continue } r1.rule.process(p, r1.XMLName.Local, context, extend) } default: err = r.rule.process(p, r.XMLName.Local, "", "") } if err != nil { return err } } return nil }
vendor/golang.org/x/text/unicode/cldr/collate.go
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.0005577838164754212, 0.00018179015023633838, 0.0001598908711457625, 0.00017256729188375175, 0.00006370435585267842 ]
{ "id": 3, "code_window": [ " <DescriptionPicker\n", " optionsWithDesc={dashboardPermissionLevels}\n", " onSelected={this.onPermissionChanged}\n", " value={item.permission}\n", " disabled={item.inherited}\n", " className={'gf-form-select2__control--menu-right'}\n", " />\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/PermissionList/PermissionListItem.tsx", "type": "replace", "edit_start_line_idx": 79 }
// // Dropdown menus // -------------------------------------------------- // Use the .menu class on any <li> element within the topbar or ul.tabs and you'll get some superfancy dropdowns .dropup, .dropdown { position: relative; } .dropdown-toggle:active, .open .dropdown-toggle { outline: 0; } .dropdown-desc { position: relative; top: -3px; width: 250px; font-size: $font-size-sm; margin-left: 22px; color: $gray-2; white-space: normal; } // Dropdown arrow/caret // -------------------- .caret { display: inline-block; width: 0; height: 0; vertical-align: top; border-top: 4px solid $text-color-weak; border-right: 4px solid transparent; border-left: 4px solid transparent; content: ''; } // Place the caret .dropdown .caret { margin-top: 8px; margin-left: 2px; } // The dropdown menu (ul) // ---------------------- .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: $zindex-dropdown; display: none; // none by default, but block on "open" of the menu float: left; min-width: 140px; margin: 2px 0 0; // override default ul list-style: none; background-color: $dropdownBackground; border: 1px solid #ccc; // Fallback for IE7-8 border: 1px solid $dropdownBorder; text-align: left; // Aligns the dropdown menu to right &.pull-right { right: 0; left: auto; } .divider { height: 0.1rem; margin: 0.5rem 0; // 8px 1px overflow: hidden; background-color: $dropdownDividerTop; border-bottom: 1px solid $dropdownDividerBottom; } // Links within the dropdown menu > li { > a { display: block; padding: 3px 20px 3px 15px; clear: both; font-weight: normal; line-height: $line-height-base; color: $dropdownLinkColor; white-space: nowrap; i { display: inline-block; margin-right: 10px; color: $link-color-disabled; position: relative; top: 3px; } .gicon { opacity: 0.9; } } } &--navbar { top: 100%; min-width: 100%; } &--menu, &--navbar, &--sidemenu { background: $menu-dropdown-bg; box-shadow: $menu-dropdown-shadow; margin-top: 0px; border: none; > li > a { display: flex; padding: 5px 10px; border-left: 2px solid transparent; &:hover { @include left-brand-border-gradient(); color: $link-hover-color; background: $menu-dropdown-hover-bg !important; } } } &--sidemenu { li.sidemenu-org-switcher { > a { padding: 8px 10px 8px 15px; } } } } .dropdown-item-text { flex-grow: 1; } // Hover/Focus state // ----------- .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus, .dropdown-submenu:hover > a, .dropdown-submenu:focus > a { text-decoration: none; color: $dropdownLinkColorHover; background-color: $dropdownLinkBackgroundHover; } // Active state // ------------ .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: $dropdownLinkColorActive; text-decoration: none; outline: 0; background-color: $dropdownLinkBackgroundHover; } // Disabled state // -------------- // Gray out text and ensure the hover/focus state remains gray .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: $gray-2; } // Nuke hover/focus effects .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; background-color: transparent; background-image: none; // Remove CSS gradient cursor: default; } // Open state for the dropdown // --------------------------- .open { & > .dropdown-menu { display: block; } &.cascade-open { .dropdown-menu { display: block; } } } // Backdrop to catch body clicks on mobile, etc. // --------------------------- .dropdown-backdrop { position: fixed; left: 0; right: 0; bottom: 0; top: 0; z-index: $zindex-dropdown - 10; } // Right aligned dropdowns // --------------------------- .pull-right > .dropdown-menu { right: 0; left: auto; } // Allow for dropdowns to go bottom up (aka, dropup-menu) // ------------------------------------------------------ // Just add .dropup after the standard .dropdown class and you're set, bro. // TODO: abstract this so that the navbar fixed styles are not placed here? .dropup, .navbar-fixed-bottom .dropdown { // Reverse the caret .caret { border-top: 0; border-bottom: 4px solid $black; content: ''; } // Different positioning for bottom up menu .dropdown-menu { top: auto; bottom: 0; margin-bottom: 1px; } } // Sub menus // --------------------------- .dropdown-submenu { position: relative; } // Default dropdowns .dropdown-submenu > .dropdown-menu { top: 0; left: 100%; margin-top: 0px; margin-left: -1px; @include border-radius(0 6px 6px 6px); } .dropdown-submenu:hover > .dropdown-menu { display: block; } // Dropups .dropup .dropdown-submenu > .dropdown-menu { top: auto; bottom: 0; margin-top: 0; margin-bottom: -2px; @include border-radius(5px 5px 5px 0); } // Caret to indicate there is a submenu .dropdown-submenu > a::after { position: absolute; top: 35%; right: $input-padding-x; background-color: transparent; color: $text-color-weak; font: normal normal normal $font-size-sm/1 FontAwesome; content: '\f0da'; pointer-events: none; font-size: 11px; } .dropdown-submenu:hover > a::after { border-left-color: $dropdownLinkColorHover; } // Left aligned submenus .dropdown-submenu.pull-left { // Undo the float // Yes, this is awkward since .pull-left adds a float, but it sticks to our conventions elsewhere. float: none; // Positioning the submenu > .dropdown-menu { left: -100%; margin-left: 10px; @include border-radius(6px 0 6px 6px); } } // Tweak nav headers // ----------------- // Increase padding from 15px to 20px on sides .dropdown .dropdown-menu .nav-header { padding-left: 20px; padding-right: 20px; } // Typeahead // --------- .typeahead { z-index: $zindex-typeahead; margin-top: 2px; // give it some space to breathe } .dropdown-menu-item-shortcut { display: block; margin-left: $spacer; color: $text-muted; min-width: 47px; &::before { font-family: FontAwesome; width: 2rem; display: inline-block; text-align: center; content: '\f11c'; } } .dropdown-menu.dropdown-menu--new { li a { padding: $spacer/2 $spacer; border-left: 2px solid $side-menu-bg; background: $side-menu-bg; i { display: inline-block; padding-right: 21px; } &:hover { @include left-brand-border-gradient(); color: $link-hover-color; background: $input-label-bg; } } }
public/sass/components/_dropdown.scss
0
https://github.com/grafana/grafana/commit/087ff2fa7479e52a451814ae8b2628c8ace28c7d
[ 0.00017599912825971842, 0.00016966683324426413, 0.00016262053395621479, 0.00016967111150734127, 0.0000031907752600091044 ]
{ "id": 0, "code_window": [ "\treadonly keyMods: IKeyMods;\n", "\n", "\tvalueSelection: Readonly<[number, number]> | undefined;\n", "\n", "\tvalidationMessage: string | undefined;\n", "}\n", "\n", "export interface IInputBox extends IQuickInput {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tinputHasFocus(): boolean;\n" ], "file_path": "src/vs/platform/quickinput/common/quickInput.ts", "type": "add", "edit_start_line_idx": 197 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick, IQuickInputButton } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen, FileFilter } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private acceptButton: IQuickInputButton; private fallbackListItem: FileQuickPickItem | undefined; private options: IOpenDialogOptions; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private filters: FileFilter[] | undefined; private hidden: boolean; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; private shouldOverwriteFile: boolean = false; constructor( @IFileService private readonly fileService: IFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; const openFileString = nls.localize('remoteFileDialog.localFileFallback', '(Open Local File)'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', '(Open Local Folder)'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', '(Open Local File or Folder)'); let fallbackLabel = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackListItem = this.getFallbackFileSystem(fallbackLabel); return this.pickResource().then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.fileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; this.options.canSelectFolders = true; this.options.canSelectFiles = true; this.fallbackListItem = this.getFallbackFileSystem(nls.localize('remoteFileDialog.localSaveFallback', '(Save Local File)')); return new Promise<URI | undefined>((resolve) => { this.pickResource(true).then(folderUri => { resolve(folderUri); }); }); } private async getOptions(options: ISaveDialogOptions | IOpenDialogOptions): Promise<IOpenDialogOptions | undefined> { let defaultUri = options.defaultUri; if (!defaultUri) { const env = await this.remoteAgentService.getEnvironment(); if (env) { defaultUri = env.userHome; } else { defaultUri = URI.from({ scheme: this.scheme, path: this.environmentService.userHome }); } } if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string { return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private getFallbackFileSystem(label: string): FileQuickPickItem | undefined { if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { return { label: label, uri: URI.from({ scheme: this.options.availableFileSystems[1] }), isFolder: true }; } return undefined; } private async pickResource(isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!this.options.canSelectFolders; this.allowFileSelection = !!this.options.canSelectFiles; this.hidden = false; let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (this.options.defaultUri) { try { stat = await this.fileService.resolveFile(this.options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(this.options.defaultUri); trailing = resources.basename(this.options.defaultUri); } // append extension if (isSave && !ext && this.options.filters) { for (let i = 0; i < this.options.filters.length; i++) { if (this.options.filters[i].extensions[0] !== '*') { ext = '.' + this.options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: this.options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolving = false; let isAcceptHandled = false; this.currentFolder = homedir; this.filePickBox.buttons = [this.acceptButton]; this.filePickBox.onDidTriggerButton(_ => { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolving = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.title = this.options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; isResolving = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { this.filePickBox.hide(); resolve(resolveValue); } else if (this.hidden) { resolve(undefined); } else { isResolving = false; isAcceptHandled = false; } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { this.filePickBox.validationMessage = undefined; this.shouldOverwriteFile = false; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value)); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { this.hidden = true; if (!isResolving) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } else { this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { // Check if Open Local has been selected const selectedItems: ReadonlyArray<FileQuickPickItem> = this.filePickBox.selectedItems; if (selectedItems && (selectedItems.length > 0) && (selectedItems[0] === this.fallbackListItem)) { if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { this.options.availableFileSystems.shift(); } if (this.requiresTrailing) { return this.fileDialogService.showSaveDialog(this.options).then(result => { return result; }); } else { return this.fileDialogService.showOpenDialog(this.options).then(result => { return result ? result[0] : undefined; }); } } let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(inputUriDirname); stat = await this.fileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.fileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.fileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(resources.dirname(uri)); stat = await this.fileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.'); return Promise.resolve(false); } else if (stat && !this.shouldOverwriteFile) { // Replacing a file. this.shouldOverwriteFile = true; this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri)); return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.'); return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.'); return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.'); return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const folder = await this.fileService.resolveFile(currentFolder); const fileNames = folder.children ? folder.children.map(child => child.name) : []; const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } if (this.fallbackListItem) { sorted.push(this.fallbackListItem); } return sorted; } private filterFile(file: URI): boolean { if (this.filters) { const ext = resources.extname(file); for (let i = 0; i < this.filters.length; i++) { for (let j = 0; j < this.filters[i].extensions.length; j++) { if (ext === ('.' + this.filters[i].extensions[j])) { return true; } } } return false; } return true; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.fileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return undefined; } catch (e) { return undefined; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.9992026686668396, 0.018081869930028915, 0.00016690643678884953, 0.0001741764135658741, 0.13112130761146545 ]
{ "id": 0, "code_window": [ "\treadonly keyMods: IKeyMods;\n", "\n", "\tvalueSelection: Readonly<[number, number]> | undefined;\n", "\n", "\tvalidationMessage: string | undefined;\n", "}\n", "\n", "export interface IInputBox extends IQuickInput {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tinputHasFocus(): boolean;\n" ], "file_path": "src/vs/platform/quickinput/common/quickInput.ts", "type": "add", "edit_start_line_idx": 197 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const path = require('path'); module.exports = { entry: { index: './preview-src/index.ts', pre: './preview-src/pre.ts' }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, devtool: 'inline-source-map', output: { filename: '[name].js', path: path.resolve(__dirname, 'media') } };
extensions/markdown-language-features/webpack.config.js
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017519379616715014, 0.00017347380344290286, 0.00017113839567173272, 0.00017408924759365618, 0.0000017118484265665757 ]
{ "id": 0, "code_window": [ "\treadonly keyMods: IKeyMods;\n", "\n", "\tvalueSelection: Readonly<[number, number]> | undefined;\n", "\n", "\tvalidationMessage: string | undefined;\n", "}\n", "\n", "export interface IInputBox extends IQuickInput {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tinputHasFocus(): boolean;\n" ], "file_path": "src/vs/platform/quickinput/common/quickInput.ts", "type": "add", "edit_start_line_idx": 197 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.784 8L13 11.217 11.215 13 8.001 9.786 4.785 13 3 11.216l3.214-3.215L3 4.785 4.784 3 8 6.216 11.216 3 13 4.785 9.784 8.001z" fill="#424242"/></svg>
src/vs/base/browser/ui/dialog/close.svg
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0001724723697407171, 0.0001724723697407171, 0.0001724723697407171, 0.0001724723697407171, 0 ]
{ "id": 0, "code_window": [ "\treadonly keyMods: IKeyMods;\n", "\n", "\tvalueSelection: Readonly<[number, number]> | undefined;\n", "\n", "\tvalidationMessage: string | undefined;\n", "}\n", "\n", "export interface IInputBox extends IQuickInput {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tinputHasFocus(): boolean;\n" ], "file_path": "src/vs/platform/quickinput/common/quickInput.ts", "type": "add", "edit_start_line_idx": 197 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" enable-background="new 0 0 16 16" height="16" width="16"><path fill="#1E1E1E" d="M13.5 4.2C13.1 2.1 10.8 0 9.3 0H6.7c-.4 0-.6.2-.6.2C4 .8 2.5 2.7 2.5 4.9c0 .5-.1 2.3 1.7 3.8.5.5 1.2 2 1.3 2.4v3.3L7.1 16h2l1.5-1.6V11c.1-.4.8-1.9 1.3-2.3 1.1-.9 1.5-1.9 1.6-2.7V4.2z"/><g><g fill="#C5C5C5"><path d="M6.5 12h3v1h-3zM7.5 15h1.1l.9-1h-3z"/></g><path fill="#DDB204" d="M12.6 5c0-2.3-1.8-4.1-4.1-4.1-.1 0-1.4.1-1.4.1-2.1.3-3.7 2-3.7 4 0 .1-.2 1.6 1.4 3 .7.7 1.5 2.4 1.6 2.9l.1.1h3l.1-.2c.1-.5.9-2.2 1.6-2.9 1.6-1.3 1.4-2.8 1.4-2.9zm-3 1l-.5 3h-.6V6c1.1 0 .9-1 .9-1H6.5v.1c0 .2.1.9 1 .9v3H7l-.2-.7L6.5 6c-.7 0-.9-.4-1-.7v-.4c0-.8.9-.9.9-.9h3.1s1 .1 1 1c0 0 .1 1-.9 1z"/></g><path fill="#252526" d="M10.5 5c0-.9-1-1-1-1H6.4s-.9.1-.9.9v.4c0 .3.3.7.9.7l.4 2.3.2.7h.5V6c-1 0-1-.7-1-.9V5h3s.1 1-.9 1v3h.6l.5-3c.9 0 .8-1 .8-1z"/></svg>
src/vs/workbench/contrib/markers/browser/media/lightbulb-dark.svg
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0021779504604637623, 0.0021779504604637623, 0.0021779504604637623, 0.0021779504604637623, 0 ]
{ "id": 1, "code_window": [ "\t\tthis.update();\n", "\t}\n", "\n", "\tonDidChangeSelection = this.onDidChangeSelectionEmitter.event;\n", "\n", "\tonDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tpublic inputHasFocus(): boolean {\n", "\t\treturn this.visible ? this.ui.inputBox.hasFocus() : false;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "add", "edit_start_line_idx": 465 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick, IQuickInputButton } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen, FileFilter } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private acceptButton: IQuickInputButton; private fallbackListItem: FileQuickPickItem | undefined; private options: IOpenDialogOptions; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private filters: FileFilter[] | undefined; private hidden: boolean; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; private shouldOverwriteFile: boolean = false; constructor( @IFileService private readonly fileService: IFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; const openFileString = nls.localize('remoteFileDialog.localFileFallback', '(Open Local File)'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', '(Open Local Folder)'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', '(Open Local File or Folder)'); let fallbackLabel = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackListItem = this.getFallbackFileSystem(fallbackLabel); return this.pickResource().then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.fileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; this.options.canSelectFolders = true; this.options.canSelectFiles = true; this.fallbackListItem = this.getFallbackFileSystem(nls.localize('remoteFileDialog.localSaveFallback', '(Save Local File)')); return new Promise<URI | undefined>((resolve) => { this.pickResource(true).then(folderUri => { resolve(folderUri); }); }); } private async getOptions(options: ISaveDialogOptions | IOpenDialogOptions): Promise<IOpenDialogOptions | undefined> { let defaultUri = options.defaultUri; if (!defaultUri) { const env = await this.remoteAgentService.getEnvironment(); if (env) { defaultUri = env.userHome; } else { defaultUri = URI.from({ scheme: this.scheme, path: this.environmentService.userHome }); } } if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string { return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private getFallbackFileSystem(label: string): FileQuickPickItem | undefined { if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { return { label: label, uri: URI.from({ scheme: this.options.availableFileSystems[1] }), isFolder: true }; } return undefined; } private async pickResource(isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!this.options.canSelectFolders; this.allowFileSelection = !!this.options.canSelectFiles; this.hidden = false; let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (this.options.defaultUri) { try { stat = await this.fileService.resolveFile(this.options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(this.options.defaultUri); trailing = resources.basename(this.options.defaultUri); } // append extension if (isSave && !ext && this.options.filters) { for (let i = 0; i < this.options.filters.length; i++) { if (this.options.filters[i].extensions[0] !== '*') { ext = '.' + this.options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: this.options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolving = false; let isAcceptHandled = false; this.currentFolder = homedir; this.filePickBox.buttons = [this.acceptButton]; this.filePickBox.onDidTriggerButton(_ => { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolving = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.title = this.options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; isResolving = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { this.filePickBox.hide(); resolve(resolveValue); } else if (this.hidden) { resolve(undefined); } else { isResolving = false; isAcceptHandled = false; } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { this.filePickBox.validationMessage = undefined; this.shouldOverwriteFile = false; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value)); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { this.hidden = true; if (!isResolving) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } else { this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { // Check if Open Local has been selected const selectedItems: ReadonlyArray<FileQuickPickItem> = this.filePickBox.selectedItems; if (selectedItems && (selectedItems.length > 0) && (selectedItems[0] === this.fallbackListItem)) { if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { this.options.availableFileSystems.shift(); } if (this.requiresTrailing) { return this.fileDialogService.showSaveDialog(this.options).then(result => { return result; }); } else { return this.fileDialogService.showOpenDialog(this.options).then(result => { return result ? result[0] : undefined; }); } } let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(inputUriDirname); stat = await this.fileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.fileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.fileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(resources.dirname(uri)); stat = await this.fileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.'); return Promise.resolve(false); } else if (stat && !this.shouldOverwriteFile) { // Replacing a file. this.shouldOverwriteFile = true; this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri)); return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.'); return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.'); return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.'); return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const folder = await this.fileService.resolveFile(currentFolder); const fileNames = folder.children ? folder.children.map(child => child.name) : []; const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } if (this.fallbackListItem) { sorted.push(this.fallbackListItem); } return sorted; } private filterFile(file: URI): boolean { if (this.filters) { const ext = resources.extname(file); for (let i = 0; i < this.filters.length; i++) { for (let j = 0; j < this.filters[i].extensions.length; j++) { if (ext === ('.' + this.filters[i].extensions[j])) { return true; } } } return false; } return true; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.fileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return undefined; } catch (e) { return undefined; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0201845932751894, 0.0005713962018489838, 0.00016469786351080984, 0.00017014455806929618, 0.0026369832921773195 ]
{ "id": 1, "code_window": [ "\t\tthis.update();\n", "\t}\n", "\n", "\tonDidChangeSelection = this.onDidChangeSelectionEmitter.event;\n", "\n", "\tonDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tpublic inputHasFocus(): boolean {\n", "\t\treturn this.visible ? this.ui.inputBox.hasFocus() : false;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "add", "edit_start_line_idx": 465 }
{ "editor.insertSpaces": false, "files.trimTrailingWhitespace": true, "files.exclude": { ".git": true, ".build": true, "**/.DS_Store": true, "build/**/*.js": { "when": "$(basename).ts" } }, "files.associations": { "cglicenses.json": "jsonc" }, "search.exclude": { "**/node_modules": true, "**/bower_components": true, ".build/**": true, "out/**": true, "out-build/**": true, "out-vscode/**": true, "i18n/**": true, "extensions/**/out/**": true, "test/smoke/out/**": true, "src/vs/base/test/node/uri.test.data.txt": true }, "lcov.path": [ "./.build/coverage/lcov.info", "./.build/coverage-single/lcov.info" ], "lcov.watch": [ { "pattern": "**/*.test.js", "command": "${workspaceFolder}/scripts/test.sh --coverage --run ${file}", "windows": { "command": "${workspaceFolder}\\scripts\\test.bat --coverage --run ${file}" } } ], "typescript.tsdk": "node_modules/typescript/lib", "npm.exclude": "**/extensions/**", "emmet.excludeLanguages": [], "typescript.preferences.importModuleSpecifier": "non-relative", "typescript.preferences.quoteStyle": "single", "json.schemas": [ { "fileMatch": [ "cgmanifest.json" ], "url": "./.vscode/cgmanifest.schema.json" }, { "fileMatch": [ "cglicenses.json" ], "url": "./.vscode/cglicenses.schema.json" } ], "git.ignoreLimitWarning": true }
.vscode/settings.json
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017517490778118372, 0.000171587715158239, 0.00016990333097055554, 0.00017096615920308977, 0.000001643573455112346 ]
{ "id": 1, "code_window": [ "\t\tthis.update();\n", "\t}\n", "\n", "\tonDidChangeSelection = this.onDidChangeSelectionEmitter.event;\n", "\n", "\tonDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tpublic inputHasFocus(): boolean {\n", "\t\treturn this.visible ? this.ui.inputBox.hasFocus() : false;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "add", "edit_start_line_idx": 465 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./sash'; import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { isIPad } from 'vs/base/browser/browser'; import { isMacintosh } from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { EventType, GestureEvent, Gesture } from 'vs/base/browser/touch'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { Event, Emitter } from 'vs/base/common/event'; import { getElementsByTagName, EventHelper, createStyleSheet, addDisposableListener, append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom'; import { domEvent } from 'vs/base/browser/event'; const DEBUG = false; export interface ISashLayoutProvider { } export interface IVerticalSashLayoutProvider extends ISashLayoutProvider { getVerticalSashLeft(sash: Sash): number; getVerticalSashTop?(sash: Sash): number; getVerticalSashHeight?(sash: Sash): number; } export interface IHorizontalSashLayoutProvider extends ISashLayoutProvider { getHorizontalSashTop(sash: Sash): number; getHorizontalSashLeft?(sash: Sash): number; getHorizontalSashWidth?(sash: Sash): number; } export interface ISashEvent { startX: number; currentX: number; startY: number; currentY: number; altKey: boolean; } export interface ISashOptions { orientation?: Orientation; orthogonalStartSash?: Sash; orthogonalEndSash?: Sash; } export const enum Orientation { VERTICAL, HORIZONTAL } export const enum SashState { Disabled, Minimum, Maximum, Enabled } export class Sash extends Disposable { private el: HTMLElement; private layoutProvider: ISashLayoutProvider; private hidden: boolean; private orientation: Orientation; private _state: SashState = SashState.Enabled; get state(): SashState { return this._state; } set state(state: SashState) { if (this._state === state) { return; } toggleClass(this.el, 'disabled', state === SashState.Disabled); toggleClass(this.el, 'minimum', state === SashState.Minimum); toggleClass(this.el, 'maximum', state === SashState.Maximum); this._state = state; this._onDidEnablementChange.fire(state); } private readonly _onDidEnablementChange = this._register(new Emitter<SashState>()); readonly onDidEnablementChange: Event<SashState> = this._onDidEnablementChange.event; private readonly _onDidStart = this._register(new Emitter<ISashEvent>()); readonly onDidStart: Event<ISashEvent> = this._onDidStart.event; private readonly _onDidChange = this._register(new Emitter<ISashEvent>()); readonly onDidChange: Event<ISashEvent> = this._onDidChange.event; private readonly _onDidReset = this._register(new Emitter<void>()); readonly onDidReset: Event<void> = this._onDidReset.event; private readonly _onDidEnd = this._register(new Emitter<void>()); readonly onDidEnd: Event<void> = this._onDidEnd.event; linkedSash: Sash | undefined = undefined; private orthogonalStartSashDisposables: IDisposable[] = []; private _orthogonalStartSash: Sash | undefined; get orthogonalStartSash(): Sash | undefined { return this._orthogonalStartSash; } set orthogonalStartSash(sash: Sash | undefined) { this.orthogonalStartSashDisposables = dispose(this.orthogonalStartSashDisposables); if (sash) { sash.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange, this, this.orthogonalStartSashDisposables); this.onOrthogonalStartSashEnablementChange(sash.state); } else { this.onOrthogonalStartSashEnablementChange(SashState.Disabled); } this._orthogonalStartSash = sash; } private orthogonalEndSashDisposables: IDisposable[] = []; private _orthogonalEndSash: Sash | undefined; get orthogonalEndSash(): Sash | undefined { return this._orthogonalEndSash; } set orthogonalEndSash(sash: Sash | undefined) { this.orthogonalEndSashDisposables = dispose(this.orthogonalEndSashDisposables); if (sash) { sash.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange, this, this.orthogonalEndSashDisposables); this.onOrthogonalEndSashEnablementChange(sash.state); } else { this.onOrthogonalEndSashEnablementChange(SashState.Disabled); } this._orthogonalEndSash = sash; } constructor(container: HTMLElement, layoutProvider: ISashLayoutProvider, options: ISashOptions = {}) { super(); this.el = append(container, $('.monaco-sash')); if (isMacintosh) { addClass(this.el, 'mac'); } this._register(domEvent(this.el, 'mousedown')(this.onMouseDown, this)); this._register(domEvent(this.el, 'dblclick')(this.onMouseDoubleClick, this)); Gesture.addTarget(this.el); this._register(domEvent(this.el, EventType.Start)(this.onTouchStart, this)); if (isIPad) { // see also http://ux.stackexchange.com/questions/39023/what-is-the-optimum-button-size-of-touch-screen-applications addClass(this.el, 'touch'); } this.setOrientation(options.orientation || Orientation.VERTICAL); this.hidden = false; this.layoutProvider = layoutProvider; this.orthogonalStartSash = options.orthogonalStartSash; this.orthogonalEndSash = options.orthogonalEndSash; toggleClass(this.el, 'debug', DEBUG); } setOrientation(orientation: Orientation): void { this.orientation = orientation; if (this.orientation === Orientation.HORIZONTAL) { addClass(this.el, 'horizontal'); removeClass(this.el, 'vertical'); } else { removeClass(this.el, 'horizontal'); addClass(this.el, 'vertical'); } if (this.layoutProvider) { this.layout(); } } private onMouseDown(e: MouseEvent): void { EventHelper.stop(e, false); let isMultisashResize = false; if (this.linkedSash && !(e as any).__linkedSashEvent) { (e as any).__linkedSashEvent = true; this.linkedSash.onMouseDown(e); } if (!(e as any).__orthogonalSashEvent) { let orthogonalSash: Sash | undefined; if (this.orientation === Orientation.VERTICAL) { if (e.offsetY <= 4) { orthogonalSash = this.orthogonalStartSash; } else if (e.offsetY >= this.el.clientHeight - 4) { orthogonalSash = this.orthogonalEndSash; } } else { if (e.offsetX <= 4) { orthogonalSash = this.orthogonalStartSash; } else if (e.offsetX >= this.el.clientWidth - 4) { orthogonalSash = this.orthogonalEndSash; } } if (orthogonalSash) { isMultisashResize = true; (e as any).__orthogonalSashEvent = true; orthogonalSash.onMouseDown(e); } } if (!this.state) { return; } const iframes = getElementsByTagName('iframe'); for (const iframe of iframes) { iframe.style.pointerEvents = 'none'; // disable mouse events on iframes as long as we drag the sash } const mouseDownEvent = new StandardMouseEvent(e); const startX = mouseDownEvent.posx; const startY = mouseDownEvent.posy; const altKey = mouseDownEvent.altKey; const startEvent: ISashEvent = { startX, currentX: startX, startY, currentY: startY, altKey }; addClass(this.el, 'active'); this._onDidStart.fire(startEvent); // fix https://github.com/Microsoft/vscode/issues/21675 const style = createStyleSheet(this.el); const updateStyle = () => { let cursor = ''; if (isMultisashResize) { cursor = 'all-scroll'; } else if (this.orientation === Orientation.HORIZONTAL) { if (this.state === SashState.Minimum) { cursor = 's-resize'; } else if (this.state === SashState.Maximum) { cursor = 'n-resize'; } else { cursor = isMacintosh ? 'row-resize' : 'ns-resize'; } } else { if (this.state === SashState.Minimum) { cursor = 'e-resize'; } else if (this.state === SashState.Maximum) { cursor = 'w-resize'; } else { cursor = isMacintosh ? 'col-resize' : 'ew-resize'; } } style.innerHTML = `* { cursor: ${cursor} !important; }`; }; const disposables: IDisposable[] = []; updateStyle(); if (!isMultisashResize) { this.onDidEnablementChange(updateStyle, null, disposables); } const onMouseMove = (e: MouseEvent) => { EventHelper.stop(e, false); const mouseMoveEvent = new StandardMouseEvent(e); const event: ISashEvent = { startX, currentX: mouseMoveEvent.posx, startY, currentY: mouseMoveEvent.posy, altKey }; this._onDidChange.fire(event); }; const onMouseUp = (e: MouseEvent) => { EventHelper.stop(e, false); this.el.removeChild(style); removeClass(this.el, 'active'); this._onDidEnd.fire(); dispose(disposables); const iframes = getElementsByTagName('iframe'); for (const iframe of iframes) { iframe.style.pointerEvents = 'auto'; } }; domEvent(window, 'mousemove')(onMouseMove, null, disposables); domEvent(window, 'mouseup')(onMouseUp, null, disposables); } private onMouseDoubleClick(event: MouseEvent): void { this._onDidReset.fire(); } private onTouchStart(event: GestureEvent): void { EventHelper.stop(event); const listeners: IDisposable[] = []; const startX = event.pageX; const startY = event.pageY; const altKey = event.altKey; this._onDidStart.fire({ startX: startX, currentX: startX, startY: startY, currentY: startY, altKey }); listeners.push(addDisposableListener(this.el, EventType.Change, (event: GestureEvent) => { if (types.isNumber(event.pageX) && types.isNumber(event.pageY)) { this._onDidChange.fire({ startX: startX, currentX: event.pageX, startY: startY, currentY: event.pageY, altKey }); } })); listeners.push(addDisposableListener(this.el, EventType.End, (event: GestureEvent) => { this._onDidEnd.fire(); dispose(listeners); })); } layout(): void { const size = isIPad ? 20 : 4; if (this.orientation === Orientation.VERTICAL) { const verticalProvider = (<IVerticalSashLayoutProvider>this.layoutProvider); this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (size / 2) + 'px'; if (verticalProvider.getVerticalSashTop) { this.el.style.top = verticalProvider.getVerticalSashTop(this) + 'px'; } if (verticalProvider.getVerticalSashHeight) { this.el.style.height = verticalProvider.getVerticalSashHeight(this) + 'px'; } } else { const horizontalProvider = (<IHorizontalSashLayoutProvider>this.layoutProvider); this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (size / 2) + 'px'; if (horizontalProvider.getHorizontalSashLeft) { this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px'; } if (horizontalProvider.getHorizontalSashWidth) { this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px'; } } } show(): void { this.hidden = false; this.el.style.removeProperty('display'); this.el.setAttribute('aria-hidden', 'false'); } hide(): void { this.hidden = true; this.el.style.display = 'none'; this.el.setAttribute('aria-hidden', 'true'); } isHidden(): boolean { return this.hidden; } private onOrthogonalStartSashEnablementChange(state: SashState): void { toggleClass(this.el, 'orthogonal-start', state !== SashState.Disabled); } private onOrthogonalEndSashEnablementChange(state: SashState): void { toggleClass(this.el, 'orthogonal-end', state !== SashState.Disabled); } dispose(): void { super.dispose(); this.orthogonalStartSashDisposables = dispose(this.orthogonalStartSashDisposables); this.orthogonalEndSashDisposables = dispose(this.orthogonalEndSashDisposables); if (this.el && this.el.parentElement) { this.el.parentElement.removeChild(this.el); } this.el = null!; // StrictNullOverride: nulling out ok in dispose } }
src/vs/base/browser/ui/sash/sash.ts
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.015391133725643158, 0.001021365518681705, 0.00016263742872979492, 0.0001689920318312943, 0.0028705911245197058 ]
{ "id": 1, "code_window": [ "\t\tthis.update();\n", "\t}\n", "\n", "\tonDidChangeSelection = this.onDidChangeSelectionEmitter.event;\n", "\n", "\tonDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tpublic inputHasFocus(): boolean {\n", "\t\treturn this.visible ? this.ui.inputBox.hasFocus() : false;\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInput.ts", "type": "add", "edit_start_line_idx": 465 }
{ "comments": { "blockComment": ["/*", "*/"], "lineComment": "//" }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}", "notIn": ["string", "comment"] }, { "open": "[", "close": "]", "notIn": ["string", "comment"] }, { "open": "(", "close": ")", "notIn": ["string", "comment"] }, { "open": "\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "'", "close": "'", "notIn": ["string", "comment"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"] ], "folding": { "markers": { "start": "^\\s*\\/\\*\\s*#region\\b\\s*(.*?)\\s*\\*\\/", "end": "^\\s*\\/\\*\\s*#endregion\\b.*\\*\\/" } } }
extensions/scss/language-configuration.json
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017631406080909073, 0.00017058465164154768, 0.00016659875109326094, 0.00016971287550404668, 0.000003565852011888637 ]
{ "id": 2, "code_window": [ "\tset enabled(enabled: boolean) {\n", "\t\tthis.inputBox.setEnabled(enabled);\n", "\t}\n", "\n", "\tsetAttribute(name: string, value: string) {\n", "\t\tthis.inputBox.inputElement.setAttribute(name, value);\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\thasFocus(): boolean {\n", "\t\treturn this.inputBox.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInputBox.ts", "type": "add", "edit_start_line_idx": 83 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick, IQuickInputButton } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen, FileFilter } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private acceptButton: IQuickInputButton; private fallbackListItem: FileQuickPickItem | undefined; private options: IOpenDialogOptions; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private filters: FileFilter[] | undefined; private hidden: boolean; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; private shouldOverwriteFile: boolean = false; constructor( @IFileService private readonly fileService: IFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; const openFileString = nls.localize('remoteFileDialog.localFileFallback', '(Open Local File)'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', '(Open Local Folder)'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', '(Open Local File or Folder)'); let fallbackLabel = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackListItem = this.getFallbackFileSystem(fallbackLabel); return this.pickResource().then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.fileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; this.options.canSelectFolders = true; this.options.canSelectFiles = true; this.fallbackListItem = this.getFallbackFileSystem(nls.localize('remoteFileDialog.localSaveFallback', '(Save Local File)')); return new Promise<URI | undefined>((resolve) => { this.pickResource(true).then(folderUri => { resolve(folderUri); }); }); } private async getOptions(options: ISaveDialogOptions | IOpenDialogOptions): Promise<IOpenDialogOptions | undefined> { let defaultUri = options.defaultUri; if (!defaultUri) { const env = await this.remoteAgentService.getEnvironment(); if (env) { defaultUri = env.userHome; } else { defaultUri = URI.from({ scheme: this.scheme, path: this.environmentService.userHome }); } } if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string { return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private getFallbackFileSystem(label: string): FileQuickPickItem | undefined { if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { return { label: label, uri: URI.from({ scheme: this.options.availableFileSystems[1] }), isFolder: true }; } return undefined; } private async pickResource(isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!this.options.canSelectFolders; this.allowFileSelection = !!this.options.canSelectFiles; this.hidden = false; let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (this.options.defaultUri) { try { stat = await this.fileService.resolveFile(this.options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(this.options.defaultUri); trailing = resources.basename(this.options.defaultUri); } // append extension if (isSave && !ext && this.options.filters) { for (let i = 0; i < this.options.filters.length; i++) { if (this.options.filters[i].extensions[0] !== '*') { ext = '.' + this.options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: this.options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolving = false; let isAcceptHandled = false; this.currentFolder = homedir; this.filePickBox.buttons = [this.acceptButton]; this.filePickBox.onDidTriggerButton(_ => { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolving = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.title = this.options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; isResolving = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { this.filePickBox.hide(); resolve(resolveValue); } else if (this.hidden) { resolve(undefined); } else { isResolving = false; isAcceptHandled = false; } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { this.filePickBox.validationMessage = undefined; this.shouldOverwriteFile = false; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value)); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { this.hidden = true; if (!isResolving) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } else { this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { // Check if Open Local has been selected const selectedItems: ReadonlyArray<FileQuickPickItem> = this.filePickBox.selectedItems; if (selectedItems && (selectedItems.length > 0) && (selectedItems[0] === this.fallbackListItem)) { if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { this.options.availableFileSystems.shift(); } if (this.requiresTrailing) { return this.fileDialogService.showSaveDialog(this.options).then(result => { return result; }); } else { return this.fileDialogService.showOpenDialog(this.options).then(result => { return result ? result[0] : undefined; }); } } let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(inputUriDirname); stat = await this.fileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.fileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.fileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(resources.dirname(uri)); stat = await this.fileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.'); return Promise.resolve(false); } else if (stat && !this.shouldOverwriteFile) { // Replacing a file. this.shouldOverwriteFile = true; this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri)); return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.'); return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.'); return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.'); return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const folder = await this.fileService.resolveFile(currentFolder); const fileNames = folder.children ? folder.children.map(child => child.name) : []; const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } if (this.fallbackListItem) { sorted.push(this.fallbackListItem); } return sorted; } private filterFile(file: URI): boolean { if (this.filters) { const ext = resources.extname(file); for (let i = 0; i < this.filters.length; i++) { for (let j = 0; j < this.filters[i].extensions.length; j++) { if (ext === ('.' + this.filters[i].extensions[j])) { return true; } } } return false; } return true; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.fileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return undefined; } catch (e) { return undefined; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.000272422272246331, 0.00017394471797160804, 0.00016402850451413542, 0.00017184972239192575, 0.000015568302842439152 ]
{ "id": 2, "code_window": [ "\tset enabled(enabled: boolean) {\n", "\t\tthis.inputBox.setEnabled(enabled);\n", "\t}\n", "\n", "\tsetAttribute(name: string, value: string) {\n", "\t\tthis.inputBox.inputElement.setAttribute(name, value);\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\thasFocus(): boolean {\n", "\t\treturn this.inputBox.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInputBox.ts", "type": "add", "edit_start_line_idx": 83 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out", "downlevelIteration": true }, "include": [ "src/**/*" ] }
extensions/debug-server-ready/tsconfig.json
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0001781684986781329, 0.00017608671623747796, 0.00017400493379682302, 0.00017608671623747796, 0.0000020817824406549335 ]
{ "id": 2, "code_window": [ "\tset enabled(enabled: boolean) {\n", "\t\tthis.inputBox.setEnabled(enabled);\n", "\t}\n", "\n", "\tsetAttribute(name: string, value: string) {\n", "\t\tthis.inputBox.inputElement.setAttribute(name, value);\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\thasFocus(): boolean {\n", "\t\treturn this.inputBox.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInputBox.ts", "type": "add", "edit_start_line_idx": 83 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./toolbar'; import * as nls from 'vs/nls'; import { Action, IActionRunner, IAction } from 'vs/base/common/actions'; import { ActionBar, ActionsOrientation, IActionItemProvider } from 'vs/base/browser/ui/actionbar/actionbar'; import { IContextMenuProvider, DropdownMenuActionItem } from 'vs/base/browser/ui/dropdown/dropdown'; import { ResolvedKeybinding } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview'; import { withNullAsUndefined } from 'vs/base/common/types'; export const CONTEXT = 'context.toolbar'; export interface IToolBarOptions { orientation?: ActionsOrientation; actionItemProvider?: IActionItemProvider; ariaLabel?: string; getKeyBinding?: (action: IAction) => ResolvedKeybinding | undefined; actionRunner?: IActionRunner; toggleMenuTitle?: string; anchorAlignmentProvider?: () => AnchorAlignment; } /** * A widget that combines an action bar for primary actions and a dropdown for secondary actions. */ export class ToolBar extends Disposable { private options: IToolBarOptions; private actionBar: ActionBar; private toggleMenuAction: ToggleMenuAction; private toggleMenuActionItem?: DropdownMenuActionItem; private hasSecondaryActions: boolean; private lookupKeybindings: boolean; constructor(container: HTMLElement, contextMenuProvider: IContextMenuProvider, options: IToolBarOptions = { orientation: ActionsOrientation.HORIZONTAL }) { super(); this.options = options; this.lookupKeybindings = typeof this.options.getKeyBinding === 'function'; this.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show(), options.toggleMenuTitle)); let element = document.createElement('div'); element.className = 'monaco-toolbar'; container.appendChild(element); this.actionBar = this._register(new ActionBar(element, { orientation: options.orientation, ariaLabel: options.ariaLabel, actionRunner: options.actionRunner, actionItemProvider: (action: Action) => { // Return special action item for the toggle menu action if (action.id === ToggleMenuAction.ID) { // Dispose old if (this.toggleMenuActionItem) { this.toggleMenuActionItem.dispose(); } // Create new this.toggleMenuActionItem = new DropdownMenuActionItem( action, (<ToggleMenuAction>action).menuActions, contextMenuProvider, this.options.actionItemProvider, this.actionRunner, this.options.getKeyBinding, 'toolbar-toggle-more', this.options.anchorAlignmentProvider ); this.toggleMenuActionItem!.setActionContext(this.actionBar.context); return this.toggleMenuActionItem; } return options.actionItemProvider ? options.actionItemProvider(action) : undefined; } })); } set actionRunner(actionRunner: IActionRunner) { this.actionBar.actionRunner = actionRunner; } get actionRunner(): IActionRunner { return this.actionBar.actionRunner; } set context(context: any) { this.actionBar.context = context; if (this.toggleMenuActionItem) { this.toggleMenuActionItem.setActionContext(context); } } getContainer(): HTMLElement { return this.actionBar.getContainer(); } getItemsWidth(): number { let itemsWidth = 0; for (let i = 0; i < this.actionBar.length(); i++) { itemsWidth += this.actionBar.getWidth(i); } return itemsWidth; } setAriaLabel(label: string): void { this.actionBar.setAriaLabel(label); } setActions(primaryActions: IAction[], secondaryActions?: IAction[]): () => void { return () => { let primaryActionsToSet = primaryActions ? primaryActions.slice(0) : []; // Inject additional action to open secondary actions if present this.hasSecondaryActions = !!(secondaryActions && secondaryActions.length > 0); if (this.hasSecondaryActions && secondaryActions) { this.toggleMenuAction.menuActions = secondaryActions.slice(0); primaryActionsToSet.push(this.toggleMenuAction); } this.actionBar.clear(); primaryActionsToSet.forEach(action => { this.actionBar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }); }); }; } private getKeybindingLabel(action: IAction): string | undefined { const key = this.lookupKeybindings && this.options.getKeyBinding ? this.options.getKeyBinding(action) : undefined; return withNullAsUndefined(key && key.getLabel()); } addPrimaryAction(primaryAction: IAction): () => void { return () => { // Add after the "..." action if we have secondary actions if (this.hasSecondaryActions) { let itemCount = this.actionBar.length(); this.actionBar.push(primaryAction, { icon: true, label: false, index: itemCount, keybinding: this.getKeybindingLabel(primaryAction) }); } // Otherwise just add to the end else { this.actionBar.push(primaryAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(primaryAction) }); } }; } dispose(): void { if (this.toggleMenuActionItem) { this.toggleMenuActionItem.dispose(); this.toggleMenuActionItem = undefined; } super.dispose(); } } class ToggleMenuAction extends Action { static readonly ID = 'toolbar.toggle.more'; private _menuActions: IAction[]; private toggleDropdownMenu: () => void; constructor(toggleDropdownMenu: () => void, title?: string) { title = title || nls.localize('moreActions', "More Actions..."); super(ToggleMenuAction.ID, title, undefined, true); this.toggleDropdownMenu = toggleDropdownMenu; } run(): Promise<any> { this.toggleDropdownMenu(); return Promise.resolve(true); } get menuActions() { return this._menuActions; } set menuActions(actions: IAction[]) { this._menuActions = actions; } }
src/vs/base/browser/ui/toolbar/toolbar.ts
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017544471484143287, 0.0001705792819848284, 0.00016512637375853956, 0.00017159178969450295, 0.0000032475145417265594 ]
{ "id": 2, "code_window": [ "\tset enabled(enabled: boolean) {\n", "\t\tthis.inputBox.setEnabled(enabled);\n", "\t}\n", "\n", "\tsetAttribute(name: string, value: string) {\n", "\t\tthis.inputBox.inputElement.setAttribute(name, value);\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\thasFocus(): boolean {\n", "\t\treturn this.inputBox.hasFocus();\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/browser/parts/quickinput/quickInputBox.ts", "type": "add", "edit_start_line_idx": 83 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-fg{fill:#2b282e}.icon-folder{fill:#C5C5C5}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M14.5 1H6.39l-1 2H2.504c-.827 0-1.5.673-1.5 1.5v4.202A4.454 4.454 0 0 0 0 11.5C0 13.981 2.019 16 4.5 16c1.557 0 2.93-.795 3.738-2H14.5c.827 0 1.5-.673 1.5-1.5v-10c0-.827-.673-1.5-1.5-1.5z" id="outline" style="display: none;"/><path class="icon-folder" d="M14.5 2H7.008l-1 2H2.504a.5.5 0 0 0-.5.5v3.26A4.47 4.47 0 0 1 4.5 7C6.981 7 9 9.019 9 11.5c0 .529-.108 1.029-.276 1.5H14.5a.5.5 0 0 0 .5-.5v-10a.5.5 0 0 0-.5-.5zm-.496 2H7.508l.5-1h5.996v1zM4.5 8a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7zM7 11.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zm-1 0a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z" id="iconBg"/><g id="iconFg"><path class="icon-vs-fg" d="M14 3v1H7.5L8 3h6z" style="display: none;"/></g></svg>
extensions/theme-defaults/fileicons/images/RootFolder_16x_inverse.svg
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0002468303428031504, 0.0002468303428031504, 0.0002468303428031504, 0.0002468303428031504, 0 ]
{ "id": 3, "code_window": [ "\tprivate requiresTrailing: boolean;\n", "\tprivate userValue: string;\n", "\tprivate scheme: string = REMOTE_HOST_SCHEME;\n", "\tprivate shouldOverwriteFile: boolean = false;\n", "\n", "\tconstructor(\n", "\t\t@IFileService private readonly fileService: IFileService,\n", "\t\t@IQuickInputService private readonly quickInputService: IQuickInputService,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate autoComplete: string;\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 49 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick, IQuickInputButton } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen, FileFilter } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private acceptButton: IQuickInputButton; private fallbackListItem: FileQuickPickItem | undefined; private options: IOpenDialogOptions; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private filters: FileFilter[] | undefined; private hidden: boolean; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; private shouldOverwriteFile: boolean = false; constructor( @IFileService private readonly fileService: IFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; const openFileString = nls.localize('remoteFileDialog.localFileFallback', '(Open Local File)'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', '(Open Local Folder)'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', '(Open Local File or Folder)'); let fallbackLabel = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackListItem = this.getFallbackFileSystem(fallbackLabel); return this.pickResource().then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.fileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; this.options.canSelectFolders = true; this.options.canSelectFiles = true; this.fallbackListItem = this.getFallbackFileSystem(nls.localize('remoteFileDialog.localSaveFallback', '(Save Local File)')); return new Promise<URI | undefined>((resolve) => { this.pickResource(true).then(folderUri => { resolve(folderUri); }); }); } private async getOptions(options: ISaveDialogOptions | IOpenDialogOptions): Promise<IOpenDialogOptions | undefined> { let defaultUri = options.defaultUri; if (!defaultUri) { const env = await this.remoteAgentService.getEnvironment(); if (env) { defaultUri = env.userHome; } else { defaultUri = URI.from({ scheme: this.scheme, path: this.environmentService.userHome }); } } if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string { return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private getFallbackFileSystem(label: string): FileQuickPickItem | undefined { if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { return { label: label, uri: URI.from({ scheme: this.options.availableFileSystems[1] }), isFolder: true }; } return undefined; } private async pickResource(isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!this.options.canSelectFolders; this.allowFileSelection = !!this.options.canSelectFiles; this.hidden = false; let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (this.options.defaultUri) { try { stat = await this.fileService.resolveFile(this.options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(this.options.defaultUri); trailing = resources.basename(this.options.defaultUri); } // append extension if (isSave && !ext && this.options.filters) { for (let i = 0; i < this.options.filters.length; i++) { if (this.options.filters[i].extensions[0] !== '*') { ext = '.' + this.options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: this.options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolving = false; let isAcceptHandled = false; this.currentFolder = homedir; this.filePickBox.buttons = [this.acceptButton]; this.filePickBox.onDidTriggerButton(_ => { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolving = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.title = this.options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; isResolving = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { this.filePickBox.hide(); resolve(resolveValue); } else if (this.hidden) { resolve(undefined); } else { isResolving = false; isAcceptHandled = false; } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { this.filePickBox.validationMessage = undefined; this.shouldOverwriteFile = false; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value)); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { this.hidden = true; if (!isResolving) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } else { this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { // Check if Open Local has been selected const selectedItems: ReadonlyArray<FileQuickPickItem> = this.filePickBox.selectedItems; if (selectedItems && (selectedItems.length > 0) && (selectedItems[0] === this.fallbackListItem)) { if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { this.options.availableFileSystems.shift(); } if (this.requiresTrailing) { return this.fileDialogService.showSaveDialog(this.options).then(result => { return result; }); } else { return this.fileDialogService.showOpenDialog(this.options).then(result => { return result ? result[0] : undefined; }); } } let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(inputUriDirname); stat = await this.fileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.fileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.fileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(resources.dirname(uri)); stat = await this.fileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.'); return Promise.resolve(false); } else if (stat && !this.shouldOverwriteFile) { // Replacing a file. this.shouldOverwriteFile = true; this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri)); return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.'); return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.'); return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.'); return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const folder = await this.fileService.resolveFile(currentFolder); const fileNames = folder.children ? folder.children.map(child => child.name) : []; const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } if (this.fallbackListItem) { sorted.push(this.fallbackListItem); } return sorted; } private filterFile(file: URI): boolean { if (this.filters) { const ext = resources.extname(file); for (let i = 0; i < this.filters.length; i++) { for (let j = 0; j < this.filters[i].extensions.length; j++) { if (ext === ('.' + this.filters[i].extensions[j])) { return true; } } } return false; } return true; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.fileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return undefined; } catch (e) { return undefined; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.9976275563240051, 0.0533873476088047, 0.0001650892081670463, 0.00022248785535339266, 0.22215281426906586 ]
{ "id": 3, "code_window": [ "\tprivate requiresTrailing: boolean;\n", "\tprivate userValue: string;\n", "\tprivate scheme: string = REMOTE_HOST_SCHEME;\n", "\tprivate shouldOverwriteFile: boolean = false;\n", "\n", "\tconstructor(\n", "\t\t@IFileService private readonly fileService: IFileService,\n", "\t\t@IQuickInputService private readonly quickInputService: IQuickInputService,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate autoComplete: string;\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 49 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><g fill="#424242"><path d="M12.714 9.603c-.07.207-.15.407-.246.601l1.017 2.139c-.335.424-.718.807-1.142 1.143l-2.14-1.018c-.193.097-.394.176-.601.247l-.795 2.235c-.265.03-.534.05-.807.05-.272 0-.541-.02-.806-.05l-.795-2.235c-.207-.071-.408-.15-.602-.247l-2.14 1.017c-.424-.336-.807-.719-1.143-1.143l1.017-2.139c-.094-.193-.175-.393-.245-.6l-2.236-.796c-.03-.265-.05-.534-.05-.807s.02-.542.05-.807l2.236-.795c.07-.207.15-.407.246-.601l-1.016-2.139c.336-.423.719-.807 1.143-1.142l2.14 1.017c.193-.096.394-.176.602-.247l.793-2.236c.265-.03.534-.05.806-.05.273 0 .542.02.808.05l.795 2.236c.207.07.407.15.601.246l2.14-1.017c.424.335.807.719 1.142 1.142l-1.017 2.139c.096.194.176.394.246.601l2.236.795c.029.266.049.535.049.808s-.02.542-.05.807l-2.236.796zm-4.714-4.603c-1.657 0-3 1.343-3 3s1.343 3 3 3 3-1.343 3-3-1.343-3-3-3z"/><circle cx="8" cy="8" r="1.5"/></g></svg>
src/vs/workbench/browser/parts/notifications/media/configure.svg
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0002653362462297082, 0.0002653362462297082, 0.0002653362462297082, 0.0002653362462297082, 0 ]
{ "id": 3, "code_window": [ "\tprivate requiresTrailing: boolean;\n", "\tprivate userValue: string;\n", "\tprivate scheme: string = REMOTE_HOST_SCHEME;\n", "\tprivate shouldOverwriteFile: boolean = false;\n", "\n", "\tconstructor(\n", "\t\t@IFileService private readonly fileService: IFileService,\n", "\t\t@IQuickInputService private readonly quickInputService: IQuickInputService,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate autoComplete: string;\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 49 }
{ "compilerOptions": { "target": "es2018", "module": "commonjs", "strict": true, "alwaysStrict": true, "noImplicitAny": true, "noImplicitReturns": true, "noUnusedLocals": true, "noUnusedParameters": true } }
extensions/shared.tsconfig.json
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017702511104289442, 0.0001756919955369085, 0.00017435886547900736, 0.0001756919955369085, 0.0000013331227819435298 ]
{ "id": 3, "code_window": [ "\tprivate requiresTrailing: boolean;\n", "\tprivate userValue: string;\n", "\tprivate scheme: string = REMOTE_HOST_SCHEME;\n", "\tprivate shouldOverwriteFile: boolean = false;\n", "\n", "\tconstructor(\n", "\t\t@IFileService private readonly fileService: IFileService,\n", "\t\t@IQuickInputService private readonly quickInputService: IQuickInputService,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate autoComplete: string;\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 49 }
/*--------------------------------------------------------------------------------------------- * 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 { CharCode } from 'vs/base/common/charCode'; import { CharacterClassifier } from 'vs/editor/common/core/characterClassifier'; suite('CharacterClassifier', () => { test('works', () => { let classifier = new CharacterClassifier<number>(0); assert.equal(classifier.get(-1), 0); assert.equal(classifier.get(0), 0); assert.equal(classifier.get(CharCode.a), 0); assert.equal(classifier.get(CharCode.b), 0); assert.equal(classifier.get(CharCode.z), 0); assert.equal(classifier.get(255), 0); assert.equal(classifier.get(1000), 0); assert.equal(classifier.get(2000), 0); classifier.set(CharCode.a, 1); classifier.set(CharCode.z, 2); classifier.set(1000, 3); assert.equal(classifier.get(-1), 0); assert.equal(classifier.get(0), 0); assert.equal(classifier.get(CharCode.a), 1); assert.equal(classifier.get(CharCode.b), 0); assert.equal(classifier.get(CharCode.z), 2); assert.equal(classifier.get(255), 0); assert.equal(classifier.get(1000), 3); assert.equal(classifier.get(2000), 0); }); });
src/vs/editor/test/common/core/characterClassifier.test.ts
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017919516540132463, 0.00017694565758574754, 0.00017537412350066006, 0.00017660667072050273, 0.0000014916740838089027 ]
{ "id": 4, "code_window": [ "\t\t\t\tisAcceptHandled = false;\n", "\t\t\t});\n", "\n", "\t\t\tthis.filePickBox.onDidChangeValue(async value => {\n", "\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\t// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything\n", "\t\t\t\tif (!this.autoComplete || (value !== this.autoComplete)) {\n", "\t\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t\t} else {\n", "\t\t\t\t\t\tthis.filePickBox.activeItems = [];\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 224 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick, IQuickInputButton } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen, FileFilter } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private acceptButton: IQuickInputButton; private fallbackListItem: FileQuickPickItem | undefined; private options: IOpenDialogOptions; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private filters: FileFilter[] | undefined; private hidden: boolean; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; private shouldOverwriteFile: boolean = false; constructor( @IFileService private readonly fileService: IFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; const openFileString = nls.localize('remoteFileDialog.localFileFallback', '(Open Local File)'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', '(Open Local Folder)'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', '(Open Local File or Folder)'); let fallbackLabel = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackListItem = this.getFallbackFileSystem(fallbackLabel); return this.pickResource().then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.fileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = await this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.options = newOptions; this.options.canSelectFolders = true; this.options.canSelectFiles = true; this.fallbackListItem = this.getFallbackFileSystem(nls.localize('remoteFileDialog.localSaveFallback', '(Save Local File)')); return new Promise<URI | undefined>((resolve) => { this.pickResource(true).then(folderUri => { resolve(folderUri); }); }); } private async getOptions(options: ISaveDialogOptions | IOpenDialogOptions): Promise<IOpenDialogOptions | undefined> { let defaultUri = options.defaultUri; if (!defaultUri) { const env = await this.remoteAgentService.getEnvironment(); if (env) { defaultUri = env.userHome; } else { defaultUri = URI.from({ scheme: this.scheme, path: this.environmentService.userHome }); } } if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string { return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private getFallbackFileSystem(label: string): FileQuickPickItem | undefined { if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { return { label: label, uri: URI.from({ scheme: this.options.availableFileSystems[1] }), isFolder: true }; } return undefined; } private async pickResource(isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!this.options.canSelectFolders; this.allowFileSelection = !!this.options.canSelectFiles; this.hidden = false; let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (this.options.defaultUri) { try { stat = await this.fileService.resolveFile(this.options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(this.options.defaultUri); trailing = resources.basename(this.options.defaultUri); } // append extension if (isSave && !ext && this.options.filters) { for (let i = 0; i < this.options.filters.length; i++) { if (this.options.filters[i].extensions[0] !== '*') { ext = '.' + this.options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: this.options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolving = false; let isAcceptHandled = false; this.currentFolder = homedir; this.filePickBox.buttons = [this.acceptButton]; this.filePickBox.onDidTriggerButton(_ => { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolving = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.title = this.options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; isResolving = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { this.filePickBox.hide(); resolve(resolveValue); } else if (this.hidden) { resolve(undefined); } else { isResolving = false; isAcceptHandled = false; } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { this.filePickBox.validationMessage = undefined; this.shouldOverwriteFile = false; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value)); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { this.hidden = true; if (!isResolving) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } else { this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { // Check if Open Local has been selected const selectedItems: ReadonlyArray<FileQuickPickItem> = this.filePickBox.selectedItems; if (selectedItems && (selectedItems.length > 0) && (selectedItems[0] === this.fallbackListItem)) { if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) { this.options.availableFileSystems.shift(); } if (this.requiresTrailing) { return this.fileDialogService.showSaveDialog(this.options).then(result => { return result; }); } else { return this.fileDialogService.showOpenDialog(this.options).then(result => { return result ? result[0] : undefined; }); } } let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(inputUriDirname); stat = await this.fileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.fileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.fileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.fileService.resolveFile(resources.dirname(uri)); stat = await this.fileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.'); return Promise.resolve(false); } else if (stat && !this.shouldOverwriteFile) { // Replacing a file. this.shouldOverwriteFile = true; this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri)); return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.'); return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.'); return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.'); return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.'); return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const folder = await this.fileService.resolveFile(currentFolder); const fileNames = folder.children ? folder.children.map(child => child.name) : []; const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } if (this.fallbackListItem) { sorted.push(this.fallbackListItem); } return sorted; } private filterFile(file: URI): boolean { if (this.filters) { const ext = resources.extname(file); for (let i = 0; i < this.filters.length; i++) { for (let j = 0; j < this.filters[i].extensions.length; j++) { if (ext === ('.' + this.filters[i].extensions[j])) { return true; } } } return false; } return true; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.fileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return undefined; } catch (e) { return undefined; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.9983744621276855, 0.0570262111723423, 0.00016173782933037728, 0.00022725583403371274, 0.2103235423564911 ]
{ "id": 4, "code_window": [ "\t\t\t\tisAcceptHandled = false;\n", "\t\t\t});\n", "\n", "\t\t\tthis.filePickBox.onDidChangeValue(async value => {\n", "\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\t// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything\n", "\t\t\t\tif (!this.autoComplete || (value !== this.autoComplete)) {\n", "\t\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t\t} else {\n", "\t\t\t\t\t\tthis.filePickBox.activeItems = [];\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 224 }
use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); println!("You guessed: {}", guess); }
extensions/rust/test/colorize-fixtures/test.rs
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017411015869583935, 0.00017335897427983582, 0.00017260777531191707, 0.00017335897427983582, 7.511916919611394e-7 ]
{ "id": 4, "code_window": [ "\t\t\t\tisAcceptHandled = false;\n", "\t\t\t});\n", "\n", "\t\t\tthis.filePickBox.onDidChangeValue(async value => {\n", "\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\t// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything\n", "\t\t\t\tif (!this.autoComplete || (value !== this.autoComplete)) {\n", "\t\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t\t} else {\n", "\t\t\t\t\t\tthis.filePickBox.activeItems = [];\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 224 }
extensions/html-language-features/server/src/test/pathCompletionFixtures/about/about.html
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00016340953879989684, 0.00016340953879989684, 0.00016340953879989684, 0.00016340953879989684, 0 ]
{ "id": 4, "code_window": [ "\t\t\t\tisAcceptHandled = false;\n", "\t\t\t});\n", "\n", "\t\t\tthis.filePickBox.onDidChangeValue(async value => {\n", "\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\t\t// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything\n", "\t\t\t\tif (!this.autoComplete || (value !== this.autoComplete)) {\n", "\t\t\t\t\tif (value !== this.userValue) {\n", "\t\t\t\t\t\tthis.filePickBox.validationMessage = undefined;\n", "\t\t\t\t\t\tthis.shouldOverwriteFile = false;\n", "\t\t\t\t\t\tconst trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value;\n", "\t\t\t\t\t\tconst valueUri = this.remoteUriFrom(trimmedPickBoxValue);\n", "\t\t\t\t\t\tif (!resources.isEqual(this.currentFolder, valueUri, true)) {\n", "\t\t\t\t\t\t\tawait this.tryUpdateItems(value, this.remoteUriFrom(this.filePickBox.value));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t\t} else {\n", "\t\t\t\t\t\tthis.filePickBox.activeItems = [];\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 224 }
/*--------------------------------------------------------------------------------------------- * 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 { getPathFromAmdModule } from 'vs/base/common/amd'; import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import * as path from 'vs/base/common/path'; import { URI } from 'vs/base/common/uri'; import { IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, IRawFileMatch, ISearchEngine, ISearchEngineStats, ISearchEngineSuccess, ISerializedFileMatch, ISerializedSearchComplete, ISerializedSearchProgressItem, ISerializedSearchSuccess, QueryType } from 'vs/workbench/services/search/common/search'; import { IProgressCallback, SearchService as RawSearchService } from 'vs/workbench/services/search/node/rawSearchService'; import { DiskSearch } from 'vs/workbench/services/search/node/searchService'; const TEST_FOLDER_QUERIES = [ { folder: URI.file(path.normalize('/some/where')) } ]; const TEST_FIXTURES = path.normalize(getPathFromAmdModule(require, './fixtures')); const MULTIROOT_QUERIES: IFolderQuery[] = [ { folder: URI.file(path.join(TEST_FIXTURES, 'examples')) }, { folder: URI.file(path.join(TEST_FIXTURES, 'more')) } ]; const stats: ISearchEngineStats = { fileWalkTime: 0, cmdTime: 1, directoriesWalked: 2, filesWalked: 3 }; class TestSearchEngine implements ISearchEngine<IRawFileMatch> { static last: TestSearchEngine; private isCanceled = false; constructor(private result: () => IRawFileMatch, public config?: IFileQuery) { TestSearchEngine.last = this; } search(onResult: (match: IRawFileMatch) => void, onProgress: (progress: IProgressMessage) => void, done: (error: Error, complete: ISearchEngineSuccess) => void): void { const self = this; (function next() { process.nextTick(() => { if (self.isCanceled) { done(null!, { limitHit: false, stats: stats }); return; } const result = self.result(); if (!result) { done(null!, { limitHit: false, stats: stats }); } else { onResult(result); next(); } }); })(); } cancel(): void { this.isCanceled = true; } } const testTimeout = 5000; suite('RawSearchService', () => { const rawSearch: IFileQuery = { type: QueryType.File, folderQueries: TEST_FOLDER_QUERIES, filePattern: 'a' }; const rawMatch: IRawFileMatch = { base: path.normalize('/some'), relativePath: 'where', basename: 'where', size: 123 }; const match: ISerializedFileMatch = { path: path.normalize('/some/where') }; test('Individual results', async function () { this.timeout(testTimeout); let i = 5; const Engine = TestSearchEngine.bind(null, () => i-- && rawMatch); const service = new RawSearchService(); let results = 0; const cb: (p: ISerializedSearchProgressItem) => void = value => { if (!Array.isArray(value)) { assert.deepStrictEqual(value, match); results++; } else { assert.fail(JSON.stringify(value)); } }; await service.doFileSearchWithEngine(Engine, rawSearch, cb, null!, 0); return assert.strictEqual(results, 5); }); test('Batch results', async function () { this.timeout(testTimeout); let i = 25; const Engine = TestSearchEngine.bind(null, () => i-- && rawMatch); const service = new RawSearchService(); const results: number[] = []; const cb: (p: ISerializedSearchProgressItem) => void = value => { if (Array.isArray(value)) { value.forEach(m => { assert.deepStrictEqual(m, match); }); results.push(value.length); } else { assert.fail(JSON.stringify(value)); } }; await service.doFileSearchWithEngine(Engine, rawSearch, cb, undefined, 10); assert.deepStrictEqual(results, [10, 10, 5]); }); test('Collect batched results', async function () { this.timeout(testTimeout); const uriPath = '/some/where'; let i = 25; const Engine = TestSearchEngine.bind(null, () => i-- && rawMatch); const service = new RawSearchService(); function fileSearch(config: IFileQuery, batchSize: number): Event<ISerializedSearchProgressItem | ISerializedSearchComplete> { let promise: CancelablePromise<ISerializedSearchSuccess | void>; const emitter = new Emitter<ISerializedSearchProgressItem | ISerializedSearchComplete>({ onFirstListenerAdd: () => { promise = createCancelablePromise(token => service.doFileSearchWithEngine(Engine, config, p => emitter.fire(p), token, batchSize) .then(c => emitter.fire(c), err => emitter.fire({ type: 'error', error: err }))); }, onLastListenerRemove: () => { promise.cancel(); } }); return emitter.event; } const progressResults: any[] = []; const onProgress = (match: IFileMatch) => { assert.strictEqual(match.resource.path, uriPath); progressResults.push(match); }; const result_2 = await DiskSearch.collectResultsFromEvent(fileSearch(rawSearch, 10), onProgress); assert.strictEqual(result_2.results.length, 25, 'Result'); assert.strictEqual(progressResults.length, 25, 'Progress'); }); test('Multi-root with include pattern and maxResults', async function () { this.timeout(testTimeout); const service = new RawSearchService(); const query: IFileQuery = { type: QueryType.File, folderQueries: MULTIROOT_QUERIES, maxResults: 1, includePattern: { '*.txt': true, '*.js': true }, }; const result = await DiskSearch.collectResultsFromEvent(service.fileSearch(query)); assert.strictEqual(result.results.length, 1, 'Result'); }); test('Multi-root with include pattern and exists', async function () { this.timeout(testTimeout); const service = new RawSearchService(); const query: IFileQuery = { type: QueryType.File, folderQueries: MULTIROOT_QUERIES, exists: true, includePattern: { '*.txt': true, '*.js': true }, }; const result = await DiskSearch.collectResultsFromEvent(service.fileSearch(query)); assert.strictEqual(result.results.length, 0, 'Result'); assert.ok(result.limitHit); }); test('Sorted results', async function () { this.timeout(testTimeout); const paths = ['bab', 'bbc', 'abb']; const matches: IRawFileMatch[] = paths.map(relativePath => ({ base: path.normalize('/some/where'), relativePath, basename: relativePath, size: 3 })); const Engine = TestSearchEngine.bind(null, () => matches.shift()); const service = new RawSearchService(); const results: any[] = []; const cb: IProgressCallback = value => { if (Array.isArray(value)) { results.push(...value.map(v => v.path)); } else { assert.fail(JSON.stringify(value)); } }; await service.doFileSearchWithEngine(Engine, { type: QueryType.File, folderQueries: TEST_FOLDER_QUERIES, filePattern: 'bb', sortByScore: true, maxResults: 2 }, cb, undefined, 1); assert.notStrictEqual(typeof TestSearchEngine.last.config!.maxResults, 'number'); assert.deepStrictEqual(results, [path.normalize('/some/where/bbc'), path.normalize('/some/where/bab')]); }); test('Sorted result batches', async function () { this.timeout(testTimeout); let i = 25; const Engine = TestSearchEngine.bind(null, () => i-- && rawMatch); const service = new RawSearchService(); const results: number[] = []; const cb: IProgressCallback = value => { if (Array.isArray(value)) { value.forEach(m => { assert.deepStrictEqual(m, match); }); results.push(value.length); } else { assert.fail(JSON.stringify(value)); } }; await service.doFileSearchWithEngine(Engine, { type: QueryType.File, folderQueries: TEST_FOLDER_QUERIES, filePattern: 'a', sortByScore: true, maxResults: 23 }, cb, undefined, 10); assert.deepStrictEqual(results, [10, 10, 3]); }); test('Cached results', function () { this.timeout(testTimeout); const paths = ['bcb', 'bbc', 'aab']; const matches: IRawFileMatch[] = paths.map(relativePath => ({ base: path.normalize('/some/where'), relativePath, basename: relativePath, size: 3 })); const Engine = TestSearchEngine.bind(null, () => matches.shift()); const service = new RawSearchService(); const results: any[] = []; const cb: IProgressCallback = value => { if (Array.isArray(value)) { results.push(...value.map(v => v.path)); } else { assert.fail(JSON.stringify(value)); } }; return service.doFileSearchWithEngine(Engine, { type: QueryType.File, folderQueries: TEST_FOLDER_QUERIES, filePattern: 'b', sortByScore: true, cacheKey: 'x' }, cb, undefined, -1).then(complete => { assert.strictEqual((<IFileSearchStats>complete.stats).fromCache, false); assert.deepStrictEqual(results, [path.normalize('/some/where/bcb'), path.normalize('/some/where/bbc'), path.normalize('/some/where/aab')]); }).then(async () => { const results: any[] = []; const cb: IProgressCallback = value => { if (Array.isArray(value)) { results.push(...value.map(v => v.path)); } else { assert.fail(JSON.stringify(value)); } }; try { const complete = await service.doFileSearchWithEngine(Engine, { type: QueryType.File, folderQueries: TEST_FOLDER_QUERIES, filePattern: 'bc', sortByScore: true, cacheKey: 'x' }, cb, undefined, -1); assert.ok((<IFileSearchStats>complete.stats).fromCache); assert.deepStrictEqual(results, [path.normalize('/some/where/bcb'), path.normalize('/some/where/bbc')]); } catch (e) { } }).then(() => { return service.clearCache('x'); }).then(async () => { matches.push({ base: path.normalize('/some/where'), relativePath: 'bc', basename: 'bc', size: 3 }); const results: any[] = []; const cb: IProgressCallback = value => { if (Array.isArray(value)) { results.push(...value.map(v => v.path)); } else { assert.fail(JSON.stringify(value)); } }; const complete = await service.doFileSearchWithEngine(Engine, { type: QueryType.File, folderQueries: TEST_FOLDER_QUERIES, filePattern: 'bc', sortByScore: true, cacheKey: 'x' }, cb, undefined, -1); assert.strictEqual((<IFileSearchStats>complete.stats).fromCache, false); assert.deepStrictEqual(results, [path.normalize('/some/where/bc')]); }); }); });
src/vs/workbench/services/search/test/node/rawSearchService.test.ts
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0002415911731077358, 0.00016971840523183346, 0.00015974778216332197, 0.00016819890879560262, 0.000012878028428531252 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t}\n", "\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [];\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t\tthis.filePickBox.onDidHide(() => {\n", "\t\t\t\tthis.hidden = true;\n", "\t\t\t\tif (!isResolving) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 232 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { SIDE_BAR_BACKGROUND, SIDE_BAR_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/dark/arrow-left.svg')), light: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/light/arrow-left.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; inputBox: QuickInputBox; visibleCount: CountBadge; count: CountBadge; message: HTMLElement; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; }; class QuickInput implements IQuickInput { private _title: string; private _steps: number; private _totalSteps: number; protected visible = false; private _enabled = true; private _contextKey: string; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private onDidTriggerButtonEmitter = new Emitter<IQuickInputButton>(); private onDidHideEmitter = new Emitter<void>(); protected visibleDisposables: IDisposable[] = []; protected disposables: IDisposable[] = [ this.onDidTriggerButtonEmitter, this.onDidHideEmitter, ]; private busyDelay: TimeoutTimer | null; constructor(protected ui: QuickInputUI) { } get title() { return this._title; } set title(title: string) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.push( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables = dispose(this.visibleDisposables); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = null; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath!), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath!), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } public dispose(): void { this.hide(); this.disposables = dispose(this.disposables); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder: string; private onDidChangeValueEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<void>(); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private onDidChangeActiveEmitter = new Emitter<T[]>(); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private onDidChangeSelectionEmitter = new Emitter<T[]>(); private onDidTriggerItemButtonEmitter = new Emitter<IQuickPickItemButtonEvent<T>>(); private _valueSelection: Readonly<[number, number]>; private valueSelectionUpdated = true; private _validationMessage: string; quickNavigate: IQuickNavigateConfiguration; constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidChangeValueEmitter, this.onDidAcceptEmitter, this.onDidChangeActiveEmitter, this.onDidChangeSelectionEmitter, this.onDidTriggerItemButtonEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string) { this._validationMessage = validationMessage; this.update(); } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); }), this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } }), this.ui.inputBox.onKeyDown(event => { switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } event.preventDefault(); break; } }), this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); }), this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); }), this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } }), this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); }), this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>)), this.registerQuickNavigation() ); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } if (this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.ui.inputBox.showDecoration(Severity.Error); } else { this.ui.message.textContent = null; this.ui.inputBox.showDecoration(Severity.Ignore); } this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true, message: !!this.validationMessage } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true, message: !!this.validationMessage }); } } class InputBox extends QuickInput implements IInputBox { private static noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]>; private valueSelectionUpdated = true; private _placeholder: string; private _password = false; private _prompt: string; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string; private onDidValueChangeEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<void>(); constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidValueChangeEmitter, this.onDidAcceptEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string) { this._validationMessage = validationMessage; this.update(); } onDidChangeValue = this.onDidValueChangeEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); }), this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined)), ); this.valueSelectionUpdated = true; } super.show(); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.ui.inputBox.showDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.ui.inputBox.showDecoration(Severity.Error); } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: ServiceIdentifier<any>; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private titleBar: HTMLElement; private filterContainer: HTMLElement; private visibleCountContainer: HTMLElement; private countContainer: HTMLElement; private okContainer: HTMLElement; private ok: Button; private ui: QuickInputUI; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: { [id: string]: IContextKey<boolean>; } = Object.create(null); private onDidAcceptEmitter = this._register(new Emitter<void>()); private onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts[id]; if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts[id] = key; } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { for (const key in this.contexts) { if (this.contexts[key].get()) { this.contexts[key].reset(); } } } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private create() { if (this.ui) { return; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; this.titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(this.titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(this.titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(this.titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); this.filterContainer = dom.append(headerContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(this.filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); this.visibleCountContainer = dom.append(this.filterContainer, $('.quick-input-visible-count')); this.visibleCountContainer.setAttribute('aria-live', 'polite'); this.visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(this.visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); this.countContainer = dom.append(this.filterContainer, $('.quick-input-count')); this.countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(this.countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); this.okContainer = dom.append(headerContainer, $('.quick-input-action')); this.ok = new Button(this.okContainer); attachButtonStyler(this.ok, this.themeService); this.ok.label = localize('ok', "OK"); this._register(this.ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const message = dom.append(container, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.ui.ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.icon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.ui.list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, title, rightActionBar, checkAll, inputBox, visibleCount, count, message, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { this.create(); return new QuickPick<T>(this.ui); } createInputBox(): IInputBox { this.create(); return new InputBox(this.ui); } private show(controller: QuickInput) { this.create(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); this.ui.leftActionBar.clear(); this.ui.title.textContent = ''; this.ui.rightActionBar.clear(); this.ui.checkAll.checked = false; // this.ui.inputBox.value = ''; Avoid triggering an event. this.ui.inputBox.placeholder = ''; this.ui.inputBox.password = false; this.ui.inputBox.showDecoration(Severity.Ignore); this.ui.visibleCount.setCount(0); this.ui.count.setCount(0); this.ui.message.textContent = ''; this.ui.progressBar.stop(); this.ui.list.setElements([]); this.ui.list.matchOnDescription = false; this.ui.list.matchOnDetail = false; this.ui.list.matchOnLabel = true; this.ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); this.ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); this.ui.container.style.display = ''; this.updateLayout(); this.ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { this.ui.title.style.display = visibilities.title ? '' : 'none'; this.ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; this.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; this.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; this.countContainer.style.display = visibilities.count ? '' : 'none'; this.okContainer.style.display = visibilities.ok ? '' : 'none'; this.ui.message.style.display = visibilities.message ? '' : 'none'; this.ui.list.display(!!visibilities.list); this.ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('role', 'combobox'); this.ui.inputBox.setAttribute('aria-haspopup', 'true'); this.ui.inputBox.setAttribute('aria-autocomplete', 'list'); this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant() || ''); } else { this.ui.inputBox.removeAttribute('role'); this.ui.inputBox.removeAttribute('aria-haspopup'); this.ui.inputBox.removeAttribute('aria-autocomplete'); this.ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.ui.leftActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } for (const item of this.ui.rightActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } this.ui.checkAll.disabled = !enabled; // this.ui.inputBox.enabled = enabled; Avoid loosing focus. this.ok.enabled = enabled; this.ui.list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.ui.container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.ui.inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.ui.list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.ui.list.isDisplayed()) { this.ui.list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : null; this.ui.inputBox.style(theme); const sideBarBackground = theme.getColor(SIDE_BAR_BACKGROUND); this.ui.container.style.backgroundColor = sideBarBackground ? sideBarBackground.toString() : null; const sideBarForeground = theme.getColor(SIDE_BAR_FOREGROUND); this.ui.container.style.color = sideBarForeground ? sideBarForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : null; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : null; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.009618005715310574, 0.000565084395930171, 0.0001621609553694725, 0.00017208205827046186, 0.0012884666211903095 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t}\n", "\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [];\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t\tthis.filePickBox.onDidHide(() => {\n", "\t\t\t\tthis.hidden = true;\n", "\t\t\t\tif (!isResolving) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 232 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path='../../../../src/vs/vscode.d.ts'/>
extensions/extension-editing/src/typings/ref.d.ts
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017651458620093763, 0.00017651458620093763, 0.00017651458620093763, 0.00017651458620093763, 0 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t}\n", "\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [];\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t\tthis.filePickBox.onDidHide(() => {\n", "\t\t\t\tthis.hidden = true;\n", "\t\t\t\tif (!isResolving) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 232 }
{ "information_for_contributors": [ "This file has been converted from https://github.com/Microsoft/vscode-JSON.tmLanguage/blob/master/JSON.tmLanguage", "If you want to provide a fix or improvement, please create a pull request against the original repository.", "Once accepted there, we are happy to receive an update request." ], "version": "https://github.com/Microsoft/vscode-JSON.tmLanguage/commit/9bd83f1c252b375e957203f21793316203f61f70", "name": "JSON with comments", "scopeName": "source.json.comments", "patterns": [ { "include": "#value" } ], "repository": { "array": { "begin": "\\[", "beginCaptures": { "0": { "name": "punctuation.definition.array.begin.json.comments" } }, "end": "\\]", "endCaptures": { "0": { "name": "punctuation.definition.array.end.json.comments" } }, "name": "meta.structure.array.json.comments", "patterns": [ { "include": "#value" }, { "match": ",", "name": "punctuation.separator.array.json.comments" }, { "match": "[^\\s\\]]", "name": "invalid.illegal.expected-array-separator.json.comments" } ] }, "comments": { "patterns": [ { "begin": "/\\*\\*(?!/)", "captures": { "0": { "name": "punctuation.definition.comment.json.comments" } }, "end": "\\*/", "name": "comment.block.documentation.json.comments" }, { "begin": "/\\*", "captures": { "0": { "name": "punctuation.definition.comment.json.comments" } }, "end": "\\*/", "name": "comment.block.json.comments" }, { "captures": { "1": { "name": "punctuation.definition.comment.json.comments" } }, "match": "(//).*$\\n?", "name": "comment.line.double-slash.js" } ] }, "constant": { "match": "\\b(?:true|false|null)\\b", "name": "constant.language.json.comments" }, "number": { "match": "(?x) # turn on extended mode\n -? # an optional minus\n (?:\n 0 # a zero\n | # ...or...\n [1-9] # a 1-9 character\n \\d* # followed by zero or more digits\n )\n (?:\n (?:\n \\. # a period\n \\d+ # followed by one or more digits\n )?\n (?:\n [eE] # an e character\n [+-]? # followed by an option +/-\n \\d+ # followed by one or more digits\n )? # make exponent optional\n )? # make decimal portion optional", "name": "constant.numeric.json.comments" }, "object": { "begin": "\\{", "beginCaptures": { "0": { "name": "punctuation.definition.dictionary.begin.json.comments" } }, "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.dictionary.end.json.comments" } }, "name": "meta.structure.dictionary.json.comments", "patterns": [ { "comment": "the JSON object key", "include": "#objectkey" }, { "include": "#comments" }, { "begin": ":", "beginCaptures": { "0": { "name": "punctuation.separator.dictionary.key-value.json.comments" } }, "end": "(,)|(?=\\})", "endCaptures": { "1": { "name": "punctuation.separator.dictionary.pair.json.comments" } }, "name": "meta.structure.dictionary.value.json.comments", "patterns": [ { "comment": "the JSON object value", "include": "#value" }, { "match": "[^\\s,]", "name": "invalid.illegal.expected-dictionary-separator.json.comments" } ] }, { "match": "[^\\s\\}]", "name": "invalid.illegal.expected-dictionary-separator.json.comments" } ] }, "string": { "begin": "\"", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.json.comments" } }, "end": "\"", "endCaptures": { "0": { "name": "punctuation.definition.string.end.json.comments" } }, "name": "string.quoted.double.json.comments", "patterns": [ { "include": "#stringcontent" } ] }, "objectkey": { "begin": "\"", "beginCaptures": { "0": { "name": "punctuation.support.type.property-name.begin.json.comments" } }, "end": "\"", "endCaptures": { "0": { "name": "punctuation.support.type.property-name.end.json.comments" } }, "name": "string.json.comments support.type.property-name.json.comments", "patterns": [ { "include": "#stringcontent" } ] }, "stringcontent": { "patterns": [ { "match": "(?x) # turn on extended mode\n \\\\ # a literal backslash\n (?: # ...followed by...\n [\"\\\\/bfnrt] # one of these characters\n | # ...or...\n u # a u\n [0-9a-fA-F]{4}) # and four hex digits", "name": "constant.character.escape.json.comments" }, { "match": "\\\\.", "name": "invalid.illegal.unrecognized-string-escape.json.comments" } ] }, "value": { "patterns": [ { "include": "#constant" }, { "include": "#number" }, { "include": "#string" }, { "include": "#array" }, { "include": "#object" }, { "include": "#comments" } ] } } }
extensions/json/syntaxes/JSONC.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.000176604138687253, 0.00017451460007578135, 0.00017205794574692845, 0.00017432952881790698, 0.0000011832514701382024 ]
{ "id": 5, "code_window": [ "\t\t\t\t\t}\n", "\t\t\t\t\tthis.setActiveItems(value);\n", "\t\t\t\t\tthis.userValue = value;\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [];\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t\tthis.filePickBox.onDidHide(() => {\n", "\t\t\t\tthis.hidden = true;\n", "\t\t\t\tif (!isResolving) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 232 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/node@^10.12.21": version "10.12.21" resolved "https://registry.yarnpkg.com/@types/node/-/node-10.12.21.tgz#7e8a0c34cf29f4e17a36e9bd0ea72d45ba03908e" integrity sha512-CBgLNk4o3XMnqMc0rhb6lc77IwShMEglz05deDcn2lQxyXEZivfwgYJu7SMha9V5XcrP6qZuevTHV/QrN2vjKQ== vscode-nls@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.0.0.tgz#4001c8a6caba5cedb23a9c5ce1090395c0e44002" integrity sha512-qCfdzcH+0LgQnBpZA53bA32kzp9rpq/f66Som577ObeuDlFIrtbEJ+A/+CCxjIh4G8dpJYNCKIsxpRAHIfsbNw==
extensions/gulp/yarn.lock
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00016980340296868235, 0.00016772153321653605, 0.0001656396489124745, 0.00016772153321653605, 0.000002081877028103918 ]
{ "id": 6, "code_window": [ "\t\t\t\tconst item = <FileQuickPickItem>this.filePickBox.items[i];\n", "\t\t\t\tconst itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri);\n", "\t\t\t\tif ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [item];\n", "\t\t\t\t\tthis.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\thasMatch = true;\n", "\t\t\t\t\tbreak;\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tif (!hasMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst insertValue = itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.autoComplete = value + insertValue;\n", "\t\t\t\t\tif (this.filePickBox.inputHasFocus()) {\n", "\t\t\t\t\t\tdocument.execCommand('insertText', false, insertValue);\n", "\t\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 358 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ResolvedKeybinding } from 'vs/base/common/keyCodes'; import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; export interface IQuickPickItem { type?: 'item'; id?: string; label: string; description?: string; detail?: string; iconClasses?: string[]; buttons?: IQuickInputButton[]; picked?: boolean; alwaysShow?: boolean; } export interface IQuickPickSeparator { type: 'separator'; label?: string; } export interface IKeyMods { readonly ctrlCmd: boolean; readonly alt: boolean; } export interface IQuickNavigateConfiguration { keybindings: ResolvedKeybinding[]; } export interface IPickOptions<T extends IQuickPickItem> { /** * an optional string to show as place holder in the input box to guide the user what she picks on */ placeHolder?: string; /** * an optional flag to include the description when filtering the picks */ matchOnDescription?: boolean; /** * an optional flag to include the detail when filtering the picks */ matchOnDetail?: boolean; /** * an optional flag to filter the picks based on label. Defaults to true. */ matchOnLabel?: boolean; /** * an option flag to control whether focus is always automatically brought to a list item. Defaults to true. */ autoFocusOnList?: boolean; /** * an optional flag to not close the picker on focus lost */ ignoreFocusLost?: boolean; /** * an optional flag to make this picker multi-select */ canPickMany?: boolean; /** * enables quick navigate in the picker to open an element without typing */ quickNavigate?: IQuickNavigateConfiguration; /** * a context key to set when this picker is active */ contextKey?: string; /** * an optional property for the item to focus initially. */ activeItem?: Promise<T> | T; onKeyMods?: (keyMods: IKeyMods) => void; onDidFocus?: (entry: T) => void; onDidTriggerItemButton?: (context: IQuickPickItemButtonContext<T>) => void; } export interface IInputOptions { /** * the value to prefill in the input box */ value?: string; /** * the selection of value, default to the whole word */ valueSelection?: [number, number]; /** * the text to display underneath the input box */ prompt?: string; /** * an optional string to show as place holder in the input box to guide the user what to type */ placeHolder?: string; /** * set to true to show a password prompt that will not show the typed value */ password?: boolean; ignoreFocusLost?: boolean; /** * an optional function that is used to validate user input. */ validateInput?: (input: string) => Promise<string | null | undefined>; } export interface IQuickInput { title: string | undefined; step: number | undefined; totalSteps: number | undefined; enabled: boolean; contextKey: string | undefined; busy: boolean; ignoreFocusOut: boolean; show(): void; hide(): void; onDidHide: Event<void>; dispose(): void; } export interface IQuickPick<T extends IQuickPickItem> extends IQuickInput { value: string; placeholder: string | undefined; readonly onDidChangeValue: Event<string>; readonly onDidAccept: Event<void>; buttons: ReadonlyArray<IQuickInputButton>; readonly onDidTriggerButton: Event<IQuickInputButton>; readonly onDidTriggerItemButton: Event<IQuickPickItemButtonEvent<T>>; items: ReadonlyArray<T | IQuickPickSeparator>; canSelectMany: boolean; matchOnDescription: boolean; matchOnDetail: boolean; matchOnLabel: boolean; autoFocusOnList: boolean; quickNavigate: IQuickNavigateConfiguration | undefined; activeItems: ReadonlyArray<T>; readonly onDidChangeActive: Event<T[]>; selectedItems: ReadonlyArray<T>; readonly onDidChangeSelection: Event<T[]>; readonly keyMods: IKeyMods; valueSelection: Readonly<[number, number]> | undefined; validationMessage: string | undefined; } export interface IInputBox extends IQuickInput { value: string; valueSelection: Readonly<[number, number]> | undefined; placeholder: string | undefined; password: boolean; readonly onDidChangeValue: Event<string>; readonly onDidAccept: Event<void>; buttons: ReadonlyArray<IQuickInputButton>; readonly onDidTriggerButton: Event<IQuickInputButton>; prompt: string | undefined; validationMessage: string | undefined; } export interface IQuickInputButton { /** iconPath or iconClass required */ iconPath?: { dark: URI; light?: URI; }; /** iconPath or iconClass required */ iconClass?: string; tooltip?: string; } export interface IQuickPickItemButtonEvent<T extends IQuickPickItem> { button: IQuickInputButton; item: T; } export interface IQuickPickItemButtonContext<T extends IQuickPickItem> extends IQuickPickItemButtonEvent<T> { removeItem(): void; } export const IQuickInputService = createDecorator<IQuickInputService>('quickInputService'); export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export type QuickPickInput<T = IQuickPickItem> = T | IQuickPickSeparator; export interface IQuickInputService { _serviceBrand: any; /** * Opens the quick input box for selecting items and returns a promise with the user selected item(s) if any. */ pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: true }, token?: CancellationToken): Promise<T[]>; pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: false }, token?: CancellationToken): Promise<T>; pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: Omit<IPickOptions<T>, 'canPickMany'>, token?: CancellationToken): Promise<T>; /** * Opens the quick input box for text input and returns a promise with the user typed value if any. */ input(options?: IInputOptions, token?: CancellationToken): Promise<string>; backButton: IQuickInputButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T>; createInputBox(): IInputBox; focus(): void; toggle(): void; navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void; accept(): Promise<void>; back(): Promise<void>; cancel(): Promise<void>; }
src/vs/platform/quickinput/common/quickInput.ts
1
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.0034575120080262423, 0.00039151706732809544, 0.00016377767315134406, 0.00016879875329323113, 0.0007513955351896584 ]
{ "id": 6, "code_window": [ "\t\t\t\tconst item = <FileQuickPickItem>this.filePickBox.items[i];\n", "\t\t\t\tconst itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri);\n", "\t\t\t\tif ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [item];\n", "\t\t\t\t\tthis.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\thasMatch = true;\n", "\t\t\t\t\tbreak;\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tif (!hasMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst insertValue = itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.autoComplete = value + insertValue;\n", "\t\t\t\t\tif (this.filePickBox.inputHasFocus()) {\n", "\t\t\t\t\t\tdocument.execCommand('insertText', false, insertValue);\n", "\t\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 358 }
{ "prettier.semi": true, "prettier.singleQuote": true, "prettier.printWidth": 120, }
extensions/css-language-features/.vscode/settings.json
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00016521125508006662, 0.00016521125508006662, 0.00016521125508006662, 0.00016521125508006662, 0 ]
{ "id": 6, "code_window": [ "\t\t\t\tconst item = <FileQuickPickItem>this.filePickBox.items[i];\n", "\t\t\t\tconst itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri);\n", "\t\t\t\tif ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [item];\n", "\t\t\t\t\tthis.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\thasMatch = true;\n", "\t\t\t\t\tbreak;\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tif (!hasMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst insertValue = itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.autoComplete = value + insertValue;\n", "\t\t\t\t\tif (this.filePickBox.inputHasFocus()) {\n", "\t\t\t\t\t\tdocument.execCommand('insertText', false, insertValue);\n", "\t\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 358 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import * as Proto from '../protocol'; import { ITypeScriptServiceClient } from '../typescriptService'; import API from '../utils/api'; import { ConditionalRegistration, ConfigurationDependentRegistration, VersionDependentRegistration } from '../utils/dependentRegistration'; import { Disposable } from '../utils/dispose'; import * as typeConverters from '../utils/typeConverters'; class TagClosing extends Disposable { private _disposed = false; private _timeout: NodeJS.Timer | undefined = undefined; private _cancel: vscode.CancellationTokenSource | undefined = undefined; constructor( private readonly client: ITypeScriptServiceClient ) { super(); vscode.workspace.onDidChangeTextDocument( event => this.onDidChangeTextDocument(event.document, event.contentChanges), null, this._disposables); } public dispose() { super.dispose(); this._disposed = true; if (this._timeout) { clearTimeout(this._timeout); this._timeout = undefined; } if (this._cancel) { this._cancel.cancel(); this._cancel.dispose(); this._cancel = undefined; } } private onDidChangeTextDocument( document: vscode.TextDocument, changes: vscode.TextDocumentContentChangeEvent[] ) { const activeDocument = vscode.window.activeTextEditor && vscode.window.activeTextEditor.document; if (document !== activeDocument || changes.length === 0) { return; } const filepath = this.client.toOpenedFilePath(document); if (!filepath) { return; } if (typeof this._timeout !== 'undefined') { clearTimeout(this._timeout); } if (this._cancel) { this._cancel.cancel(); this._cancel.dispose(); this._cancel = undefined; } const lastChange = changes[changes.length - 1]; const lastCharacter = lastChange.text[lastChange.text.length - 1]; if (lastChange.rangeLength > 0 || lastCharacter !== '>' && lastCharacter !== '/') { return; } const priorCharacter = lastChange.range.start.character > 0 ? document.getText(new vscode.Range(lastChange.range.start.translate({ characterDelta: -1 }), lastChange.range.start)) : ''; if (priorCharacter === '>') { return; } const version = document.version; this._timeout = setTimeout(async () => { this._timeout = undefined; if (this._disposed) { return; } const addedLines = lastChange.text.split(/\r\n|\n/g); const position = addedLines.length <= 1 ? lastChange.range.start.translate({ characterDelta: lastChange.text.length }) : new vscode.Position(lastChange.range.start.line + addedLines.length - 1, addedLines[addedLines.length - 1].length); const args: Proto.JsxClosingTagRequestArgs = typeConverters.Position.toFileLocationRequestArgs(filepath, position); this._cancel = new vscode.CancellationTokenSource(); const response = await this.client.execute('jsxClosingTag', args, this._cancel.token); if (response.type !== 'response' || !response.body) { return; } if (this._disposed) { return; } const activeEditor = vscode.window.activeTextEditor; if (!activeEditor) { return; } const insertion = response.body; const activeDocument = activeEditor.document; if (document === activeDocument && activeDocument.version === version) { activeEditor.insertSnippet( this.getTagSnippet(insertion), this.getInsertionPositions(activeEditor, position)); } }, 100); } private getTagSnippet(closingTag: Proto.TextInsertion): vscode.SnippetString { const snippet = new vscode.SnippetString(); snippet.appendPlaceholder('', 0); snippet.appendText(closingTag.newText); return snippet; } private getInsertionPositions(editor: vscode.TextEditor, position: vscode.Position) { const activeSelectionPositions = editor.selections.map(s => s.active); return activeSelectionPositions.some(p => p.isEqual(position)) ? activeSelectionPositions : position; } } export class ActiveDocumentDependentRegistration extends Disposable { private readonly _registration: ConditionalRegistration; constructor( private readonly selector: vscode.DocumentSelector, register: () => vscode.Disposable, ) { super(); this._registration = this._register(new ConditionalRegistration(register)); vscode.window.onDidChangeActiveTextEditor(this.update, this, this._disposables); vscode.workspace.onDidOpenTextDocument(this.onDidOpenDocument, this, this._disposables); this.update(); } private update() { const editor = vscode.window.activeTextEditor; const enabled = !!(editor && vscode.languages.match(this.selector, editor.document)); this._registration.update(enabled); } private onDidOpenDocument(openedDocument: vscode.TextDocument) { if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document === openedDocument) { // The active document's language may have changed this.update(); } } } export function register( selector: vscode.DocumentSelector, modeId: string, client: ITypeScriptServiceClient, ) { return new VersionDependentRegistration(client, API.v300, () => new ConfigurationDependentRegistration(modeId, 'autoClosingTags', () => new ActiveDocumentDependentRegistration(selector, () => new TagClosing(client)))); }
extensions/typescript-language-features/src/features/tagClosing.ts
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00017364145605824888, 0.000168442667927593, 0.0001650777121540159, 0.00016822692123241723, 0.000002835073246387765 ]
{ "id": 6, "code_window": [ "\t\t\t\tconst item = <FileQuickPickItem>this.filePickBox.items[i];\n", "\t\t\t\tconst itemBasename = (item.label === '..') ? item.label : resources.basename(item.uri);\n", "\t\t\t\tif ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) {\n", "\t\t\t\t\tthis.filePickBox.activeItems = [item];\n", "\t\t\t\t\tthis.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\thasMatch = true;\n", "\t\t\t\t\tbreak;\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t\tif (!hasMatch) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst insertValue = itemBasename.substr(inputBasename.length);\n", "\t\t\t\t\tthis.autoComplete = value + insertValue;\n", "\t\t\t\t\tif (this.filePickBox.inputHasFocus()) {\n", "\t\t\t\t\t\tdocument.execCommand('insertText', false, insertValue);\n", "\t\t\t\t\t\tthis.filePickBox.valueSelection = [value.length, this.filePickBox.value.length];\n", "\t\t\t\t\t}\n" ], "file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts", "type": "replace", "edit_start_line_idx": 358 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*eslint-env mocha*/ /*global define,run*/ var assert = require('assert'); var path = require('path'); var glob = require('glob'); var istanbul = require('istanbul'); var i_remap = require('remap-istanbul/lib/remap'); var jsdom = require('jsdom-no-contextify'); var minimatch = require('minimatch'); var fs = require('fs'); var vm = require('vm'); var TEST_GLOB = '**/test/**/*.test.js'; var optimist = require('optimist') .usage('Run the Code tests. All mocha options apply.') .describe('build', 'Run from out-build').boolean('build') .describe('run', 'Run a single file').string('run') .describe('coverage', 'Generate a coverage report').boolean('coverage') .describe('only-monaco-editor', 'Run only monaco editor tests').boolean('only-monaco-editor') .describe('forceLoad', 'Force loading').boolean('forceLoad') .describe('browser', 'Run tests in a browser').boolean('browser') .alias('h', 'help').boolean('h') .describe('h', 'Show help'); var argv = optimist.argv; if (argv.help) { optimist.showHelp(); process.exit(1); } var out = argv.build ? 'out-build' : 'out'; var loader = require('../' + out + '/vs/loader'); var src = path.join(path.dirname(__dirname), out); function main() { process.on('uncaughtException', function (e) { console.error(e.stack || e); }); var loaderConfig = { nodeRequire: require, nodeMain: __filename, baseUrl: path.join(path.dirname(__dirname), 'src'), paths: { 'vs/css': '../test/css.mock', 'vs': `../${out}/vs`, 'lib': `../${out}/lib`, 'bootstrap-fork': `../${out}/bootstrap-fork` }, catchError: true }; if (argv.coverage) { var instrumenter = new istanbul.Instrumenter(); var seenSources = {}; loaderConfig.nodeInstrumenter = function (contents, source) { seenSources[source] = true; if (minimatch(source, TEST_GLOB)) { return contents; } return instrumenter.instrumentSync(contents, source); }; process.on('exit', function (code) { if (code !== 0) { return; } if (argv.forceLoad) { var allFiles = glob.sync(out + '/vs/**/*.js'); allFiles = allFiles.map(function (source) { return path.join(__dirname, '..', source); }); allFiles = allFiles.filter(function (source) { if (seenSources[source]) { return false; } if (minimatch(source, TEST_GLOB)) { return false; } if (/fixtures/.test(source)) { return false; } return true; }); allFiles.forEach(function (source, index) { var contents = fs.readFileSync(source).toString(); contents = instrumenter.instrumentSync(contents, source); var stopAt = contents.indexOf('}\n__cov'); stopAt = contents.indexOf('}\n__cov', stopAt + 1); var str = '(function() {' + contents.substr(0, stopAt + 1) + '});'; var r = vm.runInThisContext(str, source); r.call(global); }); } let remapIgnores = /\b((marked)|(raw\.marked)|(nls)|(css))\.js$/; var remappedCoverage = i_remap(global.__coverage__, { exclude: remapIgnores }).getFinalCoverage(); // The remapped coverage comes out with broken paths var toUpperDriveLetter = function (str) { if (/^[a-z]:/.test(str)) { return str.charAt(0).toUpperCase() + str.substr(1); } return str; }; var toLowerDriveLetter = function (str) { if (/^[A-Z]:/.test(str)) { return str.charAt(0).toLowerCase() + str.substr(1); } return str; }; var REPO_PATH = toUpperDriveLetter(path.join(__dirname, '..')); var fixPath = function (brokenPath) { var startIndex = brokenPath.indexOf(REPO_PATH); if (startIndex === -1) { return toLowerDriveLetter(brokenPath); } return toLowerDriveLetter(brokenPath.substr(startIndex)); }; var finalCoverage = {}; for (var entryKey in remappedCoverage) { var entry = remappedCoverage[entryKey]; entry.path = fixPath(entry.path); finalCoverage[fixPath(entryKey)] = entry; } var collector = new istanbul.Collector(); collector.add(finalCoverage); var coveragePath = path.join(path.dirname(__dirname), '.build', 'coverage'); var reportTypes = []; if (argv.run || argv.runGlob) { // single file running coveragePath += '-single'; reportTypes = ['lcovonly']; } else { reportTypes = ['json', 'lcov', 'html']; } var reporter = new istanbul.Reporter(null, coveragePath); reporter.addAll(reportTypes); reporter.write(collector, true, function () { }); }); } loader.config(loaderConfig); global.define = loader; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.self = global.window = global.document.parentWindow; global.Element = global.window.Element; global.HTMLElement = global.window.HTMLElement; global.Node = global.window.Node; global.navigator = global.window.navigator; global.XMLHttpRequest = global.window.XMLHttpRequest; var didErr = false; var write = process.stderr.write; process.stderr.write = function (data) { didErr = didErr || !!data; write.apply(process.stderr, arguments); }; var loadFunc = null; if (argv.runGlob) { loadFunc = cb => { const doRun = tests => { const modulesToLoad = tests.map(test => { if (path.isAbsolute(test)) { test = path.relative(src, path.resolve(test)); } return test.replace(/(\.js)|(\.d\.ts)|(\.js\.map)$/, ''); }); define(modulesToLoad, () => cb(null), cb); }; glob(argv.runGlob, { cwd: src }, function (err, files) { doRun(files); }); }; } else if (argv.run) { var tests = (typeof argv.run === 'string') ? [argv.run] : argv.run; var modulesToLoad = tests.map(function (test) { test = test.replace(/^src/, 'out'); test = test.replace(/\.ts$/, '.js'); return path.relative(src, path.resolve(test)).replace(/(\.js)|(\.js\.map)$/, '').replace(/\\/g, '/'); }); loadFunc = cb => { define(modulesToLoad, () => cb(null), cb); }; } else if (argv['only-monaco-editor']) { loadFunc = function (cb) { glob(TEST_GLOB, { cwd: src }, function (err, files) { var modulesToLoad = files.map(function (file) { return file.replace(/\.js$/, ''); }); modulesToLoad = modulesToLoad.filter(function (module) { if (/^vs\/workbench\//.test(module)) { return false; } // platform tests drag in the workbench. // see https://github.com/Microsoft/vscode/commit/12eaba2f64c69247de105c3d9c47308ac6e44bc9 // and cry a little if (/^vs\/platform\//.test(module)) { return false; } return !/(\/|\\)node(\/|\\)/.test(module); }); console.log(JSON.stringify(modulesToLoad, null, '\t')); define(modulesToLoad, function () { cb(null); }, cb); }); }; } else { loadFunc = function (cb) { glob(TEST_GLOB, { cwd: src }, function (err, files) { var modulesToLoad = files.map(function (file) { return file.replace(/\.js$/, ''); }); define(modulesToLoad, function () { cb(null); }, cb); }); }; } loadFunc(function (err) { if (err) { console.error(err); return process.exit(1); } process.stderr.write = write; if (!argv.run && !argv.runGlob) { // set up last test suite('Loader', function () { test('should not explode while loading', function () { assert.ok(!didErr, 'should not explode while loading'); }); }); } // report failing test for every unexpected error during any of the tests var unexpectedErrors = []; suite('Errors', function () { test('should not have unexpected errors in tests', function () { if (unexpectedErrors.length) { unexpectedErrors.forEach(function (stack) { console.error(''); console.error(stack); }); assert.ok(false); } }); }); // replace the default unexpected error handler to be useful during tests loader(['vs/base/common/errors'], function (errors) { errors.setUnexpectedErrorHandler(function (err) { let stack = (err && err.stack) || (new Error().stack); unexpectedErrors.push((err && err.message ? err.message : err) + '\n' + stack); }); // fire up mocha run(); }); }); } if (process.argv.some(function (a) { return /^--browser/.test(a); })) { require('./browser'); } else { main(); }
test/all.js
0
https://github.com/microsoft/vscode/commit/9eb5669101936ea91eabe2751ec721cbd5ccc17f
[ 0.00022246748267207295, 0.00017133384244516492, 0.00016498456534463912, 0.00016811296518426389, 0.00001107274874811992 ]
{ "id": 0, "code_window": [ "{\n", " \"name\": \"gatsby\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@emotion/react\": \"latest\",\n", " \"@emotion/server\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/gatsby/package.json", "type": "add", "edit_start_line_idx": 4 }
{ "name": "ssr", "version": "5.0.0", "private": true, "dependencies": { "@babel/core": "latest", "@babel/node": "latest", "@babel/plugin-proposal-class-properties": "latest", "@babel/preset-env": "latest", "@babel/preset-react": "latest", "@emotion/cache": "latest", "@emotion/react": "latest", "@emotion/styled": "latest", "@emotion/server": "latest", "@mui/material": "latest", "babel-loader": "latest", "cross-env": "latest", "express": "latest", "nodemon": "latest", "npm-run-all": "latest", "react": "latest", "react-dom": "latest", "webpack": "latest", "webpack-cli": "latest" }, "scripts": { "start": "npm-run-all -p build serve", "build": "webpack -w", "serve": "nodemon --ignore ./build --exec babel-node -- server.js", "production": "cross-env NODE_ENV=production npm start", "post-update": "echo \"codesandbox preview only, need an update\" && yarn upgrade --latest" } }
examples/ssr/package.json
1
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00036578852450475097, 0.000217221982893534, 0.00016575910558458418, 0.00016867014346644282, 0.00008580192661611363 ]
{ "id": 0, "code_window": [ "{\n", " \"name\": \"gatsby\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@emotion/react\": \"latest\",\n", " \"@emotion/server\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/gatsby/package.json", "type": "add", "edit_start_line_idx": 4 }
import * as React from 'react'; import Box from '@mui/material/Box'; import { green } from '@mui/material/colors'; import Icon from '@mui/material/Icon'; export default function Icons() { return ( <Box sx={{ '& > :not(style)': { m: 2, }, }} > <Icon>add_circle</Icon> <Icon color="primary">add_circle</Icon> <Icon sx={{ color: green[500] }}>add_circle</Icon> <Icon fontSize="small">add_circle</Icon> <Icon sx={{ fontSize: 30 }}>add_circle</Icon> </Box> ); }
docs/src/pages/components/icons/Icons.tsx
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00018026727775577456, 0.00017525797011330724, 0.0001713513192953542, 0.00017415531328879297, 0.000003722496103364392 ]
{ "id": 0, "code_window": [ "{\n", " \"name\": \"gatsby\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@emotion/react\": \"latest\",\n", " \"@emotion/server\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/gatsby/package.json", "type": "add", "edit_start_line_idx": 4 }
<Tabs value={value} onChange={handleChange} variant="scrollable" scrollButtons allowScrollButtonsMobile aria-label="scrollable force tabs example" > <Tab label="Item One" /> <Tab label="Item Two" /> <Tab label="Item Three" /> <Tab label="Item Four" /> <Tab label="Item Five" /> <Tab label="Item Six" /> <Tab label="Item Seven" /> </Tabs>
docs/src/pages/components/tabs/ScrollableTabsButtonForce.tsx.preview
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00017903445404954255, 0.0001786269567674026, 0.00017821945948526263, 0.0001786269567674026, 4.0749728213995695e-7 ]
{ "id": 0, "code_window": [ "{\n", " \"name\": \"gatsby\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@emotion/react\": \"latest\",\n", " \"@emotion/server\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/gatsby/package.json", "type": "add", "edit_start_line_idx": 4 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "12", cy: "19", r: "2" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M10 3h4v12h-4z" }, "1")], 'PriorityHigh'); exports.default = _default;
packages/mui-icons-material/lib/PriorityHigh.js
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00017733951972331852, 0.00017295459110755473, 0.00016784323088359088, 0.00017368103726767004, 0.000003910725808964344 ]
{ "id": 1, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function getEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/gatsby/plugins/gatsby-plugin-mui-emotion/getEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
{ "name": "gatsby", "version": "5.0.0", "private": true, "dependencies": { "@emotion/react": "latest", "@emotion/server": "latest", "@emotion/styled": "latest", "@mui/material": "latest", "gatsby": "latest", "gatsby-plugin-react-helmet": "latest", "react": "latest", "react-dom": "latest", "react-helmet": "latest" }, "scripts": { "develop": "gatsby develop", "build": "gatsby build", "serve": "gatsby serve", "post-update": "echo \"codesandbox preview only, need an update\" && yarn upgrade --latest" } }
examples/gatsby/package.json
1
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00018259123316965997, 0.0001762422762112692, 0.00017038988880813122, 0.00017574573575984687, 0.000004993537459085928 ]
{ "id": 1, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function getEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/gatsby/plugins/gatsby-plugin-mui-emotion/getEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M4 20h16V4H4v16z" fill="none"/><path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z"/></svg>
packages/mui-icons-material/material-icons/nfc_24px.svg
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00016972844605334103, 0.00016972844605334103, 0.00016972844605334103, 0.00016972844605334103, 0 ]
{ "id": 1, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function getEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/gatsby/plugins/gatsby-plugin-mui-emotion/getEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
<svg width="40" height="40" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect width="40" height="40" rx="4" fill="url(#pattern0)"/> <defs> <pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1"> <use xlink:href="#image0" transform="scale(.00167)"/> </pattern> <image id="image0" width="600" height="600" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAJYCAYAAAC+ZpjcAAApC0lEQVR42u3d6ZdcZ4Hn+d+9EZlSppRaLMmW9wXbGDCL8bCVqYJiN0tBQVV1TVVXdc/0mfk7+uWcftNnemZezHTX1KmpqRoKsxkMGLANeMF4KWww3mTLi6x9lzKVyiXi3nkRkmx5Q8KPycjMz+ccLQZZfuJm5I1vPPeJ51bvvv5jbQAAKKZe6AEAACw1AgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACACisu9ADYOlo23ahh8AQqqpqoYcA8HsnsDgjbdumbds0TXPq94OeatPtdjM6Opput5tOp5Nup5OqrlLXVapUgxfYl7zIVqd+Yqlr+k2Oz8xmZmZm6AK81+udeD4v9EhYENVpv7zif6xO/GZw+qpO+wFnQmDxupqmTds2GR0dzYYN52TjhvVZs2Yiq1aNZ3xsLKOjIxldMZoVJwOr20m37qSq61R1lSpJ/aqB5SS11FVVlcnJqfz6N4/noYceyezs7NC8OFVVlfde966cf/656Xa7ichaFtqXfqHbwT+3bZITbx77TTP4tdfP/Px85ubnMzM7m+np45maPJYjR4/m2LHpVFWdTqcemuczw0lg8bpWrRrLBedvzsUXXZCrrr4iV1x+aS44f3M2bjwn69atyfjYmJMMr2nf/gPpdrt59NEnMjMzMzTPlbqu89kbP54//sgNGR8fG7rZNd4c7Ut/bpO2aQeR1TTp9fvpzfcy3+tlfm4+x2dmcmz6eCYnp3Lo0OHs2bMvO3buys6de3Lo0OHsP3Do1MzssDyvGS4Ci1dXJWsmJnLde96Zr3z5c3nve96ZsbGxU9PlibU1nIE2aZpmKGeIxlauzMTE6oyPjy30UFgALzb1az8529P/YHq9fg4cPJj77n8oP77tZ3ns8S05cuTo4DkOLyOweIW2bbNmYiKf++wn8rf/9s9zzvr1GR0dEVQsKZ7Py9uLX/7Xfh68fDnD6Gid887dlE9/8qP54Afem5u/c2u+c8uPsn37Ts8nXkFg8QpN0+Rjf/zhfPlLn835m89b6OEADI26rjM2tjJjYyvz5S99Lkny//7z1zM5eWyhh8aQsQ8Wp6mqKpdcclE+8P735qorr1jo4QAMrU2bNuSGP3h/PvD+681g8QoCi9NUVZX3vPsdufyySxZ6KABD74rLL8kffvgDGR0ZWeihMGQEFqepqipvf/vV2bz53IUeCsDQGx8fz1uuuCwbN21IXXtJ5UWeDZym06lz6SUXZ/26tQs9FIBFYfXqVXnbW6/MyMiILT84RWBxSl3XWbd2bdZMrF7ooQAsGitXrsiFF56fbqfjzgCcIrBIMtiaoa7rbNhwTlaMji70cAAWjRUrVmTz5nPT6dQZyk3fWBACi1PqusratWvSHbF7B8CZGhnpZv26tdZgcRrPBk6pqzoTE6vS7QgsgDPV7XQzMbE6lcDiJTwbOKWqq6waHzsxzQ3Ameh0O1m1ajx1VVmDxSleSXmJKiMjI6a5Ac5CXddZsWL0tNvqgFdSTqmqZGTEPQcBzkZdVSfOnYlF7pwksEgyOCVUqTIy0k1VCyyAM1WdDKw4d/IigcXAoLBS17WTBMBZ6nQ6cerkpQQWp6nr2iVCgLPUsXaVl/GM4DR1XXsXBnCWqqoy+89pBBYAvEHWrvJyAgsA3iBLK3g5gQUAUJjA4pQq3oUBQAkCCwCgMIHFKW2S1o20AOANE1gAAIUJLAB4g8z+83ICCwDeKH3FywgsTtNvmngjBnB2mrZJq7J4CYHFaZp+E4UFcHaaxnmT0wksBqokbdI0fe/CAM5S028WeggMGYFFkpN91WZ+vpfWOzGAs9Lr90z+cxqBxSlt22Zuft5UN8BZaJom83PzlldwGoHFKW2bzM3NpWlNdQOcqZNvTgfLK9xujAGBxSlt2+TYsen0+/2FHgrAotHv93P8+PHBXlj6ihMEFqc0TZvJyan0er2FHgrAotHr9TM5dSxN0+orThFYnFClaZocOnwk8/MCC+BM9Xq9HD58NE1jeQUvElgkSapqsFBz374DmZmZWejhACwac3Nz2b/vgMDiNAKLU9q2zfT0dA4cOOQyIcAZmpmZzc5du9Pv91NVLhIyILA4TdM0efqZ57L/wMGFHgrAonDs2HSe3LLV8gpOI7A4TdO0eeihR7J9+66FHgrA0Ov3+9m1e2+2b99pBovTCCxO07ZtHnt8Sx5/YkuOHZte6OEADLUXtu/M/Q88lKlj04NtGuAEgcUrHD58JHfdfV/uve/BHD9uwTvAq5mePp5//ddf5c677l3ooTCEugs9AIZPp9PJ/Q88lLYd/P6697wzYytXZnR0xPQ3sOzN93qZnZ3NnXfem1u+f1te2L7TuZFXEFi8pocefiS7du3O+973nnz0j27Ite94a9auXZOqqvPSc4kTy5vDcYWF0yan7i340t/Pzc3n6a3P5tYf/iR333Nftu8QV7w6gcVrmp+fz46du3P0jrvz8MOPZu26NTl/87k5f/N52XDO+qxbvzarxsczPr4yK1YMZri63U66nU7quk5V16mqKnVVDU5AbZs4Ef1WbZJOp87qVauyevWqhR4OLCtt22Z+fj7Tx2cyPX08k5NTOXTocPbtP5Dt23fmmWe3Zfv2ndm9Z1+OHj2aXs/Cdl6dwOI1VVWVtm1z+PCRHDx4KEmyatV41kxMZHx8LGPjYxkdHcnoyEi63W46nU46nXoQVyej6sTfc/rpp3K/rtfRtm3WTKzOR/7oQ/noR25Y6OEwxA4fPpIHf/nrPPzwI6lqS2rPVNUmbdq0bZumbZO2Tb/fpN80aZom/V4/8735zM3NZ3Z2LtPTxzN17NiJc+HhHD8+M3jzWFfiitcksPit6noQTclgQ73jx2fStu2JGfMXfz3186t+kMana85U2yabNm7IRRddILB4XUcnp3L//b/M//cv306321no4SwebZs2eUVgte3JndirF98HVlWqVKcFlWPNmRBYnJWXzkzx5mjbNiOjI+l0nMT5Ldr2xJud1hYBv4OqqtI5cT7z/UZp5pQBFjnveWD4CCwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsIA3T5VUVZVUCz2Q1xwewJtCYAFvml6vn6mpqTRNMwitIdI0TZq2XehhAEuUwALeFFNTx7Jly9N5csvW9Hq9hR7Oadq2zZannskL23dmfn5+oYcDLEHdhR4AsLQ0TZOjk1P56c/uyVe/9u1s2fLM0M1gNU2Tb377e5mZmcmffvHGXH31lVmxYnShhwUsIQILKKZpmuzevTdf+/p3c+uP7sj+/QfSNM1CD+tVzczM5pbv/zgvbN+Zr3z58/nYR2/IyMjIUIUgsHgJLKCI+fn5/PqRx3PTN76T+x94KAcPHUk7ZDNXLzczM5tf/fqxTE5O5fnnt+cv/uwLWb9+3UIPC1gCBBbwhh05cjR33X1fbv3RHfnlQ49kcnIqnU5nqOMqSeq6zszMTJ7csjWTU8dy5MjRfPFPPpO3XHFpul2nR+B35wwCvCHbd+zKz+78eb7/g9vz2ONPpt9v0ul0FnpYZ6yu6zRNk+3bd+bb37k1U1PH8plP/3Heee3bMjGxeqGHByxSAgv4nczOzWXbtu35wa135Du3/Cj79u1PVVWp68X34eSTM23Hjk3n5u/emr379ueLX/h03v++9+acc9ZnyCfigCEksICz0rZtjs/M5Iknnso/f/Vbuevu+zI7Ozv0lwPPxOAhVLn3Fw9m9+692bFrd774hc9k/fp16S6iWTlg4Qks4KxMTx/PbXfcla/ddHOeevqZzM0twX2kqirbXtiRr/7LzXn22W35D//DX+WSiy+0Lgs4Y84WwBnbsXN3vvnNW/KTn/08217Ykbm5uUV5SfC3qZL0+/3s338gd919Xw4ePJS/+ssv5/r3vivj4+MLPTxgERBYwG/V6/XyyCOP57vf+1Hu+fkD2b1nb5Isybg66eQlzyNHjuaBBx/OzMxsdu3akz/88Adz/vnnLfTwgCEnsIDXdfjI0fzyl7/O975/W+659/5MTx9f0mH1clVVZX6+lwcefDhHj07m4KEj+dgf35CrrrxiSaw7A94cAgt4VU3TZO/e/fn5Lx7IN7/1/Tzym8eTLO1Zq9dSVVW63W6e3PJMDh48nN279+QrX/58rrzy8oytXLnQwwOGkMACXqHX62XX7r351s3fzy3f+3H27NlntiZJt9vJocNHcuuPfpLnt+3I//Qf/jrXvuOaTEysdnyA0yy/t6LA65rv9fLoY1vyn//X/zPf/Nb3sm/fAfHwMjMzs3n0sSfyv/yn/5If3HpH9u8/uNBDAoaMGSzglMnJqfzsrnvzjW99L1u2bM2xY9Np29ho81XMzc3nhe278vf/z1fz/Lbt+fznPpm3v+3qhR4WMCQEFpC2bbPthR257fY78+PbfpYtTz2Tfr+fqqrE1eto2zbbt+/MrT/6SQ4dPpzPfOpjueGG99uUFBBYsNzNz8/nsSeeym2335nbbr8z27btSLc7/DdqHhbdbjf79u3PHT+5JwcOHMzk1FT+4EPvy7q1a1PXjiEsVwILlrGpqWN59LEnc9M3vpuf3/tAJienMjLitHC2Op1OZmZm8sCDv8qu3XszNTWVP/jQ+3P+5vMcT1imfOfDMtQ0TY4cOZpf3PfL/P0/fDXPPrct8/Pz6bi09TurqurEJcNd+d/+j/87O3buyedu/ETe8pbLMuIWO7Ds+K6HZWjnzt357vd+nG/f/IMcOHgovV5voYe0ZLRtm+np4/n6N76b5597IV/58ufz4Rs+kE7Hh7ZhORFYsIy0bZsH//VXufm7t+bn9z6YgwcPpc3g3nuU07Ztjh2bzv0PPpxDh49k2ws78qdfvDGrVo1b2wbLhMCCZeL48eO5/Y6786PbfppfPvRIDh8+km63K67eJHVdZ3p6Oo8+9mQmp6Zy6NDhfOHzn87FF52frkuGsOT5Loclrmma7N6zL3feeW++c8sP8+SWrZmbm/ci/3tQ13X6/X6efXZbvnHolkwdO5ZPfeKjeds1V2XVqvGFHh7wJnKGhSVsdnYuz2/bntvvuCtf/8Z3c+DgobRtaz3Q79HJS4KHDx/NTV//bvbtO5AvfP5Tuf66d2Xt2jULPTzgTSKwYImanZ3Nb37zRL757e/nR7f97NRCdmuAFsbJTxn+5Kf3ZMfOXfnSn9yYGz/98axZs9qnN2EJEliwxLRtm9nZudz6wzvyrZt/kMce35L5+fmFHhYvsXXrc/mHf/xann12W/7d3/xFNm8+L92uyIKlRGDBEtK2bfbtO5Cvfu3b+dld92bbth2ZnZ1NXbskOEx6vX727t2f226/M/v2H8hf//dfyTuvvSYrV65c6KEBhQgsWCJmZ+fy5Jatufm7t+buu+/L3n370+/3xdUQqqoqTdvmwMHD+fm9D+b48Zl89saP54YPvS8bN25Y6OEBBQgsWAIOHz6Shx7+TW794R356Z0/z8zMbJJKXA2xKklVV5mdnc3P730gRycnc+jQkXz0I3+Qyy69eKGHB7xBAgsWsbZts2//gdxzz/35zi0/zIP/+qt0Om7UvJhUVZVOp5Pf/OaJ7Nt3MHv27suX/uQzuezSSzI6OuJrCYuUwIJFan6+l30HDuSmm76TH/74p9mxY5dPoy1inU4n+/cfyLdv/kG2bduR//Hf/2XeevWVdn+HRUpgwSI0NzeXp7c+l//6d/+Uhx9+JEeOHPUivEQcPz6TBx58OHv27s/f/NWf5SN/9MGsW7d2oYcFnCWBBYvMkaOT+cUvHsy/3HRzntyyNceOTadtW4G1hMzOzubZZ5/P3/39P+X5bS/kC5//VC6/7JKFHhZwFgQWLCLPPf9CfvLTe/Lj236Wx594Kk3TpKoqcbXEVFWVXq+XZ5/blu99/7YcPHgon73xE/nvrn+3Dy7AIiGwYBFomiaPPbYlP7rtp7n9J3fn2ee2ZWTEAuil7OTi9527dueHP/5pDh46nKNHJ/O+912XNROrfe1hyAksGHJTU8fyxBNP5as33Zxf3PevOXLkaEZHRhZ6WPyedDqdTE8fz11335fdu/dmcmoqH3j/9dl83iaRBUNMYMEQqjKYtTp6dDL33//L/Ne//+c888zzmZ+f90nBZejkfQy3PPVM/sv//t/yZ1/ek89/9hNpmmbwZAGGTmfzBZf/x4UeBHC6idWrs2HjOdm+fWf+r//2j9mxc/epmzWzvM3OzmXLlmeyc/eedLvd7Nt3II8+9qS1WTBkqndf/7F2oQcBnG7FitGsXTORqq6zZ8++tDFRwYvats3q1auy+bxNmZmZzfYdu1wuhCHjEiEModnZuezZuz9N0wx2Zl/oATFUqqrK5ORUjh2b9ilSGFLmlGFInfwUGbyak5cE29ZFCBhGAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1jAm6Jtk6ZNOkO6g0DTDsYI8GYQWEBxTZuMjSSXrKlzydo63ToZtpY5Z6zK2EiVZtgGBiwJAgsobmU3efe5nfz5NSP5o4s7WdGphmq2qK6SD13YybvOrbN6tIp9OoHS7OQOFFMlWTlS5TNXdPOlq7pZPVrl+1ubhR7Wq47z3Zs6ueqcKj/d1s93nurl6Fw7VBEILG4CC3jD2gymw89bXeXP3jqSP7y4m4snqhycGdJiqZKRTnLpmjpfeWudzaurfP2JXp4/0qTfuu8j8MYJLOAN6bfJyk7yjk2dfPYt3Xzowk42jVXpDOG6q1NOLHDv1FUumEg+fmk3E6NVfrC1l1/u7ufYfNK1gAJ4AwQW8DvrNcmGsSrXb67zycu6ueGiblZ0F88n9Nq2TdNWWb+yyscu7WZipMq6FVXu29XPvuk2dWU2C/jdCCzgrJ28JHj+6iofvqiTL1zZzds3dZITWzMsNie3k/jQRZ2ct6rKupWDtVl7jrlkCPxuBBZw1kbr5LxVVb509Ug+dXk3m8aH61OCv6u2TS5fV+dvrx3JhaurfP3J+eycajPXX+iRAYuNwALOymgnuWZDJ3997UiuO7fO6pGlN7+zdkWVG9/SzYVr6vzTo/N5ZG8/syILOAsCCzgjvSZZt7LKRy7u5E+uGslV59QZ7w7xQvY3oKqSVaNVrjuvkzWjVW55upfbn+vl4Exr8TtwRgQW8LraDNYoXb6uyicu6+ajl3Rz1fo6nXpxrrc648fdJmPd5O0b66zodLNxvMqPn+3lmcNNqsTmpMDrEljAa2rak5cE63zy8m4+enE3568e3F5mKcfVSx9/klx9Tp11K6usW5H88NleHj/QZLY32BEe4NUILOAV2gw+Obd2RZW3b6zzp1d388ELOxnrVukvg7B6uX6bbByv8vkrR7JpVZ1vPjmfx/Y3OTrbnjpWAC8lsIBX6FTJuhVVPnhhJ3/5tpG8ZX2duloes1avpT0xm/fhCzs5f1WVrz42n3t39nN4pl3WxwV4dQILOE2bZPOJLRg+fXk3G8Yrl8JeoqqSK9bV+Z+vG81l63r59pb5bJ9szWIBpxFYQJITm4dWyXvP6+RLV3fz3vM62TBWpcrS/KTgG9GpknPHq9x4RTebx6t8a0svD+3pp4nLhcCAwALStMmaFcmHL+rm01d0864T+1s1rbh6NSePyabxKn9wUSerR6tsGq9yz45+js62ZvwAgQXLWdMOZq0uWVPnhos6+cwV3VyzwXqrM9W0yerRwVq1tSurrFlZ5Z7tveycbNO2tnKA5UxgwTLVtsmKTnLZ2jofv6ybz13ZzXnjg08Jiqszd/JYXbuxzsaxbtavSG5/vp9tR5rM9m3lAMuVwIJlqEqyYmSwv9W/edtoPnhBJ2PdLMstGErpt8mm8Tr/5u2juXhNP197fC5PHmzcxxCWKYEFy9D4SPKRS7r582tGctnaOiudCYoZ6yYfvqiT81evyE2Pz+euF3qZ7i30qIDfN6dVWEbaNrloosrnruzm45d1c8HqOiO1hewlVRlE1tXn1Pn37xrJhRNVbtnay56p1posWEYEFiwDTZt06uS6zZ18+rJuPnRhJ5tXV2l9SvBN0SYZrZPL19X5wpUjWb+yzg+f7eXRff30W+uyYDkQWLCEtRnMWq1dkVy/uZtPX9HJBy7oZGK0Sq9Z6NEtbe2Jny5aU+XGKzpZs2Jw66GH9vQzOdemI7JgSRNYsES1GWyIuXG8ygcu7OQrbx3JVevrdOqIq9+jXpOsXlHl45d1s3lVndWjyQO7+jl0vLUxKSxhAguWqJE6OX91nRuv6OaLV3ezbsXgljeta4K/d207iN1rN9U5d9Vozh2fz4+f7WXf8TZ9sQtLksCCJahTJ9du7OQr1wzWW413Kwush0B94hY7f/2O0Vyyps7Xn5zP0wcb22PAEiSwYAlp2sEWDJ+8fCSfubyTazbWWTVSmbUaInWVrFuRfPSSTjaOVfnO1vncta2fOZuSwpIisGAJaNskVXLhRJXPXDGSj1zSyZXr6ox2bB46jNoMFrxfv7mT8dHk3LEqtz3Xz97pwX0MdRYsfgILFrnmxC1vrjpncMubT17Wzbnjg1dpcTW8+m0y2k3etamT9SurTIxWueP5fp470qTXmM2CxU5gwSI22IKhyts21Pncld388SXdjHZe3CKA4Xby0u0lE3X+8u0jOWesyg+29vL0oTbT8zYmhcVMYMEiVVfJ6tEqf3RxJ3969UjevqlOoqsWozbJqpEqf3LVSC6cqHPTE708tLuf6fnW1xMWKYEFi1BVJRvG6vzl27r5yCWdbF5dL/SQKKBTJdefN1j8/r2tVW55upejsxILFiOBBYtI0yYjneRtGzr5i2u6ue68TjaMValr+1stFSOd5LK1db589UguXD3YyuHZw01OfI4BWCQEFiwSvSY5Z2WV91/QyY1v6ea6c+uMjwxecsXV0tGc2JT0ookqqy7tZPVo8v2tvTy0p5/jvbjFDiwSAguGXJvBi+6la+vccGEnn7y8k3ee2xn8f8JqSTr5ZV0/VuXjl3ayZrTKuhVVHtjdzz5bOcCiILBgiLVJRuvkojV1PnNFN5+6vJuLJ6rMu73KstC2SaeucsNFnWwcr7J2ZZW7X+hl97E2/VZkwTATWDCkqiRj3SpXrKvzt9eO5L2b60yMiqvlqN8O9jn7d9eO5OKJKjc9MZ9dU63nAgwxgQVDqE0yMVrlAxd08m+vHckla+qs7NqCYTlr22T9yiqfvqKbi9bU+cdH5vObff3MiSwYSgILhkybwczVRy/t5G/eMZLzV9fp2oWBDLbnmBit8p5zO5l4b5Vvbenlzhd6OTrXulwIQ8ZpG4bQym5y8USdt6yvM+K7lJcZ6ybXbqpz3eY65612M28YRk7dMIQ6VZW6Gnx60GsnL9dmsJP/2hVV1oyau4JhJLBgKMkqfjsBDsNLYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWAEBhAgsAoDCBBQBQmMACAChMYAEAFCawAAAKE1gAAIUJLACAwgQWsPxUCz2Actp2oUcAvBqBBSxPVZZUaAHDRWABb542GeYJlmEeG7C4CSwYUkvmxX8YH0h74tLaMI4NWBIEFgyhpfLiP8wPY1jHddYPYkk8EFh6BBYMoaX0ujmsi7DbtIv+GLdL4lHA0iSwYAgtlcBqkzRD+kDaIV8fdsaPYbE/CFiiBBYMoaYd3jA5KyceR5vh+8BevxnEybCN62y0qdIu6kcAS5fAgiHUb9v0l8DURJNkvlnoUby6/hKI2KXyPIGlSGDBEOo3VXrNIp+ZqAYzRPPNcF7Gmu8PImsx6zWDH8DwEVgwZKokvaZNf7FPr2QwQzTXH861TvNN0izyOOk3iz8SYakSWDCE5vqDH4t5DqtK0rRtjvfatEM4hTXTH0TWoj3GVTLbbzPXtwoLhpHAgiE03wxePId1/dKZ6jXJ1NyJjQSGqALaJMfn28wv4lnCKslsP5npZaiOLTAgsGAIVUlme8mx+cUdAL0mOTLbDuVi8sm5NrO9pFrEcTLdG/wAho/AgiE13WtzaGZxbyM5208OHh8E1rB1zKGZNtO9xXt023YwO3hsziVCGEYCC4ZQVSVTc8ne6cW7G2avHczAHR7CGay2TfZNt5maG77wO1OT88nR2TZz/YUeCfBqBBYMoTrJ4Zk2LxxpFmVf1dXg0uALk236Q7iOrE2yY2oQf4uxsNokOyabHJ4xewXDSmDBEKqqwQzLU4cWb2DtPdbmyQP9oR3/sbk2OyabHDi+CCOlTZ4+1GT/8XZRryGDpUxgwRCqq+ToXJuth9psn2yGcg3T62naZNvRJr/e2x/KTUaTwSzQ4weabDnYpLPIzoSz/eTXe/vZNdWmXkxPDFhGFtlpBZaPfptsn2py+3O9HJ0dVMqwv5ZWGcThtqNtfrm7yXNHhneRfl0lj+9v8sCu/uBS27Af3AxmNntN8tj+fh7Z1+TQjMCCYSWwYEh1quTAdJtbnu7lV3v6OTTTDv2u3fNNcnCmzfe2zuen23pDHS1VBmP9xY5+frKtn8khXIz/Um0Gm8++cLTJPz3ay87JNp0hPr6w3HU2X3D5f1zoQQCv7XgveXT/4JV/41ididHqxVmhamFntdoTP7VJ5ppk6+Em//Dr+dzxfD8Hjw9xrZxQV4PtGp4/2qbXJBdMVFnRqQbHdIGPbfLi8U0G23Y8tKfJ3/16Pr/e1+R4b3HMusFyVb37+o8N/1kQlrkqycbxKhdN1LnynDrXnFPn0rVVzh2rc85YlRXdV/47pb6xX+s1fGpuMAO0a6rJs4ebbDnU5qmD/eyYbDM116bJwgfKmWjbpFsnG8arXDxR59pNnbx1Q51L19Y5b7zKmtHTNyNtX/GbN6g67ZdTf/Vsv82B6eSFySZbDzV5bH+TJw822XOsGezeDgw1gQWLRL8dXDZcu6LKeauqrF9ZZfVIlVWjycpulZXdZEWnykgn6VZJpx78+SpJVVUnfn39b/e2HbzMt2nTtkmTF28o3G8Gl6hm+m1meoNbzRybHyzGP3i8zb7pNkdPbHq52NYFtRmEVl0lm8arnDteZ/1YlYnRZNVIlfFuMjZSZUUnGamrdOqkW7Wp62qwzuLUcU5e8xBXL/53Tv7atEm/Hcye9dpkrje49c3xXpup+TbH5pLDs232T7fZO91mcq5Nt1rcu8/DctF9438F8Ptwcr3NoZk2B463p71Yj9Q5LbA6rxlYSfLq2xIMLkcNLj+eDKw2g0XV/bZKv2lPBdZsL6fWK1XVIEzql4xxsXnx2CR7jrXZNdU/9fjrKhnvJitHqqzsJN26SrceHN+Tj/vkv1u91mXFNq8bWP0mmX9JYM302sz0XxzXyf/OiFWzsGgILFhk6urVZ4jm+oPLSkle5fLVmU5Uv8afe8m0TJXBJbWl6tWO71yTzM62OfKSRVFvyiXYl1wuXNFZ6CMBvBECC5aQ6hW/oZTq1E8v+WeA17CE34cCACwMgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABQmsAAAChNYAACFCSwAgMIEFgBAYQILAKAwgQUAUJjAAgAoTGABABT2/wNzSptWrBGgJQAAAABJRU5ErkJggg=="/> </defs> </svg>
docs/public/static/sponsors/tidelift.svg
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.0004882083158008754, 0.0004882083158008754, 0.0004882083158008754, 0.0004882083158008754, 0 ]
{ "id": 1, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function getEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/gatsby/plugins/gatsby-plugin-mui-emotion/getEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 5.5c-5.25 0-9.01-1.54-10-1.92V20.4c2.16-.76 5.21-1.9 10-1.9 4.78 0 7.91 1.17 10 1.9V3.6c-2.09.73-5.23 1.9-10 1.9zm0 9.5c-2.34 0-4.52.15-6.52.41l3.69-4.42 2 2.4L14 10l4.51 5.4c-1.99-.25-4.21-.4-6.51-.4z" }), 'VrpanoSharp'); exports.default = _default;
packages/mui-icons-material/lib/VrpanoSharp.js
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.0002894121571443975, 0.00022822902246844023, 0.00016704588779248297, 0.00022822902246844023, 0.00006118313467595726 ]
{ "id": 2, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function createEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/ssr/createEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
{ "name": "gatsby", "version": "5.0.0", "private": true, "dependencies": { "@emotion/react": "latest", "@emotion/server": "latest", "@emotion/styled": "latest", "@mui/material": "latest", "gatsby": "latest", "gatsby-plugin-react-helmet": "latest", "react": "latest", "react-dom": "latest", "react-helmet": "latest" }, "scripts": { "develop": "gatsby develop", "build": "gatsby build", "serve": "gatsby serve", "post-update": "echo \"codesandbox preview only, need an update\" && yarn upgrade --latest" } }
examples/gatsby/package.json
1
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00018479478603694588, 0.00017692428082227707, 0.00017029163427650928, 0.00017568643670529127, 0.000005985235020489199 ]
{ "id": 2, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function createEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/ssr/createEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M2 17v3h2v-4H3c-.55 0-1 .45-1 1zm7-1H5v4l4.69-.01c.38 0 .72-.21.89-.55l.87-1.9-1.59-3.48L9 16zm12.71.29c-.18-.18-.43-.29-.71-.29h-1v4h2v-3c0-.28-.11-.53-.29-.71zm-8.11-3.45L17.65 4H14.3l-1.76 3.97-.49 1.1-.05.14L9.7 4H6.35l4.05 8.84 1.52 3.32.08.18 1.42 3.1c.17.34.51.55.89.55L19 20v-4h-4l-1.4-3.16z" }), 'SportsHockey');
packages/mui-icons-material/lib/esm/SportsHockey.js
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00016904350195545703, 0.00016904350195545703, 0.00016904350195545703, 0.00016904350195545703, 0 ]
{ "id": 2, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function createEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/ssr/createEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("ellipse", { cx: "12", cy: "12", rx: "3", ry: "5.74" }, "0"), /*#__PURE__*/_jsx("path", { d: "M16.5 12c0 .97-.23 4.16-3.03 6.5.78.31 1.63.5 2.53.5 3.86 0 7-3.14 7-7s-3.14-7-7-7c-.9 0-1.75.19-2.53.5 2.8 2.34 3.03 5.53 3.03 6.5zM8 19c.9 0 1.75-.19 2.53-.5-.61-.51-1.1-1.07-1.49-1.63-.33.08-.68.13-1.04.13-2.76 0-5-2.24-5-5s2.24-5 5-5c.36 0 .71.05 1.04.13.39-.56.88-1.12 1.49-1.63C9.75 5.19 8.9 5 8 5c-3.86 0-7 3.14-7 7s3.14 7 7 7z" }, "1")], 'JoinRightTwoTone');
packages/mui-icons-material/lib/esm/JoinRightTwoTone.js
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.0001772531250026077, 0.00017255410784855485, 0.000167855090694502, 0.00017255410784855485, 0.000004699017154052854 ]
{ "id": 2, "code_window": [ "import createCache from '@emotion/cache';\n", "\n", "export default function createEmotionCache() {\n", " return createCache({ key: 'css' });\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return createCache({ key: 'css', prepend: true });\n" ], "file_path": "examples/ssr/createEmotionCache.js", "type": "replace", "edit_start_line_idx": 3 }
import * as React from 'react'; import { expect } from 'chai'; import { describeConformance, createRenderer } from 'test/utils'; import Radio, { radioClasses as classes } from '@mui/material/Radio'; import FormControl from '@mui/material/FormControl'; import ButtonBase from '@mui/material/ButtonBase'; describe('<Radio />', () => { const { render } = createRenderer(); describeConformance(<Radio />, () => ({ classes, inheritComponent: ButtonBase, render, muiName: 'MuiRadio', testVariantProps: { color: 'secondary' }, refInstanceof: window.HTMLSpanElement, skip: ['componentProp', 'componentsProp'], })); describe('styleSheet', () => { it('should have the classes required for SwitchBase', () => { expect(typeof classes.root).to.equal('string'); expect(typeof classes.checked).to.equal('string'); expect(typeof classes.disabled).to.equal('string'); }); }); describe('prop: unchecked', () => { it('should render an unchecked icon', () => { const { getAllByTestId } = render(<Radio />); expect(getAllByTestId('RadioButtonUncheckedIcon').length).to.equal(1); }); }); describe('prop: checked', () => { it('should render a checked icon', () => { const { getAllByTestId } = render(<Radio checked />); expect(getAllByTestId('RadioButtonCheckedIcon').length).to.equal(1); }); }); describe('with FormControl', () => { describe('enabled', () => { it('should not have the disabled class', () => { const { getByRole } = render( <FormControl> <Radio /> </FormControl>, ); expect(getByRole('radio')).not.to.have.attribute('disabled'); }); it('should be overridden by props', () => { const { getByRole } = render( <FormControl> <Radio disabled /> </FormControl>, ); expect(getByRole('radio')).to.have.attribute('disabled'); }); }); describe('disabled', () => { it('should have the disabled class', () => { const { getByRole } = render( <FormControl disabled> <Radio /> </FormControl>, ); expect(getByRole('radio')).to.have.attribute('disabled'); }); it('should be overridden by props', () => { const { getByRole } = render( <FormControl disabled> <Radio disabled={false} /> </FormControl>, ); expect(getByRole('radio')).not.to.have.attribute('disabled'); }); }); }); });
packages/mui-material/src/Radio/Radio.test.js
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00017399016360286623, 0.0001696877443464473, 0.00016625710122752935, 0.0001692126679699868, 0.0000024558378299843753 ]
{ "id": 3, "code_window": [ "{\n", " \"name\": \"ssr\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@babel/core\": \"latest\",\n", " \"@babel/node\": \"latest\",\n", " \"@babel/plugin-proposal-class-properties\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/ssr/package.json", "type": "add", "edit_start_line_idx": 4 }
{ "name": "ssr", "version": "5.0.0", "private": true, "dependencies": { "@babel/core": "latest", "@babel/node": "latest", "@babel/plugin-proposal-class-properties": "latest", "@babel/preset-env": "latest", "@babel/preset-react": "latest", "@emotion/cache": "latest", "@emotion/react": "latest", "@emotion/styled": "latest", "@emotion/server": "latest", "@mui/material": "latest", "babel-loader": "latest", "cross-env": "latest", "express": "latest", "nodemon": "latest", "npm-run-all": "latest", "react": "latest", "react-dom": "latest", "webpack": "latest", "webpack-cli": "latest" }, "scripts": { "start": "npm-run-all -p build serve", "build": "webpack -w", "serve": "nodemon --ignore ./build --exec babel-node -- server.js", "production": "cross-env NODE_ENV=production npm start", "post-update": "echo \"codesandbox preview only, need an update\" && yarn upgrade --latest" } }
examples/ssr/package.json
1
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.9951643943786621, 0.24891862273216248, 0.0001643737341510132, 0.00017286640650127083, 0.43084517121315 ]
{ "id": 3, "code_window": [ "{\n", " \"name\": \"ssr\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@babel/core\": \"latest\",\n", " \"@babel/node\": \"latest\",\n", " \"@babel/plugin-proposal-class-properties\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/ssr/package.json", "type": "add", "edit_start_line_idx": 4 }
export { default } from './CardActionArea'; export { default as cardActionAreaClasses } from './cardActionAreaClasses'; export * from './cardActionAreaClasses';
packages/mui-material/src/CardActionArea/index.js
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00017588572518434376, 0.00017588572518434376, 0.00017588572518434376, 0.00017588572518434376, 0 ]
{ "id": 3, "code_window": [ "{\n", " \"name\": \"ssr\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@babel/core\": \"latest\",\n", " \"@babel/node\": \"latest\",\n", " \"@babel/plugin-proposal-class-properties\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/ssr/package.json", "type": "add", "edit_start_line_idx": 4 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M12 5.99 19.53 19H4.47L12 5.99M12 2 1 21h22L12 2zm1 14h-2v2h2v-2zm0-6h-2v4h2v-4z" }), 'ReportProblemOutlined');
packages/mui-icons-material/lib/esm/ReportProblemOutlined.js
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.0001732025993987918, 0.0001732025993987918, 0.0001732025993987918, 0.0001732025993987918, 0 ]
{ "id": 3, "code_window": [ "{\n", " \"name\": \"ssr\",\n", " \"version\": \"5.0.0\",\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@babel/core\": \"latest\",\n", " \"@babel/node\": \"latest\",\n", " \"@babel/plugin-proposal-class-properties\": \"latest\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"browserslist\": [\n", " \">0.25%\",\n", " \"not dead\"\n", " ],\n" ], "file_path": "examples/ssr/package.json", "type": "add", "edit_start_line_idx": 4 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M6 15.5c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5V12H6v3.5zm6-3c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zM12 3C6 3 6 4.2 6 5h12c0-.8 0-2-6-2z" opacity=".3"/><path d="M20 15.5V5c0-3.5-3.58-4-8-4s-8 .5-8 4v10.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5zm-2 0c0 .83-.67 1.5-1.5 1.5h-9c-.83 0-1.5-.67-1.5-1.5V12h12v3.5zm0-5.5H6V7h12v3zM6 5c0-.8 0-2 6-2s6 1.2 6 2H6zm6 11.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"/></svg>
packages/mui-icons-material/material-icons/directions_railway_two_tone_24px.svg
0
https://github.com/mui/material-ui/commit/4e5d86c871d497306e448e99ec937439e95e3375
[ 0.00031217624200508, 0.00031217624200508, 0.00031217624200508, 0.00031217624200508, 0 ]
{ "id": 0, "code_window": [ " DISCONNECT_EVENT,\n", " ERROR_EVENT,\n", " RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT,\n", " RQM_DEFAULT_NOACK,\n", " RQM_DEFAULT_PREFETCH_COUNT,\n", " RQM_DEFAULT_QUEUE,\n", " RQM_DEFAULT_QUEUE_OPTIONS,\n", " RQM_DEFAULT_URL,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " RQM_DEFAULT_PERSISTENT,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 12 }
import { Transport } from '../enums/transport.enum'; import { ChannelOptions } from '../external/grpc-options.interface'; import { CompressionTypes, ConsumerConfig, KafkaConfig, ProducerConfig, } from '../external/kafka-options.interface'; import { MqttClientOptions } from '../external/mqtt-options.interface'; import { ClientOpts } from '../external/redis.interface'; import { Server } from '../server/server'; import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Deserializer } from './deserializer.interface'; import { Serializer } from './serializer.interface'; export type MicroserviceOptions = | GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | RmqOptions | KafkaOptions | CustomStrategy; export interface CustomStrategy { strategy: Server & CustomTransportStrategy; options?: {}; } export interface GrpcOptions { transport?: Transport.GRPC; options: { url?: string; maxSendMessageLength?: number; maxReceiveMessageLength?: number; maxMetadataSize?: number; keepalive?: { keepaliveTimeMs?: number; keepaliveTimeoutMs?: number; keepalivePermitWithoutCalls?: number; http2MaxPingsWithoutData?: number; http2MinTimeBetweenPingsMs?: number; http2MinPingIntervalWithoutDataMs?: number; http2MaxPingStrikes?: number; }; channelOptions?: ChannelOptions; credentials?: any; protoPath: string | string[]; package: string | string[]; protoLoader?: string; loader?: { keepCase?: boolean; alternateCommentMode?: boolean; longs?: Function; enums?: Function; bytes?: Function; defaults?: boolean; arrays?: boolean; objects?: boolean; oneofs?: boolean; json?: boolean; includeDirs?: string[]; }; }; } export interface TcpOptions { transport?: Transport.TCP; options?: { host?: string; port?: number; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RedisOptions { transport?: Transport.REDIS; options?: { url?: string; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; } & ClientOpts; } export interface MqttOptions { transport?: Transport.MQTT; options?: MqttClientOptions & { url?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface NatsOptions { transport?: Transport.NATS; options?: { url?: string; name?: string; user?: string; pass?: string; maxReconnectAttempts?: number; reconnectTimeWait?: number; servers?: string[]; reconnect?: boolean; pedantic?: boolean; tls?: any; queue?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RmqOptions { transport?: Transport.RMQ; options?: { urls?: string[]; queue?: string; prefetchCount?: number; isGlobalPrefetchCount?: boolean; queueOptions?: any; socketOptions?: any; noAck?: boolean; serializer?: Serializer; deserializer?: Deserializer; replyQueue?: string; }; } export interface KafkaOptions { transport?: Transport.KAFKA; options?: { client?: KafkaConfig; consumer?: ConsumerConfig; run?: { autoCommit?: boolean; autoCommitInterval?: number | null; autoCommitThreshold?: number | null; eachBatchAutoResolve?: boolean; partitionsConsumedConcurrently?: number; }; subscribe?: { fromBeginning?: boolean; }; producer?: ProducerConfig; send?: { acks?: number; timeout?: number; compression?: CompressionTypes; }; serializer?: Serializer; deserializer?: Deserializer; }; }
packages/microservices/interfaces/microservice-configuration.interface.ts
1
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0040343510918319225, 0.0006738886004313827, 0.0001661700807744637, 0.00017056759679690003, 0.0011348892003297806 ]
{ "id": 0, "code_window": [ " DISCONNECT_EVENT,\n", " ERROR_EVENT,\n", " RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT,\n", " RQM_DEFAULT_NOACK,\n", " RQM_DEFAULT_PREFETCH_COUNT,\n", " RQM_DEFAULT_QUEUE,\n", " RQM_DEFAULT_QUEUE_OPTIONS,\n", " RQM_DEFAULT_URL,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " RQM_DEFAULT_PERSISTENT,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 12 }
import { expect } from 'chai'; import { ROUTE_ARGS_METADATA } from '../../constants'; import { createParamDecorator } from '../../decorators/http/create-route-param-metadata.decorator'; import { ParseIntPipe } from '../../index'; describe('createParamDecorator', () => { let result; beforeEach(() => { const fn = (data, req) => true; result = createParamDecorator(fn); }); it('should return a function as a first element', () => { expect(result).to.be.a('function'); }); describe('returned decorator', () => { const factoryFn = (data, req) => true; const Decorator = createParamDecorator(factoryFn); describe('when 0 pipes have been passed', () => { const data = { data: 'test' }; class Test { public test(@Decorator(data) param) {} } it('should enhance param with "data"', () => { const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test'); const key = Object.keys(metadata)[0]; expect(metadata[key]).to.be.eql({ data, factory: factoryFn, index: 0, pipes: [], }); }); }); describe('when > 0 pipes have been passed', () => { const data = 'test'; const pipe = new ParseIntPipe(); class Test { public test( @Decorator(data, pipe) param, ) {} public testNoData(@Decorator(pipe) param) {} public testNoDataClass(@Decorator(ParseIntPipe) param) {} } it('should enhance param with "data" and ParseIntPipe', () => { const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test'); const key = Object.keys(metadata)[0]; expect(metadata[key]).to.be.eql({ data: 'test', factory: factoryFn, index: 0, pipes: [pipe], }); }); it('should enhance param with ParseIntPipe', () => { const metadata = Reflect.getMetadata( ROUTE_ARGS_METADATA, Test, 'testNoData', ); const key = Object.keys(metadata)[0]; expect(metadata[key]).to.be.eql({ data: undefined, factory: factoryFn, index: 0, pipes: [pipe], }); }); it('should enhance param with ParseIntPipe metatype', () => { const metadata = Reflect.getMetadata( ROUTE_ARGS_METADATA, Test, 'testNoDataClass', ); const key = Object.keys(metadata)[0]; expect(metadata[key]).to.be.eql({ data: undefined, factory: factoryFn, index: 0, pipes: [ParseIntPipe], }); }); }); describe('when class type passed as data', () => { class Data {} class Test { public test(@Decorator(Data) prop) {} } it('should return class type as data parameter', () => { const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test'); const key = Object.keys(metadata)[0]; expect(metadata[key].data).to.equal(Data); }); }); }); describe('returned generic typed decorator', () => { const factoryFn = (data, req) => true; interface User { name: string; } const stringOnlyDecorator = createParamDecorator<string>(factoryFn); const stringOrNumberDecorator = createParamDecorator<string | number>( factoryFn, ); const customTypeDecorator = createParamDecorator<User>(factoryFn); describe('when string is passed to stringOnlyDecorator', () => { const data = 'test'; class Test { public test( @stringOnlyDecorator(data) param, ) {} } it('should enhance param with "data" as string', () => { const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test'); const key = Object.keys(metadata)[0]; expect(metadata[key]).to.be.eql({ data: 'test', factory: factoryFn, index: 0, pipes: [], }); }); }); describe('when number is passed to stringOrNumberDecorator', () => { const data = 10; class Test { public test( @stringOrNumberDecorator(data) param, ) {} } it('should enhance param with "data" as number', () => { const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test'); const key = Object.keys(metadata)[0]; expect(metadata[key]).to.be.eql({ data: 10, factory: factoryFn, index: 0, pipes: [], }); }); }); describe('when a custom Type is passed to customTypeDecorator', () => { const data = { name: 'john' }; class Test { public test( @customTypeDecorator(data) param, ) {} } it('should enhance param with "data" as custom Type', () => { const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test'); const key = Object.keys(metadata)[0]; expect(metadata[key]).to.be.eql({ data: { name: 'john' }, factory: factoryFn, index: 0, pipes: [], }); }); }); }); });
packages/common/test/decorators/create-param-decorator.spec.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00018227081454824656, 0.00017008751456160098, 0.0001674808154348284, 0.00016903947107493877, 0.000003313839897600701 ]
{ "id": 0, "code_window": [ " DISCONNECT_EVENT,\n", " ERROR_EVENT,\n", " RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT,\n", " RQM_DEFAULT_NOACK,\n", " RQM_DEFAULT_PREFETCH_COUNT,\n", " RQM_DEFAULT_QUEUE,\n", " RQM_DEFAULT_QUEUE_OPTIONS,\n", " RQM_DEFAULT_URL,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " RQM_DEFAULT_PERSISTENT,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 12 }
export * from './request-method.enum'; export * from './http-status.enum'; export * from './shutdown-signal.enum';
packages/common/enums/index.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0001722739834804088, 0.0001722739834804088, 0.0001722739834804088, 0.0001722739834804088, 0 ]
{ "id": 0, "code_window": [ " DISCONNECT_EVENT,\n", " ERROR_EVENT,\n", " RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT,\n", " RQM_DEFAULT_NOACK,\n", " RQM_DEFAULT_PREFETCH_COUNT,\n", " RQM_DEFAULT_QUEUE,\n", " RQM_DEFAULT_QUEUE_OPTIONS,\n", " RQM_DEFAULT_URL,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " RQM_DEFAULT_PERSISTENT,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 12 }
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'prettier', 'prettier/@typescript-eslint', ], root: true, env: { node: true, jest: true, }, rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-explicit-any': 'off', }, };
sample/10-fastify/.eslintrc.js
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0001709620701149106, 0.00016920304915402085, 0.00016818287258502096, 0.0001684642193140462, 0.0000012491042298279353 ]
{ "id": 1, "code_window": [ " protected queue: string;\n", " protected queueOptions: any;\n", " protected responseEmitter: EventEmitter;\n", " protected replyQueue: string;\n", "\n", " constructor(protected readonly options: RmqOptions['options']) {\n", " super();\n", " this.urls = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL];\n", " this.queue =\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " protected persistent: boolean;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 34 }
import { Transport } from '../enums/transport.enum'; import { ChannelOptions } from '../external/grpc-options.interface'; import { CompressionTypes, ConsumerConfig, KafkaConfig, ProducerConfig, } from '../external/kafka-options.interface'; import { MqttClientOptions } from '../external/mqtt-options.interface'; import { ClientOpts } from '../external/redis.interface'; import { Server } from '../server/server'; import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Deserializer } from './deserializer.interface'; import { Serializer } from './serializer.interface'; export type MicroserviceOptions = | GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | RmqOptions | KafkaOptions | CustomStrategy; export interface CustomStrategy { strategy: Server & CustomTransportStrategy; options?: {}; } export interface GrpcOptions { transport?: Transport.GRPC; options: { url?: string; maxSendMessageLength?: number; maxReceiveMessageLength?: number; maxMetadataSize?: number; keepalive?: { keepaliveTimeMs?: number; keepaliveTimeoutMs?: number; keepalivePermitWithoutCalls?: number; http2MaxPingsWithoutData?: number; http2MinTimeBetweenPingsMs?: number; http2MinPingIntervalWithoutDataMs?: number; http2MaxPingStrikes?: number; }; channelOptions?: ChannelOptions; credentials?: any; protoPath: string | string[]; package: string | string[]; protoLoader?: string; loader?: { keepCase?: boolean; alternateCommentMode?: boolean; longs?: Function; enums?: Function; bytes?: Function; defaults?: boolean; arrays?: boolean; objects?: boolean; oneofs?: boolean; json?: boolean; includeDirs?: string[]; }; }; } export interface TcpOptions { transport?: Transport.TCP; options?: { host?: string; port?: number; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RedisOptions { transport?: Transport.REDIS; options?: { url?: string; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; } & ClientOpts; } export interface MqttOptions { transport?: Transport.MQTT; options?: MqttClientOptions & { url?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface NatsOptions { transport?: Transport.NATS; options?: { url?: string; name?: string; user?: string; pass?: string; maxReconnectAttempts?: number; reconnectTimeWait?: number; servers?: string[]; reconnect?: boolean; pedantic?: boolean; tls?: any; queue?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RmqOptions { transport?: Transport.RMQ; options?: { urls?: string[]; queue?: string; prefetchCount?: number; isGlobalPrefetchCount?: boolean; queueOptions?: any; socketOptions?: any; noAck?: boolean; serializer?: Serializer; deserializer?: Deserializer; replyQueue?: string; }; } export interface KafkaOptions { transport?: Transport.KAFKA; options?: { client?: KafkaConfig; consumer?: ConsumerConfig; run?: { autoCommit?: boolean; autoCommitInterval?: number | null; autoCommitThreshold?: number | null; eachBatchAutoResolve?: boolean; partitionsConsumedConcurrently?: number; }; subscribe?: { fromBeginning?: boolean; }; producer?: ProducerConfig; send?: { acks?: number; timeout?: number; compression?: CompressionTypes; }; serializer?: Serializer; deserializer?: Deserializer; }; }
packages/microservices/interfaces/microservice-configuration.interface.ts
1
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.014041561633348465, 0.0019549301359802485, 0.000168847109307535, 0.00029985158471390605, 0.00387727958150208 ]
{ "id": 1, "code_window": [ " protected queue: string;\n", " protected queueOptions: any;\n", " protected responseEmitter: EventEmitter;\n", " protected replyQueue: string;\n", "\n", " constructor(protected readonly options: RmqOptions['options']) {\n", " super();\n", " this.urls = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL];\n", " this.queue =\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " protected persistent: boolean;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 34 }
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); console.log(`Application is running on: ${await app.getUrl()}`); } bootstrap();
sample/22-graphql-prisma/src/main.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0001723398600006476, 0.0001723398600006476, 0.0001723398600006476, 0.0001723398600006476, 0 ]
{ "id": 1, "code_window": [ " protected queue: string;\n", " protected queueOptions: any;\n", " protected responseEmitter: EventEmitter;\n", " protected replyQueue: string;\n", "\n", " constructor(protected readonly options: RmqOptions['options']) {\n", " super();\n", " this.urls = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL];\n", " this.queue =\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " protected persistent: boolean;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 34 }
import { expect } from 'chai'; import { REDIRECT_METADATA } from '../../constants'; import { Redirect } from '../../decorators/http/redirect.decorator'; import { HttpStatus } from '../../index'; describe('@Redirect', () => { const url = 'http://test.com'; const statusCode = HttpStatus.FOUND; class Test { @Redirect(url, statusCode) public static test() {} } it('should enhance method with expected redirect url string', () => { const metadata = Reflect.getMetadata(REDIRECT_METADATA, Test.test); expect(metadata.url).to.be.eql(url); }); it('should enhance method with expected response code', () => { const metadata = Reflect.getMetadata(REDIRECT_METADATA, Test.test); expect(metadata.statusCode).to.be.eql(statusCode); }); });
packages/common/test/decorators/redirect.decorator.spec.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0001748529903125018, 0.0001730314252199605, 0.00017106629093177617, 0.00017317502351943403, 0.0000015492441889364272 ]
{ "id": 1, "code_window": [ " protected queue: string;\n", " protected queueOptions: any;\n", " protected responseEmitter: EventEmitter;\n", " protected replyQueue: string;\n", "\n", " constructor(protected readonly options: RmqOptions['options']) {\n", " super();\n", " this.urls = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL];\n", " this.queue =\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " protected persistent: boolean;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 34 }
/** * Interface describing options for serving static assets. * * @see [Serving static files in Express](https://expressjs.com/en/starter/static-files.html) * @see [Model-View-Controller](https://docs.nestjs.com/techniques/mvc) * * @publicApi */ export interface ServeStaticOptions { /** * Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). * Note this check is done on the path itself without checking if the path actually exists on the disk. * If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). * The default value is 'ignore'. * 'allow' No special treatment for dotfiles * 'deny' Send a 403 for any request for a dotfile * 'ignore' Pretend like the dotfile does not exist and call next() */ dotfiles?: string; /** * Enable or disable etag generation, defaults to true. */ etag?: boolean; /** * Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. * The first that exists will be served. Example: ['html', 'htm']. * The default value is false. */ extensions?: string[]; /** * Let client errors fall-through as unhandled requests, otherwise forward a client error. * The default value is false. */ fallthrough?: boolean; /** * Enable or disable the immutable directive in the Cache-Control response header. * If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed. */ immutable?: boolean; /** * By default this module will send "index.html" files in response to a request on a directory. * To disable this set false or to supply a new index pass a string or an array in preferred order. */ index?: boolean | string | string[]; /** * Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value. */ lastModified?: boolean; /** * Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module. */ maxAge?: number | string; /** * Redirect to trailing "/" when the pathname is a dir. Defaults to true. */ redirect?: boolean; /** * Function to set custom headers on response. Alterations to the headers need to occur synchronously. * The function is called as `fn(res, path, stat)`, where the arguments are: * `res` - the response object * `path` - the file path that is being sent * `stat` - the stat object of the file that is being sent */ setHeaders?: (res: any, path: string, stat: any) => any; /** * Creates a virtual path prefix */ prefix?: string; }
packages/platform-express/interfaces/serve-static-options.interface.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0006376848323270679, 0.0002299446932738647, 0.0001631829800317064, 0.00016905850498005748, 0.00015437624824699014 ]
{ "id": 2, "code_window": [ " this.queueOptions =\n", " this.getOptionsProp(this.options, 'queueOptions') ||\n", " RQM_DEFAULT_QUEUE_OPTIONS;\n", " this.replyQueue =\n", " this.getOptionsProp(this.options, 'replyQueue') || REPLY_QUEUE;\n", " loadPackage('amqplib', ClientRMQ.name, () => require('amqplib'));\n", " rqmPackage = loadPackage('amqp-connection-manager', ClientRMQ.name, () =>\n", " require('amqp-connection-manager'),\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.persistent =\n", " this.getOptionsProp(this.options, 'persistent') || RQM_DEFAULT_PERSISTENT;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 45 }
import { Logger } from '@nestjs/common/services/logger.service'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util'; import { EventEmitter } from 'events'; import { fromEvent, merge, Observable } from 'rxjs'; import { first, map, share, switchMap } from 'rxjs/operators'; import { DISCONNECTED_RMQ_MESSAGE, DISCONNECT_EVENT, ERROR_EVENT, RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT, RQM_DEFAULT_NOACK, RQM_DEFAULT_PREFETCH_COUNT, RQM_DEFAULT_QUEUE, RQM_DEFAULT_QUEUE_OPTIONS, RQM_DEFAULT_URL, } from '../constants'; import { ReadPacket, RmqOptions, WritePacket } from '../interfaces'; import { ClientProxy } from './client-proxy'; let rqmPackage: any = {}; const REPLY_QUEUE = 'amq.rabbitmq.reply-to'; export class ClientRMQ extends ClientProxy { protected readonly logger = new Logger(ClientProxy.name); protected connection: Promise<any>; protected client: any = null; protected channel: any = null; protected urls: string[]; protected queue: string; protected queueOptions: any; protected responseEmitter: EventEmitter; protected replyQueue: string; constructor(protected readonly options: RmqOptions['options']) { super(); this.urls = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL]; this.queue = this.getOptionsProp(this.options, 'queue') || RQM_DEFAULT_QUEUE; this.queueOptions = this.getOptionsProp(this.options, 'queueOptions') || RQM_DEFAULT_QUEUE_OPTIONS; this.replyQueue = this.getOptionsProp(this.options, 'replyQueue') || REPLY_QUEUE; loadPackage('amqplib', ClientRMQ.name, () => require('amqplib')); rqmPackage = loadPackage('amqp-connection-manager', ClientRMQ.name, () => require('amqp-connection-manager'), ); this.initializeSerializer(options); this.initializeDeserializer(options); } public close(): void { this.channel && this.channel.close(); this.client && this.client.close(); this.channel = null; this.client = null; } public consumeChannel() { const noAck = this.getOptionsProp(this.options, 'noAck', RQM_DEFAULT_NOACK); this.channel.addSetup((channel: any) => channel.consume( this.replyQueue, (msg: any) => this.responseEmitter.emit(msg.properties.correlationId, msg), { noAck, }, ), ); } public connect(): Promise<any> { if (this.client) { return this.connection; } this.client = this.createClient(); this.handleError(this.client); this.handleDisconnectError(this.client); const connect$ = this.connect$(this.client); this.connection = this.mergeDisconnectEvent(this.client, connect$) .pipe( switchMap(() => this.createChannel()), share(), ) .toPromise(); return this.connection; } public createChannel(): Promise<void> { return new Promise(resolve => { this.channel = this.client.createChannel({ json: false, setup: (channel: any) => this.setupChannel(channel, resolve), }); }); } public createClient<T = any>(): T { const socketOptions = this.getOptionsProp(this.options, 'socketOptions'); return rqmPackage.connect(this.urls, { connectionOptions: socketOptions, }) as T; } public mergeDisconnectEvent<T = any>( instance: any, source$: Observable<T>, ): Observable<T> { const close$ = fromEvent(instance, DISCONNECT_EVENT).pipe( map((err: any) => { throw err; }), ); return merge(source$, close$).pipe(first()); } public async setupChannel(channel: any, resolve: Function) { const prefetchCount = this.getOptionsProp(this.options, 'prefetchCount') || RQM_DEFAULT_PREFETCH_COUNT; const isGlobalPrefetchCount = this.getOptionsProp(this.options, 'isGlobalPrefetchCount') || RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT; await channel.assertQueue(this.queue, this.queueOptions); await channel.prefetch(prefetchCount, isGlobalPrefetchCount); this.responseEmitter = new EventEmitter(); this.responseEmitter.setMaxListeners(0); this.consumeChannel(); resolve(); } public handleError(client: any): void { client.addListener(ERROR_EVENT, (err: any) => this.logger.error(err)); } public handleDisconnectError(client: any): void { client.addListener(DISCONNECT_EVENT, (err: any) => { this.logger.error(DISCONNECTED_RMQ_MESSAGE); this.logger.error(err); this.close(); }); } public handleMessage( packet: unknown, callback: (packet: WritePacket) => any, ) { const { err, response, isDisposed } = this.deserializer.deserialize(packet); if (isDisposed || err) { callback({ err, response, isDisposed: true, }); } callback({ err, response, }); } protected publish( message: ReadPacket, callback: (packet: WritePacket) => any, ): Function { try { const correlationId = randomStringGenerator(); const listener = ({ content }: { content: any }) => this.handleMessage(JSON.parse(content.toString()), callback); Object.assign(message, { id: correlationId }); const serializedPacket = this.serializer.serialize(message); this.responseEmitter.on(correlationId, listener); this.channel.sendToQueue( this.queue, Buffer.from(JSON.stringify(serializedPacket)), { replyTo: this.replyQueue, correlationId, }, ); return () => this.responseEmitter.removeListener(correlationId, listener); } catch (err) { callback({ err }); } } protected dispatchEvent(packet: ReadPacket): Promise<any> { const serializedPacket = this.serializer.serialize(packet); return new Promise((resolve, reject) => this.channel.sendToQueue( this.queue, Buffer.from(JSON.stringify(serializedPacket)), {}, err => (err ? reject(err) : resolve()), ), ); } }
packages/microservices/client/client-rmq.ts
1
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.998434841632843, 0.22935080528259277, 0.00016548226994927973, 0.00017925549764186144, 0.41600358486175537 ]
{ "id": 2, "code_window": [ " this.queueOptions =\n", " this.getOptionsProp(this.options, 'queueOptions') ||\n", " RQM_DEFAULT_QUEUE_OPTIONS;\n", " this.replyQueue =\n", " this.getOptionsProp(this.options, 'replyQueue') || REPLY_QUEUE;\n", " loadPackage('amqplib', ClientRMQ.name, () => require('amqplib'));\n", " rqmPackage = loadPackage('amqp-connection-manager', ClientRMQ.name, () =>\n", " require('amqp-connection-manager'),\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.persistent =\n", " this.getOptionsProp(this.options, 'persistent') || RQM_DEFAULT_PERSISTENT;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 45 }
import { RequestMethod } from '@nestjs/common'; import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface'; import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface'; import { isFunction, isNil, isObject } from '@nestjs/common/utils/shared.utils'; import { AbstractHttpAdapter } from '@nestjs/core/adapters/http-adapter'; import { RouterMethodFactory } from '@nestjs/core/helpers/router-method-factory'; import * as bodyParser from 'body-parser'; import * as cors from 'cors'; import * as express from 'express'; import * as http from 'http'; import * as https from 'https'; import { ServeStaticOptions } from '../interfaces/serve-static-options.interface'; export class ExpressAdapter extends AbstractHttpAdapter { private readonly routerMethodFactory = new RouterMethodFactory(); constructor(instance?: any) { super(instance || express()); } public reply(response: any, body: any, statusCode?: number) { if (statusCode) { response.status(statusCode); } if (isNil(body)) { return response.send(); } return isObject(body) ? response.json(body) : response.send(String(body)); } public status(response: any, statusCode: number) { return response.status(statusCode); } public render(response: any, view: string, options: any) { return response.render(view, options); } public redirect(response: any, statusCode: number, url: string) { return response.redirect(statusCode, url); } public setErrorHandler(handler: Function, prefix?: string) { return this.use(handler); } public setNotFoundHandler(handler: Function, prefix?: string) { return this.use(handler); } public setHeader(response: any, name: string, value: string) { return response.set(name, value); } public listen(port: string | number, callback?: () => void); public listen(port: string | number, hostname: string, callback?: () => void); public listen(port: any, ...args: any[]) { return this.httpServer.listen(port, ...args); } public close() { if (!this.httpServer) { return undefined; } return new Promise(resolve => this.httpServer.close(resolve)); } public set(...args: any[]) { return this.instance.set(...args); } public enable(...args: any[]) { return this.instance.enable(...args); } public disable(...args: any[]) { return this.instance.disable(...args); } public engine(...args: any[]) { return this.instance.engine(...args); } public useStaticAssets(path: string, options: ServeStaticOptions) { if (options && options.prefix) { return this.use(options.prefix, express.static(path, options)); } return this.use(express.static(path, options)); } public setBaseViewsDir(path: string | string[]) { return this.set('views', path); } public setViewEngine(engine: string) { return this.set('view engine', engine); } public getRequestHostname(request: any): string { return request.hostname; } public getRequestMethod(request: any): string { return request.method; } public getRequestUrl(request: any): string { return request.originalUrl; } public enableCors(options: CorsOptions) { return this.use(cors(options)); } public createMiddlewareFactory( requestMethod: RequestMethod, ): (path: string, callback: Function) => any { return this.routerMethodFactory .get(this.instance, requestMethod) .bind(this.instance); } public initHttpServer(options: NestApplicationOptions) { const isHttpsEnabled = options && options.httpsOptions; if (isHttpsEnabled) { this.httpServer = https.createServer( options.httpsOptions, this.getInstance(), ); return; } this.httpServer = http.createServer(this.getInstance()); } public registerParserMiddleware() { const parserMiddleware = { jsonParser: bodyParser.json(), urlencodedParser: bodyParser.urlencoded({ extended: true }), }; Object.keys(parserMiddleware) .filter(parser => !this.isMiddlewareApplied(parser)) .forEach(parserKey => this.use(parserMiddleware[parserKey])); } public getType(): string { return 'express'; } private isMiddlewareApplied(name: string): boolean { const app = this.getInstance(); return ( !!app._router && !!app._router.stack && isFunction(app._router.stack.filter) && app._router.stack.some( (layer: any) => layer && layer.handle && layer.handle.name === name, ) ); } }
packages/platform-express/adapters/express-adapter.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00045303325168788433, 0.0001858525793068111, 0.0001635177031857893, 0.00016936147585511208, 0.0000668463617330417 ]
{ "id": 2, "code_window": [ " this.queueOptions =\n", " this.getOptionsProp(this.options, 'queueOptions') ||\n", " RQM_DEFAULT_QUEUE_OPTIONS;\n", " this.replyQueue =\n", " this.getOptionsProp(this.options, 'replyQueue') || REPLY_QUEUE;\n", " loadPackage('amqplib', ClientRMQ.name, () => require('amqplib'));\n", " rqmPackage = loadPackage('amqp-connection-manager', ClientRMQ.name, () =>\n", " require('amqp-connection-manager'),\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.persistent =\n", " this.getOptionsProp(this.options, 'persistent') || RQM_DEFAULT_PERSISTENT;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 45 }
{ "name": "@nestjs/platform-socket.io", "version": "7.4.4", "description": "Nest - modern, fast, powerful node.js web framework (@platform-socket.io)", "author": "Kamil Mysliwiec", "license": "MIT", "homepage": "https://nestjs.com", "funding": { "type": "opencollective", "url": "https://opencollective.com/nest" }, "repository": { "type": "git", "url": "https://github.com/nestjs/nest" }, "publishConfig": { "access": "public" }, "dependencies": { "socket.io": "2.3.0", "tslib": "2.0.1" }, "peerDependencies": { "@nestjs/common": "^7.0.0", "@nestjs/websockets": "^7.0.0", "rxjs": "^6.0.0" } }
packages/platform-socket.io/package.json
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0001744849287206307, 0.00017246045172214508, 0.00017080435645766556, 0.00017209206998813897, 0.0000015249987654897268 ]
{ "id": 2, "code_window": [ " this.queueOptions =\n", " this.getOptionsProp(this.options, 'queueOptions') ||\n", " RQM_DEFAULT_QUEUE_OPTIONS;\n", " this.replyQueue =\n", " this.getOptionsProp(this.options, 'replyQueue') || REPLY_QUEUE;\n", " loadPackage('amqplib', ClientRMQ.name, () => require('amqplib'));\n", " rqmPackage = loadPackage('amqp-connection-manager', ClientRMQ.name, () =>\n", " require('amqp-connection-manager'),\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.persistent =\n", " this.getOptionsProp(this.options, 'persistent') || RQM_DEFAULT_PERSISTENT;\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 45 }
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Sequelize } from 'sequelize-typescript'; import { CreateUserDto } from './dto/create-user.dto'; import { User } from './user.model'; @Injectable() export class UsersService { constructor( @InjectModel(User) private readonly userModel: typeof User, private readonly sequelize: Sequelize, ) {} create(createUserDto: CreateUserDto): Promise<User> { const user = new User(); user.firstName = createUserDto.firstName; user.lastName = createUserDto.lastName; return user.save(); } async findAll(): Promise<User[]> { try { await this.sequelize.transaction(async t => { const transactionHost = { transaction: t }; await this.userModel.create( { firstName: 'Abraham', lastName: 'Lincoln' }, transactionHost, ); await this.userModel.create( { firstName: 'John', lastName: 'Boothe' }, transactionHost, ); }); } catch (err) { // Transaction has been rolled back // err is whatever rejected the promise chain returned to the transaction callback } return this.userModel.findAll(); } findOne(id: string): Promise<User> { return this.userModel.findOne({ where: { id, }, }); } async remove(id: string): Promise<void> { const user = await this.findOne(id); await user.destroy(); } }
sample/07-sequelize/src/users/users.service.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00017505385039839894, 0.00017185705655720085, 0.00016702916764188558, 0.00017205349286086857, 0.0000027784708436229266 ]
{ "id": 3, "code_window": [ " Buffer.from(JSON.stringify(serializedPacket)),\n", " {\n", " replyTo: this.replyQueue,\n", " correlationId,\n", " },\n", " );\n", " return () => this.responseEmitter.removeListener(correlationId, listener);\n", " } catch (err) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent: this.persistent,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 189 }
import { Transport } from '../enums/transport.enum'; import { ChannelOptions } from '../external/grpc-options.interface'; import { CompressionTypes, ConsumerConfig, KafkaConfig, ProducerConfig, } from '../external/kafka-options.interface'; import { MqttClientOptions } from '../external/mqtt-options.interface'; import { ClientOpts } from '../external/redis.interface'; import { Server } from '../server/server'; import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Deserializer } from './deserializer.interface'; import { Serializer } from './serializer.interface'; export type MicroserviceOptions = | GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | RmqOptions | KafkaOptions | CustomStrategy; export interface CustomStrategy { strategy: Server & CustomTransportStrategy; options?: {}; } export interface GrpcOptions { transport?: Transport.GRPC; options: { url?: string; maxSendMessageLength?: number; maxReceiveMessageLength?: number; maxMetadataSize?: number; keepalive?: { keepaliveTimeMs?: number; keepaliveTimeoutMs?: number; keepalivePermitWithoutCalls?: number; http2MaxPingsWithoutData?: number; http2MinTimeBetweenPingsMs?: number; http2MinPingIntervalWithoutDataMs?: number; http2MaxPingStrikes?: number; }; channelOptions?: ChannelOptions; credentials?: any; protoPath: string | string[]; package: string | string[]; protoLoader?: string; loader?: { keepCase?: boolean; alternateCommentMode?: boolean; longs?: Function; enums?: Function; bytes?: Function; defaults?: boolean; arrays?: boolean; objects?: boolean; oneofs?: boolean; json?: boolean; includeDirs?: string[]; }; }; } export interface TcpOptions { transport?: Transport.TCP; options?: { host?: string; port?: number; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RedisOptions { transport?: Transport.REDIS; options?: { url?: string; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; } & ClientOpts; } export interface MqttOptions { transport?: Transport.MQTT; options?: MqttClientOptions & { url?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface NatsOptions { transport?: Transport.NATS; options?: { url?: string; name?: string; user?: string; pass?: string; maxReconnectAttempts?: number; reconnectTimeWait?: number; servers?: string[]; reconnect?: boolean; pedantic?: boolean; tls?: any; queue?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RmqOptions { transport?: Transport.RMQ; options?: { urls?: string[]; queue?: string; prefetchCount?: number; isGlobalPrefetchCount?: boolean; queueOptions?: any; socketOptions?: any; noAck?: boolean; serializer?: Serializer; deserializer?: Deserializer; replyQueue?: string; }; } export interface KafkaOptions { transport?: Transport.KAFKA; options?: { client?: KafkaConfig; consumer?: ConsumerConfig; run?: { autoCommit?: boolean; autoCommitInterval?: number | null; autoCommitThreshold?: number | null; eachBatchAutoResolve?: boolean; partitionsConsumedConcurrently?: number; }; subscribe?: { fromBeginning?: boolean; }; producer?: ProducerConfig; send?: { acks?: number; timeout?: number; compression?: CompressionTypes; }; serializer?: Serializer; deserializer?: Deserializer; }; }
packages/microservices/interfaces/microservice-configuration.interface.ts
1
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0019893546123057604, 0.000286016205791384, 0.00016714308003429323, 0.00017195928376168013, 0.0004398213932290673 ]
{ "id": 3, "code_window": [ " Buffer.from(JSON.stringify(serializedPacket)),\n", " {\n", " replyTo: this.replyQueue,\n", " correlationId,\n", " },\n", " );\n", " return () => this.responseEmitter.removeListener(correlationId, listener);\n", " } catch (err) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent: this.persistent,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 189 }
{ "compilerOptions": { "module": "commonjs", "declaration": false, "noImplicitAny": false, "removeComments": true, "noLib": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es6", "sourceMap": true, "allowJs": true, "outDir": "./dist" }, "include": [ "src/**/*", "e2e/**/*" ], "exclude": [ "node_modules" ] }
integration/nest-application/get-url/tsconfig.json
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0001752995594870299, 0.00017390928405802697, 0.00017207876953762025, 0.0001743495522532612, 0.0000013512321856978815 ]
{ "id": 3, "code_window": [ " Buffer.from(JSON.stringify(serializedPacket)),\n", " {\n", " replyTo: this.replyQueue,\n", " correlationId,\n", " },\n", " );\n", " return () => this.responseEmitter.removeListener(correlationId, listener);\n", " } catch (err) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent: this.persistent,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 189 }
### Graphql Apollo sample ### Installation `npm install` ### Graphql Playground When the application is running, you can go to [http://localhost:3000/graphql](http://localhost:3000/graphql) to access the GraphQL Playground. See [here](https://docs.nestjs.com/graphql/quick-start#playground) for more.
sample/12-graphql-schema-first/README.md
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00016919088375288993, 0.00016919088375288993, 0.00016919088375288993, 0.00016919088375288993, 0 ]
{ "id": 3, "code_window": [ " Buffer.from(JSON.stringify(serializedPacket)),\n", " {\n", " replyTo: this.replyQueue,\n", " correlationId,\n", " },\n", " );\n", " return () => this.responseEmitter.removeListener(correlationId, listener);\n", " } catch (err) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent: this.persistent,\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "add", "edit_start_line_idx": 189 }
import * as chai from 'chai'; import { expect } from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as sinon from 'sinon'; import { Inject } from '../../../common/decorators/core/inject.decorator'; import { Injectable } from '../../../common/decorators/core/injectable.decorator'; import { STATIC_CONTEXT } from '../../injector/constants'; import { NestContainer } from '../../injector/container'; import { Injector, PropertyDependency } from '../../injector/injector'; import { InstanceWrapper } from '../../injector/instance-wrapper'; import { Module } from '../../injector/module'; chai.use(chaiAsPromised); describe('Injector', () => { let injector: Injector; beforeEach(() => { injector = new Injector(); }); describe('loadInstance', () => { @Injectable() class DependencyOne {} @Injectable() class DependencyTwo {} @Injectable() class MainTest { @Inject() property: DependencyOne; constructor(public one: DependencyOne, public two: DependencyTwo) {} } let moduleDeps: Module; let mainTest, depOne, depTwo; beforeEach(() => { moduleDeps = new Module(DependencyTwo, new NestContainer()); mainTest = new InstanceWrapper({ name: 'MainTest', metatype: MainTest, instance: Object.create(MainTest.prototype), isResolved: false, }); depOne = new InstanceWrapper({ name: 'DependencyOne', metatype: DependencyOne, instance: Object.create(DependencyOne.prototype), isResolved: false, }); depTwo = new InstanceWrapper({ name: 'DependencyTwo', metatype: DependencyTwo, instance: Object.create(DependencyOne.prototype), isResolved: false, }); moduleDeps.providers.set('MainTest', mainTest); moduleDeps.providers.set('DependencyOne', depOne); moduleDeps.providers.set('DependencyTwo', depTwo); moduleDeps.providers.set('MainTestResolved', { ...mainTest, isResolved: true, }); }); it('should create an instance of component with proper dependencies', async () => { await injector.loadInstance(mainTest, moduleDeps.providers, moduleDeps); const { instance } = moduleDeps.providers.get( 'MainTest', ) as InstanceWrapper<MainTest>; expect(instance.one).instanceof(DependencyOne); expect(instance.two).instanceof(DependencyTwo); expect(instance).instanceof(MainTest); }); it('should set "isResolved" property to true after instance initialization', async () => { await injector.loadInstance(mainTest, moduleDeps.providers, moduleDeps); const { isResolved } = (moduleDeps.providers.get( 'MainTest', ) as InstanceWrapper<MainTest>).getInstanceByContextId(STATIC_CONTEXT); expect(isResolved).to.be.true; }); it('should throw RuntimeException when type is not stored in collection', () => { return expect( injector.loadInstance({} as any, moduleDeps.providers, moduleDeps), ).to.eventually.be.rejected; }); it('should await done$ when "isPending"', async () => { const value = 'test'; const wrapper = new InstanceWrapper({ name: 'MainTest', metatype: MainTest, instance: Object.create(MainTest.prototype), isResolved: false, }); const host = wrapper.getInstanceByContextId(STATIC_CONTEXT); host.donePromise = Promise.resolve(value) as any; host.isPending = true; const result = await injector.loadInstance( wrapper, moduleDeps.providers, moduleDeps, ); expect(result).to.be.eql(value); }); it('should return undefined when metatype is resolved', async () => { const value = 'test'; const result = await injector.loadInstance( new InstanceWrapper({ name: 'MainTestResolved', metatype: MainTest, instance: Object.create(MainTest.prototype), isResolved: true, }), moduleDeps.providers, moduleDeps, ); expect(result).to.be.undefined; }); }); describe('loadPrototype', () => { @Injectable() class Test {} let moduleDeps: Module; let test; beforeEach(() => { moduleDeps = new Module(Test, new NestContainer()); test = new InstanceWrapper({ name: 'Test', metatype: Test, instance: null, isResolved: false, }); moduleDeps.providers.set('Test', test); }); it('should create prototype of instance', () => { injector.loadPrototype(test, moduleDeps.providers); expect(moduleDeps.providers.get('Test').instance).to.deep.equal( Object.create(Test.prototype), ); }); it('should return undefined when collection is nil', () => { const result = injector.loadPrototype(test, null); expect(result).to.be.undefined; }); it('should return undefined when target isResolved', () => { const collection = { get: () => ({ getInstanceByContextId: () => ({ isResolved: true }), createPrototype: () => {}, }), }; const result = injector.loadPrototype(test, collection as any); expect(result).to.be.undefined; }); it('should return undefined when "inject" is not nil', () => { const collection = { get: () => new InstanceWrapper({ inject: [] }), }; const result = injector.loadPrototype(test, collection as any); expect(result).to.be.undefined; }); }); describe('resolveSingleParam', () => { it('should throw "RuntimeException" when param is undefined', async () => { return expect( injector.resolveSingleParam( null, undefined, { index: 0, dependencies: [] }, null, ), ).to.eventually.be.rejected; }); }); describe('loadMiddleware', () => { let resolveConstructorParams: sinon.SinonSpy; beforeEach(() => { resolveConstructorParams = sinon.spy(); injector.resolveConstructorParams = resolveConstructorParams; }); it('should call "resolveConstructorParams" when instance is not resolved', () => { const collection = { get: (...args) => ({}), set: (...args) => {}, }; injector.loadMiddleware( { metatype: { name: '' } } as any, collection as any, null, ); expect(resolveConstructorParams.called).to.be.true; }); it('should not call "resolveConstructorParams" when instance is not resolved', () => { const collection = { get: (...args) => ({ instance: {}, }), set: (...args) => {}, }; injector.loadMiddleware( { metatype: { name: '' } } as any, collection as any, null, ); expect(resolveConstructorParams.called).to.be.false; }); }); describe('loadController', () => { let loadInstance: sinon.SinonSpy; beforeEach(() => { loadInstance = sinon.spy(); injector.loadInstance = loadInstance; }); it('should call "loadInstance" with expected arguments', async () => { const module = { controllers: [] }; const wrapper = { test: 'test', getEnhancersMetadata: () => [] }; await injector.loadController(wrapper as any, module as any); expect(loadInstance.calledWith(wrapper, module.controllers, module)).to.be .true; }); }); describe('loadInjectable', () => { let loadInstance: sinon.SinonSpy; beforeEach(() => { loadInstance = sinon.spy(); injector.loadInstance = loadInstance; }); it('should call "loadInstance" with expected arguments', async () => { const module = { injectables: [] }; const wrapper = { test: 'test' }; await injector.loadInjectable(wrapper as any, module as any); expect(loadInstance.calledWith(wrapper, module.injectables, module)).to.be .true; }); }); describe('lookupComponent', () => { let lookupComponentInImports: sinon.SinonStub; const metatype = { name: 'test', metatype: { name: 'test' } }; const wrapper = new InstanceWrapper({ name: 'Test', metatype: metatype as any, instance: null, isResolved: false, }); beforeEach(() => { lookupComponentInImports = sinon.stub(); (injector as any).lookupComponentInImports = lookupComponentInImports; }); it('should return object from collection if exists', async () => { const instance = { test: 3 }; const collection = { has: () => true, get: () => instance, }; const result = await injector.lookupComponent( collection as any, null, { name: metatype.name, index: 0, dependencies: [] }, wrapper, ); expect(result).to.be.equal(instance); }); it('should throw an exception if recursion happens', () => { const name = 'RecursionService'; const instance = { test: 3 }; const collection = { has: () => true, get: () => instance, }; const result = injector.lookupComponent( collection as any, null, { name, index: 0, dependencies: [] }, Object.assign(wrapper, { name, }), ); expect(result).to.eventually.be.rejected; }); it('should call "lookupComponentInImports" when object is not in collection', async () => { lookupComponentInImports.returns({}); const collection = { has: () => false, }; await injector.lookupComponent( collection as any, null, { name: metatype.name, index: 0, dependencies: [] }, wrapper, ); expect(lookupComponentInImports.called).to.be.true; }); it('should throw "UnknownDependenciesException" when instanceWrapper is null and "exports" collection does not contain token', () => { lookupComponentInImports.returns(null); const collection = { has: () => false, }; const module = { exports: collection }; expect( injector.lookupComponent( collection as any, module as any, { name: metatype.name, index: 0, dependencies: [] }, wrapper, ), ).to.eventually.be.rejected; }); it('should not throw "UnknownDependenciesException" instanceWrapper is not null', () => { lookupComponentInImports.returns({}); const collection = { has: () => false, }; const module = { exports: collection }; expect( injector.lookupComponent( collection as any, module as any, { name: metatype.name, index: 0, dependencies: [] }, wrapper, ), ).to.eventually.be.not.rejected; }); }); describe('lookupComponentInImports', () => { let loadProvider: sinon.SinonSpy; const metatype = { name: 'test' }; const module = { relatedModules: new Map(), }; beforeEach(() => { loadProvider = sinon.spy(); (injector as any).loadProvider = loadProvider; }); it('should return null when there is no related modules', async () => { const result = await injector.lookupComponentInImports( module as any, null, new InstanceWrapper(), ); expect(result).to.be.eq(null); }); it('should return null when related modules do not have appropriate component', () => { let moduleFixture = { relatedModules: new Map([ [ 'key', { providers: { has: () => false, }, exports: { has: () => true, }, }, ], ] as any), }; expect( injector.lookupComponentInImports( moduleFixture as any, metatype as any, null, ), ).to.be.eventually.eq(null); moduleFixture = { relatedModules: new Map([ [ 'key', { providers: { has: () => true, }, exports: { has: () => false, }, }, ], ] as any), }; expect( injector.lookupComponentInImports( moduleFixture as any, metatype as any, null, ), ).to.eventually.be.eq(null); }); it('should call "loadProvider" when component is not resolved', async () => { const moduleFixture = { imports: new Map([ [ 'key', { providers: { has: () => true, get: () => new InstanceWrapper({ isResolved: false, }), }, exports: { has: () => true, }, imports: new Map(), }, ], ] as any), }; await injector.lookupComponentInImports( moduleFixture as any, metatype as any, new InstanceWrapper(), ); expect(loadProvider.called).to.be.true; }); it('should not call "loadProvider" when component is resolved', async () => { const moduleFixture = { relatedModules: new Map([ [ 'key', { providers: { has: () => true, get: () => ({ isResolved: true, }), }, exports: { has: () => true, }, relatedModules: new Map(), }, ], ] as any), }; await injector.lookupComponentInImports( moduleFixture as any, metatype as any, null, ); expect(loadProvider.called).to.be.false; }); }); describe('resolveParamToken', () => { let forwardRef; let wrapper; let param; describe('when "forwardRef" property is not nil', () => { beforeEach(() => { forwardRef = 'test'; wrapper = {}; param = { forwardRef: () => forwardRef, }; }); it('return forwardRef() result', () => { expect(injector.resolveParamToken(wrapper, param)).to.be.eql( forwardRef, ); }); it('set wrapper "forwardRef" property to true', () => { injector.resolveParamToken(wrapper, param); expect(wrapper.forwardRef).to.be.true; }); }); describe('when "forwardRef" property is nil', () => { beforeEach(() => { forwardRef = 'test'; wrapper = {}; param = {}; }); it('set wrapper "forwardRef" property to false', () => { injector.resolveParamToken(wrapper, param); expect(wrapper.forwardRef).to.be.undefined; }); it('return param', () => { expect(injector.resolveParamToken(wrapper, param)).to.be.eql(param); }); }); }); describe('resolveComponentInstance', () => { let module; beforeEach(() => { module = { providers: [], }; }); describe('when instanceWrapper is not resolved and does not have forward ref', () => { it('should call loadProvider', async () => { const wrapper = new InstanceWrapper({ isResolved: false }); const loadStub = sinon .stub(injector, 'loadProvider') .callsFake(() => null); sinon .stub(injector, 'lookupComponent') .returns(Promise.resolve(wrapper)); await injector.resolveComponentInstance( module, '', { index: 0, dependencies: [] }, wrapper, ); expect(loadStub.called).to.be.true; }); it('should not call loadProvider (isResolved)', async () => { const wrapper = new InstanceWrapper({ isResolved: true }); const loadStub = sinon .stub(injector, 'loadProvider') .callsFake(() => null); sinon .stub(injector, 'lookupComponent') .returns(Promise.resolve(wrapper)); await injector.resolveComponentInstance( module, '', { index: 0, dependencies: [] }, wrapper, ); expect(loadStub.called).to.be.false; }); it('should not call loadProvider (forwardRef)', async () => { const wrapper = new InstanceWrapper({ isResolved: false, forwardRef: true, }); const loadStub = sinon .stub(injector, 'loadProvider') .callsFake(() => null); sinon .stub(injector, 'lookupComponent') .returns(Promise.resolve(wrapper)); await injector.resolveComponentInstance( module, '', { index: 0, dependencies: [] }, wrapper, ); expect(loadStub.called).to.be.false; }); }); describe('when instanceWraper has async property', () => { it('should await instance', async () => { sinon.stub(injector, 'loadProvider').callsFake(() => null); const instance = Promise.resolve(true); const wrapper = new InstanceWrapper({ isResolved: false, forwardRef: true, async: true, instance, }); sinon .stub(injector, 'lookupComponent') .returns(Promise.resolve(wrapper)); const result = await injector.resolveComponentInstance( module, '', { index: 0, dependencies: [] }, wrapper, ); expect(result.instance).to.be.true; }); }); }); describe('applyProperties', () => { describe('when instance is not an object', () => { it('should return undefined', () => { expect(injector.applyProperties('test', [])).to.be.undefined; }); }); describe('when instance is an object', () => { it('should apply each not nil property', () => { const properties = [ { key: 'one', instance: {} }, { key: 'two', instance: null }, { key: 'three', instance: true }, ]; const obj: Record<any, any> = {}; injector.applyProperties(obj, properties as PropertyDependency[]); expect(obj.one).to.be.eql(properties[0].instance); expect(obj.two).to.be.undefined; expect(obj.three).to.be.eql(properties[2].instance); }); }); }); describe('instantiateClass', () => { class TestClass {} describe('when context is static', () => { it('should instantiate class', async () => { const wrapper = new InstanceWrapper({ metatype: TestClass }); await injector.instantiateClass([], wrapper, wrapper, STATIC_CONTEXT); expect(wrapper.instance).to.not.be.undefined; expect(wrapper.instance).to.be.instanceOf(TestClass); }); it('should call factory', async () => { const wrapper = new InstanceWrapper({ inject: [], metatype: (() => ({})) as any, }); await injector.instantiateClass([], wrapper, wrapper, STATIC_CONTEXT); expect(wrapper.instance).to.not.be.undefined; }); }); describe('when context is not static', () => { it('should not instantiate class', async () => { const ctx = { id: 3 }; const wrapper = new InstanceWrapper({ metatype: TestClass }); await injector.instantiateClass([], wrapper, wrapper, ctx); expect(wrapper.instance).to.be.undefined; expect(wrapper.getInstanceByContextId(ctx).isResolved).to.be.true; }); it('should not call factory', async () => { const wrapper = new InstanceWrapper({ inject: [], metatype: sinon.spy() as any, }); await injector.instantiateClass([], wrapper, wrapper, { id: 2 }); expect(wrapper.instance).to.be.undefined; expect((wrapper.metatype as any).called).to.be.false; }); }); }); describe('loadPerContext', () => { class TestClass {} it('should load instance per context id', async () => { const container = new NestContainer(); const moduleCtor = class TestModule {}; const ctx = STATIC_CONTEXT; const module = await container.addModule(moduleCtor, []); module.addProvider({ name: 'TestClass', provide: TestClass, useClass: TestClass, }); const instance = await injector.loadPerContext( new TestClass(), module, module.providers, ctx, ); expect(instance).to.be.instanceOf(TestClass); }); }); describe('loadEnhancersPerContext', () => { it('should load enhancers per context id', async () => { const wrapper = new InstanceWrapper(); wrapper.addEnhancerMetadata( new InstanceWrapper({ host: new Module(class {}, new NestContainer()), }), ); wrapper.addEnhancerMetadata( new InstanceWrapper({ host: new Module(class {}, new NestContainer()), }), ); const loadInstanceStub = sinon .stub(injector, 'loadInstance') .callsFake(async () => ({} as any)); await injector.loadEnhancersPerContext(wrapper, STATIC_CONTEXT); expect(loadInstanceStub.calledTwice).to.be.true; }); }); describe('loadCtorMetadata', () => { it('should resolve ctor metadata', async () => { const wrapper = new InstanceWrapper(); wrapper.addCtorMetadata(0, new InstanceWrapper()); wrapper.addCtorMetadata(1, new InstanceWrapper()); const resolveComponentHostStub = sinon .stub(injector, 'resolveComponentHost') .callsFake(async () => new InstanceWrapper()); await injector.loadCtorMetadata( wrapper.getCtorMetadata(), STATIC_CONTEXT, ); expect(resolveComponentHostStub.calledTwice).to.be.true; }); }); describe('loadPropertiesMetadata', () => { it('should resolve properties metadata', async () => { const wrapper = new InstanceWrapper(); wrapper.addPropertiesMetadata('key1', new InstanceWrapper()); wrapper.addPropertiesMetadata('key2', new InstanceWrapper()); const resolveComponentHostStub = sinon .stub(injector, 'resolveComponentHost') .callsFake(async () => new InstanceWrapper()); await injector.loadPropertiesMetadata( wrapper.getPropertiesMetadata(), STATIC_CONTEXT, ); expect(resolveComponentHostStub.calledTwice).to.be.true; }); }); describe('resolveConstructorParams', () => { it('should call "loadCtorMetadata" if metadata is not undefined', async () => { const wrapper = new InstanceWrapper(); const metadata = []; sinon.stub(wrapper, 'getCtorMetadata').callsFake(() => metadata); const loadCtorMetadataSpy = sinon.spy(injector, 'loadCtorMetadata'); await injector.resolveConstructorParams( wrapper, null, [], () => { expect(loadCtorMetadataSpy.called).to.be.true; }, { id: 2 }, ); }); }); describe('resolveProperties', () => { it('should call "loadPropertiesMetadata" if metadata is not undefined', async () => { const wrapper = new InstanceWrapper(); const metadata = []; sinon.stub(wrapper, 'getPropertiesMetadata').callsFake(() => metadata); const loadPropertiesMetadataSpy = sinon.spy( injector, 'loadPropertiesMetadata', ); await injector.resolveProperties(wrapper, null, null, { id: 2 }); expect(loadPropertiesMetadataSpy.called).to.be.true; }); }); });
packages/core/test/injector/injector.spec.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00017742915952112526, 0.00017286257934756577, 0.00016385701019316912, 0.00017330999253317714, 0.0000019902151962014614 ]
{ "id": 4, "code_window": [ " return new Promise((resolve, reject) =>\n", " this.channel.sendToQueue(\n", " this.queue,\n", " Buffer.from(JSON.stringify(serializedPacket)),\n", " {},\n", " err => (err ? reject(err) : resolve()),\n", " ),\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " {\n", " persistent: this.persistent,\n", " },\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "replace", "edit_start_line_idx": 204 }
import { Transport } from '../enums/transport.enum'; import { ChannelOptions } from '../external/grpc-options.interface'; import { CompressionTypes, ConsumerConfig, KafkaConfig, ProducerConfig, } from '../external/kafka-options.interface'; import { MqttClientOptions } from '../external/mqtt-options.interface'; import { ClientOpts } from '../external/redis.interface'; import { Server } from '../server/server'; import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Deserializer } from './deserializer.interface'; import { Serializer } from './serializer.interface'; export type MicroserviceOptions = | GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | RmqOptions | KafkaOptions | CustomStrategy; export interface CustomStrategy { strategy: Server & CustomTransportStrategy; options?: {}; } export interface GrpcOptions { transport?: Transport.GRPC; options: { url?: string; maxSendMessageLength?: number; maxReceiveMessageLength?: number; maxMetadataSize?: number; keepalive?: { keepaliveTimeMs?: number; keepaliveTimeoutMs?: number; keepalivePermitWithoutCalls?: number; http2MaxPingsWithoutData?: number; http2MinTimeBetweenPingsMs?: number; http2MinPingIntervalWithoutDataMs?: number; http2MaxPingStrikes?: number; }; channelOptions?: ChannelOptions; credentials?: any; protoPath: string | string[]; package: string | string[]; protoLoader?: string; loader?: { keepCase?: boolean; alternateCommentMode?: boolean; longs?: Function; enums?: Function; bytes?: Function; defaults?: boolean; arrays?: boolean; objects?: boolean; oneofs?: boolean; json?: boolean; includeDirs?: string[]; }; }; } export interface TcpOptions { transport?: Transport.TCP; options?: { host?: string; port?: number; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RedisOptions { transport?: Transport.REDIS; options?: { url?: string; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; } & ClientOpts; } export interface MqttOptions { transport?: Transport.MQTT; options?: MqttClientOptions & { url?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface NatsOptions { transport?: Transport.NATS; options?: { url?: string; name?: string; user?: string; pass?: string; maxReconnectAttempts?: number; reconnectTimeWait?: number; servers?: string[]; reconnect?: boolean; pedantic?: boolean; tls?: any; queue?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RmqOptions { transport?: Transport.RMQ; options?: { urls?: string[]; queue?: string; prefetchCount?: number; isGlobalPrefetchCount?: boolean; queueOptions?: any; socketOptions?: any; noAck?: boolean; serializer?: Serializer; deserializer?: Deserializer; replyQueue?: string; }; } export interface KafkaOptions { transport?: Transport.KAFKA; options?: { client?: KafkaConfig; consumer?: ConsumerConfig; run?: { autoCommit?: boolean; autoCommitInterval?: number | null; autoCommitThreshold?: number | null; eachBatchAutoResolve?: boolean; partitionsConsumedConcurrently?: number; }; subscribe?: { fromBeginning?: boolean; }; producer?: ProducerConfig; send?: { acks?: number; timeout?: number; compression?: CompressionTypes; }; serializer?: Serializer; deserializer?: Deserializer; }; }
packages/microservices/interfaces/microservice-configuration.interface.ts
1
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.0011940384283661842, 0.00029379496118053794, 0.00016311951912939548, 0.0001720490399748087, 0.0002790405706036836 ]
{ "id": 4, "code_window": [ " return new Promise((resolve, reject) =>\n", " this.channel.sendToQueue(\n", " this.queue,\n", " Buffer.from(JSON.stringify(serializedPacket)),\n", " {},\n", " err => (err ? reject(err) : resolve()),\n", " ),\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " {\n", " persistent: this.persistent,\n", " },\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "replace", "edit_start_line_idx": 204 }
/** * Decorator that binds *parameter decorators* to the method that follows. * * Useful when the language doesn't provide a 'Parameter Decorator' feature * (i.e., vanilla JavaScript). * * @param decorators one or more parameter decorators (e.g., `Req()`) * * @publicApi */ export function Bind(...decorators: any[]): MethodDecorator { return <T>( target: object, key: string | symbol, descriptor: TypedPropertyDescriptor<T>, ) => { decorators.forEach((fn, index) => fn(target, key, index)); return descriptor; }; }
packages/common/decorators/core/bind.decorator.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00017125772137660533, 0.00016935433086473495, 0.00016644870629534125, 0.00017035657947417349, 0.000002087267148453975 ]
{ "id": 4, "code_window": [ " return new Promise((resolve, reject) =>\n", " this.channel.sendToQueue(\n", " this.queue,\n", " Buffer.from(JSON.stringify(serializedPacket)),\n", " {},\n", " err => (err ? reject(err) : resolve()),\n", " ),\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " {\n", " persistent: this.persistent,\n", " },\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "replace", "edit_start_line_idx": 204 }
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; @Module({ imports: [], controllers: [AppController], providers: [], }) export class AppModule {}
sample/15-mvc/src/app.module.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00017085761646740139, 0.00017085761646740139, 0.00017085761646740139, 0.00017085761646740139, 0 ]
{ "id": 4, "code_window": [ " return new Promise((resolve, reject) =>\n", " this.channel.sendToQueue(\n", " this.queue,\n", " Buffer.from(JSON.stringify(serializedPacket)),\n", " {},\n", " err => (err ? reject(err) : resolve()),\n", " ),\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " {\n", " persistent: this.persistent,\n", " },\n" ], "file_path": "packages/microservices/client/client-rmq.ts", "type": "replace", "edit_start_line_idx": 204 }
import { INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import * as request from 'supertest'; import { AsyncOptionsClassModule } from '../src/async-class-options.module'; describe('Mongoose', () => { let server; let app: INestApplication; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [AsyncOptionsClassModule], }).compile(); app = module.createNestApplication(); server = app.getHttpServer(); await app.init(); }); it(`should return created entity`, () => { const cat = { name: 'Nest', age: 20, breed: 'Awesome', }; return request(server) .post('/cats') .send(cat) .expect(201) .expect(({ body }) => body.name === cat.name); }); afterEach(async () => { await app.close(); }); });
integration/mongoose/e2e/async-class-options.spec.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00017305815708823502, 0.00017047525034286082, 0.0001686228351900354, 0.0001701099972706288, 0.0000017445454432163388 ]
{ "id": 5, "code_window": [ "export const RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT = false;\n", "export const RQM_DEFAULT_QUEUE_OPTIONS = {};\n", "export const RQM_DEFAULT_NOACK = true;\n", "export const GRPC_DEFAULT_PROTO_LOADER = '@grpc/proto-loader';\n", "\n", "export const NO_MESSAGE_HANDLER = `There is no matching message handler defined in the remote service.`;\n", "export const NO_EVENT_HANDLER = `There is no matching event handler defined in the remote service.`;\n", "export const DISCONNECTED_RMQ_MESSAGE = `Disconnected from RMQ. Trying to reconnect.`;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const RQM_DEFAULT_PERSISTENT = false;\n" ], "file_path": "packages/microservices/constants.ts", "type": "add", "edit_start_line_idx": 35 }
import { Transport } from '../enums/transport.enum'; import { ChannelOptions } from '../external/grpc-options.interface'; import { CompressionTypes, ConsumerConfig, KafkaConfig, ProducerConfig, } from '../external/kafka-options.interface'; import { MqttClientOptions } from '../external/mqtt-options.interface'; import { ClientOpts } from '../external/redis.interface'; import { Server } from '../server/server'; import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Deserializer } from './deserializer.interface'; import { Serializer } from './serializer.interface'; export type MicroserviceOptions = | GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | RmqOptions | KafkaOptions | CustomStrategy; export interface CustomStrategy { strategy: Server & CustomTransportStrategy; options?: {}; } export interface GrpcOptions { transport?: Transport.GRPC; options: { url?: string; maxSendMessageLength?: number; maxReceiveMessageLength?: number; maxMetadataSize?: number; keepalive?: { keepaliveTimeMs?: number; keepaliveTimeoutMs?: number; keepalivePermitWithoutCalls?: number; http2MaxPingsWithoutData?: number; http2MinTimeBetweenPingsMs?: number; http2MinPingIntervalWithoutDataMs?: number; http2MaxPingStrikes?: number; }; channelOptions?: ChannelOptions; credentials?: any; protoPath: string | string[]; package: string | string[]; protoLoader?: string; loader?: { keepCase?: boolean; alternateCommentMode?: boolean; longs?: Function; enums?: Function; bytes?: Function; defaults?: boolean; arrays?: boolean; objects?: boolean; oneofs?: boolean; json?: boolean; includeDirs?: string[]; }; }; } export interface TcpOptions { transport?: Transport.TCP; options?: { host?: string; port?: number; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RedisOptions { transport?: Transport.REDIS; options?: { url?: string; retryAttempts?: number; retryDelay?: number; serializer?: Serializer; deserializer?: Deserializer; } & ClientOpts; } export interface MqttOptions { transport?: Transport.MQTT; options?: MqttClientOptions & { url?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface NatsOptions { transport?: Transport.NATS; options?: { url?: string; name?: string; user?: string; pass?: string; maxReconnectAttempts?: number; reconnectTimeWait?: number; servers?: string[]; reconnect?: boolean; pedantic?: boolean; tls?: any; queue?: string; serializer?: Serializer; deserializer?: Deserializer; }; } export interface RmqOptions { transport?: Transport.RMQ; options?: { urls?: string[]; queue?: string; prefetchCount?: number; isGlobalPrefetchCount?: boolean; queueOptions?: any; socketOptions?: any; noAck?: boolean; serializer?: Serializer; deserializer?: Deserializer; replyQueue?: string; }; } export interface KafkaOptions { transport?: Transport.KAFKA; options?: { client?: KafkaConfig; consumer?: ConsumerConfig; run?: { autoCommit?: boolean; autoCommitInterval?: number | null; autoCommitThreshold?: number | null; eachBatchAutoResolve?: boolean; partitionsConsumedConcurrently?: number; }; subscribe?: { fromBeginning?: boolean; }; producer?: ProducerConfig; send?: { acks?: number; timeout?: number; compression?: CompressionTypes; }; serializer?: Serializer; deserializer?: Deserializer; }; }
packages/microservices/interfaces/microservice-configuration.interface.ts
1
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.011522967368364334, 0.0009606463718228042, 0.00017046609718818218, 0.00020554399816319346, 0.0027304599061608315 ]
{ "id": 5, "code_window": [ "export const RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT = false;\n", "export const RQM_DEFAULT_QUEUE_OPTIONS = {};\n", "export const RQM_DEFAULT_NOACK = true;\n", "export const GRPC_DEFAULT_PROTO_LOADER = '@grpc/proto-loader';\n", "\n", "export const NO_MESSAGE_HANDLER = `There is no matching message handler defined in the remote service.`;\n", "export const NO_EVENT_HANDLER = `There is no matching event handler defined in the remote service.`;\n", "export const DISCONNECTED_RMQ_MESSAGE = `Disconnected from RMQ. Trying to reconnect.`;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const RQM_DEFAULT_PERSISTENT = false;\n" ], "file_path": "packages/microservices/constants.ts", "type": "add", "edit_start_line_idx": 35 }
export * from './bad-request.exception'; export * from './http.exception'; export * from './unauthorized.exception'; export * from './method-not-allowed.exception'; export * from './not-found.exception'; export * from './forbidden.exception'; export * from './not-acceptable.exception'; export * from './request-timeout.exception'; export * from './conflict.exception'; export * from './gone.exception'; export * from './payload-too-large.exception'; export * from './unsupported-media-type.exception'; export * from './unprocessable-entity.exception'; export * from './internal-server-error.exception'; export * from './not-implemented.exception'; export * from './http-version-not-supported.exception'; export * from './bad-gateway.exception'; export * from './service-unavailable.exception'; export * from './gateway-timeout.exception'; export * from './im-a-teapot.exception'; export * from './precondition-failed.exception';
packages/common/exceptions/index.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00017127387400250882, 0.00016904110088944435, 0.00016769574722275138, 0.00016815368144307286, 0.0000015898391438895487 ]
{ "id": 5, "code_window": [ "export const RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT = false;\n", "export const RQM_DEFAULT_QUEUE_OPTIONS = {};\n", "export const RQM_DEFAULT_NOACK = true;\n", "export const GRPC_DEFAULT_PROTO_LOADER = '@grpc/proto-loader';\n", "\n", "export const NO_MESSAGE_HANDLER = `There is no matching message handler defined in the remote service.`;\n", "export const NO_EVENT_HANDLER = `There is no matching event handler defined in the remote service.`;\n", "export const DISCONNECTED_RMQ_MESSAGE = `Disconnected from RMQ. Trying to reconnect.`;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const RQM_DEFAULT_PERSISTENT = false;\n" ], "file_path": "packages/microservices/constants.ts", "type": "add", "edit_start_line_idx": 35 }
import { Injectable } from '@nestjs/common'; @Injectable() export class UsersService { findById(id: string) { return { id, host: true }; } }
integration/hello-world/src/host/users/users.service.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00018178828759118915, 0.00018178828759118915, 0.00018178828759118915, 0.00018178828759118915, 0 ]
{ "id": 5, "code_window": [ "export const RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT = false;\n", "export const RQM_DEFAULT_QUEUE_OPTIONS = {};\n", "export const RQM_DEFAULT_NOACK = true;\n", "export const GRPC_DEFAULT_PROTO_LOADER = '@grpc/proto-loader';\n", "\n", "export const NO_MESSAGE_HANDLER = `There is no matching message handler defined in the remote service.`;\n", "export const NO_EVENT_HANDLER = `There is no matching event handler defined in the remote service.`;\n", "export const DISCONNECTED_RMQ_MESSAGE = `Disconnected from RMQ. Trying to reconnect.`;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const RQM_DEFAULT_PERSISTENT = false;\n" ], "file_path": "packages/microservices/constants.ts", "type": "add", "edit_start_line_idx": 35 }
import { expect } from 'chai'; import * as sinon from 'sinon'; import { NO_MESSAGE_HANDLER } from '../../constants'; import { NatsContext } from '../../ctx-host'; import { BaseRpcContext } from '../../ctx-host/base-rpc.context'; import { ServerNats } from '../../server/server-nats'; describe('ServerNats', () => { let server: ServerNats; const objectToMap = obj => new Map(Object.keys(obj).map(key => [key, obj[key]]) as any); beforeEach(() => { server = new ServerNats({}); }); describe('listen', () => { let createNatsClient; let onSpy: sinon.SinonSpy; let client; beforeEach(() => { onSpy = sinon.spy(); client = { on: onSpy, }; createNatsClient = sinon .stub(server, 'createNatsClient') .callsFake(() => client); server.listen(null); }); it('should bind "error" event to handler', () => { expect(onSpy.getCall(0).args[0]).to.be.equal('error'); }); it('should bind "connect" event to handler', () => { expect(onSpy.getCall(1).args[0]).to.be.equal('connect'); }); }); describe('close', () => { const natsClient = { close: sinon.spy() }; beforeEach(() => { (server as any).natsClient = natsClient; }); it('should close natsClient', () => { server.close(); expect(natsClient.close.called).to.be.true; }); }); describe('bindEvents', () => { let onSpy: sinon.SinonSpy, subscribeSpy: sinon.SinonSpy, natsClient; beforeEach(() => { onSpy = sinon.spy(); subscribeSpy = sinon.spy(); natsClient = { on: onSpy, subscribe: subscribeSpy, }; }); it('should subscribe to each acknowledge patterns', () => { const pattern = 'test'; const handler = sinon.spy(); (server as any).messageHandlers = objectToMap({ [pattern]: handler, }); server.bindEvents(natsClient); expect(subscribeSpy.calledWith(pattern)).to.be.true; }); }); describe('getMessageHandler', () => { it(`should return function`, () => { expect( typeof server.getMessageHandler(null, (server as any).natsClient), ).to.be.eql('function'); }); describe('handler', () => { it('should call "handleMessage"', async () => { const handleMessageStub = sinon .stub(server, 'handleMessage') .callsFake(() => null); (await server.getMessageHandler('', (server as any).natsClient))( '' as any, '', ); expect(handleMessageStub.called).to.be.true; }); }); }); describe('handleMessage', () => { let getPublisherSpy: sinon.SinonSpy; const channel = 'test'; const data = 'test'; const id = '3'; beforeEach(() => { getPublisherSpy = sinon.spy(); sinon.stub(server, 'getPublisher').callsFake(() => getPublisherSpy); }); it('should call "handleEvent" if identifier is not present', () => { const handleEventSpy = sinon.spy(server, 'handleEvent'); server.handleMessage(channel, { pattern: '', data: '' }, null, '', ''); expect(handleEventSpy.called).to.be.true; }); it(`should publish NO_MESSAGE_HANDLER if pattern not exists in messageHandlers object`, () => { server.handleMessage( channel, { id, pattern: '', data: '' }, null, '', '', ); expect( getPublisherSpy.calledWith({ id, status: 'error', err: NO_MESSAGE_HANDLER, }), ).to.be.true; }); it(`should call handler with expected arguments`, () => { const handler = sinon.spy(); (server as any).messageHandlers = objectToMap({ [channel]: handler, }); const callerSubject = 'subject'; const natsContext = new NatsContext([callerSubject]); server.handleMessage( channel, { pattern: '', data, id: '2' }, null, '', callerSubject, ); expect(handler.calledWith(data, natsContext)).to.be.true; }); }); describe('getPublisher', () => { let publisherSpy: sinon.SinonSpy; let pub, publisher; const id = '1'; const replyTo = 'test'; beforeEach(() => { publisherSpy = sinon.spy(); pub = { publish: publisherSpy, }; publisher = server.getPublisher(pub, replyTo, id); }); it(`should return function`, () => { expect(typeof server.getPublisher(null, null, id)).to.be.eql('function'); }); it(`should call "publish" with expected arguments`, () => { const respond = 'test'; publisher({ respond, id }); expect(publisherSpy.calledWith(replyTo, { respond, id })).to.be.true; }); }); describe('handleEvent', () => { const channel = 'test'; const data = 'test'; it('should call handler with expected arguments', () => { const handler = sinon.spy(); (server as any).messageHandlers = objectToMap({ [channel]: handler, }); server.handleEvent( channel, { pattern: '', data }, new BaseRpcContext([]), ); expect(handler.calledWith(data)).to.be.true; }); }); });
packages/microservices/test/server/server-nats.spec.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.9990851879119873, 0.15643370151519775, 0.00016835406131576747, 0.00018546449427958578, 0.36084020137786865 ]
{ "id": 6, "code_window": [ " socketOptions?: any;\n", " noAck?: boolean;\n", " serializer?: Serializer;\n", " deserializer?: Deserializer;\n", " replyQueue?: string;\n", " };\n", "}\n", "\n", "export interface KafkaOptions {\n", " transport?: Transport.KAFKA;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent?: boolean;\n" ], "file_path": "packages/microservices/interfaces/microservice-configuration.interface.ts", "type": "add", "edit_start_line_idx": 131 }
import { Logger } from '@nestjs/common/services/logger.service'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util'; import { EventEmitter } from 'events'; import { fromEvent, merge, Observable } from 'rxjs'; import { first, map, share, switchMap } from 'rxjs/operators'; import { DISCONNECTED_RMQ_MESSAGE, DISCONNECT_EVENT, ERROR_EVENT, RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT, RQM_DEFAULT_NOACK, RQM_DEFAULT_PREFETCH_COUNT, RQM_DEFAULT_QUEUE, RQM_DEFAULT_QUEUE_OPTIONS, RQM_DEFAULT_URL, } from '../constants'; import { ReadPacket, RmqOptions, WritePacket } from '../interfaces'; import { ClientProxy } from './client-proxy'; let rqmPackage: any = {}; const REPLY_QUEUE = 'amq.rabbitmq.reply-to'; export class ClientRMQ extends ClientProxy { protected readonly logger = new Logger(ClientProxy.name); protected connection: Promise<any>; protected client: any = null; protected channel: any = null; protected urls: string[]; protected queue: string; protected queueOptions: any; protected responseEmitter: EventEmitter; protected replyQueue: string; constructor(protected readonly options: RmqOptions['options']) { super(); this.urls = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL]; this.queue = this.getOptionsProp(this.options, 'queue') || RQM_DEFAULT_QUEUE; this.queueOptions = this.getOptionsProp(this.options, 'queueOptions') || RQM_DEFAULT_QUEUE_OPTIONS; this.replyQueue = this.getOptionsProp(this.options, 'replyQueue') || REPLY_QUEUE; loadPackage('amqplib', ClientRMQ.name, () => require('amqplib')); rqmPackage = loadPackage('amqp-connection-manager', ClientRMQ.name, () => require('amqp-connection-manager'), ); this.initializeSerializer(options); this.initializeDeserializer(options); } public close(): void { this.channel && this.channel.close(); this.client && this.client.close(); this.channel = null; this.client = null; } public consumeChannel() { const noAck = this.getOptionsProp(this.options, 'noAck', RQM_DEFAULT_NOACK); this.channel.addSetup((channel: any) => channel.consume( this.replyQueue, (msg: any) => this.responseEmitter.emit(msg.properties.correlationId, msg), { noAck, }, ), ); } public connect(): Promise<any> { if (this.client) { return this.connection; } this.client = this.createClient(); this.handleError(this.client); this.handleDisconnectError(this.client); const connect$ = this.connect$(this.client); this.connection = this.mergeDisconnectEvent(this.client, connect$) .pipe( switchMap(() => this.createChannel()), share(), ) .toPromise(); return this.connection; } public createChannel(): Promise<void> { return new Promise(resolve => { this.channel = this.client.createChannel({ json: false, setup: (channel: any) => this.setupChannel(channel, resolve), }); }); } public createClient<T = any>(): T { const socketOptions = this.getOptionsProp(this.options, 'socketOptions'); return rqmPackage.connect(this.urls, { connectionOptions: socketOptions, }) as T; } public mergeDisconnectEvent<T = any>( instance: any, source$: Observable<T>, ): Observable<T> { const close$ = fromEvent(instance, DISCONNECT_EVENT).pipe( map((err: any) => { throw err; }), ); return merge(source$, close$).pipe(first()); } public async setupChannel(channel: any, resolve: Function) { const prefetchCount = this.getOptionsProp(this.options, 'prefetchCount') || RQM_DEFAULT_PREFETCH_COUNT; const isGlobalPrefetchCount = this.getOptionsProp(this.options, 'isGlobalPrefetchCount') || RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT; await channel.assertQueue(this.queue, this.queueOptions); await channel.prefetch(prefetchCount, isGlobalPrefetchCount); this.responseEmitter = new EventEmitter(); this.responseEmitter.setMaxListeners(0); this.consumeChannel(); resolve(); } public handleError(client: any): void { client.addListener(ERROR_EVENT, (err: any) => this.logger.error(err)); } public handleDisconnectError(client: any): void { client.addListener(DISCONNECT_EVENT, (err: any) => { this.logger.error(DISCONNECTED_RMQ_MESSAGE); this.logger.error(err); this.close(); }); } public handleMessage( packet: unknown, callback: (packet: WritePacket) => any, ) { const { err, response, isDisposed } = this.deserializer.deserialize(packet); if (isDisposed || err) { callback({ err, response, isDisposed: true, }); } callback({ err, response, }); } protected publish( message: ReadPacket, callback: (packet: WritePacket) => any, ): Function { try { const correlationId = randomStringGenerator(); const listener = ({ content }: { content: any }) => this.handleMessage(JSON.parse(content.toString()), callback); Object.assign(message, { id: correlationId }); const serializedPacket = this.serializer.serialize(message); this.responseEmitter.on(correlationId, listener); this.channel.sendToQueue( this.queue, Buffer.from(JSON.stringify(serializedPacket)), { replyTo: this.replyQueue, correlationId, }, ); return () => this.responseEmitter.removeListener(correlationId, listener); } catch (err) { callback({ err }); } } protected dispatchEvent(packet: ReadPacket): Promise<any> { const serializedPacket = this.serializer.serialize(packet); return new Promise((resolve, reject) => this.channel.sendToQueue( this.queue, Buffer.from(JSON.stringify(serializedPacket)), {}, err => (err ? reject(err) : resolve()), ), ); } }
packages/microservices/client/client-rmq.ts
1
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.030646396800875664, 0.002629481488838792, 0.00016654221690259874, 0.00017419141659047455, 0.006666132714599371 ]
{ "id": 6, "code_window": [ " socketOptions?: any;\n", " noAck?: boolean;\n", " serializer?: Serializer;\n", " deserializer?: Deserializer;\n", " replyQueue?: string;\n", " };\n", "}\n", "\n", "export interface KafkaOptions {\n", " transport?: Transport.KAFKA;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent?: boolean;\n" ], "file_path": "packages/microservices/interfaces/microservice-configuration.interface.ts", "type": "add", "edit_start_line_idx": 131 }
import { Module } from '@nestjs/common'; import { ApplicationGateway } from './app.gateway'; @Module({ providers: [ApplicationGateway], }) export class ApplicationModule {}
integration/websockets/src/app.module.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00017525209113955498, 0.00017525209113955498, 0.00017525209113955498, 0.00017525209113955498, 0 ]
{ "id": 6, "code_window": [ " socketOptions?: any;\n", " noAck?: boolean;\n", " serializer?: Serializer;\n", " deserializer?: Deserializer;\n", " replyQueue?: string;\n", " };\n", "}\n", "\n", "export interface KafkaOptions {\n", " transport?: Transport.KAFKA;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent?: boolean;\n" ], "file_path": "packages/microservices/interfaces/microservice-configuration.interface.ts", "type": "add", "edit_start_line_idx": 131 }
import { CUSTOM_ROUTE_AGRS_METADATA, PARAMTYPES_METADATA, } from '@nestjs/common/constants'; import { ContextType, Controller, PipeTransform, } from '@nestjs/common/interfaces'; import { isEmpty } from '@nestjs/common/utils/shared.utils'; import { FORBIDDEN_MESSAGE } from '@nestjs/core/guards/constants'; import { GuardsConsumer } from '@nestjs/core/guards/guards-consumer'; import { GuardsContextCreator } from '@nestjs/core/guards/guards-context-creator'; import { ContextUtils, ParamProperties, } from '@nestjs/core/helpers/context-utils'; import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host'; import { HandlerMetadataStorage } from '@nestjs/core/helpers/handler-metadata-storage'; import { ParamsMetadata } from '@nestjs/core/helpers/interfaces'; import { STATIC_CONTEXT } from '@nestjs/core/injector/constants'; import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer'; import { InterceptorsContextCreator } from '@nestjs/core/interceptors/interceptors-context-creator'; import { PipesConsumer } from '@nestjs/core/pipes/pipes-consumer'; import { PipesContextCreator } from '@nestjs/core/pipes/pipes-context-creator'; import { Observable } from 'rxjs'; import { PARAM_ARGS_METADATA } from '../constants'; import { RpcException } from '../exceptions'; import { RpcParamsFactory } from '../factories/rpc-params-factory'; import { ExceptionFiltersContext } from './exception-filters-context'; import { DEFAULT_CALLBACK_METADATA } from './rpc-metadata-constants'; import { RpcProxy } from './rpc-proxy'; type RpcParamProperties = ParamProperties & { metatype?: any }; export interface RpcHandlerMetadata { argsLength: number; paramtypes: any[]; getParamsMetadata: (moduleKey: string) => RpcParamProperties[]; } export class RpcContextCreator { private readonly contextUtils = new ContextUtils(); private readonly rpcParamsFactory = new RpcParamsFactory(); private readonly handlerMetadataStorage = new HandlerMetadataStorage< RpcHandlerMetadata >(); constructor( private readonly rpcProxy: RpcProxy, private readonly exceptionFiltersContext: ExceptionFiltersContext, private readonly pipesContextCreator: PipesContextCreator, private readonly pipesConsumer: PipesConsumer, private readonly guardsContextCreator: GuardsContextCreator, private readonly guardsConsumer: GuardsConsumer, private readonly interceptorsContextCreator: InterceptorsContextCreator, private readonly interceptorsConsumer: InterceptorsConsumer, ) {} public create<T extends ParamsMetadata = ParamsMetadata>( instance: Controller, callback: (...args: unknown[]) => Observable<any>, module: string, methodName: string, contextId = STATIC_CONTEXT, inquirerId?: string, defaultCallMetadata: Record<string, any> = DEFAULT_CALLBACK_METADATA, ): (...args: any[]) => Promise<Observable<any>> { const contextType: ContextType = 'rpc'; const { argsLength, paramtypes, getParamsMetadata } = this.getMetadata<T>( instance, methodName, defaultCallMetadata, contextType, ); const exceptionHandler = this.exceptionFiltersContext.create( instance, callback, module, contextId, inquirerId, ); const pipes = this.pipesContextCreator.create( instance, callback, module, contextId, inquirerId, ); const guards = this.guardsContextCreator.create( instance, callback, module, contextId, inquirerId, ); const interceptors = this.interceptorsContextCreator.create( instance, callback, module, contextId, inquirerId, ); const paramsMetadata = getParamsMetadata(module); const paramsOptions = paramsMetadata ? this.contextUtils.mergeParamsMetatypes(paramsMetadata, paramtypes) : []; const fnApplyPipes = this.createPipesFn(pipes, paramsOptions); const fnCanActivate = this.createGuardsFn( guards, instance, callback, contextType, ); const handler = (initialArgs: unknown[], args: unknown[]) => async () => { if (fnApplyPipes) { await fnApplyPipes(initialArgs, ...args); return callback.apply(instance, initialArgs); } return callback.apply(instance, args); }; return this.rpcProxy.create(async (...args: unknown[]) => { const initialArgs = this.contextUtils.createNullArray(argsLength); fnCanActivate && (await fnCanActivate(args)); return this.interceptorsConsumer.intercept( interceptors, args, instance, callback, handler(initialArgs, args), contextType, ) as Promise<Observable<unknown>>; }, exceptionHandler); } public reflectCallbackParamtypes( instance: Controller, callback: (...args: unknown[]) => unknown, ): unknown[] { return Reflect.getMetadata(PARAMTYPES_METADATA, instance, callback.name); } public createGuardsFn<TContext extends string = ContextType>( guards: any[], instance: Controller, callback: (...args: unknown[]) => unknown, contextType?: TContext, ): Function | null { const canActivateFn = async (args: any[]) => { const canActivate = await this.guardsConsumer.tryActivate<TContext>( guards, args, instance, callback, contextType, ); if (!canActivate) { throw new RpcException(FORBIDDEN_MESSAGE); } }; return guards.length ? canActivateFn : null; } public getMetadata<TMetadata, TContext extends ContextType = ContextType>( instance: Controller, methodName: string, defaultCallMetadata: Record<string, any>, contextType: TContext, ): RpcHandlerMetadata { const cacheMetadata = this.handlerMetadataStorage.get(instance, methodName); if (cacheMetadata) { return cacheMetadata; } const metadata = this.contextUtils.reflectCallbackMetadata<TMetadata>( instance, methodName, PARAM_ARGS_METADATA, ) || defaultCallMetadata; const keys = Object.keys(metadata); const argsLength = this.contextUtils.getArgumentsLength(keys, metadata); const paramtypes = this.contextUtils.reflectCallbackParamtypes( instance, methodName, ); const contextFactory = this.contextUtils.getContextFactory( contextType, instance, instance[methodName], ); const getParamsMetadata = (moduleKey: string) => this.exchangeKeysForValues( keys, metadata, moduleKey, this.rpcParamsFactory, contextFactory, ); const handlerMetadata: RpcHandlerMetadata = { argsLength, paramtypes, getParamsMetadata, }; this.handlerMetadataStorage.set(instance, methodName, handlerMetadata); return handlerMetadata; } public exchangeKeysForValues<TMetadata = any>( keys: string[], metadata: TMetadata, moduleContext: string, paramsFactory: RpcParamsFactory, contextFactory: (args: unknown[]) => ExecutionContextHost, ): ParamProperties[] { this.pipesContextCreator.setModuleContext(moduleContext); return keys.map(key => { const { index, data, pipes: pipesCollection } = metadata[key]; const pipes = this.pipesContextCreator.createConcreteContext( pipesCollection, ); const type = this.contextUtils.mapParamType(key); if (key.includes(CUSTOM_ROUTE_AGRS_METADATA)) { const { factory } = metadata[key]; const customExtractValue = this.contextUtils.getCustomFactory( factory, data, contextFactory, ); return { index, extractValue: customExtractValue, type, data, pipes }; } const numericType = Number(type); const extractValue = (...args: unknown[]) => paramsFactory.exchangeKeyForValue(numericType, args); return { index, extractValue, type: numericType, data, pipes }; }); } public createPipesFn( pipes: PipeTransform[], paramsOptions: (ParamProperties & { metatype?: unknown })[], ) { const pipesFn = async (args: unknown[], ...params: unknown[]) => { const resolveParamValue = async ( param: ParamProperties & { metatype?: unknown }, ) => { const { index, extractValue, type, data, metatype, pipes: paramPipes, } = param; const value = extractValue(...params); args[index] = await this.getParamValue( value, { metatype, type, data }, pipes.concat(paramPipes), ); }; await Promise.all(paramsOptions.map(resolveParamValue)); }; return paramsOptions.length ? pipesFn : null; } public async getParamValue<T>( value: T, { metatype, type, data }: { metatype: any; type: any; data: any }, pipes: PipeTransform[], ): Promise<any> { return isEmpty(pipes) ? value : this.pipesConsumer.apply(value, { metatype, type, data }, pipes); } }
packages/microservices/context/rpc-context-creator.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00039622755139134824, 0.00018042523879557848, 0.00016075783059932292, 0.00017404028039891273, 0.000040971764974528924 ]
{ "id": 6, "code_window": [ " socketOptions?: any;\n", " noAck?: boolean;\n", " serializer?: Serializer;\n", " deserializer?: Deserializer;\n", " replyQueue?: string;\n", " };\n", "}\n", "\n", "export interface KafkaOptions {\n", " transport?: Transport.KAFKA;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " persistent?: boolean;\n" ], "file_path": "packages/microservices/interfaces/microservice-configuration.interface.ts", "type": "add", "edit_start_line_idx": 131 }
import { Controller, Get, INestApplication, MiddlewareConsumer, Module, Post, RequestMethod, } from '@nestjs/common'; import { FastifyAdapter, NestFastifyApplication, } from '@nestjs/platform-fastify'; import { Test } from '@nestjs/testing'; import * as request from 'supertest'; import { ApplicationModule } from '../src/app.module'; const RETURN_VALUE = 'test'; const MIDDLEWARE_VALUE = 'middleware'; @Controller() class TestController { @Get('test') test() { return RETURN_VALUE; } @Get('test2') test2() { return RETURN_VALUE; } @Get('middleware') middleware() { return RETURN_VALUE; } @Post('middleware') noMiddleware() { return RETURN_VALUE; } @Get('wildcard/overview') testOverview() { return RETURN_VALUE; } @Get('overview/:id') overviewById() { return RETURN_VALUE; } } @Module({ imports: [ApplicationModule], controllers: [TestController], }) class TestModule { configure(consumer: MiddlewareConsumer) { consumer .apply((req, res, next) => res.end(MIDDLEWARE_VALUE)) .exclude('test', 'overview/:id', 'wildcard/(.*)', { path: 'middleware', method: RequestMethod.POST, }) .forRoutes('*'); } } describe('Exclude middleware (fastify)', () => { let app: INestApplication; beforeEach(async () => { app = ( await Test.createTestingModule({ imports: [TestModule], }).compile() ).createNestApplication<NestFastifyApplication>(new FastifyAdapter()); await app.init(); await app.getHttpAdapter().getInstance().ready(); }); it(`should exclude "/test" endpoint`, () => { return request(app.getHttpServer()).get('/test').expect(200, RETURN_VALUE); }); it(`should not exclude "/test2" endpoint`, () => { return request(app.getHttpServer()) .get('/test2') .expect(200, MIDDLEWARE_VALUE); }); it(`should run middleware for "/middleware" endpoint`, () => { return request(app.getHttpServer()) .get('/middleware') .expect(200, MIDDLEWARE_VALUE); }); it(`should exclude POST "/middleware" endpoint`, () => { return request(app.getHttpServer()) .post('/middleware') .expect(201, RETURN_VALUE); }); it(`should exclude "/overview/:id" endpoint (by param)`, () => { return request(app.getHttpServer()) .get('/overview/1') .expect(200, RETURN_VALUE); }); it(`should exclude "/wildcard/overview" endpoint (by wildcard)`, () => { return request(app.getHttpServer()) .get('/wildcard/overview') .expect(200, RETURN_VALUE); }); afterEach(async () => { await app.close(); }); });
integration/hello-world/e2e/exclude-middleware-fastify.spec.ts
0
https://github.com/nestjs/nest/commit/491d1934adcb11a6a91d19b72c0c3d2765167764
[ 0.00018128148803953081, 0.0001755072153173387, 0.0001716019760351628, 0.00017490985919721425, 0.0000025631811695348006 ]
{ "id": 1, "code_window": [ " /**\n", " * Register a handler to be called when Ajax requests complete. This is an AjaxEvent.\n", " *\n", " * @param handler The function to be invoked.\n", " */\n", " ajaxComplete(handler: (event: any, XMLHttpRequest: any, ajaxOptions: any) => any): JQuery;\n", " ajaxError(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxSend(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxStart(handler: () => any): JQuery;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ajaxComplete(handler: (event: any, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery;\n" ], "file_path": "jquery/jquery.d.ts", "type": "replace", "edit_start_line_idx": 668 }
/* ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. 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 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ // Typing for the jQuery library, version 1.10.x / 2.0.x // Project: http://jquery.com/ // Definitions by: Boris Yankov <https://github.com/borisyankov/>, Christian Hoffmeister <https://github.com/choffmeister>, Steve Fenton, Diullei Gomes <https://github.com/Diullei>, Tass Iliopoulos <https://github.com/tasoili>, Jason Swearingen, Sean Hill <https://github.com/seanski>, Guus Goossens <https://github.com/Guuz>, Kelly Summerlin <https://github.com/ksummerlin>, Basarat Ali Syed <https://github.com/basarat>, Nicholas Wolverson <https://github.com/nwolverson>, Derek Cicerone <https://github.com/derekcicerone>, Andrew Gaspar <https://github.com/AndrewGaspar>, James Harrison Fisher <https://github.com/jameshfisher>, Seikichi Kondo <https://github.com/seikichi>, Benjamin Jackman <https://github.com/benjaminjackman>, Poul Sorensen <https://github.com/s093294>, Josh Strobl <https://github.com/JoshStrobl>, John Reilly <https://github.com/johnnyreilly/> // Definitions: https://github.com/borisyankov/DefinitelyTyped /* Interface for the AJAX setting that will configure the AJAX request */ interface JQueryAjaxSettings { /** * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. */ accepts?: any; /** * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). */ async?: boolean; /** * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. */ beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; /** * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. */ cache?: boolean; /** * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. */ complete? (jqXHR: JQueryXHR, textStatus: string): any; /** * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) */ contents?: { [key: string]: any; }; //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" // https://github.com/borisyankov/DefinitelyTyped/issues/742 /** * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. */ contentType?: any; /** * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). */ context?: any; /** * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) */ converters?: { [key: string]: any; }; /** * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) */ crossDomain?: boolean; /** * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). */ data?: any; /** * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. */ dataFilter? (data: any, ty: any): any; /** * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). */ dataType?: string; /** * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. */ error? (jqXHR: JQueryXHR, textStatus: string, errorThrow: string): any; /** * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. */ global?: boolean; /** * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) */ headers?: { [key: string]: any; }; /** * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. */ ifModified?: boolean; /** * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) */ isLocal?: boolean; /** * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } */ jsonp?: string; /** * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. */ jsonpCallback?: any; /** * A mime type to override the XHR mime type. (version added: 1.5.1) */ mimeType?: string; /** * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. */ password?: string; /** * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. */ processData?: boolean; /** * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. */ scriptCharset?: string; /** * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) */ statusCode?: { [key: string]: any; }; /** * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. */ success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; /** * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. */ timeout?: number; /** * Set this to true if you wish to use the traditional style of param serialization. */ traditional?: boolean; /** * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. */ type?: string; /** * A string containing the URL to which the request is sent. */ url?: string; /** * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. */ username?: string; /** * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. */ xhr?: any; /** * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) */ xhrFields?: { [key: string]: any; }; } /* Interface for the jqXHR object */ interface JQueryXHR extends XMLHttpRequest, JQueryPromise<any> { overrideMimeType(mimeType: string): any; abort(statusText?: string): void; } /* Interface for the JQuery callback */ interface JQueryCallback { add(...callbacks: any[]): any; disable(): any; empty(): any; fire(...arguments: any[]): any; fired(): boolean; fireWith(context: any, ...args: any[]): any; has(callback: any): boolean; lock(): any; locked(): boolean; remove(...callbacks: any[]): any; } /* Allows jQuery Promises to interop with non-jQuery promises */ interface JQueryGenericPromise<T> { then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => U): JQueryGenericPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (reason: any) => U): JQueryGenericPromise<U>; then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => JQueryGenericPromise<U>): JQueryGenericPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (reason: any) => JQueryGenericPromise<U>): JQueryGenericPromise<U>; } /* Interface for the JQuery promise, part of callbacks */ interface JQueryPromise<T> { // Generic versions of callbacks always(...alwaysCallbacks: T[]): JQueryPromise<T>; done(...doneCallbacks: T[]): JQueryPromise<T>; fail(...failCallbacks: T[]): JQueryPromise<T>; progress(...progressCallbacks: T[]): JQueryPromise<T>; always(...alwaysCallbacks: any[]): JQueryPromise<T>; done(...doneCallbacks: any[]): JQueryPromise<T>; fail(...failCallbacks: any[]): JQueryPromise<T>; progress(...progressCallbacks: any[]): JQueryPromise<T>; // Deprecated - given no typings pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise<any>; then<U>(onFulfill: (value: T) => U, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (value: T) => U, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; // Because JQuery Promises Suck then<U>(onFulfill: (...values: any[]) => U, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (...values: any[]) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (...values: any[]) => U, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (...values: any[]) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; } /* Interface for the JQuery deferred, part of callbacks */ interface JQueryDeferred<T> extends JQueryPromise<T> { // Generic versions of callbacks always(...alwaysCallbacks: T[]): JQueryDeferred<T>; done(...doneCallbacks: T[]): JQueryDeferred<T>; fail(...failCallbacks: T[]): JQueryDeferred<T>; progress(...progressCallbacks: T[]): JQueryDeferred<T>; always(...alwaysCallbacks: any[]): JQueryDeferred<T>; done(...doneCallbacks: any[]): JQueryDeferred<T>; fail(...failCallbacks: any[]): JQueryDeferred<T>; progress(...progressCallbacks: any[]): JQueryDeferred<T>; notify(...args: any[]): JQueryDeferred<T>; notifyWith(context: any, ...args: any[]): JQueryDeferred<T>; reject(...args: any[]): JQueryDeferred<T>; rejectWith(context: any, ...args: any[]): JQueryDeferred<T>; resolve(val: T): JQueryDeferred<T>; resolve(...args: any[]): JQueryDeferred<T>; resolveWith(context: any, ...args: any[]): JQueryDeferred<T>; state(): string; promise(target?: any): JQueryPromise<T>; } /* Interface of the JQuery extension of the W3C event object */ interface BaseJQueryEventObject extends Event { data: any; delegateTarget: Element; isDefaultPrevented(): boolean; isImmediatePropogationStopped(): boolean; isPropagationStopped(): boolean; namespace: string; preventDefault(): any; relatedTarget: Element; result: any; stopImmediatePropagation(): void; stopPropagation(): void; pageX: number; pageY: number; which: number; metaKey: boolean; } interface JQueryInputEventObject extends BaseJQueryEventObject { altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; } interface JQueryMouseEventObject extends JQueryInputEventObject { button: number; clientX: number; clientY: number; offsetX: number; offsetY: number; pageX: number; pageY: number; screenX: number; screenY: number; } interface JQueryKeyEventObject extends JQueryInputEventObject { char: any; charCode: number; key: any; keyCode: number; } interface JQueryPopStateEventObject extends BaseJQueryEventObject { originalEvent: PopStateEvent; } interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject, JQueryPopStateEventObject { } /* Collection of properties of the current browser */ interface JQuerySupport { ajax?: boolean; boxModel?: boolean; changeBubbles?: boolean; checkClone?: boolean; checkOn?: boolean; cors?: boolean; cssFloat?: boolean; hrefNormalized?: boolean; htmlSerialize?: boolean; leadingWhitespace?: boolean; noCloneChecked?: boolean; noCloneEvent?: boolean; opacity?: boolean; optDisabled?: boolean; optSelected?: boolean; scriptEval? (): boolean; style?: boolean; submitBubbles?: boolean; tbody?: boolean; } interface JQueryParam { (obj: any): string; (obj: any, traditional: boolean): string; } /** * The interface used to construct jQuery events (with $.Event). It is * defined separately instead of inline in JQueryStatic to allow * overriding the construction function with specific strings * returning specific event objects. */ interface JQueryEventConstructor { (name: string, eventProperties?: any): JQueryEventObject; new (name: string, eventProperties?: any): JQueryEventObject; } /** * The interface used to specify easing functions. */ interface JQueryEasing { linear(p: number): number; swing(p: number): number; } /* Static members of jQuery (those on $ and jQuery themselves) */ interface JQueryStatic { /** * Perform an asynchronous HTTP (Ajax) request. * * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). */ ajax(settings: JQueryAjaxSettings): JQueryXHR; /** * Perform an asynchronous HTTP (Ajax) request. * * @param url A string containing the URL to which the request is sent. * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). */ ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; /** * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). * * @param dataTypes An optional string containing one or more space-separated dataTypes * @param handler A handler to set default values for future Ajax requests. */ ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; /** * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). * * @param handler A handler to set default values for future Ajax requests. */ ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; ajaxSettings: JQueryAjaxSettings; /** * Set default values for future Ajax requests. Its use is not recommended. * * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. */ ajaxSetup(options: JQueryAjaxSettings): void; /** * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). */ get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). */ get(url: string, data?: Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). */ get(url: string, data?: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load JSON-encoded data from the server using a GET HTTP request. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. */ getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; /** * Load JSON-encoded data from the server using a GET HTTP request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. */ getJSON(url: string, data?: Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; /** * Load JSON-encoded data from the server using a GET HTTP request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. */ getJSON(url: string, data?: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; /** * Load a JavaScript file from the server using a GET HTTP request, then execute it. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. */ getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; param: JQueryParam; /** * Load data from the server using a HTTP POST request. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). */ post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP POST request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). */ post(url: string, data?: Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP POST request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). */ post(url: string, data?: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. * * @param flags An optional list of space-separated flags that change how the callback list behaves. */ Callbacks(flags?: string): JQueryCallback; /** * Holds or releases the execution of jQuery's ready event. * * @param hold Indicates whether the ready hold is being requested or released */ holdReady(hold: boolean): void; (selector: string, context?: any): JQuery; (element: Element): JQuery; (object: {}): JQuery; (elementArray: Element[]): JQuery; (object: JQuery): JQuery; (func: Function): JQuery; (array: any[]): JQuery; (): JQuery; /** * Relinquish jQuery's control of the $ variable. * * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). */ noConflict(removeAll?: boolean): Object; /** * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. * * @param deferreds One or more Deferred objects, or plain JavaScript objects. */ when<T>(...deferreds: JQueryGenericPromise<T>[]): JQueryPromise<T>; /** * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. * * @param deferreds One or more Deferred objects, or plain JavaScript objects. */ when<T>(...deferreds: T[]): JQueryPromise<T>; /** * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. * * @param deferreds One or more Deferred objects, or plain JavaScript objects. */ when<T>(...deferreds: any[]): JQueryPromise<T>; cssHooks: { [key: string]: any; }; cssNumber: any; /** * Store arbitrary data associated with the specified element. Returns the value that was set. * * @param element The DOM element to associate with the data. * @param key A string naming the piece of data to set. * @param value The new data value. */ data<T>(element: Element, key: string, value: T): T; /** * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. * * @param element The DOM element to associate with the data. * @param key A string naming the piece of data to set. */ data(element: Element, key: string): any; /** * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. * * @param element The DOM element to associate with the data. */ data(element: Element): any; dequeue(element: Element, queueName?: string): any; hasData(element: Element): boolean; queue(element: Element, queueName?: string): any[]; queue(element: Element, queueName: string, newQueueOrCallback: any): JQuery; removeData(element: Element, name?: string): JQuery; // Deferred Deferred<T>(beforeStart?: (deferred: JQueryDeferred<T>) => any): JQueryDeferred<T>; // Effects fx: { tick: () => void; interval: number; stop: () => void; speeds: { slow: number; fast: number; }; off: boolean; step: any; }; // Events proxy(fn: (...args: any[]) => any, context: any, ...args: any[]): any; proxy(context: any, name: string, ...args: any[]): any; Event: JQueryEventConstructor; // Internals error(message: any): JQuery; // Miscellaneous expr: any; fn: any; //TODO: Decide how we want to type this isReady: boolean; // Properties support: JQuerySupport; // Utilities contains(container: Element, contained: Element): boolean; each(collection: any, callback: (indexInArray: any, valueOfElement: any) => any): any; each(collection: JQuery, callback: (indexInArray: number, valueOfElement: HTMLElement) => any): any; each<T>(collection: T[], callback: (indexInArray: number, valueOfElement: T) => any): any; extend(target: any, ...objs: any[]): any; extend(deep: boolean, target: any, ...objs: any[]): any; globalEval(code: string): any; grep<T>(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; inArray<T>(value: T, array: T[], fromIndex?: number): number; isArray(obj: any): boolean; isEmptyObject(obj: any): boolean; isFunction(obj: any): boolean; isNumeric(value: any): boolean; isPlainObject(obj: any): boolean; isWindow(obj: any): boolean; isXMLDoc(node: Node): boolean; makeArray(obj: any): any[]; map<T, U>(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; map(array: any, callback: (elementOfArray: any, indexInArray: any) => any): any; merge<T>(first: T[], second: T[]): T[]; merge<T,U>(first: T[], second: U[]): any[]; noop(): any; now(): number; parseJSON(json: string): any; /** * Parses a string into an XML document. * * @param dataa well-formed XML string to be parsed */ parseXML(data: string): XMLDocument; queue(element: Element, queueName: string, newQueue: any[]): JQuery; trim(str: string): string; type(obj: any): string; unique(arr: any[]): any[]; /** * Parses a string into an array of DOM nodes. * * @param data HTML string to be parsed * @param context DOM element to serve as the context in which the HTML fragment will be created * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string */ parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; Animation(elem: any, properties: any, options: any): any; easing: JQueryEasing; } /** * The jQuery instance members */ interface JQuery { /** * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. * * @param handler The function to be invoked. */ ajaxComplete(handler: (event: any, XMLHttpRequest: any, ajaxOptions: any) => any): JQuery; ajaxError(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; ajaxSend(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; ajaxStart(handler: () => any): JQuery; ajaxStop(handler: () => any): JQuery; ajaxSuccess(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; /** * Load data from the server and place the returned HTML into the matched element. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param complete A callback function that is executed when the request completes. */ load(url: string, data?: string, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; /** * Load data from the server and place the returned HTML into the matched element. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param complete A callback function that is executed when the request completes. */ load(url: string, data?: Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; /** * Encode a set of form elements as a string for submission. */ serialize(): string; /** * Encode a set of form elements as an array of names and values. */ serializeArray(): Object[]; /** * Adds the specified class(es) to each of the set of matched elements. * * @param className One or more space-separated classes to be added to the class attribute of each matched element. */ addClass(className: string): JQuery; /** * Adds the specified class(es) to each of the set of matched elements. * * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. */ addClass(func: (index: number, className: string) => string): JQuery; /** * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. */ addBack(selector?: string): JQuery; /** * Get the value of an attribute for the first element in the set of matched elements. * * @param attributeName The name of the attribute to get. */ attr(attributeName: string): string; /** * Set one or more attributes for the set of matched elements. * * @param attributeName The name of the attribute to set. * @param value A value to set for the attribute. */ attr(attributeName: string, value: string): JQuery; /** * Set one or more attributes for the set of matched elements. * * @param attributeName The name of the attribute to set. * @param value A value to set for the attribute. */ attr(attributeName: string, value: number): JQuery; /** * Set one or more attributes for the set of matched elements. * * @param attributeName The name of the attribute to set. * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. */ attr(attributeName: string, func: (index: number, attr: any) => any): JQuery; /** * Set one or more attributes for the set of matched elements. * * @param attributes An object of attribute-value pairs to set. */ attr(attributes: Object): JQuery; /** * Determine whether any of the matched elements are assigned the given class. * * @param className The class name to search for. */ hasClass(className: string): boolean; html(): string; html(htmlString: string): JQuery; html(htmlContent: (index: number, oldhtml: string) => string): JQuery; html(obj: JQuery): JQuery; prop(propertyName: string): any; prop(propertyName: string, value: any): JQuery; prop(map: any): JQuery; prop(propertyName: string, func: (index: any, oldPropertyValue: any) => any): JQuery; /** * Remove an attribute from each element in the set of matched elements. * * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. */ removeAttr(attributeName: string): JQuery; /** * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. * * @param className One or more space-separated classes to be removed from the class attribute of each matched element. */ removeClass(className?: string): JQuery; /** * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. * * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. */ removeClass(func: (index: number, className: string) => string): JQuery; removeProp(propertyName: string): JQuery; /** * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. * * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. */ toggleClass(className: string, swtch?: boolean): JQuery; /** * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. * * @param swtch A boolean value to determine whether the class should be added or removed. */ toggleClass(swtch?: boolean): JQuery; /** * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. * * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. * @param swtch A boolean value to determine whether the class should be added or removed. */ toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; val(): any; val(value: string[]): JQuery; val(value: string): JQuery; val(value: number): JQuery; val(func: (index: any, value: any) => any): JQuery; /** * Get the value of style properties for the first element in the set of matched elements. * * @param propertyName A CSS property. */ css(propertyName: string): string; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: string): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: number): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: string[]): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: number[]): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. */ css(propertyName: string, value: (index: number, value: string) => string): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. */ css(propertyName: string, value: (index: number, value: number) => number): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param properties An object of property-value pairs to set. */ css(properties: Object): JQuery; height(): number; height(value: number): JQuery; height(value: string): JQuery; height(func: (index: any, height: any) => any): JQuery; innerHeight(): number; innerHeight(value: number): JQuery; innerWidth(): number; innerWidth(value: number): JQuery; offset(): { left: number; top: number; }; offset(coordinates: any): JQuery; offset(func: (index: any, coords: any) => any): JQuery; outerHeight(includeMargin?: boolean): number; outerHeight(value: number, includeMargin?: boolean): JQuery; outerWidth(includeMargin?: boolean): number; outerWidth(value: number, includeMargin?: boolean): JQuery; position(): { top: number; left: number; }; scrollLeft(): number; scrollLeft(value: number): JQuery; scrollTop(): number; scrollTop(value: number): JQuery; width(): number; width(value: number): JQuery; width(value: string): JQuery; width(func: (index: any, height: any) => any): JQuery; // Data clearQueue(queueName?: string): JQuery; data(key: string, value: any): JQuery; data(obj: { [key: string]: any; }): JQuery; data(key?: string): any; dequeue(queueName?: string): JQuery; removeData(nameOrList?: any): JQuery; // Deferred promise(type?: any, target?: any): JQueryPromise<any>; // Effects animate(properties: any, duration?: any, complete?: Function): JQuery; animate(properties: any, duration?: any, easing?: string, complete?: Function): JQuery; animate(properties: any, options: { duration?: any; easing?: string; complete?: Function; step?: Function; queue?: boolean; specialEasing?: any; }): JQuery; delay(duration: number, queueName?: string): JQuery; fadeIn(duration?: any, callback?: any): JQuery; fadeIn(duration?: any, easing?: string, callback?: any): JQuery; fadeOut(duration?: any, callback?: any): JQuery; fadeOut(duration?: any, easing?: string, callback?: any): JQuery; fadeTo(duration: any, opacity: number, callback?: any): JQuery; fadeTo(duration: any, opacity: number, easing?: string, callback?: any): JQuery; fadeToggle(duration?: any, callback?: any): JQuery; fadeToggle(duration?: any, easing?: string, callback?: any): JQuery; finish(): JQuery; hide(duration?: any, callback?: any): JQuery; hide(duration?: any, easing?: string, callback?: any): JQuery; show(duration?: any, callback?: any): JQuery; show(duration?: any, easing?: string, callback?: any): JQuery; slideDown(duration?: any, callback?: any): JQuery; slideDown(duration?: any, easing?: string, callback?: any): JQuery; slideToggle(duration?: any, callback?: any): JQuery; slideToggle(duration?: any, easing?: string, callback?: any): JQuery; slideUp(duration?: any, callback?: any): JQuery; slideUp(duration?: any, easing?: string, callback?: any): JQuery; stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; stop(queue?: any, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; toggle(duration?: any, callback?: any): JQuery; toggle(duration?: any, easing?: string, callback?: any): JQuery; toggle(showOrHide: boolean): JQuery; // Events bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; bind(eventType: string, preventBubble: boolean): JQuery; bind(...events: any[]): JQuery; blur(handler: (eventObject: JQueryEventObject) => any): JQuery; blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "change" event on an element. */ change(): JQuery; /** * Bind an event handler to the "change" JavaScript event * * @param handler A function to execute each time the event is triggered. */ change(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "change" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "click" event on an element. */ click(): JQuery; /** * Bind an event handler to the "click" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. */ click(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "click" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "dblclick" event on an element. */ dblclick(): JQuery; /** * Bind an event handler to the "dblclick" JavaScript event * * @param handler A function to execute each time the event is triggered. */ dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "dblclick" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "focus" event on an element. */ focus(): JQuery; /** * Bind an event handler to the "focus" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focus(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focus" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusin" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusin" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusout" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusout" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. * * @param handlerIn A function to execute when the mouse pointer enters the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. */ hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. * * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. */ hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "keydown" event on an element. */ keydown(): JQuery; /** * Bind an event handler to the "keydown" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the keydown"" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Trigger the "keypress" event on an element. */ keypress(): JQuery; /** * Bind an event handler to the "keypress" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the "keypress" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Trigger the "keyup" event on an element. */ keyup(): JQuery; /** * Bind an event handler to the "keyup" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the "keyup" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the "load" JavaScript event. * * @param handler A function to execute when the event is triggered. */ load(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "load" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "mousedown" event on an element. */ mousedown(): JQuery; /** * Bind an event handler to the "mousedown" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mousedown" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseenter" event on an element. */ mouseenter(): JQuery; /** * Bind an event handler to be fired when the mouse enters an element. * * @param handler A function to execute when the event is triggered. */ mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to be fired when the mouse enters an element. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseleave" event on an element. */ mouseleave(): JQuery; /** * Bind an event handler to be fired when the mouse leaves an element. * * @param handler A function to execute when the event is triggered. */ mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to be fired when the mouse leaves an element. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mousemove" event on an element. */ mousemove(): JQuery; /** * Bind an event handler to the "mousemove" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mousemove" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseout" event on an element. */ mouseout(): JQuery; /** * Bind an event handler to the "mouseout" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mouseout" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseover" event on an element. */ mouseover(): JQuery; /** * Bind an event handler to the "mouseover" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mouseover" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseup" event on an element. */ mouseup(): JQuery; /** * Bind an event handler to the "mouseup" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mouseup" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Remove an event handler. */ off(): JQuery; /** * Remove an event handler. * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. * @param handler A handler function previously attached for the event(s), or the special value false. */ off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove an event handler. * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". * @param handler A handler function previously attached for the event(s), or the special value false. */ off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove an event handler. * * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. */ off(events: { [key: string]: any; }, selector?: string): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). */ on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ on(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. */ on(events: { [key: string]: any; }, selector?: any, data?: any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param handler A function to execute at the time the event is triggered. */ one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param data An object containing data that will be passed to the event handler. * @param handler A function to execute at the time the event is triggered. */ one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. */ one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; /** * Specify a function to execute when the DOM is fully loaded. * * @param handler A function to execute after the DOM is ready. */ ready(handler: Function): JQuery; /** * Trigger the "resize" event on an element. */ resize(): JQuery; /** * Bind an event handler to the "resize" JavaScript event. * * @param handler A function to execute each time the event is triggered. */ resize(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "resize" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "scroll" event on an element. */ scroll(): JQuery; /** * Bind an event handler to the "scroll" JavaScript event. * * @param handler A function to execute each time the event is triggered. */ scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "scroll" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "select" event on an element. */ select(): JQuery; /** * Bind an event handler to the "select" JavaScript event. * * @param handler A function to execute each time the event is triggered. */ select(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "select" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "submit" event on an element. */ submit(): JQuery; /** * Bind an event handler to the "submit" JavaScript event * * @param handler A function to execute each time the event is triggered. */ submit(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "submit" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; trigger(eventType: string, ...extraParameters: any[]): JQuery; trigger(event: JQueryEventObject): JQuery; triggerHandler(eventType: string, ...extraParameters: any[]): Object; unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; unbind(eventType: string, fls: boolean): JQuery; unbind(evt: any): JQuery; undelegate(): JQuery; undelegate(selector: any, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; undelegate(selector: any, events: any): JQuery; undelegate(namespace: string): JQuery; unload(handler: (eventObject: JQueryEventObject) => any): JQuery; unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; // Internals context: Element; jquery: string; error(handler: (eventObject: JQueryEventObject) => any): JQuery; error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; pushStack(elements: any[]): JQuery; pushStack(elements: any[], name: any, arguments: any): JQuery; // Manipulation after(...content: any[]): JQuery; after(func: (index: any) => any): JQuery; append(...content: any[]): JQuery; append(func: (index: any, html: any) => any): JQuery; appendTo(target: any): JQuery; before(...content: any[]): JQuery; before(func: (index: any) => any): JQuery; clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; detach(selector?: any): JQuery; empty(): JQuery; insertAfter(target: any): JQuery; insertBefore(target: any): JQuery; prepend(...content: any[]): JQuery; prepend(func: (index: any, html: any) => any): JQuery; prependTo(target: any): JQuery; remove(selector?: any): JQuery; replaceAll(target: any): JQuery; replaceWith(func: any): JQuery; text(): string; text(textString: any): JQuery; text(textString: (index: number, text: string) => string): JQuery; toArray(): any[]; unwrap(): JQuery; wrap(wrappingElement: any): JQuery; wrap(func: (index: any) => any): JQuery; wrapAll(wrappingElement: any): JQuery; wrapInner(wrappingElement: any): JQuery; wrapInner(func: (index: any) => any): JQuery; // Miscellaneous each(func: (index: any, elem: Element) => any): JQuery; get(index?: number): any; index(): number; index(selector: string): number; index(element: any): number; // Properties length: number; selector: string; [x: string]: any; [x: number]: HTMLElement; // Traversing add(selector: string, context?: any): JQuery; add(...elements: any[]): JQuery; add(html: string): JQuery; add(obj: JQuery): JQuery; children(selector?: any): JQuery; closest(selector: string): JQuery; closest(selector: string, context?: Element): JQuery; closest(obj: JQuery): JQuery; closest(element: any): JQuery; closest(selectors: any, context?: Element): any[]; contents(): JQuery; end(): JQuery; eq(index: number): JQuery; filter(selector: string): JQuery; filter(func: (index: any) => any): JQuery; filter(element: any): JQuery; filter(obj: JQuery): JQuery; find(selector: string): JQuery; find(element: any): JQuery; find(obj: JQuery): JQuery; first(): JQuery; has(selector: string): JQuery; has(contained: Element): JQuery; is(selector: string): boolean; is(func: (index: any) => any): boolean; is(element: any): boolean; is(obj: JQuery): boolean; last(): JQuery; map(callback: (index: any, domElement: Element) => any): JQuery; next(selector?: string): JQuery; nextAll(selector?: string): JQuery; nextUntil(selector?: string, filter?: string): JQuery; nextUntil(element?: Element, filter?: string): JQuery; nextUntil(obj?: JQuery, filter?: string): JQuery; not(selector: string): JQuery; not(func: (index: any) => any): JQuery; not(element: any): JQuery; not(obj: JQuery): JQuery; offsetParent(): JQuery; parent(selector?: string): JQuery; parents(selector?: string): JQuery; parentsUntil(selector?: string, filter?: string): JQuery; parentsUntil(element?: Element, filter?: string): JQuery; parentsUntil(obj?: JQuery, filter?: string): JQuery; prev(selector?: string): JQuery; prevAll(selector?: string): JQuery; prevUntil(selector?: string, filter?: string): JQuery; prevUntil(element?: Element, filter?: string): JQuery; prevUntil(obj?: JQuery, filter?: string): JQuery; siblings(selector?: string): JQuery; slice(start: number, end?: number): JQuery; // Utilities queue(queueName?: string): any[]; queue(queueName: string, newQueueOrCallback: any): JQuery; queue(newQueueOrCallback: any): JQuery; } declare module "jquery" { export = $; } declare var jQuery: JQueryStatic; declare var $: JQueryStatic;
jquery/jquery.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.9677870869636536, 0.007466101087629795, 0.00016416651487816125, 0.00026290572714060545, 0.07532711327075958 ]
{ "id": 1, "code_window": [ " /**\n", " * Register a handler to be called when Ajax requests complete. This is an AjaxEvent.\n", " *\n", " * @param handler The function to be invoked.\n", " */\n", " ajaxComplete(handler: (event: any, XMLHttpRequest: any, ajaxOptions: any) => any): JQuery;\n", " ajaxError(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxSend(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxStart(handler: () => any): JQuery;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ajaxComplete(handler: (event: any, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery;\n" ], "file_path": "jquery/jquery.d.ts", "type": "replace", "edit_start_line_idx": 668 }
""
fancybox/fancybox.d.ts.tscparams
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.00017474766355007887, 0.00017474766355007887, 0.00017474766355007887, 0.00017474766355007887, 0 ]
{ "id": 1, "code_window": [ " /**\n", " * Register a handler to be called when Ajax requests complete. This is an AjaxEvent.\n", " *\n", " * @param handler The function to be invoked.\n", " */\n", " ajaxComplete(handler: (event: any, XMLHttpRequest: any, ajaxOptions: any) => any): JQuery;\n", " ajaxError(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxSend(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxStart(handler: () => any): JQuery;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ajaxComplete(handler: (event: any, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery;\n" ], "file_path": "jquery/jquery.d.ts", "type": "replace", "edit_start_line_idx": 668 }
""
nodemailer/nodemailer-tests.ts.tscparams
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.00017474766355007887, 0.00017474766355007887, 0.00017474766355007887, 0.00017474766355007887, 0 ]
{ "id": 1, "code_window": [ " /**\n", " * Register a handler to be called when Ajax requests complete. This is an AjaxEvent.\n", " *\n", " * @param handler The function to be invoked.\n", " */\n", " ajaxComplete(handler: (event: any, XMLHttpRequest: any, ajaxOptions: any) => any): JQuery;\n", " ajaxError(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxSend(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery;\n", " ajaxStart(handler: () => any): JQuery;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ajaxComplete(handler: (event: any, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery;\n" ], "file_path": "jquery/jquery.d.ts", "type": "replace", "edit_start_line_idx": 668 }
// https://github.com/mde/jake /// <reference path="jake.d.ts" /> import path = require("path"); desc('This is the default task.'); task('default', function (params) { console.log('This is the default task.'); }); desc('This task has prerequisites.'); task('hasPrereqs', ['foo', 'bar', 'baz'], function () { console.log('Ran some prereqs first.'); }); desc('This is an asynchronous task.'); task('asyncTask', {async: true}, function () { setTimeout(complete, 1000); }); desc('This builds a minified JS file for production.'); file('foo-minified.js', ['bar', 'foo-bar.js', 'foo-baz.js'], function () { // Code to concat and minify goes here }); desc('This creates the bar directory for use with the foo-minified.js file-task.'); directory('bar'); desc('This is the default task.'); task('default', function () { console.log('This is the default task.'); }); namespace('foo', function () { desc('This the foo:bar task'); task('bar', function () { console.log('doing foo:bar task'); }); desc('This the foo:baz task'); task('baz', ['default', 'foo:bar'], function () { console.log('doing foo:baz task'); }); }); desc('This is an awesome task.'); task('awesome', function (a, b, c) { console.log(a, b, c); }); desc('This is an awesome task.'); task('awesome', function (a, b, c) { console.log(a, b, c); console.log(process.env.qux, process.env.frang); }); jake.addListener('complete', function () { process.exit(); }); desc('Calls the foo:bar task and its prerequisites.'); task('invokeFooBar', function () { // Calls foo:bar and its prereqs jake.Task['foo:bar'].invoke(); }); desc('Calls the foo:bar task and its prerequisites.'); task('invokeFooBar', function () { // Calls foo:bar and its prereqs jake.Task['foo:bar'].invoke(); // Does nothing jake.Task['foo:bar'].invoke(); }); desc('Calls the foo:bar task without its prerequisites.'); task('executeFooBar', function () { // Calls foo:bar without its prereqs jake.Task['foo:baz'].execute(); }); desc('Calls the foo:bar task without its prerequisites.'); task('executeFooBar', function () { // Calls foo:bar without its prereqs jake.Task['foo:baz'].execute(); // Can keep running this over and over jake.Task['foo:baz'].execute(); jake.Task['foo:baz'].execute(); }); desc('Calls the foo:bar task and its prerequisites.'); task('invokeFooBar', function () { // Calls foo:bar and its prereqs jake.Task['foo:bar'].invoke(); // Does nothing jake.Task['foo:bar'].invoke(); // Only re-runs foo:bar, but not its prerequisites jake.Task['foo:bar'].reenable(); jake.Task['foo:bar'].invoke(); }); desc('Calls the foo:bar task and its prerequisites.'); task('invokeFooBar', function () { // Calls foo:bar and its prereqs jake.Task['foo:bar'].invoke(); // Does nothing jake.Task['foo:bar'].invoke(); // Re-runs foo:bar and all of its prerequisites jake.Task['foo:bar'].reenable(true); jake.Task['foo:bar'].invoke(); }); desc('Passes params on to other tasks.'); task('passParams', function () { var t = jake.Task['foo:bar']; // Calls foo:bar, passing along current args t.invoke.apply(t, arguments); }); desc('Calls the async foo:baz task and its prerequisites.'); task('invokeFooBaz', {async: true}, function () { var t = jake.Task['foo:baz']; t.addListener('complete', function () { console.log('Finished executing foo:baz'); // Maybe run some other code // ... // Complete the containing task complete(); }); // Kick off foo:baz t.invoke(); }); namespace('vronk', function () { task('groo', function () { var t = jake.Task['vronk:zong']; t.addListener('error', function (e) { console.log(e.message); }); t.invoke(); }); task('zong', function () { throw new Error('OMFGZONG'); }); }); desc('This task fails.'); task('failTask', function () { fail('Yikes. Something back happened.'); }); desc('This task fails with an exit-status of 42.'); task('failTaskQuestionCustomStatus', function () { fail('What is the answer?', 42); }); declare var sourceDir:string; declare var currentDir:string; jake.mkdirP('app/views/layouts'); jake.cpR(path.join(sourceDir, '/templates'), currentDir); jake.readdirR('pkg'); jake.rmRf('pkg'); desc('Runs the Jake tests.'); task('test', {async: true}, function () { var cmds = [ 'node ./tests/parseargs.js' , 'node ./tests/task_base.js' , 'node ./tests/file_task.js' ]; jake.exec(cmds, function () { console.log('All tests passed.'); complete(); }, {printStdout: true}); }); var ex = jake.createExec(['do_thing.sh'], {printStdout: true}); ex.addListener('error', function (msg, code) { if (code == 127) { console.log("Couldn't find do_thing script, trying do_other_thing"); ex.append('do_other_thing.sh'); } else { fail('Fatal error: ' + msg, code); } }); ex.run(); task('echo', {async: true}, function () { jake.exec(['echo "hello"'], function () { jake.logger.log('Done.'); complete(); }, {printStdout: !jake.program.opts.quiet}); }); function hoge(){ var t = new jake.PackageTask('fonebone', 'v0.1.2112', function () { var fileList = [ 'Jakefile' , 'README.md' , 'package.json' , 'lib/*' , 'bin/*' , 'tests/*' ]; this.packageFiles.include(fileList); this.needTarGz = true; this.needTarBz2 = true; }); } var list = new jake.FileList(); list.include('foo/*.txt'); list.include(['bar/*.txt', 'README.md']); list.include('Makefile', 'package.json'); list.exclude('foo/zoobie.txt'); list.exclude(/foo\/src.*.txt/); console.log(list.toArray()); var t = new jake.TestTask('fonebone', function () { var fileList = [ 'tests/*' , 'lib/adapters/**/test.js' ]; this.testFiles.include(fileList); this.testFiles.exclude('tests/helper.js'); this.testName = 'testMainAndAdapters'; }); var assert = require('assert') , tests; tests = { 'sync test': function () { // Assert something assert.ok(true); } , 'async test': function (next) { // Assert something else assert.ok(true); // Won't go next until this is called next(); } , 'another sync test': function () { // Assert something else assert.ok(true); } }; //module.exports = tests; var p = new jake.NpmPublishTask('jake', [ 'Makefile' , 'Jakefile' , 'README.md' , 'package.json' , 'lib/*' , 'bin/*' , 'tests/*' ]);
jake/jake-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.0001739607978379354, 0.000169516570167616, 0.00016601820243522525, 0.00016936309111770242, 0.0000020453605884540593 ]
{ "id": 2, "code_window": [ "\n", " $(\"input[type='radio']\").checkboxradio({ mini: true });\n", " $(\"input[type='radio']\").checkboxradio({ theme: \"a\" });\n", " $(\"input[type='radio']\").checkboxradio('enable');\n", " $(\"input[type='radio']:first\").attr(\"checked\", true).checkboxradio(\"refresh\");\n", " $(\"input[type='radio']\").checkboxradio({\n", " create: function (event, ui) { }\n", " });\n", "\n", " $('select').selectmenu();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $(\"input[type='radio']:first\").prop(\"checked\", true).checkboxradio(\"refresh\");\n" ], "file_path": "jquerymobile/jquerymobile-tests.ts", "type": "replace", "edit_start_line_idx": 218 }
/* ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. 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 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ // Typing for the jQuery library, version 1.10.x / 2.0.x // Project: http://jquery.com/ // Definitions by: Boris Yankov <https://github.com/borisyankov/>, Christian Hoffmeister <https://github.com/choffmeister>, Steve Fenton, Diullei Gomes <https://github.com/Diullei>, Tass Iliopoulos <https://github.com/tasoili>, Jason Swearingen, Sean Hill <https://github.com/seanski>, Guus Goossens <https://github.com/Guuz>, Kelly Summerlin <https://github.com/ksummerlin>, Basarat Ali Syed <https://github.com/basarat>, Nicholas Wolverson <https://github.com/nwolverson>, Derek Cicerone <https://github.com/derekcicerone>, Andrew Gaspar <https://github.com/AndrewGaspar>, James Harrison Fisher <https://github.com/jameshfisher>, Seikichi Kondo <https://github.com/seikichi>, Benjamin Jackman <https://github.com/benjaminjackman>, Poul Sorensen <https://github.com/s093294>, Josh Strobl <https://github.com/JoshStrobl>, John Reilly <https://github.com/johnnyreilly/> // Definitions: https://github.com/borisyankov/DefinitelyTyped /* Interface for the AJAX setting that will configure the AJAX request */ interface JQueryAjaxSettings { /** * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. */ accepts?: any; /** * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). */ async?: boolean; /** * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. */ beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; /** * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. */ cache?: boolean; /** * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. */ complete? (jqXHR: JQueryXHR, textStatus: string): any; /** * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) */ contents?: { [key: string]: any; }; //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" // https://github.com/borisyankov/DefinitelyTyped/issues/742 /** * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. */ contentType?: any; /** * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). */ context?: any; /** * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) */ converters?: { [key: string]: any; }; /** * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) */ crossDomain?: boolean; /** * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). */ data?: any; /** * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. */ dataFilter? (data: any, ty: any): any; /** * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). */ dataType?: string; /** * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. */ error? (jqXHR: JQueryXHR, textStatus: string, errorThrow: string): any; /** * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. */ global?: boolean; /** * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) */ headers?: { [key: string]: any; }; /** * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. */ ifModified?: boolean; /** * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) */ isLocal?: boolean; /** * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } */ jsonp?: string; /** * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. */ jsonpCallback?: any; /** * A mime type to override the XHR mime type. (version added: 1.5.1) */ mimeType?: string; /** * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. */ password?: string; /** * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. */ processData?: boolean; /** * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. */ scriptCharset?: string; /** * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) */ statusCode?: { [key: string]: any; }; /** * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. */ success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; /** * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. */ timeout?: number; /** * Set this to true if you wish to use the traditional style of param serialization. */ traditional?: boolean; /** * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. */ type?: string; /** * A string containing the URL to which the request is sent. */ url?: string; /** * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. */ username?: string; /** * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. */ xhr?: any; /** * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) */ xhrFields?: { [key: string]: any; }; } /* Interface for the jqXHR object */ interface JQueryXHR extends XMLHttpRequest, JQueryPromise<any> { overrideMimeType(mimeType: string): any; abort(statusText?: string): void; } /* Interface for the JQuery callback */ interface JQueryCallback { add(...callbacks: any[]): any; disable(): any; empty(): any; fire(...arguments: any[]): any; fired(): boolean; fireWith(context: any, ...args: any[]): any; has(callback: any): boolean; lock(): any; locked(): boolean; remove(...callbacks: any[]): any; } /* Allows jQuery Promises to interop with non-jQuery promises */ interface JQueryGenericPromise<T> { then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => U): JQueryGenericPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (reason: any) => U): JQueryGenericPromise<U>; then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => JQueryGenericPromise<U>): JQueryGenericPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (reason: any) => JQueryGenericPromise<U>): JQueryGenericPromise<U>; } /* Interface for the JQuery promise, part of callbacks */ interface JQueryPromise<T> { // Generic versions of callbacks always(...alwaysCallbacks: T[]): JQueryPromise<T>; done(...doneCallbacks: T[]): JQueryPromise<T>; fail(...failCallbacks: T[]): JQueryPromise<T>; progress(...progressCallbacks: T[]): JQueryPromise<T>; always(...alwaysCallbacks: any[]): JQueryPromise<T>; done(...doneCallbacks: any[]): JQueryPromise<T>; fail(...failCallbacks: any[]): JQueryPromise<T>; progress(...progressCallbacks: any[]): JQueryPromise<T>; // Deprecated - given no typings pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise<any>; then<U>(onFulfill: (value: T) => U, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (value: T) => U, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (value: T) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; // Because JQuery Promises Suck then<U>(onFulfill: (...values: any[]) => U, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (...values: any[]) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (...values: any[]) => U, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; then<U>(onFulfill: (...values: any[]) => JQueryGenericPromise<U>, onReject?: (...reasons: any[]) => JQueryGenericPromise<U>, onProgress?: (...progression: any[]) => any): JQueryPromise<U>; } /* Interface for the JQuery deferred, part of callbacks */ interface JQueryDeferred<T> extends JQueryPromise<T> { // Generic versions of callbacks always(...alwaysCallbacks: T[]): JQueryDeferred<T>; done(...doneCallbacks: T[]): JQueryDeferred<T>; fail(...failCallbacks: T[]): JQueryDeferred<T>; progress(...progressCallbacks: T[]): JQueryDeferred<T>; always(...alwaysCallbacks: any[]): JQueryDeferred<T>; done(...doneCallbacks: any[]): JQueryDeferred<T>; fail(...failCallbacks: any[]): JQueryDeferred<T>; progress(...progressCallbacks: any[]): JQueryDeferred<T>; notify(...args: any[]): JQueryDeferred<T>; notifyWith(context: any, ...args: any[]): JQueryDeferred<T>; reject(...args: any[]): JQueryDeferred<T>; rejectWith(context: any, ...args: any[]): JQueryDeferred<T>; resolve(val: T): JQueryDeferred<T>; resolve(...args: any[]): JQueryDeferred<T>; resolveWith(context: any, ...args: any[]): JQueryDeferred<T>; state(): string; promise(target?: any): JQueryPromise<T>; } /* Interface of the JQuery extension of the W3C event object */ interface BaseJQueryEventObject extends Event { data: any; delegateTarget: Element; isDefaultPrevented(): boolean; isImmediatePropogationStopped(): boolean; isPropagationStopped(): boolean; namespace: string; preventDefault(): any; relatedTarget: Element; result: any; stopImmediatePropagation(): void; stopPropagation(): void; pageX: number; pageY: number; which: number; metaKey: boolean; } interface JQueryInputEventObject extends BaseJQueryEventObject { altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; } interface JQueryMouseEventObject extends JQueryInputEventObject { button: number; clientX: number; clientY: number; offsetX: number; offsetY: number; pageX: number; pageY: number; screenX: number; screenY: number; } interface JQueryKeyEventObject extends JQueryInputEventObject { char: any; charCode: number; key: any; keyCode: number; } interface JQueryPopStateEventObject extends BaseJQueryEventObject { originalEvent: PopStateEvent; } interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject, JQueryPopStateEventObject { } /* Collection of properties of the current browser */ interface JQuerySupport { ajax?: boolean; boxModel?: boolean; changeBubbles?: boolean; checkClone?: boolean; checkOn?: boolean; cors?: boolean; cssFloat?: boolean; hrefNormalized?: boolean; htmlSerialize?: boolean; leadingWhitespace?: boolean; noCloneChecked?: boolean; noCloneEvent?: boolean; opacity?: boolean; optDisabled?: boolean; optSelected?: boolean; scriptEval? (): boolean; style?: boolean; submitBubbles?: boolean; tbody?: boolean; } interface JQueryParam { (obj: any): string; (obj: any, traditional: boolean): string; } /** * The interface used to construct jQuery events (with $.Event). It is * defined separately instead of inline in JQueryStatic to allow * overriding the construction function with specific strings * returning specific event objects. */ interface JQueryEventConstructor { (name: string, eventProperties?: any): JQueryEventObject; new (name: string, eventProperties?: any): JQueryEventObject; } /** * The interface used to specify easing functions. */ interface JQueryEasing { linear(p: number): number; swing(p: number): number; } /* Static members of jQuery (those on $ and jQuery themselves) */ interface JQueryStatic { /** * Perform an asynchronous HTTP (Ajax) request. * * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). */ ajax(settings: JQueryAjaxSettings): JQueryXHR; /** * Perform an asynchronous HTTP (Ajax) request. * * @param url A string containing the URL to which the request is sent. * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). */ ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; /** * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). * * @param dataTypes An optional string containing one or more space-separated dataTypes * @param handler A handler to set default values for future Ajax requests. */ ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; /** * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). * * @param handler A handler to set default values for future Ajax requests. */ ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; ajaxSettings: JQueryAjaxSettings; /** * Set default values for future Ajax requests. Its use is not recommended. * * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. */ ajaxSetup(options: JQueryAjaxSettings): void; /** * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). */ get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). */ get(url: string, data?: Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP GET request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). */ get(url: string, data?: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load JSON-encoded data from the server using a GET HTTP request. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. */ getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; /** * Load JSON-encoded data from the server using a GET HTTP request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. */ getJSON(url: string, data?: Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; /** * Load JSON-encoded data from the server using a GET HTTP request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. */ getJSON(url: string, data?: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; /** * Load a JavaScript file from the server using a GET HTTP request, then execute it. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. */ getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; param: JQueryParam; /** * Load data from the server using a HTTP POST request. * * @param url A string containing the URL to which the request is sent. * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). */ post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP POST request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). */ post(url: string, data?: Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * Load data from the server using a HTTP POST request. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). */ post(url: string, data?: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; /** * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. * * @param flags An optional list of space-separated flags that change how the callback list behaves. */ Callbacks(flags?: string): JQueryCallback; /** * Holds or releases the execution of jQuery's ready event. * * @param hold Indicates whether the ready hold is being requested or released */ holdReady(hold: boolean): void; (selector: string, context?: any): JQuery; (element: Element): JQuery; (object: {}): JQuery; (elementArray: Element[]): JQuery; (object: JQuery): JQuery; (func: Function): JQuery; (array: any[]): JQuery; (): JQuery; /** * Relinquish jQuery's control of the $ variable. * * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). */ noConflict(removeAll?: boolean): Object; /** * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. * * @param deferreds One or more Deferred objects, or plain JavaScript objects. */ when<T>(...deferreds: JQueryGenericPromise<T>[]): JQueryPromise<T>; /** * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. * * @param deferreds One or more Deferred objects, or plain JavaScript objects. */ when<T>(...deferreds: T[]): JQueryPromise<T>; /** * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. * * @param deferreds One or more Deferred objects, or plain JavaScript objects. */ when<T>(...deferreds: any[]): JQueryPromise<T>; cssHooks: { [key: string]: any; }; cssNumber: any; /** * Store arbitrary data associated with the specified element. Returns the value that was set. * * @param element The DOM element to associate with the data. * @param key A string naming the piece of data to set. * @param value The new data value. */ data<T>(element: Element, key: string, value: T): T; /** * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. * * @param element The DOM element to associate with the data. * @param key A string naming the piece of data to set. */ data(element: Element, key: string): any; /** * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. * * @param element The DOM element to associate with the data. */ data(element: Element): any; dequeue(element: Element, queueName?: string): any; hasData(element: Element): boolean; queue(element: Element, queueName?: string): any[]; queue(element: Element, queueName: string, newQueueOrCallback: any): JQuery; removeData(element: Element, name?: string): JQuery; // Deferred Deferred<T>(beforeStart?: (deferred: JQueryDeferred<T>) => any): JQueryDeferred<T>; // Effects fx: { tick: () => void; interval: number; stop: () => void; speeds: { slow: number; fast: number; }; off: boolean; step: any; }; // Events proxy(fn: (...args: any[]) => any, context: any, ...args: any[]): any; proxy(context: any, name: string, ...args: any[]): any; Event: JQueryEventConstructor; // Internals error(message: any): JQuery; // Miscellaneous expr: any; fn: any; //TODO: Decide how we want to type this isReady: boolean; // Properties support: JQuerySupport; // Utilities contains(container: Element, contained: Element): boolean; each(collection: any, callback: (indexInArray: any, valueOfElement: any) => any): any; each(collection: JQuery, callback: (indexInArray: number, valueOfElement: HTMLElement) => any): any; each<T>(collection: T[], callback: (indexInArray: number, valueOfElement: T) => any): any; extend(target: any, ...objs: any[]): any; extend(deep: boolean, target: any, ...objs: any[]): any; globalEval(code: string): any; grep<T>(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; inArray<T>(value: T, array: T[], fromIndex?: number): number; isArray(obj: any): boolean; isEmptyObject(obj: any): boolean; isFunction(obj: any): boolean; isNumeric(value: any): boolean; isPlainObject(obj: any): boolean; isWindow(obj: any): boolean; isXMLDoc(node: Node): boolean; makeArray(obj: any): any[]; map<T, U>(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; map(array: any, callback: (elementOfArray: any, indexInArray: any) => any): any; merge<T>(first: T[], second: T[]): T[]; merge<T,U>(first: T[], second: U[]): any[]; noop(): any; now(): number; parseJSON(json: string): any; /** * Parses a string into an XML document. * * @param dataa well-formed XML string to be parsed */ parseXML(data: string): XMLDocument; queue(element: Element, queueName: string, newQueue: any[]): JQuery; trim(str: string): string; type(obj: any): string; unique(arr: any[]): any[]; /** * Parses a string into an array of DOM nodes. * * @param data HTML string to be parsed * @param context DOM element to serve as the context in which the HTML fragment will be created * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string */ parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; Animation(elem: any, properties: any, options: any): any; easing: JQueryEasing; } /** * The jQuery instance members */ interface JQuery { /** * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. * * @param handler The function to be invoked. */ ajaxComplete(handler: (event: any, XMLHttpRequest: any, ajaxOptions: any) => any): JQuery; ajaxError(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; ajaxSend(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; ajaxStart(handler: () => any): JQuery; ajaxStop(handler: () => any): JQuery; ajaxSuccess(handler: (event: any, jqXHR: any, settings: any, exception: any) => any): JQuery; /** * Load data from the server and place the returned HTML into the matched element. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param complete A callback function that is executed when the request completes. */ load(url: string, data?: string, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; /** * Load data from the server and place the returned HTML into the matched element. * * @param url A string containing the URL to which the request is sent. * @param data A plain object or string that is sent to the server with the request. * @param complete A callback function that is executed when the request completes. */ load(url: string, data?: Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; /** * Encode a set of form elements as a string for submission. */ serialize(): string; /** * Encode a set of form elements as an array of names and values. */ serializeArray(): Object[]; /** * Adds the specified class(es) to each of the set of matched elements. * * @param className One or more space-separated classes to be added to the class attribute of each matched element. */ addClass(className: string): JQuery; /** * Adds the specified class(es) to each of the set of matched elements. * * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. */ addClass(func: (index: number, className: string) => string): JQuery; /** * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. */ addBack(selector?: string): JQuery; /** * Get the value of an attribute for the first element in the set of matched elements. * * @param attributeName The name of the attribute to get. */ attr(attributeName: string): string; /** * Set one or more attributes for the set of matched elements. * * @param attributeName The name of the attribute to set. * @param value A value to set for the attribute. */ attr(attributeName: string, value: string): JQuery; /** * Set one or more attributes for the set of matched elements. * * @param attributeName The name of the attribute to set. * @param value A value to set for the attribute. */ attr(attributeName: string, value: number): JQuery; /** * Set one or more attributes for the set of matched elements. * * @param attributeName The name of the attribute to set. * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. */ attr(attributeName: string, func: (index: number, attr: any) => any): JQuery; /** * Set one or more attributes for the set of matched elements. * * @param attributes An object of attribute-value pairs to set. */ attr(attributes: Object): JQuery; /** * Determine whether any of the matched elements are assigned the given class. * * @param className The class name to search for. */ hasClass(className: string): boolean; html(): string; html(htmlString: string): JQuery; html(htmlContent: (index: number, oldhtml: string) => string): JQuery; html(obj: JQuery): JQuery; prop(propertyName: string): any; prop(propertyName: string, value: any): JQuery; prop(map: any): JQuery; prop(propertyName: string, func: (index: any, oldPropertyValue: any) => any): JQuery; /** * Remove an attribute from each element in the set of matched elements. * * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. */ removeAttr(attributeName: string): JQuery; /** * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. * * @param className One or more space-separated classes to be removed from the class attribute of each matched element. */ removeClass(className?: string): JQuery; /** * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. * * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. */ removeClass(func: (index: number, className: string) => string): JQuery; removeProp(propertyName: string): JQuery; /** * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. * * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. */ toggleClass(className: string, swtch?: boolean): JQuery; /** * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. * * @param swtch A boolean value to determine whether the class should be added or removed. */ toggleClass(swtch?: boolean): JQuery; /** * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. * * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. * @param swtch A boolean value to determine whether the class should be added or removed. */ toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; val(): any; val(value: string[]): JQuery; val(value: string): JQuery; val(value: number): JQuery; val(func: (index: any, value: any) => any): JQuery; /** * Get the value of style properties for the first element in the set of matched elements. * * @param propertyName A CSS property. */ css(propertyName: string): string; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: string): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: number): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: string[]): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: number[]): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. */ css(propertyName: string, value: (index: number, value: string) => string): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. */ css(propertyName: string, value: (index: number, value: number) => number): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param properties An object of property-value pairs to set. */ css(properties: Object): JQuery; height(): number; height(value: number): JQuery; height(value: string): JQuery; height(func: (index: any, height: any) => any): JQuery; innerHeight(): number; innerHeight(value: number): JQuery; innerWidth(): number; innerWidth(value: number): JQuery; offset(): { left: number; top: number; }; offset(coordinates: any): JQuery; offset(func: (index: any, coords: any) => any): JQuery; outerHeight(includeMargin?: boolean): number; outerHeight(value: number, includeMargin?: boolean): JQuery; outerWidth(includeMargin?: boolean): number; outerWidth(value: number, includeMargin?: boolean): JQuery; position(): { top: number; left: number; }; scrollLeft(): number; scrollLeft(value: number): JQuery; scrollTop(): number; scrollTop(value: number): JQuery; width(): number; width(value: number): JQuery; width(value: string): JQuery; width(func: (index: any, height: any) => any): JQuery; // Data clearQueue(queueName?: string): JQuery; data(key: string, value: any): JQuery; data(obj: { [key: string]: any; }): JQuery; data(key?: string): any; dequeue(queueName?: string): JQuery; removeData(nameOrList?: any): JQuery; // Deferred promise(type?: any, target?: any): JQueryPromise<any>; // Effects animate(properties: any, duration?: any, complete?: Function): JQuery; animate(properties: any, duration?: any, easing?: string, complete?: Function): JQuery; animate(properties: any, options: { duration?: any; easing?: string; complete?: Function; step?: Function; queue?: boolean; specialEasing?: any; }): JQuery; delay(duration: number, queueName?: string): JQuery; fadeIn(duration?: any, callback?: any): JQuery; fadeIn(duration?: any, easing?: string, callback?: any): JQuery; fadeOut(duration?: any, callback?: any): JQuery; fadeOut(duration?: any, easing?: string, callback?: any): JQuery; fadeTo(duration: any, opacity: number, callback?: any): JQuery; fadeTo(duration: any, opacity: number, easing?: string, callback?: any): JQuery; fadeToggle(duration?: any, callback?: any): JQuery; fadeToggle(duration?: any, easing?: string, callback?: any): JQuery; finish(): JQuery; hide(duration?: any, callback?: any): JQuery; hide(duration?: any, easing?: string, callback?: any): JQuery; show(duration?: any, callback?: any): JQuery; show(duration?: any, easing?: string, callback?: any): JQuery; slideDown(duration?: any, callback?: any): JQuery; slideDown(duration?: any, easing?: string, callback?: any): JQuery; slideToggle(duration?: any, callback?: any): JQuery; slideToggle(duration?: any, easing?: string, callback?: any): JQuery; slideUp(duration?: any, callback?: any): JQuery; slideUp(duration?: any, easing?: string, callback?: any): JQuery; stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; stop(queue?: any, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; toggle(duration?: any, callback?: any): JQuery; toggle(duration?: any, easing?: string, callback?: any): JQuery; toggle(showOrHide: boolean): JQuery; // Events bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; bind(eventType: string, preventBubble: boolean): JQuery; bind(...events: any[]): JQuery; blur(handler: (eventObject: JQueryEventObject) => any): JQuery; blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "change" event on an element. */ change(): JQuery; /** * Bind an event handler to the "change" JavaScript event * * @param handler A function to execute each time the event is triggered. */ change(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "change" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "click" event on an element. */ click(): JQuery; /** * Bind an event handler to the "click" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. */ click(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "click" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "dblclick" event on an element. */ dblclick(): JQuery; /** * Bind an event handler to the "dblclick" JavaScript event * * @param handler A function to execute each time the event is triggered. */ dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "dblclick" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "focus" event on an element. */ focus(): JQuery; /** * Bind an event handler to the "focus" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focus(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focus" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusin" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusin" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusout" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "focusout" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. * * @param handlerIn A function to execute when the mouse pointer enters the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. */ hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. * * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. */ hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "keydown" event on an element. */ keydown(): JQuery; /** * Bind an event handler to the "keydown" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the keydown"" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Trigger the "keypress" event on an element. */ keypress(): JQuery; /** * Bind an event handler to the "keypress" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the "keypress" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Trigger the "keyup" event on an element. */ keyup(): JQuery; /** * Bind an event handler to the "keyup" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the "keyup" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; /** * Bind an event handler to the "load" JavaScript event. * * @param handler A function to execute when the event is triggered. */ load(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "load" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "mousedown" event on an element. */ mousedown(): JQuery; /** * Bind an event handler to the "mousedown" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mousedown" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseenter" event on an element. */ mouseenter(): JQuery; /** * Bind an event handler to be fired when the mouse enters an element. * * @param handler A function to execute when the event is triggered. */ mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to be fired when the mouse enters an element. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseleave" event on an element. */ mouseleave(): JQuery; /** * Bind an event handler to be fired when the mouse leaves an element. * * @param handler A function to execute when the event is triggered. */ mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to be fired when the mouse leaves an element. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mousemove" event on an element. */ mousemove(): JQuery; /** * Bind an event handler to the "mousemove" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mousemove" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseout" event on an element. */ mouseout(): JQuery; /** * Bind an event handler to the "mouseout" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mouseout" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseover" event on an element. */ mouseover(): JQuery; /** * Bind an event handler to the "mouseover" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mouseover" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Trigger the "mouseup" event on an element. */ mouseup(): JQuery; /** * Bind an event handler to the "mouseup" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Bind an event handler to the "mouseup" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; /** * Remove an event handler. */ off(): JQuery; /** * Remove an event handler. * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. * @param handler A handler function previously attached for the event(s), or the special value false. */ off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove an event handler. * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". * @param handler A handler function previously attached for the event(s), or the special value false. */ off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove an event handler. * * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. */ off(events: { [key: string]: any; }, selector?: string): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). */ on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ on(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. */ on(events: { [key: string]: any; }, selector?: any, data?: any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param handler A function to execute at the time the event is triggered. */ one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param data An object containing data that will be passed to the event handler. * @param handler A function to execute at the time the event is triggered. */ one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. */ one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; /** * Specify a function to execute when the DOM is fully loaded. * * @param handler A function to execute after the DOM is ready. */ ready(handler: Function): JQuery; /** * Trigger the "resize" event on an element. */ resize(): JQuery; /** * Bind an event handler to the "resize" JavaScript event. * * @param handler A function to execute each time the event is triggered. */ resize(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "resize" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "scroll" event on an element. */ scroll(): JQuery; /** * Bind an event handler to the "scroll" JavaScript event. * * @param handler A function to execute each time the event is triggered. */ scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "scroll" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "select" event on an element. */ select(): JQuery; /** * Bind an event handler to the "select" JavaScript event. * * @param handler A function to execute each time the event is triggered. */ select(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "select" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "submit" event on an element. */ submit(): JQuery; /** * Bind an event handler to the "submit" JavaScript event * * @param handler A function to execute each time the event is triggered. */ submit(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "submit" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; trigger(eventType: string, ...extraParameters: any[]): JQuery; trigger(event: JQueryEventObject): JQuery; triggerHandler(eventType: string, ...extraParameters: any[]): Object; unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; unbind(eventType: string, fls: boolean): JQuery; unbind(evt: any): JQuery; undelegate(): JQuery; undelegate(selector: any, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; undelegate(selector: any, events: any): JQuery; undelegate(namespace: string): JQuery; unload(handler: (eventObject: JQueryEventObject) => any): JQuery; unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; // Internals context: Element; jquery: string; error(handler: (eventObject: JQueryEventObject) => any): JQuery; error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; pushStack(elements: any[]): JQuery; pushStack(elements: any[], name: any, arguments: any): JQuery; // Manipulation after(...content: any[]): JQuery; after(func: (index: any) => any): JQuery; append(...content: any[]): JQuery; append(func: (index: any, html: any) => any): JQuery; appendTo(target: any): JQuery; before(...content: any[]): JQuery; before(func: (index: any) => any): JQuery; clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; detach(selector?: any): JQuery; empty(): JQuery; insertAfter(target: any): JQuery; insertBefore(target: any): JQuery; prepend(...content: any[]): JQuery; prepend(func: (index: any, html: any) => any): JQuery; prependTo(target: any): JQuery; remove(selector?: any): JQuery; replaceAll(target: any): JQuery; replaceWith(func: any): JQuery; text(): string; text(textString: any): JQuery; text(textString: (index: number, text: string) => string): JQuery; toArray(): any[]; unwrap(): JQuery; wrap(wrappingElement: any): JQuery; wrap(func: (index: any) => any): JQuery; wrapAll(wrappingElement: any): JQuery; wrapInner(wrappingElement: any): JQuery; wrapInner(func: (index: any) => any): JQuery; // Miscellaneous each(func: (index: any, elem: Element) => any): JQuery; get(index?: number): any; index(): number; index(selector: string): number; index(element: any): number; // Properties length: number; selector: string; [x: string]: any; [x: number]: HTMLElement; // Traversing add(selector: string, context?: any): JQuery; add(...elements: any[]): JQuery; add(html: string): JQuery; add(obj: JQuery): JQuery; children(selector?: any): JQuery; closest(selector: string): JQuery; closest(selector: string, context?: Element): JQuery; closest(obj: JQuery): JQuery; closest(element: any): JQuery; closest(selectors: any, context?: Element): any[]; contents(): JQuery; end(): JQuery; eq(index: number): JQuery; filter(selector: string): JQuery; filter(func: (index: any) => any): JQuery; filter(element: any): JQuery; filter(obj: JQuery): JQuery; find(selector: string): JQuery; find(element: any): JQuery; find(obj: JQuery): JQuery; first(): JQuery; has(selector: string): JQuery; has(contained: Element): JQuery; is(selector: string): boolean; is(func: (index: any) => any): boolean; is(element: any): boolean; is(obj: JQuery): boolean; last(): JQuery; map(callback: (index: any, domElement: Element) => any): JQuery; next(selector?: string): JQuery; nextAll(selector?: string): JQuery; nextUntil(selector?: string, filter?: string): JQuery; nextUntil(element?: Element, filter?: string): JQuery; nextUntil(obj?: JQuery, filter?: string): JQuery; not(selector: string): JQuery; not(func: (index: any) => any): JQuery; not(element: any): JQuery; not(obj: JQuery): JQuery; offsetParent(): JQuery; parent(selector?: string): JQuery; parents(selector?: string): JQuery; parentsUntil(selector?: string, filter?: string): JQuery; parentsUntil(element?: Element, filter?: string): JQuery; parentsUntil(obj?: JQuery, filter?: string): JQuery; prev(selector?: string): JQuery; prevAll(selector?: string): JQuery; prevUntil(selector?: string, filter?: string): JQuery; prevUntil(element?: Element, filter?: string): JQuery; prevUntil(obj?: JQuery, filter?: string): JQuery; siblings(selector?: string): JQuery; slice(start: number, end?: number): JQuery; // Utilities queue(queueName?: string): any[]; queue(queueName: string, newQueueOrCallback: any): JQuery; queue(newQueueOrCallback: any): JQuery; } declare module "jquery" { export = $; } declare var jQuery: JQueryStatic; declare var $: JQueryStatic;
jquery/jquery.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.001138976658694446, 0.0001859129115473479, 0.00016015561413951218, 0.00016958948981482536, 0.0001048990452545695 ]
{ "id": 2, "code_window": [ "\n", " $(\"input[type='radio']\").checkboxradio({ mini: true });\n", " $(\"input[type='radio']\").checkboxradio({ theme: \"a\" });\n", " $(\"input[type='radio']\").checkboxradio('enable');\n", " $(\"input[type='radio']:first\").attr(\"checked\", true).checkboxradio(\"refresh\");\n", " $(\"input[type='radio']\").checkboxradio({\n", " create: function (event, ui) { }\n", " });\n", "\n", " $('select').selectmenu();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $(\"input[type='radio']:first\").prop(\"checked\", true).checkboxradio(\"refresh\");\n" ], "file_path": "jquerymobile/jquerymobile-tests.ts", "type": "replace", "edit_start_line_idx": 218 }
// Type definitions for Ladda 0.7.0 // Project: https://github.com/hakimel/Ladda // Definitions by: Danil Flores <https://github.com/dflor003/> // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module Ladda { interface ILaddaButton { start(): ILaddaButton; stop(): ILaddaButton; toggle(): ILaddaButton; setProgress(progress: number): ILaddaButton; enable(): ILaddaButton; disable(): ILaddaButton; isLoading(): boolean; } interface ILaddaOptions { timeout?: number; callback?: (instance: ILaddaButton) => void; } function bind(target: HTMLElement, options?: ILaddaOptions): void; function bind(cssSelector: string, options?: ILaddaOptions): void; function create(button: Element): ILaddaButton; function stopAll(): void; }
ladda/ladda.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.0004918400081805885, 0.000248783704591915, 0.0001635345397517085, 0.00016988013521768153, 0.0001403688220307231 ]