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": 0,
"code_window": [
"export interface EventLike {\n",
"\tpreventDefault(): void;\n",
"\tstopPropagation(): void;\n",
"}\n",
"\n",
"export const EventHelper = {\n",
"\tstop: <T extends EventLike>(e: T, cancelBubble?: boolean): T => {\n",
"\t\te.preventDefault();\n",
"\t\tif (cancelBubble) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function isEventLike(obj: unknown): obj is EventLike {\n",
"\tconst candidate = obj as EventLike | undefined;\n",
"\n",
"\treturn !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');\n",
"}\n",
"\n"
],
"file_path": "src/vs/base/browser/dom.ts",
"type": "add",
"edit_start_line_idx": 827
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITerminalLinkDetector, ITerminalSimpleLink, OmitFirstArg } from 'vs/workbench/contrib/terminal/browser/links/links';
import { convertLinkRangeToBuffer, getXtermLineContent } from 'vs/workbench/contrib/terminal/browser/links/terminalLinkHelpers';
import { ITerminalExternalLinkProvider } from 'vs/workbench/contrib/terminal/browser/terminal';
import { IBufferLine, Terminal } from 'xterm';
export class TerminalExternalLinkDetector implements ITerminalLinkDetector {
readonly maxLinkLength = 2000;
constructor(
readonly id: string,
readonly xterm: Terminal,
private readonly _provideLinks: OmitFirstArg<ITerminalExternalLinkProvider['provideLinks']>
) {
}
async detect(lines: IBufferLine[], startLine: number, endLine: number): Promise<ITerminalSimpleLink[]> {
// Get the text representation of the wrapped line
const text = getXtermLineContent(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
if (text === '' || text.length > this.maxLinkLength) {
return [];
}
const externalLinks = await this._provideLinks(text);
if (!externalLinks) {
return [];
}
const result = externalLinks.map(link => {
const bufferRange = convertLinkRangeToBuffer(lines, this.xterm.cols, {
startColumn: link.startIndex + 1,
startLineNumber: 1,
endColumn: link.startIndex + link.length + 1,
endLineNumber: 1
}, startLine);
const matchingText = text.substring(link.startIndex, link.startIndex + link.length) || '';
const l: ITerminalSimpleLink = {
text: matchingText,
label: link.label,
bufferRange,
type: { id: this.id },
activate: link.activate
};
return l;
});
return result;
}
}
| src/vs/workbench/contrib/terminal/browser/links/terminalExternalLinkDetector.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001754815166350454,
0.0001732221426209435,
0.00016598797810729593,
0.0001745895278872922,
0.000003261963229306275
] |
{
"id": 0,
"code_window": [
"export interface EventLike {\n",
"\tpreventDefault(): void;\n",
"\tstopPropagation(): void;\n",
"}\n",
"\n",
"export const EventHelper = {\n",
"\tstop: <T extends EventLike>(e: T, cancelBubble?: boolean): T => {\n",
"\t\te.preventDefault();\n",
"\t\tif (cancelBubble) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function isEventLike(obj: unknown): obj is EventLike {\n",
"\tconst candidate = obj as EventLike | undefined;\n",
"\n",
"\treturn !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');\n",
"}\n",
"\n"
],
"file_path": "src/vs/base/browser/dom.ts",
"type": "add",
"edit_start_line_idx": 827
} | # GitHub Authentication for Visual Studio Code
**Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled.
## Features
This extension provides support for authenticating to GitHub. It registers the `github` Authentication Provider that can be leveraged by other extensions. This also provides the GitHub authentication used by Settings Sync.
| extensions/github-authentication/README.md | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00016937941836658865,
0.00016937941836658865,
0.00016937941836658865,
0.00016937941836658865,
0
] |
{
"id": 1,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_NEXT_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.DownArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusNext();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 198
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.009791746735572815,
0.0004394231946207583,
0.00016086945834103972,
0.00017016274796333164,
0.001372103695757687
] |
{
"id": 1,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_NEXT_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.DownArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusNext();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 198
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { Selection, workspace, CancellationTokenSource, CompletionTriggerKind, ConfigurationTarget, CompletionContext } from 'vscode';
import { withRandomFileEditor, closeAllEditors } from './testUtils';
import { expandEmmetAbbreviation } from '../abbreviationActions';
import { DefaultCompletionItemProvider } from '../defaultCompletionProvider';
const completionProvider = new DefaultCompletionItemProvider();
const htmlContents = `
<body class="header">
<ul class="nav main">
<li class="item1">img</li>
<li class="item2">hithere</li>
ul>li
ul>li*2
ul>li.item$*2
ul>li.item$@44*2
<div i
</ul>
<style>
.boo {
display: dn; m10
}
</style>
<span></span>
(ul>li.item$)*2
(ul>li.item$)*2+span
(div>dl>(dt+dd)*2)
<script type="text/html">
span.hello
</script>
<script type="text/javascript">
span.bye
</script>
</body>
`;
const invokeCompletionContext: CompletionContext = {
triggerKind: CompletionTriggerKind.Invoke,
triggerCharacter: undefined,
};
suite('Tests for Expand Abbreviations (HTML)', () => {
const oldValueForExcludeLanguages = workspace.getConfiguration('emmet').inspect('excludeLanguages');
const oldValueForIncludeLanguages = workspace.getConfiguration('emmet').inspect('includeLanguages');
teardown(closeAllEditors);
test('Expand snippets (HTML)', () => {
return testExpandAbbreviation('html', new Selection(3, 23, 3, 23), 'img', '<img src=\"\" alt=\"\">');
});
test('Expand snippets in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(3, 23, 3, 23), 'img', '<img src=\"\" alt=\"\">');
});
test('Expand snippets when no parent node (HTML)', () => {
return withRandomFileEditor('img', 'html', async (editor, _doc) => {
editor.selection = new Selection(0, 3, 0, 3);
await expandEmmetAbbreviation(null);
assert.strictEqual(editor.document.getText(), '<img src=\"\" alt=\"\">');
return Promise.resolve();
});
});
test('Expand snippets when no parent node in completion list (HTML)', () => {
return withRandomFileEditor('img', 'html', async (editor, _doc) => {
editor.selection = new Selection(0, 3, 0, 3);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
if (!completionPromise) {
assert.strictEqual(!completionPromise, false, `Got unexpected undefined instead of a completion promise`);
return Promise.resolve();
}
const completionList = await completionPromise;
assert.strictEqual(completionList && completionList.items && completionList.items.length > 0, true);
if (completionList) {
assert.strictEqual(completionList.items[0].label, 'img');
assert.strictEqual(((<string>completionList.items[0].documentation) || '').replace(/\|/g, ''), '<img src=\"\" alt=\"\">');
}
return Promise.resolve();
});
});
test('Expand abbreviation (HTML)', () => {
return testExpandAbbreviation('html', new Selection(5, 25, 5, 25), 'ul>li', '<ul>\n\t\t\t<li></li>\n\t\t</ul>');
});
test('Expand abbreviation in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(5, 25, 5, 25), 'ul>li', '<ul>\n\t<li></li>\n</ul>');
});
test('Expand text that is neither an abbreviation nor a snippet to tags (HTML)', () => {
return testExpandAbbreviation('html', new Selection(4, 20, 4, 27), 'hithere', '<hithere></hithere>');
});
test('Do not Expand text that is neither an abbreviation nor a snippet to tags in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(4, 20, 4, 27), 'hithere', '<hithere></hithere>', true);
});
test('Expand abbreviation with repeaters (HTML)', () => {
return testExpandAbbreviation('html', new Selection(6, 27, 6, 27), 'ul>li*2', '<ul>\n\t\t\t<li></li>\n\t\t\t<li></li>\n\t\t</ul>');
});
test('Expand abbreviation with repeaters in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(6, 27, 6, 27), 'ul>li*2', '<ul>\n\t<li></li>\n\t<li></li>\n</ul>');
});
test('Expand abbreviation with numbered repeaters (HTML)', () => {
return testExpandAbbreviation('html', new Selection(7, 33, 7, 33), 'ul>li.item$*2', '<ul>\n\t\t\t<li class="item1"></li>\n\t\t\t<li class="item2"></li>\n\t\t</ul>');
});
test('Expand abbreviation with numbered repeaters in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(7, 33, 7, 33), 'ul>li.item$*2', '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
});
test('Expand abbreviation with numbered repeaters with offset (HTML)', () => {
return testExpandAbbreviation('html', new Selection(8, 36, 8, 36), 'ul>li.item$@44*2', '<ul>\n\t\t\t<li class="item44"></li>\n\t\t\t<li class="item45"></li>\n\t\t</ul>');
});
test('Expand abbreviation with numbered repeaters with offset in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(8, 36, 8, 36), 'ul>li.item$@44*2', '<ul>\n\t<li class="item44"></li>\n\t<li class="item45"></li>\n</ul>');
});
test('Expand abbreviation with numbered repeaters in groups (HTML)', () => {
return testExpandAbbreviation('html', new Selection(17, 16, 17, 16), '(ul>li.item$)*2', '<ul>\n\t\t<li class="item1"></li>\n\t</ul>\n\t<ul>\n\t\t<li class="item2"></li>\n\t</ul>');
});
test('Expand abbreviation with numbered repeaters in groups in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(17, 16, 17, 16), '(ul>li.item$)*2', '<ul>\n\t<li class="item1"></li>\n</ul>\n<ul>\n\t<li class="item2"></li>\n</ul>');
});
test('Expand abbreviation with numbered repeaters in groups with sibling in the end (HTML)', () => {
return testExpandAbbreviation('html', new Selection(18, 21, 18, 21), '(ul>li.item$)*2+span', '<ul>\n\t\t<li class="item1"></li>\n\t</ul>\n\t<ul>\n\t\t<li class="item2"></li>\n\t</ul>\n\t<span></span>');
});
test('Expand abbreviation with numbered repeaters in groups with sibling in the end in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(18, 21, 18, 21), '(ul>li.item$)*2+span', '<ul>\n\t<li class="item1"></li>\n</ul>\n<ul>\n\t<li class="item2"></li>\n</ul>\n<span></span>');
});
test('Expand abbreviation with nested groups (HTML)', () => {
return testExpandAbbreviation('html', new Selection(19, 19, 19, 19), '(div>dl>(dt+dd)*2)', '<div>\n\t\t<dl>\n\t\t\t<dt></dt>\n\t\t\t<dd></dd>\n\t\t\t<dt></dt>\n\t\t\t<dd></dd>\n\t\t</dl>\n\t</div>');
});
test('Expand abbreviation with nested groups in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(19, 19, 19, 19), '(div>dl>(dt+dd)*2)', '<div>\n\t<dl>\n\t\t<dt></dt>\n\t\t<dd></dd>\n\t\t<dt></dt>\n\t\t<dd></dd>\n\t</dl>\n</div>');
});
test('Expand tag that is opened, but not closed (HTML)', () => {
return testExpandAbbreviation('html', new Selection(9, 6, 9, 6), '<div', '<div></div>');
});
test('Do not Expand tag that is opened, but not closed in completion list (HTML)', () => {
return testHtmlCompletionProvider(new Selection(9, 6, 9, 6), '<div', '<div></div>', true);
});
test('No expanding text inside open tag (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(2, 4, 2, 4);
await expandEmmetAbbreviation(null);
assert.strictEqual(editor.document.getText(), htmlContents);
return Promise.resolve();
});
});
test('No expanding text inside open tag in completion list (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', (editor, _doc) => {
editor.selection = new Selection(2, 4, 2, 4);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`);
return Promise.resolve();
});
});
test('No expanding text inside open tag when there is no closing tag (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(9, 8, 9, 8);
await expandEmmetAbbreviation(null);
assert.strictEqual(editor.document.getText(), htmlContents);
return Promise.resolve();
});
});
test('No expanding text inside open tag when there is no closing tag in completion list (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', (editor, _doc) => {
editor.selection = new Selection(9, 8, 9, 8);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`);
return Promise.resolve();
});
});
test('No expanding text inside open tag when there is no closing tag when there is no parent node (HTML)', () => {
const fileContents = '<img s';
return withRandomFileEditor(fileContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(0, 6, 0, 6);
await expandEmmetAbbreviation(null);
assert.strictEqual(editor.document.getText(), fileContents);
return Promise.resolve();
});
});
test('No expanding text in completion list inside open tag when there is no closing tag when there is no parent node (HTML)', () => {
const fileContents = '<img s';
return withRandomFileEditor(fileContents, 'html', (editor, _doc) => {
editor.selection = new Selection(0, 6, 0, 6);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`);
return Promise.resolve();
});
});
test('Expand css when inside style tag (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(13, 16, 13, 19);
const expandPromise = expandEmmetAbbreviation({ language: 'css' });
if (!expandPromise) {
return Promise.resolve();
}
await expandPromise;
assert.strictEqual(editor.document.getText(), htmlContents.replace('m10', 'margin: 10px;'));
return Promise.resolve();
});
});
test('Expand css when inside style tag in completion list (HTML)', () => {
const abbreviation = 'm10';
const expandedText = 'margin: 10px;';
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(13, 16, 13, 19);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
if (!completionPromise) {
assert.strictEqual(1, 2, `Problem with expanding m10`);
return Promise.resolve();
}
const completionList = await completionPromise;
if (!completionList || !completionList.items || !completionList.items.length) {
assert.strictEqual(1, 2, `Problem with expanding m10`);
return Promise.resolve();
}
const emmetCompletionItem = completionList.items[0];
assert.strictEqual(emmetCompletionItem.label, expandedText, `Label of completion item doesnt match.`);
assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`);
assert.strictEqual(emmetCompletionItem.filterText, abbreviation, `FilterText of completion item doesnt match.`);
return Promise.resolve();
});
});
test('No expanding text inside style tag if position is not for property name (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(13, 14, 13, 14);
await expandEmmetAbbreviation(null);
assert.strictEqual(editor.document.getText(), htmlContents);
return Promise.resolve();
});
});
test('Expand css when inside style attribute (HTML)', () => {
const styleAttributeContent = '<div style="m10" class="hello"></div>';
return withRandomFileEditor(styleAttributeContent, 'html', async (editor, _doc) => {
editor.selection = new Selection(0, 15, 0, 15);
const expandPromise = expandEmmetAbbreviation(null);
if (!expandPromise) {
return Promise.resolve();
}
await expandPromise;
assert.strictEqual(editor.document.getText(), styleAttributeContent.replace('m10', 'margin: 10px;'));
return Promise.resolve();
});
});
test('Expand css when inside style attribute in completion list (HTML)', () => {
const abbreviation = 'm10';
const expandedText = 'margin: 10px;';
return withRandomFileEditor('<div style="m10" class="hello"></div>', 'html', async (editor, _doc) => {
editor.selection = new Selection(0, 15, 0, 15);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
if (!completionPromise) {
assert.strictEqual(1, 2, `Problem with expanding m10`);
return Promise.resolve();
}
const completionList = await completionPromise;
if (!completionList || !completionList.items || !completionList.items.length) {
assert.strictEqual(1, 2, `Problem with expanding m10`);
return Promise.resolve();
}
const emmetCompletionItem = completionList.items[0];
assert.strictEqual(emmetCompletionItem.label, expandedText, `Label of completion item doesnt match.`);
assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`);
assert.strictEqual(emmetCompletionItem.filterText, abbreviation, `FilterText of completion item doesnt match.`);
return Promise.resolve();
});
});
test('Expand html when inside script tag with html type (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(21, 12, 21, 12);
const expandPromise = expandEmmetAbbreviation(null);
if (!expandPromise) {
return Promise.resolve();
}
await expandPromise;
assert.strictEqual(editor.document.getText(), htmlContents.replace('span.hello', '<span class="hello"></span>'));
return Promise.resolve();
});
});
test('Expand html in completion list when inside script tag with html type (HTML)', () => {
const abbreviation = 'span.hello';
const expandedText = '<span class="hello"></span>';
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(21, 12, 21, 12);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
if (!completionPromise) {
assert.strictEqual(1, 2, `Problem with expanding span.hello`);
return Promise.resolve();
}
const completionList = await completionPromise;
if (!completionList || !completionList.items || !completionList.items.length) {
assert.strictEqual(1, 2, `Problem with expanding span.hello`);
return Promise.resolve();
}
const emmetCompletionItem = completionList.items[0];
assert.strictEqual(emmetCompletionItem.label, abbreviation, `Label of completion item doesnt match.`);
assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`);
return Promise.resolve();
});
});
test('No expanding text inside script tag with javascript type (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(24, 12, 24, 12);
await expandEmmetAbbreviation(null);
assert.strictEqual(editor.document.getText(), htmlContents);
return Promise.resolve();
});
});
test('No expanding text in completion list inside script tag with javascript type (HTML)', () => {
return withRandomFileEditor(htmlContents, 'html', (editor, _doc) => {
editor.selection = new Selection(24, 12, 24, 12);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`);
return Promise.resolve();
});
});
test('Expand html when inside script tag with javascript type if js is mapped to html (HTML)', async () => {
await workspace.getConfiguration('emmet').update('includeLanguages', { 'javascript': 'html' }, ConfigurationTarget.Global);
await withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(24, 10, 24, 10);
const expandPromise = expandEmmetAbbreviation(null);
if (!expandPromise) {
return Promise.resolve();
}
await expandPromise;
assert.strictEqual(editor.document.getText(), htmlContents.replace('span.bye', '<span class="bye"></span>'));
});
return workspace.getConfiguration('emmet').update('includeLanguages', oldValueForIncludeLanguages || {}, ConfigurationTarget.Global);
});
test('Expand html in completion list when inside script tag with javascript type if js is mapped to html (HTML)', async () => {
const abbreviation = 'span.bye';
const expandedText = '<span class="bye"></span>';
await workspace.getConfiguration('emmet').update('includeLanguages', { 'javascript': 'html' }, ConfigurationTarget.Global);
await withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = new Selection(24, 10, 24, 10);
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
if (!completionPromise) {
assert.strictEqual(1, 2, `Problem with expanding span.bye`);
return Promise.resolve();
}
const completionList = await completionPromise;
if (!completionList || !completionList.items || !completionList.items.length) {
assert.strictEqual(1, 2, `Problem with expanding span.bye`);
return Promise.resolve();
}
const emmetCompletionItem = completionList.items[0];
assert.strictEqual(emmetCompletionItem.label, abbreviation, `Label of completion item (${emmetCompletionItem.label}) doesnt match.`);
assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`);
return Promise.resolve();
});
return workspace.getConfiguration('emmet').update('includeLanguages', oldValueForIncludeLanguages || {}, ConfigurationTarget.Global);
});
// test('No expanding when html is excluded in the settings', () => {
// return workspace.getConfiguration('emmet').update('excludeLanguages', ['html'], ConfigurationTarget.Global).then(() => {
// return testExpandAbbreviation('html', new Selection(9, 6, 9, 6), '', '', true).then(() => {
// return workspace.getConfiguration('emmet').update('excludeLanguages', oldValueForExcludeLanguages ? oldValueForExcludeLanguages.globalValue : undefined, ConfigurationTarget.Global);
// });
// });
// });
test('No expanding when html is excluded in the settings in completion list', async () => {
await workspace.getConfiguration('emmet').update('excludeLanguages', ['html'], ConfigurationTarget.Global);
await testHtmlCompletionProvider(new Selection(9, 6, 9, 6), '', '', true);
return workspace.getConfiguration('emmet').update('excludeLanguages', oldValueForExcludeLanguages ? oldValueForExcludeLanguages.globalValue : undefined, ConfigurationTarget.Global);
});
// test('No expanding when php (mapped syntax) is excluded in the settings', () => {
// return workspace.getConfiguration('emmet').update('excludeLanguages', ['php'], ConfigurationTarget.Global).then(() => {
// return testExpandAbbreviation('php', new Selection(9, 6, 9, 6), '', '', true).then(() => {
// return workspace.getConfiguration('emmet').update('excludeLanguages', oldValueForExcludeLanguages ? oldValueForExcludeLanguages.globalValue : undefined, ConfigurationTarget.Global);
// });
// });
// });
});
suite('Tests for jsx, xml and xsl', () => {
const oldValueForSyntaxProfiles = workspace.getConfiguration('emmet').inspect('syntaxProfiles');
teardown(closeAllEditors);
test('Expand abbreviation with className instead of class in jsx', () => {
return withRandomFileEditor('ul.nav', 'javascriptreact', async (editor, _doc) => {
editor.selection = new Selection(0, 6, 0, 6);
await expandEmmetAbbreviation({ language: 'javascriptreact' });
assert.strictEqual(editor.document.getText(), '<ul className="nav"></ul>');
return Promise.resolve();
});
});
test('Expand abbreviation with self closing tags for jsx', () => {
return withRandomFileEditor('img', 'javascriptreact', async (editor, _doc) => {
editor.selection = new Selection(0, 6, 0, 6);
await expandEmmetAbbreviation({ language: 'javascriptreact' });
assert.strictEqual(editor.document.getText(), '<img src="" alt="" />');
return Promise.resolve();
});
});
test('Expand abbreviation with single quotes for jsx', async () => {
await workspace.getConfiguration('emmet').update('syntaxProfiles', { jsx: { 'attr_quotes': 'single' } }, ConfigurationTarget.Global);
return withRandomFileEditor('img', 'javascriptreact', async (editor, _doc) => {
editor.selection = new Selection(0, 6, 0, 6);
await expandEmmetAbbreviation({ language: 'javascriptreact' });
assert.strictEqual(editor.document.getText(), '<img src=\'\' alt=\'\' />');
return workspace.getConfiguration('emmet').update('syntaxProfiles', oldValueForSyntaxProfiles ? oldValueForSyntaxProfiles.globalValue : undefined, ConfigurationTarget.Global);
});
});
test('Expand abbreviation with self closing tags for xml', () => {
return withRandomFileEditor('img', 'xml', async (editor, _doc) => {
editor.selection = new Selection(0, 6, 0, 6);
await expandEmmetAbbreviation({ language: 'xml' });
assert.strictEqual(editor.document.getText(), '<img src="" alt=""/>');
return Promise.resolve();
});
});
test('Expand abbreviation with no self closing tags for html', () => {
return withRandomFileEditor('img', 'html', async (editor, _doc) => {
editor.selection = new Selection(0, 6, 0, 6);
await expandEmmetAbbreviation({ language: 'html' });
assert.strictEqual(editor.document.getText(), '<img src="" alt="">');
return Promise.resolve();
});
});
test('Expand abbreviation with condition containing less than sign for jsx', () => {
return withRandomFileEditor('if (foo < 10) { span.bar', 'javascriptreact', async (editor, _doc) => {
editor.selection = new Selection(0, 27, 0, 27);
await expandEmmetAbbreviation({ language: 'javascriptreact' });
assert.strictEqual(editor.document.getText(), 'if (foo < 10) { <span className="bar"></span>');
return Promise.resolve();
});
});
test('No expanding text inside open tag in completion list (jsx)', () => {
return testNoCompletion('jsx', htmlContents, new Selection(2, 4, 2, 4));
});
test('No expanding tag that is opened, but not closed in completion list (jsx)', () => {
return testNoCompletion('jsx', htmlContents, new Selection(9, 6, 9, 6));
});
test('No expanding text inside open tag when there is no closing tag in completion list (jsx)', () => {
return testNoCompletion('jsx', htmlContents, new Selection(9, 8, 9, 8));
});
test('No expanding text in completion list inside open tag when there is no closing tag when there is no parent node (jsx)', () => {
return testNoCompletion('jsx', '<img s', new Selection(0, 6, 0, 6));
});
});
function testExpandAbbreviation(syntax: string, selection: Selection, abbreviation: string, expandedText: string, shouldFail?: boolean): Thenable<any> {
return withRandomFileEditor(htmlContents, syntax, async (editor, _doc) => {
editor.selection = selection;
const expandPromise = expandEmmetAbbreviation(null);
if (!expandPromise) {
if (!shouldFail) {
assert.strictEqual(1, 2, `Problem with expanding ${abbreviation} to ${expandedText}`);
}
return Promise.resolve();
}
await expandPromise;
assert.strictEqual(editor.document.getText(), htmlContents.replace(abbreviation, expandedText));
return Promise.resolve();
});
}
function testHtmlCompletionProvider(selection: Selection, abbreviation: string, expandedText: string, shouldFail?: boolean): Thenable<any> {
return withRandomFileEditor(htmlContents, 'html', async (editor, _doc) => {
editor.selection = selection;
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
if (!completionPromise) {
if (!shouldFail) {
assert.strictEqual(1, 2, `Problem with expanding ${abbreviation} to ${expandedText}`);
}
return Promise.resolve();
}
const completionList = await completionPromise;
if (!completionList || !completionList.items || !completionList.items.length) {
if (!shouldFail) {
assert.strictEqual(1, 2, `Problem with expanding ${abbreviation} to ${expandedText}`);
}
return Promise.resolve();
}
const emmetCompletionItem = completionList.items[0];
assert.strictEqual(emmetCompletionItem.label, abbreviation, `Label of completion item doesnt match.`);
assert.strictEqual(((<string>emmetCompletionItem.documentation) || '').replace(/\|/g, ''), expandedText, `Docs of completion item doesnt match.`);
return Promise.resolve();
});
}
function testNoCompletion(syntax: string, fileContents: string, selection: Selection): Thenable<any> {
return withRandomFileEditor(fileContents, syntax, (editor, _doc) => {
editor.selection = selection;
const cancelSrc = new CancellationTokenSource();
const completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext);
assert.strictEqual(!completionPromise, true, `Got unexpected comapletion promise instead of undefined`);
return Promise.resolve();
});
}
| extensions/emmet/src/test/abbreviationAction.test.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017895900236908346,
0.0001744399341987446,
0.00016684182628523558,
0.00017478899098932743,
0.000002288778887304943
] |
{
"id": 1,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_NEXT_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.DownArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusNext();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 198
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices';
import { AbstractResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
import { ILabelService } from 'vs/platform/label/common/label';
import { IFileService } from 'vs/platform/files/common/files';
import { EditorInputCapabilities, Verbosity } from 'vs/workbench/common/editor';
import { DisposableStore } from 'vs/base/common/lifecycle';
suite('ResourceEditorInput', () => {
let disposables: DisposableStore;
let instantiationService: IInstantiationService;
class TestResourceEditorInput extends AbstractResourceEditorInput {
readonly typeId = 'test.typeId';
constructor(
resource: URI,
@ILabelService labelService: ILabelService,
@IFileService fileService: IFileService
) {
super(resource, resource, labelService, fileService);
}
}
setup(() => {
disposables = new DisposableStore();
instantiationService = workbenchInstantiationService(undefined, disposables);
});
teardown(() => {
disposables.dispose();
});
test('basics', async () => {
const resource = URI.from({ scheme: 'testResource', path: 'thePath/of/the/resource.txt' });
const input = instantiationService.createInstance(TestResourceEditorInput, resource);
assert.ok(input.getName().length > 0);
assert.ok(input.getDescription(Verbosity.SHORT)!.length > 0);
assert.ok(input.getDescription(Verbosity.MEDIUM)!.length > 0);
assert.ok(input.getDescription(Verbosity.LONG)!.length > 0);
assert.ok(input.getTitle(Verbosity.SHORT).length > 0);
assert.ok(input.getTitle(Verbosity.MEDIUM).length > 0);
assert.ok(input.getTitle(Verbosity.LONG).length > 0);
assert.strictEqual(input.hasCapability(EditorInputCapabilities.Readonly), false);
assert.strictEqual(input.hasCapability(EditorInputCapabilities.Untitled), true);
});
});
| src/vs/workbench/test/browser/parts/editor/resourceEditorInput.test.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001772328541846946,
0.0001739818399073556,
0.00016909862461034209,
0.00017506054427940398,
0.0000027879473236680496
] |
{
"id": 1,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_NEXT_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.DownArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusNext();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 198
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { once } from 'vs/base/common/functional';
const charTable: { [hex: string]: number } = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
A: 10,
B: 11,
C: 12,
D: 13,
E: 14,
F: 15
};
const decodeData = (str: string) => {
const output = new Uint8ClampedArray(str.length / 2);
for (let i = 0; i < str.length; i += 2) {
output[i >> 1] = (charTable[str[i]] << 4) | (charTable[str[i + 1]] & 0xF);
}
return output;
};
/*
const encodeData = (data: Uint8ClampedArray, length: string) => {
const chars = '0123456789ABCDEF';
let output = '';
for (let i = 0; i < data.length; i++) {
output += chars[data[i] >> 4] + chars[data[i] & 0xf];
}
return output;
};
*/
/**
* Map of minimap scales to prebaked sample data at those scales. We don't
* sample much larger data, because then font family becomes visible, which
* is use-configurable.
*/
export const prebakedMiniMaps: { [scale: number]: () => Uint8ClampedArray } = {
1: once(() =>
decodeData(
'0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792'
)
),
2: once(() =>
decodeData(
'000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126'
)
)
};
| src/vs/editor/browser/viewParts/minimap/minimapPreBaked.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.007473100908100605,
0.0012163810897618532,
0.00016877130838111043,
0.00017453485634177923,
0.0025542965158820152
] |
{
"id": 2,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_PREVIOUS_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.UpArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusPrevious();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 209
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.009308864362537861,
0.0004211236664559692,
0.0001619872491573915,
0.00017080387624446303,
0.0012720009544864297
] |
{
"id": 2,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_PREVIOUS_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.UpArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusPrevious();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 209
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from 'vs/base/browser/browser';
import { IframeUtils } from 'vs/base/browser/iframe';
import * as platform from 'vs/base/common/platform';
export interface IMouseEvent {
readonly browserEvent: MouseEvent;
readonly leftButton: boolean;
readonly middleButton: boolean;
readonly rightButton: boolean;
readonly buttons: number;
readonly target: HTMLElement;
readonly detail: number;
readonly posx: number;
readonly posy: number;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly timestamp: number;
preventDefault(): void;
stopPropagation(): void;
}
export class StandardMouseEvent implements IMouseEvent {
public readonly browserEvent: MouseEvent;
public readonly leftButton: boolean;
public readonly middleButton: boolean;
public readonly rightButton: boolean;
public readonly buttons: number;
public readonly target: HTMLElement;
public detail: number;
public readonly posx: number;
public readonly posy: number;
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
public readonly metaKey: boolean;
public readonly timestamp: number;
constructor(e: MouseEvent) {
this.timestamp = Date.now();
this.browserEvent = e;
this.leftButton = e.button === 0;
this.middleButton = e.button === 1;
this.rightButton = e.button === 2;
this.buttons = e.buttons;
this.target = <HTMLElement>e.target;
this.detail = e.detail || 1;
if (e.type === 'dblclick') {
this.detail = 2;
}
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
if (typeof e.pageX === 'number') {
this.posx = e.pageX;
this.posy = e.pageY;
} else {
// Probably hit by MSGestureEvent
this.posx = e.clientX + document.body.scrollLeft + document.documentElement!.scrollLeft;
this.posy = e.clientY + document.body.scrollTop + document.documentElement!.scrollTop;
}
// Find the position of the iframe this code is executing in relative to the iframe where the event was captured.
const iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(self, e.view);
this.posx -= iframeOffsets.left;
this.posy -= iframeOffsets.top;
}
public preventDefault(): void {
this.browserEvent.preventDefault();
}
public stopPropagation(): void {
this.browserEvent.stopPropagation();
}
}
export class DragMouseEvent extends StandardMouseEvent {
public readonly dataTransfer: DataTransfer;
constructor(e: MouseEvent) {
super(e);
this.dataTransfer = (<any>e).dataTransfer;
}
}
export interface IMouseWheelEvent extends MouseEvent {
readonly wheelDelta: number;
readonly wheelDeltaX: number;
readonly wheelDeltaY: number;
readonly deltaX: number;
readonly deltaY: number;
readonly deltaZ: number;
readonly deltaMode: number;
}
interface IWebKitMouseWheelEvent {
wheelDeltaY: number;
wheelDeltaX: number;
}
interface IGeckoMouseWheelEvent {
HORIZONTAL_AXIS: number;
VERTICAL_AXIS: number;
axis: number;
detail: number;
}
export class StandardWheelEvent {
public readonly browserEvent: IMouseWheelEvent | null;
public readonly deltaY: number;
public readonly deltaX: number;
public readonly target: Node;
constructor(e: IMouseWheelEvent | null, deltaX: number = 0, deltaY: number = 0) {
this.browserEvent = e || null;
this.target = e ? (e.target || (<any>e).targetNode || e.srcElement) : null;
this.deltaY = deltaY;
this.deltaX = deltaX;
if (e) {
// Old (deprecated) wheel events
const e1 = <IWebKitMouseWheelEvent><any>e;
const e2 = <IGeckoMouseWheelEvent><any>e;
// vertical delta scroll
if (typeof e1.wheelDeltaY !== 'undefined') {
this.deltaY = e1.wheelDeltaY / 120;
} else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) {
this.deltaY = -e2.detail / 3;
} else if (e.type === 'wheel') {
// Modern wheel event
// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
const ev = <WheelEvent><unknown>e;
if (ev.deltaMode === ev.DOM_DELTA_LINE) {
// the deltas are expressed in lines
if (browser.isFirefox && !platform.isMacintosh) {
this.deltaY = -e.deltaY / 3;
} else {
this.deltaY = -e.deltaY;
}
} else {
this.deltaY = -e.deltaY / 40;
}
}
// horizontal delta scroll
if (typeof e1.wheelDeltaX !== 'undefined') {
if (browser.isSafari && platform.isWindows) {
this.deltaX = - (e1.wheelDeltaX / 120);
} else {
this.deltaX = e1.wheelDeltaX / 120;
}
} else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) {
this.deltaX = -e.detail / 3;
} else if (e.type === 'wheel') {
// Modern wheel event
// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
const ev = <WheelEvent><unknown>e;
if (ev.deltaMode === ev.DOM_DELTA_LINE) {
// the deltas are expressed in lines
if (browser.isFirefox && !platform.isMacintosh) {
this.deltaX = -e.deltaX / 3;
} else {
this.deltaX = -e.deltaX;
}
} else {
this.deltaX = -e.deltaX / 40;
}
}
// Assume a vertical scroll if nothing else worked
if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {
this.deltaY = e.wheelDelta / 120;
}
}
}
public preventDefault(): void {
this.browserEvent?.preventDefault();
}
public stopPropagation(): void {
this.browserEvent?.stopPropagation();
}
}
| src/vs/base/browser/mouseEvent.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017692842811811715,
0.00017371663125231862,
0.00016180356033146381,
0.00017455282795708627,
0.0000031114445846469607
] |
{
"id": 2,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_PREVIOUS_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.UpArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusPrevious();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 209
} | ## Setup
- Clone [microsoft/vscode](https://github.com/microsoft/vscode)
- Run `yarn` at `/`, this will install
- Dependencies for `/extension/json-language-features/`
- Dependencies for `/extension/json-language-features/server/`
- devDependencies such as `gulp`
- Open `/extensions/json-language-features/` as the workspace in VS Code
- In `/extensions/json-language-features/` run `yarn compile`(or `yarn watch`) to build the client and server
- Run the [`Launch Extension`](https://github.com/microsoft/vscode/blob/master/extensions/json-language-features/.vscode/launch.json) debug target in the Debug View. This will:
- Launch a new VS Code instance with the `json-language-features` extension loaded
- Open a `.json` file to activate the extension. The extension will start the JSON language server process.
- Add `"json.trace.server": "verbose"` to the settings to observe the communication between client and server in the `JSON Language Server` output.
- Debug the extension and the language server client by setting breakpoints in`json-language-features/client/`
- Debug the language server process by using `Attach to Node Process` command in the VS Code window opened on `json-language-features`.
- Pick the process that contains `jsonServerMain` in the command line. Hover over `code-insiders` resp `code` processes to see the full process command line.
- Set breakpoints in `json-language-features/server/`
- Run `Reload Window` command in the launched instance to reload the extension
### Contribute to vscode-json-languageservice
[microsoft/vscode-json-languageservice](https://github.com/microsoft/vscode-json-languageservice) is the library that implements the language smarts for JSON.
The JSON language server forwards most the of requests to the service library.
If you want to fix JSON issues or make improvements, you should make changes at [microsoft/vscode-json-languageservice](https://github.com/microsoft/vscode-json-languageservice).
However, within this extension, you can run a development version of `vscode-json-languageservice` to debug code or test language features interactively:
#### Linking `vscode-json-languageservice` in `json-language-features/server/`
- Clone [microsoft/vscode-json-languageservice](https://github.com/microsoft/vscode-json-languageservice)
- Run `npm install` in `vscode-json-languageservice`
- Run `npm link` in `vscode-json-languageservice`. This will compile and link `vscode-json-languageservice`
- In `json-language-features/server/`, run `yarn link vscode-json-languageservice`
#### Testing the development version of `vscode-json-languageservice`
- Open both `vscode-json-languageservice` and this extension in two windows or with a single window with the[multi-root workspace](https://code.visualstudio.com/docs/editor/multi-root-workspaces) feature.
- Run `yarn watch` at `json-languagefeatures/server/` to recompile this extension with the linked version of `vscode-json-languageservice`
- Make some changes in `vscode-json-languageservice`
- Now when you run `Launch Extension` debug target, the launched instance will use your development version of `vscode-json-languageservice`. You can interactively test the language features.
| extensions/json-language-features/CONTRIBUTING.md | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001731860829750076,
0.000170685671037063,
0.00016884776414372027,
0.0001705423346720636,
0.0000014068065183892031
] |
{
"id": 2,
"code_window": [
"\tKeybindingsRegistry.registerCommandAndKeybindingRule({\n",
"\t\tid: FOCUS_PREVIOUS_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.UpArrow,\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusPrevious();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 209
} | {
"displayName": "GitHub",
"description": "GitHub features for VS Code",
"config.gitAuthentication": "Controls whether to enable automatic GitHub authentication for git commands within VS Code.",
"config.gitProtocol": "Controls which protocol is used to clone a GitHub repository",
"welcome.publishFolder": {
"message": "You can directly publish this folder to a GitHub repository. Once published, you'll have access to source control features powered by git and GitHub.\n[$(github) Publish to GitHub](command:github.publish)",
"comment": [
"{Locked='$(github)'}",
"Do not translate '$(github)'. It will be rendered as an icon",
"{Locked='](command:github.publish'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"welcome.publishWorkspaceFolder": {
"message": "You can directly publish a workspace folder to a GitHub repository. Once published, you'll have access to source control features powered by git and GitHub.\n[$(github) Publish to GitHub](command:github.publish)",
"comment": [
"{Locked='$(github)'}",
"Do not translate '$(github)'. It will be rendered as an icon",
"{Locked='](command:github.publish'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
}
}
| extensions/github/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017054477939382195,
0.00016972579760476947,
0.00016911861894186586,
0.0001695139944786206,
6.011815116835351e-7
] |
{
"id": 3,
"code_window": [
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageUp,\n",
"\t\tsecondary: [KeyCode.Home],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusFirst();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 221
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.005560166668146849,
0.0003162257489748299,
0.00016203268023673445,
0.00017051227041520178,
0.0007775918929837644
] |
{
"id": 3,
"code_window": [
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageUp,\n",
"\t\tsecondary: [KeyCode.Home],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusFirst();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 221
} | {
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out",
"downlevelIteration": true,
"types": [
"node"
]
},
"include": [
"src/**/*",
"../../src/vscode-dts/vscode.d.ts",
"../../src/vscode-dts/vscode.proposed.terminalDataWriteEvent.d.ts",
]
}
| extensions/debug-server-ready/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017509792814962566,
0.00017405915423296392,
0.00017302038031630218,
0.00017405915423296392,
0.0000010387739166617393
] |
{
"id": 3,
"code_window": [
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageUp,\n",
"\t\tsecondary: [KeyCode.Home],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusFirst();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 221
} | {
"originalFileName": "./1.json",
"modifiedFileName": "./2.json",
"diffs": [
{
"originalRange": "[301,301)",
"modifiedRange": "[301,305)",
"innerChanges": [
{
"originalRange": "[301,1 -> 301,1]",
"modifiedRange": "[301,1 -> 305,1]"
}
]
}
]
} | src/vs/editor/test/node/diffing/fixtures/json-brackets/experimental.expected.diff.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017540306726004928,
0.00017506454605609179,
0.00017472601030021906,
0.00017506454605609179,
3.3852847991511226e-7
] |
{
"id": 3,
"code_window": [
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageUp,\n",
"\t\tsecondary: [KeyCode.Home],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusFirst();\n",
"\t\t}\n",
"\t});\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 221
} | {
"name": "swift",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "*"
},
"scripts": {
"update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/swift.tmbundle Syntaxes/Swift.tmLanguage ./syntaxes/swift.tmLanguage.json"
},
"contributes": {
"languages": [
{
"id": "swift",
"aliases": [
"Swift",
"swift"
],
"extensions": [
".swift"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "swift",
"scopeName": "source.swift",
"path": "./syntaxes/swift.tmLanguage.json"
}
],
"snippets": [
{
"language": "swift",
"path": "./snippets/swift.code-snippets"
}
]
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
| extensions/swift/package.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017767057579476386,
0.00017673072579782456,
0.0001757516001816839,
0.00017688912339508533,
7.130884114303626e-7
] |
{
"id": 4,
"code_window": [
"\t\tid: FOCUS_LAST_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageDown,\n",
"\t\tsecondary: [KeyCode.End],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusLast();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 233
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.011098077520728111,
0.000402176461648196,
0.00016096551553346217,
0.00017080533143598586,
0.0014624962350353599
] |
{
"id": 4,
"code_window": [
"\t\tid: FOCUS_LAST_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageDown,\n",
"\t\tsecondary: [KeyCode.End],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusLast();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 233
} | /*---------------------------------------------------------------------------------------------
* 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 { writeUInt16LE } from 'vs/base/common/buffer';
import { CharCode } from 'vs/base/common/charCode';
import { decodeUTF16LE, StringBuilder } from 'vs/editor/common/core/stringBuilder';
suite('decodeUTF16LE', () => {
test('issue #118041: unicode character undo bug 1', () => {
const buff = new Uint8Array(2);
writeUInt16LE(buff, ''.charCodeAt(0), 0);
const actual = decodeUTF16LE(buff, 0, 1);
assert.deepStrictEqual(actual, '');
});
test('issue #118041: unicode character undo bug 2', () => {
const buff = new Uint8Array(4);
writeUInt16LE(buff, 'a'.charCodeAt(0), 0);
writeUInt16LE(buff, 'a'.charCodeAt(1), 2);
const actual = decodeUTF16LE(buff, 0, 2);
assert.deepStrictEqual(actual, 'a');
});
test('issue #118041: unicode character undo bug 3', () => {
const buff = new Uint8Array(6);
writeUInt16LE(buff, 'ab'.charCodeAt(0), 0);
writeUInt16LE(buff, 'ab'.charCodeAt(1), 2);
writeUInt16LE(buff, 'ab'.charCodeAt(2), 4);
const actual = decodeUTF16LE(buff, 0, 3);
assert.deepStrictEqual(actual, 'ab');
});
});
suite('StringBuilder', () => {
test('basic', () => {
const sb = new StringBuilder(100);
sb.appendASCIICharCode(CharCode.A);
sb.appendASCIICharCode(CharCode.Space);
sb.appendString('😊');
assert.strictEqual(sb.build(), 'A 😊');
});
});
| src/vs/editor/test/common/core/stringBuilder.test.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017586827743798494,
0.00017501460388302803,
0.00017350261623505503,
0.00017500127432867885,
8.395134045713348e-7
] |
{
"id": 4,
"code_window": [
"\t\tid: FOCUS_LAST_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageDown,\n",
"\t\tsecondary: [KeyCode.End],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusLast();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 233
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { ILogService } from 'vs/platform/log/common/log';
import { IDisposable, Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { IWorkingCopyFileOperationParticipant, SourceTargetPair, IFileOperationUndoRedoInfo } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
import { FileOperation } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { LinkedList } from 'vs/base/common/linkedList';
export class WorkingCopyFileOperationParticipant extends Disposable {
private readonly participants = new LinkedList<IWorkingCopyFileOperationParticipant>();
constructor(
@ILogService private readonly logService: ILogService,
@IConfigurationService private readonly configurationService: IConfigurationService
) {
super();
}
addFileOperationParticipant(participant: IWorkingCopyFileOperationParticipant): IDisposable {
const remove = this.participants.push(participant);
return toDisposable(() => remove());
}
async participate(files: SourceTargetPair[], operation: FileOperation, undoInfo: IFileOperationUndoRedoInfo | undefined, token: CancellationToken): Promise<void> {
const timeout = this.configurationService.getValue<number>('files.participants.timeout');
if (typeof timeout !== 'number' || timeout <= 0) {
return; // disabled
}
// For each participant
for (const participant of this.participants) {
try {
await participant.participate(files, operation, undoInfo, timeout, token);
} catch (err) {
this.logService.warn(err);
}
}
}
override dispose(): void {
this.participants.clear();
}
}
| src/vs/workbench/services/workingCopy/common/workingCopyFileOperationParticipant.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017763754294719547,
0.00017537851817905903,
0.0001733604003675282,
0.0001752597454469651,
0.0000015615203210472828
] |
{
"id": 4,
"code_window": [
"\t\tid: FOCUS_LAST_NOTIFICATION_TOAST,\n",
"\t\tweight: KeybindingWeight.WorkbenchContrib,\n",
"\t\twhen: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),\n",
"\t\tprimary: KeyCode.PageDown,\n",
"\t\tsecondary: [KeyCode.End],\n",
"\t\thandler: (accessor) => {\n",
"\t\t\ttoasts.focusLast();\n",
"\t\t}\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\thandler: () => {\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsCommands.ts",
"type": "replace",
"edit_start_line_idx": 233
} | {
"originalFileName": "./1.tst",
"modifiedFileName": "./2.tst",
"diffs": [
{
"originalRange": "[3,4)",
"modifiedRange": "[3,4)",
"innerChanges": [
{
"originalRange": "[3,43 -> 3,67]",
"modifiedRange": "[3,43 -> 3,43]"
}
]
},
{
"originalRange": "[7,8)",
"modifiedRange": "[7,8)",
"innerChanges": [
{
"originalRange": "[7,1 -> 7,6]",
"modifiedRange": "[7,1 -> 7,1]"
},
{
"originalRange": "[7,9 -> 7,15]",
"modifiedRange": "[7,4 -> 7,4]"
}
]
},
{
"originalRange": "[9,10)",
"modifiedRange": "[9,10)",
"innerChanges": [
{
"originalRange": "[9,46 -> 9,70]",
"modifiedRange": "[9,46 -> 9,46]"
}
]
}
]
} | src/vs/editor/test/node/diffing/fixtures/ts-fragmented-eager-diffing3/experimental.expected.diff.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017665568157099187,
0.0001751898234942928,
0.00017324999498669058,
0.00017575797392055392,
0.000001276025727747765
] |
{
"id": 5,
"code_window": [
" * Copyright (c) Microsoft Corporation. All rights reserved.\n",
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';\n",
"import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { URI } from 'vs/base/common/uri';\n",
"import { localize } from 'vs/nls';\n",
"import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';\n",
"import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { clearNode, addDisposableListener, EventType, EventHelper, $, isEventLike } from 'vs/base/browser/dom';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0004135509952902794,
0.00018166357767768204,
0.00016397706349380314,
0.00017136879614554346,
0.00004010480552096851
] |
{
"id": 5,
"code_window": [
" * Copyright (c) Microsoft Corporation. All rights reserved.\n",
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';\n",
"import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { URI } from 'vs/base/common/uri';\n",
"import { localize } from 'vs/nls';\n",
"import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';\n",
"import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { clearNode, addDisposableListener, EventType, EventHelper, $, isEventLike } from 'vs/base/browser/dom';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 6
} | {
"originalFileName": "./1.tst",
"modifiedFileName": "./2.tst",
"diffs": [
{
"originalRange": "[24,25)",
"modifiedRange": "[24,24)",
"innerChanges": [
{
"originalRange": "[24,1 -> 25,1]",
"modifiedRange": "[24,1 -> 24,1]"
}
]
},
{
"originalRange": "[32,33)",
"modifiedRange": "[31,32)",
"innerChanges": [
{
"originalRange": "[32,59 -> 32,60]",
"modifiedRange": "[31,59 -> 31,66]"
}
]
},
{
"originalRange": "[39,40)",
"modifiedRange": "[38,38)",
"innerChanges": [
{
"originalRange": "[39,1 -> 40,1]",
"modifiedRange": "[38,1 -> 38,1]"
}
]
},
{
"originalRange": "[69,70)",
"modifiedRange": "[67,67)",
"innerChanges": [
{
"originalRange": "[69,1 -> 70,1]",
"modifiedRange": "[67,1 -> 67,1]"
}
]
},
{
"originalRange": "[84,85)",
"modifiedRange": "[81,83)",
"innerChanges": [
{
"originalRange": "[84,1 -> 84,1]",
"modifiedRange": "[81,1 -> 82,1]"
},
{
"originalRange": "[84,60 -> 84,61]",
"modifiedRange": "[82,60 -> 82,67]"
}
]
},
{
"originalRange": "[95,96)",
"modifiedRange": "[93,95)",
"innerChanges": [
{
"originalRange": "[95,1 -> 95,1]",
"modifiedRange": "[93,1 -> 94,1]"
},
{
"originalRange": "[95,60 -> 95,61]",
"modifiedRange": "[94,60 -> 94,67]"
}
]
},
{
"originalRange": "[105,106)",
"modifiedRange": "[104,106)",
"innerChanges": [
{
"originalRange": "[105,1 -> 105,1]",
"modifiedRange": "[104,1 -> 105,1]"
},
{
"originalRange": "[105,60 -> 105,61]",
"modifiedRange": "[105,60 -> 105,67]"
}
]
}
]
} | src/vs/editor/test/node/diffing/fixtures/ts-fragmented-eager-diffing/experimental.expected.diff.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017489769379608333,
0.00017335389566142112,
0.00017122752615250647,
0.0001733387471176684,
0.0000010515391295484733
] |
{
"id": 5,
"code_window": [
" * Copyright (c) Microsoft Corporation. All rights reserved.\n",
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';\n",
"import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { URI } from 'vs/base/common/uri';\n",
"import { localize } from 'vs/nls';\n",
"import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';\n",
"import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { clearNode, addDisposableListener, EventType, EventHelper, $, isEventLike } from 'vs/base/browser/dom';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* 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: '00000406', id: '', text: 'Danish' },
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_PLUS'],
Equal: ['´', '`', '|', '', 0, 'VK_OEM_4'],
BracketLeft: ['å', 'Å', '', '', 0, 'VK_OEM_6'],
BracketRight: ['¨', '^', '~', '', 0, 'VK_OEM_1'],
Backslash: ['\'', '*', '', '', 0, 'VK_OEM_2'],
Semicolon: ['æ', 'Æ', '', '', 0, 'VK_OEM_3'],
Quote: ['ø', 'Ø', '', '', 0, 'VK_OEM_7'],
Backquote: ['½', '§', '', '', 0, 'VK_OEM_5'],
Comma: [',', ';', '', '', 0, 'VK_OEM_COMMA'],
Period: ['.', ':', '', '', 0, 'VK_OEM_PERIOD'],
Slash: ['-', '_', '', '', 0, 'VK_OEM_MINUS'],
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/dk.win.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017595381359569728,
0.00017339065379928797,
0.00016590410086791962,
0.00017412976012565196,
0.0000024200533061957685
] |
{
"id": 5,
"code_window": [
" * Copyright (c) Microsoft Corporation. All rights reserved.\n",
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';\n",
"import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { URI } from 'vs/base/common/uri';\n",
"import { localize } from 'vs/nls';\n",
"import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';\n",
"import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { clearNode, addDisposableListener, EventType, EventHelper, $, isEventLike } from 'vs/base/browser/dom';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* 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 { Range } from 'vs/editor/common/core/range';
import { Action2, registerAction2 } from 'vs/platform/actions/common/actions';
import { Categories } from 'vs/platform/action/common/actionCommonCategories';
import { ITextMateService } from 'vs/workbench/services/textMate/browser/textMate';
import { IModelService } from 'vs/editor/common/services/model';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { ITextModel } from 'vs/editor/common/model';
import { Constants } from 'vs/base/common/uint';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { ILoggerService } from 'vs/platform/log/common/log';
import { joinPath } from 'vs/base/common/resources';
import { IFileService } from 'vs/platform/files/common/files';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
class StartDebugTextMate extends Action2 {
private static resource = URI.parse(`inmemory:///tm-log.txt`);
constructor() {
super({
id: 'editor.action.startDebugTextMate',
title: { value: nls.localize('startDebugTextMate', "Start Text Mate Syntax Grammar Logging"), original: 'Start Text Mate Syntax Grammar Logging' },
category: Categories.Developer,
f1: true
});
}
private _getOrCreateModel(modelService: IModelService): ITextModel {
const model = modelService.getModel(StartDebugTextMate.resource);
if (model) {
return model;
}
return modelService.createModel('', null, StartDebugTextMate.resource);
}
private _append(model: ITextModel, str: string) {
const lineCount = model.getLineCount();
model.applyEdits([{
range: new Range(lineCount, Constants.MAX_SAFE_SMALL_INTEGER, lineCount, Constants.MAX_SAFE_SMALL_INTEGER),
text: str
}]);
}
async run(accessor: ServicesAccessor) {
const textMateService = accessor.get(ITextMateService);
const modelService = accessor.get(IModelService);
const editorService = accessor.get(IEditorService);
const codeEditorService = accessor.get(ICodeEditorService);
const hostService = accessor.get(IHostService);
const environmentService = accessor.get(INativeWorkbenchEnvironmentService);
const loggerService = accessor.get(ILoggerService);
const fileService = accessor.get(IFileService);
const pathInTemp = joinPath(environmentService.tmpDir, `vcode-tm-log-${generateUuid()}.txt`);
await fileService.createFile(pathInTemp);
const logger = loggerService.createLogger(pathInTemp, { name: 'debug textmate' });
const model = this._getOrCreateModel(modelService);
const append = (str: string) => {
this._append(model, str + '\n');
scrollEditor();
logger.info(str);
logger.flush();
};
await hostService.openWindow([{ fileUri: pathInTemp }], { forceNewWindow: true });
const textEditorPane = await editorService.openEditor({
resource: model.uri,
options: { pinned: true }
});
if (!textEditorPane) {
return;
}
const scrollEditor = () => {
const editors = codeEditorService.listCodeEditors();
for (const editor of editors) {
if (editor.hasModel()) {
if (editor.getModel().uri.toString() === StartDebugTextMate.resource.toString()) {
editor.revealLine(editor.getModel().getLineCount());
}
}
}
};
append(`// Open the file you want to test to the side and watch here`);
append(`// Output mirrored at ${pathInTemp}`);
textMateService.startDebugMode(
(str) => {
this._append(model, str + '\n');
scrollEditor();
logger.info(str);
logger.flush();
},
() => {
}
);
}
}
registerAction2(StartDebugTextMate);
| src/vs/workbench/contrib/codeEditor/electron-sandbox/startDebugTextMate.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017414950707461685,
0.00017002130334731191,
0.00016280282579828054,
0.0001709977659629658,
0.000003219220388928079
] |
{
"id": 6,
"code_window": [
"import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n",
"import { DomEmitter } from 'vs/base/browser/event';\n",
"import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';\n",
"import { Event } from 'vs/base/common/event';\n",
"import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';\n",
"\n",
"export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {\n",
"\n",
"\tprivate static readonly ROW_HEIGHT = 42;\n",
"\tprivate static readonly LINE_HEIGHT = 22;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { KeyCode } from 'vs/base/common/keyCodes';\n",
"import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "add",
"edit_start_line_idx": 28
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { INotificationViewItem, isNotificationViewItem, NotificationsModel } from 'vs/workbench/common/notifications';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { localize } from 'vs/nls';
import { IListService, WorkbenchList } from 'vs/platform/list/browser/listService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NotificationMetrics, NotificationMetricsClassification, notificationToMetrics } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry';
import { NotificationFocusedContext, NotificationsCenterVisibleContext, NotificationsToastsVisibleContext } from 'vs/workbench/common/contextkeys';
import { INotificationService } from 'vs/platform/notification/common/notification';
// Center
export const SHOW_NOTIFICATIONS_CENTER = 'notifications.showList';
export const HIDE_NOTIFICATIONS_CENTER = 'notifications.hideList';
const TOGGLE_NOTIFICATIONS_CENTER = 'notifications.toggleList';
// Toasts
export const HIDE_NOTIFICATION_TOAST = 'notifications.hideToasts';
const FOCUS_NOTIFICATION_TOAST = 'notifications.focusToasts';
const FOCUS_NEXT_NOTIFICATION_TOAST = 'notifications.focusNextToast';
const FOCUS_PREVIOUS_NOTIFICATION_TOAST = 'notifications.focusPreviousToast';
const FOCUS_FIRST_NOTIFICATION_TOAST = 'notifications.focusFirstToast';
const FOCUS_LAST_NOTIFICATION_TOAST = 'notifications.focusLastToast';
// Notification
export const COLLAPSE_NOTIFICATION = 'notification.collapse';
export const EXPAND_NOTIFICATION = 'notification.expand';
const TOGGLE_NOTIFICATION = 'notification.toggle';
export const CLEAR_NOTIFICATION = 'notification.clear';
export const CLEAR_ALL_NOTIFICATIONS = 'notifications.clearAll';
export const TOGGLE_DO_NOT_DISTURB_MODE = 'notifications.toggleDoNotDisturbMode';
export interface INotificationsCenterController {
readonly isVisible: boolean;
show(): void;
hide(): void;
clearAll(): void;
}
export interface INotificationsToastController {
focus(): void;
focusNext(): void;
focusPrevious(): void;
focusFirst(): void;
focusLast(): void;
hide(): void;
}
export function registerNotificationCommands(center: INotificationsCenterController, toasts: INotificationsToastController, model: NotificationsModel): void {
function getNotificationFromContext(listService: IListService, context?: unknown): INotificationViewItem | undefined {
if (isNotificationViewItem(context)) {
return context;
}
const list = listService.lastFocusedList;
if (list instanceof WorkbenchList) {
const focusedElement = list.getFocusedElements()[0];
if (isNotificationViewItem(focusedElement)) {
return focusedElement;
}
}
return undefined;
}
// Show Notifications Cneter
CommandsRegistry.registerCommand(SHOW_NOTIFICATIONS_CENTER, () => {
toasts.hide();
center.show();
});
// Hide Notifications Center
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: HIDE_NOTIFICATIONS_CENTER,
weight: KeybindingWeight.WorkbenchContrib + 50,
when: NotificationsCenterVisibleContext,
primary: KeyCode.Escape,
handler: accessor => {
const telemetryService = accessor.get(ITelemetryService);
for (const notification of model.notifications) {
if (notification.visible) {
telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent));
}
}
center.hide();
}
});
// Toggle Notifications Center
CommandsRegistry.registerCommand(TOGGLE_NOTIFICATIONS_CENTER, accessor => {
if (center.isVisible) {
center.hide();
} else {
toasts.hide();
center.show();
}
});
// Clear Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLEAR_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.Delete,
mac: {
primary: KeyMod.CtrlCmd | KeyCode.Backspace
},
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
if (notification && !notification.hasProgress) {
notification.close();
}
}
});
// Expand Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: EXPAND_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.RightArrow,
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
notification?.expand();
}
});
// Collapse Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: COLLAPSE_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.LeftArrow,
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
notification?.collapse();
}
});
// Toggle Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: TOGGLE_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.Space,
secondary: [KeyCode.Enter],
handler: accessor => {
const notification = getNotificationFromContext(accessor.get(IListService));
notification?.toggle();
}
});
// Hide Toasts
CommandsRegistry.registerCommand(HIDE_NOTIFICATION_TOAST, accessor => {
const telemetryService = accessor.get(ITelemetryService);
for (const notification of model.notifications) {
if (notification.visible) {
telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent));
}
}
toasts.hide();
});
KeybindingsRegistry.registerKeybindingRule({
id: HIDE_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib - 50, // lower when not focused (e.g. let editor suggest win over this command)
when: NotificationsToastsVisibleContext,
primary: KeyCode.Escape
});
KeybindingsRegistry.registerKeybindingRule({
id: HIDE_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib + 100, // higher when focused
when: ContextKeyExpr.and(NotificationsToastsVisibleContext, NotificationFocusedContext),
primary: KeyCode.Escape
});
// Focus Toasts
CommandsRegistry.registerCommand(FOCUS_NOTIFICATION_TOAST, () => toasts.focus());
// Focus Next Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_NEXT_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.DownArrow,
handler: (accessor) => {
toasts.focusNext();
}
});
// Focus Previous Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_PREVIOUS_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.UpArrow,
handler: (accessor) => {
toasts.focusPrevious();
}
});
// Focus First Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_FIRST_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.PageUp,
secondary: [KeyCode.Home],
handler: (accessor) => {
toasts.focusFirst();
}
});
// Focus Last Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_LAST_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.PageDown,
secondary: [KeyCode.End],
handler: (accessor) => {
toasts.focusLast();
}
});
// Clear All Notifications
CommandsRegistry.registerCommand(CLEAR_ALL_NOTIFICATIONS, () => center.clearAll());
// Toggle Do Not Disturb Mode
CommandsRegistry.registerCommand(TOGGLE_DO_NOT_DISTURB_MODE, accessor => {
const notificationService = accessor.get(INotificationService);
notificationService.doNotDisturbMode = !notificationService.doNotDisturbMode;
});
// Commands for Command Palette
const category = { value: localize('notifications', "Notifications"), original: 'Notifications' };
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: SHOW_NOTIFICATIONS_CENTER, title: { value: localize('showNotifications', "Show Notifications"), original: 'Show Notifications' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: HIDE_NOTIFICATIONS_CENTER, title: { value: localize('hideNotifications', "Hide Notifications"), original: 'Hide Notifications' }, category }, when: NotificationsCenterVisibleContext });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: CLEAR_ALL_NOTIFICATIONS, title: { value: localize('clearAllNotifications', "Clear All Notifications"), original: 'Clear All Notifications' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: TOGGLE_DO_NOT_DISTURB_MODE, title: { value: localize('toggleDoNotDisturbMode', "Toggle Do Not Disturb Mode"), original: 'Toggle Do Not Disturb Mode' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: FOCUS_NOTIFICATION_TOAST, title: { value: localize('focusNotificationToasts', "Focus Notification Toast"), original: 'Focus Notification Toast' }, category }, when: NotificationsToastsVisibleContext });
}
| src/vs/workbench/browser/parts/notifications/notificationsCommands.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0012143806088715792,
0.00026310820248909295,
0.0001622113777557388,
0.00016737377154640853,
0.00023441051598638296
] |
{
"id": 6,
"code_window": [
"import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n",
"import { DomEmitter } from 'vs/base/browser/event';\n",
"import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';\n",
"import { Event } from 'vs/base/common/event';\n",
"import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';\n",
"\n",
"export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {\n",
"\n",
"\tprivate static readonly ROW_HEIGHT = 42;\n",
"\tprivate static readonly LINE_HEIGHT = 22;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { KeyCode } from 'vs/base/common/keyCodes';\n",
"import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "add",
"edit_start_line_idx": 28
} | /*---------------------------------------------------------------------------------------------
* 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 { stripComments } from 'vs/base/common/stripComments';
// We use this regular expression quite often to strip comments in JSON files.
suite('Strip Comments', () => {
test('Line comment', () => {
const content: string = [
"{",
" \"prop\": 10 // a comment",
"}",
].join('\n');
const expected = [
"{",
" \"prop\": 10 ",
"}",
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
test('Line comment - EOF', () => {
const content: string = [
"{",
"}",
"// a comment"
].join('\n');
const expected = [
"{",
"}",
""
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
test('Line comment - \\r\\n', () => {
const content: string = [
"{",
" \"prop\": 10 // a comment",
"}",
].join('\r\n');
const expected = [
"{",
" \"prop\": 10 ",
"}",
].join('\r\n');
assert.strictEqual(stripComments(content), expected);
});
test('Line comment - EOF - \\r\\n', () => {
const content: string = [
"{",
"}",
"// a comment"
].join('\r\n');
const expected = [
"{",
"}",
""
].join('\r\n');
assert.strictEqual(stripComments(content), expected);
});
test('Block comment - single line', () => {
const content: string = [
"{",
" /* before */\"prop\": 10/* after */",
"}",
].join('\n');
const expected = [
"{",
" \"prop\": 10",
"}",
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
test('Block comment - multi line', () => {
const content: string = [
"{",
" /**",
" * Some comment",
" */",
" \"prop\": 10",
"}",
].join('\n');
const expected = [
"{",
" ",
" \"prop\": 10",
"}",
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
test('Block comment - shortest match', () => {
const content = "/* abc */ */";
const expected = " */";
assert.strictEqual(stripComments(content), expected);
});
test('No strings - double quote', () => {
const content: string = [
"{",
" \"/* */\": 10",
"}"
].join('\n');
const expected: string = [
"{",
" \"/* */\": 10",
"}"
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
test('No strings - single quote', () => {
const content: string = [
"{",
" '/* */': 10",
"}"
].join('\n');
const expected: string = [
"{",
" '/* */': 10",
"}"
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
test('Trailing comma in object', () => {
const content: string = [
"{",
` "a": 10,`,
"}"
].join('\n');
const expected: string = [
"{",
` "a": 10`,
"}"
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
test('Trailing comma in array', () => {
const content: string = [
`[ "a", "b", "c", ]`
].join('\n');
const expected: string = [
`[ "a", "b", "c" ]`
].join('\n');
assert.strictEqual(stripComments(content), expected);
});
});
| src/vs/base/test/common/stripComments.test.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017449574079364538,
0.00017185838078148663,
0.00016513535229023546,
0.00017259064770769328,
0.000002930930122602149
] |
{
"id": 6,
"code_window": [
"import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n",
"import { DomEmitter } from 'vs/base/browser/event';\n",
"import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';\n",
"import { Event } from 'vs/base/common/event';\n",
"import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';\n",
"\n",
"export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {\n",
"\n",
"\tprivate static readonly ROW_HEIGHT = 42;\n",
"\tprivate static readonly LINE_HEIGHT = 22;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { KeyCode } from 'vs/base/common/keyCodes';\n",
"import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "add",
"edit_start_line_idx": 28
} | {
"compilerOptions": {
"module": "commonjs",
"target": "es2020",
"strict": true,
"noUnusedParameters": false,
"noUnusedLocals": true,
"outDir": "out",
"sourceMap": true,
"declaration": true,
"lib": [
"es2020",
"dom"
]
},
"exclude": [
"node_modules",
"out",
"tools"
]
}
| test/automation/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001741498417686671,
0.00017274128913413733,
0.0001718136772979051,
0.0001722603483358398,
0.0000010125526159754372
] |
{
"id": 6,
"code_window": [
"import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n",
"import { DomEmitter } from 'vs/base/browser/event';\n",
"import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';\n",
"import { Event } from 'vs/base/common/event';\n",
"import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';\n",
"\n",
"export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {\n",
"\n",
"\tprivate static readonly ROW_HEIGHT = 42;\n",
"\tprivate static readonly LINE_HEIGHT = 22;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { KeyCode } from 'vs/base/common/keyCodes';\n",
"import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "add",
"edit_start_line_idx": 28
} | /*---------------------------------------------------------------------------------------------
* 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 'mocha';
import * as vscode from 'vscode';
(vscode.env.uiKind === vscode.UIKind.Web ? suite.skip : suite)('ipynb NotebookSerializer', function () {
test('Can open an ipynb notebook', async () => {
assert.ok(vscode.workspace.workspaceFolders);
const workspace = vscode.workspace.workspaceFolders[0];
const uri = vscode.Uri.joinPath(workspace.uri, 'test.ipynb');
const notebook = await vscode.workspace.openNotebookDocument(uri);
await vscode.window.showNotebookDocument(notebook);
const notebookEditor = vscode.window.activeNotebookEditor;
assert.ok(notebookEditor);
assert.strictEqual(notebookEditor.notebook.cellCount, 2);
assert.strictEqual(notebookEditor.notebook.cellAt(0).kind, vscode.NotebookCellKind.Markup);
assert.strictEqual(notebookEditor.notebook.cellAt(1).kind, vscode.NotebookCellKind.Code);
assert.strictEqual(notebookEditor.notebook.cellAt(1).outputs.length, 1);
});
});
| extensions/vscode-api-tests/src/singlefolder-tests/ipynb.test.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017626446788199246,
0.0001749752409523353,
0.0001730436342768371,
0.00017561759159434587,
0.0000013911416090195416
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\ttitle = localize('executeCommand', \"Click to execute command '{0}'\", node.href.substr('command:'.length));\n",
"\t\t\t\t} else if (!title) {\n",
"\t\t\t\t\ttitle = node.href;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst anchor = $('a', { href: node.href, title: title, }, node.label);\n",
"\n",
"\t\t\t\tif (actionHandler) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tconst anchor = $('a', { href: node.href, title, tabIndex: 0 }, node.label);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.9964882135391235,
0.05430610105395317,
0.00016293374937959015,
0.00017345428932458162,
0.22521765530109406
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\ttitle = localize('executeCommand', \"Click to execute command '{0}'\", node.href.substr('command:'.length));\n",
"\t\t\t\t} else if (!title) {\n",
"\t\t\t\t\ttitle = node.href;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst anchor = $('a', { href: node.href, title: title, }, node.label);\n",
"\n",
"\t\t\t\tif (actionHandler) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tconst anchor = $('a', { href: node.href, title, tabIndex: 0 }, node.label);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type { IExperimentationTelemetry, ExperimentationService as TASClient, IKeyValueStorage } from 'tas-client-umd';
import { TelemetryLevel } from 'vs/platform/telemetry/common/telemetry';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IProductService } from 'vs/platform/product/common/productService';
import { getTelemetryLevel } from 'vs/platform/telemetry/common/telemetryUtils';
import { AssignmentFilterProvider, ASSIGNMENT_REFETCH_INTERVAL, ASSIGNMENT_STORAGE_KEY, IAssignmentService, TargetPopulation } from 'vs/platform/assignment/common/assignment';
class NullAssignmentServiceTelemetry implements IExperimentationTelemetry {
constructor() { }
setSharedProperty(name: string, value: string): void {
// noop due to lack of telemetry service
}
postEvent(eventName: string, props: Map<string, string>): void {
// noop due to lack of telemetry service
}
}
export abstract class BaseAssignmentService implements IAssignmentService {
_serviceBrand: undefined;
protected tasClient: Promise<TASClient> | undefined;
private networkInitialized = false;
private overrideInitDelay: Promise<void>;
protected get experimentsEnabled(): boolean {
return true;
}
constructor(
private readonly getMachineId: () => Promise<string>,
protected readonly configurationService: IConfigurationService,
protected readonly productService: IProductService,
protected telemetry: IExperimentationTelemetry,
private keyValueStorage?: IKeyValueStorage
) {
if (productService.tasConfig && this.experimentsEnabled && getTelemetryLevel(this.configurationService) === TelemetryLevel.USAGE) {
this.tasClient = this.setupTASClient();
}
// For development purposes, configure the delay until tas local tas treatment ovverrides are available
const overrideDelaySetting = this.configurationService.getValue('experiments.overrideDelay');
const overrideDelay = typeof overrideDelaySetting === 'number' ? overrideDelaySetting : 0;
this.overrideInitDelay = new Promise(resolve => setTimeout(resolve, overrideDelay));
}
async getTreatment<T extends string | number | boolean>(name: string): Promise<T | undefined> {
// For development purposes, allow overriding tas assignments to test variants locally.
await this.overrideInitDelay;
const override = this.configurationService.getValue<T>('experiments.override.' + name);
if (override !== undefined) {
return override;
}
if (!this.tasClient) {
return undefined;
}
if (!this.experimentsEnabled) {
return undefined;
}
let result: T | undefined;
const client = await this.tasClient;
// The TAS client is initialized but we need to check if the initial fetch has completed yet
// If it is complete, return a cached value for the treatment
// If not, use the async call with `checkCache: true`. This will allow the module to return a cached value if it is present.
// Otherwise it will await the initial fetch to return the most up to date value.
if (this.networkInitialized) {
result = client.getTreatmentVariable<T>('vscode', name);
} else {
result = await client.getTreatmentVariableAsync<T>('vscode', name, true);
}
result = client.getTreatmentVariable<T>('vscode', name);
return result;
}
private async setupTASClient(): Promise<TASClient> {
const targetPopulation = this.productService.quality === 'stable' ? TargetPopulation.Public : TargetPopulation.Insiders;
const machineId = await this.getMachineId();
const filterProvider = new AssignmentFilterProvider(
this.productService.version,
this.productService.nameLong,
machineId,
targetPopulation
);
const tasConfig = this.productService.tasConfig!;
const tasClient = new (await import('tas-client-umd')).ExperimentationService({
filterProviders: [filterProvider],
telemetry: this.telemetry,
storageKey: ASSIGNMENT_STORAGE_KEY,
keyValueStorage: this.keyValueStorage,
featuresTelemetryPropertyName: tasConfig.featuresTelemetryPropertyName,
assignmentContextTelemetryPropertyName: tasConfig.assignmentContextTelemetryPropertyName,
telemetryEventName: tasConfig.telemetryEventName,
endpoint: tasConfig.endpoint,
refetchInterval: ASSIGNMENT_REFETCH_INTERVAL,
});
await tasClient.initializePromise;
tasClient.initialFetch.then(() => this.networkInitialized = true);
return tasClient;
}
}
export class AssignmentService extends BaseAssignmentService {
constructor(
machineId: string,
configurationService: IConfigurationService,
productService: IProductService) {
super(() => Promise.resolve(machineId), configurationService, productService, new NullAssignmentServiceTelemetry());
}
}
| src/vs/platform/assignment/common/assignmentService.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001747899950714782,
0.00017253738769795746,
0.00016826996579766273,
0.00017370935529470444,
0.0000020647582914534723
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\ttitle = localize('executeCommand', \"Click to execute command '{0}'\", node.href.substr('command:'.length));\n",
"\t\t\t\t} else if (!title) {\n",
"\t\t\t\t\ttitle = node.href;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst anchor = $('a', { href: node.href, title: title, }, node.label);\n",
"\n",
"\t\t\t\tif (actionHandler) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tconst anchor = $('a', { href: node.href, title, tabIndex: 0 }, node.label);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module '@emmetio/css-parser' {
import { BufferStream, Stylesheet } from 'EmmetNode';
import { Stylesheet as FlatStylesheet } from 'EmmetFlatNode';
function parseStylesheet(stream: BufferStream): Stylesheet;
function parseStylesheet(stream: string): FlatStylesheet;
export default parseStylesheet;
}
| extensions/emmet/src/typings/emmetio__css-parser.d.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.000178567148395814,
0.0001765021588653326,
0.00017443718388676643,
0.0001765021588653326,
0.000002064982254523784
] |
{
"id": 7,
"code_window": [
"\t\t\t\t\ttitle = localize('executeCommand', \"Click to execute command '{0}'\", node.href.substr('command:'.length));\n",
"\t\t\t\t} else if (!title) {\n",
"\t\t\t\t\ttitle = node.href;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst anchor = $('a', { href: node.href, title: title, }, node.label);\n",
"\n",
"\t\t\t\tif (actionHandler) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tconst anchor = $('a', { href: node.href, title, tabIndex: 0 }, node.label);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IURLService, IURLHandler, IOpenURLOptions } from 'vs/platform/url/common/url';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IMainProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { URLHandlerChannel } from 'vs/platform/url/common/urlIpc';
import { IOpenerService, IOpener, matchesScheme } from 'vs/platform/opener/common/opener';
import { IProductService } from 'vs/platform/product/common/productService';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeURLService } from 'vs/platform/url/common/urlService';
export interface IRelayOpenURLOptions extends IOpenURLOptions {
openToSide?: boolean;
openExternal?: boolean;
}
export class RelayURLService extends NativeURLService implements IURLHandler, IOpener {
private urlService: IURLService;
constructor(
@IMainProcessService mainProcessService: IMainProcessService,
@IOpenerService openerService: IOpenerService,
@INativeHostService private readonly nativeHostService: INativeHostService,
@IProductService productService: IProductService
) {
super(productService);
this.urlService = ProxyChannel.toService<IURLService>(mainProcessService.getChannel('url'));
mainProcessService.registerChannel('urlHandler', new URLHandlerChannel(this));
openerService.registerOpener(this);
}
override create(options?: Partial<UriComponents>): URI {
const uri = super.create(options);
let query = uri.query;
if (!query) {
query = `windowId=${encodeURIComponent(this.nativeHostService.windowId)}`;
} else {
query += `&windowId=${encodeURIComponent(this.nativeHostService.windowId)}`;
}
return uri.with({ query });
}
override async open(resource: URI | string, options?: IRelayOpenURLOptions): Promise<boolean> {
if (!matchesScheme(resource, this.productService.urlProtocol)) {
return false;
}
if (typeof resource === 'string') {
resource = URI.parse(resource);
}
return await this.urlService.open(resource, options);
}
async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
const result = await super.open(uri, options);
if (result) {
await this.nativeHostService.focusWindow({ force: true /* Application may not be active */ });
}
return result;
}
}
registerSingleton(IURLService, RelayURLService, InstantiationType.Eager);
| src/vs/workbench/services/url/electron-sandbox/urlService.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017480814130976796,
0.00017240270972251892,
0.00016870710533112288,
0.000173847540281713,
0.000002520824409657507
] |
{
"id": 8,
"code_window": [
"\n",
"\t\t\t\tif (actionHandler) {\n",
"\t\t\t\t\tconst onPointer = (e: EventLike) => {\n",
"\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst handleOpen = (e: unknown) => {\n",
"\t\t\t\t\t\tif (isEventLike(e)) {\n",
"\t\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 155
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { INotificationViewItem, isNotificationViewItem, NotificationsModel } from 'vs/workbench/common/notifications';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { localize } from 'vs/nls';
import { IListService, WorkbenchList } from 'vs/platform/list/browser/listService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NotificationMetrics, NotificationMetricsClassification, notificationToMetrics } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry';
import { NotificationFocusedContext, NotificationsCenterVisibleContext, NotificationsToastsVisibleContext } from 'vs/workbench/common/contextkeys';
import { INotificationService } from 'vs/platform/notification/common/notification';
// Center
export const SHOW_NOTIFICATIONS_CENTER = 'notifications.showList';
export const HIDE_NOTIFICATIONS_CENTER = 'notifications.hideList';
const TOGGLE_NOTIFICATIONS_CENTER = 'notifications.toggleList';
// Toasts
export const HIDE_NOTIFICATION_TOAST = 'notifications.hideToasts';
const FOCUS_NOTIFICATION_TOAST = 'notifications.focusToasts';
const FOCUS_NEXT_NOTIFICATION_TOAST = 'notifications.focusNextToast';
const FOCUS_PREVIOUS_NOTIFICATION_TOAST = 'notifications.focusPreviousToast';
const FOCUS_FIRST_NOTIFICATION_TOAST = 'notifications.focusFirstToast';
const FOCUS_LAST_NOTIFICATION_TOAST = 'notifications.focusLastToast';
// Notification
export const COLLAPSE_NOTIFICATION = 'notification.collapse';
export const EXPAND_NOTIFICATION = 'notification.expand';
const TOGGLE_NOTIFICATION = 'notification.toggle';
export const CLEAR_NOTIFICATION = 'notification.clear';
export const CLEAR_ALL_NOTIFICATIONS = 'notifications.clearAll';
export const TOGGLE_DO_NOT_DISTURB_MODE = 'notifications.toggleDoNotDisturbMode';
export interface INotificationsCenterController {
readonly isVisible: boolean;
show(): void;
hide(): void;
clearAll(): void;
}
export interface INotificationsToastController {
focus(): void;
focusNext(): void;
focusPrevious(): void;
focusFirst(): void;
focusLast(): void;
hide(): void;
}
export function registerNotificationCommands(center: INotificationsCenterController, toasts: INotificationsToastController, model: NotificationsModel): void {
function getNotificationFromContext(listService: IListService, context?: unknown): INotificationViewItem | undefined {
if (isNotificationViewItem(context)) {
return context;
}
const list = listService.lastFocusedList;
if (list instanceof WorkbenchList) {
const focusedElement = list.getFocusedElements()[0];
if (isNotificationViewItem(focusedElement)) {
return focusedElement;
}
}
return undefined;
}
// Show Notifications Cneter
CommandsRegistry.registerCommand(SHOW_NOTIFICATIONS_CENTER, () => {
toasts.hide();
center.show();
});
// Hide Notifications Center
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: HIDE_NOTIFICATIONS_CENTER,
weight: KeybindingWeight.WorkbenchContrib + 50,
when: NotificationsCenterVisibleContext,
primary: KeyCode.Escape,
handler: accessor => {
const telemetryService = accessor.get(ITelemetryService);
for (const notification of model.notifications) {
if (notification.visible) {
telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent));
}
}
center.hide();
}
});
// Toggle Notifications Center
CommandsRegistry.registerCommand(TOGGLE_NOTIFICATIONS_CENTER, accessor => {
if (center.isVisible) {
center.hide();
} else {
toasts.hide();
center.show();
}
});
// Clear Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLEAR_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.Delete,
mac: {
primary: KeyMod.CtrlCmd | KeyCode.Backspace
},
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
if (notification && !notification.hasProgress) {
notification.close();
}
}
});
// Expand Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: EXPAND_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.RightArrow,
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
notification?.expand();
}
});
// Collapse Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: COLLAPSE_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.LeftArrow,
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
notification?.collapse();
}
});
// Toggle Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: TOGGLE_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.Space,
secondary: [KeyCode.Enter],
handler: accessor => {
const notification = getNotificationFromContext(accessor.get(IListService));
notification?.toggle();
}
});
// Hide Toasts
CommandsRegistry.registerCommand(HIDE_NOTIFICATION_TOAST, accessor => {
const telemetryService = accessor.get(ITelemetryService);
for (const notification of model.notifications) {
if (notification.visible) {
telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent));
}
}
toasts.hide();
});
KeybindingsRegistry.registerKeybindingRule({
id: HIDE_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib - 50, // lower when not focused (e.g. let editor suggest win over this command)
when: NotificationsToastsVisibleContext,
primary: KeyCode.Escape
});
KeybindingsRegistry.registerKeybindingRule({
id: HIDE_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib + 100, // higher when focused
when: ContextKeyExpr.and(NotificationsToastsVisibleContext, NotificationFocusedContext),
primary: KeyCode.Escape
});
// Focus Toasts
CommandsRegistry.registerCommand(FOCUS_NOTIFICATION_TOAST, () => toasts.focus());
// Focus Next Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_NEXT_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.DownArrow,
handler: (accessor) => {
toasts.focusNext();
}
});
// Focus Previous Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_PREVIOUS_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.UpArrow,
handler: (accessor) => {
toasts.focusPrevious();
}
});
// Focus First Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_FIRST_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.PageUp,
secondary: [KeyCode.Home],
handler: (accessor) => {
toasts.focusFirst();
}
});
// Focus Last Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_LAST_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.PageDown,
secondary: [KeyCode.End],
handler: (accessor) => {
toasts.focusLast();
}
});
// Clear All Notifications
CommandsRegistry.registerCommand(CLEAR_ALL_NOTIFICATIONS, () => center.clearAll());
// Toggle Do Not Disturb Mode
CommandsRegistry.registerCommand(TOGGLE_DO_NOT_DISTURB_MODE, accessor => {
const notificationService = accessor.get(INotificationService);
notificationService.doNotDisturbMode = !notificationService.doNotDisturbMode;
});
// Commands for Command Palette
const category = { value: localize('notifications', "Notifications"), original: 'Notifications' };
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: SHOW_NOTIFICATIONS_CENTER, title: { value: localize('showNotifications', "Show Notifications"), original: 'Show Notifications' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: HIDE_NOTIFICATIONS_CENTER, title: { value: localize('hideNotifications', "Hide Notifications"), original: 'Hide Notifications' }, category }, when: NotificationsCenterVisibleContext });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: CLEAR_ALL_NOTIFICATIONS, title: { value: localize('clearAllNotifications', "Clear All Notifications"), original: 'Clear All Notifications' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: TOGGLE_DO_NOT_DISTURB_MODE, title: { value: localize('toggleDoNotDisturbMode', "Toggle Do Not Disturb Mode"), original: 'Toggle Do Not Disturb Mode' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: FOCUS_NOTIFICATION_TOAST, title: { value: localize('focusNotificationToasts', "Focus Notification Toast"), original: 'Focus Notification Toast' }, category }, when: NotificationsToastsVisibleContext });
}
| src/vs/workbench/browser/parts/notifications/notificationsCommands.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0002772897423710674,
0.00017527287127450109,
0.00016558438073843718,
0.00017147569451481104,
0.000020505838620010763
] |
{
"id": 8,
"code_window": [
"\n",
"\t\t\t\tif (actionHandler) {\n",
"\t\t\t\t\tconst onPointer = (e: EventLike) => {\n",
"\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst handleOpen = (e: unknown) => {\n",
"\t\t\t\t\t\tif (isEventLike(e)) {\n",
"\t\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 155
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IStringDictionary } from 'vs/base/common/collections';
export interface IMergeResult {
local: {
added: IStringDictionary<string>;
updated: IStringDictionary<string>;
removed: string[];
};
remote: {
added: IStringDictionary<string>;
updated: IStringDictionary<string>;
removed: string[];
};
conflicts: string[];
}
export function merge(local: IStringDictionary<string>, remote: IStringDictionary<string> | null, base: IStringDictionary<string> | null): IMergeResult {
const localAdded: IStringDictionary<string> = {};
const localUpdated: IStringDictionary<string> = {};
const localRemoved: Set<string> = new Set<string>();
if (!remote) {
return {
local: { added: localAdded, updated: localUpdated, removed: [...localRemoved.values()] },
remote: { added: local, updated: {}, removed: [] },
conflicts: []
};
}
const localToRemote = compare(local, remote);
if (localToRemote.added.size === 0 && localToRemote.removed.size === 0 && localToRemote.updated.size === 0) {
// No changes found between local and remote.
return {
local: { added: localAdded, updated: localUpdated, removed: [...localRemoved.values()] },
remote: { added: {}, updated: {}, removed: [] },
conflicts: []
};
}
const baseToLocal = compare(base, local);
const baseToRemote = compare(base, remote);
const remoteAdded: IStringDictionary<string> = {};
const remoteUpdated: IStringDictionary<string> = {};
const remoteRemoved: Set<string> = new Set<string>();
const conflicts: Set<string> = new Set<string>();
// Removed snippets in Local
for (const key of baseToLocal.removed.values()) {
// Conflict - Got updated in remote.
if (baseToRemote.updated.has(key)) {
// Add to local
localAdded[key] = remote[key];
}
// Remove it in remote
else {
remoteRemoved.add(key);
}
}
// Removed snippets in Remote
for (const key of baseToRemote.removed.values()) {
if (conflicts.has(key)) {
continue;
}
// Conflict - Got updated in local
if (baseToLocal.updated.has(key)) {
conflicts.add(key);
}
// Also remove in Local
else {
localRemoved.add(key);
}
}
// Updated snippets in Local
for (const key of baseToLocal.updated.values()) {
if (conflicts.has(key)) {
continue;
}
// Got updated in remote
if (baseToRemote.updated.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
conflicts.add(key);
}
} else {
remoteUpdated[key] = local[key];
}
}
// Updated snippets in Remote
for (const key of baseToRemote.updated.values()) {
if (conflicts.has(key)) {
continue;
}
// Got updated in local
if (baseToLocal.updated.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
conflicts.add(key);
}
} else if (local[key] !== undefined) {
localUpdated[key] = remote[key];
}
}
// Added snippets in Local
for (const key of baseToLocal.added.values()) {
if (conflicts.has(key)) {
continue;
}
// Got added in remote
if (baseToRemote.added.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
conflicts.add(key);
}
} else {
remoteAdded[key] = local[key];
}
}
// Added snippets in remote
for (const key of baseToRemote.added.values()) {
if (conflicts.has(key)) {
continue;
}
// Got added in local
if (baseToLocal.added.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
conflicts.add(key);
}
} else {
localAdded[key] = remote[key];
}
}
return {
local: { added: localAdded, removed: [...localRemoved.values()], updated: localUpdated },
remote: { added: remoteAdded, removed: [...remoteRemoved.values()], updated: remoteUpdated },
conflicts: [...conflicts.values()],
};
}
function compare(from: IStringDictionary<string> | null, to: IStringDictionary<string> | null): { added: Set<string>; removed: Set<string>; updated: Set<string> } {
const fromKeys = from ? Object.keys(from) : [];
const toKeys = to ? Object.keys(to) : [];
const added = toKeys.filter(key => fromKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
const removed = fromKeys.filter(key => toKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
const updated: Set<string> = new Set<string>();
for (const key of fromKeys) {
if (removed.has(key)) {
continue;
}
const fromSnippet = from![key]!;
const toSnippet = to![key]!;
if (fromSnippet !== toSnippet) {
updated.add(key);
}
}
return { added, removed, updated };
}
export function areSame(a: IStringDictionary<string>, b: IStringDictionary<string>): boolean {
const { added, removed, updated } = compare(a, b);
return added.size === 0 && removed.size === 0 && updated.size === 0;
}
| src/vs/platform/userDataSync/common/snippetsMerge.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017536693485453725,
0.0001718534913379699,
0.00016886950470507145,
0.00017151329666376114,
0.000001540242351438792
] |
{
"id": 8,
"code_window": [
"\n",
"\t\t\t\tif (actionHandler) {\n",
"\t\t\t\t\tconst onPointer = (e: EventLike) => {\n",
"\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst handleOpen = (e: unknown) => {\n",
"\t\t\t\t\t\tif (isEventLike(e)) {\n",
"\t\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 155
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { getRandomElement } from 'vs/base/common/arrays';
import { CancelablePromise, createCancelablePromise, timeout } from 'vs/base/common/async';
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { memoize } from 'vs/base/common/decorators';
import { CancellationError } from 'vs/base/common/errors';
import { Emitter, Event, EventMultiplexer, Relay } from 'vs/base/common/event';
import { combinedDisposable, DisposableStore, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { revive } from 'vs/base/common/marshalling';
import * as strings from 'vs/base/common/strings';
import { isFunction, isUndefinedOrNull } from 'vs/base/common/types';
/**
* An `IChannel` is an abstraction over a collection of commands.
* You can `call` several commands on a channel, each taking at
* most one single argument. A `call` always returns a promise
* with at most one single return value.
*/
export interface IChannel {
call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T>;
listen<T>(event: string, arg?: any): Event<T>;
}
/**
* An `IServerChannel` is the counter part to `IChannel`,
* on the server-side. You should implement this interface
* if you'd like to handle remote promises or events.
*/
export interface IServerChannel<TContext = string> {
call<T>(ctx: TContext, command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T>;
listen<T>(ctx: TContext, event: string, arg?: any): Event<T>;
}
const enum RequestType {
Promise = 100,
PromiseCancel = 101,
EventListen = 102,
EventDispose = 103
}
function requestTypeToStr(type: RequestType): string {
switch (type) {
case RequestType.Promise:
return 'req';
case RequestType.PromiseCancel:
return 'cancel';
case RequestType.EventListen:
return 'subscribe';
case RequestType.EventDispose:
return 'unsubscribe';
}
}
type IRawPromiseRequest = { type: RequestType.Promise; id: number; channelName: string; name: string; arg: any };
type IRawPromiseCancelRequest = { type: RequestType.PromiseCancel; id: number };
type IRawEventListenRequest = { type: RequestType.EventListen; id: number; channelName: string; name: string; arg: any };
type IRawEventDisposeRequest = { type: RequestType.EventDispose; id: number };
type IRawRequest = IRawPromiseRequest | IRawPromiseCancelRequest | IRawEventListenRequest | IRawEventDisposeRequest;
const enum ResponseType {
Initialize = 200,
PromiseSuccess = 201,
PromiseError = 202,
PromiseErrorObj = 203,
EventFire = 204
}
function responseTypeToStr(type: ResponseType): string {
switch (type) {
case ResponseType.Initialize:
return `init`;
case ResponseType.PromiseSuccess:
return `reply:`;
case ResponseType.PromiseError:
case ResponseType.PromiseErrorObj:
return `replyErr:`;
case ResponseType.EventFire:
return `event:`;
}
}
type IRawInitializeResponse = { type: ResponseType.Initialize };
type IRawPromiseSuccessResponse = { type: ResponseType.PromiseSuccess; id: number; data: any };
type IRawPromiseErrorResponse = { type: ResponseType.PromiseError; id: number; data: { message: string; name: string; stack: string[] | undefined } };
type IRawPromiseErrorObjResponse = { type: ResponseType.PromiseErrorObj; id: number; data: any };
type IRawEventFireResponse = { type: ResponseType.EventFire; id: number; data: any };
type IRawResponse = IRawInitializeResponse | IRawPromiseSuccessResponse | IRawPromiseErrorResponse | IRawPromiseErrorObjResponse | IRawEventFireResponse;
interface IHandler {
(response: IRawResponse): void;
}
export interface IMessagePassingProtocol {
send(buffer: VSBuffer): void;
onMessage: Event<VSBuffer>;
/**
* Wait for the write buffer (if applicable) to become empty.
*/
drain?(): Promise<void>;
}
enum State {
Uninitialized,
Idle
}
/**
* An `IChannelServer` hosts a collection of channels. You are
* able to register channels onto it, provided a channel name.
*/
export interface IChannelServer<TContext = string> {
registerChannel(channelName: string, channel: IServerChannel<TContext>): void;
}
/**
* An `IChannelClient` has access to a collection of channels. You
* are able to get those channels, given their channel name.
*/
export interface IChannelClient {
getChannel<T extends IChannel>(channelName: string): T;
}
export interface Client<TContext> {
readonly ctx: TContext;
}
export interface IConnectionHub<TContext> {
readonly connections: Connection<TContext>[];
readonly onDidAddConnection: Event<Connection<TContext>>;
readonly onDidRemoveConnection: Event<Connection<TContext>>;
}
/**
* An `IClientRouter` is responsible for routing calls to specific
* channels, in scenarios in which there are multiple possible
* channels (each from a separate client) to pick from.
*/
export interface IClientRouter<TContext = string> {
routeCall(hub: IConnectionHub<TContext>, command: string, arg?: any, cancellationToken?: CancellationToken): Promise<Client<TContext>>;
routeEvent(hub: IConnectionHub<TContext>, event: string, arg?: any): Promise<Client<TContext>>;
}
/**
* Similar to the `IChannelClient`, you can get channels from this
* collection of channels. The difference being that in the
* `IRoutingChannelClient`, there are multiple clients providing
* the same channel. You'll need to pass in an `IClientRouter` in
* order to pick the right one.
*/
export interface IRoutingChannelClient<TContext = string> {
getChannel<T extends IChannel>(channelName: string, router?: IClientRouter<TContext>): T;
}
interface IReader {
read(bytes: number): VSBuffer;
}
interface IWriter {
write(buffer: VSBuffer): void;
}
/**
* @see https://en.wikipedia.org/wiki/Variable-length_quantity
*/
function readIntVQL(reader: IReader) {
let value = 0;
for (let n = 0; ; n += 7) {
const next = reader.read(1);
value |= (next.buffer[0] & 0b01111111) << n;
if (!(next.buffer[0] & 0b10000000)) {
return value;
}
}
}
const vqlZero = createOneByteBuffer(0);
/**
* @see https://en.wikipedia.org/wiki/Variable-length_quantity
*/
function writeInt32VQL(writer: IWriter, value: number) {
if (value === 0) {
writer.write(vqlZero);
return;
}
let len = 0;
for (let v2 = value; v2 !== 0; v2 = v2 >>> 7) {
len++;
}
const scratch = VSBuffer.alloc(len);
for (let i = 0; value !== 0; i++) {
scratch.buffer[i] = value & 0b01111111;
value = value >>> 7;
if (value > 0) {
scratch.buffer[i] |= 0b10000000;
}
}
writer.write(scratch);
}
export class BufferReader implements IReader {
private pos = 0;
constructor(private buffer: VSBuffer) { }
read(bytes: number): VSBuffer {
const result = this.buffer.slice(this.pos, this.pos + bytes);
this.pos += result.byteLength;
return result;
}
}
export class BufferWriter implements IWriter {
private buffers: VSBuffer[] = [];
get buffer(): VSBuffer {
return VSBuffer.concat(this.buffers);
}
write(buffer: VSBuffer): void {
this.buffers.push(buffer);
}
}
enum DataType {
Undefined = 0,
String = 1,
Buffer = 2,
VSBuffer = 3,
Array = 4,
Object = 5,
Int = 6
}
function createOneByteBuffer(value: number): VSBuffer {
const result = VSBuffer.alloc(1);
result.writeUInt8(value, 0);
return result;
}
const BufferPresets = {
Undefined: createOneByteBuffer(DataType.Undefined),
String: createOneByteBuffer(DataType.String),
Buffer: createOneByteBuffer(DataType.Buffer),
VSBuffer: createOneByteBuffer(DataType.VSBuffer),
Array: createOneByteBuffer(DataType.Array),
Object: createOneByteBuffer(DataType.Object),
Uint: createOneByteBuffer(DataType.Int),
};
declare const Buffer: any;
const hasBuffer = (typeof Buffer !== 'undefined');
export function serialize(writer: IWriter, data: any): void {
if (typeof data === 'undefined') {
writer.write(BufferPresets.Undefined);
} else if (typeof data === 'string') {
const buffer = VSBuffer.fromString(data);
writer.write(BufferPresets.String);
writeInt32VQL(writer, buffer.byteLength);
writer.write(buffer);
} else if (hasBuffer && Buffer.isBuffer(data)) {
const buffer = VSBuffer.wrap(data);
writer.write(BufferPresets.Buffer);
writeInt32VQL(writer, buffer.byteLength);
writer.write(buffer);
} else if (data instanceof VSBuffer) {
writer.write(BufferPresets.VSBuffer);
writeInt32VQL(writer, data.byteLength);
writer.write(data);
} else if (Array.isArray(data)) {
writer.write(BufferPresets.Array);
writeInt32VQL(writer, data.length);
for (const el of data) {
serialize(writer, el);
}
} else if (typeof data === 'number' && (data | 0) === data) {
// write a vql if it's a number that we can do bitwise operations on
writer.write(BufferPresets.Uint);
writeInt32VQL(writer, data);
} else {
const buffer = VSBuffer.fromString(JSON.stringify(data));
writer.write(BufferPresets.Object);
writeInt32VQL(writer, buffer.byteLength);
writer.write(buffer);
}
}
export function deserialize(reader: IReader): any {
const type = reader.read(1).readUInt8(0);
switch (type) {
case DataType.Undefined: return undefined;
case DataType.String: return reader.read(readIntVQL(reader)).toString();
case DataType.Buffer: return reader.read(readIntVQL(reader)).buffer;
case DataType.VSBuffer: return reader.read(readIntVQL(reader));
case DataType.Array: {
const length = readIntVQL(reader);
const result: any[] = [];
for (let i = 0; i < length; i++) {
result.push(deserialize(reader));
}
return result;
}
case DataType.Object: return JSON.parse(reader.read(readIntVQL(reader)).toString());
case DataType.Int: return readIntVQL(reader);
}
}
interface PendingRequest {
request: IRawPromiseRequest | IRawEventListenRequest;
timeoutTimer: any;
}
export class ChannelServer<TContext = string> implements IChannelServer<TContext>, IDisposable {
private channels = new Map<string, IServerChannel<TContext>>();
private activeRequests = new Map<number, IDisposable>();
private protocolListener: IDisposable | null;
// Requests might come in for channels which are not yet registered.
// They will timeout after `timeoutDelay`.
private pendingRequests = new Map<string, PendingRequest[]>();
constructor(private protocol: IMessagePassingProtocol, private ctx: TContext, private logger: IIPCLogger | null = null, private timeoutDelay: number = 1000) {
this.protocolListener = this.protocol.onMessage(msg => this.onRawMessage(msg));
this.sendResponse({ type: ResponseType.Initialize });
}
registerChannel(channelName: string, channel: IServerChannel<TContext>): void {
this.channels.set(channelName, channel);
// https://github.com/microsoft/vscode/issues/72531
setTimeout(() => this.flushPendingRequests(channelName), 0);
}
private sendResponse(response: IRawResponse): void {
switch (response.type) {
case ResponseType.Initialize: {
const msgLength = this.send([response.type]);
this.logger?.logOutgoing(msgLength, 0, RequestInitiator.OtherSide, responseTypeToStr(response.type));
return;
}
case ResponseType.PromiseSuccess:
case ResponseType.PromiseError:
case ResponseType.EventFire:
case ResponseType.PromiseErrorObj: {
const msgLength = this.send([response.type, response.id], response.data);
this.logger?.logOutgoing(msgLength, response.id, RequestInitiator.OtherSide, responseTypeToStr(response.type), response.data);
return;
}
}
}
private send(header: any, body: any = undefined): number {
const writer = new BufferWriter();
serialize(writer, header);
serialize(writer, body);
return this.sendBuffer(writer.buffer);
}
private sendBuffer(message: VSBuffer): number {
try {
this.protocol.send(message);
return message.byteLength;
} catch (err) {
// noop
return 0;
}
}
private onRawMessage(message: VSBuffer): void {
const reader = new BufferReader(message);
const header = deserialize(reader);
const body = deserialize(reader);
const type = header[0] as RequestType;
switch (type) {
case RequestType.Promise:
this.logger?.logIncoming(message.byteLength, header[1], RequestInitiator.OtherSide, `${requestTypeToStr(type)}: ${header[2]}.${header[3]}`, body);
return this.onPromise({ type, id: header[1], channelName: header[2], name: header[3], arg: body });
case RequestType.EventListen:
this.logger?.logIncoming(message.byteLength, header[1], RequestInitiator.OtherSide, `${requestTypeToStr(type)}: ${header[2]}.${header[3]}`, body);
return this.onEventListen({ type, id: header[1], channelName: header[2], name: header[3], arg: body });
case RequestType.PromiseCancel:
this.logger?.logIncoming(message.byteLength, header[1], RequestInitiator.OtherSide, `${requestTypeToStr(type)}`);
return this.disposeActiveRequest({ type, id: header[1] });
case RequestType.EventDispose:
this.logger?.logIncoming(message.byteLength, header[1], RequestInitiator.OtherSide, `${requestTypeToStr(type)}`);
return this.disposeActiveRequest({ type, id: header[1] });
}
}
private onPromise(request: IRawPromiseRequest): void {
const channel = this.channels.get(request.channelName);
if (!channel) {
this.collectPendingRequest(request);
return;
}
const cancellationTokenSource = new CancellationTokenSource();
let promise: Promise<any>;
try {
promise = channel.call(this.ctx, request.name, request.arg, cancellationTokenSource.token);
} catch (err) {
promise = Promise.reject(err);
}
const id = request.id;
promise.then(data => {
this.sendResponse(<IRawResponse>{ id, data, type: ResponseType.PromiseSuccess });
this.activeRequests.delete(request.id);
}, err => {
if (err instanceof Error) {
this.sendResponse(<IRawResponse>{
id, data: {
message: err.message,
name: err.name,
stack: err.stack ? (err.stack.split ? err.stack.split('\n') : err.stack) : undefined
}, type: ResponseType.PromiseError
});
} else {
this.sendResponse(<IRawResponse>{ id, data: err, type: ResponseType.PromiseErrorObj });
}
this.activeRequests.delete(request.id);
});
const disposable = toDisposable(() => cancellationTokenSource.cancel());
this.activeRequests.set(request.id, disposable);
}
private onEventListen(request: IRawEventListenRequest): void {
const channel = this.channels.get(request.channelName);
if (!channel) {
this.collectPendingRequest(request);
return;
}
const id = request.id;
const event = channel.listen(this.ctx, request.name, request.arg);
const disposable = event(data => this.sendResponse(<IRawResponse>{ id, data, type: ResponseType.EventFire }));
this.activeRequests.set(request.id, disposable);
}
private disposeActiveRequest(request: IRawRequest): void {
const disposable = this.activeRequests.get(request.id);
if (disposable) {
disposable.dispose();
this.activeRequests.delete(request.id);
}
}
private collectPendingRequest(request: IRawPromiseRequest | IRawEventListenRequest): void {
let pendingRequests = this.pendingRequests.get(request.channelName);
if (!pendingRequests) {
pendingRequests = [];
this.pendingRequests.set(request.channelName, pendingRequests);
}
const timer = setTimeout(() => {
console.error(`Unknown channel: ${request.channelName}`);
if (request.type === RequestType.Promise) {
this.sendResponse(<IRawResponse>{
id: request.id,
data: { name: 'Unknown channel', message: `Channel name '${request.channelName}' timed out after ${this.timeoutDelay}ms`, stack: undefined },
type: ResponseType.PromiseError
});
}
}, this.timeoutDelay);
pendingRequests.push({ request, timeoutTimer: timer });
}
private flushPendingRequests(channelName: string): void {
const requests = this.pendingRequests.get(channelName);
if (requests) {
for (const request of requests) {
clearTimeout(request.timeoutTimer);
switch (request.request.type) {
case RequestType.Promise: this.onPromise(request.request); break;
case RequestType.EventListen: this.onEventListen(request.request); break;
}
}
this.pendingRequests.delete(channelName);
}
}
public dispose(): void {
if (this.protocolListener) {
this.protocolListener.dispose();
this.protocolListener = null;
}
dispose(this.activeRequests.values());
this.activeRequests.clear();
}
}
export const enum RequestInitiator {
LocalSide = 0,
OtherSide = 1
}
export interface IIPCLogger {
logIncoming(msgLength: number, requestId: number, initiator: RequestInitiator, str: string, data?: any): void;
logOutgoing(msgLength: number, requestId: number, initiator: RequestInitiator, str: string, data?: any): void;
}
export class ChannelClient implements IChannelClient, IDisposable {
private isDisposed: boolean = false;
private state: State = State.Uninitialized;
private activeRequests = new Set<IDisposable>();
private handlers = new Map<number, IHandler>();
private lastRequestId: number = 0;
private protocolListener: IDisposable | null;
private logger: IIPCLogger | null;
private readonly _onDidInitialize = new Emitter<void>();
readonly onDidInitialize = this._onDidInitialize.event;
constructor(private protocol: IMessagePassingProtocol, logger: IIPCLogger | null = null) {
this.protocolListener = this.protocol.onMessage(msg => this.onBuffer(msg));
this.logger = logger;
}
getChannel<T extends IChannel>(channelName: string): T {
const that = this;
return {
call(command: string, arg?: any, cancellationToken?: CancellationToken) {
if (that.isDisposed) {
return Promise.reject(new CancellationError());
}
return that.requestPromise(channelName, command, arg, cancellationToken);
},
listen(event: string, arg: any) {
if (that.isDisposed) {
return Event.None;
}
return that.requestEvent(channelName, event, arg);
}
} as T;
}
private requestPromise(channelName: string, name: string, arg?: any, cancellationToken = CancellationToken.None): Promise<any> {
const id = this.lastRequestId++;
const type = RequestType.Promise;
const request: IRawRequest = { id, type, channelName, name, arg };
if (cancellationToken.isCancellationRequested) {
return Promise.reject(new CancellationError());
}
let disposable: IDisposable;
const result = new Promise((c, e) => {
if (cancellationToken.isCancellationRequested) {
return e(new CancellationError());
}
const doRequest = () => {
const handler: IHandler = response => {
switch (response.type) {
case ResponseType.PromiseSuccess:
this.handlers.delete(id);
c(response.data);
break;
case ResponseType.PromiseError: {
this.handlers.delete(id);
const error = new Error(response.data.message);
(<any>error).stack = Array.isArray(response.data.stack) ? response.data.stack.join('\n') : response.data.stack;
error.name = response.data.name;
e(error);
break;
}
case ResponseType.PromiseErrorObj:
this.handlers.delete(id);
e(response.data);
break;
}
};
this.handlers.set(id, handler);
this.sendRequest(request);
};
let uninitializedPromise: CancelablePromise<void> | null = null;
if (this.state === State.Idle) {
doRequest();
} else {
uninitializedPromise = createCancelablePromise(_ => this.whenInitialized());
uninitializedPromise.then(() => {
uninitializedPromise = null;
doRequest();
});
}
const cancel = () => {
if (uninitializedPromise) {
uninitializedPromise.cancel();
uninitializedPromise = null;
} else {
this.sendRequest({ id, type: RequestType.PromiseCancel });
}
e(new CancellationError());
};
const cancellationTokenListener = cancellationToken.onCancellationRequested(cancel);
disposable = combinedDisposable(toDisposable(cancel), cancellationTokenListener);
this.activeRequests.add(disposable);
});
return result.finally(() => { this.activeRequests.delete(disposable); });
}
private requestEvent(channelName: string, name: string, arg?: any): Event<any> {
const id = this.lastRequestId++;
const type = RequestType.EventListen;
const request: IRawRequest = { id, type, channelName, name, arg };
let uninitializedPromise: CancelablePromise<void> | null = null;
const emitter = new Emitter<any>({
onWillAddFirstListener: () => {
uninitializedPromise = createCancelablePromise(_ => this.whenInitialized());
uninitializedPromise.then(() => {
uninitializedPromise = null;
this.activeRequests.add(emitter);
this.sendRequest(request);
});
},
onDidRemoveLastListener: () => {
if (uninitializedPromise) {
uninitializedPromise.cancel();
uninitializedPromise = null;
} else {
this.activeRequests.delete(emitter);
this.sendRequest({ id, type: RequestType.EventDispose });
}
}
});
const handler: IHandler = (res: IRawResponse) => emitter.fire((res as IRawEventFireResponse).data);
this.handlers.set(id, handler);
return emitter.event;
}
private sendRequest(request: IRawRequest): void {
switch (request.type) {
case RequestType.Promise:
case RequestType.EventListen: {
const msgLength = this.send([request.type, request.id, request.channelName, request.name], request.arg);
this.logger?.logOutgoing(msgLength, request.id, RequestInitiator.LocalSide, `${requestTypeToStr(request.type)}: ${request.channelName}.${request.name}`, request.arg);
return;
}
case RequestType.PromiseCancel:
case RequestType.EventDispose: {
const msgLength = this.send([request.type, request.id]);
this.logger?.logOutgoing(msgLength, request.id, RequestInitiator.LocalSide, requestTypeToStr(request.type));
return;
}
}
}
private send(header: any, body: any = undefined): number {
const writer = new BufferWriter();
serialize(writer, header);
serialize(writer, body);
return this.sendBuffer(writer.buffer);
}
private sendBuffer(message: VSBuffer): number {
try {
this.protocol.send(message);
return message.byteLength;
} catch (err) {
// noop
return 0;
}
}
private onBuffer(message: VSBuffer): void {
const reader = new BufferReader(message);
const header = deserialize(reader);
const body = deserialize(reader);
const type: ResponseType = header[0];
switch (type) {
case ResponseType.Initialize:
this.logger?.logIncoming(message.byteLength, 0, RequestInitiator.LocalSide, responseTypeToStr(type));
return this.onResponse({ type: header[0] });
case ResponseType.PromiseSuccess:
case ResponseType.PromiseError:
case ResponseType.EventFire:
case ResponseType.PromiseErrorObj:
this.logger?.logIncoming(message.byteLength, header[1], RequestInitiator.LocalSide, responseTypeToStr(type), body);
return this.onResponse({ type: header[0], id: header[1], data: body });
}
}
private onResponse(response: IRawResponse): void {
if (response.type === ResponseType.Initialize) {
this.state = State.Idle;
this._onDidInitialize.fire();
return;
}
const handler = this.handlers.get(response.id);
handler?.(response);
}
@memoize
get onDidInitializePromise(): Promise<void> {
return Event.toPromise(this.onDidInitialize);
}
private whenInitialized(): Promise<void> {
if (this.state === State.Idle) {
return Promise.resolve();
} else {
return this.onDidInitializePromise;
}
}
dispose(): void {
this.isDisposed = true;
if (this.protocolListener) {
this.protocolListener.dispose();
this.protocolListener = null;
}
dispose(this.activeRequests.values());
this.activeRequests.clear();
}
}
export interface ClientConnectionEvent {
protocol: IMessagePassingProtocol;
onDidClientDisconnect: Event<void>;
}
interface Connection<TContext> extends Client<TContext> {
readonly channelServer: ChannelServer<TContext>;
readonly channelClient: ChannelClient;
}
/**
* An `IPCServer` is both a channel server and a routing channel
* client.
*
* As the owner of a protocol, you should extend both this
* and the `IPCClient` classes to get IPC implementations
* for your protocol.
*/
export class IPCServer<TContext = string> implements IChannelServer<TContext>, IRoutingChannelClient<TContext>, IConnectionHub<TContext>, IDisposable {
private channels = new Map<string, IServerChannel<TContext>>();
private _connections = new Set<Connection<TContext>>();
private readonly _onDidAddConnection = new Emitter<Connection<TContext>>();
readonly onDidAddConnection: Event<Connection<TContext>> = this._onDidAddConnection.event;
private readonly _onDidRemoveConnection = new Emitter<Connection<TContext>>();
readonly onDidRemoveConnection: Event<Connection<TContext>> = this._onDidRemoveConnection.event;
get connections(): Connection<TContext>[] {
const result: Connection<TContext>[] = [];
this._connections.forEach(ctx => result.push(ctx));
return result;
}
constructor(onDidClientConnect: Event<ClientConnectionEvent>) {
onDidClientConnect(({ protocol, onDidClientDisconnect }) => {
const onFirstMessage = Event.once(protocol.onMessage);
onFirstMessage(msg => {
const reader = new BufferReader(msg);
const ctx = deserialize(reader) as TContext;
const channelServer = new ChannelServer(protocol, ctx);
const channelClient = new ChannelClient(protocol);
this.channels.forEach((channel, name) => channelServer.registerChannel(name, channel));
const connection: Connection<TContext> = { channelServer, channelClient, ctx };
this._connections.add(connection);
this._onDidAddConnection.fire(connection);
onDidClientDisconnect(() => {
channelServer.dispose();
channelClient.dispose();
this._connections.delete(connection);
this._onDidRemoveConnection.fire(connection);
});
});
});
}
/**
* Get a channel from a remote client. When passed a router,
* one can specify which client it wants to call and listen to/from.
* Otherwise, when calling without a router, a random client will
* be selected and when listening without a router, every client
* will be listened to.
*/
getChannel<T extends IChannel>(channelName: string, router: IClientRouter<TContext>): T;
getChannel<T extends IChannel>(channelName: string, clientFilter: (client: Client<TContext>) => boolean): T;
getChannel<T extends IChannel>(channelName: string, routerOrClientFilter: IClientRouter<TContext> | ((client: Client<TContext>) => boolean)): T {
const that = this;
return {
call(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
let connectionPromise: Promise<Client<TContext>>;
if (isFunction(routerOrClientFilter)) {
// when no router is provided, we go random client picking
const connection = getRandomElement(that.connections.filter(routerOrClientFilter));
connectionPromise = connection
// if we found a client, let's call on it
? Promise.resolve(connection)
// else, let's wait for a client to come along
: Event.toPromise(Event.filter(that.onDidAddConnection, routerOrClientFilter));
} else {
connectionPromise = routerOrClientFilter.routeCall(that, command, arg);
}
const channelPromise = connectionPromise
.then(connection => (connection as Connection<TContext>).channelClient.getChannel(channelName));
return getDelayedChannel(channelPromise)
.call(command, arg, cancellationToken);
},
listen(event: string, arg: any): Event<T> {
if (isFunction(routerOrClientFilter)) {
return that.getMulticastEvent(channelName, routerOrClientFilter, event, arg);
}
const channelPromise = routerOrClientFilter.routeEvent(that, event, arg)
.then(connection => (connection as Connection<TContext>).channelClient.getChannel(channelName));
return getDelayedChannel(channelPromise)
.listen(event, arg);
}
} as T;
}
private getMulticastEvent<T extends IChannel>(channelName: string, clientFilter: (client: Client<TContext>) => boolean, eventName: string, arg: any): Event<T> {
const that = this;
let disposables = new DisposableStore();
// Create an emitter which hooks up to all clients
// as soon as first listener is added. It also
// disconnects from all clients as soon as the last listener
// is removed.
const emitter = new Emitter<T>({
onWillAddFirstListener: () => {
disposables = new DisposableStore();
// The event multiplexer is useful since the active
// client list is dynamic. We need to hook up and disconnection
// to/from clients as they come and go.
const eventMultiplexer = new EventMultiplexer<T>();
const map = new Map<Connection<TContext>, IDisposable>();
const onDidAddConnection = (connection: Connection<TContext>) => {
const channel = connection.channelClient.getChannel(channelName);
const event = channel.listen<T>(eventName, arg);
const disposable = eventMultiplexer.add(event);
map.set(connection, disposable);
};
const onDidRemoveConnection = (connection: Connection<TContext>) => {
const disposable = map.get(connection);
if (!disposable) {
return;
}
disposable.dispose();
map.delete(connection);
};
that.connections.filter(clientFilter).forEach(onDidAddConnection);
Event.filter(that.onDidAddConnection, clientFilter)(onDidAddConnection, undefined, disposables);
that.onDidRemoveConnection(onDidRemoveConnection, undefined, disposables);
eventMultiplexer.event(emitter.fire, emitter, disposables);
disposables.add(eventMultiplexer);
},
onDidRemoveLastListener: () => {
disposables.dispose();
}
});
return emitter.event;
}
registerChannel(channelName: string, channel: IServerChannel<TContext>): void {
this.channels.set(channelName, channel);
this._connections.forEach(connection => {
connection.channelServer.registerChannel(channelName, channel);
});
}
dispose(): void {
this.channels.clear();
this._connections.clear();
this._onDidAddConnection.dispose();
this._onDidRemoveConnection.dispose();
}
}
/**
* An `IPCClient` is both a channel client and a channel server.
*
* As the owner of a protocol, you should extend both this
* and the `IPCClient` classes to get IPC implementations
* for your protocol.
*/
export class IPCClient<TContext = string> implements IChannelClient, IChannelServer<TContext>, IDisposable {
private channelClient: ChannelClient;
private channelServer: ChannelServer<TContext>;
constructor(protocol: IMessagePassingProtocol, ctx: TContext, ipcLogger: IIPCLogger | null = null) {
const writer = new BufferWriter();
serialize(writer, ctx);
protocol.send(writer.buffer);
this.channelClient = new ChannelClient(protocol, ipcLogger);
this.channelServer = new ChannelServer(protocol, ctx, ipcLogger);
}
getChannel<T extends IChannel>(channelName: string): T {
return this.channelClient.getChannel(channelName) as T;
}
registerChannel(channelName: string, channel: IServerChannel<TContext>): void {
this.channelServer.registerChannel(channelName, channel);
}
dispose(): void {
this.channelClient.dispose();
this.channelServer.dispose();
}
}
export function getDelayedChannel<T extends IChannel>(promise: Promise<T>): T {
return {
call(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
return promise.then(c => c.call<T>(command, arg, cancellationToken));
},
listen<T>(event: string, arg?: any): Event<T> {
const relay = new Relay<any>();
promise.then(c => relay.input = c.listen(event, arg));
return relay.event;
}
} as T;
}
export function getNextTickChannel<T extends IChannel>(channel: T): T {
let didTick = false;
return {
call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
if (didTick) {
return channel.call(command, arg, cancellationToken);
}
return timeout(0)
.then(() => didTick = true)
.then(() => channel.call<T>(command, arg, cancellationToken));
},
listen<T>(event: string, arg?: any): Event<T> {
if (didTick) {
return channel.listen<T>(event, arg);
}
const relay = new Relay<T>();
timeout(0)
.then(() => didTick = true)
.then(() => relay.input = channel.listen<T>(event, arg));
return relay.event;
}
} as T;
}
export class StaticRouter<TContext = string> implements IClientRouter<TContext> {
constructor(private fn: (ctx: TContext) => boolean | Promise<boolean>) { }
routeCall(hub: IConnectionHub<TContext>): Promise<Client<TContext>> {
return this.route(hub);
}
routeEvent(hub: IConnectionHub<TContext>): Promise<Client<TContext>> {
return this.route(hub);
}
private async route(hub: IConnectionHub<TContext>): Promise<Client<TContext>> {
for (const connection of hub.connections) {
if (await Promise.resolve(this.fn(connection.ctx))) {
return Promise.resolve(connection);
}
}
await Event.toPromise(hub.onDidAddConnection);
return await this.route(hub);
}
}
/**
* Use ProxyChannels to automatically wrapping and unwrapping
* services to/from IPC channels, instead of manually wrapping
* each service method and event.
*
* Restrictions:
* - If marshalling is enabled, only `URI` and `RegExp` is converted
* automatically for you
* - Events must follow the naming convention `onUpperCase`
* - `CancellationToken` is currently not supported
* - If a context is provided, you can use `AddFirstParameterToFunctions`
* utility to signal this in the receiving side type
*/
export namespace ProxyChannel {
export interface IProxyOptions {
/**
* Disables automatic marshalling of `URI`.
* If marshalling is disabled, `UriComponents`
* must be used instead.
*/
disableMarshalling?: boolean;
}
export interface ICreateServiceChannelOptions extends IProxyOptions { }
export function fromService<TContext>(service: unknown, options?: ICreateServiceChannelOptions): IServerChannel<TContext> {
const handler = service as { [key: string]: unknown };
const disableMarshalling = options && options.disableMarshalling;
// Buffer any event that should be supported by
// iterating over all property keys and finding them
const mapEventNameToEvent = new Map<string, Event<unknown>>();
for (const key in handler) {
if (propertyIsEvent(key)) {
mapEventNameToEvent.set(key, Event.buffer(handler[key] as Event<unknown>, true));
}
}
return new class implements IServerChannel {
listen<T>(_: unknown, event: string, arg: any): Event<T> {
const eventImpl = mapEventNameToEvent.get(event);
if (eventImpl) {
return eventImpl as Event<T>;
}
if (propertyIsDynamicEvent(event)) {
const target = handler[event];
if (typeof target === 'function') {
return target.call(handler, arg);
}
}
throw new Error(`Event not found: ${event}`);
}
call(_: unknown, command: string, args?: any[]): Promise<any> {
const target = handler[command];
if (typeof target === 'function') {
// Revive unless marshalling disabled
if (!disableMarshalling && Array.isArray(args)) {
for (let i = 0; i < args.length; i++) {
args[i] = revive(args[i]);
}
}
return target.apply(handler, args);
}
throw new Error(`Method not found: ${command}`);
}
};
}
export interface ICreateProxyServiceOptions extends IProxyOptions {
/**
* If provided, will add the value of `context`
* to each method call to the target.
*/
context?: unknown;
/**
* If provided, will not proxy any of the properties
* that are part of the Map but rather return that value.
*/
properties?: Map<string, unknown>;
}
export function toService<T extends object>(channel: IChannel, options?: ICreateProxyServiceOptions): T {
const disableMarshalling = options && options.disableMarshalling;
return new Proxy({}, {
get(_target: T, propKey: PropertyKey) {
if (typeof propKey === 'string') {
// Check for predefined values
if (options?.properties?.has(propKey)) {
return options.properties.get(propKey);
}
// Dynamic Event
if (propertyIsDynamicEvent(propKey)) {
return function (arg: any) {
return channel.listen(propKey, arg);
};
}
// Event
if (propertyIsEvent(propKey)) {
return channel.listen(propKey);
}
// Function
return async function (...args: any[]) {
// Add context if any
let methodArgs: any[];
if (options && !isUndefinedOrNull(options.context)) {
methodArgs = [options.context, ...args];
} else {
methodArgs = args;
}
const result = await channel.call(propKey, methodArgs);
// Revive unless marshalling disabled
if (!disableMarshalling) {
return revive(result);
}
return result;
};
}
throw new Error(`Property not found: ${String(propKey)}`);
}
}) as T;
}
function propertyIsEvent(name: string): boolean {
// Assume a property is an event if it has a form of "onSomething"
return name[0] === 'o' && name[1] === 'n' && strings.isUpperAsciiLetter(name.charCodeAt(2));
}
function propertyIsDynamicEvent(name: string): boolean {
// Assume a property is a dynamic event (a method that returns an event) if it has a form of "onDynamicSomething"
return /^onDynamic/.test(name) && strings.isUpperAsciiLetter(name.charCodeAt(9));
}
}
const colorTables = [
['#2977B1', '#FC802D', '#34A13A', '#D3282F', '#9366BA'],
['#8B564C', '#E177C0', '#7F7F7F', '#BBBE3D', '#2EBECD']
];
function prettyWithoutArrays(data: any): any {
if (Array.isArray(data)) {
return data;
}
if (data && typeof data === 'object' && typeof data.toString === 'function') {
const result = data.toString();
if (result !== '[object Object]') {
return result;
}
}
return data;
}
function pretty(data: any): any {
if (Array.isArray(data)) {
return data.map(prettyWithoutArrays);
}
return prettyWithoutArrays(data);
}
function logWithColors(direction: string, totalLength: number, msgLength: number, req: number, initiator: RequestInitiator, str: string, data: any): void {
data = pretty(data);
const colorTable = colorTables[initiator];
const color = colorTable[req % colorTable.length];
let args = [`%c[${direction}]%c[${String(totalLength).padStart(7, ' ')}]%c[len: ${String(msgLength).padStart(5, ' ')}]%c${String(req).padStart(5, ' ')} - ${str}`, 'color: darkgreen', 'color: grey', 'color: grey', `color: ${color}`];
if (/\($/.test(str)) {
args = args.concat(data);
args.push(')');
} else {
args.push(data);
}
console.log.apply(console, args as [string, ...string[]]);
}
export class IPCLogger implements IIPCLogger {
private _totalIncoming = 0;
private _totalOutgoing = 0;
constructor(
private readonly _outgoingPrefix: string,
private readonly _incomingPrefix: string,
) { }
public logOutgoing(msgLength: number, requestId: number, initiator: RequestInitiator, str: string, data?: any): void {
this._totalOutgoing += msgLength;
logWithColors(this._outgoingPrefix, this._totalOutgoing, msgLength, requestId, initiator, str, data);
}
public logIncoming(msgLength: number, requestId: number, initiator: RequestInitiator, str: string, data?: any): void {
this._totalIncoming += msgLength;
logWithColors(this._incomingPrefix, this._totalIncoming, msgLength, requestId, initiator, str, data);
}
}
| src/vs/base/parts/ipc/common/ipc.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.002587483264505863,
0.0001907707192003727,
0.0001628473837627098,
0.00016927834076341242,
0.00021396046213340014
] |
{
"id": 8,
"code_window": [
"\n",
"\t\t\t\tif (actionHandler) {\n",
"\t\t\t\t\tconst onPointer = (e: EventLike) => {\n",
"\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst handleOpen = (e: unknown) => {\n",
"\t\t\t\t\t\tif (isEventLike(e)) {\n",
"\t\t\t\t\t\t\tEventHelper.stop(e, true);\n",
"\t\t\t\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 155
} | swagger: '2.0'
info:
description: 'The API Management Service API defines an updated and refined version
of the concepts currently known as Developer, APP, and API Product in Edge. Of
note is the introduction of the API concept, missing previously from Edge
'
title: API Management Service API
version: initial | extensions/vscode-colorize-tests/test/colorize-fixtures/issue-6303.yaml | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001694269012659788,
0.0001694269012659788,
0.0001694269012659788,
0.0001694269012659788,
0
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n",
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;\n",
"\n",
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.CLICK)).event;\n",
"\n",
"\t\t\t\t\tconst onKeydown = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.KEY_DOWN)).event;\n",
"\t\t\t\t\tconst onSpaceOrEnter = actionHandler.toDispose.add(Event.chain(onKeydown)).filter(e => {\n",
"\t\t\t\t\t\tconst event = new StandardKeyboardEvent(e);\n",
"\n",
"\t\t\t\t\t\treturn event.equals(KeyCode.Space) || event.equals(KeyCode.Enter);\n",
"\t\t\t\t\t}).event;\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 160
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { INotificationViewItem, isNotificationViewItem, NotificationsModel } from 'vs/workbench/common/notifications';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { localize } from 'vs/nls';
import { IListService, WorkbenchList } from 'vs/platform/list/browser/listService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NotificationMetrics, NotificationMetricsClassification, notificationToMetrics } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry';
import { NotificationFocusedContext, NotificationsCenterVisibleContext, NotificationsToastsVisibleContext } from 'vs/workbench/common/contextkeys';
import { INotificationService } from 'vs/platform/notification/common/notification';
// Center
export const SHOW_NOTIFICATIONS_CENTER = 'notifications.showList';
export const HIDE_NOTIFICATIONS_CENTER = 'notifications.hideList';
const TOGGLE_NOTIFICATIONS_CENTER = 'notifications.toggleList';
// Toasts
export const HIDE_NOTIFICATION_TOAST = 'notifications.hideToasts';
const FOCUS_NOTIFICATION_TOAST = 'notifications.focusToasts';
const FOCUS_NEXT_NOTIFICATION_TOAST = 'notifications.focusNextToast';
const FOCUS_PREVIOUS_NOTIFICATION_TOAST = 'notifications.focusPreviousToast';
const FOCUS_FIRST_NOTIFICATION_TOAST = 'notifications.focusFirstToast';
const FOCUS_LAST_NOTIFICATION_TOAST = 'notifications.focusLastToast';
// Notification
export const COLLAPSE_NOTIFICATION = 'notification.collapse';
export const EXPAND_NOTIFICATION = 'notification.expand';
const TOGGLE_NOTIFICATION = 'notification.toggle';
export const CLEAR_NOTIFICATION = 'notification.clear';
export const CLEAR_ALL_NOTIFICATIONS = 'notifications.clearAll';
export const TOGGLE_DO_NOT_DISTURB_MODE = 'notifications.toggleDoNotDisturbMode';
export interface INotificationsCenterController {
readonly isVisible: boolean;
show(): void;
hide(): void;
clearAll(): void;
}
export interface INotificationsToastController {
focus(): void;
focusNext(): void;
focusPrevious(): void;
focusFirst(): void;
focusLast(): void;
hide(): void;
}
export function registerNotificationCommands(center: INotificationsCenterController, toasts: INotificationsToastController, model: NotificationsModel): void {
function getNotificationFromContext(listService: IListService, context?: unknown): INotificationViewItem | undefined {
if (isNotificationViewItem(context)) {
return context;
}
const list = listService.lastFocusedList;
if (list instanceof WorkbenchList) {
const focusedElement = list.getFocusedElements()[0];
if (isNotificationViewItem(focusedElement)) {
return focusedElement;
}
}
return undefined;
}
// Show Notifications Cneter
CommandsRegistry.registerCommand(SHOW_NOTIFICATIONS_CENTER, () => {
toasts.hide();
center.show();
});
// Hide Notifications Center
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: HIDE_NOTIFICATIONS_CENTER,
weight: KeybindingWeight.WorkbenchContrib + 50,
when: NotificationsCenterVisibleContext,
primary: KeyCode.Escape,
handler: accessor => {
const telemetryService = accessor.get(ITelemetryService);
for (const notification of model.notifications) {
if (notification.visible) {
telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent));
}
}
center.hide();
}
});
// Toggle Notifications Center
CommandsRegistry.registerCommand(TOGGLE_NOTIFICATIONS_CENTER, accessor => {
if (center.isVisible) {
center.hide();
} else {
toasts.hide();
center.show();
}
});
// Clear Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLEAR_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.Delete,
mac: {
primary: KeyMod.CtrlCmd | KeyCode.Backspace
},
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
if (notification && !notification.hasProgress) {
notification.close();
}
}
});
// Expand Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: EXPAND_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.RightArrow,
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
notification?.expand();
}
});
// Collapse Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: COLLAPSE_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.LeftArrow,
handler: (accessor, args?) => {
const notification = getNotificationFromContext(accessor.get(IListService), args);
notification?.collapse();
}
});
// Toggle Notification
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: TOGGLE_NOTIFICATION,
weight: KeybindingWeight.WorkbenchContrib,
when: NotificationFocusedContext,
primary: KeyCode.Space,
secondary: [KeyCode.Enter],
handler: accessor => {
const notification = getNotificationFromContext(accessor.get(IListService));
notification?.toggle();
}
});
// Hide Toasts
CommandsRegistry.registerCommand(HIDE_NOTIFICATION_TOAST, accessor => {
const telemetryService = accessor.get(ITelemetryService);
for (const notification of model.notifications) {
if (notification.visible) {
telemetryService.publicLog2<NotificationMetrics, NotificationMetricsClassification>('notification:hide', notificationToMetrics(notification.message.original, notification.sourceId, notification.silent));
}
}
toasts.hide();
});
KeybindingsRegistry.registerKeybindingRule({
id: HIDE_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib - 50, // lower when not focused (e.g. let editor suggest win over this command)
when: NotificationsToastsVisibleContext,
primary: KeyCode.Escape
});
KeybindingsRegistry.registerKeybindingRule({
id: HIDE_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib + 100, // higher when focused
when: ContextKeyExpr.and(NotificationsToastsVisibleContext, NotificationFocusedContext),
primary: KeyCode.Escape
});
// Focus Toasts
CommandsRegistry.registerCommand(FOCUS_NOTIFICATION_TOAST, () => toasts.focus());
// Focus Next Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_NEXT_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.DownArrow,
handler: (accessor) => {
toasts.focusNext();
}
});
// Focus Previous Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_PREVIOUS_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.UpArrow,
handler: (accessor) => {
toasts.focusPrevious();
}
});
// Focus First Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_FIRST_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.PageUp,
secondary: [KeyCode.Home],
handler: (accessor) => {
toasts.focusFirst();
}
});
// Focus Last Toast
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: FOCUS_LAST_NOTIFICATION_TOAST,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(NotificationFocusedContext, NotificationsToastsVisibleContext),
primary: KeyCode.PageDown,
secondary: [KeyCode.End],
handler: (accessor) => {
toasts.focusLast();
}
});
// Clear All Notifications
CommandsRegistry.registerCommand(CLEAR_ALL_NOTIFICATIONS, () => center.clearAll());
// Toggle Do Not Disturb Mode
CommandsRegistry.registerCommand(TOGGLE_DO_NOT_DISTURB_MODE, accessor => {
const notificationService = accessor.get(INotificationService);
notificationService.doNotDisturbMode = !notificationService.doNotDisturbMode;
});
// Commands for Command Palette
const category = { value: localize('notifications', "Notifications"), original: 'Notifications' };
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: SHOW_NOTIFICATIONS_CENTER, title: { value: localize('showNotifications', "Show Notifications"), original: 'Show Notifications' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: HIDE_NOTIFICATIONS_CENTER, title: { value: localize('hideNotifications', "Hide Notifications"), original: 'Hide Notifications' }, category }, when: NotificationsCenterVisibleContext });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: CLEAR_ALL_NOTIFICATIONS, title: { value: localize('clearAllNotifications', "Clear All Notifications"), original: 'Clear All Notifications' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: TOGGLE_DO_NOT_DISTURB_MODE, title: { value: localize('toggleDoNotDisturbMode', "Toggle Do Not Disturb Mode"), original: 'Toggle Do Not Disturb Mode' }, category } });
MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: FOCUS_NOTIFICATION_TOAST, title: { value: localize('focusNotificationToasts', "Focus Notification Toast"), original: 'Focus Notification Toast' }, category }, when: NotificationsToastsVisibleContext });
}
| src/vs/workbench/browser/parts/notifications/notificationsCommands.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00018432983779348433,
0.00017346272943541408,
0.00016658239474054426,
0.00017339950136374682,
0.000002935121756308945
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n",
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;\n",
"\n",
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.CLICK)).event;\n",
"\n",
"\t\t\t\t\tconst onKeydown = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.KEY_DOWN)).event;\n",
"\t\t\t\t\tconst onSpaceOrEnter = actionHandler.toDispose.add(Event.chain(onKeydown)).filter(e => {\n",
"\t\t\t\t\t\tconst event = new StandardKeyboardEvent(e);\n",
"\n",
"\t\t\t\t\t\treturn event.equals(KeyCode.Space) || event.equals(KeyCode.Enter);\n",
"\t\t\t\t\t}).event;\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 160
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ipcRenderer } from 'electron';
import { Event } from 'vs/base/common/event';
import { ClientConnectionEvent, IPCServer } from 'vs/base/parts/ipc/common/ipc';
import { Protocol as MessagePortProtocol } from 'vs/base/parts/ipc/common/ipc.mp';
/**
* An implementation of a `IPCServer` on top of MessagePort style IPC communication.
* The clients register themselves via Electron IPC transfer.
*/
export class Server extends IPCServer {
private static getOnDidClientConnect(): Event<ClientConnectionEvent> {
// Clients connect via `vscode:createMessageChannel` to get a
// `MessagePort` that is ready to be used. For every connection
// we create a pair of message ports and send it back.
//
// The `nonce` is included so that the main side has a chance to
// correlate the response back to the sender.
const onCreateMessageChannel = Event.fromNodeEventEmitter<string>(ipcRenderer, 'vscode:createMessageChannel', (_, nonce: string) => nonce);
return Event.map(onCreateMessageChannel, nonce => {
// Create a new pair of ports and protocol for this connection
const { port1: incomingPort, port2: outgoingPort } = new MessageChannel();
const protocol = new MessagePortProtocol(incomingPort);
const result: ClientConnectionEvent = {
protocol,
// Not part of the standard spec, but in Electron we get a `close` event
// when the other side closes. We can use this to detect disconnects
// (https://github.com/electron/electron/blob/11-x-y/docs/api/message-port-main.md#event-close)
onDidClientDisconnect: Event.fromDOMEventEmitter(incomingPort, 'close')
};
// Send one port back to the requestor
// Note: we intentionally use `electron` APIs here because
// transferables like the `MessagePort` cannot be transferred
// over preload scripts when `contextIsolation: true`
ipcRenderer.postMessage('vscode:createMessageChannelResult', nonce, [outgoingPort]);
return result;
});
}
constructor() {
super(Server.getOnDidClientConnect());
}
}
| src/vs/base/parts/ipc/electron-browser/ipc.mp.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.002030591946095228,
0.00048152959789149463,
0.00016967198462225497,
0.00017207914788741618,
0.000692764122504741
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n",
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;\n",
"\n",
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.CLICK)).event;\n",
"\n",
"\t\t\t\t\tconst onKeydown = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.KEY_DOWN)).event;\n",
"\t\t\t\t\tconst onSpaceOrEnter = actionHandler.toDispose.add(Event.chain(onKeydown)).filter(e => {\n",
"\t\t\t\t\t\tconst event = new StandardKeyboardEvent(e);\n",
"\n",
"\t\t\t\t\t\treturn event.equals(KeyCode.Space) || event.equals(KeyCode.Enter);\n",
"\t\t\t\t\t}).event;\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 160
} | /*---------------------------------------------------------------------------------------------
* 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 { EditOperation, ISingleEditOperation } from 'vs/editor/common/core/editOperation';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { withTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor';
function testCommand(lines: string[], selections: Selection[], edits: ISingleEditOperation[], expectedLines: string[], expectedSelections: Selection[]): void {
withTestCodeEditor(lines, {}, (editor, viewModel) => {
const model = editor.getModel()!;
viewModel.setSelections('tests', selections);
model.applyEdits(edits);
assert.deepStrictEqual(model.getLinesContent(), expectedLines);
const actualSelections = viewModel.getSelections();
assert.deepStrictEqual(actualSelections.map(s => s.toString()), expectedSelections.map(s => s.toString()));
});
}
suite('Editor Side Editing - collapsed selection', () => {
test('replace at selection', () => {
testCommand(
[
'first',
'second line',
'third line',
'fourth'
],
[new Selection(1, 1, 1, 1)],
[
EditOperation.replace(new Selection(1, 1, 1, 1), 'something ')
],
[
'something first',
'second line',
'third line',
'fourth'
],
[new Selection(1, 1, 1, 11)]
);
});
test('replace at selection 2', () => {
testCommand(
[
'first',
'second line',
'third line',
'fourth'
],
[new Selection(1, 1, 1, 6)],
[
EditOperation.replace(new Selection(1, 1, 1, 6), 'something')
],
[
'something',
'second line',
'third line',
'fourth'
],
[new Selection(1, 1, 1, 10)]
);
});
test('insert at selection', () => {
testCommand(
[
'first',
'second line',
'third line',
'fourth'
],
[new Selection(1, 1, 1, 1)],
[
EditOperation.insert(new Position(1, 1), 'something ')
],
[
'something first',
'second line',
'third line',
'fourth'
],
[new Selection(1, 11, 1, 11)]
);
});
test('insert at selection sitting on max column', () => {
testCommand(
[
'first',
'second line',
'third line',
'fourth'
],
[new Selection(1, 6, 1, 6)],
[
EditOperation.insert(new Position(1, 6), ' something\nnew ')
],
[
'first something',
'new ',
'second line',
'third line',
'fourth'
],
[new Selection(2, 5, 2, 5)]
);
});
test('issue #3994: replace on top of selection', () => {
testCommand(
[
'$obj = New-Object "system.col"'
],
[new Selection(1, 30, 1, 30)],
[
EditOperation.replaceMove(new Range(1, 19, 1, 31), '"System.Collections"')
],
[
'$obj = New-Object "System.Collections"'
],
[new Selection(1, 39, 1, 39)]
);
});
test('issue #15267: Suggestion that adds a line - cursor goes to the wrong line ', () => {
testCommand(
[
'package main',
'',
'import (',
' "fmt"',
')',
'',
'func main(',
' fmt.Println(strings.Con)',
'}'
],
[new Selection(8, 25, 8, 25)],
[
EditOperation.replaceMove(new Range(5, 1, 5, 1), '\t\"strings\"\n')
],
[
'package main',
'',
'import (',
' "fmt"',
' "strings"',
')',
'',
'func main(',
' fmt.Println(strings.Con)',
'}'
],
[new Selection(9, 25, 9, 25)]
);
});
test('issue #15236: Selections broke after deleting text using vscode.TextEditor.edit ', () => {
testCommand(
[
'foofoofoo, foofoofoo, bar'
],
[new Selection(1, 1, 1, 10), new Selection(1, 12, 1, 21)],
[
EditOperation.replace(new Range(1, 1, 1, 10), ''),
EditOperation.replace(new Range(1, 12, 1, 21), ''),
],
[
', , bar'
],
[new Selection(1, 1, 1, 1), new Selection(1, 3, 1, 3)]
);
});
});
suite('SideEditing', () => {
const LINES = [
'My First Line',
'My Second Line',
'Third Line'
];
function _runTest(selection: Selection, editRange: Range, editText: string, editForceMoveMarkers: boolean, expected: Selection, msg: string): void {
withTestCodeEditor(LINES.join('\n'), {}, (editor, viewModel) => {
viewModel.setSelections('tests', [selection]);
editor.getModel().applyEdits([{
range: editRange,
text: editText,
forceMoveMarkers: editForceMoveMarkers
}]);
const actual = viewModel.getSelection();
assert.deepStrictEqual(actual.toString(), expected.toString(), msg);
});
}
function runTest(selection: Range, editRange: Range, editText: string, expected: Selection[][]): void {
const sel1 = new Selection(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn);
_runTest(sel1, editRange, editText, false, expected[0][0], '0-0-regular-no-force');
_runTest(sel1, editRange, editText, true, expected[1][0], '1-0-regular-force');
// RTL selection
const sel2 = new Selection(selection.endLineNumber, selection.endColumn, selection.startLineNumber, selection.startColumn);
_runTest(sel2, editRange, editText, false, expected[0][1], '0-1-inverse-no-force');
_runTest(sel2, editRange, editText, true, expected[1][1], '1-1-inverse-force');
}
suite('insert', () => {
suite('collapsed sel', () => {
test('before', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 3, 1, 3), 'xx',
[
[new Selection(1, 6, 1, 6), new Selection(1, 6, 1, 6)],
[new Selection(1, 6, 1, 6), new Selection(1, 6, 1, 6)],
]
);
});
test('equal', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 4, 1, 4), 'xx',
[
[new Selection(1, 4, 1, 6), new Selection(1, 4, 1, 6)],
[new Selection(1, 6, 1, 6), new Selection(1, 6, 1, 6)],
]
);
});
test('after', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 5, 1, 5), 'xx',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
});
suite('non-collapsed dec', () => {
test('before', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 3), 'xx',
[
[new Selection(1, 6, 1, 11), new Selection(1, 11, 1, 6)],
[new Selection(1, 6, 1, 11), new Selection(1, 11, 1, 6)],
]
);
});
test('start', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 4), 'xx',
[
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
[new Selection(1, 6, 1, 11), new Selection(1, 11, 1, 6)],
]
);
});
test('inside', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 5), 'xx',
[
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
]
);
});
test('end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 9, 1, 9), 'xx',
[
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
]
);
});
test('after', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 10, 1, 10), 'xx',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
]
);
});
});
});
suite('delete', () => {
suite('collapsed dec', () => {
test('edit.end < range.start', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 1, 1, 3), '',
[
[new Selection(1, 2, 1, 2), new Selection(1, 2, 1, 2)],
[new Selection(1, 2, 1, 2), new Selection(1, 2, 1, 2)],
]
);
});
test('edit.end <= range.start', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 2, 1, 4), '',
[
[new Selection(1, 2, 1, 2), new Selection(1, 2, 1, 2)],
[new Selection(1, 2, 1, 2), new Selection(1, 2, 1, 2)],
]
);
});
test('edit.start < range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 3, 1, 5), '',
[
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
]
);
});
test('edit.start >= range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 4, 1, 6), '',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
test('edit.start > range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 5, 1, 7), '',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
});
suite('non-collapsed dec', () => {
test('edit.end < range.start', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 1, 1, 3), '',
[
[new Selection(1, 2, 1, 7), new Selection(1, 7, 1, 2)],
[new Selection(1, 2, 1, 7), new Selection(1, 7, 1, 2)],
]
);
});
test('edit.end <= range.start', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 2, 1, 4), '',
[
[new Selection(1, 2, 1, 7), new Selection(1, 7, 1, 2)],
[new Selection(1, 2, 1, 7), new Selection(1, 7, 1, 2)],
]
);
});
test('edit.start < range.start && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 5), '',
[
[new Selection(1, 3, 1, 7), new Selection(1, 7, 1, 3)],
[new Selection(1, 3, 1, 7), new Selection(1, 7, 1, 3)],
]
);
});
test('edit.start < range.start && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 9), '',
[
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
]
);
});
test('edit.start < range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 10), '',
[
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
]
);
});
test('edit.start == range.start && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 6), '',
[
[new Selection(1, 4, 1, 7), new Selection(1, 7, 1, 4)],
[new Selection(1, 4, 1, 7), new Selection(1, 7, 1, 4)],
]
);
});
test('edit.start == range.start && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 9), '',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
test('edit.start == range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 10), '',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 7), '',
[
[new Selection(1, 4, 1, 7), new Selection(1, 7, 1, 4)],
[new Selection(1, 4, 1, 7), new Selection(1, 7, 1, 4)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 9), '',
[
[new Selection(1, 4, 1, 5), new Selection(1, 5, 1, 4)],
[new Selection(1, 4, 1, 5), new Selection(1, 5, 1, 4)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 10), '',
[
[new Selection(1, 4, 1, 5), new Selection(1, 5, 1, 4)],
[new Selection(1, 4, 1, 5), new Selection(1, 5, 1, 4)],
]
);
});
test('edit.start == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 9, 1, 11), '',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
]
);
});
test('edit.start > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 10, 1, 11), '',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
]
);
});
});
});
suite('replace short', () => {
suite('collapsed dec', () => {
test('edit.end < range.start', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 1, 1, 3), 'c',
[
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
]
);
});
test('edit.end <= range.start', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 2, 1, 4), 'c',
[
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
[new Selection(1, 3, 1, 3), new Selection(1, 3, 1, 3)],
]
);
});
test('edit.start < range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 3, 1, 5), 'c',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
test('edit.start >= range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 4, 1, 6), 'c',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 5, 1, 5), new Selection(1, 5, 1, 5)],
]
);
});
test('edit.start > range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 5, 1, 7), 'c',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
});
suite('non-collapsed dec', () => {
test('edit.end < range.start', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 1, 1, 3), 'c',
[
[new Selection(1, 3, 1, 8), new Selection(1, 8, 1, 3)],
[new Selection(1, 3, 1, 8), new Selection(1, 8, 1, 3)],
]
);
});
test('edit.end <= range.start', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 2, 1, 4), 'c',
[
[new Selection(1, 3, 1, 8), new Selection(1, 8, 1, 3)],
[new Selection(1, 3, 1, 8), new Selection(1, 8, 1, 3)],
]
);
});
test('edit.start < range.start && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 5), 'c',
[
[new Selection(1, 4, 1, 8), new Selection(1, 8, 1, 4)],
[new Selection(1, 4, 1, 8), new Selection(1, 8, 1, 4)],
]
);
});
test('edit.start < range.start && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 9), 'c',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
test('edit.start < range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 10), 'c',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
test('edit.start == range.start && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 6), 'c',
[
[new Selection(1, 4, 1, 8), new Selection(1, 8, 1, 4)],
[new Selection(1, 5, 1, 8), new Selection(1, 8, 1, 5)],
]
);
});
test('edit.start == range.start && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 9), 'c',
[
[new Selection(1, 4, 1, 5), new Selection(1, 5, 1, 4)],
[new Selection(1, 5, 1, 5), new Selection(1, 5, 1, 5)],
]
);
});
test('edit.start == range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 10), 'c',
[
[new Selection(1, 4, 1, 5), new Selection(1, 5, 1, 4)],
[new Selection(1, 5, 1, 5), new Selection(1, 5, 1, 5)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 7), 'c',
[
[new Selection(1, 4, 1, 8), new Selection(1, 8, 1, 4)],
[new Selection(1, 4, 1, 8), new Selection(1, 8, 1, 4)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 9), 'c',
[
[new Selection(1, 4, 1, 6), new Selection(1, 6, 1, 4)],
[new Selection(1, 4, 1, 6), new Selection(1, 6, 1, 4)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 10), 'c',
[
[new Selection(1, 4, 1, 6), new Selection(1, 6, 1, 4)],
[new Selection(1, 4, 1, 6), new Selection(1, 6, 1, 4)],
]
);
});
test('edit.start == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 9, 1, 11), 'c',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 10), new Selection(1, 10, 1, 4)],
]
);
});
test('edit.start > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 10, 1, 11), 'c',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
]
);
});
});
});
suite('replace long', () => {
suite('collapsed dec', () => {
test('edit.end < range.start', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 1, 1, 3), 'cccc',
[
[new Selection(1, 6, 1, 6), new Selection(1, 6, 1, 6)],
[new Selection(1, 6, 1, 6), new Selection(1, 6, 1, 6)],
]
);
});
test('edit.end <= range.start', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 2, 1, 4), 'cccc',
[
[new Selection(1, 4, 1, 6), new Selection(1, 4, 1, 6)],
[new Selection(1, 6, 1, 6), new Selection(1, 6, 1, 6)],
]
);
});
test('edit.start < range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 3, 1, 5), 'cccc',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 7, 1, 7), new Selection(1, 7, 1, 7)],
]
);
});
test('edit.start >= range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 4, 1, 6), 'cccc',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 8, 1, 8), new Selection(1, 8, 1, 8)],
]
);
});
test('edit.start > range.end', () => {
runTest(
new Range(1, 4, 1, 4),
new Range(1, 5, 1, 7), 'cccc',
[
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
[new Selection(1, 4, 1, 4), new Selection(1, 4, 1, 4)],
]
);
});
});
suite('non-collapsed dec', () => {
test('edit.end < range.start', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 1, 1, 3), 'cccc',
[
[new Selection(1, 6, 1, 11), new Selection(1, 11, 1, 6)],
[new Selection(1, 6, 1, 11), new Selection(1, 11, 1, 6)],
]
);
});
test('edit.end <= range.start', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 2, 1, 4), 'cccc',
[
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
[new Selection(1, 6, 1, 11), new Selection(1, 11, 1, 6)],
]
);
});
test('edit.start < range.start && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 5), 'cccc',
[
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
[new Selection(1, 7, 1, 11), new Selection(1, 11, 1, 7)],
]
);
});
test('edit.start < range.start && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 9), 'cccc',
[
[new Selection(1, 4, 1, 7), new Selection(1, 7, 1, 4)],
[new Selection(1, 7, 1, 7), new Selection(1, 7, 1, 7)],
]
);
});
test('edit.start < range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 3, 1, 10), 'cccc',
[
[new Selection(1, 4, 1, 7), new Selection(1, 7, 1, 4)],
[new Selection(1, 7, 1, 7), new Selection(1, 7, 1, 7)],
]
);
});
test('edit.start == range.start && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 6), 'cccc',
[
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
[new Selection(1, 8, 1, 11), new Selection(1, 11, 1, 8)],
]
);
});
test('edit.start == range.start && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 9), 'cccc',
[
[new Selection(1, 4, 1, 8), new Selection(1, 8, 1, 4)],
[new Selection(1, 8, 1, 8), new Selection(1, 8, 1, 8)],
]
);
});
test('edit.start == range.start && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 4, 1, 10), 'cccc',
[
[new Selection(1, 4, 1, 8), new Selection(1, 8, 1, 4)],
[new Selection(1, 8, 1, 8), new Selection(1, 8, 1, 8)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end < range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 7), 'cccc',
[
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
[new Selection(1, 4, 1, 11), new Selection(1, 11, 1, 4)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 9), 'cccc',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
]
);
});
test('edit.start > range.start && edit.start < range.end && edit.end > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 5, 1, 10), 'cccc',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
]
);
});
test('edit.start == range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 9, 1, 11), 'cccc',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 13), new Selection(1, 13, 1, 4)],
]
);
});
test('edit.start > range.end', () => {
runTest(
new Range(1, 4, 1, 9),
new Range(1, 10, 1, 11), 'cccc',
[
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
[new Selection(1, 4, 1, 9), new Selection(1, 9, 1, 4)],
]
);
});
});
});
});
| src/vs/editor/test/browser/commands/sideEditing.test.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017831278091762215,
0.00017296573787461966,
0.00016938378394115716,
0.00017282523913308978,
0.0000014944242821002263
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\t\tactionHandler.callback(node.href);\n",
"\t\t\t\t\t};\n",
"\n",
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;\n",
"\n",
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst onClick = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.CLICK)).event;\n",
"\n",
"\t\t\t\t\tconst onKeydown = actionHandler.toDispose.add(new DomEmitter(anchor, EventType.KEY_DOWN)).event;\n",
"\t\t\t\t\tconst onSpaceOrEnter = actionHandler.toDispose.add(Event.chain(onKeydown)).filter(e => {\n",
"\t\t\t\t\t\tconst event = new StandardKeyboardEvent(e);\n",
"\n",
"\t\t\t\t\t\treturn event.equals(KeyCode.Space) || event.equals(KeyCode.Enter);\n",
"\t\t\t\t\t}).event;\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 160
} | [
{
"identifier": {
"id": "pflannery.vscode-versionlens",
"uuid": "07fc4a0a-11fc-4121-ba9a-f0d534c729d8"
},
"preRelease": false,
"version": "1.0.9",
"installed": true
},
{
"identifier": {
"id": "vscode.bat",
"uuid": "5ef96c58-076f-4167-8e40-62c9deb00496"
},
"preRelease": false,
"version": "1.0.0"
}
] | src/vs/editor/test/node/diffing/fixtures/ts-shifting/2.tst | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001748096547089517,
0.0001739150902722031,
0.00017302052583545446,
0.0001739150902722031,
8.945644367486238e-7
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n",
"\t\t\t\t\tEvent.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tmessageContainer.appendChild(anchor);\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tEvent.any(onClick, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.toDispose);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 165
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.9984531402587891,
0.018412534147500992,
0.00016369321383535862,
0.00017272202239837497,
0.13336698710918427
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n",
"\t\t\t\t\tEvent.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tmessageContainer.appendChild(anchor);\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tEvent.any(onClick, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.toDispose);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 165
} | test/**
cgmanifest.json
| extensions/scss/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017412925080861896,
0.00017412925080861896,
0.00017412925080861896,
0.00017412925080861896,
0
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n",
"\t\t\t\t\tEvent.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tmessageContainer.appendChild(anchor);\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tEvent.any(onClick, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.toDispose);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 165
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withDefaults = require('../shared.webpack.config');
module.exports = withDefaults({
context: __dirname,
entry: {
main: './src/main.ts',
['askpass-main']: './src/askpass-main.ts',
['git-editor-main']: './src/git-editor-main.ts'
}
});
| extensions/git/extension.webpack.config.js | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017576971731614321,
0.00017523020505905151,
0.00017469067825004458,
0.00017523020505905151,
5.395195330493152e-7
] |
{
"id": 10,
"code_window": [
"\t\t\t\t\tactionHandler.toDispose.add(Gesture.addTarget(anchor));\n",
"\t\t\t\t\tconst onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;\n",
"\n",
"\t\t\t\t\tEvent.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tmessageContainer.appendChild(anchor);\n",
"\t\t\t}\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tEvent.any(onClick, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.toDispose);\n"
],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 165
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@azure/abort-controller@^1.0.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@azure/abort-controller/-/abort-controller-1.1.0.tgz#788ee78457a55af8a1ad342acb182383d2119249"
integrity sha512-TrRLIoSQVzfAJX9H1JeFjzAoDGcoK1IYX1UImfceTZpsyYfWr09Ss1aHW1y5TrrR3iq6RZLBwJ3E24uwPhwahw==
dependencies:
tslib "^2.2.0"
"@azure/core-auth@^1.3.0":
version "1.4.0"
resolved "https://registry.yarnpkg.com/@azure/core-auth/-/core-auth-1.4.0.tgz#6fa9661c1705857820dbc216df5ba5665ac36a9e"
integrity sha512-HFrcTgmuSuukRf/EdPmqBrc5l6Q5Uu+2TbuhaKbgaCpP2TfAeiNaQPAadxO+CYBRHGUzIDteMAjFspFLDLnKVQ==
dependencies:
"@azure/abort-controller" "^1.0.0"
tslib "^2.2.0"
"@azure/core-http@^2.2.3":
version "2.3.0"
resolved "https://registry.yarnpkg.com/@azure/core-http/-/core-http-2.3.0.tgz#fb96de9a96923c186de15127472cb8e177f7158f"
integrity sha512-Gikj2QO9W41rw7yiKWi2Q2OcVcukt+ux7ZZeFy4ilC/0b1Wcr0rjseZh9bqJ3NI9+h78Hix34ZjEg316iHjbTA==
dependencies:
"@azure/abort-controller" "^1.0.0"
"@azure/core-auth" "^1.3.0"
"@azure/core-tracing" "1.0.0-preview.13"
"@azure/core-util" "^1.1.1"
"@azure/logger" "^1.0.0"
"@types/node-fetch" "^2.5.0"
"@types/tunnel" "^0.0.3"
form-data "^4.0.0"
node-fetch "^2.6.7"
process "^0.11.10"
tough-cookie "^4.0.0"
tslib "^2.2.0"
tunnel "^0.0.6"
uuid "^8.3.0"
xml2js "^0.4.19"
"@azure/[email protected]":
version "1.0.0-preview.13"
resolved "https://registry.yarnpkg.com/@azure/core-tracing/-/core-tracing-1.0.0-preview.13.tgz#55883d40ae2042f6f1e12b17dd0c0d34c536d644"
integrity sha512-KxDlhXyMlh2Jhj2ykX6vNEU0Vou4nHr025KoSEiz7cS3BNiHNaZcdECk/DmLkEB0as5T7b/TpRcehJ5yV6NeXQ==
dependencies:
"@opentelemetry/api" "^1.0.1"
tslib "^2.2.0"
"@azure/core-util@^1.1.1":
version "1.1.1"
resolved "https://registry.yarnpkg.com/@azure/core-util/-/core-util-1.1.1.tgz#8f87b3dd468795df0f0849d9f096c3e7b29452c1"
integrity sha512-A4TBYVQCtHOigFb2ETiiKFDocBoI1Zk2Ui1KpI42aJSIDexF7DHQFpnjonltXAIU/ceH+1fsZAWWgvX6/AKzog==
dependencies:
"@azure/abort-controller" "^1.0.0"
tslib "^2.2.0"
"@azure/logger@^1.0.0":
version "1.0.3"
resolved "https://registry.yarnpkg.com/@azure/logger/-/logger-1.0.3.tgz#6e36704aa51be7d4a1bae24731ea580836293c96"
integrity sha512-aK4s3Xxjrx3daZr3VylxejK3vG5ExXck5WOHDJ8in/k9AqlfIyFMMT1uG7u8mNjX+QRILTIn0/Xgschfh/dQ9g==
dependencies:
tslib "^2.2.0"
"@microsoft/[email protected]", "@microsoft/1ds-core-js@^3.2.8":
version "3.2.8"
resolved "https://registry.yarnpkg.com/@microsoft/1ds-core-js/-/1ds-core-js-3.2.8.tgz#1b6b7d9bb858238c818ccf4e4b58ece7aeae5760"
integrity sha512-9o9SUAamJiTXIYwpkQDuueYt83uZfXp8zp8YFix1IwVPwC9RmE36T2CX9gXOeq1nDckOuOduYpA8qHvdh5BGfQ==
dependencies:
"@microsoft/applicationinsights-core-js" "2.8.9"
"@microsoft/applicationinsights-shims" "^2.0.2"
"@microsoft/dynamicproto-js" "^1.1.7"
"@microsoft/1ds-post-js@^3.2.8":
version "3.2.8"
resolved "https://registry.yarnpkg.com/@microsoft/1ds-post-js/-/1ds-post-js-3.2.8.tgz#46793842cca161bf7a2a5b6053c349f429e55110"
integrity sha512-SjlRoNcXcXBH6WQD/5SkkaCHIVqldH3gDu+bI7YagrOVJ5APxwT1Duw9gm3L1FjFa9S2i81fvJ3EVSKpp9wULA==
dependencies:
"@microsoft/1ds-core-js" "3.2.8"
"@microsoft/applicationinsights-shims" "^2.0.2"
"@microsoft/dynamicproto-js" "^1.1.7"
"@microsoft/[email protected]":
version "2.8.9"
resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-channel-js/-/applicationinsights-channel-js-2.8.9.tgz#840656f3c716de8b3eb0a98c122aa1b92bb8ebfb"
integrity sha512-fMBsAEB7pWtPn43y72q9Xy5E5y55r6gMuDQqRRccccVoQDPXyS57VCj5IdATblctru0C6A8XpL2vRyNmEsu0Vg==
dependencies:
"@microsoft/applicationinsights-common" "2.8.9"
"@microsoft/applicationinsights-core-js" "2.8.9"
"@microsoft/applicationinsights-shims" "2.0.2"
"@microsoft/dynamicproto-js" "^1.1.7"
"@microsoft/[email protected]":
version "2.8.9"
resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-common/-/applicationinsights-common-2.8.9.tgz#a75e4a3143a7fd797687830c0ddd2069fd900827"
integrity sha512-mObn1moElyxZaGIRF/IU3cOaeKMgxghXnYEoHNUCA2e+rNwBIgxjyKkblFIpmGuHf4X7Oz3o3yBWpaC6AoMpig==
dependencies:
"@microsoft/applicationinsights-core-js" "2.8.9"
"@microsoft/applicationinsights-shims" "2.0.2"
"@microsoft/dynamicproto-js" "^1.1.7"
"@microsoft/[email protected]":
version "2.8.9"
resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-2.8.9.tgz#0e5d207acfae6986a6fc97249eeb6117e523bf1b"
integrity sha512-HRuIuZ6aOWezcg/G5VyFDDWGL8hDNe/ljPP01J7ImH2kRPEgbtcfPSUMjkamGMefgdq81GZsSoC/NNGTP4pp2w==
dependencies:
"@microsoft/applicationinsights-shims" "2.0.2"
"@microsoft/dynamicproto-js" "^1.1.7"
"@microsoft/[email protected]", "@microsoft/applicationinsights-shims@^2.0.2":
version "2.0.2"
resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-shims/-/applicationinsights-shims-2.0.2.tgz#92b36a09375e2d9cb2b4203383b05772be837085"
integrity sha512-PoHEgsnmcqruLNHZ/amACqdJ6YYQpED0KSRe6J7gIJTtpZC1FfFU9b1fmDKDKtFoUSrPzEh1qzO3kmRZP0betg==
"@microsoft/applicationinsights-web-basic@^2.8.9":
version "2.8.9"
resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-web-basic/-/applicationinsights-web-basic-2.8.9.tgz#eed2f3d1e19069962ed2155915c1656e6936e1d5"
integrity sha512-CH0J8JFOy7MjK8JO4pXXU+EML+Ilix+94PMZTX5EJlBU1in+mrik74/8qSg3UC4ekPi12KwrXaHCQSVC3WseXQ==
dependencies:
"@microsoft/applicationinsights-channel-js" "2.8.9"
"@microsoft/applicationinsights-common" "2.8.9"
"@microsoft/applicationinsights-core-js" "2.8.9"
"@microsoft/applicationinsights-shims" "2.0.2"
"@microsoft/dynamicproto-js" "^1.1.7"
"@microsoft/applicationinsights-web-snippet@^1.0.1":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-web-snippet/-/applicationinsights-web-snippet-1.0.1.tgz#6bb788b2902e48bf5d460c38c6bb7fedd686ddd7"
integrity sha512-2IHAOaLauc8qaAitvWS+U931T+ze+7MNWrDHY47IENP5y2UA0vqJDu67kWZDdpCN1fFC77sfgfB+HV7SrKshnQ==
"@microsoft/dynamicproto-js@^1.1.7":
version "1.1.7"
resolved "https://registry.yarnpkg.com/@microsoft/dynamicproto-js/-/dynamicproto-js-1.1.7.tgz#ede48dd3f85af14ee369c805e5ed5b84222b9fe2"
integrity sha512-SK3D3aVt+5vOOccKPnGaJWB5gQ8FuKfjboUJHedMP7gu54HqSCXX5iFXhktGD8nfJb0Go30eDvs/UDoTnR2kOA==
"@opentelemetry/api@^1.0.1", "@opentelemetry/api@^1.0.4":
version "1.2.0"
resolved "https://registry.yarnpkg.com/@opentelemetry/api/-/api-1.2.0.tgz#89ef99401cde6208cff98760b67663726ef26686"
integrity sha512-0nBr+VZNKm9tvNDZFstI3Pq1fCTEDK5OZTnVKNvBNAKgd0yIvmwsP4m61rEv7ZP+tOUjWJhROpxK5MsnlF911g==
"@opentelemetry/[email protected]", "@opentelemetry/core@^1.0.1":
version "1.7.0"
resolved "https://registry.yarnpkg.com/@opentelemetry/core/-/core-1.7.0.tgz#83bdd1b7a4ceafcdffd6590420657caec5f7b34c"
integrity sha512-AVqAi5uc8DrKJBimCTFUT4iFI+5eXpo4sYmGbQ0CypG0piOTHE2g9c5aSoTGYXu3CzOmJZf7pT6Xh+nwm5d6yQ==
dependencies:
"@opentelemetry/semantic-conventions" "1.7.0"
"@opentelemetry/[email protected]":
version "1.7.0"
resolved "https://registry.yarnpkg.com/@opentelemetry/resources/-/resources-1.7.0.tgz#90ccd3a6a86b4dfba4e833e73944bd64958d78c5"
integrity sha512-u1M0yZotkjyKx8dj+46Sg5thwtOTBmtRieNXqdCRiWUp6SfFiIP0bI+1XK3LhuXqXkBXA1awJZaTqKduNMStRg==
dependencies:
"@opentelemetry/core" "1.7.0"
"@opentelemetry/semantic-conventions" "1.7.0"
"@opentelemetry/sdk-trace-base@^1.0.1":
version "1.7.0"
resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.7.0.tgz#b498424e0c6340a9d80de63fd408c5c2130a60a5"
integrity sha512-Iz84C+FVOskmauh9FNnj4+VrA+hG5o+tkMzXuoesvSfunVSioXib0syVFeNXwOm4+M5GdWCuW632LVjqEXStIg==
dependencies:
"@opentelemetry/core" "1.7.0"
"@opentelemetry/resources" "1.7.0"
"@opentelemetry/semantic-conventions" "1.7.0"
"@opentelemetry/[email protected]", "@opentelemetry/semantic-conventions@^1.0.1":
version "1.7.0"
resolved "https://registry.yarnpkg.com/@opentelemetry/semantic-conventions/-/semantic-conventions-1.7.0.tgz#af80a1ef7cf110ea3a68242acd95648991bcd763"
integrity sha512-FGBx/Qd09lMaqQcogCHyYrFEpTx4cAjeS+48lMIR12z7LdH+zofGDVQSubN59nL6IpubfKqTeIDu9rNO28iHVA==
"@types/node-fetch@^2.5.0":
version "2.6.2"
resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.2.tgz#d1a9c5fd049d9415dce61571557104dec3ec81da"
integrity sha512-DHqhlq5jeESLy19TYhLakJ07kNumXWjcDdxXsLUMJZ6ue8VZJj4kLPQVE/2mdHh3xZziNF1xppu5lwmS53HR+A==
dependencies:
"@types/node" "*"
form-data "^3.0.0"
"@types/node@*":
version "18.11.9"
resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.9.tgz#02d013de7058cea16d36168ef2fc653464cfbad4"
integrity sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==
"@types/tunnel@^0.0.3":
version "0.0.3"
resolved "https://registry.yarnpkg.com/@types/tunnel/-/tunnel-0.0.3.tgz#f109e730b072b3136347561fc558c9358bb8c6e9"
integrity sha512-sOUTGn6h1SfQ+gbgqC364jLFBw2lnFqkgF3q0WovEHRLMrVD1sd5aufqi/aJObLekJO+Aq5z646U4Oxy6shXMA==
dependencies:
"@types/node" "*"
"@vscode/[email protected]":
version "0.7.1-preview"
resolved "https://registry.yarnpkg.com/@vscode/extension-telemetry/-/extension-telemetry-0.7.1-preview.tgz#1b954b8932b7f27a3993abda25299b8ba7f97233"
integrity sha512-7GdA8lMrcMhRfFxVpk7KBNbx+Bh/OpG702C1uPcyOQqp5lH1txJ/8SZAacFqFMKLRnBdGlJRKBREQe/Fs1X/eQ==
dependencies:
"@microsoft/1ds-core-js" "^3.2.8"
"@microsoft/1ds-post-js" "^3.2.8"
"@microsoft/applicationinsights-web-basic" "^2.8.9"
applicationinsights "2.3.6"
[email protected]:
version "2.3.6"
resolved "https://registry.yarnpkg.com/applicationinsights/-/applicationinsights-2.3.6.tgz#91277ce44e5f6d2f85336922c05d90f8699c2e70"
integrity sha512-ZzXXpZpDRGcy6Pp5V319nDF9/+Ey7jNknEXZyaBajtC5onN0dcBem6ng5jcb3MPH2AjYWRI8XgyNEuzP/6Y5/A==
dependencies:
"@azure/core-http" "^2.2.3"
"@microsoft/applicationinsights-web-snippet" "^1.0.1"
"@opentelemetry/api" "^1.0.4"
"@opentelemetry/core" "^1.0.1"
"@opentelemetry/sdk-trace-base" "^1.0.1"
"@opentelemetry/semantic-conventions" "^1.0.1"
cls-hooked "^4.2.2"
continuation-local-storage "^3.2.1"
diagnostic-channel "1.1.0"
diagnostic-channel-publishers "1.0.5"
async-hook-jl@^1.7.6:
version "1.7.6"
resolved "https://registry.yarnpkg.com/async-hook-jl/-/async-hook-jl-1.7.6.tgz#4fd25c2f864dbaf279c610d73bf97b1b28595e68"
integrity sha512-gFaHkFfSxTjvoxDMYqDuGHlcRyUuamF8s+ZTtJdDzqjws4mCt7v0vuV79/E2Wr2/riMQgtG4/yUtXWs1gZ7JMg==
dependencies:
stack-chain "^1.3.7"
async-listener@^0.6.0:
version "0.6.10"
resolved "https://registry.yarnpkg.com/async-listener/-/async-listener-0.6.10.tgz#a7c97abe570ba602d782273c0de60a51e3e17cbc"
integrity sha512-gpuo6xOyF4D5DE5WvyqZdPA3NGhiT6Qf07l7DCB0wwDEsLvDIbCr6j9S5aj5Ch96dLace5tXVzWBZkxU/c5ohw==
dependencies:
semver "^5.3.0"
shimmer "^1.1.0"
asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==
cls-hooked@^4.2.2:
version "4.2.2"
resolved "https://registry.yarnpkg.com/cls-hooked/-/cls-hooked-4.2.2.tgz#ad2e9a4092680cdaffeb2d3551da0e225eae1908"
integrity sha512-J4Xj5f5wq/4jAvcdgoGsL3G103BtWpZrMo8NEinRltN+xpTZdI+M38pyQqhuFU/P792xkMFvnKSf+Lm81U1bxw==
dependencies:
async-hook-jl "^1.7.6"
emitter-listener "^1.0.1"
semver "^5.4.1"
combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
dependencies:
delayed-stream "~1.0.0"
continuation-local-storage@^3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/continuation-local-storage/-/continuation-local-storage-3.2.1.tgz#11f613f74e914fe9b34c92ad2d28fe6ae1db7ffb"
integrity sha512-jx44cconVqkCEEyLSKWwkvUXwO561jXMa3LPjTPsm5QR22PA0/mhe33FT4Xb5y74JDvt/Cq+5lm8S8rskLv9ZA==
dependencies:
async-listener "^0.6.0"
emitter-listener "^1.1.1"
delayed-stream@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==
[email protected]:
version "1.0.5"
resolved "https://registry.yarnpkg.com/diagnostic-channel-publishers/-/diagnostic-channel-publishers-1.0.5.tgz#df8c317086c50f5727fdfb5d2fce214d2e4130ae"
integrity sha512-dJwUS0915pkjjimPJVDnS/QQHsH0aOYhnZsLJdnZIMOrB+csj8RnZhWTuwnm8R5v3Z7OZs+ksv5luC14DGB7eg==
[email protected]:
version "1.1.0"
resolved "https://registry.yarnpkg.com/diagnostic-channel/-/diagnostic-channel-1.1.0.tgz#6985e9dfedfbc072d91dc4388477e4087147756e"
integrity sha512-fwujyMe1gj6rk6dYi9hMZm0c8Mz8NDMVl2LB4iaYh3+LIAThZC8RKFGXWG0IML2OxAit/ZFRgZhMkhQ3d/bobQ==
dependencies:
semver "^5.3.0"
emitter-listener@^1.0.1, emitter-listener@^1.1.1:
version "1.1.2"
resolved "https://registry.yarnpkg.com/emitter-listener/-/emitter-listener-1.1.2.tgz#56b140e8f6992375b3d7cb2cab1cc7432d9632e8"
integrity sha512-Bt1sBAGFHY9DKY+4/2cV6izcKJUf5T7/gkdmkxzX/qv9CcGH8xSwVRW5mtX03SWJtRTWSOpzCuWN9rBFYZepZQ==
dependencies:
shimmer "^1.2.0"
form-data@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f"
integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
mime-types "^2.1.12"
form-data@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452"
integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
mime-types "^2.1.12"
[email protected]:
version "1.52.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70"
integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==
mime-types@^2.1.12:
version "2.1.35"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a"
integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==
dependencies:
mime-db "1.52.0"
node-fetch@^2.6.7:
version "2.6.7"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad"
integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==
dependencies:
whatwg-url "^5.0.0"
process@^0.11.10:
version "0.11.10"
resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182"
integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==
psl@^1.1.33:
version "1.9.0"
resolved "https://registry.yarnpkg.com/psl/-/psl-1.9.0.tgz#d0df2a137f00794565fcaf3b2c00cd09f8d5a5a7"
integrity sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==
punycode@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec"
integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==
querystringify@^2.1.1:
version "2.2.0"
resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-2.2.0.tgz#3345941b4153cb9d082d8eee4cda2016a9aef7f6"
integrity sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==
requires-port@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff"
integrity sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==
sax@>=0.6.0:
version "1.2.4"
resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9"
integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==
semver@^5.3.0, semver@^5.4.1:
version "5.7.1"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"
integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==
shimmer@^1.1.0, shimmer@^1.2.0:
version "1.2.1"
resolved "https://registry.yarnpkg.com/shimmer/-/shimmer-1.2.1.tgz#610859f7de327b587efebf501fb43117f9aff337"
integrity sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==
stack-chain@^1.3.7:
version "1.3.7"
resolved "https://registry.yarnpkg.com/stack-chain/-/stack-chain-1.3.7.tgz#d192c9ff4ea6a22c94c4dd459171e3f00cea1285"
integrity sha512-D8cWtWVdIe/jBA7v5p5Hwl5yOSOrmZPWDPe2KxQ5UAGD+nxbxU0lKXA4h85Ta6+qgdKVL3vUxsbIZjc1kBG7ug==
tough-cookie@^4.0.0:
version "4.1.2"
resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-4.1.2.tgz#e53e84b85f24e0b65dd526f46628db6c85f6b874"
integrity sha512-G9fqXWoYFZgTc2z8Q5zaHy/vJMjm+WV0AkAeHxVCQiEB1b+dGvWzFW6QV07cY5jQ5gRkeid2qIkzkxUnmoQZUQ==
dependencies:
psl "^1.1.33"
punycode "^2.1.1"
universalify "^0.2.0"
url-parse "^1.5.3"
tr46@~0.0.3:
version "0.0.3"
resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a"
integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==
tslib@^2.2.0:
version "2.4.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.4.1.tgz#0d0bfbaac2880b91e22df0768e55be9753a5b17e"
integrity sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==
tunnel@^0.0.6:
version "0.0.6"
resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c"
integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==
universalify@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.2.0.tgz#6451760566fa857534745ab1dde952d1b1761be0"
integrity sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==
url-parse@^1.5.3:
version "1.5.10"
resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.5.10.tgz#9d3c2f736c1d75dd3bd2be507dcc111f1e2ea9c1"
integrity sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==
dependencies:
querystringify "^2.1.1"
requires-port "^1.0.0"
uuid@^8.3.0:
version "8.3.2"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"
integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==
webidl-conversions@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871"
integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==
whatwg-url@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d"
integrity sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==
dependencies:
tr46 "~0.0.3"
webidl-conversions "^3.0.0"
xml2js@^0.4.19:
version "0.4.23"
resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.23.tgz#a0c69516752421eb2ac758ee4d4ccf58843eac66"
integrity sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==
dependencies:
sax ">=0.6.0"
xmlbuilder "~11.0.0"
xmlbuilder@~11.0.0:
version "11.0.1"
resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3"
integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==
| extensions/media-preview/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00017376898904331028,
0.00016908066754695028,
0.00016335624968633056,
0.00016946138930507004,
0.00000273652540272451
] |
{
"id": 11,
"code_window": [
"\t\t} else {\n",
"\t\t\tthis.template.message.removeAttribute('title');\n",
"\t\t}\n",
"\n",
"\t\tconst links = this.template.message.querySelectorAll('a');\n",
"\t\tfor (let i = 0; i < links.length; i++) {\n",
"\t\t\tlinks.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message\n",
"\t\t}\n",
"\n",
"\t\treturn messageOverflows;\n",
"\t}\n",
"\n",
"\tprivate renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 390
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { clearNode, addDisposableListener, EventType, EventHelper, $, EventLike } from 'vs/base/browser/dom';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ButtonBar, IButtonOptions } from 'vs/base/browser/ui/button/button';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionRunner, IAction, IActionRunner } from 'vs/base/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { dispose, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationViewItem, NotificationViewItem, NotificationViewItemContentChangeKind, INotificationMessage, ChoiceAction } from 'vs/workbench/common/notifications';
import { ClearNotificationAction, ExpandNotificationAction, CollapseNotificationAction, ConfigureNotificationAction } from 'vs/workbench/browser/parts/notifications/notificationsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { Severity } from 'vs/platform/notification/common/notification';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { DomEmitter } from 'vs/base/browser/event';
import { Gesture, EventType as GestureEventType } from 'vs/base/browser/touch';
import { Event } from 'vs/base/common/event';
import { defaultButtonStyles, defaultProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles';
export class NotificationsListDelegate implements IListVirtualDelegate<INotificationViewItem> {
private static readonly ROW_HEIGHT = 42;
private static readonly LINE_HEIGHT = 22;
private offsetHelper: HTMLElement;
constructor(container: HTMLElement) {
this.offsetHelper = this.createOffsetHelper(container);
}
private createOffsetHelper(container: HTMLElement): HTMLElement {
const offsetHelper = document.createElement('div');
offsetHelper.classList.add('notification-offset-helper');
container.appendChild(offsetHelper);
return offsetHelper;
}
getHeight(notification: INotificationViewItem): number {
if (!notification.expanded) {
return NotificationsListDelegate.ROW_HEIGHT; // return early if there are no more rows to show
}
// First row: message and actions
let expandedHeight = NotificationsListDelegate.ROW_HEIGHT;
// Dynamic height: if message overflows
const preferredMessageHeight = this.computePreferredHeight(notification);
const messageOverflows = NotificationsListDelegate.LINE_HEIGHT < preferredMessageHeight;
if (messageOverflows) {
const overflow = preferredMessageHeight - NotificationsListDelegate.LINE_HEIGHT;
expandedHeight += overflow;
}
// Last row: source and buttons if we have any
if (notification.source || isNonEmptyArray(notification.actions && notification.actions.primary)) {
expandedHeight += NotificationsListDelegate.ROW_HEIGHT;
}
// If the expanded height is same as collapsed, unset the expanded state
// but skip events because there is no change that has visual impact
if (expandedHeight === NotificationsListDelegate.ROW_HEIGHT) {
notification.collapse(true /* skip events, no change in height */);
}
return expandedHeight;
}
private computePreferredHeight(notification: INotificationViewItem): number {
// Prepare offset helper depending on toolbar actions count
let actions = 1; // close
if (notification.canCollapse) {
actions++; // expand/collapse
}
if (isNonEmptyArray(notification.actions && notification.actions.secondary)) {
actions++; // secondary actions
}
this.offsetHelper.style.width = `${450 /* notifications container width */ - (10 /* padding */ + 26 /* severity icon */ + (actions * (24 + 8)) /* 24px (+8px padding) per action */ - 4 /* 4px less padding for last action */)}px`;
// Render message into offset helper
const renderedMessage = NotificationMessageRenderer.render(notification.message);
this.offsetHelper.appendChild(renderedMessage);
// Compute height
const preferredHeight = Math.max(this.offsetHelper.offsetHeight, this.offsetHelper.scrollHeight);
// Always clear offset helper after use
clearNode(this.offsetHelper);
return preferredHeight;
}
getTemplateId(element: INotificationViewItem): string {
if (element instanceof NotificationViewItem) {
return NotificationRenderer.TEMPLATE_ID;
}
throw new Error('unknown element type: ' + element);
}
}
export interface INotificationTemplateData {
container: HTMLElement;
toDispose: DisposableStore;
mainRow: HTMLElement;
icon: HTMLElement;
message: HTMLElement;
toolbar: ActionBar;
detailsRow: HTMLElement;
source: HTMLElement;
buttonsContainer: HTMLElement;
progress: ProgressBar;
renderer: NotificationTemplateRenderer;
}
interface IMessageActionHandler {
callback: (href: string) => void;
toDispose: DisposableStore;
}
class NotificationMessageRenderer {
static render(message: INotificationMessage, actionHandler?: IMessageActionHandler): HTMLElement {
const messageContainer = document.createElement('span');
for (const node of message.linkedText.nodes) {
if (typeof node === 'string') {
messageContainer.appendChild(document.createTextNode(node));
} else {
let title = node.title;
if (!title && node.href.startsWith('command:')) {
title = localize('executeCommand', "Click to execute command '{0}'", node.href.substr('command:'.length));
} else if (!title) {
title = node.href;
}
const anchor = $('a', { href: node.href, title: title, }, node.label);
if (actionHandler) {
const onPointer = (e: EventLike) => {
EventHelper.stop(e, true);
actionHandler.callback(node.href);
};
const onClick = actionHandler.toDispose.add(new DomEmitter(anchor, 'click')).event;
actionHandler.toDispose.add(Gesture.addTarget(anchor));
const onTap = actionHandler.toDispose.add(new DomEmitter(anchor, GestureEventType.Tap)).event;
Event.any(onClick, onTap)(onPointer, null, actionHandler.toDispose);
}
messageContainer.appendChild(anchor);
}
}
return messageContainer;
}
}
export class NotificationRenderer implements IListRenderer<INotificationViewItem, INotificationTemplateData> {
static readonly TEMPLATE_ID = 'notification';
constructor(
private actionRunner: IActionRunner,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
get templateId() {
return NotificationRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): INotificationTemplateData {
const data: INotificationTemplateData = Object.create(null);
data.toDispose = new DisposableStore();
// Container
data.container = document.createElement('div');
data.container.classList.add('notification-list-item');
// Main Row
data.mainRow = document.createElement('div');
data.mainRow.classList.add('notification-list-item-main-row');
// Icon
data.icon = document.createElement('div');
data.icon.classList.add('notification-list-item-icon', 'codicon');
// Message
data.message = document.createElement('div');
data.message.classList.add('notification-list-item-message');
// Toolbar
const toolbarContainer = document.createElement('div');
toolbarContainer.classList.add('notification-list-item-toolbar-container');
data.toolbar = new ActionBar(
toolbarContainer,
{
ariaLabel: localize('notificationActions', "Notification Actions"),
actionViewItemProvider: action => {
if (action && action instanceof ConfigureNotificationAction) {
const item = new DropdownMenuActionViewItem(action, action.configurationActions, this.contextMenuService, { actionRunner: this.actionRunner, classNames: action.class });
data.toDispose.add(item);
return item;
}
return undefined;
},
actionRunner: this.actionRunner
}
);
data.toDispose.add(data.toolbar);
// Details Row
data.detailsRow = document.createElement('div');
data.detailsRow.classList.add('notification-list-item-details-row');
// Source
data.source = document.createElement('div');
data.source.classList.add('notification-list-item-source');
// Buttons Container
data.buttonsContainer = document.createElement('div');
data.buttonsContainer.classList.add('notification-list-item-buttons-container');
container.appendChild(data.container);
// the details row appears first in order for better keyboard access to notification buttons
data.container.appendChild(data.detailsRow);
data.detailsRow.appendChild(data.source);
data.detailsRow.appendChild(data.buttonsContainer);
// main row
data.container.appendChild(data.mainRow);
data.mainRow.appendChild(data.icon);
data.mainRow.appendChild(data.message);
data.mainRow.appendChild(toolbarContainer);
// Progress: below the rows to span the entire width of the item
data.progress = new ProgressBar(container, defaultProgressBarStyles);
data.toDispose.add(data.progress);
// Renderer
data.renderer = this.instantiationService.createInstance(NotificationTemplateRenderer, data, this.actionRunner);
data.toDispose.add(data.renderer);
return data;
}
renderElement(notification: INotificationViewItem, index: number, data: INotificationTemplateData): void {
data.renderer.setInput(notification);
}
disposeTemplate(templateData: INotificationTemplateData): void {
dispose(templateData.toDispose);
}
}
export class NotificationTemplateRenderer extends Disposable {
private static closeNotificationAction: ClearNotificationAction;
private static expandNotificationAction: ExpandNotificationAction;
private static collapseNotificationAction: CollapseNotificationAction;
private static readonly SEVERITIES = [Severity.Info, Severity.Warning, Severity.Error];
private readonly inputDisposables = this._register(new DisposableStore());
constructor(
private template: INotificationTemplateData,
private actionRunner: IActionRunner,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
) {
super();
if (!NotificationTemplateRenderer.closeNotificationAction) {
NotificationTemplateRenderer.closeNotificationAction = instantiationService.createInstance(ClearNotificationAction, ClearNotificationAction.ID, ClearNotificationAction.LABEL);
NotificationTemplateRenderer.expandNotificationAction = instantiationService.createInstance(ExpandNotificationAction, ExpandNotificationAction.ID, ExpandNotificationAction.LABEL);
NotificationTemplateRenderer.collapseNotificationAction = instantiationService.createInstance(CollapseNotificationAction, CollapseNotificationAction.ID, CollapseNotificationAction.LABEL);
}
}
setInput(notification: INotificationViewItem): void {
this.inputDisposables.clear();
this.render(notification);
}
private render(notification: INotificationViewItem): void {
// Container
this.template.container.classList.toggle('expanded', notification.expanded);
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.MOUSE_UP, e => {
if (e.button === 1 /* Middle Button */) {
// Prevent firing the 'paste' event in the editor textarea - #109322
EventHelper.stop(e, true);
}
}));
this.inputDisposables.add(addDisposableListener(this.template.container, EventType.AUXCLICK, e => {
if (!notification.hasProgress && e.button === 1 /* Middle Button */) {
EventHelper.stop(e, true);
notification.close();
}
}));
// Severity Icon
this.renderSeverity(notification);
// Message
const messageOverflows = this.renderMessage(notification);
// Secondary Actions
this.renderSecondaryActions(notification, messageOverflows);
// Source
this.renderSource(notification);
// Buttons
this.renderButtons(notification);
// Progress
this.renderProgress(notification);
// Label Change Events that we can handle directly
// (changes to actions require an entire redraw of
// the notification because it has an impact on
// epxansion state)
this.inputDisposables.add(notification.onDidChangeContent(event => {
switch (event.kind) {
case NotificationViewItemContentChangeKind.SEVERITY:
this.renderSeverity(notification);
break;
case NotificationViewItemContentChangeKind.PROGRESS:
this.renderProgress(notification);
break;
case NotificationViewItemContentChangeKind.MESSAGE:
this.renderMessage(notification);
break;
}
}));
}
private renderSeverity(notification: INotificationViewItem): void {
// first remove, then set as the codicon class names overlap
NotificationTemplateRenderer.SEVERITIES.forEach(severity => {
if (notification.severity !== severity) {
this.template.icon.classList.remove(...this.toSeverityIcon(severity).classNamesArray);
}
});
this.template.icon.classList.add(...this.toSeverityIcon(notification.severity).classNamesArray);
}
private renderMessage(notification: INotificationViewItem): boolean {
clearNode(this.template.message);
this.template.message.appendChild(NotificationMessageRenderer.render(notification.message, {
callback: link => this.openerService.open(URI.parse(link), { allowCommands: true }),
toDispose: this.inputDisposables
}));
const messageOverflows = notification.canCollapse && !notification.expanded && this.template.message.scrollWidth > this.template.message.clientWidth;
if (messageOverflows) {
this.template.message.title = this.template.message.textContent + '';
} else {
this.template.message.removeAttribute('title');
}
const links = this.template.message.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
links.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message
}
return messageOverflows;
}
private renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {
const actions: IAction[] = [];
// Secondary Actions
const secondaryActions = notification.actions ? notification.actions.secondary : undefined;
if (isNonEmptyArray(secondaryActions)) {
const configureNotificationAction = this.instantiationService.createInstance(ConfigureNotificationAction, ConfigureNotificationAction.ID, ConfigureNotificationAction.LABEL, secondaryActions);
actions.push(configureNotificationAction);
this.inputDisposables.add(configureNotificationAction);
}
// Expand / Collapse
let showExpandCollapseAction = false;
if (notification.canCollapse) {
if (notification.expanded) {
showExpandCollapseAction = true; // allow to collapse an expanded message
} else if (notification.source) {
showExpandCollapseAction = true; // allow to expand to details row
} else if (messageOverflows) {
showExpandCollapseAction = true; // allow to expand if message overflows
}
}
if (showExpandCollapseAction) {
actions.push(notification.expanded ? NotificationTemplateRenderer.collapseNotificationAction : NotificationTemplateRenderer.expandNotificationAction);
}
// Close (unless progress is showing)
if (!notification.hasProgress) {
actions.push(NotificationTemplateRenderer.closeNotificationAction);
}
this.template.toolbar.clear();
this.template.toolbar.context = notification;
actions.forEach(action => this.template.toolbar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) }));
}
private renderSource(notification: INotificationViewItem): void {
if (notification.expanded && notification.source) {
this.template.source.textContent = localize('notificationSource', "Source: {0}", notification.source);
this.template.source.title = notification.source;
} else {
this.template.source.textContent = '';
this.template.source.removeAttribute('title');
}
}
private renderButtons(notification: INotificationViewItem): void {
clearNode(this.template.buttonsContainer);
const primaryActions = notification.actions ? notification.actions.primary : undefined;
if (notification.expanded && isNonEmptyArray(primaryActions)) {
const that = this;
const actionRunner: IActionRunner = new class extends ActionRunner {
protected override async runAction(action: IAction): Promise<void> {
// Run action
that.actionRunner.run(action, notification);
// Hide notification (unless explicitly prevented)
if (!(action instanceof ChoiceAction) || !action.keepOpen) {
notification.close();
}
}
}();
const buttonToolbar = this.inputDisposables.add(new ButtonBar(this.template.buttonsContainer));
for (let i = 0; i < primaryActions.length; i++) {
const action = primaryActions[i];
const options: IButtonOptions = {
title: true, // assign titles to buttons in case they overflow
secondary: i > 0,
...defaultButtonStyles
};
const dropdownActions = action instanceof ChoiceAction ? action.menu : undefined;
const button = this.inputDisposables.add(dropdownActions ?
buttonToolbar.addButtonWithDropdown({
...options,
contextMenuProvider: this.contextMenuService,
actions: dropdownActions,
actionRunner
}) :
buttonToolbar.addButton(options)
);
button.label = action.label;
this.inputDisposables.add(button.onDidClick(e => {
if (e) {
EventHelper.stop(e, true);
}
actionRunner.run(action);
}));
}
}
}
private renderProgress(notification: INotificationViewItem): void {
// Return early if the item has no progress
if (!notification.hasProgress) {
this.template.progress.stop().hide();
return;
}
// Infinite
const state = notification.progress.state;
if (state.infinite) {
this.template.progress.infinite().show();
}
// Total / Worked
else if (typeof state.total === 'number' || typeof state.worked === 'number') {
if (typeof state.total === 'number' && !this.template.progress.hasTotal()) {
this.template.progress.total(state.total);
}
if (typeof state.worked === 'number') {
this.template.progress.setWorked(state.worked).show();
}
}
// Done
else {
this.template.progress.done().hide();
}
}
private toSeverityIcon(severity: Severity): Codicon {
switch (severity) {
case Severity.Warning:
return Codicon.warning;
case Severity.Error:
return Codicon.error;
}
return Codicon.info;
}
private getKeybindingLabel(action: IAction): string | null {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
return keybinding ? keybinding.getLabel() : null;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsViewer.ts | 1 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.9982630610466003,
0.03783338889479637,
0.00016168200818356127,
0.00021096126874908805,
0.1857001781463623
] |
{
"id": 11,
"code_window": [
"\t\t} else {\n",
"\t\t\tthis.template.message.removeAttribute('title');\n",
"\t\t}\n",
"\n",
"\t\tconst links = this.template.message.querySelectorAll('a');\n",
"\t\tfor (let i = 0; i < links.length; i++) {\n",
"\t\t\tlinks.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message\n",
"\t\t}\n",
"\n",
"\t\treturn messageOverflows;\n",
"\t}\n",
"\n",
"\tprivate renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 390
} | {
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out",
"experimentalDecorators": true,
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"src/**/*",
"../../src/vscode-dts/vscode.d.ts"
]
}
| extensions/git-base/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001713379315333441,
0.00016949884593486786,
0.00016765977488830686,
0.00016949884593486786,
0.000001839078322518617
] |
{
"id": 11,
"code_window": [
"\t\t} else {\n",
"\t\t\tthis.template.message.removeAttribute('title');\n",
"\t\t}\n",
"\n",
"\t\tconst links = this.template.message.querySelectorAll('a');\n",
"\t\tfor (let i = 0; i < links.length; i++) {\n",
"\t\t\tlinks.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message\n",
"\t\t}\n",
"\n",
"\t\treturn messageOverflows;\n",
"\t}\n",
"\n",
"\tprivate renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 390
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { ActionBar, IActionViewItemProvider } from 'vs/base/browser/ui/actionbar/actionbar';
import { IAction } from 'vs/base/common/actions';
import { ResolvedKeybinding } from 'vs/base/common/keybindings';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { suggestWidgetStatusbarMenu } from 'vs/editor/contrib/suggest/browser/suggest';
import { localize } from 'vs/nls';
import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IMenuService, MenuItemAction } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
class StatusBarViewItem extends MenuEntryActionViewItem {
protected override updateLabel() {
const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
if (!kb) {
return super.updateLabel();
}
if (this.label) {
this.label.textContent = localize('ddd', '{0} ({1})', this._action.label, StatusBarViewItem.symbolPrintEnter(kb));
}
}
static symbolPrintEnter(kb: ResolvedKeybinding) {
return kb.getLabel()?.replace(/\benter\b/gi, '\u23CE');
}
}
export class SuggestWidgetStatus {
readonly element: HTMLElement;
private readonly _leftActions: ActionBar;
private readonly _rightActions: ActionBar;
private readonly _menuDisposables = new DisposableStore();
constructor(
container: HTMLElement,
@IInstantiationService instantiationService: IInstantiationService,
@IMenuService private _menuService: IMenuService,
@IContextKeyService private _contextKeyService: IContextKeyService,
) {
this.element = dom.append(container, dom.$('.suggest-status-bar'));
const actionViewItemProvider = <IActionViewItemProvider>(action => {
return action instanceof MenuItemAction ? instantiationService.createInstance(StatusBarViewItem, action, undefined) : undefined;
});
this._leftActions = new ActionBar(this.element, { actionViewItemProvider });
this._rightActions = new ActionBar(this.element, { actionViewItemProvider });
this._leftActions.domNode.classList.add('left');
this._rightActions.domNode.classList.add('right');
}
dispose(): void {
this._menuDisposables.dispose();
this.element.remove();
}
show(): void {
const menu = this._menuService.createMenu(suggestWidgetStatusbarMenu, this._contextKeyService);
const renderMenu = () => {
const left: IAction[] = [];
const right: IAction[] = [];
for (const [group, actions] of menu.getActions()) {
if (group === 'left') {
left.push(...actions);
} else {
right.push(...actions);
}
}
this._leftActions.clear();
this._leftActions.push(left);
this._rightActions.clear();
this._rightActions.push(right);
};
this._menuDisposables.add(menu.onDidChange(() => renderMenu()));
this._menuDisposables.add(menu);
}
hide(): void {
this._menuDisposables.clear();
}
}
| src/vs/editor/contrib/suggest/browser/suggestWidgetStatus.ts | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.0001767442881828174,
0.0001676304527791217,
0.00016381623572669923,
0.00016599131049588323,
0.000003826877218671143
] |
{
"id": 11,
"code_window": [
"\t\t} else {\n",
"\t\t\tthis.template.message.removeAttribute('title');\n",
"\t\t}\n",
"\n",
"\t\tconst links = this.template.message.querySelectorAll('a');\n",
"\t\tfor (let i = 0; i < links.length; i++) {\n",
"\t\t\tlinks.item(i).tabIndex = -1; // prevent keyboard navigation to links to allow for better keyboard support within a message\n",
"\t\t}\n",
"\n",
"\t\treturn messageOverflows;\n",
"\t}\n",
"\n",
"\tprivate renderSecondaryActions(notification: INotificationViewItem, messageOverflows: boolean): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/parts/notifications/notificationsViewer.ts",
"type": "replace",
"edit_start_line_idx": 390
} | {
"version": "0.2.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceFolder}/out",
"preLaunchTask": "npm"
}
]
} | extensions/python/.vscode/launch.json | 0 | https://github.com/microsoft/vscode/commit/9df51e1cdd092547d41c7f2d37d51c73980460bc | [
0.00016982412489596754,
0.00016921423957683146,
0.00016860435425769538,
0.00016921423957683146,
6.098853191360831e-7
] |
{
"id": 0,
"code_window": [
" runs-on: ubuntu-latest\n",
" needs: ['buildPR', 'buildBase']\n",
" env:\n",
" GITHUB_STEP_NUMBER: 7\n",
"\n",
" steps:\n",
" - uses: actions/checkout@v3\n",
"\n",
" - name: Get built packages from pr\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GITHUB_STEP_NUMBER: 8\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 110
} | # Only runs if anything under the packages/ directory changes.
# (Otherwise detect-breaking-changes-build-skip.yml takes over)
name: Levitate / Detect breaking changes
on:
pull_request:
paths:
- 'packages/**'
jobs:
buildPR:
name: Build PR
runs-on: ubuntu-latest
defaults:
run:
working-directory: './pr'
steps:
- uses: actions/checkout@v3
with:
path: './pr'
- uses: actions/[email protected]
with:
node-version: 16.16.0
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT
- name: Restore yarn cache
uses: actions/[email protected]
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-cache-folder-${{ hashFiles('**/yarn.lock', '.yarnrc.yml') }}
restore-keys: |
yarn-cache-folder-
- name: Install dependencies
run: yarn install --immutable
- name: Build packages
run: yarn packages:build
- name: Pack packages
run: yarn packages:pack --out ./%s.tgz
- name: Zip built tarballed packages
run: zip -r ./pr_built_packages.zip ./packages/**/*.tgz
- name: Upload build output as artifact
uses: actions/upload-artifact@v3
with:
name: buildPr
path: './pr/pr_built_packages.zip'
buildBase:
name: Build Base
runs-on: ubuntu-latest
defaults:
run:
working-directory: './base'
steps:
- uses: actions/checkout@v3
with:
path: './base'
ref: ${{ github.event.pull_request.base.ref }}
- uses: actions/[email protected]
with:
node-version: 16.16.0
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT
- name: Restore yarn cache
uses: actions/[email protected]
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-cache-folder-${{ hashFiles('**/yarn.lock', '.yarnrc.yml') }}
restore-keys: |
yarn-cache-folder-
- name: Install dependencies
run: yarn install --immutable
- name: Build packages
run: yarn packages:build
- name: Pack packages
run: yarn packages:pack --out ./%s.tgz
- name: Zip built tarballed packages
run: zip -r ./base_built_packages.zip ./packages/**/*.tgz
- name: Upload build output as artifact
uses: actions/upload-artifact@v3
with:
name: buildBase
path: './base/base_built_packages.zip'
Detect:
name: Detect breaking changes
runs-on: ubuntu-latest
needs: ['buildPR', 'buildBase']
env:
GITHUB_STEP_NUMBER: 7
steps:
- uses: actions/checkout@v3
- name: Get built packages from pr
uses: actions/download-artifact@v3
with:
name: buildPr
- name: Get built packages from base
uses: actions/download-artifact@v3
with:
name: buildBase
- name: Unzip artifact from pr
run: unzip -j pr_built_packages.zip -d ./pr && rm pr_built_packages.zip
- name: Unzip artifact from base
run: unzip -j base_built_packages.zip -d ./base && rm base_built_packages.zip
- name: Get link for the Github Action job
id: job
uses: actions/github-script@v6
with:
script: |
const script = require('./.github/workflows/scripts/pr-get-job-link.js')
await script({github, context, core})
- name: Detect breaking changes
id: breaking-changes
run: ./scripts/check-breaking-changes.sh
env:
FORCE_COLOR: 3
GITHUB_JOB_LINK: ${{ steps.job.outputs.link }}
- name: Persisting the check output
run: |
mkdir -p ./levitate
echo "{ \"exit_code\": ${{ steps.breaking-changes.outputs.is_breaking }}, \"message\": \"${{ steps.breaking-changes.outputs.message }}\", \"job_link\": \"${{ steps.job.outputs.link }}#step:${GITHUB_STEP_NUMBER}:1\", \"pr_number\": \"${{ github.event.pull_request.number }}\" }" > ./levitate/result.json
- name: Upload check output as artifact
uses: actions/upload-artifact@v3
with:
name: levitate
path: levitate/
- name: Exit
run: exit ${{ steps.breaking-changes.outputs.is_breaking }}
shell: bash
| .github/workflows/detect-breaking-changes-build.yml | 1 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.040325652807950974,
0.00461092172190547,
0.00017752325220499188,
0.0005751746939495206,
0.009529130533337593
] |
{
"id": 0,
"code_window": [
" runs-on: ubuntu-latest\n",
" needs: ['buildPR', 'buildBase']\n",
" env:\n",
" GITHUB_STEP_NUMBER: 7\n",
"\n",
" steps:\n",
" - uses: actions/checkout@v3\n",
"\n",
" - name: Get built packages from pr\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GITHUB_STEP_NUMBER: 8\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 110
} | import { Meta, Preview, Props } from '@storybook/addon-docs/blocks';
import { PanelContainer } from './PanelContainer';
<Meta title="MDX|PanelContainer" component={PanelContainer} />
# PanelContainer
The PanelContainer is used as a simple background for storing other components.
| packages/grafana-ui/src/components/PanelContainer/PanelContainer.mdx | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.0001738279970595613,
0.0001738279970595613,
0.0001738279970595613,
0.0001738279970595613,
0
] |
{
"id": 0,
"code_window": [
" runs-on: ubuntu-latest\n",
" needs: ['buildPR', 'buildBase']\n",
" env:\n",
" GITHUB_STEP_NUMBER: 7\n",
"\n",
" steps:\n",
" - uses: actions/checkout@v3\n",
"\n",
" - name: Get built packages from pr\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GITHUB_STEP_NUMBER: 8\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 110
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M17.34,5.46h0a1.2,1.2,0,1,0,1.2,1.2A1.2,1.2,0,0,0,17.34,5.46Zm4.6,2.42a7.59,7.59,0,0,0-.46-2.43,4.94,4.94,0,0,0-1.16-1.77,4.7,4.7,0,0,0-1.77-1.15,7.3,7.3,0,0,0-2.43-.47C15.06,2,14.72,2,12,2s-3.06,0-4.12.06a7.3,7.3,0,0,0-2.43.47A4.78,4.78,0,0,0,3.68,3.68,4.7,4.7,0,0,0,2.53,5.45a7.3,7.3,0,0,0-.47,2.43C2,8.94,2,9.28,2,12s0,3.06.06,4.12a7.3,7.3,0,0,0,.47,2.43,4.7,4.7,0,0,0,1.15,1.77,4.78,4.78,0,0,0,1.77,1.15,7.3,7.3,0,0,0,2.43.47C8.94,22,9.28,22,12,22s3.06,0,4.12-.06a7.3,7.3,0,0,0,2.43-.47,4.7,4.7,0,0,0,1.77-1.15,4.85,4.85,0,0,0,1.16-1.77,7.59,7.59,0,0,0,.46-2.43c0-1.06.06-1.4.06-4.12S22,8.94,21.94,7.88ZM20.14,16a5.61,5.61,0,0,1-.34,1.86,3.06,3.06,0,0,1-.75,1.15,3.19,3.19,0,0,1-1.15.75,5.61,5.61,0,0,1-1.86.34c-1,.05-1.37.06-4,.06s-3,0-4-.06A5.73,5.73,0,0,1,6.1,19.8,3.27,3.27,0,0,1,5,19.05a3,3,0,0,1-.74-1.15A5.54,5.54,0,0,1,3.86,16c0-1-.06-1.37-.06-4s0-3,.06-4A5.54,5.54,0,0,1,4.21,6.1,3,3,0,0,1,5,5,3.14,3.14,0,0,1,6.1,4.2,5.73,5.73,0,0,1,8,3.86c1,0,1.37-.06,4-.06s3,0,4,.06a5.61,5.61,0,0,1,1.86.34A3.06,3.06,0,0,1,19.05,5,3.06,3.06,0,0,1,19.8,6.1,5.61,5.61,0,0,1,20.14,8c.05,1,.06,1.37.06,4S20.19,15,20.14,16ZM12,6.87A5.13,5.13,0,1,0,17.14,12,5.12,5.12,0,0,0,12,6.87Zm0,8.46A3.33,3.33,0,1,1,15.33,12,3.33,3.33,0,0,1,12,15.33Z"/></svg> | public/img/icons/unicons/instagram.svg | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00017048722656909376,
0.00017048722656909376,
0.00017048722656909376,
0.00017048722656909376,
0
] |
{
"id": 0,
"code_window": [
" runs-on: ubuntu-latest\n",
" needs: ['buildPR', 'buildBase']\n",
" env:\n",
" GITHUB_STEP_NUMBER: 7\n",
"\n",
" steps:\n",
" - uses: actions/checkout@v3\n",
"\n",
" - name: Get built packages from pr\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GITHUB_STEP_NUMBER: 8\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 110
} | export * from './dataSourcesMocks';
export * from './store.navIndex.mock';
| public/app/features/datasources/__mocks__/index.ts | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00017440973897464573,
0.00017440973897464573,
0.00017440973897464573,
0.00017440973897464573,
0
] |
{
"id": 1,
"code_window": [
" - name: Get link for the Github Action job\n",
" id: job\n",
" uses: actions/github-script@v6\n",
" with:\n",
" script: |\n",
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const name = 'Detect breaking changes';\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "add",
"edit_start_line_idx": 136
} |
module.exports = async ({ github, context, core }) => {
const { owner, repo } = context.repo;
const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`
const result = await github.request(url)
const link = `https://github.com/grafana/grafana/runs/${result.data.jobs[0].id}?check_suite_focus=true`;
core.setOutput('link', link);
} | .github/workflows/scripts/pr-get-job-link.js | 1 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00030012751813046634,
0.00030012751813046634,
0.00030012751813046634,
0.00030012751813046634,
0
] |
{
"id": 1,
"code_window": [
" - name: Get link for the Github Action job\n",
" id: job\n",
" uses: actions/github-script@v6\n",
" with:\n",
" script: |\n",
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const name = 'Detect breaking changes';\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "add",
"edit_start_line_idx": 136
} | {
"size": 0,
"query": {
"bool": {
"filter": {
"range": {
"testtime": {
"gte": 1668422437218,
"lte": 1668422625668,
"format": "epoch_millis"
}
}
}
}
},
"aggs": {
"2": {
"date_histogram": {
"field": "testtime",
"min_doc_count": 0,
"extended_bounds": {
"min": 1668422437218,
"max": 1668422625668
},
"format": "epoch_millis",
"fixed_interval": "1000ms"
},
"aggs": {
"1": {
"min": {
"field": "float"
}
}
}
}
}
}
| pkg/tsdb/elasticsearch/testdata_request/metric_multi.request.line2.json | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00017292356642428786,
0.00017215627303812653,
0.00017106007726397365,
0.0001723207242321223,
7.763885037093132e-7
] |
{
"id": 1,
"code_window": [
" - name: Get link for the Github Action job\n",
" id: job\n",
" uses: actions/github-script@v6\n",
" with:\n",
" script: |\n",
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const name = 'Detect breaking changes';\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "add",
"edit_start_line_idx": 136
} | <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M3,7h18c0.6,0,1-0.4,1-1s-0.4-1-1-1H3C2.4,5,2,5.4,2,6S2.4,7,3,7z M21,9H7c-0.6,0-1,0.4-1,1s0.4,1,1,1h14c0.6,0,1-0.4,1-1S21.6,9,21,9z M21,13H3c-0.6,0-1,0.4-1,1s0.4,1,1,1h18c0.6,0,1-0.4,1-1S21.6,13,21,13z M21,17H7c-0.6,0-1,0.4-1,1s0.4,1,1,1h14c0.6,0,1-0.4,1-1S21.6,17,21,17z"/></svg> | public/img/icons/solid/align-right.svg | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.0001722380256978795,
0.0001722380256978795,
0.0001722380256978795,
0.0001722380256978795,
0
] |
{
"id": 1,
"code_window": [
" - name: Get link for the Github Action job\n",
" id: job\n",
" uses: actions/github-script@v6\n",
" with:\n",
" script: |\n",
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" const name = 'Detect breaking changes';\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "add",
"edit_start_line_idx": 136
} | // 🌟 This was machine generated. Do not edit. 🌟
//
// Frame[0] {
// "type": "timeseries-wide",
// "custom": {
// "resultType": "matrix"
// },
// "executedQueryString": "Expr: \nStep: 1s"
// }
// Name:
// Dimensions: 3 Fields by 4 Rows
// +-----------------------------------+--------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------+
// | Name: Time | Name: prometheus_http_requests_total{code="200", handler="/api/v1/query_range", job="prometheus"} | Name: prometheus_http_requests_total{code="400", handler="/api/v1/query_range", job="prometheus"} |
// | Labels: | Labels: __name__=prometheus_http_requests_total, code=200, handler=/api/v1/query_range, job=prometheus | Labels: __name__=prometheus_http_requests_total, code=400, handler=/api/v1/query_range, job=prometheus |
// | Type: []time.Time | Type: []*float64 | Type: []*float64 |
// +-----------------------------------+--------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------+
// | 2022-01-11 08:25:29.123 +0000 UTC | null | 54 |
// | 2022-01-11 08:25:30.123 +0000 UTC | 21 | null |
// | 2022-01-11 08:25:31.123 +0000 UTC | 32 | null |
// | 2022-01-11 08:25:32.123 +0000 UTC | 43 | 76 |
// +-----------------------------------+--------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------+
//
//
// 🌟 This was machine generated. Do not edit. 🌟
{
"status": 200,
"frames": [
{
"schema": {
"meta": {
"type": "timeseries-wide",
"custom": {
"resultType": "matrix"
},
"executedQueryString": "Expr: \nStep: 1s"
},
"fields": [
{
"name": "Time",
"type": "time",
"typeInfo": {
"frame": "time.Time"
},
"config": {
"interval": 1000
}
},
{
"name": "prometheus_http_requests_total{code=\"200\", handler=\"/api/v1/query_range\", job=\"prometheus\"}",
"type": "number",
"typeInfo": {
"frame": "float64",
"nullable": true
},
"labels": {
"__name__": "prometheus_http_requests_total",
"code": "200",
"handler": "/api/v1/query_range",
"job": "prometheus"
}
},
{
"name": "prometheus_http_requests_total{code=\"400\", handler=\"/api/v1/query_range\", job=\"prometheus\"}",
"type": "number",
"typeInfo": {
"frame": "float64",
"nullable": true
},
"labels": {
"__name__": "prometheus_http_requests_total",
"code": "400",
"handler": "/api/v1/query_range",
"job": "prometheus"
}
}
]
},
"data": {
"values": [
[
1641889529123,
1641889530123,
1641889531123,
1641889532123
],
[
null,
21,
32,
43
],
[
54,
null,
null,
76
]
]
}
}
]
} | pkg/tsdb/prometheus/testdata/range_simple.result.streaming-wide.golden.jsonc | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00017648511857260019,
0.00017189551726914942,
0.0001660652196733281,
0.0001715283578960225,
0.0000032490909234184073
] |
{
"id": 2,
"code_window": [
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n",
" await script({github, context, core})\n",
"\n",
" - name: Detect breaking changes\n",
" id: breaking-changes\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await script({name, github, context, core})\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 137
} |
module.exports = async ({ github, context, core }) => {
const { owner, repo } = context.repo;
const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`
const result = await github.request(url)
const link = `https://github.com/grafana/grafana/runs/${result.data.jobs[0].id}?check_suite_focus=true`;
core.setOutput('link', link);
} | .github/workflows/scripts/pr-get-job-link.js | 1 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.0003926902136299759,
0.0003926902136299759,
0.0003926902136299759,
0.0003926902136299759,
0
] |
{
"id": 2,
"code_window": [
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n",
" await script({github, context, core})\n",
"\n",
" - name: Detect breaking changes\n",
" id: breaking-changes\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await script({name, github, context, core})\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 137
} | package datasources
import "errors"
var (
ErrDataSourceNotFound = errors.New("data source not found")
ErrDataSourceNameExists = errors.New("data source with the same name already exists")
ErrDataSourceUidExists = errors.New("data source with the same uid already exists")
ErrDataSourceUpdatingOldVersion = errors.New("trying to update old version of datasource")
ErrDataSourceAccessDenied = errors.New("data source access denied")
ErrDataSourceFailedGenerateUniqueUid = errors.New("failed to generate unique datasource ID")
ErrDataSourceIdentifierNotSet = errors.New("unique identifier and org id are needed to be able to get or delete a datasource")
ErrDatasourceIsReadOnly = errors.New("data source is readonly, can only be updated from configuration")
)
| pkg/services/datasources/errors.go | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00016993882309179753,
0.00016851292457431555,
0.00016708701150491834,
0.00016851292457431555,
0.0000014259057934395969
] |
{
"id": 2,
"code_window": [
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n",
" await script({github, context, core})\n",
"\n",
" - name: Detect breaking changes\n",
" id: breaking-changes\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await script({name, github, context, core})\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 137
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M8.29,6.21l2,2a1,1,0,0,0,1.42,0,1,1,0,0,0,0-1.42l-.3-.29H15a1,1,0,0,0,0-2H11.41l.3-.29a1,1,0,1,0-1.42-1.42l-2,2a1,1,0,0,0-.21.33,1,1,0,0,0,0,.76A1,1,0,0,0,8.29,6.21ZM16,10.5H8a3,3,0,0,0-3,3v5a3,3,0,0,0,3,3h8a3,3,0,0,0,3-3v-5A3,3,0,0,0,16,10.5Zm-.42,2L12.7,15.38a1,1,0,0,1-1.4,0L8.42,12.5Zm1.42,6a1,1,0,0,1-1,1H8a1,1,0,0,1-1-1V13.91l2.88,2.87a2.94,2.94,0,0,0,2.12.89,3,3,0,0,0,2.12-.88L17,13.91Z"/></svg> | public/img/icons/unicons/envelope-receive.svg | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00017099044634960592,
0.00017099044634960592,
0.00017099044634960592,
0.00017099044634960592,
0
] |
{
"id": 2,
"code_window": [
" const script = require('./.github/workflows/scripts/pr-get-job-link.js')\n",
" await script({github, context, core})\n",
"\n",
" - name: Detect breaking changes\n",
" id: breaking-changes\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await script({name, github, context, core})\n"
],
"file_path": ".github/workflows/detect-breaking-changes-build.yml",
"type": "replace",
"edit_start_line_idx": 137
} | package k8saccess
import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/models"
)
type httpHelper struct {
access *k8sAccess
}
func newHTTPHelper(access *k8sAccess, router routing.RouteRegister) *httpHelper {
s := &httpHelper{
access: access,
}
// Must be admin for everything
router.Group("/api/k8s", func(k8sRoute routing.RouteRegister) {
k8sRoute.Get("/info", middleware.ReqOrgAdmin, routing.Wrap(s.showClientInfo))
k8sRoute.Any("/proxy/*", middleware.ReqOrgAdmin, s.doProxy)
})
return s
}
func (s *httpHelper) showClientInfo(c *models.ReqContext) response.Response {
if s.access.sys != nil {
info := s.access.sys.getInfo()
if s.access.sys.err != nil {
return response.JSON(500, info)
}
return response.JSON(200, info)
}
return response.JSON(500, map[string]interface{}{
"error": "no client initialized",
})
}
func (s *httpHelper) doProxy(c *models.ReqContext) {
// TODO... this does not yet do a real proxy
if s.access.sys != nil {
if s.access.sys.err == nil {
s.access.sys.doProxy(c)
} else {
c.Resp.WriteHeader(500)
}
return
}
_, _ = c.Resp.Write([]byte("??"))
}
| pkg/services/store/k8saccess/http.go | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00017429869330953807,
0.00016829038213472813,
0.0001618970709387213,
0.00016871863044798374,
0.000004206869562040083
] |
{
"id": 3,
"code_window": [
"\n",
"module.exports = async ({ github, context, core }) => {\n",
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"module.exports = async ({ name, github, context, core }) => {\n"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 1
} | # Only runs if anything under the packages/ directory changes.
# (Otherwise detect-breaking-changes-build-skip.yml takes over)
name: Levitate / Detect breaking changes
on:
pull_request:
paths:
- 'packages/**'
jobs:
buildPR:
name: Build PR
runs-on: ubuntu-latest
defaults:
run:
working-directory: './pr'
steps:
- uses: actions/checkout@v3
with:
path: './pr'
- uses: actions/[email protected]
with:
node-version: 16.16.0
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT
- name: Restore yarn cache
uses: actions/[email protected]
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-cache-folder-${{ hashFiles('**/yarn.lock', '.yarnrc.yml') }}
restore-keys: |
yarn-cache-folder-
- name: Install dependencies
run: yarn install --immutable
- name: Build packages
run: yarn packages:build
- name: Pack packages
run: yarn packages:pack --out ./%s.tgz
- name: Zip built tarballed packages
run: zip -r ./pr_built_packages.zip ./packages/**/*.tgz
- name: Upload build output as artifact
uses: actions/upload-artifact@v3
with:
name: buildPr
path: './pr/pr_built_packages.zip'
buildBase:
name: Build Base
runs-on: ubuntu-latest
defaults:
run:
working-directory: './base'
steps:
- uses: actions/checkout@v3
with:
path: './base'
ref: ${{ github.event.pull_request.base.ref }}
- uses: actions/[email protected]
with:
node-version: 16.16.0
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT
- name: Restore yarn cache
uses: actions/[email protected]
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-cache-folder-${{ hashFiles('**/yarn.lock', '.yarnrc.yml') }}
restore-keys: |
yarn-cache-folder-
- name: Install dependencies
run: yarn install --immutable
- name: Build packages
run: yarn packages:build
- name: Pack packages
run: yarn packages:pack --out ./%s.tgz
- name: Zip built tarballed packages
run: zip -r ./base_built_packages.zip ./packages/**/*.tgz
- name: Upload build output as artifact
uses: actions/upload-artifact@v3
with:
name: buildBase
path: './base/base_built_packages.zip'
Detect:
name: Detect breaking changes
runs-on: ubuntu-latest
needs: ['buildPR', 'buildBase']
env:
GITHUB_STEP_NUMBER: 7
steps:
- uses: actions/checkout@v3
- name: Get built packages from pr
uses: actions/download-artifact@v3
with:
name: buildPr
- name: Get built packages from base
uses: actions/download-artifact@v3
with:
name: buildBase
- name: Unzip artifact from pr
run: unzip -j pr_built_packages.zip -d ./pr && rm pr_built_packages.zip
- name: Unzip artifact from base
run: unzip -j base_built_packages.zip -d ./base && rm base_built_packages.zip
- name: Get link for the Github Action job
id: job
uses: actions/github-script@v6
with:
script: |
const script = require('./.github/workflows/scripts/pr-get-job-link.js')
await script({github, context, core})
- name: Detect breaking changes
id: breaking-changes
run: ./scripts/check-breaking-changes.sh
env:
FORCE_COLOR: 3
GITHUB_JOB_LINK: ${{ steps.job.outputs.link }}
- name: Persisting the check output
run: |
mkdir -p ./levitate
echo "{ \"exit_code\": ${{ steps.breaking-changes.outputs.is_breaking }}, \"message\": \"${{ steps.breaking-changes.outputs.message }}\", \"job_link\": \"${{ steps.job.outputs.link }}#step:${GITHUB_STEP_NUMBER}:1\", \"pr_number\": \"${{ github.event.pull_request.number }}\" }" > ./levitate/result.json
- name: Upload check output as artifact
uses: actions/upload-artifact@v3
with:
name: levitate
path: levitate/
- name: Exit
run: exit ${{ steps.breaking-changes.outputs.is_breaking }}
shell: bash
| .github/workflows/detect-breaking-changes-build.yml | 1 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.6227989792823792,
0.036801017820835114,
0.00016386999050155282,
0.00017561810091137886,
0.14649948477745056
] |
{
"id": 3,
"code_window": [
"\n",
"module.exports = async ({ github, context, core }) => {\n",
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"module.exports = async ({ name, github, context, core }) => {\n"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 1
} | import React, { ReactElement } from 'react';
import { PluginErrorCode } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { Alert } from '@grafana/ui';
import { CatalogPlugin } from '../types';
type Props = {
className?: string;
plugin: CatalogPlugin;
};
export function PluginDetailsDisabledError({ className, plugin }: Props): ReactElement | null {
if (!plugin.isDisabled) {
return null;
}
return (
<Alert
severity="error"
title="Plugin disabled"
className={className}
aria-label={selectors.pages.PluginPage.disabledInfo}
>
{renderDescriptionFromError(plugin.error)}
<p>Please contact your server administrator to get this resolved.</p>
<a
href="https://grafana.com/docs/grafana/latest/administration/cli/#plugins-commands"
className="external-link"
target="_blank"
rel="noreferrer"
>
Read more about managing plugins
</a>
</Alert>
);
}
function renderDescriptionFromError(error?: PluginErrorCode): ReactElement {
switch (error) {
case PluginErrorCode.modifiedSignature:
return (
<p>
Grafana Labs checks each plugin to verify that it has a valid digital signature. While doing this, we
discovered that the content of this plugin does not match its signature. We can not guarantee the trustworthy
of this plugin and have therefore disabled it. We recommend you to reinstall the plugin to make sure you are
running a verified version of this plugin.
</p>
);
case PluginErrorCode.invalidSignature:
return (
<p>
Grafana Labs checks each plugin to verify that it has a valid digital signature. While doing this, we
discovered that it was invalid. We can not guarantee the trustworthy of this plugin and have therefore
disabled it. We recommend you to reinstall the plugin to make sure you are running a verified version of this
plugin.
</p>
);
case PluginErrorCode.missingSignature:
return (
<p>
Grafana Labs checks each plugin to verify that it has a valid digital signature. While doing this, we
discovered that there is no signature for this plugin. We can not guarantee the trustworthy of this plugin and
have therefore disabled it. We recommend you to reinstall the plugin to make sure you are running a verified
version of this plugin.
</p>
);
default:
return (
<p>
We failed to run this plugin due to an unkown reason and have therefore disabled it. We recommend you to
reinstall the plugin to make sure you are running a working version of this plugin.
</p>
);
}
}
| public/app/features/plugins/admin/components/PluginDetailsDisabledError.tsx | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.0001783794432412833,
0.00017464670236222446,
0.00016819313168525696,
0.00017517388914711773,
0.0000030774133392696967
] |
{
"id": 3,
"code_window": [
"\n",
"module.exports = async ({ github, context, core }) => {\n",
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"module.exports = async ({ name, github, context, core }) => {\n"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 1
} | package webtest
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/google/uuid"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/web"
)
var requests = map[string]*models.ReqContext{}
type Server struct {
t testing.TB
Mux *web.Mux
RouteRegister routing.RouteRegister
TestServer *httptest.Server
}
// NewServer starts and returns a new server.
func NewServer(t testing.TB, routeRegister routing.RouteRegister) *Server {
t.Helper()
m := web.New()
initCtx := &models.ReqContext{}
m.Use(func(c *web.Context) {
initCtx.Context = c
initCtx.Logger = log.New("api-test")
c.Req = c.Req.WithContext(ctxkey.Set(c.Req.Context(), initCtx))
})
m.UseMiddleware(requestContextMiddleware())
routeRegister.Register(m.Router)
testServer := httptest.NewServer(m)
t.Cleanup(testServer.Close)
return &Server{
t: t,
RouteRegister: routeRegister,
Mux: m,
TestServer: testServer,
}
}
// NewGetRequest creates a new GET request setup for test.
func (s *Server) NewGetRequest(target string) *http.Request {
return s.NewRequest(http.MethodGet, target, nil)
}
// NewPostRequest creates a new POST request setup for test.
func (s *Server) NewPostRequest(target string, body io.Reader) *http.Request {
return s.NewRequest(http.MethodPost, target, body)
}
// NewRequest creates a new request setup for test.
func (s *Server) NewRequest(method string, target string, body io.Reader) *http.Request {
s.t.Helper()
if !strings.HasPrefix(target, "/") {
target = "/" + target
}
target = s.TestServer.URL + target
req := httptest.NewRequest(method, target, body)
reqID := generateRequestIdentifier()
req = requestWithRequestIdentifier(req, reqID)
req.RequestURI = ""
return req
}
// Send sends a HTTP request to the test server and returns an HTTP response.
func (s *Server) Send(req *http.Request) (*http.Response, error) {
return http.DefaultClient.Do(req)
}
// SendJSON sets the Content-Type header to application/json and sends
// a HTTP request to the test server and returns an HTTP response.
// Suitable for POST/PUT/PATCH requests that sends request body as JSON.
func (s *Server) SendJSON(req *http.Request) (*http.Response, error) {
req.Header.Add("Content-Type", "application/json")
return s.Send(req)
}
func generateRequestIdentifier() string {
return uuid.NewString()
}
func requestWithRequestIdentifier(req *http.Request, id string) *http.Request {
req.Header.Set("X-GRAFANA-WEB-TEST-ID", id)
return req
}
func requestIdentifierFromRequest(req *http.Request) string {
return req.Header.Get("X-GRAFANA-WEB-TEST-ID")
}
func RequestWithWebContext(req *http.Request, c *models.ReqContext) *http.Request {
reqID := requestIdentifierFromRequest(req)
requests[reqID] = c
return req
}
func RequestWithSignedInUser(req *http.Request, user *user.SignedInUser) *http.Request {
return RequestWithWebContext(req, &models.ReqContext{
SignedInUser: user,
IsSignedIn: true,
})
}
func requestContextFromRequest(req *http.Request) *models.ReqContext {
reqID := requestIdentifierFromRequest(req)
val, exists := requests[reqID]
if !exists {
return nil
}
return val
}
func requestContextMiddleware() web.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c := ctxkey.Get(r.Context()).(*models.ReqContext)
ctx := requestContextFromRequest(r)
if ctx != nil {
c.SignedInUser = ctx.SignedInUser
c.UserToken = ctx.UserToken
c.IsSignedIn = ctx.IsSignedIn
c.IsRenderCall = ctx.IsRenderCall
c.AllowAnonymous = ctx.AllowAnonymous
c.SkipCache = ctx.SkipCache
c.RequestNonce = ctx.RequestNonce
c.PerfmonTimer = ctx.PerfmonTimer
c.LookupTokenErr = ctx.LookupTokenErr
}
next.ServeHTTP(w, r)
})
}
}
| pkg/web/webtest/webtest.go | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00017836090410128236,
0.00017107866005972028,
0.0001639670372242108,
0.00017060106620192528,
0.000003892946097039385
] |
{
"id": 3,
"code_window": [
"\n",
"module.exports = async ({ github, context, core }) => {\n",
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"module.exports = async ({ name, github, context, core }) => {\n"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 1
} | export { default } from './ResourcePicker';
| public/app/plugins/datasource/grafana-azure-monitor-datasource/components/ResourcePicker/index.tsx | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00016485026571899652,
0.00016485026571899652,
0.00016485026571899652,
0.00016485026571899652,
0
] |
{
"id": 4,
"code_window": [
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n",
" const result = await github.request(url)\n",
" const link = `https://github.com/grafana/grafana/runs/${result.data.jobs[0].id}?check_suite_focus=true`;\n",
"\n",
" core.setOutput('link', link);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
" const result = await github.request(url);\n",
" const job = result.jobs.find(j => j.name === name);\n",
" \n",
" core.setOutput('link', `${job.html_url}?check_suite_focus=true`);\n",
"}"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 4
} | # Only runs if anything under the packages/ directory changes.
# (Otherwise detect-breaking-changes-build-skip.yml takes over)
name: Levitate / Detect breaking changes
on:
pull_request:
paths:
- 'packages/**'
jobs:
buildPR:
name: Build PR
runs-on: ubuntu-latest
defaults:
run:
working-directory: './pr'
steps:
- uses: actions/checkout@v3
with:
path: './pr'
- uses: actions/[email protected]
with:
node-version: 16.16.0
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT
- name: Restore yarn cache
uses: actions/[email protected]
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-cache-folder-${{ hashFiles('**/yarn.lock', '.yarnrc.yml') }}
restore-keys: |
yarn-cache-folder-
- name: Install dependencies
run: yarn install --immutable
- name: Build packages
run: yarn packages:build
- name: Pack packages
run: yarn packages:pack --out ./%s.tgz
- name: Zip built tarballed packages
run: zip -r ./pr_built_packages.zip ./packages/**/*.tgz
- name: Upload build output as artifact
uses: actions/upload-artifact@v3
with:
name: buildPr
path: './pr/pr_built_packages.zip'
buildBase:
name: Build Base
runs-on: ubuntu-latest
defaults:
run:
working-directory: './base'
steps:
- uses: actions/checkout@v3
with:
path: './base'
ref: ${{ github.event.pull_request.base.ref }}
- uses: actions/[email protected]
with:
node-version: 16.16.0
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT
- name: Restore yarn cache
uses: actions/[email protected]
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-cache-folder-${{ hashFiles('**/yarn.lock', '.yarnrc.yml') }}
restore-keys: |
yarn-cache-folder-
- name: Install dependencies
run: yarn install --immutable
- name: Build packages
run: yarn packages:build
- name: Pack packages
run: yarn packages:pack --out ./%s.tgz
- name: Zip built tarballed packages
run: zip -r ./base_built_packages.zip ./packages/**/*.tgz
- name: Upload build output as artifact
uses: actions/upload-artifact@v3
with:
name: buildBase
path: './base/base_built_packages.zip'
Detect:
name: Detect breaking changes
runs-on: ubuntu-latest
needs: ['buildPR', 'buildBase']
env:
GITHUB_STEP_NUMBER: 7
steps:
- uses: actions/checkout@v3
- name: Get built packages from pr
uses: actions/download-artifact@v3
with:
name: buildPr
- name: Get built packages from base
uses: actions/download-artifact@v3
with:
name: buildBase
- name: Unzip artifact from pr
run: unzip -j pr_built_packages.zip -d ./pr && rm pr_built_packages.zip
- name: Unzip artifact from base
run: unzip -j base_built_packages.zip -d ./base && rm base_built_packages.zip
- name: Get link for the Github Action job
id: job
uses: actions/github-script@v6
with:
script: |
const script = require('./.github/workflows/scripts/pr-get-job-link.js')
await script({github, context, core})
- name: Detect breaking changes
id: breaking-changes
run: ./scripts/check-breaking-changes.sh
env:
FORCE_COLOR: 3
GITHUB_JOB_LINK: ${{ steps.job.outputs.link }}
- name: Persisting the check output
run: |
mkdir -p ./levitate
echo "{ \"exit_code\": ${{ steps.breaking-changes.outputs.is_breaking }}, \"message\": \"${{ steps.breaking-changes.outputs.message }}\", \"job_link\": \"${{ steps.job.outputs.link }}#step:${GITHUB_STEP_NUMBER}:1\", \"pr_number\": \"${{ github.event.pull_request.number }}\" }" > ./levitate/result.json
- name: Upload check output as artifact
uses: actions/upload-artifact@v3
with:
name: levitate
path: levitate/
- name: Exit
run: exit ${{ steps.breaking-changes.outputs.is_breaking }}
shell: bash
| .github/workflows/detect-breaking-changes-build.yml | 1 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00040618146886117756,
0.00018765997083391994,
0.00016908461111597717,
0.00017480298993177712,
0.000054697935411240906
] |
{
"id": 4,
"code_window": [
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n",
" const result = await github.request(url)\n",
" const link = `https://github.com/grafana/grafana/runs/${result.data.jobs[0].id}?check_suite_focus=true`;\n",
"\n",
" core.setOutput('link', link);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
" const result = await github.request(url);\n",
" const job = result.jobs.find(j => j.name === name);\n",
" \n",
" core.setOutput('link', `${job.html_url}?check_suite_focus=true`);\n",
"}"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 4
} | import intersect from 'fast_array_intersect';
import { getTimeField, sortDataFrame } from '../../dataframe';
import { DataFrame, Field, FieldMatcher, FieldType, Vector } from '../../types';
import { ArrayVector } from '../../vector';
import { fieldMatchers } from '../matchers';
import { FieldMatcherID } from '../matchers/ids';
import { JoinMode } from './joinByField';
export function pickBestJoinField(data: DataFrame[]): FieldMatcher {
const { timeField } = getTimeField(data[0]);
if (timeField) {
return fieldMatchers.get(FieldMatcherID.firstTimeField).get({});
}
let common: string[] = [];
for (const f of data[0].fields) {
if (f.type === FieldType.number) {
common.push(f.name);
}
}
for (let i = 1; i < data.length; i++) {
const names: string[] = [];
for (const f of data[0].fields) {
if (f.type === FieldType.number) {
names.push(f.name);
}
}
common = common.filter((v) => !names.includes(v));
}
return fieldMatchers.get(FieldMatcherID.byName).get(common[0]);
}
/**
* @internal
*/
export interface JoinOptions {
/**
* The input fields
*/
frames: DataFrame[];
/**
* The field to join -- frames that do not have this field will be droppped
*/
joinBy?: FieldMatcher;
/**
* Optionally filter the non-join fields
*/
keep?: FieldMatcher;
/**
* @internal -- used when we need to keep a reference to the original frame/field index
*/
keepOriginIndices?: boolean;
/**
* @internal -- Optionally specify a join mode (outer or inner)
*/
mode?: JoinMode;
}
function getJoinMatcher(options: JoinOptions): FieldMatcher {
return options.joinBy ?? pickBestJoinField(options.frames);
}
/**
* @internal
*/
export function maybeSortFrame(frame: DataFrame, fieldIdx: number) {
if (fieldIdx >= 0) {
let sortByField = frame.fields[fieldIdx];
if (sortByField.type !== FieldType.string && !isLikelyAscendingVector(sortByField.values)) {
frame = sortDataFrame(frame, fieldIdx);
}
}
return frame;
}
/**
* This will return a single frame joined by the first matching field. When a join field is not specified,
* the default will use the first time field
*/
export function joinDataFrames(options: JoinOptions): DataFrame | undefined {
if (!options.frames?.length) {
return;
}
if (options.frames.length === 1) {
let frame = options.frames[0];
let frameCopy = frame;
const joinFieldMatcher = getJoinMatcher(options);
let joinIndex = frameCopy.fields.findIndex((f) => joinFieldMatcher(f, frameCopy, options.frames));
if (options.keepOriginIndices) {
frameCopy = {
...frame,
fields: frame.fields.map((f, fieldIndex) => {
const copy = { ...f };
const origin = {
frameIndex: 0,
fieldIndex,
};
if (copy.state) {
copy.state.origin = origin;
} else {
copy.state = { origin };
}
return copy;
}),
};
// Make sure the join field is first
if (joinIndex > 0) {
const joinField = frameCopy.fields[joinIndex];
const fields = frameCopy.fields.filter((f, idx) => idx !== joinIndex);
fields.unshift(joinField);
frameCopy.fields = fields;
joinIndex = 0;
}
}
if (joinIndex >= 0) {
frameCopy = maybeSortFrame(frameCopy, joinIndex);
}
if (options.keep) {
let fields = frameCopy.fields.filter(
(f, fieldIdx) => fieldIdx === joinIndex || options.keep!(f, frameCopy, options.frames)
);
// mutate already copied frame
if (frame !== frameCopy) {
frameCopy.fields = fields;
} else {
frameCopy = {
...frame,
fields,
};
}
}
return frameCopy;
}
const nullModes: JoinNullMode[][] = [];
const allData: AlignedData[] = [];
const originalFields: Field[] = [];
const joinFieldMatcher = getJoinMatcher(options);
for (let frameIndex = 0; frameIndex < options.frames.length; frameIndex++) {
const frame = options.frames[frameIndex];
if (!frame || !frame.fields?.length) {
continue; // skip the frame
}
const nullModesFrame: JoinNullMode[] = [NULL_REMOVE];
let join: Field | undefined = undefined;
let fields: Field[] = [];
for (let fieldIndex = 0; fieldIndex < frame.fields.length; fieldIndex++) {
const field = frame.fields[fieldIndex];
field.state = field.state || {};
if (!join && joinFieldMatcher(field, frame, options.frames)) {
join = field;
} else {
if (options.keep && !options.keep(field, frame, options.frames)) {
continue; // skip field
}
// Support the standard graph span nulls field config
let spanNulls = field.config.custom?.spanNulls;
nullModesFrame.push(spanNulls === true ? NULL_REMOVE : spanNulls === -1 ? NULL_RETAIN : NULL_EXPAND);
let labels = field.labels ?? {};
if (frame.name) {
labels = { ...labels, name: frame.name };
}
fields.push({
...field,
labels, // add the name label from frame
});
}
if (options.keepOriginIndices) {
field.state.origin = {
frameIndex,
fieldIndex,
};
}
}
if (!join) {
continue; // skip the frame
}
if (originalFields.length === 0) {
originalFields.push(join); // first join field
}
nullModes.push(nullModesFrame);
const a: AlignedData = [join.values.toArray()]; //
for (const field of fields) {
a.push(field.values.toArray());
originalFields.push(field);
// clear field displayName state
delete field.state?.displayName;
}
allData.push(a);
}
const joined = join(allData, nullModes, options.mode);
return {
// ...options.data[0], // keep name, meta?
length: joined[0].length,
fields: originalFields.map((f, index) => ({
...f,
values: new ArrayVector(joined[index]),
})),
};
}
//--------------------------------------------------------------------------------
// Below here is copied from uplot (MIT License)
// https://github.com/leeoniya/uPlot/blob/master/src/utils.js#L325
// This avoids needing to import uplot into the data package
//--------------------------------------------------------------------------------
// Copied from uplot
export type TypedArray =
| Int8Array
| Uint8Array
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Uint8ClampedArray
| Float32Array
| Float64Array;
export type AlignedData =
| TypedArray[]
| [xValues: number[] | TypedArray, ...yValues: Array<Array<number | null | undefined> | TypedArray>];
// nullModes
const NULL_REMOVE = 0; // nulls are converted to undefined (e.g. for spanGaps: true)
const NULL_RETAIN = 1; // nulls are retained, with alignment artifacts set to undefined (default)
const NULL_EXPAND = 2; // nulls are expanded to include any adjacent alignment artifacts
type JoinNullMode = number; // NULL_IGNORE | NULL_RETAIN | NULL_EXPAND;
// sets undefined values to nulls when adjacent to existing nulls (minesweeper)
function nullExpand(yVals: Array<number | null>, nullIdxs: number[], alignedLen: number) {
for (let i = 0, xi, lastNullIdx = -1; i < nullIdxs.length; i++) {
let nullIdx = nullIdxs[i];
if (nullIdx > lastNullIdx) {
xi = nullIdx - 1;
while (xi >= 0 && yVals[xi] == null) {
yVals[xi--] = null;
}
xi = nullIdx + 1;
while (xi < alignedLen && yVals[xi] == null) {
yVals[(lastNullIdx = xi++)] = null;
}
}
}
}
// nullModes is a tables-matched array indicating how to treat nulls in each series
export function join(tables: AlignedData[], nullModes?: number[][], mode: JoinMode = JoinMode.outer) {
let xVals: Set<number>;
if (mode === JoinMode.inner) {
// @ts-ignore
xVals = new Set(intersect(tables.map((t) => t[0])));
} else {
xVals = new Set();
for (let ti = 0; ti < tables.length; ti++) {
let t = tables[ti];
let xs = t[0];
let len = xs.length;
for (let i = 0; i < len; i++) {
xVals.add(xs[i]);
}
}
}
let data = [Array.from(xVals).sort((a, b) => a - b)];
let alignedLen = data[0].length;
let xIdxs = new Map();
for (let i = 0; i < alignedLen; i++) {
xIdxs.set(data[0][i], i);
}
for (let ti = 0; ti < tables.length; ti++) {
let t = tables[ti];
let xs = t[0];
for (let si = 1; si < t.length; si++) {
let ys = t[si];
let yVals = Array(alignedLen).fill(undefined);
let nullMode = nullModes ? nullModes[ti][si] : NULL_RETAIN;
let nullIdxs = [];
for (let i = 0; i < ys.length; i++) {
let yVal = ys[i];
let alignedIdx = xIdxs.get(xs[i]);
if (yVal === null) {
if (nullMode !== NULL_REMOVE) {
yVals[alignedIdx] = yVal;
if (nullMode === NULL_EXPAND) {
nullIdxs.push(alignedIdx);
}
}
} else {
yVals[alignedIdx] = yVal;
}
}
nullExpand(yVals, nullIdxs, alignedLen);
data.push(yVals);
}
}
return data;
}
// Test a few samples to see if the values are ascending
// Only exported for tests
export function isLikelyAscendingVector(data: Vector, samples = 50) {
const len = data.length;
// empty or single value
if (len <= 1) {
return true;
}
// skip leading & trailing nullish
let firstIdx = 0;
let lastIdx = len - 1;
while (firstIdx <= lastIdx && data.get(firstIdx) == null) {
firstIdx++;
}
while (lastIdx >= firstIdx && data.get(lastIdx) == null) {
lastIdx--;
}
// all nullish or one value surrounded by nullish
if (lastIdx <= firstIdx) {
return true;
}
const stride = Math.max(1, Math.floor((lastIdx - firstIdx + 1) / samples));
for (let prevVal = data.get(firstIdx), i = firstIdx + stride; i <= lastIdx; i += stride) {
const v = data.get(i);
if (v != null) {
if (v <= prevVal) {
return false;
}
prevVal = v;
}
}
return true;
}
| packages/grafana-data/src/transformations/transformers/joinDataFrames.ts | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.0001784226333256811,
0.00017549050971865654,
0.00016757154662627727,
0.00017608204507268965,
0.0000023793541004124563
] |
{
"id": 4,
"code_window": [
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n",
" const result = await github.request(url)\n",
" const link = `https://github.com/grafana/grafana/runs/${result.data.jobs[0].id}?check_suite_focus=true`;\n",
"\n",
" core.setOutput('link', link);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
" const result = await github.request(url);\n",
" const job = result.jobs.find(j => j.name === name);\n",
" \n",
" core.setOutput('link', `${job.html_url}?check_suite_focus=true`);\n",
"}"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 4
} | package provisioning
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/require"
)
func TestAlertRuleService(t *testing.T) {
ruleService := createAlertRuleService(t)
t.Run("alert rule creation should return the created id", func(t *testing.T) {
var orgID int64 = 1
rule, err := ruleService.CreateAlertRule(context.Background(), dummyRule("test#1", orgID), models.ProvenanceNone, 0)
require.NoError(t, err)
require.NotEqual(t, 0, rule.ID, "expected to get the created id and not the zero value")
})
t.Run("alert rule creation should set the right provenance", func(t *testing.T) {
var orgID int64 = 1
rule, err := ruleService.CreateAlertRule(context.Background(), dummyRule("test#2", orgID), models.ProvenanceAPI, 0)
require.NoError(t, err)
_, provenance, err := ruleService.GetAlertRule(context.Background(), orgID, rule.UID)
require.NoError(t, err)
require.Equal(t, models.ProvenanceAPI, provenance)
})
t.Run("group creation should set the right provenance", func(t *testing.T) {
var orgID int64 = 1
group := createDummyGroup("group-test-1", orgID)
err := ruleService.ReplaceRuleGroup(context.Background(), orgID, group, 0, models.ProvenanceAPI)
require.NoError(t, err)
readGroup, err := ruleService.GetRuleGroup(context.Background(), orgID, "my-namespace", "group-test-1")
require.NoError(t, err)
require.NotEmpty(t, readGroup.Rules)
for _, rule := range readGroup.Rules {
_, provenance, err := ruleService.GetAlertRule(context.Background(), orgID, rule.UID)
require.NoError(t, err)
require.Equal(t, models.ProvenanceAPI, provenance)
}
})
t.Run("alert rule group should be updated correctly", func(t *testing.T) {
var orgID int64 = 1
rule := dummyRule("test#3", orgID)
rule.RuleGroup = "a"
rule, err := ruleService.CreateAlertRule(context.Background(), rule, models.ProvenanceNone, 0)
require.NoError(t, err)
require.Equal(t, int64(60), rule.IntervalSeconds)
var interval int64 = 120
err = ruleService.UpdateRuleGroup(context.Background(), orgID, rule.NamespaceUID, rule.RuleGroup, 120)
require.NoError(t, err)
rule, _, err = ruleService.GetAlertRule(context.Background(), orgID, rule.UID)
require.NoError(t, err)
require.Equal(t, interval, rule.IntervalSeconds)
})
t.Run("if a folder was renamed the interval should be fetched from the renamed folder", func(t *testing.T) {
var orgID int64 = 2
rule := dummyRule("test#1", orgID)
rule.NamespaceUID = "123abc"
rule, err := ruleService.CreateAlertRule(context.Background(), rule, models.ProvenanceNone, 0)
require.NoError(t, err)
rule.NamespaceUID = "abc123"
_, err = ruleService.UpdateAlertRule(context.Background(),
rule, models.ProvenanceNone)
require.NoError(t, err)
})
t.Run("group creation should propagate group title correctly", func(t *testing.T) {
var orgID int64 = 1
group := createDummyGroup("group-test-3", orgID)
group.Rules[0].RuleGroup = "something different"
err := ruleService.ReplaceRuleGroup(context.Background(), orgID, group, 0, models.ProvenanceAPI)
require.NoError(t, err)
readGroup, err := ruleService.GetRuleGroup(context.Background(), orgID, "my-namespace", "group-test-3")
require.NoError(t, err)
require.NotEmpty(t, readGroup.Rules)
for _, rule := range readGroup.Rules {
require.Equal(t, "group-test-3", rule.RuleGroup)
}
})
t.Run("alert rule should get interval from existing rule group", func(t *testing.T) {
var orgID int64 = 1
rule := dummyRule("test#4", orgID)
rule.RuleGroup = "b"
rule, err := ruleService.CreateAlertRule(context.Background(), rule, models.ProvenanceNone, 0)
require.NoError(t, err)
var interval int64 = 120
err = ruleService.UpdateRuleGroup(context.Background(), orgID, rule.NamespaceUID, rule.RuleGroup, 120)
require.NoError(t, err)
rule = dummyRule("test#4-1", orgID)
rule.RuleGroup = "b"
rule, err = ruleService.CreateAlertRule(context.Background(), rule, models.ProvenanceNone, 0)
require.NoError(t, err)
require.Equal(t, interval, rule.IntervalSeconds)
})
t.Run("updating a rule group's top level fields should bump the version number", func(t *testing.T) {
const (
orgID = 123
namespaceUID = "abc"
ruleUID = "some_rule_uid"
ruleGroup = "abc"
newInterval int64 = 120
)
rule := dummyRule("my_rule", orgID)
rule.UID = ruleUID
rule.RuleGroup = ruleGroup
rule.NamespaceUID = namespaceUID
_, err := ruleService.CreateAlertRule(context.Background(), rule, models.ProvenanceNone, 0)
require.NoError(t, err)
rule, _, err = ruleService.GetAlertRule(context.Background(), orgID, ruleUID)
require.NoError(t, err)
require.Equal(t, int64(1), rule.Version)
require.Equal(t, int64(60), rule.IntervalSeconds)
err = ruleService.UpdateRuleGroup(context.Background(), orgID, namespaceUID, ruleGroup, newInterval)
require.NoError(t, err)
rule, _, err = ruleService.GetAlertRule(context.Background(), orgID, ruleUID)
require.NoError(t, err)
require.Equal(t, int64(2), rule.Version)
require.Equal(t, newInterval, rule.IntervalSeconds)
})
t.Run("updating a group by updating a rule should bump that rule's data and version number", func(t *testing.T) {
var orgID int64 = 1
group := createDummyGroup("group-test-5", orgID)
err := ruleService.ReplaceRuleGroup(context.Background(), orgID, group, 0, models.ProvenanceAPI)
require.NoError(t, err)
updatedGroup, err := ruleService.GetRuleGroup(context.Background(), orgID, "my-namespace", "group-test-5")
require.NoError(t, err)
updatedGroup.Rules[0].Title = "some-other-title-asdf"
err = ruleService.ReplaceRuleGroup(context.Background(), orgID, updatedGroup, 0, models.ProvenanceAPI)
require.NoError(t, err)
readGroup, err := ruleService.GetRuleGroup(context.Background(), orgID, "my-namespace", "group-test-5")
require.NoError(t, err)
require.NotEmpty(t, readGroup.Rules)
require.Len(t, readGroup.Rules, 1)
require.Equal(t, "some-other-title-asdf", readGroup.Rules[0].Title)
require.Equal(t, int64(2), readGroup.Rules[0].Version)
})
t.Run("alert rule provenace should be correctly checked", func(t *testing.T) {
tests := []struct {
name string
from models.Provenance
to models.Provenance
errNil bool
}{
{
name: "should be able to update from provenance none to api",
from: models.ProvenanceNone,
to: models.ProvenanceAPI,
errNil: true,
},
{
name: "should be able to update from provenance none to file",
from: models.ProvenanceNone,
to: models.ProvenanceFile,
errNil: true,
},
{
name: "should not be able to update from provenance api to file",
from: models.ProvenanceAPI,
to: models.ProvenanceFile,
errNil: false,
},
{
name: "should not be able to update from provenance api to none",
from: models.ProvenanceAPI,
to: models.ProvenanceNone,
errNil: false,
},
{
name: "should not be able to update from provenance file to api",
from: models.ProvenanceFile,
to: models.ProvenanceAPI,
errNil: false,
},
{
name: "should not be able to update from provenance file to none",
from: models.ProvenanceFile,
to: models.ProvenanceNone,
errNil: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var orgID int64 = 1
rule := dummyRule(t.Name(), orgID)
rule, err := ruleService.CreateAlertRule(context.Background(), rule, test.from, 0)
require.NoError(t, err)
_, err = ruleService.UpdateAlertRule(context.Background(), rule, test.to)
if test.errNil {
require.NoError(t, err)
} else {
require.Error(t, err)
}
})
}
})
t.Run("alert rule provenace should be correctly checked when writing groups", func(t *testing.T) {
tests := []struct {
name string
from models.Provenance
to models.Provenance
errNil bool
}{
{
name: "should be able to update from provenance none to api",
from: models.ProvenanceNone,
to: models.ProvenanceAPI,
errNil: true,
},
{
name: "should be able to update from provenance none to file",
from: models.ProvenanceNone,
to: models.ProvenanceFile,
errNil: true,
},
{
name: "should not be able to update from provenance api to file",
from: models.ProvenanceAPI,
to: models.ProvenanceFile,
errNil: false,
},
{
name: "should not be able to update from provenance api to none",
from: models.ProvenanceAPI,
to: models.ProvenanceNone,
errNil: false,
},
{
name: "should not be able to update from provenance file to api",
from: models.ProvenanceFile,
to: models.ProvenanceAPI,
errNil: false,
},
{
name: "should not be able to update from provenance file to none",
from: models.ProvenanceFile,
to: models.ProvenanceNone,
errNil: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var orgID int64 = 1
group := createDummyGroup(t.Name(), orgID)
err := ruleService.ReplaceRuleGroup(context.Background(), 1, group, 0, test.from)
require.NoError(t, err)
group.Rules[0].Title = t.Name()
err = ruleService.ReplaceRuleGroup(context.Background(), 1, group, 0, test.to)
if test.errNil {
require.NoError(t, err)
} else {
require.Error(t, err)
}
})
}
})
t.Run("quota met causes create to be rejected", func(t *testing.T) {
ruleService := createAlertRuleService(t)
checker := &MockQuotaChecker{}
checker.EXPECT().LimitExceeded()
ruleService.quotas = checker
_, err := ruleService.CreateAlertRule(context.Background(), dummyRule("test#1", 1), models.ProvenanceNone, 0)
require.ErrorIs(t, err, models.ErrQuotaReached)
})
t.Run("quota met causes group write to be rejected", func(t *testing.T) {
ruleService := createAlertRuleService(t)
checker := &MockQuotaChecker{}
checker.EXPECT().LimitExceeded()
ruleService.quotas = checker
group := createDummyGroup("quota-reached", 1)
err := ruleService.ReplaceRuleGroup(context.Background(), 1, group, 0, models.ProvenanceAPI)
require.ErrorIs(t, err, models.ErrQuotaReached)
})
}
func createAlertRuleService(t *testing.T) AlertRuleService {
t.Helper()
sqlStore := db.InitTestDB(t)
store := store.DBstore{
SQLStore: sqlStore,
Cfg: setting.UnifiedAlertingSettings{
BaseInterval: time.Second * 10,
},
Logger: log.NewNopLogger(),
}
quotas := MockQuotaChecker{}
quotas.EXPECT().LimitOK()
return AlertRuleService{
ruleStore: store,
provenanceStore: store,
quotas: "as,
xact: sqlStore,
log: log.New("testing"),
baseIntervalSeconds: 10,
defaultIntervalSeconds: 60,
}
}
func dummyRule(title string, orgID int64) models.AlertRule {
return createTestRule(title, "my-cool-group", orgID)
}
func createTestRule(title string, groupTitle string, orgID int64) models.AlertRule {
return models.AlertRule{
OrgID: orgID,
Title: title,
Condition: "A",
Version: 1,
IntervalSeconds: 60,
Data: []models.AlertQuery{
{
RefID: "A",
Model: json.RawMessage("{}"),
DatasourceUID: "-100",
RelativeTimeRange: models.RelativeTimeRange{
From: models.Duration(60),
To: models.Duration(0),
},
},
},
NamespaceUID: "my-namespace",
RuleGroup: groupTitle,
For: time.Second * 60,
NoDataState: models.OK,
ExecErrState: models.OkErrState,
}
}
func createDummyGroup(title string, orgID int64) models.AlertRuleGroup {
return models.AlertRuleGroup{
Title: title,
Interval: 60,
FolderUID: "my-namespace",
Rules: []models.AlertRule{
dummyRule(title+"-"+"rule-1", orgID),
},
}
}
| pkg/services/ngalert/provisioning/alert_rules_test.go | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.0005619876901619136,
0.00018214460578747094,
0.00016101232904475182,
0.0001737445272738114,
0.0000626152686891146
] |
{
"id": 4,
"code_window": [
" const { owner, repo } = context.repo;\n",
" const url = `https://api.github.com/repos/${owner}/${repo}/actions/runs/${context.runId}/jobs`\n",
" const result = await github.request(url)\n",
" const link = `https://github.com/grafana/grafana/runs/${result.data.jobs[0].id}?check_suite_focus=true`;\n",
"\n",
" core.setOutput('link', link);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
" const result = await github.request(url);\n",
" const job = result.jobs.find(j => j.name === name);\n",
" \n",
" core.setOutput('link', `${job.html_url}?check_suite_focus=true`);\n",
"}"
],
"file_path": ".github/workflows/scripts/pr-get-job-link.js",
"type": "replace",
"edit_start_line_idx": 4
} | package accesscontrol
import (
"strings"
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
func AddAdminOnlyMigration(mg *migrator.Migrator) {
mg.AddMigration("admin only folder/dashboard permission", &adminOnlyMigrator{})
}
type adminOnlyMigrator struct {
migrator.MigrationBase
}
func (m *adminOnlyMigrator) SQL(dialect migrator.Dialect) string {
return CodeMigrationSQL
}
func (m *adminOnlyMigrator) Exec(sess *xorm.Session, mg *migrator.Migrator) error {
logger := log.New("admin-permissions-only-migrator")
type model struct {
UID string `xorm:"uid"`
OrgID int64 `xorm:"org_id"`
IsFolder bool `xorm:"is_folder"`
}
var models []model
// Find all dashboards and folders that should have only admin permission in acl
// When a dashboard or folder only has admin permission the acl table should be empty and the has_acl set to true
sql := `
SELECT res.uid, res.is_folder, res.org_id
FROM (SELECT dashboard.id, dashboard.uid, dashboard.is_folder, dashboard.org_id, count(dashboard_acl.id) as count
FROM dashboard
LEFT JOIN dashboard_acl ON dashboard.id = dashboard_acl.dashboard_id
WHERE dashboard.has_acl IS TRUE
GROUP BY dashboard.id) as res
WHERE res.count = 0
`
if err := sess.SQL(sql).Find(&models); err != nil {
return err
}
for _, model := range models {
var scope string
// set scope based on type
if model.IsFolder {
scope = "folders:uid:" + model.UID
} else {
scope = "dashboards:uid:" + model.UID
}
// Find all managed editor and viewer permissions with scopes to folder or dashboard
sql = `
SELECT r.id
FROM role r
LEFT JOIN permission p on r.id = p.role_id
WHERE p.scope = ?
AND r.org_id = ?
AND r.name IN ('managed:builtins:editor:permissions', 'managed:builtins:viewer:permissions')
GROUP BY r.id
`
var roleIDS []int64
if err := sess.SQL(sql, scope, model.OrgID).Find(&roleIDS); err != nil {
return err
}
if len(roleIDS) == 0 {
continue
}
msg := "removing viewer and editor permissions on "
if model.IsFolder {
msg += "folder"
} else {
msg += "dashboard"
}
logger.Info(msg, "uid", model.UID)
// Remove managed permission for editors and viewers if there was any
removeSQL := `DELETE FROM permission WHERE scope = ? AND role_id IN(?` + strings.Repeat(", ?", len(roleIDS)-1) + `) `
params := []interface{}{removeSQL, scope}
for _, id := range roleIDS {
params = append(params, id)
}
if _, err := sess.Exec(params...); err != nil {
return err
}
}
return nil
}
| pkg/services/sqlstore/migrations/accesscontrol/admin_only.go | 0 | https://github.com/grafana/grafana/commit/d0a68b266c5e9196768df5031d7dbce32a33a438 | [
0.00019496699678711593,
0.0001750979427015409,
0.0001650122576393187,
0.00017421577649656683,
0.000006951863724680152
] |
{
"id": 0,
"code_window": [
"// Type definitions for @pollyjs/core 2.3\n",
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n"
],
"labels": [
"replace",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @pollyjs/core 2.6\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | // Type definitions for @pollyjs/core 2.3
// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core
// Definitions by: feinoujc <https://github.com/feinoujc>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { MODES } from '@pollyjs/utils';
import Adapter from '@pollyjs/adapter';
import Persister from '@pollyjs/persister';
export const Timing: {
fixed(ms: number): () => Promise<void>;
relative(ratio: number): (ms: number) => Promise<void>;
};
export type MatchBy<T = string, R = T> = (input: T) => R;
export interface PollyConfig {
mode?: MODES | string;
adapters?: Array<string | typeof Adapter>;
adapterOptions?: any;
persister?: string | typeof Persister;
persisterOptions?: {
keepUnusedRequests?: boolean;
[key: string]: any;
};
logging?: boolean;
recordIfMissing?: boolean;
recordIfExpired?: boolean;
recordFailedRequests?: boolean;
expiresIn?: string | null;
timing?: ((ms: number) => Promise<void>) | (() => Promise<void>);
matchRequestsBy?: {
method?: boolean | MatchBy;
headers?: boolean | { exclude: string[] } | MatchBy<Record<string, string>>;
body?: boolean | MatchBy<any>;
order?: boolean;
url?: {
protocol?: boolean | MatchBy;
username?: boolean | MatchBy;
password?: boolean | MatchBy;
hostname?: boolean | MatchBy;
port?: boolean | MatchBy<number>;
pathname?: boolean | MatchBy;
query?: boolean | MatchBy<any>;
hash?: boolean | MatchBy;
};
};
}
export interface Request {
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Request;
setHeaders(headers: Record<string, string | string[]>): Request;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Request;
send(body: any): Request;
json(body: any): Request;
jsonBody(): any;
method: string;
url: string;
protocol: string;
hostname: string;
port: string;
pathname: string;
hash: string;
headers: Record<string, string | string[]>;
body: any;
query: any;
params: any;
recordingName: string;
responseTime?: number;
}
export interface Response {
statusCode?: number;
headers: Record<string, string | string[]>;
body: any;
status(status: number): Response;
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Response;
setHeaders(headers: Record<string, string | string[]>): Response;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Response;
send(body: any): Response;
sendStatus(status: number): Response;
json(body: any): Response;
jsonBody(): any;
end(): Readonly<Response>;
}
export interface Intercept {
abort(): void;
passthrough(): void;
}
export type RequestRouteEvent = 'request';
export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist';
export type ResponseRouteEvent = 'beforeResponse' | 'response';
export type ErrorRouteEvent = 'error';
export type EventListenerResponse = any;
export type ErrorEventListener = (req: Request, error: any) => EventListenerResponse;
export type RequestEventListener = (req: Request) => EventListenerResponse;
export type RecordingEventListener = (req: Request, recording: any) => EventListenerResponse;
export type ResponseEventListener = (req: Request, res: Response) => EventListenerResponse;
export type InterceptHandler = (
req: Request,
res: Response,
intercept: Intercept
) => EventListenerResponse;
export class RouteHandler {
on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
on(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
on(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
off(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
off(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
off(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
off(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
once(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
once(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
once(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
filter: (callback: (req: Request) => boolean) => RouteHandler;
passthrough(value?: boolean): RouteHandler;
intercept(
fn: (req: Request, res: Response, intercept: Intercept) => EventListenerResponse
): RouteHandler;
recordingName(recordingName?: string): RouteHandler;
configure(config: PollyConfig): RouteHandler;
}
export class PollyServer {
timeout: (ms: number) => Promise<void>;
get: (...args: any[]) => RouteHandler;
put: (...args: any[]) => RouteHandler;
post: (...args: any[]) => RouteHandler;
delete: (...args: any[]) => RouteHandler;
patch: (...args: any[]) => RouteHandler;
head: (...args: any[]) => RouteHandler;
options: (...args: any[]) => RouteHandler;
any: (...args: any[]) => RouteHandler;
host(host: string, callback: () => void): void;
namespace(path: string, callback: () => void): void;
}
export type PollyEvent = 'create' | 'stop' | 'register';
export type PollyEventListener = (poll: Polly) => void;
export class Polly {
static register(Factory: typeof Adapter | typeof Persister): void;
static on(event: PollyEvent, listener: PollyEventListener): void;
static off(event: PollyEvent, listener: PollyEventListener): void;
static once(event: PollyEvent, listener: PollyEventListener): void;
constructor(name: string, options?: PollyConfig);
readonly recordingName: string | null;
mode: MODES;
server: PollyServer;
persister: Persister;
pause: () => void;
play: () => void;
replay: () => void;
record: () => void;
stop: () => Promise<void>;
flush: () => Promise<void>;
configure(config: PollyConfig): void;
connectTo(name: string | typeof Adapter): void;
disconnectFrom(name: string | typeof Adapter): void;
disconnect(): void;
}
| types/pollyjs__core/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.08612331002950668,
0.00494499783962965,
0.00016412127297371626,
0.00016909188707359135,
0.01968863420188427
] |
{
"id": 0,
"code_window": [
"// Type definitions for @pollyjs/core 2.3\n",
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n"
],
"labels": [
"replace",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @pollyjs/core 2.6\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | { "extends": "dtslint/dt.json" }
| types/freeport/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017344587831757963,
0.00017344587831757963,
0.00017344587831757963,
0.00017344587831757963,
0
] |
{
"id": 0,
"code_window": [
"// Type definitions for @pollyjs/core 2.3\n",
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n"
],
"labels": [
"replace",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @pollyjs/core 2.6\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojFormLayout extends JetElement<ojFormLayoutSettableProperties> {
direction: 'column' | 'row';
labelEdge: 'start' | 'top';
labelWidth: string;
labelWrapping: 'truncate' | 'wrap';
maxColumns: number;
onDirectionChanged: ((event: JetElementCustomEvent<ojFormLayout["direction"]>) => any) | null;
onLabelEdgeChanged: ((event: JetElementCustomEvent<ojFormLayout["labelEdge"]>) => any) | null;
onLabelWidthChanged: ((event: JetElementCustomEvent<ojFormLayout["labelWidth"]>) => any) | null;
onLabelWrappingChanged: ((event: JetElementCustomEvent<ojFormLayout["labelWrapping"]>) => any) | null;
onMaxColumnsChanged: ((event: JetElementCustomEvent<ojFormLayout["maxColumns"]>) => any) | null;
addEventListener<T extends keyof ojFormLayoutEventMap>(type: T, listener: (this: HTMLElement, ev: ojFormLayoutEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojFormLayoutSettableProperties>(property: T): ojFormLayout[T];
getProperty(property: string): any;
setProperty<T extends keyof ojFormLayoutSettableProperties>(property: T, value: ojFormLayoutSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojFormLayoutSettableProperties>): void;
setProperties(properties: ojFormLayoutSettablePropertiesLenient): void;
refresh(): void;
}
export interface ojFormLayoutEventMap extends HTMLElementEventMap {
'directionChanged': JetElementCustomEvent<ojFormLayout["direction"]>;
'labelEdgeChanged': JetElementCustomEvent<ojFormLayout["labelEdge"]>;
'labelWidthChanged': JetElementCustomEvent<ojFormLayout["labelWidth"]>;
'labelWrappingChanged': JetElementCustomEvent<ojFormLayout["labelWrapping"]>;
'maxColumnsChanged': JetElementCustomEvent<ojFormLayout["maxColumns"]>;
}
export interface ojFormLayoutSettableProperties extends JetSettableProperties {
direction: 'column' | 'row';
labelEdge: 'start' | 'top';
labelWidth: string;
labelWrapping: 'truncate' | 'wrap';
maxColumns: number;
}
export interface ojFormLayoutSettablePropertiesLenient extends Partial<ojFormLayoutSettableProperties> {
[key: string]: any;
}
| types/oracle__oraclejet/ojformlayout/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017362491053063422,
0.0001709341595415026,
0.00016874185530468822,
0.00017068494344130158,
0.0000019146450540574733
] |
{
"id": 0,
"code_window": [
"// Type definitions for @pollyjs/core 2.3\n",
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n"
],
"labels": [
"replace",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @pollyjs/core 2.6\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | { "extends": "dtslint/dt.json" }
| types/login-with-amazon-sdk-browser/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017344587831757963,
0.00017344587831757963,
0.00017344587831757963,
0.00017344587831757963,
0
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.4\n",
"\n",
"import { MODES } from '@pollyjs/utils';\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Borui Gu <https://github.com/BoruiGu>\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 3
} | // Type definitions for @pollyjs/core 2.3
// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core
// Definitions by: feinoujc <https://github.com/feinoujc>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { MODES } from '@pollyjs/utils';
import Adapter from '@pollyjs/adapter';
import Persister from '@pollyjs/persister';
export const Timing: {
fixed(ms: number): () => Promise<void>;
relative(ratio: number): (ms: number) => Promise<void>;
};
export type MatchBy<T = string, R = T> = (input: T) => R;
export interface PollyConfig {
mode?: MODES | string;
adapters?: Array<string | typeof Adapter>;
adapterOptions?: any;
persister?: string | typeof Persister;
persisterOptions?: {
keepUnusedRequests?: boolean;
[key: string]: any;
};
logging?: boolean;
recordIfMissing?: boolean;
recordIfExpired?: boolean;
recordFailedRequests?: boolean;
expiresIn?: string | null;
timing?: ((ms: number) => Promise<void>) | (() => Promise<void>);
matchRequestsBy?: {
method?: boolean | MatchBy;
headers?: boolean | { exclude: string[] } | MatchBy<Record<string, string>>;
body?: boolean | MatchBy<any>;
order?: boolean;
url?: {
protocol?: boolean | MatchBy;
username?: boolean | MatchBy;
password?: boolean | MatchBy;
hostname?: boolean | MatchBy;
port?: boolean | MatchBy<number>;
pathname?: boolean | MatchBy;
query?: boolean | MatchBy<any>;
hash?: boolean | MatchBy;
};
};
}
export interface Request {
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Request;
setHeaders(headers: Record<string, string | string[]>): Request;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Request;
send(body: any): Request;
json(body: any): Request;
jsonBody(): any;
method: string;
url: string;
protocol: string;
hostname: string;
port: string;
pathname: string;
hash: string;
headers: Record<string, string | string[]>;
body: any;
query: any;
params: any;
recordingName: string;
responseTime?: number;
}
export interface Response {
statusCode?: number;
headers: Record<string, string | string[]>;
body: any;
status(status: number): Response;
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Response;
setHeaders(headers: Record<string, string | string[]>): Response;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Response;
send(body: any): Response;
sendStatus(status: number): Response;
json(body: any): Response;
jsonBody(): any;
end(): Readonly<Response>;
}
export interface Intercept {
abort(): void;
passthrough(): void;
}
export type RequestRouteEvent = 'request';
export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist';
export type ResponseRouteEvent = 'beforeResponse' | 'response';
export type ErrorRouteEvent = 'error';
export type EventListenerResponse = any;
export type ErrorEventListener = (req: Request, error: any) => EventListenerResponse;
export type RequestEventListener = (req: Request) => EventListenerResponse;
export type RecordingEventListener = (req: Request, recording: any) => EventListenerResponse;
export type ResponseEventListener = (req: Request, res: Response) => EventListenerResponse;
export type InterceptHandler = (
req: Request,
res: Response,
intercept: Intercept
) => EventListenerResponse;
export class RouteHandler {
on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
on(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
on(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
off(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
off(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
off(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
off(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
once(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
once(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
once(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
filter: (callback: (req: Request) => boolean) => RouteHandler;
passthrough(value?: boolean): RouteHandler;
intercept(
fn: (req: Request, res: Response, intercept: Intercept) => EventListenerResponse
): RouteHandler;
recordingName(recordingName?: string): RouteHandler;
configure(config: PollyConfig): RouteHandler;
}
export class PollyServer {
timeout: (ms: number) => Promise<void>;
get: (...args: any[]) => RouteHandler;
put: (...args: any[]) => RouteHandler;
post: (...args: any[]) => RouteHandler;
delete: (...args: any[]) => RouteHandler;
patch: (...args: any[]) => RouteHandler;
head: (...args: any[]) => RouteHandler;
options: (...args: any[]) => RouteHandler;
any: (...args: any[]) => RouteHandler;
host(host: string, callback: () => void): void;
namespace(path: string, callback: () => void): void;
}
export type PollyEvent = 'create' | 'stop' | 'register';
export type PollyEventListener = (poll: Polly) => void;
export class Polly {
static register(Factory: typeof Adapter | typeof Persister): void;
static on(event: PollyEvent, listener: PollyEventListener): void;
static off(event: PollyEvent, listener: PollyEventListener): void;
static once(event: PollyEvent, listener: PollyEventListener): void;
constructor(name: string, options?: PollyConfig);
readonly recordingName: string | null;
mode: MODES;
server: PollyServer;
persister: Persister;
pause: () => void;
play: () => void;
replay: () => void;
record: () => void;
stop: () => Promise<void>;
flush: () => Promise<void>;
configure(config: PollyConfig): void;
connectTo(name: string | typeof Adapter): void;
disconnectFrom(name: string | typeof Adapter): void;
disconnect(): void;
}
| types/pollyjs__core/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.9918619394302368,
0.05531652271747589,
0.0001653814542805776,
0.000170754618011415,
0.22714568674564362
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.4\n",
"\n",
"import { MODES } from '@pollyjs/utils';\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Borui Gu <https://github.com/BoruiGu>\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 3
} |
import lag = require("event-loop-lag");
var fn: () => number = lag(1000);
var n: number = fn();
| types/event-loop-lag/event-loop-lag-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00016901899653021246,
0.00016901899653021246,
0.00016901899653021246,
0.00016901899653021246,
0
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.4\n",
"\n",
"import { MODES } from '@pollyjs/utils';\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Borui Gu <https://github.com/BoruiGu>\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 3
} | export interface WriteRequestType {
data: string;
type?: string;
}
export interface WriteAnyRequestType {
data: {
text?: string;
html?: string;
rtf?: string;
};
type?: string;
}
| types/openfin/v34/_v2/api/clipboard/write-request.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00016742861771490425,
0.0001656933018239215,
0.00016395798593293875,
0.0001656933018239215,
0.000001735315890982747
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\n",
"// Definitions by: feinoujc <https://github.com/feinoujc>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.4\n",
"\n",
"import { MODES } from '@pollyjs/utils';\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Borui Gu <https://github.com/BoruiGu>\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 3
} | import * as React from "react";
import { Animated, View, NativeSyntheticEvent, NativeScrollEvent } from "react-native";
function TestAnimatedAPI() {
// Value
const v1 = new Animated.Value(0);
const v2 = new Animated.Value(0);
v1.setValue(0.1);
v1.addListener(e => {
const n: number = e.value;
});
const v200 = v1.interpolate({
inputRange: [0, 1],
outputRange: [0, 200],
});
// ValueXY
const position = new Animated.ValueXY({ x: 0, y: 0 });
// Animation functions
const spring1 = Animated.spring(v1, {
toValue: 0.5,
tension: 10,
delay: 100,
});
const springXY = Animated.spring(position, {
toValue: {
x: 1,
y: 2,
},
});
spring1.start();
spring1.stop();
Animated.parallel([Animated.spring(v1, { toValue: 1 }), Animated.spring(v2, { toValue: 1 })], {
stopTogether: true,
});
Animated.decay(v1, {
velocity: 2,
});
Animated.timing(v1, {
toValue: 1,
duration: 100,
delay: 100,
easing: v => v,
});
Animated.add(v1, v2);
Animated.subtract(v1, v2);
Animated.divide(v1, v2);
Animated.multiply(v1, v2);
Animated.modulo(v1, 2);
Animated.delay(100);
Animated.sequence([spring1, springXY]);
Animated.stagger(100, [spring1, springXY]);
const listener = (e?: NativeSyntheticEvent<NativeScrollEvent>) => {
if (e) {
console.warn(e.nativeEvent.contentOffset.y);
}
};
Animated.event([{ nativeEvent: { contentOffset: { y: v1 } } }], { useNativeDriver: true, listener });
return (
<View>
<Animated.View
style={[
position.getLayout(),
{
opacity: v1,
},
]}
/>
<Animated.Image style={position.getTranslateTransform()} />
</View>
);
}
| types/react-native/test/animated.tsx | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017758048488758504,
0.0001726959308143705,
0.00016629433957859874,
0.00017287294031120837,
0.0000033883243304444477
] |
{
"id": 2,
"code_window": [
"\t};\n",
"\n",
"\tlogging?: boolean;\n",
"\n",
"\trecordIfMissing?: boolean;\n",
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t/** @deprecated use expiryStrategy */\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 31
} | // Type definitions for @pollyjs/core 2.3
// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core
// Definitions by: feinoujc <https://github.com/feinoujc>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { MODES } from '@pollyjs/utils';
import Adapter from '@pollyjs/adapter';
import Persister from '@pollyjs/persister';
export const Timing: {
fixed(ms: number): () => Promise<void>;
relative(ratio: number): (ms: number) => Promise<void>;
};
export type MatchBy<T = string, R = T> = (input: T) => R;
export interface PollyConfig {
mode?: MODES | string;
adapters?: Array<string | typeof Adapter>;
adapterOptions?: any;
persister?: string | typeof Persister;
persisterOptions?: {
keepUnusedRequests?: boolean;
[key: string]: any;
};
logging?: boolean;
recordIfMissing?: boolean;
recordIfExpired?: boolean;
recordFailedRequests?: boolean;
expiresIn?: string | null;
timing?: ((ms: number) => Promise<void>) | (() => Promise<void>);
matchRequestsBy?: {
method?: boolean | MatchBy;
headers?: boolean | { exclude: string[] } | MatchBy<Record<string, string>>;
body?: boolean | MatchBy<any>;
order?: boolean;
url?: {
protocol?: boolean | MatchBy;
username?: boolean | MatchBy;
password?: boolean | MatchBy;
hostname?: boolean | MatchBy;
port?: boolean | MatchBy<number>;
pathname?: boolean | MatchBy;
query?: boolean | MatchBy<any>;
hash?: boolean | MatchBy;
};
};
}
export interface Request {
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Request;
setHeaders(headers: Record<string, string | string[]>): Request;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Request;
send(body: any): Request;
json(body: any): Request;
jsonBody(): any;
method: string;
url: string;
protocol: string;
hostname: string;
port: string;
pathname: string;
hash: string;
headers: Record<string, string | string[]>;
body: any;
query: any;
params: any;
recordingName: string;
responseTime?: number;
}
export interface Response {
statusCode?: number;
headers: Record<string, string | string[]>;
body: any;
status(status: number): Response;
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Response;
setHeaders(headers: Record<string, string | string[]>): Response;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Response;
send(body: any): Response;
sendStatus(status: number): Response;
json(body: any): Response;
jsonBody(): any;
end(): Readonly<Response>;
}
export interface Intercept {
abort(): void;
passthrough(): void;
}
export type RequestRouteEvent = 'request';
export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist';
export type ResponseRouteEvent = 'beforeResponse' | 'response';
export type ErrorRouteEvent = 'error';
export type EventListenerResponse = any;
export type ErrorEventListener = (req: Request, error: any) => EventListenerResponse;
export type RequestEventListener = (req: Request) => EventListenerResponse;
export type RecordingEventListener = (req: Request, recording: any) => EventListenerResponse;
export type ResponseEventListener = (req: Request, res: Response) => EventListenerResponse;
export type InterceptHandler = (
req: Request,
res: Response,
intercept: Intercept
) => EventListenerResponse;
export class RouteHandler {
on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
on(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
on(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
off(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
off(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
off(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
off(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
once(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
once(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
once(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
filter: (callback: (req: Request) => boolean) => RouteHandler;
passthrough(value?: boolean): RouteHandler;
intercept(
fn: (req: Request, res: Response, intercept: Intercept) => EventListenerResponse
): RouteHandler;
recordingName(recordingName?: string): RouteHandler;
configure(config: PollyConfig): RouteHandler;
}
export class PollyServer {
timeout: (ms: number) => Promise<void>;
get: (...args: any[]) => RouteHandler;
put: (...args: any[]) => RouteHandler;
post: (...args: any[]) => RouteHandler;
delete: (...args: any[]) => RouteHandler;
patch: (...args: any[]) => RouteHandler;
head: (...args: any[]) => RouteHandler;
options: (...args: any[]) => RouteHandler;
any: (...args: any[]) => RouteHandler;
host(host: string, callback: () => void): void;
namespace(path: string, callback: () => void): void;
}
export type PollyEvent = 'create' | 'stop' | 'register';
export type PollyEventListener = (poll: Polly) => void;
export class Polly {
static register(Factory: typeof Adapter | typeof Persister): void;
static on(event: PollyEvent, listener: PollyEventListener): void;
static off(event: PollyEvent, listener: PollyEventListener): void;
static once(event: PollyEvent, listener: PollyEventListener): void;
constructor(name: string, options?: PollyConfig);
readonly recordingName: string | null;
mode: MODES;
server: PollyServer;
persister: Persister;
pause: () => void;
play: () => void;
replay: () => void;
record: () => void;
stop: () => Promise<void>;
flush: () => Promise<void>;
configure(config: PollyConfig): void;
connectTo(name: string | typeof Adapter): void;
disconnectFrom(name: string | typeof Adapter): void;
disconnect(): void;
}
| types/pollyjs__core/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.9419817328453064,
0.05271776765584946,
0.00016720207349862903,
0.0001705629692878574,
0.2156800776720047
] |
{
"id": 2,
"code_window": [
"\t};\n",
"\n",
"\tlogging?: boolean;\n",
"\n",
"\trecordIfMissing?: boolean;\n",
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t/** @deprecated use expiryStrategy */\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 31
} | // Type definitions for gulp-diff 1.0
// Project: https://github.com/creativelive/gulp-diff
// Definitions by: Ika <https://github.com/ikatyang>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import stream = require('stream');
/**
* Gulp task to diff files in the stream against a destination.
* @param dest target directory to diff against, defaults to diff against original source file
*/
declare function gulp_diff(dest?: string): stream.Transform;
declare namespace gulp_diff {
const diff: typeof gulp_diff;
function reporter(opts?: ReporterOptions): stream.Transform;
interface ReporterOptions {
/**
* do not show diff information, defaults to `false`
*/
quiet?: boolean;
/**
* emit an error on finding diffs, defaults to `false`
*/
fail?: boolean;
}
}
export = gulp_diff;
| types/gulp-diff/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.002687573665753007,
0.0008009556331671774,
0.00017075063078664243,
0.00017274908896069974,
0.001089239725843072
] |
{
"id": 2,
"code_window": [
"\t};\n",
"\n",
"\tlogging?: boolean;\n",
"\n",
"\trecordIfMissing?: boolean;\n",
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t/** @deprecated use expiryStrategy */\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 31
} | { "extends": "dtslint/dt.json" }
| types/module-alias/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.0001707138289930299,
0.0001707138289930299,
0.0001707138289930299,
0.0001707138289930299,
0
] |
{
"id": 2,
"code_window": [
"\t};\n",
"\n",
"\tlogging?: boolean;\n",
"\n",
"\trecordIfMissing?: boolean;\n",
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t/** @deprecated use expiryStrategy */\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 31
} | import { extendAllWith } from "../fp";
export = extendAllWith;
| types/lodash/ts3.1/fp/extendAllWith.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017335642769467086,
0.00017335642769467086,
0.00017335642769467086,
0.00017335642769467086,
0
] |
{
"id": 3,
"code_window": [
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n",
"\n",
"\texpiresIn?: string | null;\n",
"\ttiming?: ((ms: number) => Promise<void>) | (() => Promise<void>);\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\texpiryStrategy?: 'warn' | 'error' | 'record';\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 33
} | // Type definitions for @pollyjs/core 2.3
// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core
// Definitions by: feinoujc <https://github.com/feinoujc>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { MODES } from '@pollyjs/utils';
import Adapter from '@pollyjs/adapter';
import Persister from '@pollyjs/persister';
export const Timing: {
fixed(ms: number): () => Promise<void>;
relative(ratio: number): (ms: number) => Promise<void>;
};
export type MatchBy<T = string, R = T> = (input: T) => R;
export interface PollyConfig {
mode?: MODES | string;
adapters?: Array<string | typeof Adapter>;
adapterOptions?: any;
persister?: string | typeof Persister;
persisterOptions?: {
keepUnusedRequests?: boolean;
[key: string]: any;
};
logging?: boolean;
recordIfMissing?: boolean;
recordIfExpired?: boolean;
recordFailedRequests?: boolean;
expiresIn?: string | null;
timing?: ((ms: number) => Promise<void>) | (() => Promise<void>);
matchRequestsBy?: {
method?: boolean | MatchBy;
headers?: boolean | { exclude: string[] } | MatchBy<Record<string, string>>;
body?: boolean | MatchBy<any>;
order?: boolean;
url?: {
protocol?: boolean | MatchBy;
username?: boolean | MatchBy;
password?: boolean | MatchBy;
hostname?: boolean | MatchBy;
port?: boolean | MatchBy<number>;
pathname?: boolean | MatchBy;
query?: boolean | MatchBy<any>;
hash?: boolean | MatchBy;
};
};
}
export interface Request {
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Request;
setHeaders(headers: Record<string, string | string[]>): Request;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Request;
send(body: any): Request;
json(body: any): Request;
jsonBody(): any;
method: string;
url: string;
protocol: string;
hostname: string;
port: string;
pathname: string;
hash: string;
headers: Record<string, string | string[]>;
body: any;
query: any;
params: any;
recordingName: string;
responseTime?: number;
}
export interface Response {
statusCode?: number;
headers: Record<string, string | string[]>;
body: any;
status(status: number): Response;
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Response;
setHeaders(headers: Record<string, string | string[]>): Response;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Response;
send(body: any): Response;
sendStatus(status: number): Response;
json(body: any): Response;
jsonBody(): any;
end(): Readonly<Response>;
}
export interface Intercept {
abort(): void;
passthrough(): void;
}
export type RequestRouteEvent = 'request';
export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist';
export type ResponseRouteEvent = 'beforeResponse' | 'response';
export type ErrorRouteEvent = 'error';
export type EventListenerResponse = any;
export type ErrorEventListener = (req: Request, error: any) => EventListenerResponse;
export type RequestEventListener = (req: Request) => EventListenerResponse;
export type RecordingEventListener = (req: Request, recording: any) => EventListenerResponse;
export type ResponseEventListener = (req: Request, res: Response) => EventListenerResponse;
export type InterceptHandler = (
req: Request,
res: Response,
intercept: Intercept
) => EventListenerResponse;
export class RouteHandler {
on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
on(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
on(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
off(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
off(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
off(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
off(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
once(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
once(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
once(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
filter: (callback: (req: Request) => boolean) => RouteHandler;
passthrough(value?: boolean): RouteHandler;
intercept(
fn: (req: Request, res: Response, intercept: Intercept) => EventListenerResponse
): RouteHandler;
recordingName(recordingName?: string): RouteHandler;
configure(config: PollyConfig): RouteHandler;
}
export class PollyServer {
timeout: (ms: number) => Promise<void>;
get: (...args: any[]) => RouteHandler;
put: (...args: any[]) => RouteHandler;
post: (...args: any[]) => RouteHandler;
delete: (...args: any[]) => RouteHandler;
patch: (...args: any[]) => RouteHandler;
head: (...args: any[]) => RouteHandler;
options: (...args: any[]) => RouteHandler;
any: (...args: any[]) => RouteHandler;
host(host: string, callback: () => void): void;
namespace(path: string, callback: () => void): void;
}
export type PollyEvent = 'create' | 'stop' | 'register';
export type PollyEventListener = (poll: Polly) => void;
export class Polly {
static register(Factory: typeof Adapter | typeof Persister): void;
static on(event: PollyEvent, listener: PollyEventListener): void;
static off(event: PollyEvent, listener: PollyEventListener): void;
static once(event: PollyEvent, listener: PollyEventListener): void;
constructor(name: string, options?: PollyConfig);
readonly recordingName: string | null;
mode: MODES;
server: PollyServer;
persister: Persister;
pause: () => void;
play: () => void;
replay: () => void;
record: () => void;
stop: () => Promise<void>;
flush: () => Promise<void>;
configure(config: PollyConfig): void;
connectTo(name: string | typeof Adapter): void;
disconnectFrom(name: string | typeof Adapter): void;
disconnect(): void;
}
| types/pollyjs__core/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.9976779818534851,
0.05580594018101692,
0.00016441919433418661,
0.00017299599130637944,
0.22843872010707855
] |
{
"id": 3,
"code_window": [
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n",
"\n",
"\texpiresIn?: string | null;\n",
"\ttiming?: ((ms: number) => Promise<void>) | (() => Promise<void>);\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\texpiryStrategy?: 'warn' | 'error' | 'record';\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 33
} | { "extends": "dtslint/dt.json" }
| types/js-levenshtein/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017117167590186,
0.00017117167590186,
0.00017117167590186,
0.00017117167590186,
0
] |
{
"id": 3,
"code_window": [
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n",
"\n",
"\texpiresIn?: string | null;\n",
"\ttiming?: ((ms: number) => Promise<void>) | (() => Promise<void>);\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\texpiryStrategy?: 'warn' | 'error' | 'record';\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 33
} | metric_suffix(42) // 42
metric_suffix(999) // 999
metric_suffix(1000) // 1.0k
metric_suffix(1234, 2) // 1.2k
metric_suffix(12345, 2) // 12k
metric_suffix(123456, 2) // 123k
metric_suffix(1234, 3) // 1.23k
metric_suffix(12345, 3) // 12.3k
metric_suffix(123456, 3) // 123k
metric_suffix(1234, 4) // 1.234k
metric_suffix(12345, 4) // 12.35k
metric_suffix(123456, 4) // 123.5k
metric_suffix(986725) // 987k
metric_suffix(986725, 4) // 986.7k
metric_suffix(986725123) // 987M
metric_suffix(986725123, 5) // 986.73M | types/metric-suffix/metric-suffix-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.0001748396607581526,
0.00017304734501522034,
0.0001709223142825067,
0.00017338006000500172,
0.0000016164623275471968
] |
{
"id": 3,
"code_window": [
"\trecordIfExpired?: boolean;\n",
"\trecordFailedRequests?: boolean;\n",
"\n",
"\texpiresIn?: string | null;\n",
"\ttiming?: ((ms: number) => Promise<void>) | (() => Promise<void>);\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\texpiryStrategy?: 'warn' | 'error' | 'record';\n"
],
"file_path": "types/pollyjs__core/index.d.ts",
"type": "add",
"edit_start_line_idx": 33
} | // Type definitions for react-dynamic-number 1.7
// Project: https://github.com/uhlryk/react-dynamic-number
// Definitions by: Eugene Rodin <https://github.com/eugrdn>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as React from 'react';
export type Omit<T, K extends keyof T> = Pick<T, ({ [P in keyof T]: P } & { [P in K]: never } & { [x: string]: never, [x: number]: never })[keyof T]>;
export type BaseInputProps = Partial<
Omit<
React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>,
'ref' | 'value' | 'onChange' | 'placeholder'
>
>;
export interface DynamicNumberProps extends BaseInputProps {
value?: number | '';
separator?: '.' | ',';
thousand?: boolean | ' ';
integer?: number;
fraction?: number;
positive?: boolean;
negative?: boolean;
placeholder?: string;
onChange?: (event: React.ChangeEvent<HTMLInputElement>, modelValue: number, viewValue: string) => void;
}
export default class DynamicNumber extends React.Component<DynamicNumberProps> {}
| types/react-dynamic-number/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.0004734025860670954,
0.00028639729134738445,
0.0001653414365136996,
0.00025342259323224425,
0.00012663994857575744
] |
{
"id": 4,
"code_window": [
"\tmode: MODES.PASSTHROUGH,\n",
"\trecordFailedRequests: true,\n",
"\tadapters: ['xhr', 'fetch'],\n",
"\tpersister: 'rest',\n",
"\ttiming: Timing.relative(3),\n",
"\tmatchRequestsBy: {\n",
"\t\tmethod: true,\n",
"\t\theaders: true,\n",
"\t\tbody: true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" persister: 'rest',\n",
" expiryStrategy: 'error',\n"
],
"file_path": "types/pollyjs__core/pollyjs__core-tests.ts",
"type": "replace",
"edit_start_line_idx": 7
} | // Type definitions for @pollyjs/core 2.3
// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core
// Definitions by: feinoujc <https://github.com/feinoujc>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { MODES } from '@pollyjs/utils';
import Adapter from '@pollyjs/adapter';
import Persister from '@pollyjs/persister';
export const Timing: {
fixed(ms: number): () => Promise<void>;
relative(ratio: number): (ms: number) => Promise<void>;
};
export type MatchBy<T = string, R = T> = (input: T) => R;
export interface PollyConfig {
mode?: MODES | string;
adapters?: Array<string | typeof Adapter>;
adapterOptions?: any;
persister?: string | typeof Persister;
persisterOptions?: {
keepUnusedRequests?: boolean;
[key: string]: any;
};
logging?: boolean;
recordIfMissing?: boolean;
recordIfExpired?: boolean;
recordFailedRequests?: boolean;
expiresIn?: string | null;
timing?: ((ms: number) => Promise<void>) | (() => Promise<void>);
matchRequestsBy?: {
method?: boolean | MatchBy;
headers?: boolean | { exclude: string[] } | MatchBy<Record<string, string>>;
body?: boolean | MatchBy<any>;
order?: boolean;
url?: {
protocol?: boolean | MatchBy;
username?: boolean | MatchBy;
password?: boolean | MatchBy;
hostname?: boolean | MatchBy;
port?: boolean | MatchBy<number>;
pathname?: boolean | MatchBy;
query?: boolean | MatchBy<any>;
hash?: boolean | MatchBy;
};
};
}
export interface Request {
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Request;
setHeaders(headers: Record<string, string | string[]>): Request;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Request;
send(body: any): Request;
json(body: any): Request;
jsonBody(): any;
method: string;
url: string;
protocol: string;
hostname: string;
port: string;
pathname: string;
hash: string;
headers: Record<string, string | string[]>;
body: any;
query: any;
params: any;
recordingName: string;
responseTime?: number;
}
export interface Response {
statusCode?: number;
headers: Record<string, string | string[]>;
body: any;
status(status: number): Response;
getHeader(name: string): string | null;
setHeader(name: string, value?: string | null): Response;
setHeaders(headers: Record<string, string | string[]>): Response;
removeHeader(name: string): Request;
removeHeaders(headers: string[]): Request;
hasHeader(name: string): boolean;
type(contentType: string): Response;
send(body: any): Response;
sendStatus(status: number): Response;
json(body: any): Response;
jsonBody(): any;
end(): Readonly<Response>;
}
export interface Intercept {
abort(): void;
passthrough(): void;
}
export type RequestRouteEvent = 'request';
export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist';
export type ResponseRouteEvent = 'beforeResponse' | 'response';
export type ErrorRouteEvent = 'error';
export type EventListenerResponse = any;
export type ErrorEventListener = (req: Request, error: any) => EventListenerResponse;
export type RequestEventListener = (req: Request) => EventListenerResponse;
export type RecordingEventListener = (req: Request, recording: any) => EventListenerResponse;
export type ResponseEventListener = (req: Request, res: Response) => EventListenerResponse;
export type InterceptHandler = (
req: Request,
res: Response,
intercept: Intercept
) => EventListenerResponse;
export class RouteHandler {
on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
on(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
on(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
off(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
off(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
off(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
off(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
once(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler;
once(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
once(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
filter: (callback: (req: Request) => boolean) => RouteHandler;
passthrough(value?: boolean): RouteHandler;
intercept(
fn: (req: Request, res: Response, intercept: Intercept) => EventListenerResponse
): RouteHandler;
recordingName(recordingName?: string): RouteHandler;
configure(config: PollyConfig): RouteHandler;
}
export class PollyServer {
timeout: (ms: number) => Promise<void>;
get: (...args: any[]) => RouteHandler;
put: (...args: any[]) => RouteHandler;
post: (...args: any[]) => RouteHandler;
delete: (...args: any[]) => RouteHandler;
patch: (...args: any[]) => RouteHandler;
head: (...args: any[]) => RouteHandler;
options: (...args: any[]) => RouteHandler;
any: (...args: any[]) => RouteHandler;
host(host: string, callback: () => void): void;
namespace(path: string, callback: () => void): void;
}
export type PollyEvent = 'create' | 'stop' | 'register';
export type PollyEventListener = (poll: Polly) => void;
export class Polly {
static register(Factory: typeof Adapter | typeof Persister): void;
static on(event: PollyEvent, listener: PollyEventListener): void;
static off(event: PollyEvent, listener: PollyEventListener): void;
static once(event: PollyEvent, listener: PollyEventListener): void;
constructor(name: string, options?: PollyConfig);
readonly recordingName: string | null;
mode: MODES;
server: PollyServer;
persister: Persister;
pause: () => void;
play: () => void;
replay: () => void;
record: () => void;
stop: () => Promise<void>;
flush: () => Promise<void>;
configure(config: PollyConfig): void;
connectTo(name: string | typeof Adapter): void;
disconnectFrom(name: string | typeof Adapter): void;
disconnect(): void;
}
| types/pollyjs__core/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.004825321026146412,
0.0005772530566900969,
0.00016187300207093358,
0.00017247721552848816,
0.0011059867683798075
] |
{
"id": 4,
"code_window": [
"\tmode: MODES.PASSTHROUGH,\n",
"\trecordFailedRequests: true,\n",
"\tadapters: ['xhr', 'fetch'],\n",
"\tpersister: 'rest',\n",
"\ttiming: Timing.relative(3),\n",
"\tmatchRequestsBy: {\n",
"\t\tmethod: true,\n",
"\t\theaders: true,\n",
"\t\tbody: true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" persister: 'rest',\n",
" expiryStrategy: 'error',\n"
],
"file_path": "types/pollyjs__core/pollyjs__core-tests.ts",
"type": "replace",
"edit_start_line_idx": 7
} | { "extends": "dtslint/dt.json" }
| types/graphql-list-fields/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.0001716204424155876,
0.0001716204424155876,
0.0001716204424155876,
0.0001716204424155876,
0
] |
{
"id": 4,
"code_window": [
"\tmode: MODES.PASSTHROUGH,\n",
"\trecordFailedRequests: true,\n",
"\tadapters: ['xhr', 'fetch'],\n",
"\tpersister: 'rest',\n",
"\ttiming: Timing.relative(3),\n",
"\tmatchRequestsBy: {\n",
"\t\tmethod: true,\n",
"\t\theaders: true,\n",
"\t\tbody: true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" persister: 'rest',\n",
" expiryStrategy: 'error',\n"
],
"file_path": "types/pollyjs__core/pollyjs__core-tests.ts",
"type": "replace",
"edit_start_line_idx": 7
} | // Type definitions for ReactCSS 1.2.0
// Project: http://reactcss.com/
// Definitions by: Chris Gervang <https://github.com/chrisgervang>, Karol Janyst <https://github.com/LKay>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as React from "react"
interface LoopableProps extends React.Props<any> {
"nth-child": number
"first-child"?: boolean
"last-child"?: boolean
even?: boolean
odd?: boolean
}
interface HoverProps<T> extends React.Props<T> {
hover?: boolean
}
interface Classes<T> {
default: Partial<T>
[scope: string]: Partial<T>
}
export type CSS = React.CSSProperties
export function hover<A>(component: React.ComponentClass<A> | React.StatelessComponent<A>): React.ComponentClass<A>
export function loop(index: number, length: number): LoopableProps
export default function reactCSS<T>(classes: Classes<T>, ...activations: Array<any>): T
| types/reactcss/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017098082753363997,
0.00016852955741342157,
0.00016643536218907684,
0.00016817243886180222,
0.0000018727798760664882
] |
{
"id": 4,
"code_window": [
"\tmode: MODES.PASSTHROUGH,\n",
"\trecordFailedRequests: true,\n",
"\tadapters: ['xhr', 'fetch'],\n",
"\tpersister: 'rest',\n",
"\ttiming: Timing.relative(3),\n",
"\tmatchRequestsBy: {\n",
"\t\tmethod: true,\n",
"\t\theaders: true,\n",
"\t\tbody: true,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" persister: 'rest',\n",
" expiryStrategy: 'error',\n"
],
"file_path": "types/pollyjs__core/pollyjs__core-tests.ts",
"type": "replace",
"edit_start_line_idx": 7
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"superagent-bunyan-tests.ts"
]
}
| types/superagent-bunyan/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2696df1a3a0478a9640d8d7bca50366d847c3902 | [
0.00017280917381867766,
0.00017124829173553735,
0.00016832115943543613,
0.00017261452740058303,
0.000002071316657747957
] |
{
"id": 0,
"code_window": [
" constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserTypeInitializer) {\n",
" super(parent, type, guid, initializer);\n",
" }\n",
"\n",
" executablePath(): string {\n",
" return this._initializer.executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this._initializer.executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n"
],
"file_path": "src/client/browserType.ts",
"type": "add",
"edit_start_line_idx": 56
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as util from 'util';
import { BrowserContext, normalizeProxySettings, validateBrowserContextOptions } from './browserContext';
import * as browserPaths from '../utils/browserPaths';
import { ConnectionTransport, WebSocketTransport } from './transport';
import { BrowserOptions, Browser, BrowserProcess } from './browser';
import { launchProcess, Env, waitForLine, envArrayToObject } from './processLauncher';
import { PipeTransport } from './pipeTransport';
import { Progress, ProgressController } from './progress';
import * as types from './types';
import { TimeoutSettings } from '../utils/timeoutSettings';
import { validateHostRequirements } from './validateDependencies';
import { isDebugMode } from '../utils/utils';
const mkdirAsync = util.promisify(fs.mkdir);
const mkdtempAsync = util.promisify(fs.mkdtemp);
const existsAsync = (path: string): Promise<boolean> => new Promise(resolve => fs.stat(path, err => resolve(!err)));
const DOWNLOADS_FOLDER = path.join(os.tmpdir(), 'playwright_downloads-');
type WebSocketNotPipe = { webSocketRegex: RegExp, stream: 'stdout' | 'stderr' };
export abstract class BrowserType {
private _name: string;
private _executablePath: string | undefined;
private _webSocketNotPipe: WebSocketNotPipe | null;
private _browserDescriptor: browserPaths.BrowserDescriptor;
readonly _browserPath: string;
constructor(packagePath: string, browser: browserPaths.BrowserDescriptor, webSocketOrPipe: WebSocketNotPipe | null) {
this._name = browser.name;
const browsersPath = browserPaths.browsersPath(packagePath);
this._browserDescriptor = browser;
this._browserPath = browserPaths.browserDirectory(browsersPath, browser);
this._executablePath = browserPaths.executablePath(this._browserPath, browser);
this._webSocketNotPipe = webSocketOrPipe;
}
executablePath(): string {
if (!this._executablePath)
throw new Error('Browser is not supported on current platform');
return this._executablePath;
}
name(): string {
return this._name;
}
async launch(options: types.LaunchOptions = {}): Promise<Browser> {
options = validateLaunchOptions(options);
const controller = new ProgressController();
controller.setLogName('browser');
const browser = await controller.run(progress => {
return this._innerLaunch(progress, options, undefined).catch(e => { throw this._rewriteStartupError(e); });
}, TimeoutSettings.timeout(options));
return browser;
}
async launchPersistentContext(userDataDir: string, options: types.LaunchPersistentOptions = {}): Promise<BrowserContext> {
options = validateLaunchOptions(options);
const persistent: types.BrowserContextOptions = options;
const controller = new ProgressController();
controller.setLogName('browser');
const browser = await controller.run(progress => {
return this._innerLaunch(progress, options, persistent, userDataDir).catch(e => { throw this._rewriteStartupError(e); });
}, TimeoutSettings.timeout(options));
return browser._defaultContext!;
}
async _innerLaunch(progress: Progress, options: types.LaunchOptions, persistent: types.BrowserContextOptions | undefined, userDataDir?: string): Promise<Browser> {
options.proxy = options.proxy ? normalizeProxySettings(options.proxy) : undefined;
const { browserProcess, downloadsPath, transport } = await this._launchProcess(progress, options, !!persistent, userDataDir);
if ((options as any).__testHookBeforeCreateBrowser)
await (options as any).__testHookBeforeCreateBrowser();
const browserOptions: BrowserOptions = {
name: this._name,
slowMo: options.slowMo,
persistent,
headful: !options.headless,
artifactsPath: options.artifactsPath,
downloadsPath,
browserProcess,
proxy: options.proxy,
};
if (persistent)
validateBrowserContextOptions(persistent, browserOptions);
copyTestHooks(options, browserOptions);
const browser = await this._connectToTransport(transport, browserOptions);
// We assume no control when using custom arguments, and do not prepare the default context in that case.
if (persistent && !options.ignoreAllDefaultArgs)
await browser._defaultContext!._loadDefaultContext(progress);
return browser;
}
private async _launchProcess(progress: Progress, options: types.LaunchOptions, isPersistent: boolean, userDataDir?: string): Promise<{ browserProcess: BrowserProcess, downloadsPath: string, transport: ConnectionTransport }> {
const {
ignoreDefaultArgs,
ignoreAllDefaultArgs,
args = [],
executablePath = null,
handleSIGINT = true,
handleSIGTERM = true,
handleSIGHUP = true,
} = options;
const env = options.env ? envArrayToObject(options.env) : process.env;
const tempDirectories = [];
const ensurePath = async (tmpPrefix: string, pathFromOptions?: string) => {
let dir;
if (pathFromOptions) {
dir = pathFromOptions;
await mkdirAsync(pathFromOptions, { recursive: true });
} else {
dir = await mkdtempAsync(tmpPrefix);
tempDirectories.push(dir);
}
return dir;
};
// TODO: use artifactsPath for downloads.
const downloadsPath = await ensurePath(DOWNLOADS_FOLDER, options.downloadsPath);
if (!userDataDir) {
userDataDir = await mkdtempAsync(path.join(os.tmpdir(), `playwright_${this._name}dev_profile-`));
tempDirectories.push(userDataDir);
}
const browserArguments = [];
if (ignoreAllDefaultArgs)
browserArguments.push(...args);
else if (ignoreDefaultArgs)
browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir).filter(arg => ignoreDefaultArgs.indexOf(arg) === -1));
else
browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir));
const executable = executablePath || this.executablePath();
if (!executable)
throw new Error(`No executable path is specified. Pass "executablePath" option directly.`);
if (!(await existsAsync(executable))) {
const errorMessageLines = [`Failed to launch ${this._name} because executable doesn't exist at ${executable}`];
// If we tried using stock downloaded browser, suggest re-installing playwright.
if (!executablePath)
errorMessageLines.push(`Try re-installing playwright with "npm install playwright"`);
throw new Error(errorMessageLines.join('\n'));
}
if (!executablePath) {
// We can only validate dependencies for bundled browsers.
await validateHostRequirements(this._browserPath, this._browserDescriptor);
}
// Note: it is important to define these variables before launchProcess, so that we don't get
// "Cannot access 'browserServer' before initialization" if something went wrong.
let transport: ConnectionTransport | undefined = undefined;
let browserProcess: BrowserProcess | undefined = undefined;
const { launchedProcess, gracefullyClose, kill } = await launchProcess({
executablePath: executable,
args: this._amendArguments(browserArguments),
env: this._amendEnvironment(env, userDataDir, executable, browserArguments),
handleSIGINT,
handleSIGTERM,
handleSIGHUP,
progress,
pipe: !this._webSocketNotPipe,
tempDirectories,
attemptToGracefullyClose: async () => {
if ((options as any).__testHookGracefullyClose)
await (options as any).__testHookGracefullyClose();
// We try to gracefully close to prevent crash reporting and core dumps.
// Note that it's fine to reuse the pipe transport, since
// our connection ignores kBrowserCloseMessageId.
this._attemptToGracefullyCloseBrowser(transport!);
},
onExit: (exitCode, signal) => {
if (browserProcess && browserProcess.onclose)
browserProcess.onclose(exitCode, signal);
},
});
browserProcess = {
onclose: undefined,
process: launchedProcess,
close: gracefullyClose,
kill
};
progress.cleanupWhenAborted(() => browserProcess && closeOrKill(browserProcess, progress.timeUntilDeadline()));
if (this._webSocketNotPipe) {
const match = await waitForLine(progress, launchedProcess, this._webSocketNotPipe.stream === 'stdout' ? launchedProcess.stdout : launchedProcess.stderr, this._webSocketNotPipe.webSocketRegex);
const innerEndpoint = match[1];
transport = await WebSocketTransport.connect(progress, innerEndpoint);
} else {
const stdio = launchedProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
transport = new PipeTransport(stdio[3], stdio[4]);
}
return { browserProcess, downloadsPath, transport };
}
abstract _defaultArgs(options: types.LaunchOptions, isPersistent: boolean, userDataDir: string): string[];
abstract _connectToTransport(transport: ConnectionTransport, options: BrowserOptions): Promise<Browser>;
abstract _amendEnvironment(env: Env, userDataDir: string, executable: string, browserArguments: string[]): Env;
abstract _amendArguments(browserArguments: string[]): string[];
abstract _rewriteStartupError(error: Error): Error;
abstract _attemptToGracefullyCloseBrowser(transport: ConnectionTransport): void;
}
function copyTestHooks(from: object, to: object) {
for (const [key, value] of Object.entries(from)) {
if (key.startsWith('__testHook'))
(to as any)[key] = value;
}
}
function validateLaunchOptions<Options extends types.LaunchOptions>(options: Options): Options {
const { devtools = false, headless = !isDebugMode() && !devtools } = options;
return { ...options, devtools, headless };
}
async function closeOrKill(browserProcess: BrowserProcess, timeout: number): Promise<void> {
let timer: NodeJS.Timer;
try {
await Promise.race([
browserProcess.close(),
new Promise((resolve, reject) => timer = setTimeout(reject, timeout)),
]);
} catch (ignored) {
await browserProcess.kill().catch(ignored => {}); // Make sure to await actual process exit.
} finally {
clearTimeout(timer!);
}
}
| src/server/browserType.ts | 1 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.9986996650695801,
0.20291265845298767,
0.0001677016553003341,
0.00017521684640087187,
0.3833148181438446
] |
{
"id": 0,
"code_window": [
" constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserTypeInitializer) {\n",
" super(parent, type, guid, initializer);\n",
" }\n",
"\n",
" executablePath(): string {\n",
" return this._initializer.executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this._initializer.executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n"
],
"file_path": "src/client/browserType.ts",
"type": "add",
"edit_start_line_idx": 56
} | // !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
256AC3DA0F4B6AC300CF336A /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 256AC3D90F4B6AC300CF336A /* AppDelegate.m */; };
51E244FA11EFCE07008228D2 /* MBToolbarItem.m in Sources */ = {isa = PBXBuildFile; fileRef = 51E244F911EFCE07008228D2 /* MBToolbarItem.m */; };
BC329487116A92E2008635D1 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = BC329486116A92E2008635D1 /* main.m */; };
BC329498116A941B008635D1 /* BrowserWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = BC329497116A941B008635D1 /* BrowserWindowController.m */; };
BC72B89511E57E07001EB4EB /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1DDD58150DA1D0A300B3202A /* MainMenu.xib */; };
BC72B89611E57E0F001EB4EB /* BrowserWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = BC3294A2116A9852008635D1 /* BrowserWindow.xib */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
1AFFEF761860EE6800DA465F /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; };
1AFFEF781860EE6800DA465F /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = System/Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; };
1DDD58150DA1D0A300B3202A /* MainMenu.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = MainMenu.xib; path = mac/MainMenu.xib; sourceTree = "<group>"; };
256AC3D80F4B6AC300CF336A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = mac/AppDelegate.h; sourceTree = "<group>"; };
256AC3D90F4B6AC300CF336A /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AppDelegate.m; path = mac/AppDelegate.m; sourceTree = "<group>"; };
256AC3F00F4B6AF500CF336A /* Playwright_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Playwright_Prefix.pch; path = mac/Playwright_Prefix.pch; sourceTree = "<group>"; };
29B97324FDCFA39411CA2CEB /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = "<absolute>"; };
29B97325FDCFA39411CA2CEB /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = "<absolute>"; };
37BAF90620218053000EA87A /* Playwright.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Playwright.entitlements; sourceTree = "<group>"; };
51E244F811EFCE07008228D2 /* MBToolbarItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MBToolbarItem.h; sourceTree = "<group>"; };
51E244F911EFCE07008228D2 /* MBToolbarItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MBToolbarItem.m; sourceTree = "<group>"; };
8D1107320486CEB800E47091 /* Playwright.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Playwright.app; sourceTree = BUILT_PRODUCTS_DIR; };
A1B89B95221E027A00EB4CEB /* SDKVariant.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = SDKVariant.xcconfig; sourceTree = "<group>"; };
BC329486116A92E2008635D1 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = mac/main.m; sourceTree = "<group>"; };
BC329496116A941B008635D1 /* BrowserWindowController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = BrowserWindowController.h; path = mac/BrowserWindowController.h; sourceTree = "<group>"; };
BC329497116A941B008635D1 /* BrowserWindowController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = BrowserWindowController.m; path = mac/BrowserWindowController.m; sourceTree = "<group>"; };
BC3294A2116A9852008635D1 /* BrowserWindow.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = BrowserWindow.xib; path = mac/BrowserWindow.xib; sourceTree = "<group>"; };
BC72B89A11E57E8A001EB4EB /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = mac/Info.plist; sourceTree = "<group>"; };
BCA8CBDD11E578A000812FB8 /* Base.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Base.xcconfig; sourceTree = "<group>"; };
BCA8CBDE11E578A000812FB8 /* DebugRelease.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = DebugRelease.xcconfig; sourceTree = "<group>"; };
BCA8CBDF11E578A000812FB8 /* Playwright.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Playwright.xcconfig; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
8D11072E0486CEB800E47091 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
080E96DDFE201D6D7F000002 /* Playwright */ = {
isa = PBXGroup;
children = (
256AC3D80F4B6AC300CF336A /* AppDelegate.h */,
256AC3D90F4B6AC300CF336A /* AppDelegate.m */,
BC72B89A11E57E8A001EB4EB /* Info.plist */,
BC329486116A92E2008635D1 /* main.m */,
51E244F811EFCE07008228D2 /* MBToolbarItem.h */,
51E244F911EFCE07008228D2 /* MBToolbarItem.m */,
37BAF90620218053000EA87A /* Playwright.entitlements */,
BC329496116A941B008635D1 /* BrowserWindowController.h */,
BC329497116A941B008635D1 /* BrowserWindowController.m */,
);
name = Playwright;
sourceTree = "<group>";
};
1058C7A2FEA54F0111CA2CBC /* Other Frameworks */ = {
isa = PBXGroup;
children = (
29B97324FDCFA39411CA2CEB /* AppKit.framework */,
1AFFEF781860EE6800DA465F /* CoreData.framework */,
29B97325FDCFA39411CA2CEB /* Foundation.framework */,
);
name = "Other Frameworks";
sourceTree = "<group>";
};
19C28FACFE9D520D11CA2CBC /* Products */ = {
isa = PBXGroup;
children = (
8D1107320486CEB800E47091 /* Playwright.app */,
);
name = Products;
sourceTree = "<group>";
};
29B97314FDCFA39411CA2CEB /* Playwright */ = {
isa = PBXGroup;
children = (
256AC3F00F4B6AF500CF336A /* Playwright_Prefix.pch */,
080E96DDFE201D6D7F000002 /* Playwright */,
29B97317FDCFA39411CA2CEB /* Resources */,
BCA8CBDA11E5787800812FB8 /* Configurations */,
29B97323FDCFA39411CA2CEB /* Frameworks */,
19C28FACFE9D520D11CA2CBC /* Products */,
);
name = Playwright;
sourceTree = "<group>";
};
29B97317FDCFA39411CA2CEB /* Resources */ = {
isa = PBXGroup;
children = (
BC3294A2116A9852008635D1 /* BrowserWindow.xib */,
1DDD58150DA1D0A300B3202A /* MainMenu.xib */,
);
name = Resources;
sourceTree = "<group>";
};
29B97323FDCFA39411CA2CEB /* Frameworks */ = {
isa = PBXGroup;
children = (
1058C7A2FEA54F0111CA2CBC /* Other Frameworks */,
1AFFEF761860EE6800DA465F /* Cocoa.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
BCA8CBDA11E5787800812FB8 /* Configurations */ = {
isa = PBXGroup;
children = (
BCA8CBDD11E578A000812FB8 /* Base.xcconfig */,
BCA8CBDE11E578A000812FB8 /* DebugRelease.xcconfig */,
BCA8CBDF11E578A000812FB8 /* Playwright.xcconfig */,
A1B89B95221E027A00EB4CEB /* SDKVariant.xcconfig */,
);
path = Configurations;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8D1107260486CEB800E47091 /* Playwright */ = {
isa = PBXNativeTarget;
buildConfigurationList = C01FCF4A08A954540054247C /* Build configuration list for PBXNativeTarget "Playwright" */;
buildPhases = (
8D1107290486CEB800E47091 /* Resources */,
8D11072C0486CEB800E47091 /* Sources */,
8D11072E0486CEB800E47091 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = Playwright;
productInstallPath = "$(HOME)/Applications";
productName = Playwright;
productReference = 8D1107320486CEB800E47091 /* Playwright.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
29B97313FDCFA39411CA2CEC /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 1000;
TargetAttributes = {
8D1107260486CEB800E47091 = {
SystemCapabilities = {
com.apple.Sandbox = {
enabled = 1;
};
};
};
};
};
buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "Playwright" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = en;
hasScannedForEncodings = 1;
knownRegions = (
en,
);
mainGroup = 29B97314FDCFA39411CA2CEB /* Playwright */;
projectDirPath = "";
projectRoot = "";
targets = (
8D1107260486CEB800E47091 /* Playwright */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
8D1107290486CEB800E47091 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
BC72B89611E57E0F001EB4EB /* BrowserWindow.xib in Resources */,
BC72B89511E57E07001EB4EB /* MainMenu.xib in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
8D11072C0486CEB800E47091 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
256AC3DA0F4B6AC300CF336A /* AppDelegate.m in Sources */,
BC329487116A92E2008635D1 /* main.m in Sources */,
51E244FA11EFCE07008228D2 /* MBToolbarItem.m in Sources */,
BC329498116A941B008635D1 /* BrowserWindowController.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C01FCF4B08A954540054247C /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = BCA8CBDF11E578A000812FB8 /* Playwright.xcconfig */;
buildSettings = {
};
name = Debug;
};
C01FCF4C08A954540054247B /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = BCA8CBDF11E578A000812FB8 /* Playwright.xcconfig */;
buildSettings = {
};
name = Release;
};
C01FCF4F08A954540054247C /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = BCA8CBDE11E578A000812FB8 /* DebugRelease.xcconfig */;
buildSettings = {
GCC_OPTIMIZATION_LEVEL = 0;
};
name = Debug;
};
C01FCF5008A954540054247C /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = BCA8CBDE11E578A000812FB8 /* DebugRelease.xcconfig */;
buildSettings = {
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C01FCF4A08A954540054247C /* Build configuration list for PBXNativeTarget "Playwright" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C01FCF4B08A954540054247C /* Debug */,
C01FCF4C08A954540054247B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C01FCF4E08A954540054247B /* Build configuration list for PBXProject "Playwright" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C01FCF4F08A954540054247C /* Debug */,
C01FCF5008A954540054247C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 29B97313FDCFA39411CA2CEC /* Project object */;
}
| browser_patches/webkit/embedder/Playwright/Playwright.xcodeproj/project.pbxproj | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.0002769219863694161,
0.00017229726654477417,
0.00016512841102667153,
0.00016730061906855553,
0.00002087419488816522
] |
{
"id": 0,
"code_window": [
" constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserTypeInitializer) {\n",
" super(parent, type, guid, initializer);\n",
" }\n",
"\n",
" executablePath(): string {\n",
" return this._initializer.executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this._initializer.executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n"
],
"file_path": "src/client/browserType.ts",
"type": "add",
"edit_start_line_idx": 56
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30320.27
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PrintDeps", "PrintDeps.vcxproj", "{90C6CF9B-BED7-41E9-904D-50BD303BACC8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Debug|x64.ActiveCfg = Debug|x64
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Debug|x64.Build.0 = Debug|x64
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Debug|x86.ActiveCfg = Debug|Win32
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Debug|x86.Build.0 = Debug|Win32
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Release|x64.ActiveCfg = Release|x64
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Release|x64.Build.0 = Release|x64
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Release|x86.ActiveCfg = Release|Win32
{90C6CF9B-BED7-41E9-904D-50BD303BACC8}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BD2E80ED-0995-43D3-918A-976F61655AD7}
EndGlobalSection
EndGlobal
| browser_patches/winldd/PrintDeps.sln | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00017143957666121423,
0.00017067493172362447,
0.00016987677372526377,
0.00017069169552996755,
7.649232429685071e-7
] |
{
"id": 0,
"code_window": [
" constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserTypeInitializer) {\n",
" super(parent, type, guid, initializer);\n",
" }\n",
"\n",
" executablePath(): string {\n",
" return this._initializer.executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this._initializer.executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n"
],
"file_path": "src/client/browserType.ts",
"type": "add",
"edit_start_line_idx": 56
} | body {
background-color: pink;
}
| test/assets/cached/one-style.css | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.0001728004135657102,
0.0001728004135657102,
0.0001728004135657102,
0.0001728004135657102,
0
] |
{
"id": 1,
"code_window": [
"type WebSocketNotPipe = { webSocketRegex: RegExp, stream: 'stdout' | 'stderr' };\n",
"\n",
"export abstract class BrowserType {\n",
" private _name: string;\n",
" private _executablePath: string | undefined;\n",
" private _webSocketNotPipe: WebSocketNotPipe | null;\n",
" private _browserDescriptor: browserPaths.BrowserDescriptor;\n",
" readonly _browserPath: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" private _executablePath: string;\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as util from 'util';
import { BrowserContext, normalizeProxySettings, validateBrowserContextOptions } from './browserContext';
import * as browserPaths from '../utils/browserPaths';
import { ConnectionTransport, WebSocketTransport } from './transport';
import { BrowserOptions, Browser, BrowserProcess } from './browser';
import { launchProcess, Env, waitForLine, envArrayToObject } from './processLauncher';
import { PipeTransport } from './pipeTransport';
import { Progress, ProgressController } from './progress';
import * as types from './types';
import { TimeoutSettings } from '../utils/timeoutSettings';
import { validateHostRequirements } from './validateDependencies';
import { isDebugMode } from '../utils/utils';
const mkdirAsync = util.promisify(fs.mkdir);
const mkdtempAsync = util.promisify(fs.mkdtemp);
const existsAsync = (path: string): Promise<boolean> => new Promise(resolve => fs.stat(path, err => resolve(!err)));
const DOWNLOADS_FOLDER = path.join(os.tmpdir(), 'playwright_downloads-');
type WebSocketNotPipe = { webSocketRegex: RegExp, stream: 'stdout' | 'stderr' };
export abstract class BrowserType {
private _name: string;
private _executablePath: string | undefined;
private _webSocketNotPipe: WebSocketNotPipe | null;
private _browserDescriptor: browserPaths.BrowserDescriptor;
readonly _browserPath: string;
constructor(packagePath: string, browser: browserPaths.BrowserDescriptor, webSocketOrPipe: WebSocketNotPipe | null) {
this._name = browser.name;
const browsersPath = browserPaths.browsersPath(packagePath);
this._browserDescriptor = browser;
this._browserPath = browserPaths.browserDirectory(browsersPath, browser);
this._executablePath = browserPaths.executablePath(this._browserPath, browser);
this._webSocketNotPipe = webSocketOrPipe;
}
executablePath(): string {
if (!this._executablePath)
throw new Error('Browser is not supported on current platform');
return this._executablePath;
}
name(): string {
return this._name;
}
async launch(options: types.LaunchOptions = {}): Promise<Browser> {
options = validateLaunchOptions(options);
const controller = new ProgressController();
controller.setLogName('browser');
const browser = await controller.run(progress => {
return this._innerLaunch(progress, options, undefined).catch(e => { throw this._rewriteStartupError(e); });
}, TimeoutSettings.timeout(options));
return browser;
}
async launchPersistentContext(userDataDir: string, options: types.LaunchPersistentOptions = {}): Promise<BrowserContext> {
options = validateLaunchOptions(options);
const persistent: types.BrowserContextOptions = options;
const controller = new ProgressController();
controller.setLogName('browser');
const browser = await controller.run(progress => {
return this._innerLaunch(progress, options, persistent, userDataDir).catch(e => { throw this._rewriteStartupError(e); });
}, TimeoutSettings.timeout(options));
return browser._defaultContext!;
}
async _innerLaunch(progress: Progress, options: types.LaunchOptions, persistent: types.BrowserContextOptions | undefined, userDataDir?: string): Promise<Browser> {
options.proxy = options.proxy ? normalizeProxySettings(options.proxy) : undefined;
const { browserProcess, downloadsPath, transport } = await this._launchProcess(progress, options, !!persistent, userDataDir);
if ((options as any).__testHookBeforeCreateBrowser)
await (options as any).__testHookBeforeCreateBrowser();
const browserOptions: BrowserOptions = {
name: this._name,
slowMo: options.slowMo,
persistent,
headful: !options.headless,
artifactsPath: options.artifactsPath,
downloadsPath,
browserProcess,
proxy: options.proxy,
};
if (persistent)
validateBrowserContextOptions(persistent, browserOptions);
copyTestHooks(options, browserOptions);
const browser = await this._connectToTransport(transport, browserOptions);
// We assume no control when using custom arguments, and do not prepare the default context in that case.
if (persistent && !options.ignoreAllDefaultArgs)
await browser._defaultContext!._loadDefaultContext(progress);
return browser;
}
private async _launchProcess(progress: Progress, options: types.LaunchOptions, isPersistent: boolean, userDataDir?: string): Promise<{ browserProcess: BrowserProcess, downloadsPath: string, transport: ConnectionTransport }> {
const {
ignoreDefaultArgs,
ignoreAllDefaultArgs,
args = [],
executablePath = null,
handleSIGINT = true,
handleSIGTERM = true,
handleSIGHUP = true,
} = options;
const env = options.env ? envArrayToObject(options.env) : process.env;
const tempDirectories = [];
const ensurePath = async (tmpPrefix: string, pathFromOptions?: string) => {
let dir;
if (pathFromOptions) {
dir = pathFromOptions;
await mkdirAsync(pathFromOptions, { recursive: true });
} else {
dir = await mkdtempAsync(tmpPrefix);
tempDirectories.push(dir);
}
return dir;
};
// TODO: use artifactsPath for downloads.
const downloadsPath = await ensurePath(DOWNLOADS_FOLDER, options.downloadsPath);
if (!userDataDir) {
userDataDir = await mkdtempAsync(path.join(os.tmpdir(), `playwright_${this._name}dev_profile-`));
tempDirectories.push(userDataDir);
}
const browserArguments = [];
if (ignoreAllDefaultArgs)
browserArguments.push(...args);
else if (ignoreDefaultArgs)
browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir).filter(arg => ignoreDefaultArgs.indexOf(arg) === -1));
else
browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir));
const executable = executablePath || this.executablePath();
if (!executable)
throw new Error(`No executable path is specified. Pass "executablePath" option directly.`);
if (!(await existsAsync(executable))) {
const errorMessageLines = [`Failed to launch ${this._name} because executable doesn't exist at ${executable}`];
// If we tried using stock downloaded browser, suggest re-installing playwright.
if (!executablePath)
errorMessageLines.push(`Try re-installing playwright with "npm install playwright"`);
throw new Error(errorMessageLines.join('\n'));
}
if (!executablePath) {
// We can only validate dependencies for bundled browsers.
await validateHostRequirements(this._browserPath, this._browserDescriptor);
}
// Note: it is important to define these variables before launchProcess, so that we don't get
// "Cannot access 'browserServer' before initialization" if something went wrong.
let transport: ConnectionTransport | undefined = undefined;
let browserProcess: BrowserProcess | undefined = undefined;
const { launchedProcess, gracefullyClose, kill } = await launchProcess({
executablePath: executable,
args: this._amendArguments(browserArguments),
env: this._amendEnvironment(env, userDataDir, executable, browserArguments),
handleSIGINT,
handleSIGTERM,
handleSIGHUP,
progress,
pipe: !this._webSocketNotPipe,
tempDirectories,
attemptToGracefullyClose: async () => {
if ((options as any).__testHookGracefullyClose)
await (options as any).__testHookGracefullyClose();
// We try to gracefully close to prevent crash reporting and core dumps.
// Note that it's fine to reuse the pipe transport, since
// our connection ignores kBrowserCloseMessageId.
this._attemptToGracefullyCloseBrowser(transport!);
},
onExit: (exitCode, signal) => {
if (browserProcess && browserProcess.onclose)
browserProcess.onclose(exitCode, signal);
},
});
browserProcess = {
onclose: undefined,
process: launchedProcess,
close: gracefullyClose,
kill
};
progress.cleanupWhenAborted(() => browserProcess && closeOrKill(browserProcess, progress.timeUntilDeadline()));
if (this._webSocketNotPipe) {
const match = await waitForLine(progress, launchedProcess, this._webSocketNotPipe.stream === 'stdout' ? launchedProcess.stdout : launchedProcess.stderr, this._webSocketNotPipe.webSocketRegex);
const innerEndpoint = match[1];
transport = await WebSocketTransport.connect(progress, innerEndpoint);
} else {
const stdio = launchedProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
transport = new PipeTransport(stdio[3], stdio[4]);
}
return { browserProcess, downloadsPath, transport };
}
abstract _defaultArgs(options: types.LaunchOptions, isPersistent: boolean, userDataDir: string): string[];
abstract _connectToTransport(transport: ConnectionTransport, options: BrowserOptions): Promise<Browser>;
abstract _amendEnvironment(env: Env, userDataDir: string, executable: string, browserArguments: string[]): Env;
abstract _amendArguments(browserArguments: string[]): string[];
abstract _rewriteStartupError(error: Error): Error;
abstract _attemptToGracefullyCloseBrowser(transport: ConnectionTransport): void;
}
function copyTestHooks(from: object, to: object) {
for (const [key, value] of Object.entries(from)) {
if (key.startsWith('__testHook'))
(to as any)[key] = value;
}
}
function validateLaunchOptions<Options extends types.LaunchOptions>(options: Options): Options {
const { devtools = false, headless = !isDebugMode() && !devtools } = options;
return { ...options, devtools, headless };
}
async function closeOrKill(browserProcess: BrowserProcess, timeout: number): Promise<void> {
let timer: NodeJS.Timer;
try {
await Promise.race([
browserProcess.close(),
new Promise((resolve, reject) => timer = setTimeout(reject, timeout)),
]);
} catch (ignored) {
await browserProcess.kill().catch(ignored => {}); // Make sure to await actual process exit.
} finally {
clearTimeout(timer!);
}
}
| src/server/browserType.ts | 1 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.9974984526634216,
0.19683073461055756,
0.00016923782823141664,
0.0022987176198512316,
0.3643917143344879
] |
{
"id": 1,
"code_window": [
"type WebSocketNotPipe = { webSocketRegex: RegExp, stream: 'stdout' | 'stderr' };\n",
"\n",
"export abstract class BrowserType {\n",
" private _name: string;\n",
" private _executablePath: string | undefined;\n",
" private _webSocketNotPipe: WebSocketNotPipe | null;\n",
" private _browserDescriptor: browserPaths.BrowserDescriptor;\n",
" readonly _browserPath: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" private _executablePath: string;\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 41
} | # Setting Up Build Bots
We currently have 5 build bots that produce 9 browser builds:
- **`buildbot-ubuntu-18.04`**
- `firefox-ubuntu-18.04.zip`
- `webkit-ubuntu-18.04.zip`
- **`buildbot-ubuntu-20.04`**
- `webkit-ubuntu-20.04.zip`
- **`buildbot-mac-10.14`**
- `firefox-mac-10.14.zip`
- `webkit-mac-10.14.zip`
- **`buildbot-mac-10.15`**
- `webkit-mac-10.15.zip`
- **`buildbot-windows`**
- `firefox-win32.zip`
- `firefox-win64.zip`
- `webkit-win64.zip`
This document describes setting up bots infrastructure to produce
browser builds.
Each bot configuration has 3 parts:
1. Setup toolchains to build browsers
2. Setup bot-specific environment required for bot operations
- `azure-cli`
- setting `AZ_ACCOUNT_KEY`, `AZ_ACCOUNT_NAME`, `TELEGRAM_BOT_KEY` env variables
3. Running relevant build script `//browser_patches/buildbots/buildbot-*.sh` using host scheduling system (cron on Linux, launchctl on Mac, polling on Win).
- [Windows](#windows)
- [Setting Up Browser Toolchains](#setting-up-browser-toolchains)
- [Setting Bot Environment](#setting-bot-environment)
- [Running Build Loop](#running-build-loop)
- [Mac](#mac)
- [Setting Up Browser Toolchains](#setting-up-browser-toolchains-1)
- [Setting Bot Environment](#setting-bot-environment-1)
- [Running Build Loop](#running-build-loop-1)
- [Linux](#linux)
- [Setting Up Browser Toolchains](#setting-up-browser-toolchains-2)
- [Setting Bot Environment](#setting-bot-environment-2)
- [Running Build Loop](#running-build-loop-2)
# Windows
## Setting Up Browser Toolchains
We currently use MINGW environment that comes with Firefox to run our buildbot infrastructure on Windows.
Browser toolchains:
- Firefox: Follow instructions on [Building Firefox for Windows](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions/Windows_Prerequisites). Get the checkout with mercurial and run "./mach bootstrap" from mercurial root.
- WebKit: mostly follow instructions on [Building WebKit For Windows](https://trac.webkit.org/wiki/BuildingCairoOnWindows). Use chocolatey to install dependencies; we don't use clang to compile webkit on windows. (**NOTE**: we didn't need to install pywin32 with pip and just skipped that step).
- Our WebKit port requires libvpx. Install [vcpkg](https://github.com/Microsoft/vcpkg) and build libvpx from source. Run the following commands in Windows Terminal as Administrator(required for bootstrap-vcpkg.bat).
```bash
cd c:\
git clone https://github.com/microsoft/vcpkg.git
cd vcpkg
.\bootstrap-vcpkg.bat
.\vcpkg.exe install libvpx --triplet x64-windows
```
If you install vcpkg in a different location, cmake files should be pointed to the new location (see `-DLIBVPX_PACKAGE_PATH` parameter in [`buildwin.bat`](https://github.com/microsoft/playwright/blob/master/browser_patches/webkit/buildwin.bat)).
After this step, you should:
- have `c:\mozilla-build` folder and `c:\mozilla-source` folder with firefox checkout.
- being able to build webkit-cairo from `cmd.exe`.
## Setting Bot Environment
### 1. Install azure-cli
Install [azure-cli](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-windows?view=azure-cli-latest) for windows using MS Installer
### 2. Export "az" to the mingw world
The easiest away to export "az" to mingw is to create `c:\mozilla-build\bin\az` with the following content:
```
cmd.exe /c "\"C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd\" $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15} ${16}"
```
### 3. Install node.js
Node.js: https://nodejs.org/en/download/
### 4. Set custom env variables to mingw env
Edit `c:\mozilla-build\start-shell.bat` and add the following lines in the beginning:
```bat
SET AZ_ACCOUNT_NAME=<account-name>
SET AZ_ACCOUNT_KEY=<account-key>
SET TELEGRAM_BOT_KEY=<bot_key>
SET WEBKIT_BUILD_PATH=<value of "PATH" variable from cmd.exe>
SET DEVENV="C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.com"
```
> **NOTE:** mind different quotes position in DEVENV="..." than in PATH (and WEBKIT_BUILD_PATH). This is important.
And right before the `REM Start shell.`, change `PATH` to export locally-installed node.js:
```bat
SET "PATH=C:\Program Files\nodejs\;%PATH%"
```
Remarks:
- the `WEBKIT_BUILD_PATH` value is the value of `PATH` variable. To get the value, run `cmd.exe` and run `PATH` command.
- the `DEVENV` variable should point to VS2019 devenv executable.
- change `<account-name>` and `<account-key>` with relevant keys/names.
> **NOTE:** No spaces or quotes are allowed here!
### 5. Disable git autocrlf and enable longpaths
Run `c:\mozilla-build\start-shell.bat` and run:
- `git config --global core.autocrlf false`
- `git config --global core.longpaths true`
The `core.longpaths` is needed for webkit since it has some very long layout paths.
> **NOTE:** If git config fails, run shell as administrator!
### 6. Checkout Playwright to /c/
Run `c:\mozilla-build\start-shell.bat` and checkout Playwright repo to `/c/playwright`.
### 7. Create a c:\WEBKIT_WIN64_LIBS\ directory with win64 dlls
Create a new `c:\WEBKIT_WIN64_LIBS` folder and copy the following libraries from `C:\Windows\System32` into it:
- `msvcp140.dll`
- `msvcp140_2.dll`
- `vcruntime140.dll`
- `vcruntime140_1.dll`
> **NOTE**: these libraries are expected by `//browser_patches/webkit/archive.sh`.
This is necessary since mingw is a 32-bit application and cannot access the `C:\Windows\System32` folder due to [Windows FileSystem Redirector](https://docs.microsoft.com/en-us/windows/win32/winprog64/file-system-redirector?redirectedfrom=MSDN). ([StackOverflow question](https://stackoverflow.com/questions/18982551/is-mingw-caching-windows-directory-contents))
## Running Build Loop
1. Launch `c:\mozilla-build/start-shell.bat`
2. Run `/c/playwright/browser_patches/buildbots/buildbot-windows.sh`
3. Disable "QuickEdit" terminal mode to avoid [terminal freezing and postponing builds](https://stackoverflow.com/questions/33883530/why-is-my-command-prompt-freezing-on-windows-10)
# Mac
## Setting Up Browser Toolchains
1. Install XCode from AppStore
2. Run XCode once and install components, if it requires any.
2. Install XCode command-line tools: `xcode-select --install`
3. Install homebrew: https://brew.sh/
Mac 10.14 builds both firefox and webkit, whereas we only build webkit on mac 10.15.
Browser Toolchains:
- [Building Firefox On Mac](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions/Mac_OS_X_Prerequisites)
- [Building WebKit On Mac](https://webkit.org/building-webkit/) (though as of Dec, 2019 it does not require any additional steps)
## Setting Bot Environment
1. Install [`azure-cli`](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-macos?view=azure-cli-latest)
2. Clone `https://github.com/microsoft/playwright`
3. Run `//browser_patches/prepare_checkout.sh` for every browser you care about
4. Make sure `//browser_patches/{webkit,firefox}/build.sh` works and compiles browsers
## Running Build Loop
We use `launchctl` on Mac instead of cron since launchctl lets us run daemons even for non-logged-in users.
Create a `/Library/LaunchDaemons/dev.playwright.plist` with the contents below (will require `sudo` access).
Make sure to change the following fields:
1. Set values for all keys in the `EnvironmentVariables` dict.
2. Put a proper path to the `Program`
3. Make sure to put correct `UserName`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>dev.playwright</string>
<key>Program</key>
<string>/Users/aslushnikov/prog/cron/playwright/browser_patches/buildbots/buildbot-mac-10.14.sh</string>
<key>UserName</key>
<string>aslushnikov</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/bin:/usr/sbin</string>
<key>TELEGRAM_BOT_KEY</key>
<string></string>
<key>AZ_ACCOUNT_NAME</key>
<string></string>
<key>AZ_ACCOUNT_KEY</key>
<string></string>
<key>MOZ_NOSPAM</key>
<string>1</string>
</dict>
<key>StandardOutPath</key>
<string>/tmp/launchctl-playwright-buildbot.log</string>
<key>StandardErrorPath</key>
<string>/tmp/launchctl-playwright-buildbot.errorlog</string>
<key>StartInterval</key>
<integer>300</integer>
</dict>
</plist>
```
Next, you can either use `launchctl load` command to load the daemon, or reboot bot to make sure it auto-starts.
> **NOTE**: mozbuild uses [terminal-notifier](https://github.com/julienXX/terminal-notifier) which hangs
> in launchctl environment. The `MOZ_NOSPAM` env variable disables terminal notifications.
Finally, MacBooks tend to go to sleep no matter what their "energy settings" are. To disable sleep permanently on Macs ([source](https://gist.github.com/pwnsdx/2ae98341e7e5e64d32b734b871614915)):
```sh
sudo pmset -a sleep 0; sudo pmset -a hibernatemode 0; sudo pmset -a disablesleep 1;
```
# Linux
## Setting Up Browser Toolchains
1. Note: firefox binaries will crash randomly if compiled with clang 6. They do work when compiled with clang 9.
To install clang 9 on ubuntu and make it default:
```sh
$ sudo apt-get install clang-9
$ sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-9 100
$ sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-9 100
```
2. FFMPEG cross-compilation requires Docker. Install docker and add `$USER` to docker for sudo-less docker access
```sh
$ sudo apt-get install -y docker.io # install docker
$ sudo usermod -aG docker $USER # add user to docker group
$ newgrp docker # activate group changes
```
> **NOTE**: Firefox build config can be checked official Firefox builds, navigating to `about:buildconfig` URL.
To document precisely my steps to bring up bots:
- [July 22, 2020: Setting up Ubuntu 18.04 buildbot on Azure](https://gist.github.com/aslushnikov/a4a3823b894888546e741899e69a1d8e)
- [July 22, 2020: Setting up Ubuntu 20.04 buildbot on Azure](https://gist.github.com/aslushnikov/a0bd658b575022e198443f856b5185e7)
| browser_patches/buildbots/README.md | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00024385539290960878,
0.00017544999718666077,
0.00016366090858355165,
0.00016781373415142298,
0.000018288017599843442
] |
{
"id": 1,
"code_window": [
"type WebSocketNotPipe = { webSocketRegex: RegExp, stream: 'stdout' | 'stderr' };\n",
"\n",
"export abstract class BrowserType {\n",
" private _name: string;\n",
" private _executablePath: string | undefined;\n",
" private _webSocketNotPipe: WebSocketNotPipe | null;\n",
" private _browserDescriptor: browserPaths.BrowserDescriptor;\n",
" readonly _browserPath: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" private _executablePath: string;\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 41
} | <?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1140"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8D1107260486CEB800E47090"
BuildableName = "Playwright.app"
BlueprintName = "Playwright"
ReferencedContainer = "container:Playwright.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8D1107260486CEB800E47090"
BuildableName = "Playwright.app"
BlueprintName = "Playwright"
ReferencedContainer = "container:Playwright.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8D1107260486CEB800E47090"
BuildableName = "Playwright.app"
BlueprintName = "Playwright"
ReferencedContainer = "container:Playwright.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
| browser_patches/webkit/embedder/Playwright/Playwright.xcodeproj/xcshareddata/xcschemes/Playwright.xcscheme | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00017412492888979614,
0.00017176948313135654,
0.0001678909466136247,
0.00017259892774745822,
0.000002168390437873313
] |
{
"id": 1,
"code_window": [
"type WebSocketNotPipe = { webSocketRegex: RegExp, stream: 'stdout' | 'stderr' };\n",
"\n",
"export abstract class BrowserType {\n",
" private _name: string;\n",
" private _executablePath: string | undefined;\n",
" private _webSocketNotPipe: WebSocketNotPipe | null;\n",
" private _browserDescriptor: browserPaths.BrowserDescriptor;\n",
" readonly _browserPath: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" private _executablePath: string;\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 41
} | output
| packages/installation-tests/.gitignore | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00017021984967868775,
0.00017021984967868775,
0.00017021984967868775,
0.00017021984967868775,
0
] |
{
"id": 2,
"code_window": [
" const browsersPath = browserPaths.browsersPath(packagePath);\n",
" this._browserDescriptor = browser;\n",
" this._browserPath = browserPaths.browserDirectory(browsersPath, browser);\n",
" this._executablePath = browserPaths.executablePath(this._browserPath, browser);\n",
" this._webSocketNotPipe = webSocketOrPipe;\n",
" }\n",
"\n",
" executablePath(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._executablePath = browserPaths.executablePath(this._browserPath, browser) || '';\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as channels from '../protocol/channels';
import { Browser } from './browser';
import { BrowserContext } from './browserContext';
import { ChannelOwner } from './channelOwner';
import { LaunchOptions, LaunchServerOptions, ConnectOptions, LaunchPersistentContextOptions } from './types';
import * as WebSocket from 'ws';
import { Connection } from './connection';
import { serializeError } from '../protocol/serializers';
import { Events } from './events';
import { TimeoutSettings } from '../utils/timeoutSettings';
import { ChildProcess } from 'child_process';
import { envObjectToArray } from './clientHelper';
import { validateHeaders } from './network';
import { assert, makeWaitForNextTask, headersObjectToArray } from '../utils/utils';
import { SelectorsOwner, sharedSelectors } from './selectors';
export interface BrowserServerLauncher {
launchServer(options?: LaunchServerOptions): Promise<BrowserServer>;
}
export interface BrowserServer {
process(): ChildProcess;
wsEndpoint(): string;
close(): Promise<void>;
kill(): Promise<void>;
}
export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel, channels.BrowserTypeInitializer> {
private _timeoutSettings = new TimeoutSettings();
_serverLauncher?: BrowserServerLauncher;
static from(browserType: channels.BrowserTypeChannel): BrowserType {
return (browserType as any)._object;
}
constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserTypeInitializer) {
super(parent, type, guid, initializer);
}
executablePath(): string {
return this._initializer.executablePath;
}
name(): string {
return this._initializer.name;
}
async launch(options: LaunchOptions = {}): Promise<Browser> {
const logger = options.logger;
return this._wrapApiCall('browserType.launch', async () => {
assert(!(options as any).userDataDir, 'userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead');
assert(!(options as any).port, 'Cannot specify a port without launching as a server.');
const launchOptions: channels.BrowserTypeLaunchParams = {
...options,
ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined,
ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),
env: options.env ? envObjectToArray(options.env) : undefined,
};
const browser = Browser.from((await this._channel.launch(launchOptions)).browser);
browser._logger = logger;
return browser;
}, logger);
}
async launchServer(options: LaunchServerOptions = {}): Promise<BrowserServer> {
if (!this._serverLauncher)
throw new Error('Launching server is not supported');
return this._serverLauncher.launchServer(options);
}
async launchPersistentContext(userDataDir: string, options: LaunchPersistentContextOptions = {}): Promise<BrowserContext> {
const logger = options.logger;
return this._wrapApiCall('browserType.launchPersistentContext', async () => {
assert(!(options as any).port, 'Cannot specify a port without launching as a server.');
if (options.extraHTTPHeaders)
validateHeaders(options.extraHTTPHeaders);
const persistentOptions: channels.BrowserTypeLaunchPersistentContextParams = {
...options,
viewport: options.viewport === null ? undefined : options.viewport,
noDefaultViewport: options.viewport === null,
ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined,
ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),
env: options.env ? envObjectToArray(options.env) : undefined,
extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
userDataDir,
};
const result = await this._channel.launchPersistentContext(persistentOptions);
const context = BrowserContext.from(result.context);
context._logger = logger;
return context;
}, logger);
}
async connect(options: ConnectOptions): Promise<Browser> {
const logger = options.logger;
return this._wrapApiCall('browserType.connect', async () => {
const connection = new Connection();
const ws = new WebSocket(options.wsEndpoint, [], {
perMessageDeflate: false,
maxPayload: 256 * 1024 * 1024, // 256Mb,
handshakeTimeout: this._timeoutSettings.timeout(options),
});
// The 'ws' module in node sometimes sends us multiple messages in a single task.
const waitForNextTask = options.slowMo
? (cb: () => any) => setTimeout(cb, options.slowMo)
: makeWaitForNextTask();
connection.onmessage = message => {
if (ws.readyState !== WebSocket.OPEN) {
setTimeout(() => {
connection.dispatch({ id: (message as any).id, error: serializeError(new Error('Browser has been closed')) });
}, 0);
return;
}
ws.send(JSON.stringify(message));
};
ws.addEventListener('message', event => {
waitForNextTask(() => connection.dispatch(JSON.parse(event.data)));
});
return await new Promise<Browser>(async (fulfill, reject) => {
if ((options as any).__testHookBeforeCreateBrowser) {
try {
await (options as any).__testHookBeforeCreateBrowser();
} catch (e) {
reject(e);
}
}
ws.addEventListener('open', async () => {
const remoteBrowser = await connection.waitForObjectWithKnownName('remoteBrowser') as RemoteBrowser;
// Inherit shared selectors for connected browser.
const selectorsOwner = SelectorsOwner.from(remoteBrowser._initializer.selectors);
sharedSelectors._addChannel(selectorsOwner);
const browser = Browser.from(remoteBrowser._initializer.browser);
browser._logger = logger;
browser._isRemote = true;
const closeListener = () => {
// Emulate all pages, contexts and the browser closing upon disconnect.
for (const context of browser.contexts()) {
for (const page of context.pages())
page._onClose();
context._onClose();
}
browser._didClose();
};
ws.addEventListener('close', closeListener);
browser.on(Events.Browser.Disconnected, () => {
sharedSelectors._removeChannel(selectorsOwner);
ws.removeEventListener('close', closeListener);
ws.close();
});
fulfill(browser);
});
ws.addEventListener('error', event => {
ws.close();
reject(new Error('WebSocket error: ' + event.message));
});
});
}, logger);
}
}
export class RemoteBrowser extends ChannelOwner<channels.RemoteBrowserChannel, channels.RemoteBrowserInitializer> {
}
| src/client/browserType.ts | 1 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00595095893368125,
0.0007410926045849919,
0.0001660064881434664,
0.00017338320321869105,
0.0015125857898965478
] |
{
"id": 2,
"code_window": [
" const browsersPath = browserPaths.browsersPath(packagePath);\n",
" this._browserDescriptor = browser;\n",
" this._browserPath = browserPaths.browserDirectory(browsersPath, browser);\n",
" this._executablePath = browserPaths.executablePath(this._browserPath, browser);\n",
" this._webSocketNotPipe = webSocketOrPipe;\n",
" }\n",
"\n",
" executablePath(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._executablePath = browserPaths.executablePath(this._browserPath, browser) || '';\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 51
} | ### class: Foo
#### event: 'start'
#### event: 'stop'
| utils/doclint/check_public_api/test/diff-events/doc.md | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.0001752631360432133,
0.0001752631360432133,
0.0001752631360432133,
0.0001752631360432133,
0
] |
{
"id": 2,
"code_window": [
" const browsersPath = browserPaths.browsersPath(packagePath);\n",
" this._browserDescriptor = browser;\n",
" this._browserPath = browserPaths.browserDirectory(browsersPath, browser);\n",
" this._executablePath = browserPaths.executablePath(this._browserPath, browser);\n",
" this._webSocketNotPipe = webSocketOrPipe;\n",
" }\n",
"\n",
" executablePath(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._executablePath = browserPaths.executablePath(this._browserPath, browser) || '';\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 51
} | {
"name": "Playwright",
"image": "mcr.microsoft.com/playwright:next",
"postCreateCommand": "npm install && npm run build && apt-get update && apt-get install -y software-properties-common && curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - && add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" && apt-get install -y docker-ce-cli",
"settings": {
"terminal.integrated.shell.linux": "/bin/bash"
},
"runArgs": [
"-v", "/var/run/docker.sock:/var/run/docker.sock"
]
} | .devcontainer/devcontainer.json | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00017793149163480848,
0.00017506530275568366,
0.0001721990993246436,
0.00017506530275568366,
0.0000028661961550824344
] |
{
"id": 2,
"code_window": [
" const browsersPath = browserPaths.browsersPath(packagePath);\n",
" this._browserDescriptor = browser;\n",
" this._browserPath = browserPaths.browserDirectory(browsersPath, browser);\n",
" this._executablePath = browserPaths.executablePath(this._browserPath, browser);\n",
" this._webSocketNotPipe = webSocketOrPipe;\n",
" }\n",
"\n",
" executablePath(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._executablePath = browserPaths.executablePath(this._browserPath, browser) || '';\n"
],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /**
* Copyright 2017 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as dom from './dom';
import * as frames from './frames';
import * as input from './input';
import * as js from './javascript';
import * as network from './network';
import { Screenshotter } from './screenshotter';
import { TimeoutSettings } from '../utils/timeoutSettings';
import * as types from './types';
import { BrowserContext } from './browserContext';
import { ConsoleMessage } from './console';
import * as accessibility from './accessibility';
import { EventEmitter } from 'events';
import { FileChooser } from './fileChooser';
import { ProgressController, runAbortableTask } from './progress';
import { assert, isError } from '../utils/utils';
import { debugLogger } from '../utils/debugLogger';
import { Selectors } from './selectors';
export interface PageDelegate {
readonly rawMouse: input.RawMouse;
readonly rawKeyboard: input.RawKeyboard;
opener(): Promise<Page | null>;
reload(): Promise<void>;
goBack(): Promise<boolean>;
goForward(): Promise<boolean>;
exposeBinding(binding: PageBinding): Promise<void>;
evaluateOnNewDocument(source: string): Promise<void>;
closePage(runBeforeUnload: boolean): Promise<void>;
navigateFrame(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult>;
updateExtraHTTPHeaders(): Promise<void>;
setViewportSize(viewportSize: types.Size): Promise<void>;
updateEmulateMedia(): Promise<void>;
updateRequestInterception(): Promise<void>;
setFileChooserIntercepted(enabled: boolean): Promise<void>;
bringToFront(): Promise<void>;
canScreenshotOutsideViewport(): boolean;
resetViewport(): Promise<void>; // Only called if canScreenshotOutsideViewport() returns false.
setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void>;
startScreencast(options: types.PageScreencastOptions): Promise<void>;
stopScreencast(): Promise<void>;
takeScreenshot(format: string, documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined): Promise<Buffer>;
isElementHandle(remoteObject: any): boolean;
adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>>;
getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null>; // Only called for frame owner elements.
getOwnerFrame(handle: dom.ElementHandle): Promise<string | null>; // Returns frameId.
getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null>;
setInputFiles(handle: dom.ElementHandle<HTMLInputElement>, files: types.FilePayload[]): Promise<void>;
getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null>;
getFrameElement(frame: frames.Frame): Promise<dom.ElementHandle>;
scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<'error:notvisible' | 'error:notconnected' | 'done'>;
getAccessibilityTree(needle?: dom.ElementHandle): Promise<{tree: accessibility.AXNode, needle: accessibility.AXNode | null}>;
pdf?: (options?: types.PDFOptions) => Promise<Buffer>;
coverage?: () => any;
// Work around WebKit's raf issues on Windows.
rafCountForStablePosition(): number;
// Work around Chrome's non-associated input and protocol.
inputActionEpilogue(): Promise<void>;
// Work around for asynchronously dispatched CSP errors in Firefox.
readonly cspErrorsAsynchronousForInlineScipts?: boolean;
}
type PageState = {
viewportSize: types.Size | null;
mediaType: types.MediaType | null;
colorScheme: types.ColorScheme | null;
extraHTTPHeaders: types.HeadersArray | null;
};
export class Page extends EventEmitter {
static Events = {
Close: 'close',
Crash: 'crash',
Console: 'console',
Dialog: 'dialog',
Download: 'download',
FileChooser: 'filechooser',
DOMContentLoaded: 'domcontentloaded',
// Can't use just 'error' due to node.js special treatment of error events.
// @see https://nodejs.org/api/events.html#events_error_events
PageError: 'pageerror',
Request: 'request',
Response: 'response',
RequestFailed: 'requestfailed',
RequestFinished: 'requestfinished',
FrameAttached: 'frameattached',
FrameDetached: 'framedetached',
FrameNavigated: 'framenavigated',
Load: 'load',
Popup: 'popup',
Worker: 'worker',
VideoStarted: 'videostarted',
};
private _closedState: 'open' | 'closing' | 'closed' = 'open';
private _closedCallback: () => void;
private _closedPromise: Promise<void>;
private _disconnected = false;
private _disconnectedCallback: (e: Error) => void;
readonly _disconnectedPromise: Promise<Error>;
private _crashedCallback: (e: Error) => void;
readonly _crashedPromise: Promise<Error>;
readonly _browserContext: BrowserContext;
readonly keyboard: input.Keyboard;
readonly mouse: input.Mouse;
readonly _timeoutSettings: TimeoutSettings;
readonly _delegate: PageDelegate;
readonly _state: PageState;
readonly _pageBindings = new Map<string, PageBinding>();
readonly _evaluateOnNewDocumentSources: string[] = [];
readonly _screenshotter: Screenshotter;
readonly _frameManager: frames.FrameManager;
readonly accessibility: accessibility.Accessibility;
private _workers = new Map<string, Worker>();
readonly pdf: ((options?: types.PDFOptions) => Promise<Buffer>) | undefined;
readonly coverage: any;
private _requestInterceptor?: network.RouteHandler;
_ownedContext: BrowserContext | undefined;
readonly selectors: Selectors;
constructor(delegate: PageDelegate, browserContext: BrowserContext) {
super();
this._delegate = delegate;
this._closedCallback = () => {};
this._closedPromise = new Promise(f => this._closedCallback = f);
this._disconnectedCallback = () => {};
this._disconnectedPromise = new Promise(f => this._disconnectedCallback = f);
this._crashedCallback = () => {};
this._crashedPromise = new Promise(f => this._crashedCallback = f);
this._browserContext = browserContext;
this._state = {
viewportSize: browserContext._options.viewport || null,
mediaType: null,
colorScheme: null,
extraHTTPHeaders: null,
};
this.accessibility = new accessibility.Accessibility(delegate.getAccessibilityTree.bind(delegate));
this.keyboard = new input.Keyboard(delegate.rawKeyboard, this);
this.mouse = new input.Mouse(delegate.rawMouse, this);
this._timeoutSettings = new TimeoutSettings(browserContext._timeoutSettings);
this._screenshotter = new Screenshotter(this);
this._frameManager = new frames.FrameManager(this);
if (delegate.pdf)
this.pdf = delegate.pdf.bind(delegate);
this.coverage = delegate.coverage ? delegate.coverage() : null;
this.selectors = browserContext.selectors();
}
async _doSlowMo() {
const slowMo = this._browserContext._browser._options.slowMo;
if (!slowMo)
return;
await new Promise(x => setTimeout(x, slowMo));
}
_didClose() {
this._frameManager.dispose();
assert(this._closedState !== 'closed', 'Page closed twice');
this._closedState = 'closed';
this.emit(Page.Events.Close);
this._closedCallback();
}
_didCrash() {
this._frameManager.dispose();
this.emit(Page.Events.Crash);
this._crashedCallback(new Error('Page crashed'));
}
_didDisconnect() {
this._frameManager.dispose();
assert(!this._disconnected, 'Page disconnected twice');
this._disconnected = true;
this._disconnectedCallback(new Error('Page closed'));
}
async _onFileChooserOpened(handle: dom.ElementHandle) {
const multiple = await handle.evaluate(element => !!(element as HTMLInputElement).multiple);
if (!this.listenerCount(Page.Events.FileChooser)) {
handle.dispose();
return;
}
const fileChooser = new FileChooser(this, handle, multiple);
this.emit(Page.Events.FileChooser, fileChooser);
}
context(): BrowserContext {
return this._browserContext;
}
async opener(): Promise<Page | null> {
return await this._delegate.opener();
}
mainFrame(): frames.Frame {
return this._frameManager.mainFrame();
}
frames(): frames.Frame[] {
return this._frameManager.frames();
}
setDefaultNavigationTimeout(timeout: number) {
this._timeoutSettings.setDefaultNavigationTimeout(timeout);
}
setDefaultTimeout(timeout: number) {
this._timeoutSettings.setDefaultTimeout(timeout);
}
async exposeBinding(name: string, playwrightBinding: frames.FunctionWithSource) {
if (this._pageBindings.has(name))
throw new Error(`Function "${name}" has been already registered`);
if (this._browserContext._pageBindings.has(name))
throw new Error(`Function "${name}" has been already registered in the browser context`);
const binding = new PageBinding(name, playwrightBinding);
this._pageBindings.set(name, binding);
await this._delegate.exposeBinding(binding);
}
setExtraHTTPHeaders(headers: types.HeadersArray) {
this._state.extraHTTPHeaders = headers;
return this._delegate.updateExtraHTTPHeaders();
}
async _onBindingCalled(payload: string, context: dom.FrameExecutionContext) {
if (this._disconnected || this._closedState === 'closed')
return;
await PageBinding.dispatch(this, payload, context);
}
_addConsoleMessage(type: string, args: js.JSHandle[], location: types.ConsoleMessageLocation, text?: string) {
const message = new ConsoleMessage(type, text, args, location);
const intercepted = this._frameManager.interceptConsoleMessage(message);
if (intercepted || !this.listenerCount(Page.Events.Console))
args.forEach(arg => arg.dispose());
else
this.emit(Page.Events.Console, message);
}
async reload(controller: ProgressController, options: types.NavigateOptions): Promise<network.Response | null> {
this.mainFrame().setupNavigationProgressController(controller);
const response = await controller.run(async progress => {
const waitPromise = this.mainFrame()._waitForNavigation(progress, options);
await this._delegate.reload();
return waitPromise;
}, this._timeoutSettings.navigationTimeout(options));
await this._doSlowMo();
return response;
}
async goBack(controller: ProgressController, options: types.NavigateOptions): Promise<network.Response | null> {
this.mainFrame().setupNavigationProgressController(controller);
const response = await controller.run(async progress => {
const waitPromise = this.mainFrame()._waitForNavigation(progress, options);
const result = await this._delegate.goBack();
if (!result) {
waitPromise.catch(() => {});
return null;
}
return waitPromise;
}, this._timeoutSettings.navigationTimeout(options));
await this._doSlowMo();
return response;
}
async goForward(controller: ProgressController, options: types.NavigateOptions): Promise<network.Response | null> {
this.mainFrame().setupNavigationProgressController(controller);
const response = await controller.run(async progress => {
const waitPromise = this.mainFrame()._waitForNavigation(progress, options);
const result = await this._delegate.goForward();
if (!result) {
waitPromise.catch(() => {});
return null;
}
return waitPromise;
}, this._timeoutSettings.navigationTimeout(options));
await this._doSlowMo();
return response;
}
async emulateMedia(options: { media?: types.MediaType | null, colorScheme?: types.ColorScheme | null }) {
if (options.media !== undefined)
assert(options.media === null || types.mediaTypes.has(options.media), 'media: expected one of (screen|print|null)');
if (options.colorScheme !== undefined)
assert(options.colorScheme === null || types.colorSchemes.has(options.colorScheme), 'colorScheme: expected one of (dark|light|no-preference|null)');
if (options.media !== undefined)
this._state.mediaType = options.media;
if (options.colorScheme !== undefined)
this._state.colorScheme = options.colorScheme;
await this._delegate.updateEmulateMedia();
await this._doSlowMo();
}
async setViewportSize(viewportSize: types.Size) {
this._state.viewportSize = { ...viewportSize };
await this._delegate.setViewportSize(this._state.viewportSize);
await this._doSlowMo();
}
viewportSize(): types.Size | null {
return this._state.viewportSize;
}
async bringToFront(): Promise<void> {
await this._delegate.bringToFront();
}
async _addInitScriptExpression(source: string) {
this._evaluateOnNewDocumentSources.push(source);
await this._delegate.evaluateOnNewDocument(source);
}
_needsRequestInterception(): boolean {
return !!this._requestInterceptor || !!this._browserContext._requestInterceptor;
}
async _setRequestInterceptor(handler: network.RouteHandler | undefined): Promise<void> {
this._requestInterceptor = handler;
await this._delegate.updateRequestInterception();
}
_requestStarted(request: network.Request) {
this.emit(Page.Events.Request, request);
const route = request._route();
if (!route)
return;
if (this._requestInterceptor) {
this._requestInterceptor(route, request);
return;
}
if (this._browserContext._requestInterceptor) {
this._browserContext._requestInterceptor(route, request);
return;
}
route.continue();
}
async screenshot(options: types.ScreenshotOptions = {}): Promise<Buffer> {
return runAbortableTask(
progress => this._screenshotter.screenshotPage(progress, options),
this._timeoutSettings.timeout(options));
}
async close(options?: { runBeforeUnload?: boolean }) {
if (this._closedState === 'closed')
return;
const runBeforeUnload = !!options && !!options.runBeforeUnload;
if (this._closedState !== 'closing') {
this._closedState = 'closing';
assert(!this._disconnected, 'Protocol error: Connection closed. Most likely the page has been closed.');
await this._delegate.closePage(runBeforeUnload);
}
if (!runBeforeUnload)
await this._closedPromise;
if (this._ownedContext)
await this._ownedContext.close();
}
_setIsError() {
if (!this._frameManager.mainFrame())
this._frameManager.frameAttached('<dummy>', null);
}
isClosed(): boolean {
return this._closedState === 'closed';
}
_addWorker(workerId: string, worker: Worker) {
this._workers.set(workerId, worker);
this.emit(Page.Events.Worker, worker);
}
_removeWorker(workerId: string) {
const worker = this._workers.get(workerId);
if (!worker)
return;
worker.emit(Worker.Events.Close, worker);
this._workers.delete(workerId);
}
_clearWorkers() {
for (const [workerId, worker] of this._workers) {
worker.emit(Worker.Events.Close, worker);
this._workers.delete(workerId);
}
}
async _setFileChooserIntercepted(enabled: boolean): Promise<void> {
await this._delegate.setFileChooserIntercepted(enabled);
}
}
export class Worker extends EventEmitter {
static Events = {
Close: 'close',
};
private _url: string;
private _executionContextPromise: Promise<js.ExecutionContext>;
private _executionContextCallback: (value?: js.ExecutionContext) => void;
_existingExecutionContext: js.ExecutionContext | null = null;
constructor(url: string) {
super();
this._url = url;
this._executionContextCallback = () => {};
this._executionContextPromise = new Promise(x => this._executionContextCallback = x);
}
_createExecutionContext(delegate: js.ExecutionContextDelegate) {
this._existingExecutionContext = new js.ExecutionContext(delegate);
this._executionContextCallback(this._existingExecutionContext);
}
url(): string {
return this._url;
}
async _evaluateExpression(expression: string, isFunction: boolean, arg: any): Promise<any> {
return js.evaluateExpression(await this._executionContextPromise, true /* returnByValue */, expression, isFunction, arg);
}
async _evaluateExpressionHandle(expression: string, isFunction: boolean, arg: any): Promise<any> {
return js.evaluateExpression(await this._executionContextPromise, false /* returnByValue */, expression, isFunction, arg);
}
}
export class PageBinding {
readonly name: string;
readonly playwrightFunction: frames.FunctionWithSource;
readonly source: string;
constructor(name: string, playwrightFunction: frames.FunctionWithSource) {
this.name = name;
this.playwrightFunction = playwrightFunction;
this.source = `(${addPageBinding.toString()})(${JSON.stringify(name)})`;
}
static async dispatch(page: Page, payload: string, context: dom.FrameExecutionContext) {
const {name, seq, args} = JSON.parse(payload);
try {
let binding = page._pageBindings.get(name);
if (!binding)
binding = page._browserContext._pageBindings.get(name);
const result = await binding!.playwrightFunction({ frame: context.frame, page, context: page._browserContext }, ...args);
context.evaluateInternal(deliverResult, { name, seq, result }).catch(e => debugLogger.log('error', e));
} catch (error) {
if (isError(error))
context.evaluateInternal(deliverError, { name, seq, message: error.message, stack: error.stack }).catch(e => debugLogger.log('error', e));
else
context.evaluateInternal(deliverErrorValue, { name, seq, error }).catch(e => debugLogger.log('error', e));
}
function deliverResult(arg: { name: string, seq: number, result: any }) {
(window as any)[arg.name]['callbacks'].get(arg.seq).resolve(arg.result);
(window as any)[arg.name]['callbacks'].delete(arg.seq);
}
function deliverError(arg: { name: string, seq: number, message: string, stack: string | undefined }) {
const error = new Error(arg.message);
error.stack = arg.stack;
(window as any)[arg.name]['callbacks'].get(arg.seq).reject(error);
(window as any)[arg.name]['callbacks'].delete(arg.seq);
}
function deliverErrorValue(arg: { name: string, seq: number, error: any }) {
(window as any)[arg.name]['callbacks'].get(arg.seq).reject(arg.error);
(window as any)[arg.name]['callbacks'].delete(arg.seq);
}
}
}
function addPageBinding(bindingName: string) {
const binding = (window as any)[bindingName];
if (binding.__installed)
return;
(window as any)[bindingName] = (...args: any[]) => {
const me = (window as any)[bindingName];
let callbacks = me['callbacks'];
if (!callbacks) {
callbacks = new Map();
me['callbacks'] = callbacks;
}
const seq = (me['lastSeq'] || 0) + 1;
me['lastSeq'] = seq;
const promise = new Promise((resolve, reject) => callbacks.set(seq, {resolve, reject}));
binding(JSON.stringify({name: bindingName, seq, args}));
return promise;
};
(window as any)[bindingName].__installed = true;
}
| src/server/page.ts | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.003061915747821331,
0.00023196348047349602,
0.00016323293675668538,
0.00017566606402397156,
0.0003966126241721213
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" executablePath(): string {\n",
" if (!this._executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n",
" return this._executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 56
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as util from 'util';
import { BrowserContext, normalizeProxySettings, validateBrowserContextOptions } from './browserContext';
import * as browserPaths from '../utils/browserPaths';
import { ConnectionTransport, WebSocketTransport } from './transport';
import { BrowserOptions, Browser, BrowserProcess } from './browser';
import { launchProcess, Env, waitForLine, envArrayToObject } from './processLauncher';
import { PipeTransport } from './pipeTransport';
import { Progress, ProgressController } from './progress';
import * as types from './types';
import { TimeoutSettings } from '../utils/timeoutSettings';
import { validateHostRequirements } from './validateDependencies';
import { isDebugMode } from '../utils/utils';
const mkdirAsync = util.promisify(fs.mkdir);
const mkdtempAsync = util.promisify(fs.mkdtemp);
const existsAsync = (path: string): Promise<boolean> => new Promise(resolve => fs.stat(path, err => resolve(!err)));
const DOWNLOADS_FOLDER = path.join(os.tmpdir(), 'playwright_downloads-');
type WebSocketNotPipe = { webSocketRegex: RegExp, stream: 'stdout' | 'stderr' };
export abstract class BrowserType {
private _name: string;
private _executablePath: string | undefined;
private _webSocketNotPipe: WebSocketNotPipe | null;
private _browserDescriptor: browserPaths.BrowserDescriptor;
readonly _browserPath: string;
constructor(packagePath: string, browser: browserPaths.BrowserDescriptor, webSocketOrPipe: WebSocketNotPipe | null) {
this._name = browser.name;
const browsersPath = browserPaths.browsersPath(packagePath);
this._browserDescriptor = browser;
this._browserPath = browserPaths.browserDirectory(browsersPath, browser);
this._executablePath = browserPaths.executablePath(this._browserPath, browser);
this._webSocketNotPipe = webSocketOrPipe;
}
executablePath(): string {
if (!this._executablePath)
throw new Error('Browser is not supported on current platform');
return this._executablePath;
}
name(): string {
return this._name;
}
async launch(options: types.LaunchOptions = {}): Promise<Browser> {
options = validateLaunchOptions(options);
const controller = new ProgressController();
controller.setLogName('browser');
const browser = await controller.run(progress => {
return this._innerLaunch(progress, options, undefined).catch(e => { throw this._rewriteStartupError(e); });
}, TimeoutSettings.timeout(options));
return browser;
}
async launchPersistentContext(userDataDir: string, options: types.LaunchPersistentOptions = {}): Promise<BrowserContext> {
options = validateLaunchOptions(options);
const persistent: types.BrowserContextOptions = options;
const controller = new ProgressController();
controller.setLogName('browser');
const browser = await controller.run(progress => {
return this._innerLaunch(progress, options, persistent, userDataDir).catch(e => { throw this._rewriteStartupError(e); });
}, TimeoutSettings.timeout(options));
return browser._defaultContext!;
}
async _innerLaunch(progress: Progress, options: types.LaunchOptions, persistent: types.BrowserContextOptions | undefined, userDataDir?: string): Promise<Browser> {
options.proxy = options.proxy ? normalizeProxySettings(options.proxy) : undefined;
const { browserProcess, downloadsPath, transport } = await this._launchProcess(progress, options, !!persistent, userDataDir);
if ((options as any).__testHookBeforeCreateBrowser)
await (options as any).__testHookBeforeCreateBrowser();
const browserOptions: BrowserOptions = {
name: this._name,
slowMo: options.slowMo,
persistent,
headful: !options.headless,
artifactsPath: options.artifactsPath,
downloadsPath,
browserProcess,
proxy: options.proxy,
};
if (persistent)
validateBrowserContextOptions(persistent, browserOptions);
copyTestHooks(options, browserOptions);
const browser = await this._connectToTransport(transport, browserOptions);
// We assume no control when using custom arguments, and do not prepare the default context in that case.
if (persistent && !options.ignoreAllDefaultArgs)
await browser._defaultContext!._loadDefaultContext(progress);
return browser;
}
private async _launchProcess(progress: Progress, options: types.LaunchOptions, isPersistent: boolean, userDataDir?: string): Promise<{ browserProcess: BrowserProcess, downloadsPath: string, transport: ConnectionTransport }> {
const {
ignoreDefaultArgs,
ignoreAllDefaultArgs,
args = [],
executablePath = null,
handleSIGINT = true,
handleSIGTERM = true,
handleSIGHUP = true,
} = options;
const env = options.env ? envArrayToObject(options.env) : process.env;
const tempDirectories = [];
const ensurePath = async (tmpPrefix: string, pathFromOptions?: string) => {
let dir;
if (pathFromOptions) {
dir = pathFromOptions;
await mkdirAsync(pathFromOptions, { recursive: true });
} else {
dir = await mkdtempAsync(tmpPrefix);
tempDirectories.push(dir);
}
return dir;
};
// TODO: use artifactsPath for downloads.
const downloadsPath = await ensurePath(DOWNLOADS_FOLDER, options.downloadsPath);
if (!userDataDir) {
userDataDir = await mkdtempAsync(path.join(os.tmpdir(), `playwright_${this._name}dev_profile-`));
tempDirectories.push(userDataDir);
}
const browserArguments = [];
if (ignoreAllDefaultArgs)
browserArguments.push(...args);
else if (ignoreDefaultArgs)
browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir).filter(arg => ignoreDefaultArgs.indexOf(arg) === -1));
else
browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir));
const executable = executablePath || this.executablePath();
if (!executable)
throw new Error(`No executable path is specified. Pass "executablePath" option directly.`);
if (!(await existsAsync(executable))) {
const errorMessageLines = [`Failed to launch ${this._name} because executable doesn't exist at ${executable}`];
// If we tried using stock downloaded browser, suggest re-installing playwright.
if (!executablePath)
errorMessageLines.push(`Try re-installing playwright with "npm install playwright"`);
throw new Error(errorMessageLines.join('\n'));
}
if (!executablePath) {
// We can only validate dependencies for bundled browsers.
await validateHostRequirements(this._browserPath, this._browserDescriptor);
}
// Note: it is important to define these variables before launchProcess, so that we don't get
// "Cannot access 'browserServer' before initialization" if something went wrong.
let transport: ConnectionTransport | undefined = undefined;
let browserProcess: BrowserProcess | undefined = undefined;
const { launchedProcess, gracefullyClose, kill } = await launchProcess({
executablePath: executable,
args: this._amendArguments(browserArguments),
env: this._amendEnvironment(env, userDataDir, executable, browserArguments),
handleSIGINT,
handleSIGTERM,
handleSIGHUP,
progress,
pipe: !this._webSocketNotPipe,
tempDirectories,
attemptToGracefullyClose: async () => {
if ((options as any).__testHookGracefullyClose)
await (options as any).__testHookGracefullyClose();
// We try to gracefully close to prevent crash reporting and core dumps.
// Note that it's fine to reuse the pipe transport, since
// our connection ignores kBrowserCloseMessageId.
this._attemptToGracefullyCloseBrowser(transport!);
},
onExit: (exitCode, signal) => {
if (browserProcess && browserProcess.onclose)
browserProcess.onclose(exitCode, signal);
},
});
browserProcess = {
onclose: undefined,
process: launchedProcess,
close: gracefullyClose,
kill
};
progress.cleanupWhenAborted(() => browserProcess && closeOrKill(browserProcess, progress.timeUntilDeadline()));
if (this._webSocketNotPipe) {
const match = await waitForLine(progress, launchedProcess, this._webSocketNotPipe.stream === 'stdout' ? launchedProcess.stdout : launchedProcess.stderr, this._webSocketNotPipe.webSocketRegex);
const innerEndpoint = match[1];
transport = await WebSocketTransport.connect(progress, innerEndpoint);
} else {
const stdio = launchedProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
transport = new PipeTransport(stdio[3], stdio[4]);
}
return { browserProcess, downloadsPath, transport };
}
abstract _defaultArgs(options: types.LaunchOptions, isPersistent: boolean, userDataDir: string): string[];
abstract _connectToTransport(transport: ConnectionTransport, options: BrowserOptions): Promise<Browser>;
abstract _amendEnvironment(env: Env, userDataDir: string, executable: string, browserArguments: string[]): Env;
abstract _amendArguments(browserArguments: string[]): string[];
abstract _rewriteStartupError(error: Error): Error;
abstract _attemptToGracefullyCloseBrowser(transport: ConnectionTransport): void;
}
function copyTestHooks(from: object, to: object) {
for (const [key, value] of Object.entries(from)) {
if (key.startsWith('__testHook'))
(to as any)[key] = value;
}
}
function validateLaunchOptions<Options extends types.LaunchOptions>(options: Options): Options {
const { devtools = false, headless = !isDebugMode() && !devtools } = options;
return { ...options, devtools, headless };
}
async function closeOrKill(browserProcess: BrowserProcess, timeout: number): Promise<void> {
let timer: NodeJS.Timer;
try {
await Promise.race([
browserProcess.close(),
new Promise((resolve, reject) => timer = setTimeout(reject, timeout)),
]);
} catch (ignored) {
await browserProcess.kill().catch(ignored => {}); // Make sure to await actual process exit.
} finally {
clearTimeout(timer!);
}
}
| src/server/browserType.ts | 1 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.9988791346549988,
0.23057980835437775,
0.00016769285139162093,
0.0001753808173816651,
0.40677371621131897
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" executablePath(): string {\n",
" if (!this._executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n",
" return this._executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 56
} | /checkout
| browser_patches/webkit/.gitignore | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00017724467033986002,
0.00017724467033986002,
0.00017724467033986002,
0.00017724467033986002,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.