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": 3, "code_window": [ "\t\tconst event = new StandardMouseEvent(e);\n", "\t\tconst anchor = { x: event.posx, y: event.posy };\n", "\n", "\t\t// Fill in contributed actions\n", "\t\tconst actions: IAction[] = [];\n", "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions);\n", "\n", "\t\t// Show it\n", "\t\tthis.contextMenuService.showContextMenu({\n", "\t\t\tgetAnchor: () => anchor,\n", "\t\t\tgetActions: () => actions,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.titleContextMenu, undefined, actions);\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 389 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export const IIntegrityService = createDecorator<IIntegrityService>('integrityService'); export interface ChecksumPair { uri: URI; actual: string; expected: string; isPure: boolean; } export interface IntegrityTestResult { isPure: boolean; proof: ChecksumPair[]; } export interface IIntegrityService { readonly _serviceBrand: undefined; isPure(): Promise<IntegrityTestResult>; }
src/vs/workbench/services/integrity/common/integrity.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00017777158063836396, 0.00017544807633385062, 0.00017082682461477816, 0.00017774582374840975, 0.000003267735337431077 ]
{ "id": 3, "code_window": [ "\t\tconst event = new StandardMouseEvent(e);\n", "\t\tconst anchor = { x: event.posx, y: event.posy };\n", "\n", "\t\t// Fill in contributed actions\n", "\t\tconst actions: IAction[] = [];\n", "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions);\n", "\n", "\t\t// Show it\n", "\t\tthis.contextMenuService.showContextMenu({\n", "\t\t\tgetAnchor: () => anchor,\n", "\t\t\tgetActions: () => actions,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.titleContextMenu, undefined, actions);\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 389 }
/*--------------------------------------------------------------------------------------------- * 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'; import { Event } from 'vs/base/common/event'; import { FormattingOptions } from 'vs/base/common/jsonFormatter'; import { Disposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc'; import { IUserDataAutoSyncService, IUserDataSyncStore, IUserDataSyncStoreManagementService, IUserDataSyncUtilService, UserDataSyncStoreType } from 'vs/platform/userDataSync/common/userDataSync'; import { IUserDataSyncAccountService } from 'vs/platform/userDataSync/common/userDataSyncAccount'; import { IUserDataSyncMachinesService } from 'vs/platform/userDataSync/common/userDataSyncMachines'; export class UserDataAutoSyncChannel implements IServerChannel { constructor(private readonly service: IUserDataAutoSyncService) { } listen(_: unknown, event: string): Event<any> { switch (event) { case 'onError': return this.service.onError; } throw new Error(`Event not found: ${event}`); } call(context: any, command: string, args?: any): Promise<any> { switch (command) { case 'triggerSync': return this.service.triggerSync(args[0], args[1], args[2]); case 'turnOn': return this.service.turnOn(); case 'turnOff': return this.service.turnOff(args[0]); } throw new Error('Invalid call'); } } export class UserDataSycnUtilServiceChannel implements IServerChannel { constructor(private readonly service: IUserDataSyncUtilService) { } listen(_: unknown, event: string): Event<any> { throw new Error(`Event not found: ${event}`); } call(context: any, command: string, args?: any): Promise<any> { switch (command) { case 'resolveDefaultIgnoredSettings': return this.service.resolveDefaultIgnoredSettings(); case 'resolveUserKeybindings': return this.service.resolveUserBindings(args[0]); case 'resolveFormattingOptions': return this.service.resolveFormattingOptions(URI.revive(args[0])); } throw new Error('Invalid call'); } } export class UserDataSyncUtilServiceClient implements IUserDataSyncUtilService { declare readonly _serviceBrand: undefined; constructor(private readonly channel: IChannel) { } async resolveDefaultIgnoredSettings(): Promise<string[]> { return this.channel.call('resolveDefaultIgnoredSettings'); } async resolveUserBindings(userbindings: string[]): Promise<IStringDictionary<string>> { return this.channel.call('resolveUserKeybindings', [userbindings]); } async resolveFormattingOptions(file: URI): Promise<FormattingOptions> { return this.channel.call('resolveFormattingOptions', [file]); } } export class UserDataSyncMachinesServiceChannel implements IServerChannel { constructor(private readonly service: IUserDataSyncMachinesService) { } listen(_: unknown, event: string): Event<any> { switch (event) { case 'onDidChange': return this.service.onDidChange; } throw new Error(`Event not found: ${event}`); } async call(context: any, command: string, args?: any): Promise<any> { switch (command) { case 'getMachines': return this.service.getMachines(); case 'addCurrentMachine': return this.service.addCurrentMachine(); case 'removeCurrentMachine': return this.service.removeCurrentMachine(); case 'renameMachine': return this.service.renameMachine(args[0], args[1]); case 'setEnablements': return this.service.setEnablements(args); } throw new Error('Invalid call'); } } export class UserDataSyncAccountServiceChannel implements IServerChannel { constructor(private readonly service: IUserDataSyncAccountService) { } listen(_: unknown, event: string): Event<any> { switch (event) { case 'onDidChangeAccount': return this.service.onDidChangeAccount; case 'onTokenFailed': return this.service.onTokenFailed; } throw new Error(`Event not found: ${event}`); } call(context: any, command: string, args?: any): Promise<any> { switch (command) { case '_getInitialData': return Promise.resolve(this.service.account); case 'updateAccount': return this.service.updateAccount(args); } throw new Error('Invalid call'); } } export class UserDataSyncStoreManagementServiceChannel implements IServerChannel { constructor(private readonly service: IUserDataSyncStoreManagementService) { } listen(_: unknown, event: string): Event<any> { switch (event) { case 'onDidChangeUserDataSyncStore': return this.service.onDidChangeUserDataSyncStore; } throw new Error(`Event not found: ${event}`); } call(context: any, command: string, args?: any): Promise<any> { switch (command) { case 'switch': return this.service.switch(args[0]); case 'getPreviousUserDataSyncStore': return this.service.getPreviousUserDataSyncStore(); } throw new Error('Invalid call'); } } export class UserDataSyncStoreManagementServiceChannelClient extends Disposable { readonly onDidChangeUserDataSyncStore: Event<void>; constructor(private readonly channel: IChannel) { super(); this.onDidChangeUserDataSyncStore = this.channel.listen<void>('onDidChangeUserDataSyncStore'); } async switch(type: UserDataSyncStoreType): Promise<void> { return this.channel.call('switch', [type]); } async getPreviousUserDataSyncStore(): Promise<IUserDataSyncStore> { const userDataSyncStore = await this.channel.call<IUserDataSyncStore>('getPreviousUserDataSyncStore'); return this.revive(userDataSyncStore); } private revive(userDataSyncStore: IUserDataSyncStore): IUserDataSyncStore { return { url: URI.revive(userDataSyncStore.url), type: userDataSyncStore.type, defaultUrl: URI.revive(userDataSyncStore.defaultUrl), insidersUrl: URI.revive(userDataSyncStore.insidersUrl), stableUrl: URI.revive(userDataSyncStore.stableUrl), canSwitch: userDataSyncStore.canSwitch, authenticationProviders: userDataSyncStore.authenticationProviders, }; } }
src/vs/platform/userDataSync/common/userDataSyncIpc.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00030675213201902807, 0.00017696777649689466, 0.00016116116603370756, 0.00017038809892255813, 0.00003275731432950124 ]
{ "id": 4, "code_window": [ "\n", "\t\t\tconst commandId = `workbench.action.revealPathInFinder${i}`;\n", "\t\t\tthis.customTitleContextMenuDisposable.add(CommandsRegistry.registerCommand(commandId, () => this.nativeHostService.showItemInFolder(path.fsPath)));\n", "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n", "\t\t}\n", "\t}\n", "\n", "\tprivate create(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarTitleContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n" ], "file_path": "src/vs/workbench/electron-sandbox/window.ts", "type": "replace", "edit_start_line_idx": 605 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/titlebarpart'; import { localize } from 'vs/nls'; import { Part } from 'vs/workbench/browser/part'; import { ITitleService, ITitleProperties } from 'vs/workbench/services/title/common/titleService'; import { getZoomFactor } from 'vs/base/browser/browser'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility } from 'vs/platform/window/common/window'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction, toAction } from 'vs/base/common/actions'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TITLE_BAR_ACTIVE_BACKGROUND, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_BACKGROUND, TITLE_BAR_BORDER, WORKBENCH_BACKGROUND } from 'vs/workbench/common/theme'; import { isMacintosh, isWindows, isLinux, isWeb } from 'vs/base/common/platform'; import { Color } from 'vs/base/common/color'; import { EventType, EventHelper, Dimension, isAncestor, append, $, addDisposableListener, runAtThisOrScheduleAtNextAnimationFrame, prepend, reset } from 'vs/base/browser/dom'; import { CustomMenubarControl } from 'vs/workbench/browser/parts/titlebar/menubarControl'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Emitter, Event } from 'vs/base/common/event'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { Parts, IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { createActionViewItem, createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, IMenu, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { Codicon } from 'vs/base/common/codicons'; import { getIconRegistry } from 'vs/platform/theme/common/iconRegistry'; import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar'; import { WindowTitle } from 'vs/workbench/browser/parts/titlebar/windowTitle'; import { CommandCenterControl } from 'vs/workbench/browser/parts/titlebar/commandCenterControl'; import { IHoverDelegate } from 'vs/base/browser/ui/iconLabel/iconHoverDelegate'; import { IHoverService } from 'vs/workbench/services/hover/browser/hover'; export class TitlebarPart extends Part implements ITitleService { private static readonly configCommandCenter = 'window.commandCenter'; declare readonly _serviceBrand: undefined; //#region IView readonly minimumWidth: number = 0; readonly maximumWidth: number = Number.POSITIVE_INFINITY; get minimumHeight(): number { const value = this.isCommandCenterVisible ? 35 : 30; return value / (this.currentMenubarVisibility === 'hidden' || getZoomFactor() < 1 ? getZoomFactor() : 1); } get maximumHeight(): number { return this.minimumHeight; } //#endregion private _onMenubarVisibilityChange = this._register(new Emitter<boolean>()); readonly onMenubarVisibilityChange = this._onMenubarVisibilityChange.event; private readonly _onDidChangeCommandCenterVisibility = new Emitter<void>(); readonly onDidChangeCommandCenterVisibility: Event<void> = this._onDidChangeCommandCenterVisibility.event; protected rootContainer!: HTMLElement; protected windowControls: HTMLElement | undefined; protected title!: HTMLElement; protected customMenubar: CustomMenubarControl | undefined; protected appIcon: HTMLElement | undefined; private appIconBadge: HTMLElement | undefined; protected menubar?: HTMLElement; protected layoutControls: HTMLElement | undefined; private layoutToolbar: ToolBar | undefined; protected lastLayoutDimensions: Dimension | undefined; private hoverDelegate: IHoverDelegate; private readonly titleDisposables = this._register(new DisposableStore()); private titleBarStyle: 'native' | 'custom'; private isInactive: boolean = false; private readonly windowTitle: WindowTitle; private readonly contextMenu: IMenu; constructor( @IContextMenuService private readonly contextMenuService: IContextMenuService, @IConfigurationService protected readonly configurationService: IConfigurationService, @IBrowserWorkbenchEnvironmentService protected readonly environmentService: IBrowserWorkbenchEnvironmentService, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IHostService private readonly hostService: IHostService, @IHoverService hoverService: IHoverService, ) { super(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService); this.windowTitle = this._register(instantiationService.createInstance(WindowTitle)); this.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService)); this.titleBarStyle = getTitleBarStyle(this.configurationService); this.hoverDelegate = new class implements IHoverDelegate { private _lastHoverHideTime: number = 0; readonly showHover = hoverService.showHover.bind(hoverService); readonly placement = 'element'; get delay(): number { return Date.now() - this._lastHoverHideTime < 200 ? 0 // show instantly when a hover was recently shown : configurationService.getValue<number>('workbench.hover.delay'); } onDidHideHover() { this._lastHoverHideTime = Date.now(); } }; this.registerListeners(); } updateProperties(properties: ITitleProperties): void { this.windowTitle.updateProperties(properties); } get isCommandCenterVisible() { return this.configurationService.getValue<boolean>(TitlebarPart.configCommandCenter); } private registerListeners(): void { this._register(this.hostService.onDidChangeFocus(focused => focused ? this.onFocus() : this.onBlur())); this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); } private onBlur(): void { this.isInactive = true; this.updateStyles(); } private onFocus(): void { this.isInactive = false; this.updateStyles(); } protected onConfigurationChanged(event: IConfigurationChangeEvent): void { if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb)) { if (event.affectsConfiguration('window.menuBarVisibility')) { if (this.currentMenubarVisibility === 'compact') { this.uninstallMenubar(); } else { this.installMenubar(); } } } if (this.titleBarStyle !== 'native' && this.layoutControls && event.affectsConfiguration('workbench.layoutControl.enabled')) { this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); } if (event.affectsConfiguration(TitlebarPart.configCommandCenter)) { this.updateTitle(); this.adjustTitleMarginToCenter(); this._onDidChangeCommandCenterVisibility.fire(); } } protected onMenubarVisibilityChanged(visible: boolean): void { if (isWeb || isWindows || isLinux) { if (this.lastLayoutDimensions) { this.layout(this.lastLayoutDimensions.width, this.lastLayoutDimensions.height); } this._onMenubarVisibilityChange.fire(visible); } } private uninstallMenubar(): void { if (this.customMenubar) { this.customMenubar.dispose(); this.customMenubar = undefined; } if (this.menubar) { this.menubar.remove(); this.menubar = undefined; } this.onMenubarVisibilityChanged(false); } protected installMenubar(): void { // If the menubar is already installed, skip if (this.menubar) { return; } this.customMenubar = this._register(this.instantiationService.createInstance(CustomMenubarControl)); this.menubar = this.rootContainer.insertBefore($('div.menubar'), this.title); this.menubar.setAttribute('role', 'menubar'); this._register(this.customMenubar.onVisibilityChange(e => this.onMenubarVisibilityChanged(e))); this.customMenubar.create(this.menubar); } private updateTitle(): void { this.titleDisposables.clear(); if (!this.isCommandCenterVisible) { // Text Title this.title.innerText = this.windowTitle.value; this.titleDisposables.add(this.windowTitle.onDidChange(() => { this.title.innerText = this.windowTitle.value; this.adjustTitleMarginToCenter(); })); } else { // Menu Title const commandCenter = this.instantiationService.createInstance(CommandCenterControl, this.windowTitle, this.hoverDelegate); reset(this.title, commandCenter.element); this.titleDisposables.add(commandCenter); this.titleDisposables.add(commandCenter.onDidChangeVisibility(this.adjustTitleMarginToCenter, this)); } } override createContentArea(parent: HTMLElement): HTMLElement { this.element = parent; this.rootContainer = append(parent, $('.titlebar-container')); // App Icon (Native Windows/Linux and Web) if (!isMacintosh || isWeb) { this.appIcon = prepend(this.rootContainer, $('a.window-appicon')); // Web-only home indicator and menu if (isWeb) { const homeIndicator = this.environmentService.options?.homeIndicator; if (homeIndicator) { const icon: ThemeIcon = getIconRegistry().getIcon(homeIndicator.icon) ? { id: homeIndicator.icon } : Codicon.code; this.appIcon.setAttribute('href', homeIndicator.href); this.appIcon.classList.add(...ThemeIcon.asClassNameArray(icon)); this.appIconBadge = document.createElement('div'); this.appIconBadge.classList.add('home-bar-icon-badge'); this.appIcon.appendChild(this.appIconBadge); } } } // Menubar: install a custom menu bar depending on configuration // and when not in activity bar if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb) && this.currentMenubarVisibility !== 'compact') { this.installMenubar(); } // Title this.title = append(this.rootContainer, $('div.window-title')); this.updateTitle(); if (this.titleBarStyle !== 'native') { this.layoutControls = append(this.rootContainer, $('div.layout-controls-container')); this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); this.layoutToolbar = new ToolBar(this.layoutControls, this.contextMenuService, { actionViewItemProvider: action => { return createActionViewItem(this.instantiationService, action, { hoverDelegate: this.hoverDelegate }); }, allowContextMenu: true }); this._register(addDisposableListener(this.layoutControls, EventType.CONTEXT_MENU, e => { EventHelper.stop(e); this.onLayoutControlContextMenu(e, this.layoutControls!); })); const menu = this._register(this.menuService.createMenu(MenuId.LayoutControlMenu, this.contextKeyService)); const updateLayoutMenu = () => { if (!this.layoutToolbar) { return; } const actions: IAction[] = []; const toDispose = createAndFillInContextMenuActions(menu, undefined, { primary: [], secondary: actions }); this.layoutToolbar.setActions(actions); toDispose.dispose(); }; menu.onDidChange(updateLayoutMenu); updateLayoutMenu(); } this.windowControls = append(this.element, $('div.window-controls-container')); // Context menu on title [EventType.CONTEXT_MENU, EventType.MOUSE_DOWN].forEach(event => { this._register(addDisposableListener(this.title, event, e => { if (e.type === EventType.CONTEXT_MENU || e.metaKey) { EventHelper.stop(e); this.onContextMenu(e); } })); }); // Since the title area is used to drag the window, we do not want to steal focus from the // currently active element. So we restore focus after a timeout back to where it was. this._register(addDisposableListener(this.element, EventType.MOUSE_DOWN, e => { if (e.target && this.menubar && isAncestor(e.target as HTMLElement, this.menubar)) { return; } if (e.target && this.layoutToolbar && isAncestor(e.target as HTMLElement, this.layoutToolbar.getElement())) { return; } if (e.target && isAncestor(e.target as HTMLElement, this.title)) { return; } const active = document.activeElement; setTimeout(() => { if (active instanceof HTMLElement) { active.focus(); } }, 0 /* need a timeout because we are in capture phase */); }, true /* use capture to know the currently active element properly */)); this.updateStyles(); return this.element; } override updateStyles(): void { super.updateStyles(); // Part container if (this.element) { if (this.isInactive) { this.element.classList.add('inactive'); } else { this.element.classList.remove('inactive'); } const titleBackground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND, (color, theme) => { // LCD Rendering Support: the title bar part is a defining its own GPU layer. // To benefit from LCD font rendering, we must ensure that we always set an // opaque background color. As such, we compute an opaque color given we know // the background color is the workbench background. return color.isOpaque() ? color : color.makeOpaque(WORKBENCH_BACKGROUND(theme)); }) || ''; this.element.style.backgroundColor = titleBackground; if (this.appIconBadge) { this.appIconBadge.style.backgroundColor = titleBackground; } if (titleBackground && Color.fromHex(titleBackground).isLighter()) { this.element.classList.add('light'); } else { this.element.classList.remove('light'); } const titleForeground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND); this.element.style.color = titleForeground || ''; const titleBorder = this.getColor(TITLE_BAR_BORDER); this.element.style.borderBottom = titleBorder ? `1px solid ${titleBorder}` : ''; } } private onContextMenu(e: MouseEvent): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; // Fill in contributed actions const actions: IAction[] = []; const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, onHide: () => dispose(actionsDisposable) }); } private onLayoutControlContextMenu(e: MouseEvent, el: HTMLElement): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; const actions: IAction[] = []; actions.push(toAction({ id: 'layoutControl.hide', label: localize('layoutControl.hide', "Hide Layout Control"), run: () => { this.configurationService.updateValue('workbench.layoutControl.enabled', false); } })); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, domForShadowRoot: el }); } protected adjustTitleMarginToCenter(): void { const base = isMacintosh ? (this.windowControls?.clientWidth ?? 0) : 0; const leftMarker = base + (this.appIcon?.clientWidth ?? 0) + (this.menubar?.clientWidth ?? 0) + 10; const rightMarker = base + this.rootContainer.clientWidth - (this.layoutControls?.clientWidth ?? 0) - 10; // Not enough space to center the titlebar within window, // Center between left and right controls if (leftMarker > (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) - this.title.clientWidth) / 2 || rightMarker < (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) + this.title.clientWidth) / 2) { this.title.style.position = ''; this.title.style.left = ''; this.title.style.transform = ''; return; } this.title.style.position = 'absolute'; this.title.style.left = `calc(50% - ${this.title.clientWidth / 2}px)`; } protected get currentMenubarVisibility(): MenuBarVisibility { return getMenuBarVisibility(this.configurationService); } private get layoutControlEnabled(): boolean { return this.configurationService.getValue<boolean>('workbench.layoutControl.enabled'); } updateLayout(dimension: Dimension): void { this.lastLayoutDimensions = dimension; if (getTitleBarStyle(this.configurationService) === 'custom') { // Prevent zooming behavior if any of the following conditions are met: // 1. Native macOS // 2. Menubar is hidden // 3. Shrinking below the window control size (zoom < 1) const zoomFactor = getZoomFactor(); this.element.style.setProperty('--zoom-factor', zoomFactor.toString()); this.rootContainer.classList.toggle('counter-zoom', zoomFactor < 1 || (!isWeb && isMacintosh) || this.currentMenubarVisibility === 'hidden'); runAtThisOrScheduleAtNextAnimationFrame(() => this.adjustTitleMarginToCenter()); if (this.customMenubar) { const menubarDimension = new Dimension(0, dimension.height); this.customMenubar.layout(menubarDimension); } } } override layout(width: number, height: number): void { this.updateLayout(new Dimension(width, height)); super.layoutContents(width, height); } toJSON(): object { return { type: Parts.TITLEBAR_PART }; } } registerThemingParticipant((theme, collector) => { const titlebarActiveFg = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND); if (titlebarActiveFg) { collector.addRule(` .monaco-workbench .part.titlebar .window-controls-container .window-icon { color: ${titlebarActiveFg}; } `); } const titlebarInactiveFg = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND); if (titlebarInactiveFg) { collector.addRule(` .monaco-workbench .part.titlebar.inactive .window-controls-container .window-icon { color: ${titlebarInactiveFg}; } `); } });
src/vs/workbench/browser/parts/titlebar/titlebarPart.ts
1
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.7874840497970581, 0.015653012320399284, 0.00015963845362421125, 0.0001684544258750975, 0.10915354639291763 ]
{ "id": 4, "code_window": [ "\n", "\t\t\tconst commandId = `workbench.action.revealPathInFinder${i}`;\n", "\t\t\tthis.customTitleContextMenuDisposable.add(CommandsRegistry.registerCommand(commandId, () => this.nativeHostService.showItemInFolder(path.fsPath)));\n", "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n", "\t\t}\n", "\t}\n", "\n", "\tprivate create(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarTitleContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n" ], "file_path": "src/vs/workbench/electron-sandbox/window.ts", "type": "replace", "edit_start_line_idx": 605 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as sinon from 'sinon'; import { timeout } from 'vs/base/common/async'; import { Emitter } from 'vs/base/common/event'; import { OS } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { DidUninstallExtensionEvent, IExtensionIdentifier, IExtensionManagementService, ILocalExtension, InstallExtensionEvent, InstallExtensionResult } from 'vs/platform/extensionManagement/common/extensionManagement'; import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService'; import { ExtensionType } from 'vs/platform/extensions/common/extensions'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IProductService } from 'vs/platform/product/common/productService'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { ITelemetryService, lastSessionDateStorageKey } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { IURLService } from 'vs/platform/url/common/url'; import { NativeURLService } from 'vs/platform/url/common/urlService'; import { IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust'; import { currentSchemaVersion, ExperimentActionType, ExperimentService, ExperimentState, getCurrentActivationRecord, IExperiment } from 'vs/workbench/contrib/experiments/common/experimentService'; import { IWorkbenchExtensionEnablementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { TestExtensionEnablementService } from 'vs/workbench/services/extensionManagement/test/browser/extensionEnablementService.test'; import { IExtensionService, IWillActivateEvent } from 'vs/workbench/services/extensions/common/extensions'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { TestWorkspaceTrustManagementService } from 'vs/workbench/services/workspaces/test/common/testWorkspaceTrustService'; import { TestLifecycleService } from 'vs/workbench/test/browser/workbenchTestServices'; import { TestExtensionService } from 'vs/workbench/test/common/workbenchTestServices'; interface ExperimentSettings { enabled?: boolean; id?: string; state?: ExperimentState; } let experimentData: { [i: string]: any } = { experiments: [] }; const local = aLocalExtension('installedExtension1', { version: '1.0.0' }); function aLocalExtension(name: string = 'someext', manifest: any = {}, properties: any = {}): ILocalExtension { manifest = Object.assign({ name, publisher: 'pub', version: '1.0.0' }, manifest); properties = Object.assign({ type: ExtensionType.User, location: URI.file(`pub.${name}`), identifier: { id: getGalleryExtensionId(manifest.publisher, manifest.name), uuid: undefined }, metadata: { id: getGalleryExtensionId(manifest.publisher, manifest.name), publisherId: manifest.publisher, publisherDisplayName: 'somename' } }, properties); return <ILocalExtension>Object.create({ manifest, ...properties }); } export class TestExperimentService extends ExperimentService { public override getExperiments(): Promise<any[]> { return Promise.resolve(experimentData.experiments); } } suite('Experiment Service', () => { let instantiationService: TestInstantiationService; let testConfigurationService: TestConfigurationService; let testObject: ExperimentService; let activationEvent: Emitter<IWillActivateEvent>; let installEvent: Emitter<InstallExtensionEvent>, didInstallEvent: Emitter<readonly InstallExtensionResult[]>, uninstallEvent: Emitter<IExtensionIdentifier>, didUninstallEvent: Emitter<DidUninstallExtensionEvent>; suiteSetup(() => { instantiationService = new TestInstantiationService(); installEvent = new Emitter<InstallExtensionEvent>(); didInstallEvent = new Emitter<readonly InstallExtensionResult[]>(); uninstallEvent = new Emitter<IExtensionIdentifier>(); didUninstallEvent = new Emitter<DidUninstallExtensionEvent>(); activationEvent = new Emitter<IWillActivateEvent>(); instantiationService.stub(IExtensionService, TestExtensionService); instantiationService.stub(IExtensionService, 'onWillActivateByEvent', activationEvent.event); instantiationService.stub(IUriIdentityService, UriIdentityService); instantiationService.stub(IExtensionManagementService, ExtensionManagementService); instantiationService.stub(IExtensionManagementService, 'onInstallExtension', installEvent.event); instantiationService.stub(IExtensionManagementService, 'onDidInstallExtensions', didInstallEvent.event); instantiationService.stub(IExtensionManagementService, 'onUninstallExtension', uninstallEvent.event); instantiationService.stub(IExtensionManagementService, 'onDidUninstallExtension', didUninstallEvent.event); instantiationService.stub(IWorkbenchExtensionEnablementService, new TestExtensionEnablementService(instantiationService)); instantiationService.stub(ITelemetryService, NullTelemetryService); instantiationService.stub(IURLService, NativeURLService); instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]); testConfigurationService = new TestConfigurationService(); instantiationService.stub(IConfigurationService, testConfigurationService); instantiationService.stub(ILifecycleService, new TestLifecycleService()); instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => c, getBoolean: (a: string, b: StorageScope, c?: boolean) => c, store: () => { }, remove: () => { } }); instantiationService.stub(IWorkspaceTrustManagementService, new TestWorkspaceTrustManagementService()); setup(() => { instantiationService.stub(IProductService, {}); instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => c, getBoolean: (a: string, b: StorageScope, c?: boolean) => c, store: () => { }, remove: () => { } }); }); teardown(() => { if (testObject) { testObject.dispose(); } }); }); test('Simple Experiment Test', () => { experimentData = { experiments: [ { id: 'experiment1' }, { id: 'experiment2', enabled: false }, { id: 'experiment3', enabled: true }, { id: 'experiment4', enabled: true, condition: { } }, { id: 'experiment5', enabled: true, condition: { insidersOnly: true } } ] }; testObject = instantiationService.createInstance(TestExperimentService); const tests: Promise<IExperiment>[] = []; tests.push(testObject.getExperimentById('experiment1')); tests.push(testObject.getExperimentById('experiment2')); tests.push(testObject.getExperimentById('experiment3')); tests.push(testObject.getExperimentById('experiment4')); tests.push(testObject.getExperimentById('experiment5')); return Promise.all(tests).then(results => { assert.strictEqual(results[0].id, 'experiment1'); assert.strictEqual(results[0].enabled, false); assert.strictEqual(results[0].state, ExperimentState.NoRun); assert.strictEqual(results[1].id, 'experiment2'); assert.strictEqual(results[1].enabled, false); assert.strictEqual(results[1].state, ExperimentState.NoRun); assert.strictEqual(results[2].id, 'experiment3'); assert.strictEqual(results[2].enabled, true); assert.strictEqual(results[2].state, ExperimentState.Run); assert.strictEqual(results[3].id, 'experiment4'); assert.strictEqual(results[3].enabled, true); assert.strictEqual(results[3].state, ExperimentState.Run); assert.strictEqual(results[4].id, 'experiment5'); assert.strictEqual(results[4].enabled, true); assert.strictEqual(results[4].state, ExperimentState.Run); }); }); test('filters out experiments with newer schema versions', async () => { experimentData = { experiments: [ { id: 'experiment1', // no version == 0 }, { id: 'experiment2', schemaVersion: currentSchemaVersion, }, { id: 'experiment3', schemaVersion: currentSchemaVersion + 1, }, ] }; testObject = instantiationService.createInstance(TestExperimentService); const actual = await Promise.all([ testObject.getExperimentById('experiment1'), testObject.getExperimentById('experiment2'), testObject.getExperimentById('experiment3'), ]); assert.strictEqual(actual[0]?.id, 'experiment1'); assert.strictEqual(actual[1]?.id, 'experiment2'); assert.strictEqual(actual[2], undefined); }); test('Insiders only experiment shouldnt be enabled in stable', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { insidersOnly: true } } ] }; instantiationService.stub(IProductService, { quality: 'stable' }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('NewUsers experiment shouldnt be enabled for old users', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { newUser: true } } ] }; instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => { return a === lastSessionDateStorageKey ? 'some-date' : undefined; }, getBoolean: (a: string, b: StorageScope, c?: boolean) => c, store: () => { }, remove: () => { } }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('OldUsers experiment shouldnt be enabled for new users', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { newUser: false } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('Experiment without NewUser condition should be enabled for old users', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: {} } ] }; instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c: string | undefined) => { return a === lastSessionDateStorageKey ? 'some-date' : undefined; }, getBoolean: (a: string, b: StorageScope, c?: boolean) => c, store: () => { }, remove: () => { } }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Experiment without NewUser condition should be enabled for new users', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: {} } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Experiment with OS should be enabled on current OS', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { os: [OS], } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Experiment with OS should be disabled on other OS', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { os: [OS - 1], } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('Activation event experiment with not enough events should be evaluating', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { activationEvent: { event: 'my:event', minEvents: 5, } } } ] }; instantiationService.stub(IStorageService, 'get', (a: string, b: StorageScope, c?: string) => { return a === 'experimentEventRecord-my-event' ? JSON.stringify({ count: [2], mostRecentBucket: Date.now() }) : undefined; }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Evaluating); }); }); test('Activation event works with enough events', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { activationEvent: { event: 'my:event', minEvents: 5, } } } ] }; instantiationService.stub(IStorageService, 'get', (a: string, b: StorageScope, c?: string) => { return a === 'experimentEventRecord-my-event' ? JSON.stringify({ count: [10], mostRecentBucket: Date.now() }) : undefined; }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Activation event allows multiple', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { activationEvent: { event: ['other:event', 'my:event'], minEvents: 5, } } } ] }; instantiationService.stub(IStorageService, 'get', (a: string, b: StorageScope, c?: string) => { return a === 'experimentEventRecord-my-event' ? JSON.stringify({ count: [10], mostRecentBucket: Date.now() }) : undefined; }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Activation event does not work with old data', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { activationEvent: { event: 'my:event', minEvents: 5, } } } ] }; instantiationService.stub(IStorageService, 'get', (a: string, b: StorageScope, c?: string) => { return a === 'experimentEventRecord-my-event' ? JSON.stringify({ count: [10], mostRecentBucket: Date.now() - (1000 * 60 * 60 * 24 * 10) }) : undefined; }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Evaluating); }); }); test('Parses activation records correctly', () => { const timers = sinon.useFakeTimers(); // so Date.now() is stable const oneDay = 1000 * 60 * 60 * 24; teardown(() => timers.restore()); let rec = getCurrentActivationRecord(); // good default: assert.deepStrictEqual(rec, { count: [0, 0, 0, 0, 0, 0, 0], mostRecentBucket: Date.now(), }); rec.count[0] = 1; timers.tick(1); rec = getCurrentActivationRecord(rec); // does not advance unnecessarily assert.deepStrictEqual(getCurrentActivationRecord(rec), { count: [1, 0, 0, 0, 0, 0, 0], mostRecentBucket: Date.now() - 1, }); // advances time timers.tick(oneDay * 3); rec = getCurrentActivationRecord(rec); assert.deepStrictEqual(getCurrentActivationRecord(rec), { count: [0, 0, 0, 1, 0, 0, 0], mostRecentBucket: Date.now() - 1, }); // rotates off time timers.tick(oneDay * 4); rec.count[0] = 2; rec = getCurrentActivationRecord(rec); assert.deepStrictEqual(getCurrentActivationRecord(rec), { count: [0, 0, 0, 0, 2, 0, 0], mostRecentBucket: Date.now() - 1, }); }); test('Activation event updates', async () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { activationEvent: { event: 'my:event', minEvents: 2, } } } ] }; instantiationService.stub(IStorageService, 'get', (a: string, b: StorageScope, c?: string) => { return a === 'experimentEventRecord-my-event' ? JSON.stringify({ count: [10, 0, 0, 0, 0, 0, 0], mostRecentBucket: Date.now() - (1000 * 60 * 60 * 24 * 2) }) : undefined; }); let didGetCall = false; instantiationService.stub(IStorageService, 'store', (key: string, value: string, scope: StorageScope) => { if (key.includes('experimentEventRecord')) { didGetCall = true; assert.strictEqual(key, 'experimentEventRecord-my-event'); assert.deepStrictEqual(JSON.parse(value).count, [1, 0, 10, 0, 0, 0, 0]); assert.strictEqual(scope, StorageScope.APPLICATION); } }); testObject = instantiationService.createInstance(TestExperimentService); await testObject.getExperimentById('experiment1'); activationEvent.fire({ event: 'not our event', activation: Promise.resolve() }); activationEvent.fire({ event: 'my:event', activation: Promise.resolve() }); assert(didGetCall); }); test('Activation events run experiments in realtime', async () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { activationEvent: { event: 'my:event', minEvents: 2, } } } ] }; let calls = 0; instantiationService.stub(IStorageService, 'get', (a: string, b: StorageScope, c?: string) => { return a === 'experimentEventRecord-my-event' ? JSON.stringify({ count: [++calls, 0, 0, 0, 0, 0, 0], mostRecentBucket: Date.now() }) : undefined; }); const enabledListener = sinon.stub(); testObject = instantiationService.createInstance(TestExperimentService); testObject.onExperimentEnabled(enabledListener); assert.strictEqual((await testObject.getExperimentById('experiment1')).state, ExperimentState.Evaluating); assert.strictEqual((await testObject.getExperimentById('experiment1')).state, ExperimentState.Evaluating); assert.strictEqual(enabledListener.callCount, 0); activationEvent.fire({ event: 'my:event', activation: Promise.resolve() }); await timeout(1); assert.strictEqual(enabledListener.callCount, 1); assert.strictEqual((await testObject.getExperimentById('experiment1')).state, ExperimentState.Run); }); test('Experiment not matching user setting should be disabled', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { userSetting: { neat: true } } } ] }; instantiationService.stub(IConfigurationService, 'getValue', (key: string) => key === 'neat' ? false : undefined); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('Experiment matching user setting should be enabled', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { userSetting: { neat: true } } } ] }; instantiationService.stub(IConfigurationService, 'getValue', (key: string) => key === 'neat' ? true : undefined); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Experiment with no matching display language should be disabled', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { displayLanguage: 'somethingthat-nooneknows' } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('Experiment with condition type InstalledExtensions is enabled when one of the expected extensions is installed', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { installedExtensions: { inlcudes: ['pub.installedExtension1', 'uninstalled-extention-id'] } } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Experiment with condition type InstalledExtensions is disabled when none of the expected extensions is installed', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { installedExtensions: { includes: ['uninstalled-extention-id1', 'uninstalled-extention-id2'] } } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('Experiment with condition type InstalledExtensions is disabled when one of the exlcuded extensions is installed', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { installedExtensions: { excludes: ['pub.installedExtension1', 'uninstalled-extention-id2'] } } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.NoRun); }); }); test('Experiment that is marked as complete should be disabled regardless of the conditions', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { installedExtensions: { includes: ['pub.installedExtension1', 'uninstalled-extention-id2'] } } } ] }; instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => a === 'experiments.experiment1' ? JSON.stringify({ state: ExperimentState.Complete }) : c, store: () => { } }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Complete); }); }); test('Experiment with evaluate only once should read enablement from storage service', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: true, condition: { installedExtensions: { excludes: ['pub.installedExtension1', 'uninstalled-extention-id2'] }, evaluateOnlyOnce: true } } ] }; instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => a === 'experiments.experiment1' ? JSON.stringify({ enabled: true, state: ExperimentState.Run }) : c, store: () => { } }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); }); }); test('Curated list should be available if experiment is enabled.', () => { const promptText = 'Hello there! Can you see this?'; const curatedExtensionsKey = 'AzureDeploy'; const curatedExtensionsList = ['uninstalled-extention-id1', 'uninstalled-extention-id2']; experimentData = { experiments: [ { id: 'experiment1', enabled: true, action: { type: 'Prompt', properties: { promptText, commands: [ { text: 'Search Marketplace', dontShowAgain: true, curatedExtensionsKey, curatedExtensionsList }, { text: 'No' } ] } } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, true); assert.strictEqual(result.state, ExperimentState.Run); return testObject.getCuratedExtensionsList(curatedExtensionsKey).then(curatedList => { assert.strictEqual(curatedList, curatedExtensionsList); }); }); }); test('Curated list shouldnt be available if experiment is disabled.', () => { const promptText = 'Hello there! Can you see this?'; const curatedExtensionsKey = 'AzureDeploy'; const curatedExtensionsList = ['uninstalled-extention-id1', 'uninstalled-extention-id2']; experimentData = { experiments: [ { id: 'experiment1', enabled: false, action: { type: 'Prompt', properties: { promptText, commands: [ { text: 'Search Marketplace', dontShowAgain: true, curatedExtensionsKey, curatedExtensionsList }, { text: 'No' } ] } } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, false); assert.strictEqual(result.action?.type, 'Prompt'); assert.strictEqual(result.state, ExperimentState.NoRun); return testObject.getCuratedExtensionsList(curatedExtensionsKey).then(curatedList => { assert.strictEqual(curatedList.length, 0); }); }); }); test('Maps action2 to action.', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: false, action2: { type: 'Prompt', properties: { promptText: 'Hello world', commands: [] } } } ] }; testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.action?.type, 'Prompt'); }); }); test('Experiment that is disabled or deleted should be removed from storage', () => { experimentData = { experiments: [ { id: 'experiment1', enabled: false }, { id: 'experiment3', enabled: true } ] }; let storageDataExperiment1: ExperimentSettings | null = { enabled: false }; let storageDataExperiment2: ExperimentSettings | null = { enabled: false }; let storageDataAllExperiments: string[] | null = ['experiment1', 'experiment2', 'experiment3']; instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => { switch (a) { case 'experiments.experiment1': return JSON.stringify(storageDataExperiment1); case 'experiments.experiment2': return JSON.stringify(storageDataExperiment2); case 'allExperiments': return JSON.stringify(storageDataAllExperiments); default: break; } return c; }, store: (a: string, b: any, c: StorageScope) => { switch (a) { case 'experiments.experiment1': storageDataExperiment1 = JSON.parse(b); break; case 'experiments.experiment2': storageDataExperiment2 = JSON.parse(b); break; case 'allExperiments': storageDataAllExperiments = JSON.parse(b); break; default: break; } }, remove: (a: string) => { switch (a) { case 'experiments.experiment1': storageDataExperiment1 = null; break; case 'experiments.experiment2': storageDataExperiment2 = null; break; case 'allExperiments': storageDataAllExperiments = null; break; default: break; } } }); testObject = instantiationService.createInstance(TestExperimentService); const disabledExperiment = testObject.getExperimentById('experiment1').then(result => { assert.strictEqual(result.enabled, false); assert.strictEqual(!!storageDataExperiment1, false); }); const deletedExperiment = testObject.getExperimentById('experiment2').then(result => { assert.strictEqual(!!result, false); assert.strictEqual(!!storageDataExperiment2, false); }); return Promise.all([disabledExperiment, deletedExperiment]).then(() => { assert.strictEqual(storageDataAllExperiments!.length, 1); assert.strictEqual(storageDataAllExperiments![0], 'experiment3'); }); }); test('Offline mode', () => { experimentData = { experiments: null }; let storageDataExperiment1: ExperimentSettings | null = { enabled: true, state: ExperimentState.Run }; let storageDataExperiment2: ExperimentSettings | null = { enabled: true, state: ExperimentState.NoRun }; let storageDataExperiment3: ExperimentSettings | null = { enabled: true, state: ExperimentState.Evaluating }; let storageDataExperiment4: ExperimentSettings | null = { enabled: true, state: ExperimentState.Complete }; let storageDataAllExperiments: string[] | null = ['experiment1', 'experiment2', 'experiment3', 'experiment4']; instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => { switch (a) { case 'experiments.experiment1': return JSON.stringify(storageDataExperiment1); case 'experiments.experiment2': return JSON.stringify(storageDataExperiment2); case 'experiments.experiment3': return JSON.stringify(storageDataExperiment3); case 'experiments.experiment4': return JSON.stringify(storageDataExperiment4); case 'allExperiments': return JSON.stringify(storageDataAllExperiments); default: break; } return c; }, store: (a, b, c) => { switch (a) { case 'experiments.experiment1': storageDataExperiment1 = JSON.parse(b + ''); break; case 'experiments.experiment2': storageDataExperiment2 = JSON.parse(b + ''); break; case 'experiments.experiment3': storageDataExperiment3 = JSON.parse(b + ''); break; case 'experiments.experiment4': storageDataExperiment4 = JSON.parse(b + ''); break; case 'allExperiments': storageDataAllExperiments = JSON.parse(b + ''); break; default: break; } }, remove: a => { switch (a) { case 'experiments.experiment1': storageDataExperiment1 = null; break; case 'experiments.experiment2': storageDataExperiment2 = null; break; case 'experiments.experiment3': storageDataExperiment3 = null; break; case 'experiments.experiment4': storageDataExperiment4 = null; break; case 'allExperiments': storageDataAllExperiments = null; break; default: break; } } }); testObject = instantiationService.createInstance(TestExperimentService); const tests: Promise<IExperiment>[] = []; tests.push(testObject.getExperimentById('experiment1')); tests.push(testObject.getExperimentById('experiment2')); tests.push(testObject.getExperimentById('experiment3')); tests.push(testObject.getExperimentById('experiment4')); return Promise.all(tests).then(results => { assert.strictEqual(results[0].id, 'experiment1'); assert.strictEqual(results[0].enabled, true); assert.strictEqual(results[0].state, ExperimentState.Run); assert.strictEqual(results[1].id, 'experiment2'); assert.strictEqual(results[1].enabled, true); assert.strictEqual(results[1].state, ExperimentState.NoRun); assert.strictEqual(results[2].id, 'experiment3'); assert.strictEqual(results[2].enabled, true); assert.strictEqual(results[2].state, ExperimentState.Evaluating); assert.strictEqual(results[3].id, 'experiment4'); assert.strictEqual(results[3].enabled, true); assert.strictEqual(results[3].state, ExperimentState.Complete); }); }); test('getExperimentByType', () => { const customProperties = { some: 'random-value' }; experimentData = { experiments: [ { id: 'simple-experiment', enabled: true }, { id: 'custom-experiment', enabled: true, action: { type: 'Custom', properties: customProperties } }, { id: 'custom-experiment-no-properties', enabled: true, action: { type: 'Custom' } }, { id: 'prompt-with-no-commands', enabled: true, action: { type: 'Prompt', properties: { promptText: 'someText' } } }, { id: 'prompt-with-commands', enabled: true, action: { type: 'Prompt', properties: { promptText: 'someText', commands: [ { text: 'Hello' } ] } } } ] }; testObject = instantiationService.createInstance(TestExperimentService); const custom = testObject.getExperimentsByType(ExperimentActionType.Custom).then(result => { assert.strictEqual(result.length, 3); assert.strictEqual(result[0].id, 'simple-experiment'); assert.strictEqual(result[1].id, 'custom-experiment'); assert.strictEqual(result[1].action!.properties, customProperties); assert.strictEqual(result[2].id, 'custom-experiment-no-properties'); assert.strictEqual(!!result[2].action!.properties, true); }); const prompt = testObject.getExperimentsByType(ExperimentActionType.Prompt).then(result => { assert.strictEqual(result.length, 2); assert.strictEqual(result[0].id, 'prompt-with-no-commands'); assert.strictEqual(result[1].id, 'prompt-with-commands'); }); return Promise.all([custom, prompt]); }); test('experimentsPreviouslyRun includes, excludes check', () => { experimentData = { experiments: [ { id: 'experiment3', enabled: true, condition: { experimentsPreviouslyRun: { includes: ['experiment1'], excludes: ['experiment2'] } } }, { id: 'experiment4', enabled: true, condition: { experimentsPreviouslyRun: { includes: ['experiment1'], excludes: ['experiment200'] } } } ] }; let storageDataExperiment3 = { enabled: true, state: ExperimentState.Evaluating }; let storageDataExperiment4 = { enabled: true, state: ExperimentState.Evaluating }; instantiationService.stub(IStorageService, <Partial<IStorageService>>{ get: (a: string, b: StorageScope, c?: string) => { switch (a) { case 'currentOrPreviouslyRunExperiments': return JSON.stringify(['experiment1', 'experiment2']); default: break; } return c; }, store: (a, b, c) => { switch (a) { case 'experiments.experiment3': storageDataExperiment3 = JSON.parse(b + ''); break; case 'experiments.experiment4': storageDataExperiment4 = JSON.parse(b + ''); break; default: break; } } }); testObject = instantiationService.createInstance(TestExperimentService); return testObject.getExperimentsByType(ExperimentActionType.Custom).then(result => { assert.strictEqual(result.length, 2); assert.strictEqual(result[0].id, 'experiment3'); assert.strictEqual(result[0].state, ExperimentState.NoRun); assert.strictEqual(result[1].id, 'experiment4'); assert.strictEqual(result[1].state, ExperimentState.Run); assert.strictEqual(storageDataExperiment3.state, ExperimentState.NoRun); assert.strictEqual(storageDataExperiment4.state, ExperimentState.Run); return Promise.resolve(null); }); }); // test('Experiment with condition type FileEdit should increment editcount as appropriate', () => { // }); // test('Experiment with condition type WorkspaceEdit should increment editcount as appropriate', () => { // }); });
src/vs/workbench/contrib/experiments/test/electron-browser/experimentService.test.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.0001759989681886509, 0.0001721017324598506, 0.0001639734546188265, 0.00017260867753066123, 0.0000022865672235639067 ]
{ "id": 4, "code_window": [ "\n", "\t\t\tconst commandId = `workbench.action.revealPathInFinder${i}`;\n", "\t\t\tthis.customTitleContextMenuDisposable.add(CommandsRegistry.registerCommand(commandId, () => this.nativeHostService.showItemInFolder(path.fsPath)));\n", "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n", "\t\t}\n", "\t}\n", "\n", "\tprivate create(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarTitleContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n" ], "file_path": "src/vs/workbench/electron-sandbox/window.ts", "type": "replace", "edit_start_line_idx": 605 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IRange } from 'vs/editor/common/core/range'; import { SymbolKind, ProviderResult, SymbolTag } from 'vs/editor/common/languages'; import { ITextModel } from 'vs/editor/common/model'; import { CancellationToken } from 'vs/base/common/cancellation'; import { LanguageFeatureRegistry } from 'vs/editor/common/languageFeatureRegistry'; import { URI } from 'vs/base/common/uri'; import { IPosition, Position } from 'vs/editor/common/core/position'; import { isNonEmptyArray } from 'vs/base/common/arrays'; import { onUnexpectedExternalError } from 'vs/base/common/errors'; import { IDisposable, RefCountedDisposable } from 'vs/base/common/lifecycle'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { assertType } from 'vs/base/common/types'; import { IModelService } from 'vs/editor/common/services/model'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; export const enum CallHierarchyDirection { CallsTo = 'incomingCalls', CallsFrom = 'outgoingCalls' } export interface CallHierarchyItem { _sessionId: string; _itemId: string; kind: SymbolKind; name: string; detail?: string; uri: URI; range: IRange; selectionRange: IRange; tags?: SymbolTag[]; } export interface IncomingCall { from: CallHierarchyItem; fromRanges: IRange[]; } export interface OutgoingCall { fromRanges: IRange[]; to: CallHierarchyItem; } export interface CallHierarchySession { roots: CallHierarchyItem[]; dispose(): void; } export interface CallHierarchyProvider { prepareCallHierarchy(document: ITextModel, position: IPosition, token: CancellationToken): ProviderResult<CallHierarchySession>; provideIncomingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult<IncomingCall[]>; provideOutgoingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult<OutgoingCall[]>; } export const CallHierarchyProviderRegistry = new LanguageFeatureRegistry<CallHierarchyProvider>(); export class CallHierarchyModel { static async create(model: ITextModel, position: IPosition, token: CancellationToken): Promise<CallHierarchyModel | undefined> { const [provider] = CallHierarchyProviderRegistry.ordered(model); if (!provider) { return undefined; } const session = await provider.prepareCallHierarchy(model, position, token); if (!session) { return undefined; } return new CallHierarchyModel(session.roots.reduce((p, c) => p + c._sessionId, ''), provider, session.roots, new RefCountedDisposable(session)); } readonly root: CallHierarchyItem; private constructor( readonly id: string, readonly provider: CallHierarchyProvider, readonly roots: CallHierarchyItem[], readonly ref: RefCountedDisposable, ) { this.root = roots[0]; } dispose(): void { this.ref.release(); } fork(item: CallHierarchyItem): CallHierarchyModel { const that = this; return new class extends CallHierarchyModel { constructor() { super(that.id, that.provider, [item], that.ref.acquire()); } }; } async resolveIncomingCalls(item: CallHierarchyItem, token: CancellationToken): Promise<IncomingCall[]> { try { const result = await this.provider.provideIncomingCalls(item, token); if (isNonEmptyArray(result)) { return result; } } catch (e) { onUnexpectedExternalError(e); } return []; } async resolveOutgoingCalls(item: CallHierarchyItem, token: CancellationToken): Promise<OutgoingCall[]> { try { const result = await this.provider.provideOutgoingCalls(item, token); if (isNonEmptyArray(result)) { return result; } } catch (e) { onUnexpectedExternalError(e); } return []; } } // --- API command support const _models = new Map<string, CallHierarchyModel>(); CommandsRegistry.registerCommand('_executePrepareCallHierarchy', async (accessor, ...args) => { const [resource, position] = args; assertType(URI.isUri(resource)); assertType(Position.isIPosition(position)); const modelService = accessor.get(IModelService); let textModel = modelService.getModel(resource); let textModelReference: IDisposable | undefined; if (!textModel) { const textModelService = accessor.get(ITextModelService); const result = await textModelService.createModelReference(resource); textModel = result.object.textEditorModel; textModelReference = result; } try { const model = await CallHierarchyModel.create(textModel, position, CancellationToken.None); if (!model) { return []; } // _models.set(model.id, model); _models.forEach((value, key, map) => { if (map.size > 10) { value.dispose(); _models.delete(key); } }); return [model.root]; } finally { textModelReference?.dispose(); } }); function isCallHierarchyItemDto(obj: any): obj is CallHierarchyItem { return true; } CommandsRegistry.registerCommand('_executeProvideIncomingCalls', async (_accessor, ...args) => { const [item] = args; assertType(isCallHierarchyItemDto(item)); // find model const model = _models.get(item._sessionId); if (!model) { return undefined; } return model.resolveIncomingCalls(item, CancellationToken.None); }); CommandsRegistry.registerCommand('_executeProvideOutgoingCalls', async (_accessor, ...args) => { const [item] = args; assertType(isCallHierarchyItemDto(item)); // find model const model = _models.get(item._sessionId); if (!model) { return undefined; } return model.resolveOutgoingCalls(item, CancellationToken.None); });
src/vs/workbench/contrib/callHierarchy/common/callHierarchy.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.0007064072415232658, 0.00019548230920918286, 0.00015960649761836976, 0.00017065164865925908, 0.00011728699610102922 ]
{ "id": 4, "code_window": [ "\n", "\t\t\tconst commandId = `workbench.action.revealPathInFinder${i}`;\n", "\t\t\tthis.customTitleContextMenuDisposable.add(CommandsRegistry.registerCommand(commandId, () => this.nativeHostService.showItemInFolder(path.fsPath)));\n", "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n", "\t\t}\n", "\t}\n", "\n", "\tprivate create(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarTitleContext, { command: { id: commandId, title: label || posix.sep }, order: -i }));\n" ], "file_path": "src/vs/workbench/electron-sandbox/window.ts", "type": "replace", "edit_start_line_idx": 605 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { EditorConfiguration, IEditorConstructionOptions } from 'vs/editor/browser/config/editorConfiguration'; import { IActiveCodeEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { View } from 'vs/editor/browser/view'; import { CodeEditorWidget, ICodeEditorWidgetOptions } from 'vs/editor/browser/widget/codeEditorWidget'; import * as editorOptions from 'vs/editor/common/config/editorOptions'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { ITextBufferFactory, ITextModel } from 'vs/editor/common/model'; import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker'; import { ILanguageFeatureDebounceService, LanguageFeatureDebounceService } from 'vs/editor/common/services/languageFeatureDebounce'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { LanguageFeaturesService } from 'vs/editor/common/services/languageFeaturesService'; import { LanguageService } from 'vs/editor/common/services/languageService'; import { IModelService } from 'vs/editor/common/services/model'; import { ModelService } from 'vs/editor/common/services/modelService'; import { ITextResourcePropertiesService } from 'vs/editor/common/services/textResourceConfiguration'; import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl'; import { TestConfiguration } from 'vs/editor/test/browser/config/testConfiguration'; import { TestCodeEditorService, TestCommandService } from 'vs/editor/test/browser/editorTestServices'; import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService'; import { TestEditorWorkerService } from 'vs/editor/test/common/services/testEditorWorkerService'; import { TestTextResourcePropertiesService } from 'vs/editor/test/common/services/testTextResourcePropertiesService'; import { instantiateTextModel } from 'vs/editor/test/common/testTextModel'; import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility'; import { TestAccessibilityService } from 'vs/platform/accessibility/test/common/testAccessibilityService'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { TestClipboardService } from 'vs/platform/clipboard/test/common/testClipboardService'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { IContextKeyService, IContextKeyServiceTarget } from 'vs/platform/contextkey/common/contextkey'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { TestDialogService } from 'vs/platform/dialogs/test/common/testDialogService'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { BrandedService, IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { IOpenerService, NullOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryServiceShape } from 'vs/platform/telemetry/common/telemetryUtils'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo'; import { UndoRedoService } from 'vs/platform/undoRedo/common/undoRedoService'; export interface ITestCodeEditor extends IActiveCodeEditor { getViewModel(): ViewModel | undefined; registerAndInstantiateContribution<T extends IEditorContribution, Services extends BrandedService[]>(id: string, ctor: new (editor: ICodeEditor, ...services: Services) => T): T; registerDisposable(disposable: IDisposable): void; } export class TestCodeEditor extends CodeEditorWidget implements ICodeEditor { //#region testing overrides protected override _createConfiguration(isSimpleWidget: boolean, options: Readonly<IEditorConstructionOptions>): EditorConfiguration { return new TestConfiguration(options); } protected override _createView(viewModel: ViewModel): [View, boolean] { // Never create a view return [null! as View, false]; } private _hasTextFocus = false; public setHasTextFocus(hasTextFocus: boolean): void { this._hasTextFocus = hasTextFocus; } public override hasTextFocus(): boolean { return this._hasTextFocus; } //#endregion //#region Testing utils public getViewModel(): ViewModel | undefined { return this._modelData ? this._modelData.viewModel : undefined; } public registerAndInstantiateContribution<T extends IEditorContribution>(id: string, ctor: new (editor: ICodeEditor, ...services: BrandedService[]) => T): T { const r: T = this._instantiationService.createInstance(ctor, this); this._contributions[id] = r; return r; } public registerDisposable(disposable: IDisposable): void { this._register(disposable); } } class TestEditorDomElement { parentElement: IContextKeyServiceTarget | null = null; setAttribute(attr: string, value: string): void { } removeAttribute(attr: string): void { } hasAttribute(attr: string): boolean { return false; } getAttribute(attr: string): string | undefined { return undefined; } addEventListener(event: string): void { } removeEventListener(event: string): void { } } export interface TestCodeEditorCreationOptions extends editorOptions.IEditorOptions { /** * If the editor has text focus. * Defaults to true. */ hasTextFocus?: boolean; } export interface TestCodeEditorInstantiationOptions extends TestCodeEditorCreationOptions { /** * Services to use. */ serviceCollection?: ServiceCollection; } export function withTestCodeEditor(text: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => void): void { return _withTestCodeEditor(text, options, callback); } export async function withAsyncTestCodeEditor(text: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => Promise<void>): Promise<void> { return _withTestCodeEditor(text, options, callback); } function isTextModel(arg: ITextModel | string | string[] | ITextBufferFactory): arg is ITextModel { return Boolean(arg && (arg as ITextModel).uri); } function _withTestCodeEditor(arg: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => void): void; function _withTestCodeEditor(arg: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => Promise<void>): Promise<void>; function _withTestCodeEditor(arg: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => Promise<void> | void): Promise<void> | void { const disposables = new DisposableStore(); const instantiationService = createCodeEditorServices(disposables, options.serviceCollection); delete options.serviceCollection; // create a model if necessary let model: ITextModel; if (isTextModel(arg)) { model = arg; } else { model = disposables.add(instantiateTextModel(instantiationService, Array.isArray(arg) ? arg.join('\n') : arg)); } const editor = disposables.add(instantiateTestCodeEditor(instantiationService, model, options)); const viewModel = editor.getViewModel()!; viewModel.setHasFocus(true); const result = callback(<ITestCodeEditor>editor, editor.getViewModel()!, instantiationService); if (result) { return result.then(() => disposables.dispose()); } disposables.dispose(); } export function createCodeEditorServices(disposables: DisposableStore, services: ServiceCollection = new ServiceCollection()): TestInstantiationService { const serviceIdentifiers: ServiceIdentifier<any>[] = []; const define = <T>(id: ServiceIdentifier<T>, ctor: new (...args: any[]) => T) => { if (!services.has(id)) { services.set(id, new SyncDescriptor(ctor)); } serviceIdentifiers.push(id); }; const defineInstance = <T>(id: ServiceIdentifier<T>, instance: T) => { if (!services.has(id)) { services.set(id, instance); } serviceIdentifiers.push(id); }; define(IAccessibilityService, TestAccessibilityService); define(IClipboardService, TestClipboardService); define(IEditorWorkerService, TestEditorWorkerService); defineInstance(IOpenerService, NullOpenerService); define(INotificationService, TestNotificationService); define(IDialogService, TestDialogService); define(IUndoRedoService, UndoRedoService); define(ILanguageService, LanguageService); define(ILanguageConfigurationService, TestLanguageConfigurationService); define(IConfigurationService, TestConfigurationService); define(ITextResourcePropertiesService, TestTextResourcePropertiesService); define(IThemeService, TestThemeService); define(ILogService, NullLogService); define(IModelService, ModelService); define(ICodeEditorService, TestCodeEditorService); define(IContextKeyService, MockContextKeyService); define(ICommandService, TestCommandService); define(ITelemetryService, NullTelemetryServiceShape); define(ILanguageFeatureDebounceService, LanguageFeatureDebounceService); define(ILanguageFeaturesService, LanguageFeaturesService); const instantiationService = new TestInstantiationService(services, true); disposables.add(toDisposable(() => { for (const id of serviceIdentifiers) { const instanceOrDescriptor = services.get(id); if (typeof instanceOrDescriptor.dispose === 'function') { instanceOrDescriptor.dispose(); } } })); return instantiationService; } export function createTestCodeEditor(model: ITextModel | undefined, options: TestCodeEditorInstantiationOptions = {}): ITestCodeEditor { const disposables = new DisposableStore(); const instantiationService = createCodeEditorServices(disposables, options.serviceCollection); delete options.serviceCollection; const editor = instantiateTestCodeEditor(instantiationService, model || null, options); editor.registerDisposable(disposables); return editor; } export function instantiateTestCodeEditor(instantiationService: IInstantiationService, model: ITextModel | null, options: TestCodeEditorCreationOptions = {}): ITestCodeEditor { const codeEditorWidgetOptions: ICodeEditorWidgetOptions = { contributions: [] }; const editor = instantiationService.createInstance( TestCodeEditor, <HTMLElement><any>new TestEditorDomElement(), options, codeEditorWidgetOptions ); if (typeof options.hasTextFocus === 'undefined') { options.hasTextFocus = true; } editor.setHasTextFocus(options.hasTextFocus); editor.setModel(model); const viewModel = editor.getViewModel(); viewModel?.setHasFocus(options.hasTextFocus); return <ITestCodeEditor>editor; }
src/vs/editor/test/browser/testCodeEditor.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.0010928967967629433, 0.00021043683227617294, 0.0001638073445064947, 0.00017241522436961532, 0.00018404416914563626 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {HttpClient} from '@angular/common/http';\n", "import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/http/testing/test/request_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /// <reference types="rxjs" /> import {EventEmitter} from '@angular/core'; import {defineComponent, defineDirective} from '../../src/render3/index'; import {bind, container, containerRefreshEnd, containerRefreshStart, element, elementEnd, elementProperty, elementStart, embeddedViewEnd, embeddedViewStart, interpolation1, listener, load, reference, text, textBinding} from '../../src/render3/instructions'; import {RenderFlags} from '../../src/render3/interfaces/definition'; import {NO_CHANGE} from '../../src/render3/tokens'; import {ComponentFixture, createComponent, renderToHtml} from './render_util'; describe('elementProperty', () => { it('should support bindings to properties', () => { const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'span'); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id)); } }, 1, 1); const fixture = new ComponentFixture(App); fixture.component.id = 'testId'; fixture.update(); expect(fixture.html).toEqual('<span id="testId"></span>'); fixture.component.id = 'otherId'; fixture.update(); expect(fixture.html).toEqual('<span id="otherId"></span>'); }); it('should support creation time bindings to properties', () => { function expensive(ctx: string): any { if (ctx === 'cheapId') { return ctx; } else { throw 'Too expensive!'; } } function Template(rf: RenderFlags, ctx: string) { if (rf & RenderFlags.Create) { element(0, 'span'); elementProperty(0, 'id', expensive(ctx)); } } expect(renderToHtml(Template, 'cheapId', 1)).toEqual('<span id="cheapId"></span>'); expect(renderToHtml(Template, 'expensiveId', 1)).toEqual('<span id="cheapId"></span>'); }); it('should support interpolation for properties', () => { const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'span'); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', interpolation1('_', ctx.id, '_')); } }, 1, 1); const fixture = new ComponentFixture(App); fixture.component.id = 'testId'; fixture.update(); expect(fixture.html).toEqual('<span id="_testId_"></span>'); fixture.component.id = 'otherId'; fixture.update(); expect(fixture.html).toEqual('<span id="_otherId_"></span>'); }); describe('input properties', () => { let button: MyButton; let otherDir: OtherDir; let otherDisabledDir: OtherDisabledDir; let idDir: IdDir; class MyButton { // TODO(issue/24571): remove '!'. disabled !: boolean; static ngDirectiveDef = defineDirective({ type: MyButton, selectors: [['', 'myButton', '']], factory: () => button = new MyButton(), inputs: {disabled: 'disabled'} }); } class OtherDir { // TODO(issue/24571): remove '!'. id !: number; clickStream = new EventEmitter(); static ngDirectiveDef = defineDirective({ type: OtherDir, selectors: [['', 'otherDir', '']], factory: () => otherDir = new OtherDir(), inputs: {id: 'id'}, outputs: {clickStream: 'click'} }); } class OtherDisabledDir { // TODO(issue/24571): remove '!'. disabled !: boolean; static ngDirectiveDef = defineDirective({ type: OtherDisabledDir, selectors: [['', 'otherDisabledDir', '']], factory: () => otherDisabledDir = new OtherDisabledDir(), inputs: {disabled: 'disabled'} }); } class IdDir { // TODO(issue/24571): remove '!'. idNumber !: string; static ngDirectiveDef = defineDirective({ type: IdDir, selectors: [['', 'idDir', '']], factory: () => idDir = new IdDir(), inputs: {idNumber: 'id'} }); } const deps = [MyButton, OtherDir, OtherDisabledDir, IdDir]; it('should check input properties before setting (directives)', () => { /** <button myButton otherDir [id]="id" [disabled]="isDisabled">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['otherDir', '', 'myButton', '']); { text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'disabled', bind(ctx.isDisabled)); elementProperty(0, 'id', bind(ctx.id)); } }, 2, 2, deps); const fixture = new ComponentFixture(App); fixture.component.isDisabled = true; fixture.component.id = 0; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdir="">Click me</button>`); expect(button !.disabled).toEqual(true); expect(otherDir !.id).toEqual(0); fixture.component.isDisabled = false; fixture.component.id = 1; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdir="">Click me</button>`); expect(button !.disabled).toEqual(false); expect(otherDir !.id).toEqual(1); }); it('should support mixed element properties and input properties', () => { /** <button myButton [id]="id" [disabled]="isDisabled">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['myButton', '']); { text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'disabled', bind(ctx.isDisabled)); elementProperty(0, 'id', bind(ctx.id)); } }, 2, 2, deps); const fixture = new ComponentFixture(App); fixture.component.isDisabled = true; fixture.component.id = 0; fixture.update(); expect(fixture.html).toEqual(`<button id="0" mybutton="">Click me</button>`); expect(button !.disabled).toEqual(true); fixture.component.isDisabled = false; fixture.component.id = 1; fixture.update(); expect(fixture.html).toEqual(`<button id="1" mybutton="">Click me</button>`); expect(button !.disabled).toEqual(false); }); it('should check that property is not an input property before setting (component)', () => { let comp: Comp; class Comp { // TODO(issue/24571): remove '!'. id !: number; static ngComponentDef = defineComponent({ type: Comp, selectors: [['comp']], consts: 0, vars: 0, template: function(rf: RenderFlags, ctx: any) {}, factory: () => comp = new Comp(), inputs: {id: 'id'} }); } /** <comp [id]="id"></comp> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'comp'); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id)); } }, 1, 1, [Comp]); const fixture = new ComponentFixture(App); fixture.component.id = 1; fixture.update(); expect(fixture.html).toEqual(`<comp></comp>`); expect(comp !.id).toEqual(1); fixture.component.id = 2; fixture.update(); expect(fixture.html).toEqual(`<comp></comp>`); expect(comp !.id).toEqual(2); }); it('should support two input properties with the same name', () => { /** <button myButton otherDisabledDir [disabled]="isDisabled">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['myButton', '', 'otherDisabledDir', '']); { text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'disabled', bind(ctx.isDisabled)); } }, 2, 1, deps); const fixture = new ComponentFixture(App); fixture.component.isDisabled = true; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdisableddir="">Click me</button>`); expect(button !.disabled).toEqual(true); expect(otherDisabledDir !.disabled).toEqual(true); fixture.component.isDisabled = false; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdisableddir="">Click me</button>`); expect(button !.disabled).toEqual(false); expect(otherDisabledDir !.disabled).toEqual(false); }); it('should set input property if there is an output first', () => { /** <button otherDir [id]="id" (click)="onClick()">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['otherDir', '']); { listener('click', () => ctx.onClick()); text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id)); } }, 2, 1, deps); const fixture = new ComponentFixture(App); let counter = 0; fixture.component.id = 1; fixture.component.onClick = () => counter++; fixture.update(); expect(fixture.html).toEqual(`<button otherdir="">Click me</button>`); expect(otherDir !.id).toEqual(1); otherDir !.clickStream.next(); expect(counter).toEqual(1); fixture.component.id = 2; fixture.update(); fixture.html; expect(otherDir !.id).toEqual(2); }); it('should support unrelated element properties at same index in if-else block', () => { /** * <button idDir [id]="id1">Click me</button> // inputs: {'id': [0, 'idNumber']} * % if (condition) { * <button [id]="id2">Click me too</button> // inputs: null * % } else { * <button otherDir [id]="id3">Click me too</button> // inputs: {'id': [0, 'id']} * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['idDir', '']); { text(1, 'Click me'); } elementEnd(); container(2); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id1)); containerRefreshStart(2); { if (ctx.condition) { let rf0 = embeddedViewStart(0, 2, 1); if (rf0 & RenderFlags.Create) { elementStart(0, 'button'); { text(1, 'Click me too'); } elementEnd(); } if (rf0 & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id2)); } embeddedViewEnd(); } else { let rf1 = embeddedViewStart(1, 2, 1); if (rf1 & RenderFlags.Create) { elementStart(0, 'button', ['otherDir', '']); { text(1, 'Click me too'); } elementEnd(); } if (rf1 & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id3)); } embeddedViewEnd(); } } containerRefreshEnd(); } }, 3, 1, deps); const fixture = new ComponentFixture(App); fixture.component.condition = true; fixture.component.id1 = 'one'; fixture.component.id2 = 'two'; fixture.component.id3 = 3; fixture.update(); expect(fixture.html) .toEqual(`<button iddir="">Click me</button><button id="two">Click me too</button>`); expect(idDir !.idNumber).toEqual('one'); fixture.component.condition = false; fixture.component.id1 = 'four'; fixture.update(); expect(fixture.html) .toEqual(`<button iddir="">Click me</button><button otherdir="">Click me too</button>`); expect(idDir !.idNumber).toEqual('four'); expect(otherDir !.id).toEqual(3); }); }); describe('attributes and input properties', () => { let myDir: MyDir; class MyDir { // TODO(issue/24571): remove '!'. role !: string; // TODO(issue/24571): remove '!'. direction !: string; changeStream = new EventEmitter(); static ngDirectiveDef = defineDirective({ type: MyDir, selectors: [['', 'myDir', '']], factory: () => myDir = new MyDir(), inputs: {role: 'role', direction: 'dir'}, outputs: {changeStream: 'change'}, exportAs: ['myDir'] }); } let dirB: MyDirB; class MyDirB { // TODO(issue/24571): remove '!'. roleB !: string; static ngDirectiveDef = defineDirective({ type: MyDirB, selectors: [['', 'myDirB', '']], factory: () => dirB = new MyDirB(), inputs: {roleB: 'role'} }); } const deps = [MyDir, MyDirB]; it('should set input property based on attribute if existing', () => { /** <div role="button" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', '']); } }, 1, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html).toEqual(`<div mydir="" role="button"></div>`); expect(myDir !.role).toEqual('button'); }); it('should set input property and attribute if both defined', () => { /** <div role="button" [role]="role" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', '']); } if (rf & RenderFlags.Update) { elementProperty(0, 'role', bind(ctx.role)); } }, 1, 1, deps); const fixture = new ComponentFixture(App); fixture.component.role = 'listbox'; fixture.update(); expect(fixture.html).toEqual(`<div mydir="" role="button"></div>`); expect(myDir !.role).toEqual('listbox'); fixture.component.role = 'button'; fixture.update(); expect(myDir !.role).toEqual('button'); }); it('should set two directive input properties based on same attribute', () => { /** <div role="button" myDir myDirB></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', '', 'myDirB', '']); } }, 1, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html).toEqual(`<div mydir="" mydirb="" role="button"></div>`); expect(myDir !.role).toEqual('button'); expect(dirB !.roleB).toEqual('button'); }); it('should process two attributes on same directive', () => { /** <div role="button" dir="rtl" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'dir', 'rtl', 'myDir', '']); } }, 1, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html).toEqual(`<div dir="rtl" mydir="" role="button"></div>`); expect(myDir !.role).toEqual('button'); expect(myDir !.direction).toEqual('rtl'); }); it('should process attributes and outputs properly together', () => { /** <div role="button" (change)="onChange()" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'div', ['role', 'button', 'myDir', '']); { listener('change', () => ctx.onChange()); } elementEnd(); } }, 1, 0, deps); const fixture = new ComponentFixture(App); let counter = 0; fixture.component.onChange = () => counter++; fixture.update(); expect(fixture.html).toEqual(`<div mydir="" role="button"></div>`); expect(myDir !.role).toEqual('button'); myDir !.changeStream.next(); expect(counter).toEqual(1); }); it('should process attributes properly for directives with later indices', () => { /** * <div role="button" dir="rtl" myDir></div> * <div role="listbox" myDirB></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'dir', 'rtl', 'myDir', '']); element(1, 'div', ['role', 'listbox', 'myDirB', '']); } }, 2, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html) .toEqual( `<div dir="rtl" mydir="" role="button"></div><div mydirb="" role="listbox"></div>`); expect(myDir !.role).toEqual('button'); expect(myDir !.direction).toEqual('rtl'); expect(dirB !.roleB).toEqual('listbox'); }); it('should support attributes at same index inside an if-else block', () => { /** * <div role="listbox" myDir></div> // initialInputs: [['role', 'listbox']] * * % if (condition) { * <div role="button" myDirB></div> // initialInputs: [['role', 'button']] * % } else { * <div role="menu"></div> // initialInputs: [null] * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'listbox', 'myDir', '']); container(1); } if (rf & RenderFlags.Update) { containerRefreshStart(1); { if (ctx.condition) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDirB', '']); } embeddedViewEnd(); } else { let rf2 = embeddedViewStart(1, 1, 0); if (rf2 & RenderFlags.Create) { element(0, 'div', ['role', 'menu']); } embeddedViewEnd(); } } containerRefreshEnd(); } }, 2, 0, deps); const fixture = new ComponentFixture(App); fixture.component.condition = true; fixture.update(); expect(fixture.html) .toEqual(`<div mydir="" role="listbox"></div><div mydirb="" role="button"></div>`); expect(myDir !.role).toEqual('listbox'); expect(dirB !.roleB).toEqual('button'); expect((dirB !as any).role).toBeUndefined(); fixture.component.condition = false; fixture.update(); expect(fixture.html).toEqual(`<div mydir="" role="listbox"></div><div role="menu"></div>`); expect(myDir !.role).toEqual('listbox'); }); it('should process attributes properly inside a for loop', () => { class Comp { static ngComponentDef = defineComponent({ type: Comp, selectors: [['comp']], consts: 3, vars: 1, /** <div role="button" dir #dir="myDir"></div> {{ dir.role }} */ template: function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', ''], ['dir', 'myDir']); text(2); } if (rf & RenderFlags.Update) { const tmp = reference(1) as any; textBinding(2, bind(tmp.role)); } }, factory: () => new Comp(), directives: () => [MyDir] }); } /** * % for (let i = 0; i < 3; i++) { * <comp></comp> * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); { for (let i = 0; i < 2; i++) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { element(0, 'comp'); } embeddedViewEnd(); } } containerRefreshEnd(); } }, 1, 0, [Comp]); const fixture = new ComponentFixture(App); expect(fixture.html) .toEqual( `<comp><div mydir="" role="button"></div>button</comp><comp><div mydir="" role="button"></div>button</comp>`); }); }); });
packages/core/test/render3/properties_spec.ts
1
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.0001809970272006467, 0.00017334125004708767, 0.0001652509527048096, 0.0001731725496938452, 0.000003949048732465599 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {HttpClient} from '@angular/common/http';\n", "import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/http/testing/test/request_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core'; import {FormArray} from '../../model'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators'; import {AbstractFormGroupDirective} from '../abstract_form_group_directive'; import {ControlContainer} from '../control_container'; import {ReactiveErrors} from '../reactive_errors'; import {composeAsyncValidators, composeValidators, controlPath} from '../shared'; import {AsyncValidatorFn, ValidatorFn} from '../validators'; import {FormGroupDirective} from './form_group_directive'; export const formGroupNameProvider: any = { provide: ControlContainer, useExisting: forwardRef(() => FormGroupName) }; /** * @description * * Syncs a nested `FormGroup` to a DOM element. * * This directive can only be used with a parent `FormGroupDirective`. * * It accepts the string name of the nested `FormGroup` to link, and * looks for a `FormGroup` registered with that name in the parent * `FormGroup` instance you passed into `FormGroupDirective`. * * Use nested form groups to validate a sub-group of a * form separately from the rest or to group the values of certain * controls into their own nested object. * * @see [Reactive Forms Guide](guide/reactive-forms) * * @usageNotes * * ### Access the group by name * * The following example uses the {@link AbstractControl#get get} method to access the * associated `FormGroup` * * ```ts * this.form.get('name'); * ``` * * ### Access individual controls in the group * * The following example uses the {@link AbstractControl#get get} method to access * individual controls within the group using dot syntax. * * ```ts * this.form.get('name.first'); * ``` * * ### Register a nested `FormGroup`. * * The following example registers a nested *name* `FormGroup` within an existing `FormGroup`, * and provides methods to retrieve the nested `FormGroup` and individual controls. * * {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'} * * @ngModule ReactiveFormsModule * @publicApi */ @Directive({selector: '[formGroupName]', providers: [formGroupNameProvider]}) export class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy { /** * @description * Tracks the name of the `FormGroup` bound to the directive. The name corresponds * to a key in the parent `FormGroup` or `FormArray`. */ // TODO(issue/24571): remove '!'. @Input('formGroupName') name !: string; constructor( @Optional() @Host() @SkipSelf() parent: ControlContainer, @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { super(); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; } /** @internal */ _checkParentType(): void { if (_hasInvalidParent(this._parent)) { ReactiveErrors.groupParentException(); } } } export const formArrayNameProvider: any = { provide: ControlContainer, useExisting: forwardRef(() => FormArrayName) }; /** * @description * * Syncs a nested `FormArray` to a DOM element. * * This directive is designed to be used with a parent `FormGroupDirective` (selector: * `[formGroup]`). * * It accepts the string name of the nested `FormArray` you want to link, and * will look for a `FormArray` registered with that name in the parent * `FormGroup` instance you passed into `FormGroupDirective`. * * @see [Reactive Forms Guide](guide/reactive-forms) * @see `AbstractControl` * * @usageNotes * * ### Example * * {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'} * * @ngModule ReactiveFormsModule * @publicApi */ @Directive({selector: '[formArrayName]', providers: [formArrayNameProvider]}) export class FormArrayName extends ControlContainer implements OnInit, OnDestroy { /** @internal */ _parent: ControlContainer; /** @internal */ _validators: any[]; /** @internal */ _asyncValidators: any[]; /** * @description * Tracks the name of the `FormArray` bound to the directive. The name corresponds * to a key in the parent `FormGroup` or `FormArray`. */ // TODO(issue/24571): remove '!'. @Input('formArrayName') name !: string; constructor( @Optional() @Host() @SkipSelf() parent: ControlContainer, @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { super(); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; } /** * @description * A lifecycle method called when the directive's inputs are initialized. For internal use only. * * @throws If the directive does not have a valid parent. */ ngOnInit(): void { this._checkParentType(); this.formDirective !.addFormArray(this); } /** * @description * A lifecycle method called before the directive's instance is destroyed. For internal use only. */ ngOnDestroy(): void { if (this.formDirective) { this.formDirective.removeFormArray(this); } } /** * @description * The `FormArray` bound to this directive. */ get control(): FormArray { return this.formDirective !.getFormArray(this); } /** * @description * The top-level directive for this group if present, otherwise null. */ get formDirective(): FormGroupDirective|null { return this._parent ? <FormGroupDirective>this._parent.formDirective : null; } /** * @description * Returns an array that represents the path from the top-level form to this control. * Each index is the string name of the control on that level. */ get path(): string[] { return controlPath(this.name, this._parent); } /** * @description * Synchronous validator function composed of all the synchronous validators registered with this * directive. */ get validator(): ValidatorFn|null { return composeValidators(this._validators); } /** * @description * Async validator function composed of all the async validators registered with this directive. */ get asyncValidator(): AsyncValidatorFn|null { return composeAsyncValidators(this._asyncValidators); } private _checkParentType(): void { if (_hasInvalidParent(this._parent)) { ReactiveErrors.arrayParentException(); } } } function _hasInvalidParent(parent: ControlContainer): boolean { return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) && !(parent instanceof FormArrayName); }
packages/forms/src/directives/reactive_directives/form_group_name.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017695422866381705, 0.0001705409522401169, 0.00016387732466682792, 0.00017116662638727576, 0.000003195261115251924 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {HttpClient} from '@angular/common/http';\n", "import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/http/testing/test/request_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Injector} from '../di/injector'; import {Type} from '../interface/type'; import {stringify} from '../util/stringify'; import {ComponentFactory, ComponentRef} from './component_factory'; import {NgModuleRef} from './ng_module_factory'; export function noComponentFactoryError(component: Function) { const error = Error( `No component factory found for ${stringify(component)}. Did you add it to @NgModule.entryComponents?`); (error as any)[ERROR_COMPONENT] = component; return error; } const ERROR_COMPONENT = 'ngComponent'; export function getComponent(error: Error): Type<any> { return (error as any)[ERROR_COMPONENT]; } class _NullComponentFactoryResolver implements ComponentFactoryResolver { resolveComponentFactory<T>(component: {new (...args: any[]): T}): ComponentFactory<T> { throw noComponentFactoryError(component); } } /** * @publicApi */ export abstract class ComponentFactoryResolver { static NULL: ComponentFactoryResolver = new _NullComponentFactoryResolver(); abstract resolveComponentFactory<T>(component: Type<T>): ComponentFactory<T>; } export class CodegenComponentFactoryResolver implements ComponentFactoryResolver { private _factories = new Map<any, ComponentFactory<any>>(); constructor( factories: ComponentFactory<any>[], private _parent: ComponentFactoryResolver, private _ngModule: NgModuleRef<any>) { for (let i = 0; i < factories.length; i++) { const factory = factories[i]; this._factories.set(factory.componentType, factory); } } resolveComponentFactory<T>(component: {new (...args: any[]): T}): ComponentFactory<T> { let factory = this._factories.get(component); if (!factory && this._parent) { factory = this._parent.resolveComponentFactory(component); } if (!factory) { throw noComponentFactoryError(component); } return new ComponentFactoryBoundToModule(factory, this._ngModule); } } export class ComponentFactoryBoundToModule<C> extends ComponentFactory<C> { readonly selector: string; readonly componentType: Type<any>; readonly ngContentSelectors: string[]; readonly inputs: {propName: string, templateName: string}[]; readonly outputs: {propName: string, templateName: string}[]; constructor(private factory: ComponentFactory<C>, private ngModule: NgModuleRef<any>) { super(); this.selector = factory.selector; this.componentType = factory.componentType; this.ngContentSelectors = factory.ngContentSelectors; this.inputs = factory.inputs; this.outputs = factory.outputs; } create( injector: Injector, projectableNodes?: any[][], rootSelectorOrNode?: string|any, ngModule?: NgModuleRef<any>): ComponentRef<C> { return this.factory.create( injector, projectableNodes, rootSelectorOrNode, ngModule || this.ngModule); } }
packages/core/src/linker/component_factory_resolver.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017938713426701725, 0.00017089772154577076, 0.00016338538262061775, 0.00017045171989593655, 0.000004265291408955818 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {HttpClient} from '@angular/common/http';\n", "import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend';\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/http/testing/test/request_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
<h2>CRISIS CENTER</h2> <router-outlet></router-outlet>
aio/content/examples/router/src/app/crisis-center/crisis-center/crisis-center.component.html
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00016580524970777333, 0.00016580524970777333, 0.00016580524970777333, 0.00016580524970777333, 0 ]
{ "id": 1, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Subject, Subscription} from 'rxjs';\n", "\n", "/**\n", " * Use in directives and components to emit custom events synchronously\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "/// <reference types=\"rxjs\" />\n", "\n" ], "file_path": "packages/core/src/event_emitter.ts", "type": "add", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /// <reference types="rxjs" /> import {EventEmitter} from '@angular/core'; import {defineComponent, defineDirective} from '../../src/render3/index'; import {bind, container, containerRefreshEnd, containerRefreshStart, element, elementEnd, elementProperty, elementStart, embeddedViewEnd, embeddedViewStart, listener, text} from '../../src/render3/instructions'; import {RenderFlags} from '../../src/render3/interfaces/definition'; import {containerEl, renderToHtml} from './render_util'; describe('outputs', () => { let buttonToggle: ButtonToggle; let destroyComp: DestroyComp; let buttonDir: MyButton; class ButtonToggle { change = new EventEmitter(); resetStream = new EventEmitter(); static ngComponentDef = defineComponent({ type: ButtonToggle, selectors: [['button-toggle']], template: function(rf: RenderFlags, ctx: any) {}, consts: 0, vars: 0, factory: () => buttonToggle = new ButtonToggle(), outputs: {change: 'change', resetStream: 'reset'} }); } let otherDir: OtherDir; class OtherDir { changeStream = new EventEmitter(); static ngDirectiveDef = defineDirective({ type: OtherDir, selectors: [['', 'otherDir', '']], factory: () => otherDir = new OtherDir, outputs: {changeStream: 'change'} }); } class DestroyComp { events: string[] = []; ngOnDestroy() { this.events.push('destroy'); } static ngComponentDef = defineComponent({ type: DestroyComp, selectors: [['destroy-comp']], consts: 0, vars: 0, template: function(rf: RenderFlags, ctx: any) {}, factory: () => destroyComp = new DestroyComp() }); } /** <button myButton (click)="onClick()">Click me</button> */ class MyButton { click = new EventEmitter(); static ngDirectiveDef = defineDirective({ type: MyButton, selectors: [['', 'myButton', '']], factory: () => buttonDir = new MyButton, outputs: {click: 'click'} }); } const deps = [ButtonToggle, OtherDir, DestroyComp, MyButton]; it('should call component output function when event is emitted', () => { /** <button-toggle (change)="onChange()"></button-toggle> */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button-toggle'); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); } } let counter = 0; const ctx = {onChange: () => counter++}; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); buttonToggle !.change.next(); expect(counter).toEqual(2); }); it('should support more than 1 output function on the same node', () => { /** <button-toggle (change)="onChange()" (reset)="onReset()"></button-toggle> */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button-toggle'); { listener('change', function() { return ctx.onChange(); }); listener('reset', function() { return ctx.onReset(); }); } elementEnd(); } } let counter = 0; let resetCounter = 0; const ctx = {onChange: () => counter++, onReset: () => resetCounter++}; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); buttonToggle !.resetStream.next(); expect(resetCounter).toEqual(1); }); it('should eval component output expression when event is emitted', () => { /** <button-toggle (change)="counter++"></button-toggle> */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button-toggle'); { listener('change', function() { return ctx.counter++; }); } elementEnd(); } } const ctx = {counter: 0}; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(ctx.counter).toEqual(1); buttonToggle !.change.next(); expect(ctx.counter).toEqual(2); }); it('should unsubscribe from output when view is destroyed', () => { /** * % if (condition) { * <button-toggle (change)="onChange()"></button-toggle> * % } */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); { if (ctx.condition) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { elementStart(0, 'button-toggle'); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); } embeddedViewEnd(); } } containerRefreshEnd(); } } let counter = 0; const ctx = {onChange: () => counter++, condition: true}; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); ctx.condition = false; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); }); it('should unsubscribe from output in nested view', () => { /** * % if (condition) { * % if (condition2) { * <button-toggle (change)="onChange()"></button-toggle> * % } * % } */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); { if (ctx.condition) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { container(0); } containerRefreshStart(0); { if (ctx.condition2) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { elementStart(0, 'button-toggle'); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); } embeddedViewEnd(); } } containerRefreshEnd(); embeddedViewEnd(); } } containerRefreshEnd(); } } let counter = 0; const ctx = {onChange: () => counter++, condition: true, condition2: true}; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); ctx.condition = false; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); }); it('should work properly when view also has listeners and destroys', () => { /** * % if (condition) { * <button (click)="onClick()">Click me</button> * <button-toggle (change)="onChange()"></button-toggle> * <destroy-comp></destroy-comp> * % } */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); { if (ctx.condition) { let rf1 = embeddedViewStart(0, 4, 0); if (rf1 & RenderFlags.Create) { elementStart(0, 'button'); { listener('click', function() { return ctx.onClick(); }); text(1, 'Click me'); } elementEnd(); elementStart(2, 'button-toggle'); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); element(3, 'destroy-comp'); } embeddedViewEnd(); } } containerRefreshEnd(); } } let clickCounter = 0; let changeCounter = 0; const ctx = {condition: true, onChange: () => changeCounter++, onClick: () => clickCounter++}; renderToHtml(Template, ctx, 1, 0, deps); buttonToggle !.change.next(); expect(changeCounter).toEqual(1); expect(clickCounter).toEqual(0); const button = containerEl.querySelector('button'); button !.click(); expect(changeCounter).toEqual(1); expect(clickCounter).toEqual(1); ctx.condition = false; renderToHtml(Template, ctx, 1, 0, deps); expect(destroyComp !.events).toEqual(['destroy']); buttonToggle !.change.next(); button !.click(); expect(changeCounter).toEqual(1); expect(clickCounter).toEqual(1); }); it('should fire event listeners along with outputs if they match', () => { function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['myButton', '']); { listener('click', function() { return ctx.onClick(); }); } elementEnd(); } } let counter = 0; renderToHtml(Template, {counter, onClick: () => counter++}, 1, 0, deps); // To match current Angular behavior, the click listener is still // set up in addition to any matching outputs. const button = containerEl.querySelector('button') !; button.click(); expect(counter).toEqual(1); buttonDir !.click.next(); expect(counter).toEqual(2); }); it('should work with two outputs of the same name', () => { /** <button-toggle (change)="onChange()" otherDir></button-toggle> */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button-toggle', ['otherDir', '']); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); } } let counter = 0; renderToHtml(Template, {counter, onChange: () => counter++}, 1, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); otherDir !.changeStream.next(); expect(counter).toEqual(2); }); it('should work with an input and output of the same name', () => { let otherDir: OtherChangeDir; class OtherChangeDir { // TODO(issue/24571): remove '!'. change !: boolean; static ngDirectiveDef = defineDirective({ type: OtherChangeDir, selectors: [['', 'otherChangeDir', '']], factory: () => otherDir = new OtherChangeDir, inputs: {change: 'change'} }); } /** <button-toggle (change)="onChange()" otherChangeDir [change]="change"></button-toggle> */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button-toggle', ['otherChangeDir', '']); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'change', bind(ctx.change)); } } let counter = 0; const deps = [ButtonToggle, OtherChangeDir]; renderToHtml(Template, {counter, onChange: () => counter++, change: true}, 1, 1, deps); expect(otherDir !.change).toEqual(true); renderToHtml(Template, {counter, onChange: () => counter++, change: false}, 1, 1, deps); expect(otherDir !.change).toEqual(false); buttonToggle !.change.next(); expect(counter).toEqual(1); }); it('should work with outputs at same index in if block', () => { /** * <button (click)="onClick()">Click me</button> // outputs: null * % if (condition) { * <button-toggle (change)="onChange()"></button-toggle> // outputs: {change: [0, 'change']} * % } else { * <div otherDir (change)="onChange()"></div> // outputs: {change: [0, * 'changeStream']} * % } */ function Template(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button'); { listener('click', function() { return ctx.onClick(); }); text(1, 'Click me'); } elementEnd(); container(2); } if (rf & RenderFlags.Update) { containerRefreshStart(2); { if (ctx.condition) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { elementStart(0, 'button-toggle'); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); } embeddedViewEnd(); } else { if (embeddedViewStart(1, 1, 0)) { elementStart(0, 'div', ['otherDir', '']); { listener('change', function() { return ctx.onChange(); }); } elementEnd(); } embeddedViewEnd(); } } containerRefreshEnd(); } } let counter = 0; const ctx = {condition: true, onChange: () => counter++, onClick: () => {}}; renderToHtml(Template, ctx, 3, 0, deps); buttonToggle !.change.next(); expect(counter).toEqual(1); ctx.condition = false; renderToHtml(Template, ctx, 3, 0, deps); expect(counter).toEqual(1); otherDir !.changeStream.next(); expect(counter).toEqual(2); }); });
packages/core/test/render3/outputs_spec.ts
1
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017106971063185483, 0.00016713739023543894, 0.00016351178055629134, 0.00016681429406162351, 0.0000016368765045626787 ]
{ "id": 1, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Subject, Subscription} from 'rxjs';\n", "\n", "/**\n", " * Use in directives and components to emit custom events synchronously\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "/// <reference types=\"rxjs\" />\n", "\n" ], "file_path": "packages/core/src/event_emitter.ts", "type": "add", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'es-CU', [['a. m.', 'p. m.'], ['a.m.', 'p.m.'], u], [['a.m.', 'p.m.'], u, u], [ ['d', 'l', 'm', 'm', 'j', 'v', 's'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'], ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'], ['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA'] ], [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'], ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'], ['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA'] ], [ ['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.' ], [ 'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre' ] ], u, [['a. C.', 'd. C.'], u, ['antes de Cristo', 'después de Cristo']], 1, [6, 0], ['d/M/yy', 'd MMM y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, '{1}, {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '¤#,##0.00', '#E0'], '$', 'peso cubano', { 'AUD': [u, '$'], 'BRL': [u, 'R$'], 'CAD': [u, '$'], 'CNY': [u, '¥'], 'CUP': ['$'], 'ESP': ['₧'], 'EUR': [u, '€'], 'FKP': [u, 'FK£'], 'GBP': [u, '£'], 'HKD': [u, '$'], 'ILS': [u, '₪'], 'INR': [u, '₹'], 'JPY': [u, '¥'], 'KRW': [u, '₩'], 'MXN': [u, '$'], 'NZD': [u, '$'], 'RON': [u, 'L'], 'SSP': [u, 'SD£'], 'SYP': [u, 'S£'], 'TWD': [u, 'NT$'], 'USD': ['US$', '$'], 'VEF': [u, 'BsF'], 'VND': [u, '₫'], 'XAF': [], 'XCD': [u, '$'], 'XOF': [] }, plural ];
packages/common/locales/es-CU.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017036811914294958, 0.0001686624891590327, 0.00016464227519463748, 0.00016956523177213967, 0.0000018275721913596499 ]
{ "id": 1, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Subject, Subscription} from 'rxjs';\n", "\n", "/**\n", " * Use in directives and components to emit custom events synchronously\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "/// <reference types=\"rxjs\" />\n", "\n" ], "file_path": "packages/core/src/event_emitter.ts", "type": "add", "edit_start_line_idx": 8 }
.content { img { &.right { clear: both; float: right; margin-left: 20px; margin-bottom: 20px; } &.left { clear: both; float: left; margin-right: 20px; margin-bottom: 20px; } @media (max-width: 1300px) { max-width: 100%; height: auto; } @media (max-width: 600px) { float: none !important; &.right { margin-left: 0; } &.left { margin-right: 0; } } } figure { border-radius: 4px; background: $white; padding: 20px; display: inline-block; box-shadow: 2px 2px 5px 0 rgba(0, 0, 0, .2); margin: 0 0 14px 0; img { border-radius: 4px; } } }
aio/src/styles/2-modules/_images.scss
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017199068679474294, 0.00016966550901997834, 0.00016869841783773154, 0.00016926671378314495, 0.0000012109990166209172 ]
{ "id": 1, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Subject, Subscription} from 'rxjs';\n", "\n", "/**\n", " * Use in directives and components to emit custom events synchronously\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "/// <reference types=\"rxjs\" />\n", "\n" ], "file_path": "packages/core/src/event_emitter.ts", "type": "add", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [];
packages/common/locales/extra/kab.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00016824847261887044, 0.00016644537390675396, 0.00016464227519463748, 0.00016644537390675396, 0.0000018030987121164799 ]
{ "id": 3, "code_window": [ " *\n", " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {EventEmitter} from '@angular/core';\n", "\n", "import {defineComponent, defineDirective} from '../../src/render3/index';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/properties_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /// <reference types="rxjs" /> import {EventEmitter} from '@angular/core'; import {defineComponent, defineDirective} from '../../src/render3/index'; import {bind, container, containerRefreshEnd, containerRefreshStart, element, elementEnd, elementProperty, elementStart, embeddedViewEnd, embeddedViewStart, interpolation1, listener, load, reference, text, textBinding} from '../../src/render3/instructions'; import {RenderFlags} from '../../src/render3/interfaces/definition'; import {NO_CHANGE} from '../../src/render3/tokens'; import {ComponentFixture, createComponent, renderToHtml} from './render_util'; describe('elementProperty', () => { it('should support bindings to properties', () => { const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'span'); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id)); } }, 1, 1); const fixture = new ComponentFixture(App); fixture.component.id = 'testId'; fixture.update(); expect(fixture.html).toEqual('<span id="testId"></span>'); fixture.component.id = 'otherId'; fixture.update(); expect(fixture.html).toEqual('<span id="otherId"></span>'); }); it('should support creation time bindings to properties', () => { function expensive(ctx: string): any { if (ctx === 'cheapId') { return ctx; } else { throw 'Too expensive!'; } } function Template(rf: RenderFlags, ctx: string) { if (rf & RenderFlags.Create) { element(0, 'span'); elementProperty(0, 'id', expensive(ctx)); } } expect(renderToHtml(Template, 'cheapId', 1)).toEqual('<span id="cheapId"></span>'); expect(renderToHtml(Template, 'expensiveId', 1)).toEqual('<span id="cheapId"></span>'); }); it('should support interpolation for properties', () => { const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'span'); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', interpolation1('_', ctx.id, '_')); } }, 1, 1); const fixture = new ComponentFixture(App); fixture.component.id = 'testId'; fixture.update(); expect(fixture.html).toEqual('<span id="_testId_"></span>'); fixture.component.id = 'otherId'; fixture.update(); expect(fixture.html).toEqual('<span id="_otherId_"></span>'); }); describe('input properties', () => { let button: MyButton; let otherDir: OtherDir; let otherDisabledDir: OtherDisabledDir; let idDir: IdDir; class MyButton { // TODO(issue/24571): remove '!'. disabled !: boolean; static ngDirectiveDef = defineDirective({ type: MyButton, selectors: [['', 'myButton', '']], factory: () => button = new MyButton(), inputs: {disabled: 'disabled'} }); } class OtherDir { // TODO(issue/24571): remove '!'. id !: number; clickStream = new EventEmitter(); static ngDirectiveDef = defineDirective({ type: OtherDir, selectors: [['', 'otherDir', '']], factory: () => otherDir = new OtherDir(), inputs: {id: 'id'}, outputs: {clickStream: 'click'} }); } class OtherDisabledDir { // TODO(issue/24571): remove '!'. disabled !: boolean; static ngDirectiveDef = defineDirective({ type: OtherDisabledDir, selectors: [['', 'otherDisabledDir', '']], factory: () => otherDisabledDir = new OtherDisabledDir(), inputs: {disabled: 'disabled'} }); } class IdDir { // TODO(issue/24571): remove '!'. idNumber !: string; static ngDirectiveDef = defineDirective({ type: IdDir, selectors: [['', 'idDir', '']], factory: () => idDir = new IdDir(), inputs: {idNumber: 'id'} }); } const deps = [MyButton, OtherDir, OtherDisabledDir, IdDir]; it('should check input properties before setting (directives)', () => { /** <button myButton otherDir [id]="id" [disabled]="isDisabled">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['otherDir', '', 'myButton', '']); { text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'disabled', bind(ctx.isDisabled)); elementProperty(0, 'id', bind(ctx.id)); } }, 2, 2, deps); const fixture = new ComponentFixture(App); fixture.component.isDisabled = true; fixture.component.id = 0; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdir="">Click me</button>`); expect(button !.disabled).toEqual(true); expect(otherDir !.id).toEqual(0); fixture.component.isDisabled = false; fixture.component.id = 1; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdir="">Click me</button>`); expect(button !.disabled).toEqual(false); expect(otherDir !.id).toEqual(1); }); it('should support mixed element properties and input properties', () => { /** <button myButton [id]="id" [disabled]="isDisabled">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['myButton', '']); { text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'disabled', bind(ctx.isDisabled)); elementProperty(0, 'id', bind(ctx.id)); } }, 2, 2, deps); const fixture = new ComponentFixture(App); fixture.component.isDisabled = true; fixture.component.id = 0; fixture.update(); expect(fixture.html).toEqual(`<button id="0" mybutton="">Click me</button>`); expect(button !.disabled).toEqual(true); fixture.component.isDisabled = false; fixture.component.id = 1; fixture.update(); expect(fixture.html).toEqual(`<button id="1" mybutton="">Click me</button>`); expect(button !.disabled).toEqual(false); }); it('should check that property is not an input property before setting (component)', () => { let comp: Comp; class Comp { // TODO(issue/24571): remove '!'. id !: number; static ngComponentDef = defineComponent({ type: Comp, selectors: [['comp']], consts: 0, vars: 0, template: function(rf: RenderFlags, ctx: any) {}, factory: () => comp = new Comp(), inputs: {id: 'id'} }); } /** <comp [id]="id"></comp> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'comp'); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id)); } }, 1, 1, [Comp]); const fixture = new ComponentFixture(App); fixture.component.id = 1; fixture.update(); expect(fixture.html).toEqual(`<comp></comp>`); expect(comp !.id).toEqual(1); fixture.component.id = 2; fixture.update(); expect(fixture.html).toEqual(`<comp></comp>`); expect(comp !.id).toEqual(2); }); it('should support two input properties with the same name', () => { /** <button myButton otherDisabledDir [disabled]="isDisabled">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['myButton', '', 'otherDisabledDir', '']); { text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'disabled', bind(ctx.isDisabled)); } }, 2, 1, deps); const fixture = new ComponentFixture(App); fixture.component.isDisabled = true; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdisableddir="">Click me</button>`); expect(button !.disabled).toEqual(true); expect(otherDisabledDir !.disabled).toEqual(true); fixture.component.isDisabled = false; fixture.update(); expect(fixture.html).toEqual(`<button mybutton="" otherdisableddir="">Click me</button>`); expect(button !.disabled).toEqual(false); expect(otherDisabledDir !.disabled).toEqual(false); }); it('should set input property if there is an output first', () => { /** <button otherDir [id]="id" (click)="onClick()">Click me</button> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['otherDir', '']); { listener('click', () => ctx.onClick()); text(1, 'Click me'); } elementEnd(); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id)); } }, 2, 1, deps); const fixture = new ComponentFixture(App); let counter = 0; fixture.component.id = 1; fixture.component.onClick = () => counter++; fixture.update(); expect(fixture.html).toEqual(`<button otherdir="">Click me</button>`); expect(otherDir !.id).toEqual(1); otherDir !.clickStream.next(); expect(counter).toEqual(1); fixture.component.id = 2; fixture.update(); fixture.html; expect(otherDir !.id).toEqual(2); }); it('should support unrelated element properties at same index in if-else block', () => { /** * <button idDir [id]="id1">Click me</button> // inputs: {'id': [0, 'idNumber']} * % if (condition) { * <button [id]="id2">Click me too</button> // inputs: null * % } else { * <button otherDir [id]="id3">Click me too</button> // inputs: {'id': [0, 'id']} * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'button', ['idDir', '']); { text(1, 'Click me'); } elementEnd(); container(2); } if (rf & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id1)); containerRefreshStart(2); { if (ctx.condition) { let rf0 = embeddedViewStart(0, 2, 1); if (rf0 & RenderFlags.Create) { elementStart(0, 'button'); { text(1, 'Click me too'); } elementEnd(); } if (rf0 & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id2)); } embeddedViewEnd(); } else { let rf1 = embeddedViewStart(1, 2, 1); if (rf1 & RenderFlags.Create) { elementStart(0, 'button', ['otherDir', '']); { text(1, 'Click me too'); } elementEnd(); } if (rf1 & RenderFlags.Update) { elementProperty(0, 'id', bind(ctx.id3)); } embeddedViewEnd(); } } containerRefreshEnd(); } }, 3, 1, deps); const fixture = new ComponentFixture(App); fixture.component.condition = true; fixture.component.id1 = 'one'; fixture.component.id2 = 'two'; fixture.component.id3 = 3; fixture.update(); expect(fixture.html) .toEqual(`<button iddir="">Click me</button><button id="two">Click me too</button>`); expect(idDir !.idNumber).toEqual('one'); fixture.component.condition = false; fixture.component.id1 = 'four'; fixture.update(); expect(fixture.html) .toEqual(`<button iddir="">Click me</button><button otherdir="">Click me too</button>`); expect(idDir !.idNumber).toEqual('four'); expect(otherDir !.id).toEqual(3); }); }); describe('attributes and input properties', () => { let myDir: MyDir; class MyDir { // TODO(issue/24571): remove '!'. role !: string; // TODO(issue/24571): remove '!'. direction !: string; changeStream = new EventEmitter(); static ngDirectiveDef = defineDirective({ type: MyDir, selectors: [['', 'myDir', '']], factory: () => myDir = new MyDir(), inputs: {role: 'role', direction: 'dir'}, outputs: {changeStream: 'change'}, exportAs: ['myDir'] }); } let dirB: MyDirB; class MyDirB { // TODO(issue/24571): remove '!'. roleB !: string; static ngDirectiveDef = defineDirective({ type: MyDirB, selectors: [['', 'myDirB', '']], factory: () => dirB = new MyDirB(), inputs: {roleB: 'role'} }); } const deps = [MyDir, MyDirB]; it('should set input property based on attribute if existing', () => { /** <div role="button" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', '']); } }, 1, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html).toEqual(`<div mydir="" role="button"></div>`); expect(myDir !.role).toEqual('button'); }); it('should set input property and attribute if both defined', () => { /** <div role="button" [role]="role" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', '']); } if (rf & RenderFlags.Update) { elementProperty(0, 'role', bind(ctx.role)); } }, 1, 1, deps); const fixture = new ComponentFixture(App); fixture.component.role = 'listbox'; fixture.update(); expect(fixture.html).toEqual(`<div mydir="" role="button"></div>`); expect(myDir !.role).toEqual('listbox'); fixture.component.role = 'button'; fixture.update(); expect(myDir !.role).toEqual('button'); }); it('should set two directive input properties based on same attribute', () => { /** <div role="button" myDir myDirB></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', '', 'myDirB', '']); } }, 1, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html).toEqual(`<div mydir="" mydirb="" role="button"></div>`); expect(myDir !.role).toEqual('button'); expect(dirB !.roleB).toEqual('button'); }); it('should process two attributes on same directive', () => { /** <div role="button" dir="rtl" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'dir', 'rtl', 'myDir', '']); } }, 1, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html).toEqual(`<div dir="rtl" mydir="" role="button"></div>`); expect(myDir !.role).toEqual('button'); expect(myDir !.direction).toEqual('rtl'); }); it('should process attributes and outputs properly together', () => { /** <div role="button" (change)="onChange()" myDir></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { elementStart(0, 'div', ['role', 'button', 'myDir', '']); { listener('change', () => ctx.onChange()); } elementEnd(); } }, 1, 0, deps); const fixture = new ComponentFixture(App); let counter = 0; fixture.component.onChange = () => counter++; fixture.update(); expect(fixture.html).toEqual(`<div mydir="" role="button"></div>`); expect(myDir !.role).toEqual('button'); myDir !.changeStream.next(); expect(counter).toEqual(1); }); it('should process attributes properly for directives with later indices', () => { /** * <div role="button" dir="rtl" myDir></div> * <div role="listbox" myDirB></div> */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'dir', 'rtl', 'myDir', '']); element(1, 'div', ['role', 'listbox', 'myDirB', '']); } }, 2, 0, deps); const fixture = new ComponentFixture(App); expect(fixture.html) .toEqual( `<div dir="rtl" mydir="" role="button"></div><div mydirb="" role="listbox"></div>`); expect(myDir !.role).toEqual('button'); expect(myDir !.direction).toEqual('rtl'); expect(dirB !.roleB).toEqual('listbox'); }); it('should support attributes at same index inside an if-else block', () => { /** * <div role="listbox" myDir></div> // initialInputs: [['role', 'listbox']] * * % if (condition) { * <div role="button" myDirB></div> // initialInputs: [['role', 'button']] * % } else { * <div role="menu"></div> // initialInputs: [null] * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'listbox', 'myDir', '']); container(1); } if (rf & RenderFlags.Update) { containerRefreshStart(1); { if (ctx.condition) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDirB', '']); } embeddedViewEnd(); } else { let rf2 = embeddedViewStart(1, 1, 0); if (rf2 & RenderFlags.Create) { element(0, 'div', ['role', 'menu']); } embeddedViewEnd(); } } containerRefreshEnd(); } }, 2, 0, deps); const fixture = new ComponentFixture(App); fixture.component.condition = true; fixture.update(); expect(fixture.html) .toEqual(`<div mydir="" role="listbox"></div><div mydirb="" role="button"></div>`); expect(myDir !.role).toEqual('listbox'); expect(dirB !.roleB).toEqual('button'); expect((dirB !as any).role).toBeUndefined(); fixture.component.condition = false; fixture.update(); expect(fixture.html).toEqual(`<div mydir="" role="listbox"></div><div role="menu"></div>`); expect(myDir !.role).toEqual('listbox'); }); it('should process attributes properly inside a for loop', () => { class Comp { static ngComponentDef = defineComponent({ type: Comp, selectors: [['comp']], consts: 3, vars: 1, /** <div role="button" dir #dir="myDir"></div> {{ dir.role }} */ template: function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { element(0, 'div', ['role', 'button', 'myDir', ''], ['dir', 'myDir']); text(2); } if (rf & RenderFlags.Update) { const tmp = reference(1) as any; textBinding(2, bind(tmp.role)); } }, factory: () => new Comp(), directives: () => [MyDir] }); } /** * % for (let i = 0; i < 3; i++) { * <comp></comp> * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); { for (let i = 0; i < 2; i++) { let rf1 = embeddedViewStart(0, 1, 0); if (rf1 & RenderFlags.Create) { element(0, 'comp'); } embeddedViewEnd(); } } containerRefreshEnd(); } }, 1, 0, [Comp]); const fixture = new ComponentFixture(App); expect(fixture.html) .toEqual( `<comp><div mydir="" role="button"></div>button</comp><comp><div mydir="" role="button"></div>button</comp>`); }); }); });
packages/core/test/render3/properties_spec.ts
1
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.0002389892761129886, 0.0001724526664474979, 0.00016517423500772566, 0.00017078562814276665, 0.00000971272402239265 ]
{ "id": 3, "code_window": [ " *\n", " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {EventEmitter} from '@angular/core';\n", "\n", "import {defineComponent, defineDirective} from '../../src/render3/index';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/properties_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ConstantPool, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, InterpolationConfig, LexerRange, R3ComponentMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr, compileComponentFromMetadata, makeBindingParser, parseTemplate} from '@angular/compiler'; import * as path from 'path'; import * as ts from 'typescript'; import {CycleAnalyzer} from '../../cycles'; import {ErrorCode, FatalDiagnosticError} from '../../diagnostics'; import {ModuleResolver, Reference} from '../../imports'; import {EnumValue, PartialEvaluator} from '../../partial_evaluator'; import {Decorator, ReflectionHost, filterToMembersWithDecorator, reflectObjectLiteral} from '../../reflection'; import {AnalysisOutput, CompileResult, DecoratorHandler, DetectResult, HandlerPrecedence} from '../../transform'; import {TypeCheckContext} from '../../typecheck'; import {tsSourceMapBug29300Fixed} from '../../util/src/ts_source_map_bug_29300'; import {ResourceLoader} from './api'; import {extractDirectiveMetadata, extractQueriesFromDecorator, parseFieldArrayValue, queriesFromFields} from './directive'; import {generateSetClassMetadataCall} from './metadata'; import {ScopeDirective, SelectorScopeRegistry} from './selector_scope'; import {extractDirectiveGuards, isAngularCore, isAngularCoreReference, unwrapExpression} from './util'; const EMPTY_MAP = new Map<string, Expression>(); const EMPTY_ARRAY: any[] = []; export interface ComponentHandlerData { meta: R3ComponentMetadata; parsedTemplate: TmplAstNode[]; metadataStmt: Statement|null; } /** * `DecoratorHandler` which handles the `@Component` annotation. */ export class ComponentDecoratorHandler implements DecoratorHandler<ComponentHandlerData, Decorator> { constructor( private reflector: ReflectionHost, private evaluator: PartialEvaluator, private scopeRegistry: SelectorScopeRegistry, private isCore: boolean, private resourceLoader: ResourceLoader, private rootDirs: string[], private defaultPreserveWhitespaces: boolean, private i18nUseExternalIds: boolean, private moduleResolver: ModuleResolver, private cycleAnalyzer: CycleAnalyzer) {} private literalCache = new Map<Decorator, ts.ObjectLiteralExpression>(); private elementSchemaRegistry = new DomElementSchemaRegistry(); readonly precedence = HandlerPrecedence.PRIMARY; detect(node: ts.Declaration, decorators: Decorator[]|null): DetectResult<Decorator>|undefined { if (!decorators) { return undefined; } const decorator = decorators.find( decorator => decorator.name === 'Component' && (this.isCore || isAngularCore(decorator))); if (decorator !== undefined) { return { trigger: decorator.node, metadata: decorator, }; } else { return undefined; } } preanalyze(node: ts.ClassDeclaration, decorator: Decorator): Promise<void>|undefined { if (!this.resourceLoader.canPreload) { return undefined; } const meta = this._resolveLiteral(decorator); const component = reflectObjectLiteral(meta); const promises: Promise<void>[] = []; const containingFile = node.getSourceFile().fileName; if (component.has('templateUrl')) { const templateUrlExpr = component.get('templateUrl') !; const templateUrl = this.evaluator.evaluate(templateUrlExpr); if (typeof templateUrl !== 'string') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, templateUrlExpr, 'templateUrl must be a string'); } const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile); const promise = this.resourceLoader.preload(resourceUrl); if (promise !== undefined) { promises.push(promise); } } const styleUrls = this._extractStyleUrls(component); if (styleUrls !== null) { for (const styleUrl of styleUrls) { const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile); const promise = this.resourceLoader.preload(resourceUrl); if (promise !== undefined) { promises.push(promise); } } } if (promises.length !== 0) { return Promise.all(promises).then(() => undefined); } else { return undefined; } } analyze(node: ts.ClassDeclaration, decorator: Decorator): AnalysisOutput<ComponentHandlerData> { const containingFile = node.getSourceFile().fileName; const meta = this._resolveLiteral(decorator); this.literalCache.delete(decorator); // @Component inherits @Directive, so begin by extracting the @Directive metadata and building // on it. const directiveResult = extractDirectiveMetadata( node, decorator, this.reflector, this.evaluator, this.isCore, this.elementSchemaRegistry.getDefaultComponentElementName()); if (directiveResult === undefined) { // `extractDirectiveMetadata` returns undefined when the @Directive has `jit: true`. In this // case, compilation of the decorator is skipped. Returning an empty object signifies // that no analysis was produced. return {}; } // Next, read the `@Component`-specific fields. const {decoratedElements, decorator: component, metadata} = directiveResult; // Go through the root directories for this project, and select the one with the smallest // relative path representation. const filePath = node.getSourceFile().fileName; const relativeContextFilePath = this.rootDirs.reduce<string|undefined>((previous, rootDir) => { const candidate = path.posix.relative(rootDir, filePath); if (previous === undefined || candidate.length < previous.length) { return candidate; } else { return previous; } }, undefined) !; let templateStr: string|null = null; let templateUrl: string = ''; let templateRange: LexerRange|undefined; let escapedString: boolean = false; if (component.has('templateUrl')) { const templateUrlExpr = component.get('templateUrl') !; const evalTemplateUrl = this.evaluator.evaluate(templateUrlExpr); if (typeof evalTemplateUrl !== 'string') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, templateUrlExpr, 'templateUrl must be a string'); } templateUrl = this.resourceLoader.resolve(evalTemplateUrl, containingFile); templateStr = this.resourceLoader.load(templateUrl); if (!tsSourceMapBug29300Fixed()) { // By removing the template URL we are telling the translator not to try to // map the external source file to the generated code, since the version // of TS that is running does not support it. templateUrl = ''; } } else if (component.has('template')) { const templateExpr = component.get('template') !; // We only support SourceMaps for inline templates that are simple string literals. if (ts.isStringLiteral(templateExpr) || ts.isNoSubstitutionTemplateLiteral(templateExpr)) { // the start and end of the `templateExpr` node includes the quotation marks, which we must // strip templateRange = getTemplateRange(templateExpr); templateStr = templateExpr.getSourceFile().text; templateUrl = relativeContextFilePath; escapedString = true; } else { const resolvedTemplate = this.evaluator.evaluate(templateExpr); if (typeof resolvedTemplate !== 'string') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, templateExpr, 'template must be a string'); } templateStr = resolvedTemplate; } } else { throw new FatalDiagnosticError( ErrorCode.COMPONENT_MISSING_TEMPLATE, decorator.node, 'component is missing a template'); } let preserveWhitespaces: boolean = this.defaultPreserveWhitespaces; if (component.has('preserveWhitespaces')) { const expr = component.get('preserveWhitespaces') !; const value = this.evaluator.evaluate(expr); if (typeof value !== 'boolean') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, expr, 'preserveWhitespaces must be a boolean'); } preserveWhitespaces = value; } const viewProviders: Expression|null = component.has('viewProviders') ? new WrappedNodeExpr(component.get('viewProviders') !) : null; let interpolation: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG; if (component.has('interpolation')) { const expr = component.get('interpolation') !; const value = this.evaluator.evaluate(expr); if (!Array.isArray(value) || value.length !== 2 || !value.every(element => typeof element === 'string')) { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, expr, 'interpolation must be an array with 2 elements of string type'); } interpolation = InterpolationConfig.fromArray(value as[string, string]); } const template = parseTemplate(templateStr, templateUrl, { preserveWhitespaces, interpolationConfig: interpolation, range: templateRange, escapedString }); if (template.errors !== undefined) { throw new Error( `Errors parsing template: ${template.errors.map(e => e.toString()).join(', ')}`); } // If the component has a selector, it should be registered with the `SelectorScopeRegistry` so // when this component appears in an `@NgModule` scope, its selector can be determined. if (metadata.selector !== null) { const ref = new Reference(node); this.scopeRegistry.registerDirective(node, { ref, name: node.name !.text, directive: ref, selector: metadata.selector, exportAs: metadata.exportAs, inputs: metadata.inputs, outputs: metadata.outputs, queries: metadata.queries.map(query => query.propertyName), isComponent: true, ...extractDirectiveGuards(node, this.reflector), }); } // Construct the list of view queries. const coreModule = this.isCore ? undefined : '@angular/core'; const viewChildFromFields = queriesFromFields( filterToMembersWithDecorator(decoratedElements, 'ViewChild', coreModule), this.reflector, this.evaluator); const viewChildrenFromFields = queriesFromFields( filterToMembersWithDecorator(decoratedElements, 'ViewChildren', coreModule), this.reflector, this.evaluator); const viewQueries = [...viewChildFromFields, ...viewChildrenFromFields]; if (component.has('queries')) { const queriesFromDecorator = extractQueriesFromDecorator( component.get('queries') !, this.reflector, this.evaluator, this.isCore); viewQueries.push(...queriesFromDecorator.view); } let styles: string[]|null = null; if (component.has('styles')) { styles = parseFieldArrayValue(component, 'styles', this.evaluator); } let styleUrls = this._extractStyleUrls(component); if (styleUrls !== null) { if (styles === null) { styles = []; } styleUrls.forEach(styleUrl => { const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile); styles !.push(this.resourceLoader.load(resourceUrl)); }); } const encapsulation: number = this._resolveEnumValue(component, 'encapsulation', 'ViewEncapsulation') || 0; const changeDetection: number|null = this._resolveEnumValue(component, 'changeDetection', 'ChangeDetectionStrategy'); let animations: Expression|null = null; if (component.has('animations')) { animations = new WrappedNodeExpr(component.get('animations') !); } const output = { analysis: { meta: { ...metadata, template, viewQueries, encapsulation, interpolation, styles: styles || [], // These will be replaced during the compilation step, after all `NgModule`s have been // analyzed and the full compilation scope for the component can be realized. pipes: EMPTY_MAP, directives: EMPTY_ARRAY, wrapDirectivesAndPipesInClosure: false, // animations, viewProviders, i18nUseExternalIds: this.i18nUseExternalIds, relativeContextFilePath }, metadataStmt: generateSetClassMetadataCall(node, this.reflector, this.isCore), parsedTemplate: template.nodes, }, typeCheck: true, }; if (changeDetection !== null) { (output.analysis.meta as R3ComponentMetadata).changeDetection = changeDetection; } return output; } typeCheck(ctx: TypeCheckContext, node: ts.Declaration, meta: ComponentHandlerData): void { const scope = this.scopeRegistry.lookupCompilationScopeAsRefs(node); const matcher = new SelectorMatcher<ScopeDirective<any>>(); if (scope !== null) { for (const meta of scope.directives) { matcher.addSelectables(CssSelector.parse(meta.selector), meta); } ctx.addTemplate(node as ts.ClassDeclaration, meta.parsedTemplate, matcher); } } resolve(node: ts.ClassDeclaration, analysis: ComponentHandlerData): void { // Check whether this component was registered with an NgModule. If so, it should be compiled // under that module's compilation scope. const scope = this.scopeRegistry.lookupCompilationScope(node); let metadata = analysis.meta; if (scope !== null) { // Replace the empty components and directives from the analyze() step with a fully expanded // scope. This is possible now because during resolve() the whole compilation unit has been // fully analyzed. const {pipes, containsForwardDecls} = scope; const directives = scope.directives.map(dir => ({selector: dir.selector, expression: dir.directive})); // Scan through the references of the `scope.directives` array and check whether // any import which needs to be generated for the directive would create a cycle. const origin = node.getSourceFile(); const cycleDetected = scope.directives.some(meta => this._isCyclicImport(meta.directive, origin)) || Array.from(scope.pipes.values()).some(pipe => this._isCyclicImport(pipe, origin)); if (!cycleDetected) { const wrapDirectivesAndPipesInClosure: boolean = !!containsForwardDecls; metadata.directives = directives; metadata.pipes = pipes; metadata.wrapDirectivesAndPipesInClosure = wrapDirectivesAndPipesInClosure; } else { this.scopeRegistry.setComponentAsRequiringRemoteScoping(node); } } } compile(node: ts.ClassDeclaration, analysis: ComponentHandlerData, pool: ConstantPool): CompileResult { const res = compileComponentFromMetadata(analysis.meta, pool, makeBindingParser()); const statements = res.statements; if (analysis.metadataStmt !== null) { statements.push(analysis.metadataStmt); } return { name: 'ngComponentDef', initializer: res.expression, statements, type: res.type, }; } private _resolveLiteral(decorator: Decorator): ts.ObjectLiteralExpression { if (this.literalCache.has(decorator)) { return this.literalCache.get(decorator) !; } if (decorator.args === null || decorator.args.length !== 1) { throw new FatalDiagnosticError( ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, `Incorrect number of arguments to @Component decorator`); } const meta = unwrapExpression(decorator.args[0]); if (!ts.isObjectLiteralExpression(meta)) { throw new FatalDiagnosticError( ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `Decorator argument must be literal.`); } this.literalCache.set(decorator, meta); return meta; } private _resolveEnumValue( component: Map<string, ts.Expression>, field: string, enumSymbolName: string): number|null { let resolved: number|null = null; if (component.has(field)) { const expr = component.get(field) !; const value = this.evaluator.evaluate(expr) as any; if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) { resolved = value.resolved as number; } else { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, expr, `${field} must be a member of ${enumSymbolName} enum from @angular/core`); } } return resolved; } private _extractStyleUrls(component: Map<string, ts.Expression>): string[]|null { if (!component.has('styleUrls')) { return null; } const styleUrlsExpr = component.get('styleUrls') !; const styleUrls = this.evaluator.evaluate(styleUrlsExpr); if (!Array.isArray(styleUrls) || !styleUrls.every(url => typeof url === 'string')) { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, styleUrlsExpr, 'styleUrls must be an array of strings'); } return styleUrls as string[]; } private _isCyclicImport(expr: Expression, origin: ts.SourceFile): boolean { if (!(expr instanceof ExternalExpr)) { return false; } // Figure out what file is being imported. const imported = this.moduleResolver.resolveModuleName(expr.value.moduleName !, origin); if (imported === null) { return false; } // Check whether the import is legal. return this.cycleAnalyzer.wouldCreateCycle(origin, imported); } } function getTemplateRange(templateExpr: ts.Expression) { const startPos = templateExpr.getStart() + 1; const {line, character} = ts.getLineAndCharacterOfPosition(templateExpr.getSourceFile(), startPos); return { startPos, startLine: line, startCol: character, endPos: templateExpr.getEnd() - 1, }; }
packages/compiler-cli/src/ngtsc/annotations/src/component.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.0001771524257492274, 0.0001703793095657602, 0.00016426516231149435, 0.00017048251174855977, 0.000003650516418929328 ]
{ "id": 3, "code_window": [ " *\n", " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {EventEmitter} from '@angular/core';\n", "\n", "import {defineComponent, defineDirective} from '../../src/render3/index';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/properties_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {TagContentType, TagDefinition} from './tags'; export class HtmlTagDefinition implements TagDefinition { private closedByChildren: {[key: string]: boolean} = {}; closedByParent: boolean = false; // TODO(issue/24571): remove '!'. requiredParents !: {[key: string]: boolean}; // TODO(issue/24571): remove '!'. parentToAdd !: string; implicitNamespacePrefix: string|null; contentType: TagContentType; isVoid: boolean; ignoreFirstLf: boolean; canSelfClose: boolean = false; constructor( {closedByChildren, requiredParents, implicitNamespacePrefix, contentType = TagContentType.PARSABLE_DATA, closedByParent = false, isVoid = false, ignoreFirstLf = false}: { closedByChildren?: string[], closedByParent?: boolean, requiredParents?: string[], implicitNamespacePrefix?: string, contentType?: TagContentType, isVoid?: boolean, ignoreFirstLf?: boolean } = {}) { if (closedByChildren && closedByChildren.length > 0) { closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true); } this.isVoid = isVoid; this.closedByParent = closedByParent || isVoid; if (requiredParents && requiredParents.length > 0) { this.requiredParents = {}; // The first parent is the list is automatically when none of the listed parents are present this.parentToAdd = requiredParents[0]; requiredParents.forEach(tagName => this.requiredParents[tagName] = true); } this.implicitNamespacePrefix = implicitNamespacePrefix || null; this.contentType = contentType; this.ignoreFirstLf = ignoreFirstLf; } requireExtraParent(currentParent: string): boolean { if (!this.requiredParents) { return false; } if (!currentParent) { return true; } const lcParent = currentParent.toLowerCase(); const isParentTemplate = lcParent === 'template' || currentParent === 'ng-template'; return !isParentTemplate && this.requiredParents[lcParent] != true; } isClosedByChild(name: string): boolean { return this.isVoid || name.toLowerCase() in this.closedByChildren; } } let _DEFAULT_TAG_DEFINITION !: HtmlTagDefinition; // see http://www.w3.org/TR/html51/syntax.html#optional-tags // This implementation does not fully conform to the HTML5 spec. let TAG_DEFINITIONS !: {[key: string]: HtmlTagDefinition}; export function getHtmlTagDefinition(tagName: string): HtmlTagDefinition { if (!TAG_DEFINITIONS) { _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition(); TAG_DEFINITIONS = { 'base': new HtmlTagDefinition({isVoid: true}), 'meta': new HtmlTagDefinition({isVoid: true}), 'area': new HtmlTagDefinition({isVoid: true}), 'embed': new HtmlTagDefinition({isVoid: true}), 'link': new HtmlTagDefinition({isVoid: true}), 'img': new HtmlTagDefinition({isVoid: true}), 'input': new HtmlTagDefinition({isVoid: true}), 'param': new HtmlTagDefinition({isVoid: true}), 'hr': new HtmlTagDefinition({isVoid: true}), 'br': new HtmlTagDefinition({isVoid: true}), 'source': new HtmlTagDefinition({isVoid: true}), 'track': new HtmlTagDefinition({isVoid: true}), 'wbr': new HtmlTagDefinition({isVoid: true}), 'p': new HtmlTagDefinition({ closedByChildren: [ 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul' ], closedByParent: true }), 'thead': new HtmlTagDefinition({closedByChildren: ['tbody', 'tfoot']}), 'tbody': new HtmlTagDefinition({closedByChildren: ['tbody', 'tfoot'], closedByParent: true}), 'tfoot': new HtmlTagDefinition({closedByChildren: ['tbody'], closedByParent: true}), 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], requiredParents: ['tbody', 'tfoot', 'thead'], closedByParent: true }), 'td': new HtmlTagDefinition({closedByChildren: ['td', 'th'], closedByParent: true}), 'th': new HtmlTagDefinition({closedByChildren: ['td', 'th'], closedByParent: true}), 'col': new HtmlTagDefinition({requiredParents: ['colgroup'], isVoid: true}), 'svg': new HtmlTagDefinition({implicitNamespacePrefix: 'svg'}), 'math': new HtmlTagDefinition({implicitNamespacePrefix: 'math'}), 'li': new HtmlTagDefinition({closedByChildren: ['li'], closedByParent: true}), 'dt': new HtmlTagDefinition({closedByChildren: ['dt', 'dd']}), 'dd': new HtmlTagDefinition({closedByChildren: ['dt', 'dd'], closedByParent: true}), 'rb': new HtmlTagDefinition( {closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true}), 'rt': new HtmlTagDefinition( {closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true}), 'rtc': new HtmlTagDefinition({closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true}), 'rp': new HtmlTagDefinition( {closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true}), 'optgroup': new HtmlTagDefinition({closedByChildren: ['optgroup'], closedByParent: true}), 'option': new HtmlTagDefinition({closedByChildren: ['option', 'optgroup'], closedByParent: true}), 'pre': new HtmlTagDefinition({ignoreFirstLf: true}), 'listing': new HtmlTagDefinition({ignoreFirstLf: true}), 'style': new HtmlTagDefinition({contentType: TagContentType.RAW_TEXT}), 'script': new HtmlTagDefinition({contentType: TagContentType.RAW_TEXT}), 'title': new HtmlTagDefinition({contentType: TagContentType.ESCAPABLE_RAW_TEXT}), 'textarea': new HtmlTagDefinition( {contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true}), }; } return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION; }
packages/compiler/src/ml_parser/html_tags.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017905904678627849, 0.00017295223369728774, 0.0001635797816561535, 0.00017383380327373743, 0.000003957768512918847 ]
{ "id": 3, "code_window": [ " *\n", " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {EventEmitter} from '@angular/core';\n", "\n", "import {defineComponent, defineDirective} from '../../src/render3/index';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/properties_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
// #docregion import { Component, EventEmitter, Input, Output } from '@angular/core'; // #docregion example @Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { // No aliases @Output() change = new EventEmitter<any>(); @Input() label: string; } // #enddocregion example
aio/content/examples/styleguide/src/05-13/app/heroes/shared/hero-button/hero-button.component.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.0001678886910667643, 0.00016663665883243084, 0.00016538462659809738, 0.00016663665883243084, 0.0000012520322343334556 ]
{ "id": 4, "code_window": [ " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {NgForOfContext} from '@angular/common';\n", "import {ElementRef, QueryList, TemplateRef, ViewContainerRef} from '@angular/core';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/query_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Subject, Subscription} from 'rxjs'; /** * Use in directives and components to emit custom events synchronously * or asynchronously, and register handlers for those events by subscribing * to an instance. * * @usageNotes * * In the following example, a component defines two output properties * that create event emitters. When the title is clicked, the emitter * emits an open or close event to toggle the current visibility state. * * ``` * @Component({ * selector: 'zippy', * template: ` * <div class="zippy"> * <div (click)="toggle()">Toggle</div> * <div [hidden]="!visible"> * <ng-content></ng-content> * </div> * </div>`}) * export class Zippy { * visible: boolean = true; * @Output() open: EventEmitter<any> = new EventEmitter(); * @Output() close: EventEmitter<any> = new EventEmitter(); * * toggle() { * this.visible = !this.visible; * if (this.visible) { * this.open.emit(null); * } else { * this.close.emit(null); * } * } * } * ``` * * Access the event object with the `$event` argument passed to the output event * handler: * * ``` * <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy> * ``` * * ### Notes * * Uses Rx.Observable but provides an adapter to make it work as specified here: * https://github.com/jhusain/observable-spec * * Once a reference implementation of the spec is available, switch to it. * * @publicApi */ export class EventEmitter<T> extends Subject<T> { // TODO: mark this as internal once all the facades are gone // we can't mark it as internal now because EventEmitter exported via @angular/core would not // contain this property making it incompatible with all the code that uses EventEmitter via // facades, which are local to the code and do not have this property stripped. /** * Internal */ __isAsync: boolean; // tslint:disable-line /** * Creates an instance of this class that can * deliver events synchronously or asynchronously. * * @param isAsync When true, deliver events asynchronously. * */ constructor(isAsync: boolean = false) { super(); this.__isAsync = isAsync; } /** * Emits an event containing a given value. * @param value The value to emit. */ emit(value?: T) { super.next(value); } /** * Registers handlers for events emitted by this instance. * @param generatorOrNext When supplied, a custom handler for emitted events. * @param error When supplied, a custom handler for an error notification * from this emitter. * @param complete When supplied, a custom handler for a completion * notification from this emitter. */ subscribe(generatorOrNext?: any, error?: any, complete?: any): Subscription { let schedulerFn: (t: any) => any; let errorFn = (err: any): any => null; let completeFn = (): any => null; if (generatorOrNext && typeof generatorOrNext === 'object') { schedulerFn = this.__isAsync ? (value: any) => { setTimeout(() => generatorOrNext.next(value)); } : (value: any) => { generatorOrNext.next(value); }; if (generatorOrNext.error) { errorFn = this.__isAsync ? (err) => { setTimeout(() => generatorOrNext.error(err)); } : (err) => { generatorOrNext.error(err); }; } if (generatorOrNext.complete) { completeFn = this.__isAsync ? () => { setTimeout(() => generatorOrNext.complete()); } : () => { generatorOrNext.complete(); }; } } else { schedulerFn = this.__isAsync ? (value: any) => { setTimeout(() => generatorOrNext(value)); } : (value: any) => { generatorOrNext(value); }; if (error) { errorFn = this.__isAsync ? (err) => { setTimeout(() => error(err)); } : (err) => { error(err); }; } if (complete) { completeFn = this.__isAsync ? () => { setTimeout(() => complete()); } : () => { complete(); }; } } const sink = super.subscribe(schedulerFn, errorFn, completeFn); if (generatorOrNext instanceof Subscription) { generatorOrNext.add(sink); } return sink; } }
packages/core/src/event_emitter.ts
1
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017884897533804178, 0.000172636064235121, 0.0001646680320845917, 0.00017322192434221506, 0.000004549941422737902 ]
{ "id": 4, "code_window": [ " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {NgForOfContext} from '@angular/common';\n", "import {ElementRef, QueryList, TemplateRef, ViewContainerRef} from '@angular/core';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/query_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
// #docregion import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ComposeMessageComponent } from './compose-message/compose-message.component'; import { CanDeactivateGuard } from './can-deactivate.guard'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; const appRoutes: Routes = [ { path: 'compose', component: ComposeMessageComponent, outlet: 'popup' }, { path: '', redirectTo: '/heroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: true } // <-- debugging purposes only ) ], exports: [ RouterModule ] }) export class AppRoutingModule {}
aio/content/examples/router/src/app/app-routing.module.4.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017859830404631793, 0.00017428561113774776, 0.0001688541960902512, 0.0001748449431033805, 0.00000426015731136431 ]
{ "id": 4, "code_window": [ " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {NgForOfContext} from '@angular/common';\n", "import {ElementRef, QueryList, TemplateRef, ViewContainerRef} from '@angular/core';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/query_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
// Imports import {GithubApi} from '../../lib/common/github-api'; import {GithubPullRequests} from '../../lib/common/github-pull-requests'; // Tests describe('GithubPullRequests', () => { let githubApi: jasmine.SpyObj<GithubApi>; beforeEach(() => { githubApi = jasmine.createSpyObj('githubApi', ['post', 'get', 'getPaginated']); }); describe('constructor()', () => { it('should throw if \'githubOrg\' is missing or empty', () => { expect(() => new GithubPullRequests(githubApi, '', 'bar')). toThrowError('Missing or empty required parameter \'githubOrg\'!'); }); it('should throw if \'githubRepo\' is missing or empty', () => { expect(() => new GithubPullRequests(githubApi, 'foo', '')). toThrowError('Missing or empty required parameter \'githubRepo\'!'); }); }); describe('addComment()', () => { let prs: GithubPullRequests; beforeEach(() => { prs = new GithubPullRequests(githubApi, 'foo', 'bar'); }); it('should throw if the PR number is invalid', () => { expect(() => prs.addComment(-1337, 'body')).toThrowError(`Invalid PR number: -1337`); expect(() => prs.addComment(NaN, 'body')).toThrowError(`Invalid PR number: NaN`); }); it('should throw if the comment body is invalid or empty', () => { expect(() => prs.addComment(42, '')).toThrowError(`Invalid or empty comment body: `); }); it('should make a POST request to Github with the correct pathname, params and data', () => { githubApi.post.and.callFake(() => Promise.resolve()); prs.addComment(42, 'body'); expect(githubApi.post).toHaveBeenCalledWith('/repos/foo/bar/issues/42/comments', null, {body: 'body'}); }); it('should reject if the request fails', done => { githubApi.post.and.callFake(() => Promise.reject('Test')); prs.addComment(42, 'body').catch(err => { expect(err).toBe('Test'); done(); }); }); it('should resolve with the data from the Github POST', done => { githubApi.post.and.callFake(() => Promise.resolve('Test')); prs.addComment(42, 'body').then(data => { expect(data).toBe('Test'); done(); }); }); }); describe('fetch()', () => { let prs: GithubPullRequests; beforeEach(() => { prs = new GithubPullRequests(githubApi, 'foo', 'bar'); }); it('should make a GET request to GitHub with the correct pathname', () => { prs.fetch(42); expect(githubApi.get).toHaveBeenCalledWith('/repos/foo/bar/issues/42'); }); it('should resolve with the data returned from GitHub', done => { const expected: any = {number: 42}; githubApi.get.and.callFake(() => Promise.resolve(expected)); prs.fetch(42).then(data => { expect(data).toEqual(expected); done(); }); }); }); describe('fetchAll()', () => { let prs: GithubPullRequests; beforeEach(() => prs = new GithubPullRequests(githubApi, 'foo', 'bar')); it('should call \'getPaginated()\' with the correct pathname and params', () => { const expectedPathname = '/repos/foo/bar/pulls'; prs.fetchAll('all'); prs.fetchAll('closed'); prs.fetchAll('open'); expect(githubApi.getPaginated).toHaveBeenCalledTimes(3); expect(githubApi.getPaginated.calls.argsFor(0)).toEqual([expectedPathname, {state: 'all'}]); expect(githubApi.getPaginated.calls.argsFor(1)).toEqual([expectedPathname, {state: 'closed'}]); expect(githubApi.getPaginated.calls.argsFor(2)).toEqual([expectedPathname, {state: 'open'}]); }); it('should default to \'all\' if no state is specified', () => { prs.fetchAll(); expect(githubApi.getPaginated).toHaveBeenCalledWith('/repos/foo/bar/pulls', {state: 'all'}); }); it('should forward the value returned by \'getPaginated()\'', () => { githubApi.getPaginated.and.returnValue('Test'); expect(prs.fetchAll() as any).toBe('Test'); }); }); describe('fetchFiles()', () => { let prs: GithubPullRequests; beforeEach(() => { prs = new GithubPullRequests(githubApi, 'foo', 'bar'); }); it('should make a paginated GET request to GitHub with the correct pathname', () => { prs.fetchFiles(42); expect(githubApi.getPaginated).toHaveBeenCalledWith('/repos/foo/bar/pulls/42/files'); }); it('should resolve with the data returned from GitHub', done => { const expected: any = [{sha: 'ABCDE', filename: 'a/b/c'}, {sha: '12345', filename: 'x/y/z'}]; githubApi.getPaginated.and.callFake(() => Promise.resolve(expected)); prs.fetchFiles(42).then(data => { expect(data).toEqual(expected); done(); }); }); }); });
aio/aio-builds-setup/dockerbuild/scripts-js/test/common/github-pull-requests.spec.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00018093835387844592, 0.0001772727264324203, 0.00017244883929379284, 0.0001776651624822989, 0.0000021468918021128047 ]
{ "id": 4, "code_window": [ " * Use of this source code is governed by an MIT-style license that can be\n", " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "/// <reference types=\"rxjs\" />\n", "\n", "import {NgForOfContext} from '@angular/common';\n", "import {ElementRef, QueryList, TemplateRef, ViewContainerRef} from '@angular/core';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/core/test/render3/query_spec.ts", "type": "replace", "edit_start_line_idx": 8 }
export * from './hero-list'; export * from './shared';
aio/content/examples/styleguide/src/05-15/app/heroes/index.ts
0
https://github.com/angular/angular/commit/67ad8a2632ad8a2eb4d82735170b145c2439dc8e
[ 0.00017710801330395043, 0.00017710801330395043, 0.00017710801330395043, 0.00017710801330395043, 0 ]
{ "id": 0, "code_window": [ "\n", "import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock';\n", "import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock';\n", "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';\n", "import {LocationStrategy} from 'angular2/src/router/location_strategy';\n", "import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';\n", "\n", "import {TestComponentBuilder} from './test_component_builder';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 32 }
import {provide, Provider} from 'angular2/src/core/di'; import {MockSchemaRegistry} from './schema_registry_mock'; import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry'; export var TEST_PROVIDERS = [provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];
modules/angular2/test/core/compiler/test_bindings.ts
1
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.0002075673983199522, 0.0002075673983199522, 0.0002075673983199522, 0.0002075673983199522, 0 ]
{ "id": 0, "code_window": [ "\n", "import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock';\n", "import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock';\n", "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';\n", "import {LocationStrategy} from 'angular2/src/router/location_strategy';\n", "import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';\n", "\n", "import {TestComponentBuilder} from './test_component_builder';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 32 }
library benchpress.test.firefox_extension.spec; main() {}
modules/benchpress/test/firefox_extension/spec.dart
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.0001703481248114258, 0.0001703481248114258, 0.0001703481248114258, 0.0001703481248114258, 0 ]
{ "id": 0, "code_window": [ "\n", "import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock';\n", "import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock';\n", "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';\n", "import {LocationStrategy} from 'angular2/src/router/location_strategy';\n", "import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';\n", "\n", "import {TestComponentBuilder} from './test_component_builder';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 32 }
/// <reference path="../typings/node/node.d.ts" /> /// <reference path="../typings/jasmine/jasmine.d.ts" /> console.warn( "Skipping all tests in broccoli-merge-trees.spec.ts because they require mock-fs which is currently incompatible with node 4.x. See: https://github.com/tschaub/mock-fs/issues/59"); /* let mockfs = require('mock-fs'); import fs = require('fs'); import {TreeDiffer} from './tree-differ'; import {MergeTrees} from './broccoli-merge-trees'; describe('MergeTrees', () => { afterEach(() => mockfs.restore()); function mergeTrees(inputPaths, cachePath, options) { return new MergeTrees(inputPaths, cachePath, options); } function MakeTreeDiffers(rootDirs) { let treeDiffers = rootDirs.map((rootDir) => new TreeDiffer('MergeTrees', rootDir)); treeDiffers.diffTrees = () => { return treeDiffers.map(tree => tree.diffTree()); }; return treeDiffers; } function read(path) { return fs.readFileSync(path, "utf-8"); } it('should copy the file from the right-most inputTree with overwrite=true', () => { let testDir: any = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {'foo.js': mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)})}, 'tree3': {'foo.js': mockfs.file({content: 'tree3/foo.js content', mtime: new Date(1000)})} }; mockfs(testDir); let treeDiffer = MakeTreeDiffers(['tree1', 'tree2', 'tree3']); let treeMerger = mergeTrees(['tree1', 'tree2', 'tree3'], 'dest', {overwrite: true}); treeMerger.rebuild(treeDiffer.diffTrees()); expect(read('dest/foo.js')).toBe('tree3/foo.js content'); delete testDir.tree2['foo.js']; delete testDir.tree3['foo.js']; mockfs(testDir); treeMerger.rebuild(treeDiffer.diffTrees()); expect(read('dest/foo.js')).toBe('tree1/foo.js content'); testDir.tree2['foo.js'] = mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)}); mockfs(testDir); treeMerger.rebuild(treeDiffer.diffTrees()); expect(read('dest/foo.js')).toBe('tree2/foo.js content'); }); it('should throw if duplicates are found during the initial build', () => { let testDir: any = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {'foo.js': mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)})}, 'tree3': {'foo.js': mockfs.file({content: 'tree3/foo.js content', mtime: new Date(1000)})} }; mockfs(testDir); let treeDiffer = MakeTreeDiffers(['tree1', 'tree2', 'tree3']); let treeMerger = mergeTrees(['tree1', 'tree2', 'tree3'], 'dest', {}); expect(() => treeMerger.rebuild(treeDiffer.diffTrees())) .toThrowError( 'Duplicate path found while merging trees. Path: "foo.js".\n' + 'Either remove the duplicate or enable the "overwrite" option for this merge.'); testDir = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {}, 'tree3': {} }; mockfs(testDir); }); it('should throw if duplicates are found during rebuild', () => { let testDir = { 'tree1': {'foo.js': mockfs.file({content: 'tree1/foo.js content', mtime: new Date(1000)})}, 'tree2': {}, 'tree3': {} }; mockfs(testDir); let treeDiffer = MakeTreeDiffers(['tree1', 'tree2', 'tree3']); let treeMerger = mergeTrees(['tree1', 'tree2', 'tree3'], 'dest', {}); expect(() => treeMerger.rebuild(treeDiffer.diffTrees())).not.toThrow(); testDir.tree2['foo.js'] = mockfs.file({content: 'tree2/foo.js content', mtime: new Date(1000)}); mockfs(testDir); expect(() => treeMerger.rebuild(treeDiffer.diffTrees())) .toThrowError( 'Duplicate path found while merging trees. Path: "foo.js".\n' + 'Either remove the duplicate or enable the "overwrite" option for this merge.'); }); }); */
tools/broccoli/broccoli-merge-trees.spec.ts
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00017767430108506233, 0.0001725109468679875, 0.00016519046039320529, 0.00017340871272608638, 0.00000401344505007728 ]
{ "id": 0, "code_window": [ "\n", "import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock';\n", "import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock';\n", "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';\n", "import {LocationStrategy} from 'angular2/src/router/location_strategy';\n", "import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';\n", "\n", "import {TestComponentBuilder} from './test_component_builder';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 32 }
<div class="md-spinner-wrapper"> <div class="md-inner"> <div class="md-gap"></div> <div class="md-left"> <div class="md-half-circle"></div> </div> <div class="md-right"> <div class="md-half-circle"></div> </div> </div> </div>
modules/angular2_material/src/components/progress-circular/progress_circular.html
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.000169723920407705, 0.00016874822904355824, 0.00016777252312749624, 0.00016874822904355824, 9.756986401043832e-7 ]
{ "id": 1, "code_window": [ " provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),\n", " PipeResolver,\n", " provide(ExceptionHandler, {asValue: new ExceptionHandler(DOM)}),\n", " provide(LocationStrategy, {asClass: MockLocationStrategy}),\n", " provide(XHR, {asClass: MockXHR}),\n", " TestComponentBuilder,\n", " provide(NgZone, {asClass: MockNgZone}),\n", " provide(AnimationBuilder, {asClass: MockAnimationBuilder}),\n", " EventManager,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " XHR,\n" ], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 118 }
import {provide, Provider} from 'angular2/src/core/di'; import {DEFAULT_PIPES} from 'angular2/src/core/pipes'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock'; import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory'; import {Reflector, reflector} from 'angular2/src/core/reflection/reflection'; import { IterableDiffers, defaultIterableDiffers, KeyValueDiffers, defaultKeyValueDiffers, ChangeDetectorGenConfig } from 'angular2/src/core/change_detection/change_detection'; import {ExceptionHandler} from 'angular2/src/core/facade/exceptions'; import {ViewResolver} from 'angular2/src/core/linker/view_resolver'; import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; import {PipeResolver} from 'angular2/src/core/linker/pipe_resolver'; import {DynamicComponentLoader} from 'angular2/src/core/linker/dynamic_component_loader'; import {XHR} from 'angular2/src/core/compiler/xhr'; import {NgZone} from 'angular2/src/core/zone/ng_zone'; import {DOM} from 'angular2/src/core/dom/dom_adapter'; import { EventManager, DomEventsPlugin, EVENT_MANAGER_PLUGINS } from 'angular2/src/core/render/dom/events/event_manager'; import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock'; import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock'; import {MockXHR} from 'angular2/src/core/compiler/xhr_mock'; import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {LocationStrategy} from 'angular2/src/router/location_strategy'; import {MockNgZone} from 'angular2/src/mock/ng_zone_mock'; import {TestComponentBuilder} from './test_component_builder'; import {Injector} from 'angular2/src/core/di'; import {ELEMENT_PROBE_PROVIDERS} from 'angular2/src/core/debug'; import {ListWrapper} from 'angular2/src/core/facade/collection'; import {FunctionWrapper, Type} from 'angular2/src/core/facade/lang'; import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view_pool'; import {AppViewManager} from 'angular2/src/core/linker/view_manager'; import {AppViewManagerUtils} from 'angular2/src/core/linker/view_manager_utils'; import {Renderer} from 'angular2/src/core/render/api'; import { DomRenderer, DOCUMENT, SharedStylesHost, DomSharedStylesHost } from 'angular2/src/core/render/render'; import {APP_ID} from 'angular2/src/core/application_tokens'; import {Serializer} from "angular2/src/web_workers/shared/serializer"; import {Log} from './utils'; import {compilerProviders} from 'angular2/src/core/compiler/compiler'; import {DomRenderer_} from "angular2/src/core/render/dom/dom_renderer"; import {DynamicComponentLoader_} from "angular2/src/core/linker/dynamic_component_loader"; import {AppViewManager_} from "angular2/src/core/linker/view_manager"; /** * Returns the root injector providers. * * This must be kept in sync with the _rootBindings in application.js * * @returns {any[]} */ function _getRootProviders() { return [provide(Reflector, {asValue: reflector})]; } /** * Returns the application injector providers. * * This must be kept in sync with _injectorBindings() in application.js * * @returns {any[]} */ function _getAppBindings() { var appDoc; // The document is only available in browser environment try { appDoc = DOM.defaultDoc(); } catch (e) { appDoc = null; } return [ compilerProviders(), provide(ChangeDetectorGenConfig, {asValue: new ChangeDetectorGenConfig(true, true, false, true)}), provide(DOCUMENT, {asValue: appDoc}), provide(DomRenderer, {asClass: DomRenderer_}), provide(Renderer, {asAlias: DomRenderer}), provide(APP_ID, {asValue: 'a'}), DomSharedStylesHost, provide(SharedStylesHost, {asAlias: DomSharedStylesHost}), AppViewPool, provide(AppViewManager, {asClass: AppViewManager_}), AppViewManagerUtils, Serializer, ELEMENT_PROBE_PROVIDERS, provide(APP_VIEW_POOL_CAPACITY, {asValue: 500}), ProtoViewFactory, provide(DirectiveResolver, {asClass: MockDirectiveResolver}), provide(ViewResolver, {asClass: MockViewResolver}), DEFAULT_PIPES, provide(IterableDiffers, {asValue: defaultIterableDiffers}), provide(KeyValueDiffers, {asValue: defaultKeyValueDiffers}), Log, provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}), PipeResolver, provide(ExceptionHandler, {asValue: new ExceptionHandler(DOM)}), provide(LocationStrategy, {asClass: MockLocationStrategy}), provide(XHR, {asClass: MockXHR}), TestComponentBuilder, provide(NgZone, {asClass: MockNgZone}), provide(AnimationBuilder, {asClass: MockAnimationBuilder}), EventManager, new Provider(EVENT_MANAGER_PLUGINS, {toClass: DomEventsPlugin, multi: true}) ]; } export function createTestInjector(providers: Array<Type | Provider | any[]>): Injector { var rootInjector = Injector.resolveAndCreate(_getRootProviders()); return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), providers)); } /** * Allows injecting dependencies in `beforeEach()` and `it()`. * * Example: * * ``` * beforeEach(inject([Dependency, AClass], (dep, object) => { * // some code that uses `dep` and `object` * // ... * })); * * it('...', inject([AClass, AsyncTestCompleter], (object, async) => { * object.doSomething().then(() => { * expect(...); * async.done(); * }); * }) * ``` * * Notes: * - injecting an `AsyncTestCompleter` allow completing async tests - this is the equivalent of * adding a `done` parameter in Jasmine, * - inject is currently a function because of some Traceur limitation the syntax should eventually * becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });` * * @param {Array} tokens * @param {Function} fn * @return {FunctionWithParamTokens} */ export function inject(tokens: any[], fn: Function): FunctionWithParamTokens { return new FunctionWithParamTokens(tokens, fn); } export class FunctionWithParamTokens { constructor(private _tokens: any[], private _fn: Function) {} /** * Returns the value of the executed function. */ execute(injector: Injector): any { var params = this._tokens.map(t => injector.get(t)); return FunctionWrapper.apply(this._fn, params); } hasToken(token: any): boolean { return this._tokens.indexOf(token) > -1; } }
modules/angular2/src/test_lib/test_injector.ts
1
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.04199954867362976, 0.0026398631744086742, 0.00016175264318007976, 0.00017314369324594736, 0.009554111398756504 ]
{ "id": 1, "code_window": [ " provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),\n", " PipeResolver,\n", " provide(ExceptionHandler, {asValue: new ExceptionHandler(DOM)}),\n", " provide(LocationStrategy, {asClass: MockLocationStrategy}),\n", " provide(XHR, {asClass: MockXHR}),\n", " TestComponentBuilder,\n", " provide(NgZone, {asClass: MockNgZone}),\n", " provide(AnimationBuilder, {asClass: MockAnimationBuilder}),\n", " EventManager,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " XHR,\n" ], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 118 }
// Public API for Services export {AppRootUrl} from 'angular2/src/core/compiler/app_root_url'; export {UrlResolver} from 'angular2/src/core/compiler/url_resolver'; export {Title} from 'angular2/src/core/services/title';
modules/angular2/src/core/services.ts
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00017234413826372474, 0.00017234413826372474, 0.00017234413826372474, 0.00017234413826372474, 0 ]
{ "id": 1, "code_window": [ " provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),\n", " PipeResolver,\n", " provide(ExceptionHandler, {asValue: new ExceptionHandler(DOM)}),\n", " provide(LocationStrategy, {asClass: MockLocationStrategy}),\n", " provide(XHR, {asClass: MockXHR}),\n", " TestComponentBuilder,\n", " provide(NgZone, {asClass: MockNgZone}),\n", " provide(AnimationBuilder, {asClass: MockAnimationBuilder}),\n", " EventManager,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " XHR,\n" ], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 118 }
import { getIntParameter, getStringParameter, bindAction } from 'angular2/src/test_lib/benchmark_util'; declare var angular: any; var totalRows = getIntParameter('rows'); var totalColumns = getIntParameter('columns'); var benchmarkType = getStringParameter('benchmarkType'); export function main() { angular.bootstrap(document.querySelector('largetable'), ['app']); } angular.module('app', []) .config(function($compileProvider) { if ($compileProvider.debugInfoEnabled) { $compileProvider.debugInfoEnabled(false); } }) .filter('noop', function() { return function(input) { return input; }; }) .directive('largetable', function() { return { restrict: 'E', templateUrl: 'largetable-js-template.html', controller: 'DataController' }; }) .controller('DataController', function($scope) { bindAction('#destroyDom', destroyDom); bindAction('#createDom', createDom); function destroyDom() { $scope.$apply(function() { $scope.benchmarkType = 'none'; }); } function createDom() { $scope.$apply(function() { $scope.benchmarkType = benchmarkType; }); } var data = $scope.data = []; function iGetter() { return this.i; } function jGetter() { return this.j; } for (var i = 0; i < totalRows; i++) { data[i] = []; for (var j = 0; j < totalColumns; j++) { data[i][j] = {i: i, j: j, iFn: iGetter, jFn: jGetter}; } } }) .directive('baselineBindingTable', function() { return { restrict: 'E', link: function($scope, $element) { var i, j, row, cell, comment; var template = document.createElement('span'); template.setAttribute('ng-repeat', 'foo in foos'); template.classList.add('ng-scope'); template.appendChild(document.createElement('span')); template.appendChild(document.createTextNode(':')); template.appendChild(document.createElement('span')); template.appendChild(document.createTextNode('|')); for (i = 0; i < totalRows; i++) { row = document.createElement('div'); $element[0].appendChild(row); for (j = 0; j < totalColumns; j++) { cell = template.cloneNode(true); row.appendChild(cell); cell.childNodes[0].textContent = i; cell.childNodes[2].textContent = j; cell.ng3992 = 'xxx'; comment = document.createComment('ngRepeat end: bar in foo'); row.appendChild(comment); } comment = document.createComment('ngRepeat end: foo in foos'); $element[0].appendChild(comment); } } }; }) .directive('baselineInterpolationTable', function() { return { restrict: 'E', link: function($scope, $element) { var i, j, row, cell, comment; var template = document.createElement('span'); template.setAttribute('ng-repeat', 'foo in foos'); template.classList.add('ng-scope'); for (i = 0; i < totalRows; i++) { row = document.createElement('div'); $element[0].appendChild(row); for (j = 0; j < totalColumns; j++) { cell = template.cloneNode(true); row.appendChild(cell); cell.textContent = '' + i + ':' + j + '|'; cell.ng3992 = 'xxx'; comment = document.createComment('ngRepeat end: bar in foo'); row.appendChild(comment); } comment = document.createComment('ngRepeat end: foo in foos'); $element[0].appendChild(comment); } } }; })
modules/benchmarks_external/src/largetable/largetable_benchmark.ts
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.0001760039885994047, 0.0001723313907859847, 0.00016958948981482536, 0.00017195013060700148, 0.0000020681404748756904 ]
{ "id": 1, "code_window": [ " provide(DynamicComponentLoader, {asClass: DynamicComponentLoader_}),\n", " PipeResolver,\n", " provide(ExceptionHandler, {asValue: new ExceptionHandler(DOM)}),\n", " provide(LocationStrategy, {asClass: MockLocationStrategy}),\n", " provide(XHR, {asClass: MockXHR}),\n", " TestComponentBuilder,\n", " provide(NgZone, {asClass: MockNgZone}),\n", " provide(AnimationBuilder, {asClass: MockAnimationBuilder}),\n", " EventManager,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " XHR,\n" ], "file_path": "modules/angular2/src/test_lib/test_injector.ts", "type": "replace", "edit_start_line_idx": 118 }
.hidden{ display: none !important; } #images { width: 600px; margin: 0 auto; } ul li { list-style-type: none; float: left; margin-left: 20px; width: 200px; } #main ul { width: 700px; } .card-image .image-loader{ position: absolute; bottom: 0; margin: auto; } .card-image img.grey { opacity: 0.4; } .fixed-action-btn.bottom { bottom: 45px; right: 24px; }
modules/examples/src/web_workers/images/image_demo.css
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00017605014727450907, 0.00017498449597042054, 0.00017386727267876267, 0.00017501029651612043, 8.191057645490218e-7 ]
{ "id": 2, "code_window": [ "import {provide, Provider} from 'angular2/src/core/di';\n", "import {MockSchemaRegistry} from './schema_registry_mock';\n", "import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {XHR} from 'angular2/src/core/compiler/xhr';\n" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "add", "edit_start_line_idx": 3 }
import {provide, Provider} from 'angular2/src/core/di'; import {MockSchemaRegistry} from './schema_registry_mock'; import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry'; export var TEST_PROVIDERS = [provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];
modules/angular2/test/core/compiler/test_bindings.ts
1
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.528558611869812, 0.528558611869812, 0.528558611869812, 0.528558611869812, 0 ]
{ "id": 2, "code_window": [ "import {provide, Provider} from 'angular2/src/core/di';\n", "import {MockSchemaRegistry} from './schema_registry_mock';\n", "import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {XHR} from 'angular2/src/core/compiler/xhr';\n" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "add", "edit_start_line_idx": 3 }
import {Math} from 'angular2/src/core/facade/math'; import {StringWrapper} from 'angular2/src/core/facade/lang'; import {ListWrapper, Map, MapWrapper} from 'angular2/src/core/facade/collection'; export var ITEMS = 1000; export var ITEM_HEIGHT = 40; export var VISIBLE_ITEMS = 17; export var HEIGHT = ITEMS * ITEM_HEIGHT; export var VIEW_PORT_HEIGHT = ITEM_HEIGHT * VISIBLE_ITEMS; export var COMPANY_NAME_WIDTH = 100; export var OPPORTUNITY_NAME_WIDTH = 100; export var OFFERING_NAME_WIDTH = 100; export var ACCOUNT_CELL_WIDTH = 50; export var BASE_POINTS_WIDTH = 50; export var KICKER_POINTS_WIDTH = 50; export var STAGE_BUTTONS_WIDTH = 220; export var BUNDLES_WIDTH = 120; export var DUE_DATE_WIDTH = 100; export var END_DATE_WIDTH = 100; export var AAT_STATUS_WIDTH = 100; export var ROW_WIDTH = COMPANY_NAME_WIDTH + OPPORTUNITY_NAME_WIDTH + OFFERING_NAME_WIDTH + ACCOUNT_CELL_WIDTH + BASE_POINTS_WIDTH + KICKER_POINTS_WIDTH + STAGE_BUTTONS_WIDTH + BUNDLES_WIDTH + DUE_DATE_WIDTH + END_DATE_WIDTH + AAT_STATUS_WIDTH; export var STATUS_LIST = ['Planned', 'Pitched', 'Won', 'Lost']; export var AAT_STATUS_LIST = ['Active', 'Passive', 'Abandoned']; // Imitate Streamy entities. // Just a non-trivial object. Nothing fancy or correct. export class CustomDate { year: number; month: number; day: number; constructor(y: number, m: number, d: number) { this.year = y; this.month = m; this.day = d; } addDays(days: number): CustomDate { var newDay = this.day + days; var newMonth = this.month + Math.floor(newDay / 30); newDay = newDay % 30; var newYear = this.year + Math.floor(newMonth / 12); return new CustomDate(newYear, newMonth, newDay); } static now(): CustomDate { return new CustomDate(2014, 1, 28); } } export class RawEntity { _data: Map<any, any>; constructor() { this._data = new Map(); } get(key: string) { if (key.indexOf('.') == -1) { return this._data[key]; } var pieces = key.split('.'); var last = ListWrapper.last(pieces); pieces.length = pieces.length - 1; var target = this._resolve(pieces, this); if (target == null) { return null; } return target[last]; } set(key: string, value) { if (key.indexOf('.') == -1) { this._data[key] = value; return; } var pieces = key.split('.'); var last = ListWrapper.last(pieces); pieces.length = pieces.length - 1; var target = this._resolve(pieces, this); target[last] = value; } remove(key: string) { if (!StringWrapper.contains(key, '.')) { return this._data.delete(key); } var pieces = key.split('.'); var last = ListWrapper.last(pieces); pieces.length = pieces.length - 1; var target = this._resolve(pieces, this); return target.remove(last); } _resolve(pieces, start) { var cur = start; for (var i = 0; i < pieces.length; i++) { cur = cur[pieces[i]]; if (cur == null) { return null; } } return cur; } } export class Company extends RawEntity { get name(): string { return this.get('name'); } set name(val: string) { this.set('name', val); } } export class Offering extends RawEntity { get name(): string { return this.get('name'); } set name(val: string) { this.set('name', val); } get company(): Company { return this.get('company'); } set company(val: Company) { this.set('company', val); } get opportunity(): Opportunity { return this.get('opportunity'); } set opportunity(val: Opportunity) { this.set('opportunity', val); } get account(): Account { return this.get('account'); } set account(val: Account) { this.set('account', val); } get basePoints(): number { return this.get('basePoints'); } set basePoints(val: number) { this.set('basePoints', val); } get kickerPoints(): number { return this.get('kickerPoints'); } set kickerPoints(val: number) { this.set('kickerPoints', val); } get status(): string { return this.get('status'); } set status(val: string) { this.set('status', val); } get bundles(): string { return this.get('bundles'); } set bundles(val: string) { this.set('bundles', val); } get dueDate(): CustomDate { return this.get('dueDate'); } set dueDate(val: CustomDate) { this.set('dueDate', val); } get endDate(): CustomDate { return this.get('endDate'); } set endDate(val: CustomDate) { this.set('endDate', val); } get aatStatus(): string { return this.get('aatStatus'); } set aatStatus(val: string) { this.set('aatStatus', val); } } export class Opportunity extends RawEntity { get name(): string { return this.get('name'); } set name(val: string) { this.set('name', val); } } export class Account extends RawEntity { get accountId(): number { return this.get('accountId'); } set accountId(val: number) { this.set('accountId', val); } }
modules/benchmarks/src/naive_infinite_scroll/common.ts
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00022673510829918087, 0.00017617305275052786, 0.00016715089441277087, 0.0001725884503684938, 0.000013440968359645922 ]
{ "id": 2, "code_window": [ "import {provide, Provider} from 'angular2/src/core/di';\n", "import {MockSchemaRegistry} from './schema_registry_mock';\n", "import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {XHR} from 'angular2/src/core/compiler/xhr';\n" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "add", "edit_start_line_idx": 3 }
///<reference path="../dist/docs/typings/angular2/angular2.d.ts"/> ///<reference path="../dist/docs/typings/angular2/router.d.ts"/> import {Component, bootstrap, View} from 'angular2/angular2'; import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from 'angular2/router'; @Component({ selector: 'my-app' }) @View({ template: '<h1>Hello</h1>', }) class FooCmp { constructor(a: string, b: number) {} } @Component({ selector: 'my-app' }) @View({ template: '<h1>Hello {{ name }}</h1><router-outlet></router-outlet>', directives: ROUTER_DIRECTIVES }) @RouteConfig([ {path: '/home', component: FooCmp} ]) class MyAppComponent { name: string; constructor() { this.name = 'Alice'; } } bootstrap(MyAppComponent, ROUTER_PROVIDERS);
typing_spec/router_spec.ts
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00016860145842656493, 0.00016611855244264007, 0.00016444097855128348, 0.0001657158718444407, 0.0000017483990859545884 ]
{ "id": 2, "code_window": [ "import {provide, Provider} from 'angular2/src/core/di';\n", "import {MockSchemaRegistry} from './schema_registry_mock';\n", "import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';\n", "import {XHR} from 'angular2/src/core/compiler/xhr';\n" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "add", "edit_start_line_idx": 3 }
library examples.src.web_workers.todo.background_index; import "index_common.dart" show TodoApp; import "dart:isolate"; import "package:angular2/src/web_workers/worker/application.dart" show bootstrapWebWorker; import "package:angular2/src/core/reflection/reflection_capabilities.dart"; import "package:angular2/src/core/reflection/reflection.dart"; main(List<String> args, SendPort replyTo) { reflector.reflectionCapabilities = new ReflectionCapabilities(); bootstrapWebWorker(replyTo, TodoApp).catchError((error) => throw error); }
modules/examples/src/web_workers/todo/background_index.dart
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00017519260291010141, 0.00016891563427634537, 0.00016263866564258933, 0.00016891563427634537, 0.0000062769686337560415 ]
{ "id": 3, "code_window": [ "\n", "export var TEST_PROVIDERS =\n", " [provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export var TEST_PROVIDERS = [\n", " provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})}),\n", " provide(XHR, {asClass: MockXHR})\n", "];" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "replace", "edit_start_line_idx": 4 }
import {provide, Provider} from 'angular2/src/core/di'; import {MockSchemaRegistry} from './schema_registry_mock'; import {ElementSchemaRegistry} from 'angular2/src/core/compiler/schema/element_schema_registry'; export var TEST_PROVIDERS = [provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];
modules/angular2/test/core/compiler/test_bindings.ts
1
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.998551070690155, 0.998551070690155, 0.998551070690155, 0.998551070690155, 0 ]
{ "id": 3, "code_window": [ "\n", "export var TEST_PROVIDERS =\n", " [provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export var TEST_PROVIDERS = [\n", " provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})}),\n", " provide(XHR, {asClass: MockXHR})\n", "];" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "replace", "edit_start_line_idx": 4 }
import { afterEach, AsyncTestCompleter, beforeEach, ddescribe, describe, expect, iit, inject, it, xit, } from 'angular2/test_lib'; import {PromiseWrapper} from 'angular2/src/core/facade/async'; import {Json, isBlank} from 'angular2/src/core/facade/lang'; import { WebDriverExtension, ChromeDriverExtension, WebDriverAdapter, Injector, bind, provide, Options } from 'benchpress/common'; import {TraceEventFactory} from '../trace_event_factory'; export function main() { describe('chrome driver extension', () => { var CHROME44_USER_AGENT = '"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.0 Safari/537.36"'; var CHROME45_USER_AGENT = '"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2499.0 Safari/537.36"'; var log; var extension; var blinkEvents = new TraceEventFactory('blink.console', 'pid0'); var v8Events = new TraceEventFactory('v8', 'pid0'); var v8EventsOtherProcess = new TraceEventFactory('v8', 'pid1'); var chromeTimelineEvents = new TraceEventFactory('disabled-by-default-devtools.timeline', 'pid0'); var chrome45TimelineEvents = new TraceEventFactory('devtools.timeline', 'pid0'); var chromeTimelineV8Events = new TraceEventFactory('devtools.timeline,v8', 'pid0'); var chromeBlinkTimelineEvents = new TraceEventFactory('blink,devtools.timeline', 'pid0'); var benchmarkEvents = new TraceEventFactory('benchmark', 'pid0'); var normEvents = new TraceEventFactory('timeline', 'pid0'); function createExtension(perfRecords = null, userAgent = null, messageMethod = 'Tracing.dataCollected') { if (isBlank(perfRecords)) { perfRecords = []; } if (isBlank(userAgent)) { userAgent = CHROME44_USER_AGENT; } log = []; extension = Injector.resolveAndCreate([ ChromeDriverExtension.BINDINGS, bind(WebDriverAdapter) .toValue(new MockDriverAdapter(log, perfRecords, messageMethod)), bind(Options.USER_AGENT).toValue(userAgent) ]) .get(ChromeDriverExtension); return extension; } it('should force gc via window.gc()', inject([AsyncTestCompleter], (async) => { createExtension().gc().then((_) => { expect(log).toEqual([['executeScript', 'window.gc()']]); async.done(); }); })); it('should mark the timeline via console.time()', inject([AsyncTestCompleter], (async) => { createExtension() .timeBegin('someName') .then((_) => { expect(log).toEqual([['executeScript', `console.time('someName');`]]); async.done(); }); })); it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => { createExtension() .timeEnd('someName') .then((_) => { expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); async.done(); }); })); it('should mark the timeline via console.time() and console.timeEnd()', inject([AsyncTestCompleter], (async) => { createExtension() .timeEnd('name1', 'name2') .then((_) => { expect(log) .toEqual([['executeScript', `console.timeEnd('name1');console.time('name2');`]]); async.done(); }); })); describe('readPerfLog Chrome44', () => { it('should normalize times to ms and forward ph and pid event properties', inject([AsyncTestCompleter], (async) => { createExtension([chromeTimelineEvents.complete('FunctionCall', 1100, 5500, null)]) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.complete('script', 1.1, 5.5, null), ]); async.done(); }); })); it('should normalize "tdur" to "dur"', inject([AsyncTestCompleter], (async) => { var event = chromeTimelineEvents.create('X', 'FunctionCall', 1100, null); event['tdur'] = 5500; createExtension([event]).readPerfLog().then((events) => { expect(events).toEqual([ normEvents.complete('script', 1.1, 5.5, null), ]); async.done(); }); })); it('should report FunctionCall events as "script"', inject([AsyncTestCompleter], (async) => { createExtension([chromeTimelineEvents.start('FunctionCall', 0)]) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('script', 0), ]); async.done(); }); })); it('should report gc', inject([AsyncTestCompleter], (async) => { createExtension([ chromeTimelineEvents.start('GCEvent', 1000, {'usedHeapSizeBefore': 1000}), chromeTimelineEvents.end('GCEvent', 2000, {'usedHeapSizeAfter': 0}), ]) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('gc', 1.0, {'usedHeapSize': 1000}), normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': false}), ]); async.done(); }); })); it('should ignore major gc from different processes', inject([AsyncTestCompleter], (async) => { createExtension([ chromeTimelineEvents.start('GCEvent', 1000, {'usedHeapSizeBefore': 1000}), v8EventsOtherProcess.start('majorGC', 1100, null), v8EventsOtherProcess.end('majorGC', 1200, null), chromeTimelineEvents.end('GCEvent', 2000, {'usedHeapSizeAfter': 0}), ]) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('gc', 1.0, {'usedHeapSize': 1000}), normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': false}), ]); async.done(); }); })); it('should report major gc', inject([AsyncTestCompleter], (async) => { createExtension([ chromeTimelineEvents.start('GCEvent', 1000, {'usedHeapSizeBefore': 1000}), v8Events.start('majorGC', 1100, null), v8Events.end('majorGC', 1200, null), chromeTimelineEvents.end('GCEvent', 2000, {'usedHeapSizeAfter': 0}), ]) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('gc', 1.0, {'usedHeapSize': 1000}), normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': true}), ]); async.done(); }); })); ['RecalculateStyles', 'Layout', 'UpdateLayerTree', 'Paint'].forEach((recordType) => { it(`should report ${recordType} as "render"`, inject([AsyncTestCompleter], (async) => { createExtension([ chromeTimelineEvents.start(recordType, 1234), chromeTimelineEvents.end(recordType, 2345) ]) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('render', 1.234), normEvents.end('render', 2.345), ]); async.done(); }); })); }); it('should ignore FunctionCalls from webdriver', inject([AsyncTestCompleter], (async) => { createExtension([ chromeTimelineEvents.start('FunctionCall', 0, {'data': {'scriptName': 'InjectedScript'}}) ]) .readPerfLog() .then((events) => { expect(events).toEqual([]); async.done(); }); })); }); describe('readPerfLog Chrome45', () => { it('should normalize times to ms and forward ph and pid event properties', inject([AsyncTestCompleter], (async) => { createExtension([chromeTimelineV8Events.complete('FunctionCall', 1100, 5500, null)], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.complete('script', 1.1, 5.5, null), ]); async.done(); }); })); it('should normalize "tdur" to "dur"', inject([AsyncTestCompleter], (async) => { var event = chromeTimelineV8Events.create('X', 'FunctionCall', 1100, null); event['tdur'] = 5500; createExtension([event], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.complete('script', 1.1, 5.5, null), ]); async.done(); }); })); it('should report FunctionCall events as "script"', inject([AsyncTestCompleter], (async) => { createExtension([chromeTimelineV8Events.start('FunctionCall', 0)], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('script', 0), ]); async.done(); }); })); it('should report minor gc', inject([AsyncTestCompleter], (async) => { createExtension( [ chromeTimelineV8Events.start('MinorGC', 1000, {'usedHeapSizeBefore': 1000}), chromeTimelineV8Events.end('MinorGC', 2000, {'usedHeapSizeAfter': 0}), ], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events.length).toEqual(2); expect(events[0]).toEqual( normEvents.start('gc', 1.0, {'usedHeapSize': 1000, 'majorGc': false})); expect(events[1]) .toEqual(normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': false})); async.done(); }); })); it('should report major gc', inject([AsyncTestCompleter], (async) => { createExtension( [ chromeTimelineV8Events.start('MajorGC', 1000, {'usedHeapSizeBefore': 1000}), chromeTimelineV8Events.end('MajorGC', 2000, {'usedHeapSizeAfter': 0}), ], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events.length).toEqual(2); expect(events[0]) .toEqual(normEvents.start('gc', 1.0, {'usedHeapSize': 1000, 'majorGc': true})); expect(events[1]) .toEqual(normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': true})); async.done(); }); })); ['Layout', 'UpdateLayerTree', 'Paint'].forEach((recordType) => { it(`should report ${recordType} as "render"`, inject([AsyncTestCompleter], (async) => { createExtension( [ chrome45TimelineEvents.start(recordType, 1234), chrome45TimelineEvents.end(recordType, 2345) ], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('render', 1.234), normEvents.end('render', 2.345), ]); async.done(); }); })); }); it(`should report UpdateLayoutTree as "render"`, inject([AsyncTestCompleter], (async) => { createExtension( [ chromeBlinkTimelineEvents.start('UpdateLayoutTree', 1234), chromeBlinkTimelineEvents.end('UpdateLayoutTree', 2345) ], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('render', 1.234), normEvents.end('render', 2.345), ]); async.done(); }); })); it('should ignore FunctionCalls from webdriver', inject([AsyncTestCompleter], (async) => { createExtension([ chromeTimelineV8Events.start('FunctionCall', 0, {'data': {'scriptName': 'InjectedScript'}}) ]) .readPerfLog() .then((events) => { expect(events).toEqual([]); async.done(); }); })); it('should ignore FunctionCalls with empty scriptName', inject([AsyncTestCompleter], (async) => { createExtension( [chromeTimelineV8Events.start('FunctionCall', 0, {'data': {'scriptName': ''}})]) .readPerfLog() .then((events) => { expect(events).toEqual([]); async.done(); }); })); }); describe('readPerfLog (common)', () => { it('should execute a dummy script before reading them', inject([AsyncTestCompleter], (async) => { // TODO(tbosch): This seems to be a bug in ChromeDriver: // Sometimes it does not report the newest events of the performance log // to the WebDriver client unless a script is executed... createExtension([]).readPerfLog().then((_) => { expect(log).toEqual([['executeScript', '1+1'], ['logs', 'performance']]); async.done(); }); })); ['Rasterize', 'CompositeLayers'].forEach((recordType) => { it(`should report ${recordType} as "render"`, inject([AsyncTestCompleter], (async) => { createExtension( [ chromeTimelineEvents.start(recordType, 1234), chromeTimelineEvents.end(recordType, 2345) ], CHROME45_USER_AGENT) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.start('render', 1.234), normEvents.end('render', 2.345), ]); async.done(); }); })); }); describe('frame metrics', () => { it('should report ImplThreadRenderingStats as frame event', inject([AsyncTestCompleter], (async) => { createExtension([ benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {'data': {'frame_count': 1}}) ]) .readPerfLog() .then((events) => { expect(events).toEqual([ normEvents.create('i', 'frame', 1.1), ]); async.done(); }); })); it('should not report ImplThreadRenderingStats with zero frames', inject([AsyncTestCompleter], (async) => { createExtension([ benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {'data': {'frame_count': 0}}) ]) .readPerfLog() .then((events) => { expect(events).toEqual([]); async.done(); }); })); it('should throw when ImplThreadRenderingStats contains more than one frame', inject([AsyncTestCompleter], (async) => { PromiseWrapper.catchError( createExtension([ benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {'data': {'frame_count': 2}}) ]).readPerfLog(), (err) => { expect(() => { throw err; }) .toThrowError('multi-frame render stats not supported'); async.done(); }); })); }); it('should report begin timestamps', inject([AsyncTestCompleter], (async) => { createExtension([blinkEvents.create('S', 'someName', 1000)]) .readPerfLog() .then((events) => { expect(events).toEqual([normEvents.markStart('someName', 1.0)]); async.done(); }); })); it('should report end timestamps', inject([AsyncTestCompleter], (async) => { createExtension([blinkEvents.create('F', 'someName', 1000)]) .readPerfLog() .then((events) => { expect(events).toEqual([normEvents.markEnd('someName', 1.0)]); async.done(); }); })); it('should throw an error on buffer overflow', inject([AsyncTestCompleter], (async) => { PromiseWrapper.catchError( createExtension( [ chromeTimelineEvents.start('FunctionCall', 1234), ], CHROME45_USER_AGENT, 'Tracing.bufferUsage') .readPerfLog(), (err) => { expect(() => { throw err; }) .toThrowError('The DevTools trace buffer filled during the test!'); async.done(); }); })); it('should match chrome browsers', () => { expect(createExtension().supports({'browserName': 'chrome'})).toBe(true); expect(createExtension().supports({'browserName': 'Chrome'})).toBe(true); }); }); }); } class MockDriverAdapter extends WebDriverAdapter { constructor(private _log: any[], private _events: any[], private _messageMethod: string) { super(); } executeScript(script) { this._log.push(['executeScript', script]); return PromiseWrapper.resolve(null); } logs(type) { this._log.push(['logs', type]); if (type === 'performance') { return PromiseWrapper.resolve(this._events.map((event) => { return { 'message': Json.stringify({'message': {'method': this._messageMethod, 'params': event}}) }; })); } else { return null; } } }
modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00047779441229067743, 0.0001859402982518077, 0.00016627484001219273, 0.00017101768753491342, 0.00005589185093413107 ]
{ "id": 3, "code_window": [ "\n", "export var TEST_PROVIDERS =\n", " [provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export var TEST_PROVIDERS = [\n", " provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})}),\n", " provide(XHR, {asClass: MockXHR})\n", "];" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "replace", "edit_start_line_idx": 4 }
'use strict'; describe('navigation', function () { var elt, $compile, $rootScope, $router, $compileProvider; beforeEach(function () { module('ng'); module('ngComponentRouter'); module(function (_$compileProvider_) { $compileProvider = _$compileProvider_; }); inject(function (_$compile_, _$rootScope_, _$router_) { $compile = _$compile_; $rootScope = _$rootScope_; $router = _$router_; }); registerComponent('userCmp', { template: '<div>hello {{userCmp.$routeParams.name}}</div>' }); registerComponent('oneCmp', { template: '<div>{{oneCmp.number}}</div>', controller: function () {this.number = 'one'} }); registerComponent('twoCmp', { template: '<div>{{twoCmp.number}}</div>', controller: function () {this.number = 'two'} }); }); it('should work in a simple case', function () { compile('<ng-outlet></ng-outlet>'); $router.config([ { path: '/', component: 'oneCmp' } ]); $router.navigateByUrl('/'); $rootScope.$digest(); expect(elt.text()).toBe('one'); }); it('should navigate between components with different parameters', function () { $router.config([ { path: '/user/:name', component: 'userCmp' } ]); compile('<ng-outlet></ng-outlet>'); $router.navigateByUrl('/user/brian'); $rootScope.$digest(); expect(elt.text()).toBe('hello brian'); $router.navigateByUrl('/user/igor'); $rootScope.$digest(); expect(elt.text()).toBe('hello igor'); }); it('should reuse a parent when navigating between child components with different parameters', function () { var instanceCount = 0; function ParentController() { instanceCount += 1; } registerComponent('parentCmp', { template: 'parent { <ng-outlet></ng-outlet> }', $routeConfig: [ { path: '/user/:name', component: 'userCmp' } ], controller: ParentController }); $router.config([ { path: '/parent/...', component: 'parentCmp' } ]); compile('<ng-outlet></ng-outlet>'); $router.navigateByUrl('/parent/user/brian'); $rootScope.$digest(); expect(instanceCount).toBe(1); expect(elt.text()).toBe('parent { hello brian }'); $router.navigateByUrl('/parent/user/igor'); $rootScope.$digest(); expect(instanceCount).toBe(1); expect(elt.text()).toBe('parent { hello igor }'); }); it('should work with nested outlets', function () { registerComponent('childCmp', { template: '<div>inner { <div ng-outlet></div> }</div>', $routeConfig: [ { path: '/b', component: 'oneCmp' } ] }); $router.config([ { path: '/a/...', component: 'childCmp' } ]); compile('<div>outer { <div ng-outlet></div> }</div>'); $router.navigateByUrl('/a/b'); $rootScope.$digest(); expect(elt.text()).toBe('outer { inner { one } }'); }); // TODO: fix this xit('should work with recursive nested outlets', function () { registerComponent('recurCmp', { template: '<div>recur { <div ng-outlet></div> }</div>', $routeConfig: [ { path: '/recur', component: 'recurCmp' }, { path: '/end', component: 'oneCmp' } ]}); $router.config([ { path: '/recur', component: 'recurCmp' }, { path: '/', component: 'oneCmp' } ]); compile('<div>root { <div ng-outlet></div> }</div>'); $router.navigateByUrl('/recur/recur/end'); $rootScope.$digest(); expect(elt.text()).toBe('root { one }'); }); it('should change location path', inject(function ($location) { $router.config([ { path: '/user', component: 'userCmp' } ]); compile('<div ng-outlet></div>'); $router.navigateByUrl('/user'); $rootScope.$digest(); expect($location.path()).toBe('/user'); })); it('should change location to the canonical route', inject(function ($location) { compile('<div ng-outlet></div>'); $router.config([ { path: '/', redirectTo: '/user' }, { path: '/user', component: 'userCmp' } ]); $router.navigateByUrl('/'); $rootScope.$digest(); expect($location.path()).toBe('/user'); })); it('should change location to the canonical route with nested components', inject(function ($location) { registerComponent('childRouter', { template: '<div>inner { <div ng-outlet></div> }</div>', $routeConfig: [ { path: '/old-child', redirectTo: '/new-child' }, { path: '/new-child', component: 'oneCmp'}, { path: '/old-child-two', redirectTo: '/new-child-two' }, { path: '/new-child-two', component: 'twoCmp'} ] }); $router.config([ { path: '/old-parent', redirectTo: '/new-parent' }, { path: '/new-parent/...', component: 'childRouter' } ]); compile('<div ng-outlet></div>'); $router.navigateByUrl('/old-parent/old-child'); $rootScope.$digest(); expect($location.path()).toBe('/new-parent/new-child'); expect(elt.text()).toBe('inner { one }'); $router.navigateByUrl('/old-parent/old-child-two'); $rootScope.$digest(); expect($location.path()).toBe('/new-parent/new-child-two'); expect(elt.text()).toBe('inner { two }'); })); it('should navigate when the location path changes', inject(function ($location) { $router.config([ { path: '/one', component: 'oneCmp' } ]); compile('<div ng-outlet></div>'); $location.path('/one'); $rootScope.$digest(); expect(elt.text()).toBe('one'); })); it('should expose a "navigating" property on $router', inject(function ($q) { var defer; registerComponent('pendingActivate', { $canActivate: function () { defer = $q.defer(); return defer.promise; } }); $router.config([ { path: '/pending-activate', component: 'pendingActivate' } ]); compile('<div ng-outlet></div>'); $router.navigateByUrl('/pending-activate'); $rootScope.$digest(); expect($router.navigating).toBe(true); defer.resolve(); $rootScope.$digest(); expect($router.navigating).toBe(false); })); function registerComponent(name, options) { var controller = options.controller || function () {}; ['$onActivate', '$onDeactivate', '$onReuse', '$canReuse', '$canDeactivate'].forEach(function (hookName) { if (options[hookName]) { controller.prototype[hookName] = options[hookName]; } }); function factory() { return { template: options.template || '', controllerAs: name, controller: controller }; } if (options.$canActivate) { factory.$canActivate = options.$canActivate; } if (options.$routeConfig) { factory.$routeConfig = options.$routeConfig; } $compileProvider.directive(name, factory); } function compile(template) { elt = $compile('<div>' + template + '</div>')($rootScope); $rootScope.$digest(); return elt; } });
modules/angular1_router/test/integration/navigation_spec.js
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00017449240840505809, 0.00017048890003934503, 0.0001662409194977954, 0.00017057699733413756, 0.00000203913327823102 ]
{ "id": 3, "code_window": [ "\n", "export var TEST_PROVIDERS =\n", " [provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})})];\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export var TEST_PROVIDERS = [\n", " provide(ElementSchemaRegistry, {asValue: new MockSchemaRegistry({}, {})}),\n", " provide(XHR, {asClass: MockXHR})\n", "];" ], "file_path": "modules/angular2/test/core/compiler/test_bindings.ts", "type": "replace", "edit_start_line_idx": 4 }
<!doctype html> <html> <body> <h2>Params</h2> <form> Iterations: <input type="number" name="iterations" placeholder="iterations" value="20000"> <br> <button>Apply</button> </form> <h2>Actions</h2> <p> <button id="instantiate">instantiate</button> <button id="hydrate">hydrate</button> </p> $SCRIPTS$ </body> </html>
modules/benchmarks/src/element_injector/element_injector_benchmark.html
0
https://github.com/angular/angular/commit/6abed8d996168f695e638c0c2d0fde1ad7ae273c
[ 0.00017706748622003943, 0.0001727227499941364, 0.0001700239081401378, 0.00017107689927797765, 0.000003102112486885744 ]
{ "id": 0, "code_window": [ "\tborder-bottom-left-radius: 2px;\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "\tcursor: text;\n", "}\n", "\n", ".monaco-editor .interactive-editor .monaco-editor-background {\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "}\n", "\n", ".monaco-editor .interactive-editor .body .content .input .editor-placeholder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ ".monaco-editor .interactive-editor .body .content .input .monaco-editor-background {\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0006969469250179827, 0.00019615057681221515, 0.00016160804079845548, 0.0001707191113382578, 0.0001056365726981312 ]
{ "id": 0, "code_window": [ "\tborder-bottom-left-radius: 2px;\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "\tcursor: text;\n", "}\n", "\n", ".monaco-editor .interactive-editor .monaco-editor-background {\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "}\n", "\n", ".monaco-editor .interactive-editor .body .content .input .editor-placeholder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ ".monaco-editor .interactive-editor .body .content .input .monaco-editor-background {\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { assertNever } from 'vs/base/common/assert'; import { URI } from 'vs/base/common/uri'; export const TEST_DATA_SCHEME = 'vscode-test-data'; export const enum TestUriType { AllOutput, ResultMessage, ResultActualOutput, ResultExpectedOutput, } interface IAllOutputReference { type: TestUriType.AllOutput; resultId: string; } interface IResultTestUri { resultId: string; taskIndex: number; testExtId: string; } interface IResultTestMessageReference extends IResultTestUri { type: TestUriType.ResultMessage; messageIndex: number; } interface IResultTestOutputReference extends IResultTestUri { type: TestUriType.ResultActualOutput | TestUriType.ResultExpectedOutput; messageIndex: number; } export type ParsedTestUri = | IAllOutputReference | IResultTestMessageReference | IResultTestOutputReference; const enum TestUriParts { Results = 'results', AllOutput = 'output', Messages = 'message', Text = 'TestFailureMessage', ActualOutput = 'ActualOutput', ExpectedOutput = 'ExpectedOutput', } export const parseTestUri = (uri: URI): ParsedTestUri | undefined => { const type = uri.authority; const [locationId, ...request] = uri.path.slice(1).split('/'); if (request[0] === TestUriParts.Messages) { const taskIndex = Number(request[1]); const index = Number(request[2]); const part = request[3]; const testExtId = uri.query; if (type === TestUriParts.Results) { switch (part) { case TestUriParts.Text: return { resultId: locationId, taskIndex, testExtId, messageIndex: index, type: TestUriType.ResultMessage }; case TestUriParts.ActualOutput: return { resultId: locationId, taskIndex, testExtId, messageIndex: index, type: TestUriType.ResultActualOutput }; case TestUriParts.ExpectedOutput: return { resultId: locationId, taskIndex, testExtId, messageIndex: index, type: TestUriType.ResultExpectedOutput }; } } } if (request[0] === TestUriParts.AllOutput) { return { resultId: locationId, type: TestUriType.AllOutput }; } return undefined; }; export const buildTestUri = (parsed: ParsedTestUri): URI => { if (parsed.type === TestUriType.AllOutput) { return URI.from({ scheme: TEST_DATA_SCHEME, authority: TestUriParts.Results, path: ['', parsed.resultId, TestUriParts.AllOutput].join('/'), }); } const uriParts = { scheme: TEST_DATA_SCHEME, authority: TestUriParts.Results }; const msgRef = (locationId: string, ...remaining: (string | number)[]) => URI.from({ ...uriParts, query: parsed.testExtId, path: ['', locationId, TestUriParts.Messages, ...remaining].join('/'), }); switch (parsed.type) { case TestUriType.ResultActualOutput: return msgRef(parsed.resultId, parsed.taskIndex, parsed.messageIndex, TestUriParts.ActualOutput); case TestUriType.ResultExpectedOutput: return msgRef(parsed.resultId, parsed.taskIndex, parsed.messageIndex, TestUriParts.ExpectedOutput); case TestUriType.ResultMessage: return msgRef(parsed.resultId, parsed.taskIndex, parsed.messageIndex, TestUriParts.Text); default: assertNever(parsed, 'Invalid test uri'); } };
src/vs/workbench/contrib/testing/common/testingUri.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017723150085657835, 0.00017361195932608098, 0.0001699944114079699, 0.0001736890699248761, 0.0000023398638404614758 ]
{ "id": 0, "code_window": [ "\tborder-bottom-left-radius: 2px;\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "\tcursor: text;\n", "}\n", "\n", ".monaco-editor .interactive-editor .monaco-editor-background {\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "}\n", "\n", ".monaco-editor .interactive-editor .body .content .input .editor-placeholder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ ".monaco-editor .interactive-editor .body .content .input .monaco-editor-background {\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "replace", "edit_start_line_idx": 39 }
{ "name": "Ignore", "scopeName": "source.ignore", "patterns": [ { "match": "^#.*", "name": "comment.line.number-sign.ignore" } ] }
extensions/git-base/syntaxes/ignore.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001755924749886617, 0.00017283682245761156, 0.0001700811553746462, 0.00017283682245761156, 0.00000275565980700776 ]
{ "id": 0, "code_window": [ "\tborder-bottom-left-radius: 2px;\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "\tcursor: text;\n", "}\n", "\n", ".monaco-editor .interactive-editor .monaco-editor-background {\n", "\tbackground-color: var(--vscode-interactiveEditorInput-background);\n", "}\n", "\n", ".monaco-editor .interactive-editor .body .content .input .editor-placeholder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ ".monaco-editor .interactive-editor .body .content .input .monaco-editor-background {\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * 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 { FileAccess } from 'vs/base/common/network'; import { LanguageService } from 'vs/editor/common/services/languageService'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { GettingStartedDetailsRenderer } from 'vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedDetailsRenderer'; import { convertInternalMediaPathToFileURI } from 'vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedService'; import { TestFileService } from 'vs/workbench/test/browser/workbenchTestServices'; import { TestExtensionService } from 'vs/workbench/test/common/workbenchTestServices'; suite('Getting Started Markdown Renderer', () => { test('renders theme picker markdown with images', async () => { const fileService = new TestFileService(); const languageService = new LanguageService(); const renderer = new GettingStartedDetailsRenderer(fileService, new TestNotificationService(), new TestExtensionService(), languageService); const mdPath = convertInternalMediaPathToFileURI('theme_picker').with({ query: JSON.stringify({ moduleId: 'vs/workbench/contrib/welcomeGettingStarted/common/media/theme_picker' }) }); const mdBase = FileAccess.asFileUri('vs/workbench/contrib/welcomeGettingStarted/common/media/'); const rendered = await renderer.renderMarkdown(mdPath, mdBase); const imageSrcs = [...rendered.matchAll(/img src="[^"]*"/g)].map(match => match[0]); for (const src of imageSrcs) { const targetSrcFormat = /^img src="https:\/\/file\+.vscode-resource.vscode-cdn.net\/.*\/vs\/workbench\/contrib\/welcomeGettingStarted\/common\/media\/.*.png"$/; assert(targetSrcFormat.test(src), `${src} didnt match regex`); } languageService.dispose(); }); });
src/vs/workbench/contrib/welcomeGettingStarted/test/browser/gettingStartedMarkdownRenderer.test.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017559918342158198, 0.00017315456352662295, 0.0001697592088021338, 0.000173629930941388, 0.0000021345804270822555 ]
{ "id": 1, "code_window": [ ".monaco-editor .interactive-editor-diff-widget {\n", "\tpadding: 6px 0;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor-background,\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor .margin-view-overlays {\n", "\tbackground-color: var(--vscode-interactiveEditor-regionHighlight);\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "add", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.007428804412484169, 0.0008013565093278885, 0.00016543919628020376, 0.00025942266802303493, 0.0017008408904075623 ]
{ "id": 1, "code_window": [ ".monaco-editor .interactive-editor-diff-widget {\n", "\tpadding: 6px 0;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor-background,\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor .margin-view-overlays {\n", "\tbackground-color: var(--vscode-interactiveEditor-regionHighlight);\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "add", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path="../../../typings/require.d.ts" /> //@ts-check (function () { 'use strict'; /** * @param {typeof import('path')} path * @param {typeof import('fs')} fs * @param {typeof import('../common/performance')} perf */ function factory(path, fs, perf) { /** * @param {string} file * @returns {Promise<boolean>} */ function exists(file) { return new Promise(c => fs.exists(file, c)); } /** * @param {string} file * @returns {Promise<void>} */ function touch(file) { return new Promise((c, e) => { const d = new Date(); fs.utimes(file, d, d, err => err ? e(err) : c()); }); } /** * @param {string} dir * @returns {Promise<string>} */ function mkdirp(dir) { return new Promise((c, e) => fs.mkdir(dir, { recursive: true }, err => (err && err.code !== 'EEXIST') ? e(err) : c(dir))); } /** * @param {string} location * @returns {Promise<void>} */ function rimraf(location) { return new Promise((c, e) => fs.rm(location, { recursive: true, force: true, maxRetries: 3 }, err => err ? e(err) : c())); } /** * @param {string} file * @returns {Promise<string>} */ function readFile(file) { return new Promise((c, e) => fs.readFile(file, 'utf8', (err, data) => err ? e(err) : c(data))); } /** * @param {string} file * @param {string} content * @returns {Promise<void>} */ function writeFile(file, content) { return new Promise((c, e) => fs.writeFile(file, content, 'utf8', err => err ? e(err) : c())); } /** * @param {string} userDataPath * @returns {Promise<object | undefined>} */ async function getLanguagePackConfigurations(userDataPath) { const configFile = path.join(userDataPath, 'languagepacks.json'); try { return JSON.parse(await readFile(configFile)); } catch (err) { // Do nothing. If we can't read the file we have no // language pack config. } return undefined; } /** * @param {object} config * @param {string | undefined} locale */ function resolveLanguagePackLocale(config, locale) { try { while (locale) { if (config[locale]) { return locale; } else { const index = locale.lastIndexOf('-'); if (index > 0) { locale = locale.substring(0, index); } else { return undefined; } } } } catch (err) { console.error('Resolving language pack configuration failed.', err); } return undefined; } /** * @param {string | undefined} commit * @param {string} userDataPath * @param {string} metaDataFile * @param {string} locale * @param {string} osLocale * @returns {Promise<import('./languagePacks').NLSConfiguration>} */ function getNLSConfiguration(commit, userDataPath, metaDataFile, locale, osLocale) { const defaultResult = function (locale) { perf.mark('code/didGenerateNls'); return Promise.resolve({ locale, osLocale, availableLanguages: {} }); }; perf.mark('code/willGenerateNls'); if (locale === 'pseudo') { return Promise.resolve({ locale, osLocale, availableLanguages: {}, pseudo: true }); } if (process.env['VSCODE_DEV']) { return Promise.resolve({ locale, osLocale, availableLanguages: {} }); } // We have a built version so we have extracted nls file. Try to find // the right file to use. // Check if we have an English or English US locale. If so fall to default since that is our // English translation (we don't ship *.nls.en.json files) if (locale && (locale === 'en' || locale === 'en-us')) { return Promise.resolve({ locale, osLocale, availableLanguages: {} }); } const initialLocale = locale; try { if (!commit) { return defaultResult(initialLocale); } return getLanguagePackConfigurations(userDataPath).then(configs => { if (!configs) { return defaultResult(initialLocale); } const resolvedLocale = resolveLanguagePackLocale(configs, locale); if (!resolvedLocale) { return defaultResult(initialLocale); } locale = resolvedLocale; const packConfig = configs[locale]; let mainPack; if (!packConfig || typeof packConfig.hash !== 'string' || !packConfig.translations || typeof (mainPack = packConfig.translations['vscode']) !== 'string') { return defaultResult(initialLocale); } return exists(mainPack).then(fileExists => { if (!fileExists) { return defaultResult(initialLocale); } const packId = packConfig.hash + '.' + locale; const cacheRoot = path.join(userDataPath, 'clp', packId); const coreLocation = path.join(cacheRoot, commit); const translationsConfigFile = path.join(cacheRoot, 'tcf.json'); const corruptedFile = path.join(cacheRoot, 'corrupted.info'); const result = { locale: initialLocale, osLocale, availableLanguages: { '*': locale }, _languagePackId: packId, _translationsConfigFile: translationsConfigFile, _cacheRoot: cacheRoot, _resolvedLanguagePackCoreLocation: coreLocation, _corruptedFile: corruptedFile }; return exists(corruptedFile).then(corrupted => { // The nls cache directory is corrupted. let toDelete; if (corrupted) { toDelete = rimraf(cacheRoot); } else { toDelete = Promise.resolve(undefined); } return toDelete.then(() => { return exists(coreLocation).then(fileExists => { if (fileExists) { // We don't wait for this. No big harm if we can't touch touch(coreLocation).catch(() => { }); perf.mark('code/didGenerateNls'); return result; } return mkdirp(coreLocation).then(() => { return Promise.all([readFile(metaDataFile), readFile(mainPack)]); }).then(values => { const metadata = JSON.parse(values[0]); const packData = JSON.parse(values[1]).contents; const bundles = Object.keys(metadata.bundles); const writes = []; for (const bundle of bundles) { const modules = metadata.bundles[bundle]; const target = Object.create(null); for (const module of modules) { const keys = metadata.keys[module]; const defaultMessages = metadata.messages[module]; const translations = packData[module]; let targetStrings; if (translations) { targetStrings = []; for (let i = 0; i < keys.length; i++) { const elem = keys[i]; const key = typeof elem === 'string' ? elem : elem.key; let translatedMessage = translations[key]; if (translatedMessage === undefined) { translatedMessage = defaultMessages[i]; } targetStrings.push(translatedMessage); } } else { targetStrings = defaultMessages; } target[module] = targetStrings; } writes.push(writeFile(path.join(coreLocation, bundle.replace(/\//g, '!') + '.nls.json'), JSON.stringify(target))); } writes.push(writeFile(translationsConfigFile, JSON.stringify(packConfig.translations))); return Promise.all(writes); }).then(() => { perf.mark('code/didGenerateNls'); return result; }).catch(err => { console.error('Generating translation files failed.', err); return defaultResult(locale); }); }); }); }); }); }); } catch (err) { console.error('Generating translation files failed.', err); return defaultResult(locale); } } return { getNLSConfiguration }; } if (typeof define === 'function') { // amd define(['path', 'fs', 'vs/base/common/performance'], function (/** @type {typeof import('path')} */ path, /** @type {typeof import('fs')} */ fs, /** @type {typeof import('../common/performance')} */ perf) { return factory(path, fs, perf); }); } else if (typeof module === 'object' && typeof module.exports === 'object') { const path = require('path'); const fs = require('fs'); const perf = require('../common/performance'); module.exports = factory(path, fs, perf); } else { throw new Error('Unknown context'); } }());
src/vs/base/node/languagePacks.js
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001752611278789118, 0.0001703835732769221, 0.0001668186014285311, 0.00017008163558784872, 0.000001866235265879368 ]
{ "id": 1, "code_window": [ ".monaco-editor .interactive-editor-diff-widget {\n", "\tpadding: 6px 0;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor-background,\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor .margin-view-overlays {\n", "\tbackground-color: var(--vscode-interactiveEditor-regionHighlight);\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "add", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { assertIsDefined } from 'vs/base/common/types'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IProgressIndicator } from 'vs/platform/progress/common/progress'; import { PaneCompositeDescriptor } from 'vs/workbench/browser/panecomposite'; import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart'; import { AuxiliaryBarPart } from 'vs/workbench/browser/parts/auxiliarybar/auxiliaryBarPart'; import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart'; import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart'; import { IPaneComposite } from 'vs/workbench/common/panecomposite'; import { ViewContainerLocation, ViewContainerLocations } from 'vs/workbench/common/views'; import { IBadge } from 'vs/workbench/services/activity/common/activity'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { IView } from 'vs/base/browser/ui/grid/grid'; export interface IPaneCompositePart extends IView { readonly onDidPaneCompositeOpen: Event<IPaneComposite>; readonly onDidPaneCompositeClose: Event<IPaneComposite>; /** * Opens a viewlet with the given identifier and pass keyboard focus to it if specified. */ openPaneComposite(id: string | undefined, focus?: boolean): Promise<IPaneComposite | undefined>; /** * Returns the current active viewlet if any. */ getActivePaneComposite(): IPaneComposite | undefined; /** * Returns the viewlet by id. */ getPaneComposite(id: string): PaneCompositeDescriptor | undefined; /** * Returns all enabled viewlets */ getPaneComposites(): PaneCompositeDescriptor[]; /** * Returns the progress indicator for the side bar. */ getProgressIndicator(id: string): IProgressIndicator | undefined; /** * Hide the active viewlet. */ hideActivePaneComposite(): void; /** * Return the last active viewlet id. */ getLastActivePaneCompositeId(): string; } export interface IPaneCompositeSelectorPart { /** * Returns id of pinned view containers following the visual order. */ getPinnedPaneCompositeIds(): string[]; /** * Returns id of visible view containers following the visual order. */ getVisiblePaneCompositeIds(): string[]; /** * Show an activity in a viewlet. */ showActivity(id: string, badge: IBadge, clazz?: string, priority?: number): IDisposable; } export class PaneCompositeParts extends Disposable implements IPaneCompositePartService { declare readonly _serviceBrand: undefined; readonly onDidPaneCompositeOpen: Event<{ composite: IPaneComposite; viewContainerLocation: ViewContainerLocation }>; readonly onDidPaneCompositeClose: Event<{ composite: IPaneComposite; viewContainerLocation: ViewContainerLocation }>; private readonly paneCompositeParts = new Map<ViewContainerLocation, IPaneCompositePart>(); private readonly paneCompositeSelectorParts = new Map<ViewContainerLocation, IPaneCompositeSelectorPart>(); constructor(@IInstantiationService instantiationService: IInstantiationService) { super(); const panelPart = instantiationService.createInstance(PanelPart); const sideBarPart = instantiationService.createInstance(SidebarPart); const auxiliaryBarPart = instantiationService.createInstance(AuxiliaryBarPart); const activityBarPart = instantiationService.createInstance(ActivitybarPart, sideBarPart); this.paneCompositeParts.set(ViewContainerLocation.Panel, panelPart); this.paneCompositeParts.set(ViewContainerLocation.Sidebar, sideBarPart); this.paneCompositeParts.set(ViewContainerLocation.AuxiliaryBar, auxiliaryBarPart); this.paneCompositeSelectorParts.set(ViewContainerLocation.Panel, panelPart); this.paneCompositeSelectorParts.set(ViewContainerLocation.Sidebar, activityBarPart); this.paneCompositeSelectorParts.set(ViewContainerLocation.AuxiliaryBar, auxiliaryBarPart); const eventDisposables = this._register(new DisposableStore()); this.onDidPaneCompositeOpen = Event.any(...ViewContainerLocations.map(loc => Event.map(this.paneCompositeParts.get(loc)!.onDidPaneCompositeOpen, composite => { return { composite, viewContainerLocation: loc }; }, eventDisposables))); this.onDidPaneCompositeClose = Event.any(...ViewContainerLocations.map(loc => Event.map(this.paneCompositeParts.get(loc)!.onDidPaneCompositeClose, composite => { return { composite, viewContainerLocation: loc }; }, eventDisposables))); } openPaneComposite(id: string | undefined, viewContainerLocation: ViewContainerLocation, focus?: boolean): Promise<IPaneComposite | undefined> { return this.getPartByLocation(viewContainerLocation).openPaneComposite(id, focus); } getActivePaneComposite(viewContainerLocation: ViewContainerLocation): IPaneComposite | undefined { return this.getPartByLocation(viewContainerLocation).getActivePaneComposite(); } getPaneComposite(id: string, viewContainerLocation: ViewContainerLocation): PaneCompositeDescriptor | undefined { return this.getPartByLocation(viewContainerLocation).getPaneComposite(id); } getPaneComposites(viewContainerLocation: ViewContainerLocation): PaneCompositeDescriptor[] { return this.getPartByLocation(viewContainerLocation).getPaneComposites(); } getPinnedPaneCompositeIds(viewContainerLocation: ViewContainerLocation): string[] { return this.getSelectorPartByLocation(viewContainerLocation).getPinnedPaneCompositeIds(); } getVisiblePaneCompositeIds(viewContainerLocation: ViewContainerLocation): string[] { return this.getSelectorPartByLocation(viewContainerLocation).getVisiblePaneCompositeIds(); } getProgressIndicator(id: string, viewContainerLocation: ViewContainerLocation): IProgressIndicator | undefined { return this.getPartByLocation(viewContainerLocation).getProgressIndicator(id); } hideActivePaneComposite(viewContainerLocation: ViewContainerLocation): void { this.getPartByLocation(viewContainerLocation).hideActivePaneComposite(); } getLastActivePaneCompositeId(viewContainerLocation: ViewContainerLocation): string { return this.getPartByLocation(viewContainerLocation).getLastActivePaneCompositeId(); } showActivity(id: string, viewContainerLocation: ViewContainerLocation, badge: IBadge, clazz?: string, priority?: number): IDisposable { return this.getSelectorPartByLocation(viewContainerLocation).showActivity(id, badge, clazz, priority); } private getPartByLocation(viewContainerLocation: ViewContainerLocation): IPaneCompositePart { return assertIsDefined(this.paneCompositeParts.get(viewContainerLocation)); } private getSelectorPartByLocation(viewContainerLocation: ViewContainerLocation): IPaneCompositeSelectorPart { return assertIsDefined(this.paneCompositeSelectorParts.get(viewContainerLocation)); } } registerSingleton(IPaneCompositePartService, PaneCompositeParts, InstantiationType.Delayed);
src/vs/workbench/browser/parts/paneCompositePart.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0011922686826437712, 0.0002403605030849576, 0.00016395891725551337, 0.00017297665181104094, 0.00023862389207351953 ]
{ "id": 1, "code_window": [ ".monaco-editor .interactive-editor-diff-widget {\n", "\tpadding: 6px 0;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor-background,\n", ".monaco-editor .interactive-editor-diff-widget .monaco-diff-editor .monaco-editor .margin-view-overlays {\n", "\tbackground-color: var(--vscode-interactiveEditor-regionHighlight);\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css", "type": "add", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * 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 { TextDecoder } from 'util'; import * as vscode from 'vscode'; import { asPromise, assertNoRpc, closeAllEditors, createRandomFile, DeferredPromise, disposeAll, revertAllDirty, saveAllEditors } from '../utils'; async function createRandomNotebookFile() { return createRandomFile('', undefined, '.vsctestnb'); } async function openRandomNotebookDocument() { const uri = await createRandomNotebookFile(); return vscode.workspace.openNotebookDocument(uri); } export async function saveAllFilesAndCloseAll() { await saveAllEditors(); await closeAllEditors(); } async function withEvent<T>(event: vscode.Event<T>, callback: (e: Promise<T>) => Promise<void>) { const e = asPromise<T>(event); await callback(e); } function sleep(ms: number): Promise<void> { return new Promise(resolve => { setTimeout(resolve, ms); }); } export class Kernel { readonly controller: vscode.NotebookController; readonly associatedNotebooks = new Set<string>(); constructor(id: string, label: string, viewType: string = 'notebookCoreTest') { this.controller = vscode.notebooks.createNotebookController(id, viewType, label); this.controller.executeHandler = this._execute.bind(this); this.controller.supportsExecutionOrder = true; this.controller.supportedLanguages = ['typescript', 'javascript']; this.controller.onDidChangeSelectedNotebooks(e => { if (e.selected) { this.associatedNotebooks.add(e.notebook.uri.toString()); } else { this.associatedNotebooks.delete(e.notebook.uri.toString()); } }); } protected async _execute(cells: vscode.NotebookCell[]): Promise<void> { for (const cell of cells) { await this._runCell(cell); } } protected async _runCell(cell: vscode.NotebookCell) { // create a single output with exec order 1 and output is plain/text // of either the cell itself or (iff empty) the cell's document's uri const task = this.controller.createNotebookCellExecution(cell); task.start(Date.now()); task.executionOrder = 1; await sleep(10); // Force to be take some time await task.replaceOutput([new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text(cell.document.getText() || cell.document.uri.toString(), 'text/plain') ])]); task.end(true); } } async function assertKernel(kernel: Kernel, notebook: vscode.NotebookDocument): Promise<void> { const success = await vscode.commands.executeCommand('notebook.selectKernel', { extension: 'vscode.vscode-api-tests', id: kernel.controller.id }); assert.ok(success, `expected selected kernel to be ${kernel.controller.id}`); assert.ok(kernel.associatedNotebooks.has(notebook.uri.toString())); } const apiTestSerializer: vscode.NotebookSerializer = { serializeNotebook(_data, _token) { return new Uint8Array(); }, deserializeNotebook(_content, _token) { const dto: vscode.NotebookData = { metadata: { custom: { testMetadata: false } }, cells: [ { value: 'test', languageId: 'typescript', kind: vscode.NotebookCellKind.Code, outputs: [], metadata: { custom: { testCellMetadata: 123 } }, executionSummary: { timing: { startTime: 10, endTime: 20 } } }, { value: 'test2', languageId: 'typescript', kind: vscode.NotebookCellKind.Code, outputs: [ new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text('Hello World', 'text/plain') ], { testOutputMetadata: true, ['text/plain']: { testOutputItemMetadata: true } }) ], executionSummary: { executionOrder: 5, success: true }, metadata: { custom: { testCellMetadata: 456 } } } ] }; return dto; } }; (vscode.env.uiKind === vscode.UIKind.Web ? suite.skip : suite)('Notebook Kernel API tests', function () { const testDisposables: vscode.Disposable[] = []; const suiteDisposables: vscode.Disposable[] = []; suiteTeardown(async function () { assertNoRpc(); await revertAllDirty(); await closeAllEditors(); disposeAll(suiteDisposables); suiteDisposables.length = 0; }); suiteSetup(() => { suiteDisposables.push(vscode.workspace.registerNotebookSerializer('notebookCoreTest', apiTestSerializer)); }); let defaultKernel: Kernel; setup(async function () { // there should be ONE default kernel in this suite defaultKernel = new Kernel('mainKernel', 'Notebook Default Kernel'); testDisposables.push(defaultKernel.controller); await saveAllFilesAndCloseAll(); }); teardown(async function () { disposeAll(testDisposables); testDisposables.length = 0; await saveAllFilesAndCloseAll(); }); test('cell execute command takes arguments', async () => { const notebook = await openRandomNotebookDocument(); await vscode.window.showNotebookDocument(notebook); assert.strictEqual(vscode.window.activeNotebookEditor !== undefined, true, 'notebook first'); const editor = vscode.window.activeNotebookEditor!; const cell = editor.notebook.cellAt(0); await withEvent(vscode.workspace.onDidChangeNotebookDocument, async event => { await vscode.commands.executeCommand('notebook.execute'); await event; assert.strictEqual(cell.outputs.length, 1, 'should execute'); // runnable, it worked }); await withEvent(vscode.workspace.onDidChangeNotebookDocument, async event => { await vscode.commands.executeCommand('notebook.cell.clearOutputs'); await event; assert.strictEqual(cell.outputs.length, 0, 'should clear'); }); const secondResource = await createRandomNotebookFile(); const secondDocument = await vscode.workspace.openNotebookDocument(secondResource); await vscode.window.showNotebookDocument(secondDocument); await withEvent<vscode.NotebookDocumentChangeEvent>(vscode.workspace.onDidChangeNotebookDocument, async event => { await vscode.commands.executeCommand('notebook.cell.execute', { start: 0, end: 1 }, notebook.uri); await event; assert.strictEqual(cell.outputs.length, 1, 'should execute'); // runnable, it worked assert.strictEqual(vscode.window.activeNotebookEditor?.notebook.uri.fsPath, secondResource.fsPath); }); }); test('cell execute command takes arguments 2', async () => { const notebook = await openRandomNotebookDocument(); await vscode.window.showNotebookDocument(notebook); let firstCellExecuted = false; let secondCellExecuted = false; const def = new DeferredPromise<void>(); testDisposables.push(vscode.workspace.onDidChangeNotebookDocument(e => { e.cellChanges.forEach(change => { if (change.cell.index === 0 && change.executionSummary) { firstCellExecuted = true; } if (change.cell.index === 1 && change.executionSummary) { secondCellExecuted = true; } }); if (firstCellExecuted && secondCellExecuted) { def.complete(); } })); vscode.commands.executeCommand('notebook.cell.execute', { document: notebook.uri, ranges: [{ start: 0, end: 1 }, { start: 1, end: 2 }] }); await def.p; await saveAllFilesAndCloseAll(); }); test('document execute command takes arguments', async () => { const notebook = await openRandomNotebookDocument(); await vscode.window.showNotebookDocument(notebook); assert.strictEqual(vscode.window.activeNotebookEditor !== undefined, true, 'notebook first'); const editor = vscode.window.activeNotebookEditor!; const cell = editor.notebook.cellAt(0); await withEvent<vscode.NotebookDocumentChangeEvent>(vscode.workspace.onDidChangeNotebookDocument, async (event) => { await vscode.commands.executeCommand('notebook.execute', notebook.uri); await event; assert.strictEqual(cell.outputs.length, 1, 'should execute'); // runnable, it worked }); }); test('cell execute and select kernel', async function () { const notebook = await openRandomNotebookDocument(); const editor = await vscode.window.showNotebookDocument(notebook); assert.strictEqual(vscode.window.activeNotebookEditor === editor, true, 'notebook first'); const cell = editor.notebook.cellAt(0); const alternativeKernel = new class extends Kernel { constructor() { super('secondaryKernel', 'Notebook Secondary Test Kernel'); this.controller.supportsExecutionOrder = false; } override async _runCell(cell: vscode.NotebookCell) { const task = this.controller.createNotebookCellExecution(cell); task.start(); await task.replaceOutput([new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text('my second output', 'text/plain') ])]); task.end(true); } }; testDisposables.push(alternativeKernel.controller); await withEvent<vscode.NotebookDocumentChangeEvent>(vscode.workspace.onDidChangeNotebookDocument, async (event) => { await assertKernel(defaultKernel, notebook); await vscode.commands.executeCommand('notebook.cell.execute'); await event; assert.strictEqual(cell.outputs.length, 1, 'should execute'); // runnable, it worked assert.strictEqual(cell.outputs[0].items.length, 1); assert.strictEqual(cell.outputs[0].items[0].mime, 'text/plain'); assert.deepStrictEqual(new TextDecoder().decode(cell.outputs[0].items[0].data), cell.document.getText()); }); await withEvent<vscode.NotebookDocumentChangeEvent>(vscode.workspace.onDidChangeNotebookDocument, async (event) => { await assertKernel(alternativeKernel, notebook); await vscode.commands.executeCommand('notebook.cell.execute'); await event; assert.strictEqual(cell.outputs.length, 1, 'should execute'); // runnable, it worked assert.strictEqual(cell.outputs[0].items.length, 1); assert.strictEqual(cell.outputs[0].items[0].mime, 'text/plain'); assert.deepStrictEqual(new TextDecoder().decode(cell.outputs[0].items[0].data), 'my second output'); }); }); test('onDidChangeCellExecutionState is fired', async () => { const notebook = await openRandomNotebookDocument(); const editor = await vscode.window.showNotebookDocument(notebook); const cell = editor.notebook.cellAt(0); let eventCount = 0; const def = new DeferredPromise<void>(); testDisposables.push(vscode.notebooks.onDidChangeNotebookCellExecutionState(e => { try { assert.strictEqual(e.cell.document.uri.toString(), cell.document.uri.toString(), 'event should be fired for the executing cell'); if (eventCount === 0) { assert.strictEqual(e.state, vscode.NotebookCellExecutionState.Pending, 'should be set to Pending'); } else if (eventCount === 1) { assert.strictEqual(e.state, vscode.NotebookCellExecutionState.Executing, 'should be set to Executing'); assert.strictEqual(cell.outputs.length, 0, 'no outputs yet: ' + JSON.stringify(cell.outputs[0])); } else if (e.state === vscode.NotebookCellExecutionState.Idle) { assert.strictEqual(cell.outputs.length, 1, 'should have an output'); def.complete(); } eventCount++; } catch (err) { def.error(err); } })); vscode.commands.executeCommand('notebook.cell.execute', { document: notebook.uri, ranges: [{ start: 0, end: 1 }] }); await def.p; }); test('Output changes are applied once the promise resolves', async function () { let called = false; const verifyOutputSyncKernel = new class extends Kernel { constructor() { super('verifyOutputSyncKernel', ''); } override async _execute(cells: vscode.NotebookCell[]) { const [cell] = cells; const task = this.controller.createNotebookCellExecution(cell); task.start(); await task.replaceOutput([new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text('Some output', 'text/plain') ])]); assert.strictEqual(cell.notebook.cellAt(0).outputs.length, 1); assert.deepStrictEqual(new TextDecoder().decode(cell.notebook.cellAt(0).outputs[0].items[0].data), 'Some output'); task.end(undefined); called = true; } }; const notebook = await openRandomNotebookDocument(); await vscode.window.showNotebookDocument(notebook); await assertKernel(verifyOutputSyncKernel, notebook); await vscode.commands.executeCommand('notebook.cell.execute'); assert.strictEqual(called, true); verifyOutputSyncKernel.controller.dispose(); }); test('executionSummary', async () => { const notebook = await openRandomNotebookDocument(); const editor = await vscode.window.showNotebookDocument(notebook); const cell = editor.notebook.cellAt(0); assert.strictEqual(cell.executionSummary?.success, undefined); assert.strictEqual(cell.executionSummary?.executionOrder, undefined); await vscode.commands.executeCommand('notebook.cell.execute'); assert.strictEqual(cell.outputs.length, 1, 'should execute'); assert.ok(cell.executionSummary); assert.strictEqual(cell.executionSummary!.success, true); assert.strictEqual(typeof cell.executionSummary!.executionOrder, 'number'); }); test('initialize executionSummary', async () => { const document = await openRandomNotebookDocument(); const cell = document.cellAt(0); assert.strictEqual(cell.executionSummary?.success, undefined); assert.strictEqual(cell.executionSummary?.timing?.startTime, 10); assert.strictEqual(cell.executionSummary?.timing?.endTime, 20); }); test('execution cancelled when delete while executing', async () => { const document = await openRandomNotebookDocument(); const cell = document.cellAt(0); let executionWasCancelled = false; const cancelledKernel = new class extends Kernel { constructor() { super('cancelledKernel', ''); } override async _execute(cells: vscode.NotebookCell[]) { const [cell] = cells; const exe = this.controller.createNotebookCellExecution(cell); exe.token.onCancellationRequested(() => executionWasCancelled = true); } }; testDisposables.push(cancelledKernel.controller); await vscode.window.showNotebookDocument(document); await assertKernel(cancelledKernel, document); await vscode.commands.executeCommand('notebook.cell.execute'); // Delete executing cell const edit = new vscode.WorkspaceEdit(); edit.set(cell!.notebook.uri, [vscode.NotebookEdit.replaceCells(new vscode.NotebookRange(cell!.index, cell!.index + 1), [])]); await vscode.workspace.applyEdit(edit); assert.strictEqual(executionWasCancelled, true); }); test('appendOutput to different cell', async function () { const notebook = await openRandomNotebookDocument(); const editor = await vscode.window.showNotebookDocument(notebook); const cell0 = editor.notebook.cellAt(0); const notebookEdit = new vscode.NotebookEdit(new vscode.NotebookRange(1, 1), [new vscode.NotebookCellData(vscode.NotebookCellKind.Code, 'test 2', 'javascript')]); const edit = new vscode.WorkspaceEdit(); edit.set(notebook.uri, [notebookEdit]); await vscode.workspace.applyEdit(edit); const cell1 = editor.notebook.cellAt(1); const nextCellKernel = new class extends Kernel { constructor() { super('nextCellKernel', 'Append to cell kernel'); } override async _runCell(cell: vscode.NotebookCell) { const task = this.controller.createNotebookCellExecution(cell); task.start(); await task.appendOutput([new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text('my output') ])], cell1); await task.appendOutput([new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text('my output 2') ])], cell1); task.end(true); } }; testDisposables.push(nextCellKernel.controller); await withEvent<vscode.NotebookDocumentChangeEvent>(vscode.workspace.onDidChangeNotebookDocument, async (event) => { await assertKernel(nextCellKernel, notebook); await vscode.commands.executeCommand('notebook.cell.execute'); await event; assert.strictEqual(cell0.outputs.length, 0, 'should not change cell 0'); assert.strictEqual(cell1.outputs.length, 2, 'should update cell 1'); assert.strictEqual(cell1.outputs[0].items.length, 1); assert.deepStrictEqual(new TextDecoder().decode(cell1.outputs[0].items[0].data), 'my output'); }); }); test('replaceOutput to different cell', async function () { const notebook = await openRandomNotebookDocument(); const editor = await vscode.window.showNotebookDocument(notebook); const cell0 = editor.notebook.cellAt(0); const notebookEdit = new vscode.NotebookEdit(new vscode.NotebookRange(1, 1), [new vscode.NotebookCellData(vscode.NotebookCellKind.Code, 'test 2', 'javascript')]); const edit = new vscode.WorkspaceEdit(); edit.set(notebook.uri, [notebookEdit]); await vscode.workspace.applyEdit(edit); const cell1 = editor.notebook.cellAt(1); const nextCellKernel = new class extends Kernel { constructor() { super('nextCellKernel', 'Replace to cell kernel'); } override async _runCell(cell: vscode.NotebookCell) { const task = this.controller.createNotebookCellExecution(cell); task.start(); await task.replaceOutput([new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text('my output') ])], cell1); await task.replaceOutput([new vscode.NotebookCellOutput([ vscode.NotebookCellOutputItem.text('my output 2') ])], cell1); task.end(true); } }; testDisposables.push(nextCellKernel.controller); await withEvent<vscode.NotebookDocumentChangeEvent>(vscode.workspace.onDidChangeNotebookDocument, async (event) => { await assertKernel(nextCellKernel, notebook); await vscode.commands.executeCommand('notebook.cell.execute'); await event; assert.strictEqual(cell0.outputs.length, 0, 'should not change cell 0'); assert.strictEqual(cell1.outputs.length, 1, 'should update cell 1'); assert.strictEqual(cell1.outputs[0].items.length, 1); assert.deepStrictEqual(new TextDecoder().decode(cell1.outputs[0].items[0].data), 'my output 2'); }); }); });
extensions/vscode-api-tests/src/singlefolder-tests/notebook.kernel.test.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.000254524260526523, 0.00017319068138021976, 0.00016448316455353051, 0.00016943630180321634, 0.000014052057849767152 ]
{ "id": 2, "code_window": [ "\t\t\t.getEditorContributions()\n", "\t\t\t.filter(c => c.id !== INTERACTIVE_EDITOR_ID);\n", "\n", "\t\tthis._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, {\n", "\t\t\tscrollbar: { useShadows: false, alwaysConsumeMouseWheel: false },\n", "\t\t\trenderMarginRevertIcon: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tscrollBeyondLastLine: false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 52 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.9866681098937988, 0.07514216005802155, 0.00016617293294984847, 0.00036215526051819324, 0.2093060314655304 ]
{ "id": 2, "code_window": [ "\t\t\t.getEditorContributions()\n", "\t\t\t.filter(c => c.id !== INTERACTIVE_EDITOR_ID);\n", "\n", "\t\tthis._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, {\n", "\t\t\tscrollbar: { useShadows: false, alwaysConsumeMouseWheel: false },\n", "\t\t\trenderMarginRevertIcon: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tscrollBeyondLastLine: false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 52 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Registry } from 'vs/platform/registry/common/platform'; import { IQuickAccessRegistry, Extensions } from 'vs/platform/quickinput/common/quickAccess'; import { QuickCommandNLS } from 'vs/editor/common/standaloneStrings'; import { ICommandQuickPick } from 'vs/platform/quickinput/browser/commandsQuickAccess'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { AbstractEditorCommandsQuickAccessProvider } from 'vs/editor/contrib/quickAccess/browser/commandsQuickAccess'; import { IEditor } from 'vs/editor/common/editorCommon'; import { withNullAsUndefined } from 'vs/base/common/types'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { EditorAction, registerEditorAction } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; export class StandaloneCommandsQuickAccessProvider extends AbstractEditorCommandsQuickAccessProvider { protected get activeTextEditorControl(): IEditor | undefined { return withNullAsUndefined(this.codeEditorService.getFocusedCodeEditor()); } constructor( @IInstantiationService instantiationService: IInstantiationService, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, @IKeybindingService keybindingService: IKeybindingService, @ICommandService commandService: ICommandService, @ITelemetryService telemetryService: ITelemetryService, @IDialogService dialogService: IDialogService ) { super({ showAlias: false }, instantiationService, keybindingService, commandService, telemetryService, dialogService); } protected getCommandPicks(): Array<ICommandQuickPick> { return this.getCodeEditorCommandPicks(); } protected async getAdditionalCommandPicks(): Promise<ICommandQuickPick[]> { return []; } } export class GotoLineAction extends EditorAction { static readonly ID = 'editor.action.quickCommand'; constructor() { super({ id: GotoLineAction.ID, label: QuickCommandNLS.quickCommandActionLabel, alias: 'Command Palette', precondition: undefined, kbOpts: { kbExpr: EditorContextKeys.focus, primary: KeyCode.F1, weight: KeybindingWeight.EditorContrib }, contextMenuOpts: { group: 'z_commands', order: 1 } }); } run(accessor: ServicesAccessor): void { accessor.get(IQuickInputService).quickAccess.show(StandaloneCommandsQuickAccessProvider.PREFIX); } } registerEditorAction(GotoLineAction); Registry.as<IQuickAccessRegistry>(Extensions.Quickaccess).registerQuickAccessProvider({ ctor: StandaloneCommandsQuickAccessProvider, prefix: StandaloneCommandsQuickAccessProvider.PREFIX, helpEntries: [{ description: QuickCommandNLS.quickCommandHelp, commandId: GotoLineAction.ID }] });
src/vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00035493035102263093, 0.00019035331206396222, 0.00016353609680663794, 0.00017094415670726448, 0.00005829549263580702 ]
{ "id": 2, "code_window": [ "\t\t\t.getEditorContributions()\n", "\t\t\t.filter(c => c.id !== INTERACTIVE_EDITOR_ID);\n", "\n", "\t\tthis._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, {\n", "\t\t\tscrollbar: { useShadows: false, alwaysConsumeMouseWheel: false },\n", "\t\t\trenderMarginRevertIcon: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tscrollBeyondLastLine: false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 52 }
/*--------------------------------------------------------------------------------------------- * 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, CompletionList, CancellationTokenSource, Position, CompletionTriggerKind, CompletionContext } from 'vscode'; import { withRandomFileEditor, closeAllEditors } from './testUtils'; import { expandEmmetAbbreviation } from '../abbreviationActions'; import { DefaultCompletionItemProvider } from '../defaultCompletionProvider'; const completionProvider = new DefaultCompletionItemProvider(); const cssContents = ` .boo { margin: 20px 10px; pos:f background-image: url('tryme.png'); pos:f } .boo .hoo { margin: 10px; ind } `; const scssContents = ` .boo { margin: 10px; p10 .hoo { p20 } } @include b(alert) { margin: 10px; p30 @include b(alert) { p40 } } .foo { margin: 10px; margin: a .hoo { color: #000; } } `; const invokeCompletionContext: CompletionContext = { triggerKind: CompletionTriggerKind.Invoke, triggerCharacter: undefined, }; suite('Tests for Expand Abbreviations (CSS)', () => { teardown(closeAllEditors); test('Expand abbreviation (CSS)', () => { return withRandomFileEditor(cssContents, 'css', (editor, _) => { editor.selections = [new Selection(3, 1, 3, 6), new Selection(5, 1, 5, 6)]; return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), cssContents.replace(/pos:f/g, 'position: fixed;')); return Promise.resolve(); }); }); }); test('No emmet when cursor inside comment (CSS)', () => { const testContent = ` .foo { /*margin: 10px; m10 padding: 10px;*/ display: auto; } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { editor.selection = new Selection(3, 4, 3, 4); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(2, 10), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion at property value`); } return Promise.resolve(); }); }); }); test('No emmet when cursor in selector of a rule (CSS)', () => { const testContent = ` .foo { margin: 10px; } nav# `; return withRandomFileEditor(testContent, 'css', (editor, _) => { editor.selection = new Selection(5, 4, 5, 4); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(2, 10), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion at property value`); } return Promise.resolve(); }); }); }); test('Skip when typing property values when there is a property in the next line (CSS)', () => { const testContent = ` .foo { margin: a margin: 10px; } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { editor.selection = new Selection(2, 10, 2, 10); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(2, 10), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion at property value`); } return Promise.resolve(); }); }); }); test('Skip when typing the last property value in single line rules (CSS)', () => { const testContent = `.foo {padding: 10px; margin: a}`; return withRandomFileEditor(testContent, 'css', (editor, _) => { editor.selection = new Selection(0, 30, 0, 30); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(0, 30), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion at property value`); } return Promise.resolve(); }); }); }); test('Allow hex color or !important when typing property values when there is a property in the next line (CSS)', () => { const testContent = ` .foo { margin: #12 ! margin: 10px; } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { const cancelSrc = new CancellationTokenSource(); const completionPromise1 = completionProvider.provideCompletionItems(editor.document, new Position(2, 12), cancelSrc.token, invokeCompletionContext); const completionPromise2 = completionProvider.provideCompletionItems(editor.document, new Position(2, 14), cancelSrc.token, invokeCompletionContext); if (!completionPromise1 || !completionPromise2) { assert.strictEqual(1, 2, `Completion promise wasnt returned`); return Promise.resolve(); } const callBack = (completionList: CompletionList, expandedText: string) => { if (!completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Empty Completions`); return; } 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.`); }; return Promise.all<CompletionList>([completionPromise1, completionPromise2]).then(([result1, result2]) => { callBack(result1, '#121212'); callBack(result2, '!important'); editor.selections = [new Selection(2, 12, 2, 12), new Selection(2, 14, 2, 14)]; return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent.replace('#12', '#121212').replace('!', '!important')); }); }); }); }); test('Skip when typing property values when there is a property in the previous line (CSS)', () => { const testContent = ` .foo { margin: 10px; margin: a } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { editor.selection = new Selection(3, 10, 3, 10); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(3, 10), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion at property value`); } return Promise.resolve(); }); }); }); test('Allow hex color or !important when typing property values when there is a property in the previous line (CSS)', () => { const testContent = ` .foo { margin: 10px; margin: #12 ! } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { const cancelSrc = new CancellationTokenSource(); const completionPromise1 = completionProvider.provideCompletionItems(editor.document, new Position(3, 12), cancelSrc.token, invokeCompletionContext); const completionPromise2 = completionProvider.provideCompletionItems(editor.document, new Position(3, 14), cancelSrc.token, invokeCompletionContext); if (!completionPromise1 || !completionPromise2) { assert.strictEqual(1, 2, `Completion promise wasnt returned`); return Promise.resolve(); } const callBack = (completionList: CompletionList, expandedText: string) => { if (!completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Empty Completions`); return; } 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.`); }; return Promise.all<CompletionList>([completionPromise1, completionPromise2]).then(([result1, result2]) => { callBack(result1, '#121212'); callBack(result2, '!important'); editor.selections = [new Selection(3, 12, 3, 12), new Selection(3, 14, 3, 14)]; return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent.replace('#12', '#121212').replace('!', '!important')); }); }); }); }); test('Skip when typing property values when it is the only property in the rule (CSS)', () => { const testContent = ` .foo { margin: a } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { editor.selection = new Selection(2, 10, 2, 10); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(2, 10), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion at property value`); } return Promise.resolve(); }); }); }); test('Allow hex colors or !important when typing property values when it is the only property in the rule (CSS)', () => { const testContent = ` .foo { margin: #12 ! } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { const cancelSrc = new CancellationTokenSource(); const completionPromise1 = completionProvider.provideCompletionItems(editor.document, new Position(2, 12), cancelSrc.token, invokeCompletionContext); const completionPromise2 = completionProvider.provideCompletionItems(editor.document, new Position(2, 14), cancelSrc.token, invokeCompletionContext); if (!completionPromise1 || !completionPromise2) { assert.strictEqual(1, 2, `Completion promise wasnt returned`); return Promise.resolve(); } const callBack = (completionList: CompletionList, expandedText: string) => { if (!completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Empty Completions`); return; } 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.`); }; return Promise.all<CompletionList>([completionPromise1, completionPromise2]).then(([result1, result2]) => { callBack(result1, '#121212'); callBack(result2, '!important'); editor.selections = [new Selection(2, 12, 2, 12), new Selection(2, 14, 2, 14)]; return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent.replace('#12', '#121212').replace('!', '!important')); }); }); }); }); test('# shouldnt expand to hex color when in selector (CSS)', () => { const testContent = ` .foo { # } `; return withRandomFileEditor(testContent, 'css', (editor, _) => { editor.selection = new Selection(2, 2, 2, 2); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), testContent); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(2, 2), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion of hex color at property name`); } return Promise.resolve(); }); }); }); test('Expand abbreviation in completion list (CSS)', () => { const abbreviation = 'pos:f'; const expandedText = 'position: fixed;'; return withRandomFileEditor(cssContents, 'css', (editor, _) => { editor.selection = new Selection(3, 1, 3, 6); const cancelSrc = new CancellationTokenSource(); const completionPromise1 = completionProvider.provideCompletionItems(editor.document, new Position(3, 6), cancelSrc.token, invokeCompletionContext); const completionPromise2 = completionProvider.provideCompletionItems(editor.document, new Position(5, 6), cancelSrc.token, invokeCompletionContext); if (!completionPromise1 || !completionPromise2) { assert.strictEqual(1, 2, `Problem with expanding pos:f`); return Promise.resolve(); } const callBack = (completionList: CompletionList) => { if (!completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Problem with expanding pos:f`); return; } 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.all<CompletionList>([completionPromise1, completionPromise2]).then(([result1, result2]) => { callBack(result1); callBack(result2); return Promise.resolve(); }); }); }); test('Expand abbreviation (SCSS)', () => { return withRandomFileEditor(scssContents, 'scss', (editor, _) => { editor.selections = [ new Selection(3, 4, 3, 4), new Selection(5, 5, 5, 5), new Selection(11, 4, 11, 4), new Selection(14, 5, 14, 5) ]; return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), scssContents.replace(/p(\d\d)/g, 'padding: $1px;')); return Promise.resolve(); }); }); }); test('Expand abbreviation in completion list (SCSS)', () => { return withRandomFileEditor(scssContents, 'scss', (editor, _) => { editor.selection = new Selection(3, 4, 3, 4); const cancelSrc = new CancellationTokenSource(); const completionPromise1 = completionProvider.provideCompletionItems(editor.document, new Position(3, 4), cancelSrc.token, invokeCompletionContext); const completionPromise2 = completionProvider.provideCompletionItems(editor.document, new Position(5, 5), cancelSrc.token, invokeCompletionContext); const completionPromise3 = completionProvider.provideCompletionItems(editor.document, new Position(11, 4), cancelSrc.token, invokeCompletionContext); const completionPromise4 = completionProvider.provideCompletionItems(editor.document, new Position(14, 5), cancelSrc.token, invokeCompletionContext); if (!completionPromise1) { assert.strictEqual(1, 2, `Problem with expanding padding abbreviations at line 3 col 4`); } if (!completionPromise2) { assert.strictEqual(1, 2, `Problem with expanding padding abbreviations at line 5 col 5`); } if (!completionPromise3) { assert.strictEqual(1, 2, `Problem with expanding padding abbreviations at line 11 col 4`); } if (!completionPromise4) { assert.strictEqual(1, 2, `Problem with expanding padding abbreviations at line 14 col 5`); } if (!completionPromise1 || !completionPromise2 || !completionPromise3 || !completionPromise4) { return Promise.resolve(); } const callBack = (completionList: CompletionList, abbreviation: string, expandedText: string) => { if (!completionList.items || !completionList.items.length) { assert.strictEqual(1, 2, `Problem with expanding m10`); return; } 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.all<CompletionList>([completionPromise1, completionPromise2, completionPromise3, completionPromise4]).then(([result1, result2, result3, result4]) => { callBack(result1, 'p10', 'padding: 10px;'); callBack(result2, 'p20', 'padding: 20px;'); callBack(result3, 'p30', 'padding: 30px;'); callBack(result4, 'p40', 'padding: 40px;'); return Promise.resolve(); }); }); }); test('Invalid locations for abbreviations in scss', () => { const scssContentsNoExpand = ` m10 .boo { margin: 10px; .hoo { background: } } `; return withRandomFileEditor(scssContentsNoExpand, 'scss', (editor, _) => { editor.selections = [ new Selection(1, 3, 1, 3), // outside rule new Selection(5, 15, 5, 15) // in the value part of property value ]; return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), scssContentsNoExpand); return Promise.resolve(); }); }); }); test('Invalid locations for abbreviations in scss in completion list', () => { const scssContentsNoExpand = ` m10 .boo { margin: 10px; .hoo { background: } } `; return withRandomFileEditor(scssContentsNoExpand, 'scss', (editor, _) => { editor.selection = new Selection(1, 3, 1, 3); // outside rule const cancelSrc = new CancellationTokenSource(); let completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `m10 gets expanded in invalid location (outside rule)`); } editor.selection = new Selection(5, 15, 5, 15); // in the value part of property value completionPromise = completionProvider.provideCompletionItems(editor.document, editor.selection.active, cancelSrc.token, invokeCompletionContext); if (completionPromise) { return completionPromise.then((completionList: CompletionList | undefined) => { if (completionList && completionList.items && completionList.items.length > 0) { assert.strictEqual(1, 2, `m10 gets expanded in invalid location (n the value part of property value)`); } return Promise.resolve(); }); } return Promise.resolve(); }); }); test('Skip when typing property values when there is a nested rule in the next line (SCSS)', () => { return withRandomFileEditor(scssContents, 'scss', (editor, _) => { editor.selection = new Selection(19, 10, 19, 10); return expandEmmetAbbreviation(null).then(() => { assert.strictEqual(editor.document.getText(), scssContents); const cancelSrc = new CancellationTokenSource(); const completionPromise = completionProvider.provideCompletionItems(editor.document, new Position(19, 10), cancelSrc.token, invokeCompletionContext); if (completionPromise) { assert.strictEqual(1, 2, `Invalid completion at property value`); } return Promise.resolve(); }); }); }); });
extensions/emmet/src/test/cssAbbreviationAction.test.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017832349112723023, 0.00017222405585926026, 0.0001672272483119741, 0.00017224538896698505, 0.0000024499586288584396 ]
{ "id": 2, "code_window": [ "\t\t\t.getEditorContributions()\n", "\t\t\t.filter(c => c.id !== INTERACTIVE_EDITOR_ID);\n", "\n", "\t\tthis._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, {\n", "\t\t\tscrollbar: { useShadows: false, alwaysConsumeMouseWheel: false },\n", "\t\t\trenderMarginRevertIcon: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tscrollBeyondLastLine: false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 52 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/csharp/yarn.lock
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001689701748546213, 0.0001689701748546213, 0.0001689701748546213, 0.0001689701748546213, 0 ]
{ "id": 3, "code_window": [ "\t\t\tscrollBeyondLastLine: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\trenderOverviewRuler: false,\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\trenderMarginRevertIcon: false,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.9924066662788391, 0.04151461645960808, 0.00016537090414203703, 0.00016835753922350705, 0.19827470183372498 ]
{ "id": 3, "code_window": [ "\t\t\tscrollBeyondLastLine: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\trenderOverviewRuler: false,\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\trenderMarginRevertIcon: false,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 55 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.getBuiltInExtensions = exports.getExtensionStream = void 0; const fs = require("fs"); const path = require("path"); const os = require("os"); const rimraf = require("rimraf"); const es = require("event-stream"); const rename = require("gulp-rename"); const vfs = require("vinyl-fs"); const ext = require("./extensions"); const fancyLog = require("fancy-log"); const ansiColors = require("ansi-colors"); const mkdirp = require('mkdirp'); const root = path.dirname(path.dirname(__dirname)); const productjson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../product.json'), 'utf8')); const builtInExtensions = productjson.builtInExtensions || []; const webBuiltInExtensions = productjson.webBuiltInExtensions || []; const controlFilePath = path.join(os.homedir(), '.vscode-oss-dev', 'extensions', 'control.json'); const ENABLE_LOGGING = !process.env['VSCODE_BUILD_BUILTIN_EXTENSIONS_SILENCE_PLEASE']; function log(...messages) { if (ENABLE_LOGGING) { fancyLog(...messages); } } function getExtensionPath(extension) { return path.join(root, '.build', 'builtInExtensions', extension.name); } function isUpToDate(extension) { const packagePath = path.join(getExtensionPath(extension), 'package.json'); if (!fs.existsSync(packagePath)) { return false; } const packageContents = fs.readFileSync(packagePath, { encoding: 'utf8' }); try { const diskVersion = JSON.parse(packageContents).version; return (diskVersion === extension.version); } catch (err) { return false; } } function getExtensionDownloadStream(extension) { const galleryServiceUrl = productjson.extensionsGallery?.serviceUrl; return (galleryServiceUrl ? ext.fromMarketplace(galleryServiceUrl, extension) : ext.fromGithub(extension)) .pipe(rename(p => p.dirname = `${extension.name}/${p.dirname}`)); } function getExtensionStream(extension) { // if the extension exists on disk, use those files instead of downloading anew if (isUpToDate(extension)) { log('[extensions]', `${extension.name}@${extension.version} up to date`, ansiColors.green('✔︎')); return vfs.src(['**'], { cwd: getExtensionPath(extension), dot: true }) .pipe(rename(p => p.dirname = `${extension.name}/${p.dirname}`)); } return getExtensionDownloadStream(extension); } exports.getExtensionStream = getExtensionStream; function syncMarketplaceExtension(extension) { const galleryServiceUrl = productjson.extensionsGallery?.serviceUrl; const source = ansiColors.blue(galleryServiceUrl ? '[marketplace]' : '[github]'); if (isUpToDate(extension)) { log(source, `${extension.name}@${extension.version}`, ansiColors.green('✔︎')); return es.readArray([]); } rimraf.sync(getExtensionPath(extension)); return getExtensionDownloadStream(extension) .pipe(vfs.dest('.build/builtInExtensions')) .on('end', () => log(source, extension.name, ansiColors.green('✔︎'))); } function syncExtension(extension, controlState) { if (extension.platforms) { const platforms = new Set(extension.platforms); if (!platforms.has(process.platform)) { log(ansiColors.gray('[skip]'), `${extension.name}@${extension.version}: Platform '${process.platform}' not supported: [${extension.platforms}]`, ansiColors.green('✔︎')); return es.readArray([]); } } switch (controlState) { case 'disabled': log(ansiColors.blue('[disabled]'), ansiColors.gray(extension.name)); return es.readArray([]); case 'marketplace': return syncMarketplaceExtension(extension); default: if (!fs.existsSync(controlState)) { log(ansiColors.red(`Error: Built-in extension '${extension.name}' is configured to run from '${controlState}' but that path does not exist.`)); return es.readArray([]); } else if (!fs.existsSync(path.join(controlState, 'package.json'))) { log(ansiColors.red(`Error: Built-in extension '${extension.name}' is configured to run from '${controlState}' but there is no 'package.json' file in that directory.`)); return es.readArray([]); } log(ansiColors.blue('[local]'), `${extension.name}: ${ansiColors.cyan(controlState)}`, ansiColors.green('✔︎')); return es.readArray([]); } } function readControlFile() { try { return JSON.parse(fs.readFileSync(controlFilePath, 'utf8')); } catch (err) { return {}; } } function writeControlFile(control) { mkdirp.sync(path.dirname(controlFilePath)); fs.writeFileSync(controlFilePath, JSON.stringify(control, null, 2)); } function getBuiltInExtensions() { log('Synchronizing built-in extensions...'); log(`You can manage built-in extensions with the ${ansiColors.cyan('--builtin')} flag`); const control = readControlFile(); const streams = []; for (const extension of [...builtInExtensions, ...webBuiltInExtensions]) { const controlState = control[extension.name] || 'marketplace'; control[extension.name] = controlState; streams.push(syncExtension(extension, controlState)); } writeControlFile(control); return new Promise((resolve, reject) => { es.merge(streams) .on('error', reject) .on('end', resolve); }); } exports.getBuiltInExtensions = getBuiltInExtensions; if (require.main === module) { getBuiltInExtensions().then(() => process.exit(0)).catch(err => { console.error(err); process.exit(1); }); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbHRJbkV4dGVuc2lvbnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJidWlsdEluRXh0ZW5zaW9ucy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7OztnR0FHZ0c7OztBQUVoRyx5QkFBeUI7QUFDekIsNkJBQTZCO0FBQzdCLHlCQUF5QjtBQUN6QixpQ0FBaUM7QUFDakMsbUNBQW1DO0FBQ25DLHNDQUFzQztBQUN0QyxnQ0FBZ0M7QUFDaEMsb0NBQW9DO0FBQ3BDLHNDQUFzQztBQUN0QywwQ0FBMEM7QUFHMUMsTUFBTSxNQUFNLEdBQUcsT0FBTyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0FBbUJqQyxNQUFNLElBQUksR0FBRyxJQUFJLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsU0FBUyxDQUFDLENBQUMsQ0FBQztBQUNuRCxNQUFNLFdBQVcsR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFDLEVBQUUsQ0FBQyxZQUFZLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxTQUFTLEVBQUUsb0JBQW9CLENBQUMsRUFBRSxNQUFNLENBQUMsQ0FBQyxDQUFDO0FBQ3BHLE1BQU0saUJBQWlCLEdBQTJCLFdBQVcsQ0FBQyxpQkFBaUIsSUFBSSxFQUFFLENBQUM7QUFDdEYsTUFBTSxvQkFBb0IsR0FBMkIsV0FBVyxDQUFDLG9CQUFvQixJQUFJLEVBQUUsQ0FBQztBQUM1RixNQUFNLGVBQWUsR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBRSxpQkFBaUIsRUFBRSxZQUFZLEVBQUUsY0FBYyxDQUFDLENBQUM7QUFDakcsTUFBTSxjQUFjLEdBQUcsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLGdEQUFnRCxDQUFDLENBQUM7QUFFdEYsU0FBUyxHQUFHLENBQUMsR0FBRyxRQUFrQjtJQUNqQyxJQUFJLGNBQWMsRUFBRTtRQUNuQixRQUFRLENBQUMsR0FBRyxRQUFRLENBQUMsQ0FBQztLQUN0QjtBQUNGLENBQUM7QUFFRCxTQUFTLGdCQUFnQixDQUFDLFNBQStCO0lBQ3hELE9BQU8sSUFBSSxDQUFDLElBQUksQ0FBQyxJQUFJLEVBQUUsUUFBUSxFQUFFLG1CQUFtQixFQUFFLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUN2RSxDQUFDO0FBRUQsU0FBUyxVQUFVLENBQUMsU0FBK0I7SUFDbEQsTUFBTSxXQUFXLEdBQUcsSUFBSSxDQUFDLElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxTQUFTLENBQUMsRUFBRSxjQUFjLENBQUMsQ0FBQztJQUUzRSxJQUFJLENBQUMsRUFBRSxDQUFDLFVBQVUsQ0FBQyxXQUFXLENBQUMsRUFBRTtRQUNoQyxPQUFPLEtBQUssQ0FBQztLQUNiO0lBRUQsTUFBTSxlQUFlLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxXQUFXLEVBQUUsRUFBRSxRQUFRLEVBQUUsTUFBTSxFQUFFLENBQUMsQ0FBQztJQUUzRSxJQUFJO1FBQ0gsTUFBTSxXQUFXLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxlQUFlLENBQUMsQ0FBQyxPQUFPLENBQUM7UUFDeEQsT0FBTyxDQUFDLFdBQVcsS0FBSyxTQUFTLENBQUMsT0FBTyxDQUFDLENBQUM7S0FDM0M7SUFBQyxPQUFPLEdBQUcsRUFBRTtRQUNiLE9BQU8sS0FBSyxDQUFDO0tBQ2I7QUFDRixDQUFDO0FBRUQsU0FBUywwQkFBMEIsQ0FBQyxTQUErQjtJQUNsRSxNQUFNLGlCQUFpQixHQUFHLFdBQVcsQ0FBQyxpQkFBaUIsRUFBRSxVQUFVLENBQUM7SUFDcEUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsZUFBZSxDQUFDLGlCQUFpQixFQUFFLFNBQVMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsVUFBVSxDQUFDLFNBQVMsQ0FBQyxDQUFDO1NBQ3hHLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUMsT0FBTyxHQUFHLEdBQUcsU0FBUyxDQUFDLElBQUksSUFBSSxDQUFDLENBQUMsT0FBTyxFQUFFLENBQUMsQ0FBQyxDQUFDO0FBQ25FLENBQUM7QUFFRCxTQUFnQixrQkFBa0IsQ0FBQyxTQUErQjtJQUNqRSwrRUFBK0U7SUFDL0UsSUFBSSxVQUFVLENBQUMsU0FBUyxDQUFDLEVBQUU7UUFDMUIsR0FBRyxDQUFDLGNBQWMsRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLElBQUksU0FBUyxDQUFDLE9BQU8sYUFBYSxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztRQUNqRyxPQUFPLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxJQUFJLENBQUMsRUFBRSxFQUFFLEdBQUcsRUFBRSxnQkFBZ0IsQ0FBQyxTQUFTLENBQUMsRUFBRSxHQUFHLEVBQUUsSUFBSSxFQUFFLENBQUM7YUFDckUsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQyxPQUFPLEdBQUcsR0FBRyxTQUFTLENBQUMsSUFBSSxJQUFJLENBQUMsQ0FBQyxPQUFPLEVBQUUsQ0FBQyxDQUFDLENBQUM7S0FDbEU7SUFFRCxPQUFPLDBCQUEwQixDQUFDLFNBQVMsQ0FBQyxDQUFDO0FBQzlDLENBQUM7QUFURCxnREFTQztBQUVELFNBQVMsd0JBQXdCLENBQUMsU0FBK0I7SUFDaEUsTUFBTSxpQkFBaUIsR0FBRyxXQUFXLENBQUMsaUJBQWlCLEVBQUUsVUFBVSxDQUFDO0lBQ3BFLE1BQU0sTUFBTSxHQUFHLFVBQVUsQ0FBQyxJQUFJLENBQUMsaUJBQWlCLENBQUMsQ0FBQyxDQUFDLGVBQWUsQ0FBQyxDQUFDLENBQUMsVUFBVSxDQUFDLENBQUM7SUFDakYsSUFBSSxVQUFVLENBQUMsU0FBUyxDQUFDLEVBQUU7UUFDMUIsR0FBRyxDQUFDLE1BQU0sRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLElBQUksU0FBUyxDQUFDLE9BQU8sRUFBRSxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztRQUM5RSxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7S0FDeEI7SUFFRCxNQUFNLENBQUMsSUFBSSxDQUFDLGdCQUFnQixDQUFDLFNBQVMsQ0FBQyxDQUFDLENBQUM7SUFFekMsT0FBTywwQkFBMEIsQ0FBQyxTQUFTLENBQUM7U0FDMUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxJQUFJLENBQUMsMEJBQTBCLENBQUMsQ0FBQztTQUMxQyxFQUFFLENBQUMsS0FBSyxFQUFFLEdBQUcsRUFBRSxDQUFDLEdBQUcsQ0FBQyxNQUFNLEVBQUUsU0FBUyxDQUFDLElBQUksRUFBRSxVQUFVLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUN4RSxDQUFDO0FBRUQsU0FBUyxhQUFhLENBQUMsU0FBK0IsRUFBRSxZQUF3QztJQUMvRixJQUFJLFNBQVMsQ0FBQyxTQUFTLEVBQUU7UUFDeEIsTUFBTSxTQUFTLEdBQUcsSUFBSSxHQUFHLENBQUMsU0FBUyxDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBRS9DLElBQUksQ0FBQyxTQUFTLENBQUMsR0FBRyxDQUFDLE9BQU8sQ0FBQyxRQUFRLENBQUMsRUFBRTtZQUNyQyxHQUFHLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxRQUFRLENBQUMsRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLElBQUksU0FBUyxDQUFDLE9BQU8sZUFBZSxPQUFPLENBQUMsUUFBUSxxQkFBcUIsU0FBUyxDQUFDLFNBQVMsR0FBRyxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztZQUN6SyxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7U0FDeEI7S0FDRDtJQUVELFFBQVEsWUFBWSxFQUFFO1FBQ3JCLEtBQUssVUFBVTtZQUNkLEdBQUcsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLFlBQVksQ0FBQyxFQUFFLFVBQVUsQ0FBQyxJQUFJLENBQUMsU0FBUyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUM7WUFDcEUsT0FBTyxFQUFFLENBQUMsU0FBUyxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBRXpCLEtBQUssYUFBYTtZQUNqQixPQUFPLHdCQUF3QixDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBRTVDO1lBQ0MsSUFBSSxDQUFDLEVBQUUsQ0FBQyxVQUFVLENBQUMsWUFBWSxDQUFDLEVBQUU7Z0JBQ2pDLEdBQUcsQ0FBQyxVQUFVLENBQUMsR0FBRyxDQUFDLDhCQUE4QixTQUFTLENBQUMsSUFBSSxnQ0FBZ0MsWUFBWSxpQ0FBaUMsQ0FBQyxDQUFDLENBQUM7Z0JBQy9JLE9BQU8sRUFBRSxDQUFDLFNBQVMsQ0FBQyxFQUFFLENBQUMsQ0FBQzthQUV4QjtpQkFBTSxJQUFJLENBQUMsRUFBRSxDQUFDLFVBQVUsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLFlBQVksRUFBRSxjQUFjLENBQUMsQ0FBQyxFQUFFO2dCQUNuRSxHQUFHLENBQUMsVUFBVSxDQUFDLEdBQUcsQ0FBQyw4QkFBOEIsU0FBUyxDQUFDLElBQUksZ0NBQWdDLFlBQVksMERBQTBELENBQUMsQ0FBQyxDQUFDO2dCQUN4SyxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7YUFDeEI7WUFFRCxHQUFHLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsRUFBRSxHQUFHLFNBQVMsQ0FBQyxJQUFJLEtBQUssVUFBVSxDQUFDLElBQUksQ0FBQyxZQUFZLENBQUMsRUFBRSxFQUFFLFVBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztZQUMvRyxPQUFPLEVBQUUsQ0FBQyxTQUFTLENBQUMsRUFBRSxDQUFDLENBQUM7S0FDekI7QUFDRixDQUFDO0FBTUQsU0FBUyxlQUFlO0lBQ3ZCLElBQUk7UUFDSCxPQUFPLElBQUksQ0FBQyxLQUFLLENBQUMsRUFBRSxDQUFDLFlBQVksQ0FBQyxlQUFlLEVBQUUsTUFBTSxDQUFDLENBQUMsQ0FBQztLQUM1RDtJQUFDLE9BQU8sR0FBRyxFQUFFO1FBQ2IsT0FBTyxFQUFFLENBQUM7S0FDVjtBQUNGLENBQUM7QUFFRCxTQUFTLGdCQUFnQixDQUFDLE9BQXFCO0lBQzlDLE1BQU0sQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxlQUFlLENBQUMsQ0FBQyxDQUFDO0lBQzNDLEVBQUUsQ0FBQyxhQUFhLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxTQUFTLENBQUMsT0FBTyxFQUFFLElBQUksRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ3JFLENBQUM7QUFFRCxTQUFnQixvQkFBb0I7SUFDbkMsR0FBRyxDQUFDLHNDQUFzQyxDQUFDLENBQUM7SUFDNUMsR0FBRyxDQUFDLCtDQUErQyxVQUFVLENBQUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxPQUFPLENBQUMsQ0FBQztJQUV4RixNQUFNLE9BQU8sR0FBRyxlQUFlLEVBQUUsQ0FBQztJQUNsQyxNQUFNLE9BQU8sR0FBYSxFQUFFLENBQUM7SUFFN0IsS0FBSyxNQUFNLFNBQVMsSUFBSSxDQUFDLEdBQUcsaUJBQWlCLEVBQUUsR0FBRyxvQkFBb0IsQ0FBQyxFQUFFO1FBQ3hFLE1BQU0sWUFBWSxHQUFHLE9BQU8sQ0FBQyxTQUFTLENBQUMsSUFBSSxDQUFDLElBQUksYUFBYSxDQUFDO1FBQzlELE9BQU8sQ0FBQyxTQUFTLENBQUMsSUFBSSxDQUFDLEdBQUcsWUFBWSxDQUFDO1FBRXZDLE9BQU8sQ0FBQyxJQUFJLENBQUMsYUFBYSxDQUFDLFNBQVMsRUFBRSxZQUFZLENBQUMsQ0FBQyxDQUFDO0tBQ3JEO0lBRUQsZ0JBQWdCLENBQUMsT0FBTyxDQUFDLENBQUM7SUFFMUIsT0FBTyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNLEVBQUUsRUFBRTtRQUN0QyxFQUFFLENBQUMsS0FBSyxDQUFDLE9BQU8sQ0FBQzthQUNmLEVBQUUsQ0FBQyxPQUFPLEVBQUUsTUFBTSxDQUFDO2FBQ25CLEVBQUUsQ0FBQyxLQUFLLEVBQUUsT0FBTyxDQUFDLENBQUM7SUFDdEIsQ0FBQyxDQUFDLENBQUM7QUFDSixDQUFDO0FBckJELG9EQXFCQztBQUVELElBQUksT0FBTyxDQUFDLElBQUksS0FBSyxNQUFNLEVBQUU7SUFDNUIsb0JBQW9CLEVBQUUsQ0FBQyxJQUFJLENBQUMsR0FBRyxFQUFFLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsRUFBRTtRQUM5RCxPQUFPLENBQUMsS0FBSyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQ25CLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDakIsQ0FBQyxDQUFDLENBQUM7Q0FDSCJ9
build/lib/builtInExtensions.js
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0069197253324091434, 0.0006553007988259196, 0.0001658074907027185, 0.00016893490101210773, 0.0017374741146340966 ]
{ "id": 3, "code_window": [ "\t\t\tscrollBeyondLastLine: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\trenderOverviewRuler: false,\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\trenderMarginRevertIcon: false,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 55 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "title": "TypeScript contributions to package.json", "type": "object", "properties": { "contributes": { "type": "object", "properties": { "typescriptServerPlugins": { "type": "array", "description": "Contributed TypeScript server plugins.", "items": { "type": "object", "description": "TypeScript server plugin.", "properties": { "name": { "type": "string", "description": "Name of the plugin as listed in the package.json." }, "enableForWorkspaceTypeScriptVersions": { "type": "boolean", "default": false, "description": "Should the plugin be loaded when using workspace versions of TypeScript?" } } } } } } } }
extensions/typescript-language-features/schemas/package.schema.json
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.000175683424458839, 0.00016993119788821787, 0.00016680778935551643, 0.00016861679614521563, 0.0000034411268643452786 ]
{ "id": 3, "code_window": [ "\t\t\tscrollBeyondLastLine: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\trenderOverviewRuler: false,\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\trenderMarginRevertIcon: false,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import { Application, Logger } from '../../../../automation'; import { installAllHandlers } from '../../utils'; export function setup(logger: Logger) { describe.skip('Notebooks', () => { // https://github.com/microsoft/vscode/issues/140575 // Shared before/after handling installAllHandlers(logger); afterEach(async function () { const app = this.app as Application; await app.workbench.quickaccess.runCommand('workbench.action.files.save'); await app.workbench.quickaccess.runCommand('workbench.action.closeActiveEditor'); }); after(async function () { const app = this.app as Application; cp.execSync('git checkout . --quiet', { cwd: app.workspacePathOrFolder }); cp.execSync('git reset --hard HEAD --quiet', { cwd: app.workspacePathOrFolder }); }); it('inserts/edits code cell', async function () { const app = this.app as Application; await app.workbench.notebook.openNotebook(); await app.workbench.notebook.focusNextCell(); await app.workbench.notebook.insertNotebookCell('code'); await app.workbench.notebook.waitForTypeInEditor('// some code'); await app.workbench.notebook.stopEditingCell(); }); it('inserts/edits markdown cell', async function () { const app = this.app as Application; await app.workbench.notebook.openNotebook(); await app.workbench.notebook.focusNextCell(); await app.workbench.notebook.insertNotebookCell('markdown'); await app.workbench.notebook.waitForTypeInEditor('## hello2! '); await app.workbench.notebook.stopEditingCell(); await app.workbench.notebook.waitForMarkdownContents('h2', 'hello2!'); }); it.skip('moves focus as it inserts/deletes a cell', async function () { const app = this.app as Application; await app.workbench.notebook.openNotebook(); await app.workbench.notebook.insertNotebookCell('code'); await app.workbench.notebook.waitForActiveCellEditorContents(''); await app.workbench.notebook.stopEditingCell(); await app.workbench.notebook.deleteActiveCell(); await app.workbench.notebook.waitForMarkdownContents('p', 'Markdown Cell'); }); it.skip('moves focus in and out of output', async function () { // TODO@rebornix https://github.com/microsoft/vscode/issues/139270 const app = this.app as Application; await app.workbench.notebook.openNotebook(); await app.workbench.notebook.executeActiveCell(); await app.workbench.notebook.focusInCellOutput(); await app.workbench.notebook.focusOutCellOutput(); await app.workbench.notebook.waitForActiveCellEditorContents('code()'); }); it.skip('cell action execution', async function () { // TODO@rebornix https://github.com/microsoft/vscode/issues/139270 const app = this.app as Application; await app.workbench.notebook.openNotebook(); await app.workbench.notebook.insertNotebookCell('code'); await app.workbench.notebook.executeCellAction('.notebook-editor .monaco-list-row.focused div.monaco-toolbar .codicon-debug'); await app.workbench.notebook.waitForActiveCellEditorContents('test'); }); }); }
test/smoke/src/areas/notebook/notebook.test.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017351401038467884, 0.0001673987862886861, 0.00016390108794439584, 0.00016664891154505312, 0.0000030395303838304244 ]
{ "id": 4, "code_window": [ "\t\t\trenderOverviewRuler: false,\n", "\t\t\tdiffAlgorithm: 'advanced',\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\trulers: undefined,\n", "\t\t\toverviewRulerBorder: undefined,\n", "\t\t\toverviewRulerLanes: 0,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 57 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .interactive-editor { z-index: 100; color: inherit; padding: 6px; border-radius: 6px; border: 1px solid var(--vscode-interactiveEditor-border); box-shadow: 0 4px 8px var(--vscode-interactiveEditor-shadow); } /* body */ .monaco-editor .interactive-editor .body { display: flex; } .monaco-editor .interactive-editor .body .content { display: flex; box-sizing: border-box; border-radius: 2px; border: 1px solid var(--vscode-interactiveEditorInput-border); } .monaco-editor .interactive-editor .body .content.synthetic-focus { outline: 1px solid var(--vscode-interactiveEditorInput-focusBorder); } .monaco-editor .interactive-editor .body .content .input { padding: 2px 2px 2px 4px; border-top-left-radius: 2px; border-bottom-left-radius: 2px; background-color: var(--vscode-interactiveEditorInput-background); cursor: text; } .monaco-editor .interactive-editor .monaco-editor-background { background-color: var(--vscode-interactiveEditorInput-background); } .monaco-editor .interactive-editor .body .content .input .editor-placeholder { position: absolute; z-index: 1; padding: 3px 0 0 0; color: var(--vscode-interactiveEditorInput-placeholderForeground); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .monaco-editor .interactive-editor .body .content .input .editor-placeholder.hidden { display: none; } .monaco-editor .interactive-editor .body .content .input .editor-container { vertical-align: middle; } .monaco-editor .interactive-editor .body .toolbar { display: flex; flex-direction: column; align-self: stretch; padding-right: 4px; border-top-right-radius: 2px; border-bottom-right-radius: 2px; background: var(--vscode-interactiveEditorInput-background); } .monaco-editor .interactive-editor .body .toolbar .actions-container { display: flex; flex-direction: row; gap: 4px; } /* progress bit */ .monaco-editor .interactive-editor .progress { position: relative; width: calc(100% - 18px); left: 19px; } /* UGLY - fighting against workbench styles */ .monaco-workbench .part.editor>.content .monaco-editor .interactive-editor .progress .monaco-progress-container { top: 0; } /* status */ .monaco-editor .interactive-editor .status { padding: 6px 0px 2px 0px; display: flex; justify-content: space-between; align-items: center; } .monaco-editor .interactive-editor .status .actions.hidden { display: none; } .monaco-editor .interactive-editor .status .link { color: var(--vscode-textLink-foreground); cursor: pointer; font-size: 12px; white-space: nowrap; /* margin-top: auto; */ } .monaco-editor .interactive-editor .status .label { overflow: hidden; font-size: 12px; margin-left: auto; } .monaco-editor .interactive-editor .status .label.message>span>p { margin: 0px; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; display: -webkit-box; } .monaco-editor .interactive-editor .status .link .status-link { padding-left: 10px; } .monaco-editor .interactive-editor .status .link .status-link .codicon { line-height: unset; font-size: 12px; padding-right: 4px; } .monaco-editor .interactive-editor .status .label A { color: var(--vscode-textLink-foreground); cursor: pointer; } .monaco-editor .interactive-editor .status .label.error { color: var(--vscode-errorForeground); } .monaco-editor .interactive-editor .status .label.warn { color: var(--vscode-editorWarning-foreground); } .monaco-editor .interactive-editor .status .monaco-toolbar .action-item { padding: 0 2px; } .monaco-editor .interactive-editor .status .monaco-toolbar .action-label.checked { color: var(--vscode-inputOption-activeForeground); background-color: var(--vscode-inputOption-activeBackground); outline: 1px solid var(--vscode-inputOption-activeBorder); } /* preview */ .monaco-editor .interactive-editor .preview { display: none; } .monaco-editor .interactive-editor .previewDiff { display: inherit; padding: 6px; border: 1px solid var(--vscode-interactiveEditor-border); border-top: none; border-bottom-left-radius: 2px; border-bottom-right-radius: 2px; margin: 0 2px 6px 2px; } .monaco-editor .interactive-editor .previewCreateTitle { padding-top: 6px; } .monaco-editor .interactive-editor .previewCreate { display: inherit; padding: 6px; border: 1px solid var(--vscode-interactiveEditor-border); border-radius: 2px; margin: 0 2px 6px 2px; } .monaco-editor .interactive-editor .previewDiff.hidden, .monaco-editor .interactive-editor .previewCreate.hidden, .monaco-editor .interactive-editor .previewCreateTitle.hidden { display: none; } /* decoration styles */ .monaco-editor .interactive-editor-lines-deleted-range-inline { text-decoration: line-through; background-color: var(--vscode-diffEditor-removedTextBackground); opacity: 0.6; } .monaco-editor .interactive-editor-lines-inserted-range { background-color: var(--vscode-diffEditor-insertedTextBackground); } .monaco-editor .interactive-editor-block-selection { background-color: var(--vscode-interactiveEditor-regionHighlight); } .monaco-editor .interactive-editor-slash-command { color: var(--vscode-textLink-foreground) } .monaco-editor .interactive-editor-slash-command-detail { opacity: 0.5; } /* diff zone */ .monaco-editor .interactive-editor-diff-widget { padding: 6px 0; }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00021709145221393555, 0.00017163640586659312, 0.00016681398847140372, 0.00016833897097967565, 0.000010513771485420875 ]
{ "id": 4, "code_window": [ "\t\t\trenderOverviewRuler: false,\n", "\t\t\tdiffAlgorithm: 'advanced',\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\trulers: undefined,\n", "\t\t\toverviewRulerBorder: undefined,\n", "\t\t\toverviewRulerLanes: 0,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 57 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type * as nbformat from '@jupyterlab/nbformat'; /** * Metadata we store in VS Code cell output items. * This contains the original metadata from the Jupyter outputs. */ export interface CellOutputMetadata { /** * Cell output metadata. */ metadata?: any; /** * Transient data from Jupyter. */ transient?: { /** * This is used for updating the output in other cells. * We don't know of other properties, but this is definitely used. */ display_id?: string; } & any; /** * Original cell output type */ outputType: nbformat.OutputType | string; executionCount?: nbformat.IExecuteResult['ExecutionCount']; /** * Whether the original Mime data is JSON or not. * This properly only exists in metadata for NotebookCellOutputItems * (this is something we have added) */ __isJson?: boolean; } /** * Metadata we store in VS Code cells. * This contains the original metadata from the Jupyter cells. */ export interface CellMetadata { /** * Cell id for notebooks created with the new 4.5 version of nbformat. */ id?: string; /** * Stores attachments for cells. */ attachments?: nbformat.IAttachments; /** * Stores cell metadata. */ metadata?: Partial<nbformat.ICellMetadata>; }
extensions/ipynb/src/common.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017244621994905174, 0.00016909072292037308, 0.00016551620501559228, 0.00016909345868043602, 0.000002224240688519785 ]
{ "id": 4, "code_window": [ "\t\t\trenderOverviewRuler: false,\n", "\t\t\tdiffAlgorithm: 'advanced',\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\trulers: undefined,\n", "\t\t\toverviewRulerBorder: undefined,\n", "\t\t\toverviewRulerLanes: 0,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 57 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { RunOnceScheduler } from 'vs/base/common/async'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { LRUCache } from 'vs/base/common/map'; import { TernarySearchTree } from 'vs/base/common/ternarySearchTree'; import { IPosition } from 'vs/editor/common/core/position'; import { ITextModel } from 'vs/editor/common/model'; import { CompletionItemKind, CompletionItemKinds } from 'vs/editor/common/languages'; import { CompletionItem } from 'vs/editor/contrib/suggest/browser/suggest'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope, StorageTarget, WillSaveStateReason } from 'vs/platform/storage/common/storage'; export abstract class Memory { constructor(readonly name: MemMode) { } select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { if (items.length === 0) { return 0; } const topScore = items[0].score[0]; for (let i = 0; i < items.length; i++) { const { score, completion: suggestion } = items[i]; if (score[0] !== topScore) { // stop when leaving the group of top matches break; } if (suggestion.preselect) { // stop when seeing an auto-select-item return i; } } return 0; } abstract memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void; abstract toJSON(): object | undefined; abstract fromJSON(data: object): void; } export class NoMemory extends Memory { constructor() { super('first'); } memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { // no-op } toJSON() { return undefined; } fromJSON() { // } } export interface MemItem { type: string | CompletionItemKind; insertText: string; touch: number; } export class LRUMemory extends Memory { constructor() { super('recentlyUsed'); } private _cache = new LRUCache<string, MemItem>(300, 0.66); private _seq = 0; memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { const key = `${model.getLanguageId()}/${item.textLabel}`; this._cache.set(key, { touch: this._seq++, type: item.completion.kind, insertText: item.completion.insertText }); } override select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { if (items.length === 0) { return 0; } const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1); if (/\s$/.test(lineSuffix)) { return super.select(model, pos, items); } const topScore = items[0].score[0]; let indexPreselect = -1; let indexRecency = -1; let seq = -1; for (let i = 0; i < items.length; i++) { if (items[i].score[0] !== topScore) { // consider only top items break; } const key = `${model.getLanguageId()}/${items[i].textLabel}`; const item = this._cache.peek(key); if (item && item.touch > seq && item.type === items[i].completion.kind && item.insertText === items[i].completion.insertText) { seq = item.touch; indexRecency = i; } if (items[i].completion.preselect && indexPreselect === -1) { // stop when seeing an auto-select-item return indexPreselect = i; } } if (indexRecency !== -1) { return indexRecency; } else if (indexPreselect !== -1) { return indexPreselect; } else { return 0; } } toJSON(): object { return this._cache.toJSON(); } fromJSON(data: [string, MemItem][]): void { this._cache.clear(); const seq = 0; for (const [key, value] of data) { value.touch = seq; value.type = typeof value.type === 'number' ? value.type : CompletionItemKinds.fromString(value.type); this._cache.set(key, value); } this._seq = this._cache.size; } } export class PrefixMemory extends Memory { constructor() { super('recentlyUsedByPrefix'); } private _trie = TernarySearchTree.forStrings<MemItem>(); private _seq = 0; memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { const { word } = model.getWordUntilPosition(pos); const key = `${model.getLanguageId()}/${word}`; this._trie.set(key, { type: item.completion.kind, insertText: item.completion.insertText, touch: this._seq++ }); } override select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { const { word } = model.getWordUntilPosition(pos); if (!word) { return super.select(model, pos, items); } const key = `${model.getLanguageId()}/${word}`; let item = this._trie.get(key); if (!item) { item = this._trie.findSubstr(key); } if (item) { for (let i = 0; i < items.length; i++) { const { kind, insertText } = items[i].completion; if (kind === item.type && insertText === item.insertText) { return i; } } } return super.select(model, pos, items); } toJSON(): object { const entries: [string, MemItem][] = []; this._trie.forEach((value, key) => entries.push([key, value])); // sort by last recently used (touch), then // take the top 200 item and normalize their // touch entries .sort((a, b) => -(a[1].touch - b[1].touch)) .forEach((value, i) => value[1].touch = i); return entries.slice(0, 200); } fromJSON(data: [string, MemItem][]): void { this._trie.clear(); if (data.length > 0) { this._seq = data[0][1].touch + 1; for (const [key, value] of data) { value.type = typeof value.type === 'number' ? value.type : CompletionItemKinds.fromString(value.type); this._trie.set(key, value); } } } } export type MemMode = 'first' | 'recentlyUsed' | 'recentlyUsedByPrefix'; export class SuggestMemoryService implements ISuggestMemoryService { private static readonly _strategyCtors = new Map<MemMode, { new(): Memory }>([ ['recentlyUsedByPrefix', PrefixMemory], ['recentlyUsed', LRUMemory], ['first', NoMemory] ]); private static readonly _storagePrefix = 'suggest/memories'; readonly _serviceBrand: undefined; private readonly _persistSoon: RunOnceScheduler; private readonly _disposables = new DisposableStore(); private _strategy?: Memory; constructor( @IStorageService private readonly _storageService: IStorageService, @IConfigurationService private readonly _configService: IConfigurationService, ) { this._persistSoon = new RunOnceScheduler(() => this._saveState(), 500); this._disposables.add(_storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN) { this._saveState(); } })); } dispose(): void { this._disposables.dispose(); this._persistSoon.dispose(); } memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { this._withStrategy(model, pos).memorize(model, pos, item); this._persistSoon.schedule(); } select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { return this._withStrategy(model, pos).select(model, pos, items); } private _withStrategy(model: ITextModel, pos: IPosition): Memory { const mode = this._configService.getValue<MemMode>('editor.suggestSelection', { overrideIdentifier: model.getLanguageIdAtPosition(pos.lineNumber, pos.column), resource: model.uri }); if (this._strategy?.name !== mode) { this._saveState(); const ctor = SuggestMemoryService._strategyCtors.get(mode) || NoMemory; this._strategy = new ctor(); try { const share = this._configService.getValue<boolean>('editor.suggest.shareSuggestSelections'); const scope = share ? StorageScope.PROFILE : StorageScope.WORKSPACE; const raw = this._storageService.get(`${SuggestMemoryService._storagePrefix}/${mode}`, scope); if (raw) { this._strategy.fromJSON(JSON.parse(raw)); } } catch (e) { // things can go wrong with JSON... } } return this._strategy; } private _saveState() { if (this._strategy) { const share = this._configService.getValue<boolean>('editor.suggest.shareSuggestSelections'); const scope = share ? StorageScope.PROFILE : StorageScope.WORKSPACE; const raw = JSON.stringify(this._strategy); this._storageService.store(`${SuggestMemoryService._storagePrefix}/${this._strategy.name}`, raw, scope, StorageTarget.MACHINE); } } } export const ISuggestMemoryService = createDecorator<ISuggestMemoryService>('ISuggestMemories'); export interface ISuggestMemoryService { readonly _serviceBrand: undefined; memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void; select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number; } registerSingleton(ISuggestMemoryService, SuggestMemoryService, InstantiationType.Delayed);
src/vs/editor/contrib/suggest/browser/suggestMemory.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001789004891179502, 0.00017000135267153382, 0.0001661843416513875, 0.000169434177223593, 0.000002707796284084907 ]
{ "id": 4, "code_window": [ "\t\t\trenderOverviewRuler: false,\n", "\t\t\tdiffAlgorithm: 'advanced',\n" ], "labels": [ "add", "keep" ], "after_edit": [ "\t\t\trulers: undefined,\n", "\t\t\toverviewRulerBorder: undefined,\n", "\t\t\toverviewRulerLanes: 0,\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 57 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { IdleDeadline, runWhenIdle } from 'vs/base/common/async'; import { BugIndicatingError, onUnexpectedError } from 'vs/base/common/errors'; import { Disposable, MutableDisposable } from 'vs/base/common/lifecycle'; import { setTimeout0 } from 'vs/base/common/platform'; import { StopWatch } from 'vs/base/common/stopwatch'; import { countEOL } from 'vs/editor/common/core/eolCounter'; import { Position } from 'vs/editor/common/core/position'; import { IRange } from 'vs/editor/common/core/range'; import { StandardTokenType } from 'vs/editor/common/encodedTokenAttributes'; import { EncodedTokenizationResult, IBackgroundTokenizationStore, IBackgroundTokenizer, ILanguageIdCodec, IState, ITokenizationSupport, TokenizationRegistry } from 'vs/editor/common/languages'; import { nullTokenizeEncoded } from 'vs/editor/common/languages/nullTokenize'; import { ITextModel } from 'vs/editor/common/model'; import { TextModel } from 'vs/editor/common/model/textModel'; import { TokenizationTextModelPart } from 'vs/editor/common/model/tokenizationTextModelPart'; import { IModelContentChangedEvent, IModelLanguageChangedEvent } from 'vs/editor/common/textModelEvents'; import { ContiguousMultilineTokensBuilder } from 'vs/editor/common/tokens/contiguousMultilineTokensBuilder'; import { LineTokens } from 'vs/editor/common/tokens/lineTokens'; const enum Constants { CHEAP_TOKENIZATION_LENGTH_LIMIT = 2048 } /** * An array that avoids being sparse by always * filling up unused indices with a default value. */ export class ContiguousGrowingArray<T> { private _store: T[] = []; constructor( private readonly _default: T ) { } public get(index: number): T { if (index < this._store.length) { return this._store[index]; } return this._default; } public set(index: number, value: T): void { while (index >= this._store.length) { this._store[this._store.length] = this._default; } this._store[index] = value; } // TODO have `replace` instead of `delete` and `insert` public delete(deleteIndex: number, deleteCount: number): void { if (deleteCount === 0 || deleteIndex >= this._store.length) { return; } this._store.splice(deleteIndex, deleteCount); } public insert(insertIndex: number, insertCount: number): void { if (insertCount === 0 || insertIndex >= this._store.length) { return; } const arr: T[] = []; for (let i = 0; i < insertCount; i++) { arr[i] = this._default; } this._store = arrays.arrayInsert(this._store, insertIndex, arr); } } /** * Stores the states at the start of each line and keeps track of which lines * must be re-tokenized. Also uses state equality to quickly validate lines * that don't need to be re-tokenized. * * For example, when typing on a line, the line gets marked as needing to be tokenized. * Once the line is tokenized, the end state is checked for equality against the begin * state of the next line. If the states are equal, tokenization doesn't need to run * again over the rest of the file. If the states are not equal, the next line gets marked * as needing to be tokenized. */ export class TokenizationStateStore { requestTokens(startLineNumber: number, endLineNumberExclusive: number): void { for (let lineNumber = startLineNumber; lineNumber < endLineNumberExclusive; lineNumber++) { this._stateStore.markMustBeTokenized(lineNumber - 1); } } }
src/vs/editor/test/node/diffing/fixtures/class-replacement/1.tst
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00018170858675148338, 0.0001728473580442369, 0.0001665892341407016, 0.000171082210727036, 0.0000055387404245266225 ]
{ "id": 5, "code_window": [ "\t\t\tdiffAlgorithm: 'advanced',\n", "\t\t\tsplitViewDefaultRatio: 0.35\n", "\t\t}, {\n", "\t\t\toriginalEditor: { contributions: diffContributions },\n", "\t\t\tmodifiedEditor: { contributions: diffContributions }\n", "\t\t}, editor);\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsplitViewDefaultRatio: 0.35,\n", "\t\t\tpadding: { top: 0, bottom: 0 },\n", "\t\t\tfolding: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\tminimap: { enabled: false },\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.056396689265966415, 0.002658467972651124, 0.00016503474034834653, 0.00017381604993715882, 0.011214504949748516 ]
{ "id": 5, "code_window": [ "\t\t\tdiffAlgorithm: 'advanced',\n", "\t\t\tsplitViewDefaultRatio: 0.35\n", "\t\t}, {\n", "\t\t\toriginalEditor: { contributions: diffContributions },\n", "\t\t\tmodifiedEditor: { contributions: diffContributions }\n", "\t\t}, editor);\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsplitViewDefaultRatio: 0.35,\n", "\t\t\tpadding: { top: 0, bottom: 0 },\n", "\t\t\tfolding: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\tminimap: { enabled: false },\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { illegalArgument } from 'vs/base/common/errors'; import { escapeIcons } from 'vs/base/common/iconLabels'; import { isEqual } from 'vs/base/common/resources'; import { escapeRegExpCharacters } from 'vs/base/common/strings'; import { URI, UriComponents } from 'vs/base/common/uri'; export interface MarkdownStringTrustedOptions { readonly enabledCommands: readonly string[]; } export interface IMarkdownString { readonly value: string; readonly isTrusted?: boolean | MarkdownStringTrustedOptions; readonly supportThemeIcons?: boolean; readonly supportHtml?: boolean; readonly baseUri?: UriComponents; uris?: { [href: string]: UriComponents }; } export const enum MarkdownStringTextNewlineStyle { Paragraph = 0, Break = 1, } export class MarkdownString implements IMarkdownString { public value: string; public isTrusted?: boolean | MarkdownStringTrustedOptions; public supportThemeIcons?: boolean; public supportHtml?: boolean; public baseUri?: URI; constructor( value: string = '', isTrustedOrOptions: boolean | { isTrusted?: boolean | MarkdownStringTrustedOptions; supportThemeIcons?: boolean; supportHtml?: boolean } = false, ) { this.value = value; if (typeof this.value !== 'string') { throw illegalArgument('value'); } if (typeof isTrustedOrOptions === 'boolean') { this.isTrusted = isTrustedOrOptions; this.supportThemeIcons = false; this.supportHtml = false; } else { this.isTrusted = isTrustedOrOptions.isTrusted ?? undefined; this.supportThemeIcons = isTrustedOrOptions.supportThemeIcons ?? false; this.supportHtml = isTrustedOrOptions.supportHtml ?? false; } } appendText(value: string, newlineStyle: MarkdownStringTextNewlineStyle = MarkdownStringTextNewlineStyle.Paragraph): MarkdownString { this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? escapeIcons(value) : value) .replace(/([ \t]+)/g, (_match, g1) => '&nbsp;'.repeat(g1.length)) .replace(/\>/gm, '\\>') .replace(/\n/g, newlineStyle === MarkdownStringTextNewlineStyle.Break ? '\\\n' : '\n\n'); return this; } appendMarkdown(value: string): MarkdownString { this.value += value; return this; } appendCodeblock(langId: string, code: string): MarkdownString { this.value += '\n```'; this.value += langId; this.value += '\n'; this.value += code; this.value += '\n```\n'; return this; } appendLink(target: URI | string, label: string, title?: string): MarkdownString { this.value += '['; this.value += this._escape(label, ']'); this.value += ']('; this.value += this._escape(String(target), ')'); if (title) { this.value += ` "${this._escape(this._escape(title, '"'), ')')}"`; } this.value += ')'; return this; } private _escape(value: string, ch: string): string { const r = new RegExp(escapeRegExpCharacters(ch), 'g'); return value.replace(r, (match, offset) => { if (value.charAt(offset - 1) !== '\\') { return `\\${match}`; } else { return match; } }); } } export function isEmptyMarkdownString(oneOrMany: IMarkdownString | IMarkdownString[] | null | undefined): boolean { if (isMarkdownString(oneOrMany)) { return !oneOrMany.value; } else if (Array.isArray(oneOrMany)) { return oneOrMany.every(isEmptyMarkdownString); } else { return true; } } export function isMarkdownString(thing: any): thing is IMarkdownString { if (thing instanceof MarkdownString) { return true; } else if (thing && typeof thing === 'object') { return typeof (<IMarkdownString>thing).value === 'string' && (typeof (<IMarkdownString>thing).isTrusted === 'boolean' || (<IMarkdownString>thing).isTrusted === undefined) && (typeof (<IMarkdownString>thing).supportThemeIcons === 'boolean' || (<IMarkdownString>thing).supportThemeIcons === undefined); } return false; } export function markdownStringEqual(a: IMarkdownString, b: IMarkdownString): boolean { if (a === b) { return true; } else if (!a || !b) { return false; } else { return a.value === b.value && a.isTrusted === b.isTrusted && a.supportThemeIcons === b.supportThemeIcons && a.supportHtml === b.supportHtml && (a.baseUri === b.baseUri || !!a.baseUri && !!b.baseUri && isEqual(URI.from(a.baseUri), URI.from(b.baseUri))); } } export function escapeMarkdownSyntaxTokens(text: string): string { // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash return text.replace(/[\\`*_{}[\]()#+\-!~]/g, '\\$&'); } export function escapeDoubleQuotes(input: string) { return input.replace(/"/g, '&quot;'); } export function removeMarkdownEscapes(text: string): string { if (!text) { return text; } return text.replace(/\\([\\`*_{}[\]()#+\-.!~])/g, '$1'); } export function parseHrefAndDimensions(href: string): { href: string; dimensions: string[] } { const dimensions: string[] = []; const splitted = href.split('|').map(s => s.trim()); href = splitted[0]; const parameters = splitted[1]; if (parameters) { const heightFromParams = /height=(\d+)/.exec(parameters); const widthFromParams = /width=(\d+)/.exec(parameters); const height = heightFromParams ? heightFromParams[1] : ''; const width = widthFromParams ? widthFromParams[1] : ''; const widthIsFinite = isFinite(parseInt(width)); const heightIsFinite = isFinite(parseInt(height)); if (widthIsFinite) { dimensions.push(`width="${width}"`); } if (heightIsFinite) { dimensions.push(`height="${height}"`); } } return { href, dimensions }; }
src/vs/base/common/htmlContent.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017616181867197156, 0.00017141558055300266, 0.000166525220265612, 0.00017197817214764655, 0.000003077110250160331 ]
{ "id": 5, "code_window": [ "\t\t\tdiffAlgorithm: 'advanced',\n", "\t\t\tsplitViewDefaultRatio: 0.35\n", "\t\t}, {\n", "\t\t\toriginalEditor: { contributions: diffContributions },\n", "\t\t\tmodifiedEditor: { contributions: diffContributions }\n", "\t\t}, editor);\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsplitViewDefaultRatio: 0.35,\n", "\t\t\tpadding: { top: 0, bottom: 0 },\n", "\t\t\tfolding: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\tminimap: { enabled: false },\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Queue } from 'vs/base/common/async'; import { VSBuffer } from 'vs/base/common/buffer'; import { Disposable } from 'vs/base/common/lifecycle'; import { Emitter, Event } from 'vs/base/common/event'; import { ResourceMap } from 'vs/base/common/map'; import { URI, UriComponents } from 'vs/base/common/uri'; import { Metadata, isIExtensionIdentifier } from 'vs/platform/extensionManagement/common/extensionManagement'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { IExtension, IExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { FileOperationResult, IFileService, toFileOperationResult } from 'vs/platform/files/common/files'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ILogService } from 'vs/platform/log/common/log'; import { IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { Mutable, isObject, isString, isUndefined } from 'vs/base/common/types'; import { getErrorMessage } from 'vs/base/common/errors'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; interface IStoredProfileExtension { identifier: IExtensionIdentifier; location: UriComponents | string; relativeLocation: string | undefined; version: string; metadata?: Metadata; } export const enum ExtensionsProfileScanningErrorCode { /** * Error when trying to scan extensions from a profile that does not exist. */ ERROR_PROFILE_NOT_FOUND = 'ERROR_PROFILE_NOT_FOUND', /** * Error when profile file is invalid. */ ERROR_INVALID_CONTENT = 'ERROR_INVALID_CONTENT', } export class ExtensionsProfileScanningError extends Error { constructor(message: string, public code: ExtensionsProfileScanningErrorCode) { super(message); } } export interface IScannedProfileExtension { readonly identifier: IExtensionIdentifier; readonly version: string; readonly location: URI; readonly metadata?: Metadata; } export interface ProfileExtensionsEvent { readonly extensions: readonly IScannedProfileExtension[]; readonly profileLocation: URI; } export interface DidAddProfileExtensionsEvent extends ProfileExtensionsEvent { readonly error?: Error; } export interface DidRemoveProfileExtensionsEvent extends ProfileExtensionsEvent { readonly error?: Error; } export interface IProfileExtensionsScanOptions { readonly bailOutWhenFileNotFound?: boolean; } export const IExtensionsProfileScannerService = createDecorator<IExtensionsProfileScannerService>('IExtensionsProfileScannerService'); export interface IExtensionsProfileScannerService { readonly _serviceBrand: undefined; readonly onAddExtensions: Event<ProfileExtensionsEvent>; readonly onDidAddExtensions: Event<DidAddProfileExtensionsEvent>; readonly onRemoveExtensions: Event<ProfileExtensionsEvent>; readonly onDidRemoveExtensions: Event<DidRemoveProfileExtensionsEvent>; scanProfileExtensions(profileLocation: URI, options?: IProfileExtensionsScanOptions): Promise<IScannedProfileExtension[]>; addExtensionsToProfile(extensions: [IExtension, Metadata | undefined][], profileLocation: URI): Promise<IScannedProfileExtension[]>; updateMetadata(extensions: [IExtension, Metadata | undefined][], profileLocation: URI): Promise<IScannedProfileExtension[]>; removeExtensionFromProfile(extension: IExtension, profileLocation: URI): Promise<void>; } export abstract class AbstractExtensionsProfileScannerService extends Disposable implements IExtensionsProfileScannerService { readonly _serviceBrand: undefined; private readonly _onAddExtensions = this._register(new Emitter<ProfileExtensionsEvent>()); readonly onAddExtensions = this._onAddExtensions.event; private readonly _onDidAddExtensions = this._register(new Emitter<DidAddProfileExtensionsEvent>()); readonly onDidAddExtensions = this._onDidAddExtensions.event; private readonly _onRemoveExtensions = this._register(new Emitter<ProfileExtensionsEvent>()); readonly onRemoveExtensions = this._onRemoveExtensions.event; private readonly _onDidRemoveExtensions = this._register(new Emitter<DidRemoveProfileExtensionsEvent>()); readonly onDidRemoveExtensions = this._onDidRemoveExtensions.event; private readonly resourcesAccessQueueMap = new ResourceMap<Queue<IScannedProfileExtension[]>>(); constructor( private readonly extensionsLocation: URI, @IFileService private readonly fileService: IFileService, @IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @ITelemetryService private readonly telemetryService: ITelemetryService, @ILogService private readonly logService: ILogService, ) { super(); } scanProfileExtensions(profileLocation: URI, options?: IProfileExtensionsScanOptions): Promise<IScannedProfileExtension[]> { return this.withProfileExtensions(profileLocation, undefined, options); } async addExtensionsToProfile(extensions: [IExtension, Metadata | undefined][], profileLocation: URI): Promise<IScannedProfileExtension[]> { const extensionsToRemove: IScannedProfileExtension[] = []; const extensionsToAdd: IScannedProfileExtension[] = []; try { await this.withProfileExtensions(profileLocation, profileExtensions => { const result: IScannedProfileExtension[] = []; for (const extension of profileExtensions) { if (extensions.some(([e]) => areSameExtensions(e.identifier, extension.identifier) && e.manifest.version !== extension.version)) { // Remove the existing extension with different version extensionsToRemove.push(extension); } else { result.push(extension); } } for (const [extension, metadata] of extensions) { if (!result.some(e => areSameExtensions(e.identifier, extension.identifier) && e.version === extension.manifest.version)) { // Add only if the same version of the extension is not already added const extensionToAdd = { identifier: extension.identifier, version: extension.manifest.version, location: extension.location, metadata }; extensionsToAdd.push(extensionToAdd); result.push(extensionToAdd); } } if (extensionsToAdd.length) { this._onAddExtensions.fire({ extensions: extensionsToAdd, profileLocation }); } if (extensionsToRemove.length) { this._onRemoveExtensions.fire({ extensions: extensionsToRemove, profileLocation }); } return result; }); if (extensionsToAdd.length) { this._onDidAddExtensions.fire({ extensions: extensionsToAdd, profileLocation }); } if (extensionsToRemove.length) { this._onDidRemoveExtensions.fire({ extensions: extensionsToRemove, profileLocation }); } return extensionsToAdd; } catch (error) { if (extensionsToAdd.length) { this._onDidAddExtensions.fire({ extensions: extensionsToAdd, error, profileLocation }); } if (extensionsToRemove.length) { this._onDidRemoveExtensions.fire({ extensions: extensionsToRemove, error, profileLocation }); } throw error; } } async updateMetadata(extensions: [IExtension, Metadata][], profileLocation: URI): Promise<IScannedProfileExtension[]> { const updatedExtensions: IScannedProfileExtension[] = []; await this.withProfileExtensions(profileLocation, profileExtensions => { const result: IScannedProfileExtension[] = []; for (const profileExtension of profileExtensions) { const extension = extensions.find(([e]) => areSameExtensions(e.identifier, profileExtension.identifier) && e.manifest.version === profileExtension.version); if (extension) { profileExtension.metadata = { ...profileExtension.metadata, ...extension[1] }; updatedExtensions.push(profileExtension); result.push(profileExtension); } else { result.push(profileExtension); } } return result; }); return updatedExtensions; } async removeExtensionFromProfile(extension: IExtension, profileLocation: URI): Promise<void> { const extensionsToRemove: IScannedProfileExtension[] = []; this._onRemoveExtensions.fire({ extensions: extensionsToRemove, profileLocation }); try { await this.withProfileExtensions(profileLocation, profileExtensions => { const result: IScannedProfileExtension[] = []; for (const e of profileExtensions) { if (areSameExtensions(e.identifier, extension.identifier)) { extensionsToRemove.push(e); } else { result.push(e); } } if (extensionsToRemove.length) { this._onRemoveExtensions.fire({ extensions: extensionsToRemove, profileLocation }); } return result; }); if (extensionsToRemove.length) { this._onDidRemoveExtensions.fire({ extensions: extensionsToRemove, profileLocation }); } } catch (error) { if (extensionsToRemove.length) { this._onDidRemoveExtensions.fire({ extensions: extensionsToRemove, error, profileLocation }); } throw error; } } private async withProfileExtensions(file: URI, updateFn?: (extensions: Mutable<IScannedProfileExtension>[]) => IScannedProfileExtension[], options?: IProfileExtensionsScanOptions): Promise<IScannedProfileExtension[]> { return this.getResourceAccessQueue(file).queue(async () => { let extensions: IScannedProfileExtension[] = []; // Read let storedProfileExtensions: IStoredProfileExtension[] | undefined; try { const content = await this.fileService.readFile(file); storedProfileExtensions = JSON.parse(content.value.toString().trim() || '[]'); } catch (error) { if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) { throw error; } // migrate from old location, remove this after couple of releases if (this.uriIdentityService.extUri.isEqual(file, this.userDataProfilesService.defaultProfile.extensionsResource)) { storedProfileExtensions = await this.migrateFromOldDefaultProfileExtensionsLocation(); } if (!storedProfileExtensions && options?.bailOutWhenFileNotFound) { throw new ExtensionsProfileScanningError(getErrorMessage(error), ExtensionsProfileScanningErrorCode.ERROR_PROFILE_NOT_FOUND); } } if (storedProfileExtensions) { if (!Array.isArray(storedProfileExtensions)) { this.reportAndThrowInvalidConentError(file); } // TODO @sandy081: Remove this migration after couple of releases let migrate = false; for (const e of storedProfileExtensions) { if (!isStoredProfileExtension(e)) { this.reportAndThrowInvalidConentError(file); } let location: URI; if (isString(e.relativeLocation) && e.relativeLocation) { // Extension in new format. No migration needed. location = this.resolveExtensionLocation(e.relativeLocation); } else if (isString(e.location)) { // Extension in intermediate format. Migrate to new format. location = this.resolveExtensionLocation(e.location); migrate = true; e.relativeLocation = e.location; // retain old format so that old clients can read it e.location = location.toJSON(); } else { location = URI.revive(e.location); const relativePath = this.toRelativePath(location); if (relativePath) { // Extension in old format. Migrate to new format. migrate = true; e.relativeLocation = relativePath; } } extensions.push({ identifier: e.identifier, location, version: e.version, metadata: e.metadata, }); } if (migrate) { await this.fileService.writeFile(file, VSBuffer.fromString(JSON.stringify(storedProfileExtensions))); } } // Update if (updateFn) { extensions = updateFn(extensions); const storedProfileExtensions: IStoredProfileExtension[] = extensions.map(e => ({ identifier: e.identifier, version: e.version, // retain old format so that old clients can read it location: e.location.toJSON(), relativeLocation: this.toRelativePath(e.location), metadata: e.metadata })); await this.fileService.writeFile(file, VSBuffer.fromString(JSON.stringify(storedProfileExtensions))); } return extensions; }); } private reportAndThrowInvalidConentError(file: URI): void { type ErrorClassification = { owner: 'sandy081'; comment: 'Information about the error that occurred while scanning'; code: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'error code' }; }; const error = new ExtensionsProfileScanningError(`Invalid extensions content in ${file.toString()}`, ExtensionsProfileScanningErrorCode.ERROR_INVALID_CONTENT); this.telemetryService.publicLogError2<{ code: string }, ErrorClassification>('extensionsProfileScanningError', { code: error.code }); throw error; } private toRelativePath(extensionLocation: URI): string | undefined { return this.uriIdentityService.extUri.isEqual(this.uriIdentityService.extUri.dirname(extensionLocation), this.extensionsLocation) ? this.uriIdentityService.extUri.basename(extensionLocation) : undefined; } private resolveExtensionLocation(path: string): URI { return this.uriIdentityService.extUri.joinPath(this.extensionsLocation, path); } private _migrationPromise: Promise<IStoredProfileExtension[] | undefined> | undefined; private async migrateFromOldDefaultProfileExtensionsLocation(): Promise<IStoredProfileExtension[] | undefined> { if (!this._migrationPromise) { this._migrationPromise = (async () => { const oldDefaultProfileExtensionsLocation = this.uriIdentityService.extUri.joinPath(this.userDataProfilesService.defaultProfile.location, 'extensions.json'); const oldDefaultProfileExtensionsInitLocation = this.uriIdentityService.extUri.joinPath(this.extensionsLocation, '.init-default-profile-extensions'); let content: string; try { content = (await this.fileService.readFile(oldDefaultProfileExtensionsLocation)).value.toString(); } catch (error) { if (toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND) { return undefined; } throw error; } this.logService.info('Migrating extensions from old default profile location', oldDefaultProfileExtensionsLocation.toString()); let storedProfileExtensions: IStoredProfileExtension[] | undefined; try { const parsedData = JSON.parse(content); if (Array.isArray(parsedData) && parsedData.every(candidate => isStoredProfileExtension(candidate))) { storedProfileExtensions = parsedData; } else { this.logService.warn('Skipping migrating from old default profile locaiton: Found invalid data', parsedData); } } catch (error) { /* Ignore */ this.logService.error(error); } if (storedProfileExtensions) { try { await this.fileService.createFile(this.userDataProfilesService.defaultProfile.extensionsResource, VSBuffer.fromString(JSON.stringify(storedProfileExtensions)), { overwrite: false }); this.logService.info('Migrated extensions from old default profile location to new location', oldDefaultProfileExtensionsLocation.toString(), this.userDataProfilesService.defaultProfile.extensionsResource.toString()); } catch (error) { if (toFileOperationResult(error) === FileOperationResult.FILE_MODIFIED_SINCE) { this.logService.info('Migration from old default profile location to new location is done by another window', oldDefaultProfileExtensionsLocation.toString(), this.userDataProfilesService.defaultProfile.extensionsResource.toString()); } else { throw error; } } } try { await this.fileService.del(oldDefaultProfileExtensionsLocation); } catch (error) { if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) { this.logService.error(error); } } try { await this.fileService.del(oldDefaultProfileExtensionsInitLocation); } catch (error) { if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) { this.logService.error(error); } } return storedProfileExtensions; })(); } return this._migrationPromise; } private getResourceAccessQueue(file: URI): Queue<IScannedProfileExtension[]> { let resourceQueue = this.resourcesAccessQueueMap.get(file); if (!resourceQueue) { resourceQueue = new Queue<IScannedProfileExtension[]>(); this.resourcesAccessQueueMap.set(file, resourceQueue); } return resourceQueue; } } function isStoredProfileExtension(candidate: any): candidate is IStoredProfileExtension { return isObject(candidate) && isIExtensionIdentifier(candidate.identifier) && (isUriComponents(candidate.location) || (isString(candidate.location) && candidate.location)) && (isUndefined(candidate.relativeLocation) || isString(candidate.relativeLocation)) && candidate.version && isString(candidate.version); } function isUriComponents(thing: unknown): thing is UriComponents { if (!thing) { return false; } return isString((<any>thing).path) && isString((<any>thing).scheme); }
src/vs/platform/extensionManagement/common/extensionsProfileScannerService.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00019182323012501001, 0.00017345418746117502, 0.00016406072245445102, 0.00017303442291449755, 0.000005156918177817715 ]
{ "id": 5, "code_window": [ "\t\t\tdiffAlgorithm: 'advanced',\n", "\t\t\tsplitViewDefaultRatio: 0.35\n", "\t\t}, {\n", "\t\t\toriginalEditor: { contributions: diffContributions },\n", "\t\t\tmodifiedEditor: { contributions: diffContributions }\n", "\t\t}, editor);\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tsplitViewDefaultRatio: 0.35,\n", "\t\t\tpadding: { top: 0, bottom: 0 },\n", "\t\t\tfolding: false,\n", "\t\t\tdiffCodeLens: false,\n", "\t\t\tstickyScroll: { enabled: false },\n", "\t\t\tminimap: { enabled: false },\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Color, HSLA } from 'vs/base/common/color'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange } from 'vs/editor/common/core/range'; import { IColor, IColorInformation } from 'vs/editor/common/languages'; export interface IDocumentColorComputerTarget { getValue(): string; positionAt(offset: number): IPosition; findMatches(regex: RegExp): RegExpMatchArray[]; } function _parseCaptureGroups(captureGroups: IterableIterator<string>) { const values = []; for (const captureGroup of captureGroups) { const parsedNumber = Number(captureGroup); if (parsedNumber || parsedNumber === 0 && captureGroup.replace(/\s/g, '') !== '') { values.push(parsedNumber); } } return values; } function _toIColor(r: number, g: number, b: number, a: number): IColor { return { red: r / 255, blue: b / 255, green: g / 255, alpha: a }; } function _findRange(model: IDocumentColorComputerTarget, match: RegExpMatchArray): IRange | undefined { const index = match.index; const length = match[0].length; if (!index) { return; } const startPosition = model.positionAt(index); const range: IRange = { startLineNumber: startPosition.lineNumber, startColumn: startPosition.column, endLineNumber: startPosition.lineNumber, endColumn: startPosition.column + length }; return range; } function _findHexColorInformation(range: IRange | undefined, hexValue: string) { if (!range) { return; } const parsedHexColor = Color.Format.CSS.parseHex(hexValue); if (!parsedHexColor) { return; } return { range: range, color: _toIColor(parsedHexColor.rgba.r, parsedHexColor.rgba.g, parsedHexColor.rgba.b, parsedHexColor.rgba.a) }; } function _findRGBColorInformation(range: IRange | undefined, matches: RegExpMatchArray[], isAlpha: boolean) { if (!range || matches.length !== 1) { return; } const match = matches[0]!; const captureGroups = match.values(); const parsedRegex = _parseCaptureGroups(captureGroups); return { range: range, color: _toIColor(parsedRegex[0], parsedRegex[1], parsedRegex[2], isAlpha ? parsedRegex[3] : 1) }; } function _findHSLColorInformation(range: IRange | undefined, matches: RegExpMatchArray[], isAlpha: boolean) { if (!range || matches.length !== 1) { return; } const match = matches[0]!; const captureGroups = match.values(); const parsedRegex = _parseCaptureGroups(captureGroups); const colorEquivalent = new Color(new HSLA(parsedRegex[0], parsedRegex[1] / 100, parsedRegex[2] / 100, isAlpha ? parsedRegex[3] : 1)); return { range: range, color: _toIColor(colorEquivalent.rgba.r, colorEquivalent.rgba.g, colorEquivalent.rgba.b, colorEquivalent.rgba.a) }; } function _findMatches(model: IDocumentColorComputerTarget | string, regex: RegExp): RegExpMatchArray[] { if (typeof model === 'string') { return [...model.matchAll(regex)]; } else { return model.findMatches(regex); } } function computeColors(model: IDocumentColorComputerTarget): IColorInformation[] { const result: IColorInformation[] = []; // Early validation for RGB and HSL const initialValidationRegex = /\b(rgb|rgba|hsl|hsla)(\([0-9\s,.\%]*\))|(#)([A-Fa-f0-9]{6})\b|(#)([A-Fa-f0-9]{8})\b/gm; const initialValidationMatches = _findMatches(model, initialValidationRegex); // Potential colors have been found, validate the parameters if (initialValidationMatches.length > 0) { for (const initialMatch of initialValidationMatches) { const initialCaptureGroups = initialMatch.filter(captureGroup => captureGroup !== undefined); const colorScheme = initialCaptureGroups[1]; const colorParameters = initialCaptureGroups[2]; if (!colorParameters) { continue; } let colorInformation; if (colorScheme === 'rgb') { const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*\)$/gm; colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false); } else if (colorScheme === 'rgba') { const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm; colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true); } else if (colorScheme === 'hsl') { const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*\)$/gm; colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false); } else if (colorScheme === 'hsla') { const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm; colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true); } else if (colorScheme === '#') { colorInformation = _findHexColorInformation(_findRange(model, initialMatch), colorScheme + colorParameters); } if (colorInformation) { result.push(colorInformation); } } } return result; } /** * Returns an array of all default document colors in the provided document */ export function computeDefaultDocumentColors(model: IDocumentColorComputerTarget): IColorInformation[] { if (!model || typeof model.getValue !== 'function' || typeof model.positionAt !== 'function') { // Unknown caller! return []; } return computeColors(model); }
src/vs/editor/common/languages/defaultDocumentColorsComputer.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001772029499989003, 0.00017164407472591847, 0.00016492306895088404, 0.00017252516408916563, 0.000003444248022788088 ]
{ "id": 6, "code_window": [ "\t\t\tthis.hide();\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis._hideEditorRanges(this.editor, [ranges.modifiedHidden]);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.9958460927009583, 0.04636004939675331, 0.0001619696558918804, 0.0005537270335480571, 0.1982228308916092 ]
{ "id": 6, "code_window": [ "\t\t\tthis.hide();\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis._hideEditorRanges(this.editor, [ranges.modifiedHidden]);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 129 }
/*--------------------------------------------------------------------------------------------- * 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 { join } from 'path'; import * as vscode from 'vscode'; import { closeAllEditors, pathEquals } from '../utils'; suite('vscode API - workspace', () => { teardown(closeAllEditors); test('rootPath', () => { assert.ok(pathEquals(vscode.workspace.rootPath!, join(__dirname, '../../testWorkspace'))); }); test('workspaceFile', () => { assert.ok(pathEquals(vscode.workspace.workspaceFile!.fsPath, join(__dirname, '../../testworkspace.code-workspace'))); }); test('workspaceFolders', () => { assert.strictEqual(vscode.workspace.workspaceFolders!.length, 2); assert.ok(pathEquals(vscode.workspace.workspaceFolders![0].uri.fsPath, join(__dirname, '../../testWorkspace'))); assert.ok(pathEquals(vscode.workspace.workspaceFolders![1].uri.fsPath, join(__dirname, '../../testWorkspace2'))); assert.ok(pathEquals(vscode.workspace.workspaceFolders![1].name, 'Test Workspace 2')); }); test('getWorkspaceFolder', () => { const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(join(__dirname, '../../testWorkspace2/far.js'))); assert.ok(!!folder); if (folder) { assert.ok(pathEquals(folder.uri.fsPath, join(__dirname, '../../testWorkspace2'))); } }); });
extensions/vscode-api-tests/src/workspace-tests/workspace.test.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.000175889756064862, 0.00017463114636484534, 0.00017316709272563457, 0.00017473385378252715, 0.000001185472001452581 ]
{ "id": 6, "code_window": [ "\t\t\tthis.hide();\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis._hideEditorRanges(this.editor, [ranges.modifiedHidden]);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; export const Categories = Object.freeze({ View: { value: localize('view', "View"), original: 'View' }, Help: { value: localize('help', "Help"), original: 'Help' }, Test: { value: localize('test', "Test"), original: 'Test' }, File: { value: localize('file', "File"), original: 'File' }, Preferences: { value: localize('preferences', "Preferences"), original: 'Preferences' }, Developer: { value: localize({ key: 'developer', comment: ['A developer on Code itself or someone diagnosing issues in Code'] }, "Developer"), original: 'Developer' } });
src/vs/platform/action/common/actionCommonCategories.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017599560669623315, 0.00017452357860747725, 0.00017305155051872134, 0.00017452357860747725, 0.0000014720280887559056 ]
{ "id": 6, "code_window": [ "\t\t\tthis.hide();\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis._hideEditorRanges(this.editor, [ranges.modifiedHidden]);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n", "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 129 }
#!/usr/bin/env bash if [[ "$OSTYPE" == "darwin"* ]]; then realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"; } ROOT=$(dirname $(dirname $(realpath "$0"))) else ROOT=$(dirname $(dirname $(readlink -f $0))) fi DEVELOPER=$(xcode-select -print-path) LIPO=$(xcrun -sdk iphoneos -find lipo) cat <<-EOF > /path/file # A heredoc with a variable $DEVELOPER some more file EOF function code() { cd $ROOT # Node modules test -d node_modules || ./scripts/npm.sh install # Configuration export NODE_ENV=development # Launch Code if [[ "$OSTYPE" == "darwin"* ]]; then exec ./.build/electron/Electron.app/Contents/MacOS/Electron . "$@" else exec ./.build/electron/electron . "$@" fi } code "$@"
extensions/vscode-colorize-tests/test/colorize-fixtures/test.sh
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017352608847431839, 0.00016939829220063984, 0.00016183302795980126, 0.00017111701890826225, 0.000004659078513213899 ]
{ "id": 7, "code_window": [ "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n", "\n", "\t\tthis._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.17624631524085999, 0.013781423680484295, 0.00016287784092128277, 0.0003408387419767678, 0.04252691566944122 ]
{ "id": 7, "code_window": [ "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n", "\n", "\t\tthis._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Command, CommandManager } from '../commands/commandManager'; import { isSupportedLanguageMode } from '../configuration/languageIds'; import { API } from '../tsServer/api'; import * as typeConverters from '../typeConverters'; import { ITypeScriptServiceClient } from '../typescriptService'; class FileReferencesCommand implements Command { public static readonly context = 'tsSupportsFileReferences'; public static readonly minVersion = API.v420; public readonly id = 'typescript.findAllFileReferences'; public constructor( private readonly client: ITypeScriptServiceClient ) { } public async execute(resource?: vscode.Uri) { if (this.client.apiVersion.lt(FileReferencesCommand.minVersion)) { vscode.window.showErrorMessage(vscode.l10n.t("Find file references failed. Requires TypeScript 4.2+.")); return; } resource ??= vscode.window.activeTextEditor?.document.uri; if (!resource) { vscode.window.showErrorMessage(vscode.l10n.t("Find file references failed. No resource provided.")); return; } const document = await vscode.workspace.openTextDocument(resource); if (!isSupportedLanguageMode(document)) { vscode.window.showErrorMessage(vscode.l10n.t("Find file references failed. Unsupported file type.")); return; } const openedFiledPath = this.client.toOpenTsFilePath(document); if (!openedFiledPath) { vscode.window.showErrorMessage(vscode.l10n.t("Find file references failed. Unknown file type.")); return; } await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: vscode.l10n.t("Finding file references") }, async (_progress, token) => { const response = await this.client.execute('fileReferences', { file: openedFiledPath }, token); if (response.type !== 'response' || !response.body) { return; } const locations: vscode.Location[] = response.body.refs.map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference)); const config = vscode.workspace.getConfiguration('references'); const existingSetting = config.inspect<string>('preferredLocation'); await config.update('preferredLocation', 'view'); try { await vscode.commands.executeCommand('editor.action.showReferences', resource, new vscode.Position(0, 0), locations); } finally { await config.update('preferredLocation', existingSetting?.workspaceFolderValue ?? existingSetting?.workspaceValue); } }); } } export function register( client: ITypeScriptServiceClient, commandManager: CommandManager ) { function updateContext() { vscode.commands.executeCommand('setContext', FileReferencesCommand.context, client.apiVersion.gte(FileReferencesCommand.minVersion)); } updateContext(); commandManager.register(new FileReferencesCommand(client)); return client.onTsServerStarted(() => updateContext()); }
extensions/typescript-language-features/src/languageFeatures/fileReferences.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017552969802636653, 0.00017279136227443814, 0.00016981377848424017, 0.0001736596750561148, 0.000002119796363331261 ]
{ "id": 7, "code_window": [ "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n", "\n", "\t\tthis._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { timeout } from 'vs/base/common/async'; import { VSBuffer } from 'vs/base/common/buffer'; import { CancellationError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; import * as objects from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { removeDangerousEnvVariables } from 'vs/base/common/processes'; import { StopWatch } from 'vs/base/common/stopwatch'; import { withNullAsUndefined } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { generateUuid } from 'vs/base/common/uuid'; import { IMessagePassingProtocol } from 'vs/base/parts/ipc/common/ipc'; import { BufferedEmitter } from 'vs/base/parts/ipc/common/ipc.net'; import { acquirePort } from 'vs/base/parts/ipc/electron-sandbox/ipc.mp'; import { process } from 'vs/base/parts/sandbox/electron-sandbox/globals'; import * as nls from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { IExtensionHostProcessOptions, IExtensionHostStarter } from 'vs/platform/extensions/common/extensionHostStarter'; import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { ILabelService } from 'vs/platform/label/common/label'; import { ILogService, ILoggerService } from 'vs/platform/log/common/log'; import { INativeHostService } from 'vs/platform/native/common/native'; import { INotificationService, NotificationPriority, Severity } from 'vs/platform/notification/common/notification'; import { IProductService } from 'vs/platform/product/common/productService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { isLoggingOnly } from 'vs/platform/telemetry/common/telemetryUtils'; import { IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile'; import { IWorkspaceContextService, WorkbenchState, isUntitledWorkspace } from 'vs/platform/workspace/common/workspace'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService'; import { IShellEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/shellEnvironmentService'; import { MessagePortExtHostConnection, writeExtHostConnection } from 'vs/workbench/services/extensions/common/extensionHostEnv'; import { IExtensionHostInitData, MessageType, NativeLogMarkers, UIKind, isMessageOfType } from 'vs/workbench/services/extensions/common/extensionHostProtocol'; import { LocalProcessRunningLocation } from 'vs/workbench/services/extensions/common/extensionRunningLocation'; import { ExtensionHostExtensions, ExtensionHostStartup, IExtensionHost } from 'vs/workbench/services/extensions/common/extensions'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { ILifecycleService, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { parseExtensionDevOptions } from '../common/extensionDevOptions'; export interface ILocalProcessExtensionHostInitData { readonly allExtensions: IExtensionDescription[]; readonly myExtensions: ExtensionIdentifier[]; } export interface ILocalProcessExtensionHostDataProvider { getInitData(): Promise<ILocalProcessExtensionHostInitData>; } export class ExtensionHostProcess { private readonly _id: string; public get onStdout(): Event<string> { return this._extensionHostStarter.onDynamicStdout(this._id); } public get onStderr(): Event<string> { return this._extensionHostStarter.onDynamicStderr(this._id); } public get onMessage(): Event<any> { return this._extensionHostStarter.onDynamicMessage(this._id); } public get onExit(): Event<{ code: number; signal: string }> { return this._extensionHostStarter.onDynamicExit(this._id); } constructor( id: string, private readonly _extensionHostStarter: IExtensionHostStarter, ) { this._id = id; } public start(opts: IExtensionHostProcessOptions): Promise<void> { return this._extensionHostStarter.start(this._id, opts); } public enableInspectPort(): Promise<boolean> { return this._extensionHostStarter.enableInspectPort(this._id); } public kill(): Promise<void> { return this._extensionHostStarter.kill(this._id); } } export class NativeLocalProcessExtensionHost implements IExtensionHost { public readonly remoteAuthority = null; public readonly extensions = new ExtensionHostExtensions(); private readonly _onExit: Emitter<[number, string]> = new Emitter<[number, string]>(); public readonly onExit: Event<[number, string]> = this._onExit.event; private readonly _onDidSetInspectPort = new Emitter<void>(); protected readonly _toDispose = new DisposableStore(); private readonly _isExtensionDevHost: boolean; private readonly _isExtensionDevDebug: boolean; private readonly _isExtensionDevDebugBrk: boolean; private readonly _isExtensionDevTestFromCli: boolean; // State private _terminating: boolean; // Resources, in order they get acquired/created when .start() is called: private _inspectPort: number | null; private _extensionHostProcess: ExtensionHostProcess | null; private _messageProtocol: Promise<IMessagePassingProtocol> | null; constructor( public readonly runningLocation: LocalProcessRunningLocation, public readonly startup: ExtensionHostStartup.EagerAutoStart | ExtensionHostStartup.EagerManualStart, private readonly _initDataProvider: ILocalProcessExtensionHostDataProvider, @IWorkspaceContextService private readonly _contextService: IWorkspaceContextService, @INotificationService private readonly _notificationService: INotificationService, @INativeHostService private readonly _nativeHostService: INativeHostService, @ILifecycleService private readonly _lifecycleService: ILifecycleService, @INativeWorkbenchEnvironmentService private readonly _environmentService: INativeWorkbenchEnvironmentService, @IUserDataProfilesService private readonly _userDataProfilesService: IUserDataProfilesService, @ITelemetryService private readonly _telemetryService: ITelemetryService, @ILogService protected readonly _logService: ILogService, @ILoggerService protected readonly _loggerService: ILoggerService, @ILabelService private readonly _labelService: ILabelService, @IExtensionHostDebugService private readonly _extensionHostDebugService: IExtensionHostDebugService, @IHostService private readonly _hostService: IHostService, @IProductService private readonly _productService: IProductService, @IShellEnvironmentService private readonly _shellEnvironmentService: IShellEnvironmentService, @IExtensionHostStarter protected readonly _extensionHostStarter: IExtensionHostStarter, @IConfigurationService protected readonly _configurationService: IConfigurationService, ) { const devOpts = parseExtensionDevOptions(this._environmentService); this._isExtensionDevHost = devOpts.isExtensionDevHost; this._isExtensionDevDebug = devOpts.isExtensionDevDebug; this._isExtensionDevDebugBrk = devOpts.isExtensionDevDebugBrk; this._isExtensionDevTestFromCli = devOpts.isExtensionDevTestFromCli; this._terminating = false; this._inspectPort = null; this._extensionHostProcess = null; this._messageProtocol = null; this._toDispose.add(this._onExit); this._toDispose.add(this._lifecycleService.onWillShutdown(e => this._onWillShutdown(e))); this._toDispose.add(this._extensionHostDebugService.onClose(event => { if (this._isExtensionDevHost && this._environmentService.debugExtensionHost.debugId === event.sessionId) { this._nativeHostService.closeWindow(); } })); this._toDispose.add(this._extensionHostDebugService.onReload(event => { if (this._isExtensionDevHost && this._environmentService.debugExtensionHost.debugId === event.sessionId) { this._hostService.reload(); } })); } public dispose(): void { if (this._terminating) { return; } this._terminating = true; this._toDispose.dispose(); } public start(): Promise<IMessagePassingProtocol> { if (this._terminating) { // .terminate() was called throw new CancellationError(); } if (!this._messageProtocol) { this._messageProtocol = this._start(); } return this._messageProtocol; } protected async _start(): Promise<IMessagePassingProtocol> { const communication = this._toDispose.add(new ExtHostMessagePortCommunication(this._logService)); return this._startWithCommunication(communication); } protected async _startWithCommunication<T>(communication: IExtHostCommunication<T>): Promise<IMessagePassingProtocol> { const [extensionHostCreationResult, communicationPreparedData, portNumber, processEnv] = await Promise.all([ this._extensionHostStarter.createExtensionHost(), communication.prepare(), this._tryFindDebugPort(), this._shellEnvironmentService.getShellEnv(), ]); this._extensionHostProcess = new ExtensionHostProcess(extensionHostCreationResult.id, this._extensionHostStarter); const env = objects.mixin(processEnv, { VSCODE_AMD_ENTRYPOINT: 'vs/workbench/api/node/extensionHostProcess', VSCODE_HANDLES_UNCAUGHT_ERRORS: true }); if (this._environmentService.debugExtensionHost.env) { objects.mixin(env, this._environmentService.debugExtensionHost.env); } removeDangerousEnvVariables(env); if (this._isExtensionDevHost) { // Unset `VSCODE_CODE_CACHE_PATH` when developing extensions because it might // be that dependencies, that otherwise would be cached, get modified. delete env['VSCODE_CODE_CACHE_PATH']; } const opts: IExtensionHostProcessOptions = { responseWindowId: this._environmentService.window.id, responseChannel: 'vscode:startExtensionHostMessagePortResult', responseNonce: generateUuid(), env, // We only detach the extension host on windows. Linux and Mac orphan by default // and detach under Linux and Mac create another process group. // We detach because we have noticed that when the renderer exits, its child processes // (i.e. extension host) are taken down in a brutal fashion by the OS detached: !!platform.isWindows, execArgv: undefined as string[] | undefined, silent: true }; if (portNumber !== 0) { opts.execArgv = [ '--nolazy', (this._isExtensionDevDebugBrk ? '--inspect-brk=' : '--inspect=') + portNumber ]; } else { opts.execArgv = ['--inspect-port=0']; } if (this._environmentService.extensionTestsLocationURI) { opts.execArgv.unshift('--expose-gc'); } if (this._environmentService.args['prof-v8-extensions']) { opts.execArgv.unshift('--prof'); } // Catch all output coming from the extension host process type Output = { data: string; format: string[] }; const onStdout = this._handleProcessOutputStream(this._extensionHostProcess.onStdout); const onStderr = this._handleProcessOutputStream(this._extensionHostProcess.onStderr); const onOutput = Event.any( Event.map(onStdout.event, o => ({ data: `%c${o}`, format: [''] })), Event.map(onStderr.event, o => ({ data: `%c${o}`, format: ['color: red'] })) ); // Debounce all output, so we can render it in the Chrome console as a group const onDebouncedOutput = Event.debounce<Output>(onOutput, (r, o) => { return r ? { data: r.data + o.data, format: [...r.format, ...o.format] } : { data: o.data, format: o.format }; }, 100); // Print out extension host output onDebouncedOutput(output => { const inspectorUrlMatch = output.data && output.data.match(/ws:\/\/([^\s]+:(\d+)\/[^\s]+)/); if (inspectorUrlMatch) { if (!this._environmentService.isBuilt && !this._isExtensionDevTestFromCli) { console.log(`%c[Extension Host] %cdebugger inspector at devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=${inspectorUrlMatch[1]}`, 'color: blue', 'color:'); } if (!this._inspectPort) { this._inspectPort = Number(inspectorUrlMatch[2]); this._onDidSetInspectPort.fire(); } } else { if (!this._isExtensionDevTestFromCli) { console.group('Extension Host'); console.log(output.data, ...output.format); console.groupEnd(); } } }); // Lifecycle this._extensionHostProcess.onExit(({ code, signal }) => this._onExtHostProcessExit(code, signal)); // Notify debugger that we are ready to attach to the process if we run a development extension if (portNumber) { if (this._isExtensionDevHost && portNumber && this._isExtensionDevDebug && this._environmentService.debugExtensionHost.debugId) { this._extensionHostDebugService.attachSession(this._environmentService.debugExtensionHost.debugId, portNumber); } this._inspectPort = portNumber; this._onDidSetInspectPort.fire(); } // Help in case we fail to start it let startupTimeoutHandle: any; if (!this._environmentService.isBuilt && !this._environmentService.remoteAuthority || this._isExtensionDevHost) { startupTimeoutHandle = setTimeout(() => { this._logService.error(`[LocalProcessExtensionHost]: Extension host did not start in 10 seconds (debugBrk: ${this._isExtensionDevDebugBrk})`); const msg = this._isExtensionDevDebugBrk ? nls.localize('extensionHost.startupFailDebug', "Extension host did not start in 10 seconds, it might be stopped on the first line and needs a debugger to continue.") : nls.localize('extensionHost.startupFail', "Extension host did not start in 10 seconds, that might be a problem."); this._notificationService.prompt(Severity.Warning, msg, [{ label: nls.localize('reloadWindow', "Reload Window"), run: () => this._hostService.reload() }], { sticky: true, priority: NotificationPriority.URGENT } ); }, 10000); } // Initialize extension host process with hand shakes const protocol = await communication.establishProtocol(communicationPreparedData, this._extensionHostProcess, opts); await this._performHandshake(protocol); clearTimeout(startupTimeoutHandle); return protocol; } /** * Find a free port if extension host debugging is enabled. */ private async _tryFindDebugPort(): Promise<number> { if (typeof this._environmentService.debugExtensionHost.port !== 'number') { return 0; } const expected = this._environmentService.debugExtensionHost.port; const port = await this._nativeHostService.findFreePort(expected, 10 /* try 10 ports */, 5000 /* try up to 5 seconds */, 2048 /* skip 2048 ports between attempts */); if (!this._isExtensionDevTestFromCli) { if (!port) { console.warn('%c[Extension Host] %cCould not find a free port for debugging', 'color: blue', 'color:'); } else { if (port !== expected) { console.warn(`%c[Extension Host] %cProvided debugging port ${expected} is not free, using ${port} instead.`, 'color: blue', 'color:'); } if (this._isExtensionDevDebugBrk) { console.warn(`%c[Extension Host] %cSTOPPED on first line for debugging on port ${port}`, 'color: blue', 'color:'); } else { console.info(`%c[Extension Host] %cdebugger listening on port ${port}`, 'color: blue', 'color:'); } } } return port || 0; } private _performHandshake(protocol: IMessagePassingProtocol): Promise<void> { // 1) wait for the incoming `ready` event and send the initialization data. // 2) wait for the incoming `initialized` event. return new Promise<void>((resolve, reject) => { let timeoutHandle: any; const installTimeoutCheck = () => { timeoutHandle = setTimeout(() => { reject('The local extension host took longer than 60s to send its ready message.'); }, 60 * 1000); }; const uninstallTimeoutCheck = () => { clearTimeout(timeoutHandle); }; // Wait 60s for the ready message installTimeoutCheck(); const disposable = protocol.onMessage(msg => { if (isMessageOfType(msg, MessageType.Ready)) { // 1) Extension Host is ready to receive messages, initialize it uninstallTimeoutCheck(); this._createExtHostInitData().then(data => { // Wait 60s for the initialized message installTimeoutCheck(); protocol.send(VSBuffer.fromString(JSON.stringify(data))); }); return; } if (isMessageOfType(msg, MessageType.Initialized)) { // 2) Extension Host is initialized uninstallTimeoutCheck(); // stop listening for messages here disposable.dispose(); // release this promise resolve(); return; } console.error(`received unexpected message during handshake phase from the extension host: `, msg); }); }); } private async _createExtHostInitData(): Promise<IExtensionHostInitData> { const initData = await this._initDataProvider.getInitData(); const workspace = this._contextService.getWorkspace(); const deltaExtensions = this.extensions.set(initData.allExtensions, initData.myExtensions); return { commit: this._productService.commit, version: this._productService.version, parentPid: process.sandboxed ? 0 : process.pid, environment: { isExtensionDevelopmentDebug: this._isExtensionDevDebug, appRoot: this._environmentService.appRoot ? URI.file(this._environmentService.appRoot) : undefined, appName: this._productService.nameLong, appHost: this._productService.embedderIdentifier || 'desktop', appUriScheme: this._productService.urlProtocol, extensionTelemetryLogResource: this._environmentService.extHostTelemetryLogFile, isExtensionTelemetryLoggingOnly: isLoggingOnly(this._productService, this._environmentService), appLanguage: platform.language, extensionDevelopmentLocationURI: this._environmentService.extensionDevelopmentLocationURI, extensionTestsLocationURI: this._environmentService.extensionTestsLocationURI, globalStorageHome: this._userDataProfilesService.defaultProfile.globalStorageHome, workspaceStorageHome: this._environmentService.workspaceStorageHome, extensionLogLevel: this._environmentService.extensionLogLevel }, workspace: this._contextService.getWorkbenchState() === WorkbenchState.EMPTY ? undefined : { configuration: withNullAsUndefined(workspace.configuration), id: workspace.id, name: this._labelService.getWorkspaceLabel(workspace), isUntitled: workspace.configuration ? isUntitledWorkspace(workspace.configuration, this._environmentService) : false, transient: workspace.transient }, remote: { authority: this._environmentService.remoteAuthority, connectionData: null, isRemote: false }, consoleForward: { includeStack: !this._isExtensionDevTestFromCli && (this._isExtensionDevHost || !this._environmentService.isBuilt || this._productService.quality !== 'stable' || this._environmentService.verbose), logNative: !this._isExtensionDevTestFromCli && this._isExtensionDevHost }, allExtensions: deltaExtensions.toAdd, activationEvents: deltaExtensions.addActivationEvents, myExtensions: deltaExtensions.myToAdd, telemetryInfo: { sessionId: this._telemetryService.sessionId, machineId: this._telemetryService.machineId, firstSessionDate: this._telemetryService.firstSessionDate, msftInternal: this._telemetryService.msftInternal }, logLevel: this._logService.getLevel(), loggers: [...this._loggerService.getRegisteredLoggers()], logsLocation: this._environmentService.extHostLogsPath, autoStart: (this.startup === ExtensionHostStartup.EagerAutoStart), uiKind: UIKind.Desktop }; } private _onExtHostProcessExit(code: number, signal: string): void { if (this._terminating) { // Expected termination path (we asked the process to terminate) return; } this._onExit.fire([code, signal]); } private _handleProcessOutputStream(stream: Event<string>) { let last = ''; let isOmitting = false; const event = new Emitter<string>(); stream((chunk) => { // not a fancy approach, but this is the same approach used by the split2 // module which is well-optimized (https://github.com/mcollina/split2) last += chunk; const lines = last.split(/\r?\n/g); last = lines.pop()!; // protected against an extension spamming and leaking memory if no new line is written. if (last.length > 10_000) { lines.push(last); last = ''; } for (const line of lines) { if (isOmitting) { if (line === NativeLogMarkers.End) { isOmitting = false; } } else if (line === NativeLogMarkers.Start) { isOmitting = true; } else if (line.length) { event.fire(line + '\n'); } } }); return event; } public async enableInspectPort(): Promise<boolean> { if (typeof this._inspectPort === 'number') { return true; } if (!this._extensionHostProcess) { return false; } const result = await this._extensionHostProcess.enableInspectPort(); if (!result) { return false; } await Promise.race([Event.toPromise(this._onDidSetInspectPort.event), timeout(1000)]); return typeof this._inspectPort === 'number'; } public getInspectPort(): number | undefined { return withNullAsUndefined(this._inspectPort); } private _onWillShutdown(event: WillShutdownEvent): void { // If the extension development host was started without debugger attached we need // to communicate this back to the main side to terminate the debug session if (this._isExtensionDevHost && !this._isExtensionDevTestFromCli && !this._isExtensionDevDebug && this._environmentService.debugExtensionHost.debugId) { this._extensionHostDebugService.terminateSession(this._environmentService.debugExtensionHost.debugId); event.join(timeout(100 /* wait a bit for IPC to get delivered */), { id: 'join.extensionDevelopment', label: nls.localize('join.extensionDevelopment', "Terminating extension debug session") }); } } } export interface IExtHostCommunication<T> { prepare(): Promise<T>; establishProtocol(prepared: T, extensionHostProcess: ExtensionHostProcess, opts: IExtensionHostProcessOptions): Promise<IMessagePassingProtocol>; } export class ExtHostMessagePortCommunication extends Disposable implements IExtHostCommunication<void> { constructor( @ILogService private readonly _logService: ILogService ) { super(); } async prepare(): Promise<void> { } establishProtocol(prepared: void, extensionHostProcess: ExtensionHostProcess, opts: IExtensionHostProcessOptions): Promise<IMessagePassingProtocol> { writeExtHostConnection(new MessagePortExtHostConnection(), opts.env); // Get ready to acquire the message port from the shared process worker const portPromise = acquirePort(undefined /* we trigger the request via service call! */, opts.responseChannel, opts.responseNonce); return new Promise<IMessagePassingProtocol>((resolve, reject) => { const handle = setTimeout(() => { reject('The local extension host took longer than 60s to connect.'); }, 60 * 1000); portPromise.then((port) => { this._register(toDisposable(() => { // Close the message port when the extension host is disposed port.close(); })); clearTimeout(handle); const onMessage = new BufferedEmitter<VSBuffer>(); port.onmessage = ((e) => onMessage.fire(VSBuffer.wrap(e.data))); port.start(); resolve({ onMessage: onMessage.event, send: message => port.postMessage(message.buffer), }); }); // Now that the message port listener is installed, start the ext host process const sw = StopWatch.create(false); extensionHostProcess.start(opts).then(() => { const duration = sw.elapsed(); if (platform.isCI) { this._logService.info(`IExtensionHostStarter.start() took ${duration} ms.`); } }, (err) => { // Starting the ext host process resulted in an error reject(err); }); }); } }
src/vs/workbench/services/extensions/electron-sandbox/localProcessExtensionHost.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0002789559948723763, 0.0001737139536999166, 0.00016410813259426504, 0.00017117493553087115, 0.000016820107703097165 ]
{ "id": 7, "code_window": [ "\t\tthis._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden);\n", "\n", "\t\tthis._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate);\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { AddFirstParameterToFunctions } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { IBackupMainService } from 'vs/platform/backup/electron-main/backup'; import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows'; import { IEnterWorkspaceResult, IRecent, IRecentlyOpened, IWorkspaceFolderCreationData, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces'; import { IWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace'; import { IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService'; import { IWorkspacesManagementMainService } from 'vs/platform/workspaces/electron-main/workspacesManagementMainService'; import { IWorkspaceBackupInfo, IFolderBackupInfo } from 'vs/platform/backup/common/backup'; export class WorkspacesMainService implements AddFirstParameterToFunctions<IWorkspacesService, Promise<unknown> /* only methods, not events */, number /* window ID */> { declare readonly _serviceBrand: undefined; constructor( @IWorkspacesManagementMainService private readonly workspacesManagementMainService: IWorkspacesManagementMainService, @IWindowsMainService private readonly windowsMainService: IWindowsMainService, @IWorkspacesHistoryMainService private readonly workspacesHistoryMainService: IWorkspacesHistoryMainService, @IBackupMainService private readonly backupMainService: IBackupMainService ) { } //#region Workspace Management async enterWorkspace(windowId: number, path: URI): Promise<IEnterWorkspaceResult | undefined> { const window = this.windowsMainService.getWindowById(windowId); if (window) { return this.workspacesManagementMainService.enterWorkspace(window, this.windowsMainService.getWindows(), path); } return undefined; } createUntitledWorkspace(windowId: number, folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier> { return this.workspacesManagementMainService.createUntitledWorkspace(folders, remoteAuthority); } deleteUntitledWorkspace(windowId: number, workspace: IWorkspaceIdentifier): Promise<void> { return this.workspacesManagementMainService.deleteUntitledWorkspace(workspace); } getWorkspaceIdentifier(windowId: number, workspacePath: URI): Promise<IWorkspaceIdentifier> { return this.workspacesManagementMainService.getWorkspaceIdentifier(workspacePath); } //#endregion //#region Workspaces History readonly onDidChangeRecentlyOpened = this.workspacesHistoryMainService.onDidChangeRecentlyOpened; getRecentlyOpened(windowId: number): Promise<IRecentlyOpened> { return this.workspacesHistoryMainService.getRecentlyOpened(); } addRecentlyOpened(windowId: number, recents: IRecent[]): Promise<void> { return this.workspacesHistoryMainService.addRecentlyOpened(recents); } removeRecentlyOpened(windowId: number, paths: URI[]): Promise<void> { return this.workspacesHistoryMainService.removeRecentlyOpened(paths); } clearRecentlyOpened(windowId: number): Promise<void> { return this.workspacesHistoryMainService.clearRecentlyOpened(); } //#endregion //#region Dirty Workspaces async getDirtyWorkspaces(): Promise<Array<IWorkspaceBackupInfo | IFolderBackupInfo>> { return this.backupMainService.getDirtyWorkspaces(); } //#endregion }
src/vs/platform/workspaces/electron-main/workspacesMainService.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001755121338646859, 0.00017233140533789992, 0.00016802290338091552, 0.00017320770712103695, 0.000002783172021736391 ]
{ "id": 8, "code_window": [ "\t\tconst lineCountModified = ranges.modifiedHidden.length;\n", "\t\tconst lineCountOriginal = ranges.originalHidden.length;\n", "\n", "\t\tconst lineHeightDiff = Math.max(lineCountModified, lineCountOriginal);\n", "\t\tconst lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\t\tconst heightInLines = lineHeightDiff + lineHeightPadding;\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 139 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.9990328550338745, 0.08442911505699158, 0.00016304284508805722, 0.0001753567048581317, 0.2757062315940857 ]
{ "id": 8, "code_window": [ "\t\tconst lineCountModified = ranges.modifiedHidden.length;\n", "\t\tconst lineCountOriginal = ranges.originalHidden.length;\n", "\n", "\t\tconst lineHeightDiff = Math.max(lineCountModified, lineCountOriginal);\n", "\t\tconst lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\t\tconst heightInLines = lineHeightDiff + lineHeightPadding;\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 139 }
/*--------------------------------------------------------------------------------------------- * 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', }, resolve: { mainFields: ['module', 'main'] } });
extensions/grunt/extension.webpack.config.js
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017898633086588234, 0.0001777855068212375, 0.00017681845929473639, 0.0001775516866473481, 9.003390459838556e-7 ]
{ "id": 8, "code_window": [ "\t\tconst lineCountModified = ranges.modifiedHidden.length;\n", "\t\tconst lineCountOriginal = ranges.originalHidden.length;\n", "\n", "\t\tconst lineHeightDiff = Math.max(lineCountModified, lineCountOriginal);\n", "\t\tconst lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\t\tconst heightInLines = lineHeightDiff + lineHeightPadding;\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 139 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IMenuService, registerAction2 } from 'vs/platform/actions/common/actions'; import { MenuHiddenStatesReset } from 'vs/platform/actions/common/menuResetAction'; import { MenuService } from 'vs/platform/actions/common/menuService'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; registerSingleton(IMenuService, MenuService, InstantiationType.Delayed); registerAction2(MenuHiddenStatesReset);
src/vs/platform/actions/common/actions.contribution.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001766957575455308, 0.0001704380993032828, 0.0001641804410610348, 0.0001704380993032828, 0.000006257658242247999 ]
{ "id": 8, "code_window": [ "\t\tconst lineCountModified = ranges.modifiedHidden.length;\n", "\t\tconst lineCountOriginal = ranges.originalHidden.length;\n", "\n", "\t\tconst lineHeightDiff = Math.max(lineCountModified, lineCountOriginal);\n", "\t\tconst lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\t\tconst heightInLines = lineHeightDiff + lineHeightPadding;\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "add", "edit_start_line_idx": 139 }
:root { --spacing-unit: 6px; --cell-padding: (4 * var(--spacing-unit)); } body { padding-left: calc(4 * var(--spacing-unit, 5px)); }
extensions/vscode-colorize-tests/test/colorize-fixtures/test-cssvariables.scss
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001704685273580253, 0.0001704685273580253, 0.0001704685273580253, 0.0001704685273580253, 0 ]
{ "id": 9, "code_window": [ "\n", "\t\tsuper.show(ranges.anchor, lineHeightDiff + lineHeightPadding);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`);\n", "\t}\n", "\n", "\tprivate _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.show(ranges.anchor, heightInLines);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor} with ${heightInLines} lines height`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 140 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .interactive-editor { z-index: 100; color: inherit; padding: 6px; border-radius: 6px; border: 1px solid var(--vscode-interactiveEditor-border); box-shadow: 0 4px 8px var(--vscode-interactiveEditor-shadow); } /* body */ .monaco-editor .interactive-editor .body { display: flex; } .monaco-editor .interactive-editor .body .content { display: flex; box-sizing: border-box; border-radius: 2px; border: 1px solid var(--vscode-interactiveEditorInput-border); } .monaco-editor .interactive-editor .body .content.synthetic-focus { outline: 1px solid var(--vscode-interactiveEditorInput-focusBorder); } .monaco-editor .interactive-editor .body .content .input { padding: 2px 2px 2px 4px; border-top-left-radius: 2px; border-bottom-left-radius: 2px; background-color: var(--vscode-interactiveEditorInput-background); cursor: text; } .monaco-editor .interactive-editor .monaco-editor-background { background-color: var(--vscode-interactiveEditorInput-background); } .monaco-editor .interactive-editor .body .content .input .editor-placeholder { position: absolute; z-index: 1; padding: 3px 0 0 0; color: var(--vscode-interactiveEditorInput-placeholderForeground); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .monaco-editor .interactive-editor .body .content .input .editor-placeholder.hidden { display: none; } .monaco-editor .interactive-editor .body .content .input .editor-container { vertical-align: middle; } .monaco-editor .interactive-editor .body .toolbar { display: flex; flex-direction: column; align-self: stretch; padding-right: 4px; border-top-right-radius: 2px; border-bottom-right-radius: 2px; background: var(--vscode-interactiveEditorInput-background); } .monaco-editor .interactive-editor .body .toolbar .actions-container { display: flex; flex-direction: row; gap: 4px; } /* progress bit */ .monaco-editor .interactive-editor .progress { position: relative; width: calc(100% - 18px); left: 19px; } /* UGLY - fighting against workbench styles */ .monaco-workbench .part.editor>.content .monaco-editor .interactive-editor .progress .monaco-progress-container { top: 0; } /* status */ .monaco-editor .interactive-editor .status { padding: 6px 0px 2px 0px; display: flex; justify-content: space-between; align-items: center; } .monaco-editor .interactive-editor .status .actions.hidden { display: none; } .monaco-editor .interactive-editor .status .link { color: var(--vscode-textLink-foreground); cursor: pointer; font-size: 12px; white-space: nowrap; /* margin-top: auto; */ } .monaco-editor .interactive-editor .status .label { overflow: hidden; font-size: 12px; margin-left: auto; } .monaco-editor .interactive-editor .status .label.message>span>p { margin: 0px; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; display: -webkit-box; } .monaco-editor .interactive-editor .status .link .status-link { padding-left: 10px; } .monaco-editor .interactive-editor .status .link .status-link .codicon { line-height: unset; font-size: 12px; padding-right: 4px; } .monaco-editor .interactive-editor .status .label A { color: var(--vscode-textLink-foreground); cursor: pointer; } .monaco-editor .interactive-editor .status .label.error { color: var(--vscode-errorForeground); } .monaco-editor .interactive-editor .status .label.warn { color: var(--vscode-editorWarning-foreground); } .monaco-editor .interactive-editor .status .monaco-toolbar .action-item { padding: 0 2px; } .monaco-editor .interactive-editor .status .monaco-toolbar .action-label.checked { color: var(--vscode-inputOption-activeForeground); background-color: var(--vscode-inputOption-activeBackground); outline: 1px solid var(--vscode-inputOption-activeBorder); } /* preview */ .monaco-editor .interactive-editor .preview { display: none; } .monaco-editor .interactive-editor .previewDiff { display: inherit; padding: 6px; border: 1px solid var(--vscode-interactiveEditor-border); border-top: none; border-bottom-left-radius: 2px; border-bottom-right-radius: 2px; margin: 0 2px 6px 2px; } .monaco-editor .interactive-editor .previewCreateTitle { padding-top: 6px; } .monaco-editor .interactive-editor .previewCreate { display: inherit; padding: 6px; border: 1px solid var(--vscode-interactiveEditor-border); border-radius: 2px; margin: 0 2px 6px 2px; } .monaco-editor .interactive-editor .previewDiff.hidden, .monaco-editor .interactive-editor .previewCreate.hidden, .monaco-editor .interactive-editor .previewCreateTitle.hidden { display: none; } /* decoration styles */ .monaco-editor .interactive-editor-lines-deleted-range-inline { text-decoration: line-through; background-color: var(--vscode-diffEditor-removedTextBackground); opacity: 0.6; } .monaco-editor .interactive-editor-lines-inserted-range { background-color: var(--vscode-diffEditor-insertedTextBackground); } .monaco-editor .interactive-editor-block-selection { background-color: var(--vscode-interactiveEditor-regionHighlight); } .monaco-editor .interactive-editor-slash-command { color: var(--vscode-textLink-foreground) } .monaco-editor .interactive-editor-slash-command-detail { opacity: 0.5; } /* diff zone */ .monaco-editor .interactive-editor-diff-widget { padding: 6px 0; }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditor.css
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017642388411331922, 0.00017250269593205303, 0.00016740753198973835, 0.00017249793745577335, 0.00000218981381294725 ]
{ "id": 9, "code_window": [ "\n", "\t\tsuper.show(ranges.anchor, lineHeightDiff + lineHeightPadding);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`);\n", "\t}\n", "\n", "\tprivate _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.show(ranges.anchor, heightInLines);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor} with ${heightInLines} lines height`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 140 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const fetching = fetch;
extensions/microsoft-authentication/src/browser/fetch.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017658055003266782, 0.00017658055003266782, 0.00017658055003266782, 0.00017658055003266782, 0 ]
{ "id": 9, "code_window": [ "\n", "\t\tsuper.show(ranges.anchor, lineHeightDiff + lineHeightPadding);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`);\n", "\t}\n", "\n", "\tprivate _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.show(ranges.anchor, heightInLines);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor} with ${heightInLines} lines height`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 140 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Toggle } from 'vs/base/browser/ui/toggle/toggle'; import { isMacintosh, OperatingSystem } from 'vs/base/common/platform'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService'; import { localize } from 'vs/nls'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IQuickInputButton, IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput'; import { ITerminalCommand, TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities'; import { collapseTildePath } from 'vs/platform/terminal/common/terminalEnvironment'; import { asCssVariable, inputActiveOptionBackground, inputActiveOptionBorder, inputActiveOptionForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeIcon } from 'vs/base/common/themables'; import { ITerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminal'; import { commandHistoryFuzzySearchIcon, commandHistoryOutputIcon, commandHistoryRemoveIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons'; import { getCommandHistory, getDirectoryHistory, getShellFileHistory } from 'vs/workbench/contrib/terminal/common/history'; import { TerminalStorageKeys } from 'vs/workbench/contrib/terminal/common/terminalStorageKeys'; import { terminalStrings } from 'vs/workbench/contrib/terminal/common/terminalStrings'; import { URI } from 'vs/base/common/uri'; import { fromNow } from 'vs/base/common/date'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { showWithPinnedItems } from 'vs/platform/quickinput/browser/quickPickPin'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IContextKey } from 'vs/platform/contextkey/common/contextkey'; export async function showRunRecentQuickPick( accessor: ServicesAccessor, instance: ITerminalInstance, terminalInRunCommandPicker: IContextKey<boolean>, type: 'command' | 'cwd', filterMode?: 'fuzzy' | 'contiguous', value?: string ): Promise<void> { if (!instance.xterm) { return; } const editorService = accessor.get(IEditorService); const instantiationService = accessor.get(IInstantiationService); const quickInputService = accessor.get(IQuickInputService); const storageService = accessor.get(IStorageService); const runRecentStorageKey = `${TerminalStorageKeys.PinnedRecentCommandsPrefix}.${instance.shellType}`; let placeholder: string; type Item = IQuickPickItem & { command?: ITerminalCommand; rawLabel: string }; let items: (Item | IQuickPickItem & { rawLabel: string } | IQuickPickSeparator)[] = []; const commandMap: Set<string> = new Set(); const removeFromCommandHistoryButton: IQuickInputButton = { iconClass: ThemeIcon.asClassName(commandHistoryRemoveIcon), tooltip: localize('removeCommand', "Remove from Command History") }; const commandOutputButton: IQuickInputButton = { iconClass: ThemeIcon.asClassName(commandHistoryOutputIcon), tooltip: localize('viewCommandOutput', "View Command Output"), alwaysVisible: false }; if (type === 'command') { placeholder = isMacintosh ? localize('selectRecentCommandMac', 'Select a command to run (hold Option-key to edit the command)') : localize('selectRecentCommand', 'Select a command to run (hold Alt-key to edit the command)'); const cmdDetection = instance.capabilities.get(TerminalCapability.CommandDetection); const commands = cmdDetection?.commands; // Current session history const executingCommand = cmdDetection?.executingCommand; if (executingCommand) { commandMap.add(executingCommand); } function formatLabel(label: string) { return label // Replace new lines with "enter" symbol .replace(/\r?\n/g, '\u23CE') // Replace 3 or more spaces with midline horizontal ellipsis which looks similar // to whitespace in the editor .replace(/\s\s\s+/g, '\u22EF'); } if (commands && commands.length > 0) { for (const entry of commands) { // Trim off any whitespace and/or line endings, replace new lines with the // Downwards Arrow with Corner Leftwards symbol const label = entry.command.trim(); if (label.length === 0 || commandMap.has(label)) { continue; } let description = collapseTildePath(entry.cwd, instance.userHome, instance.os === OperatingSystem.Windows ? '\\' : '/'); if (entry.exitCode) { // Since you cannot get the last command's exit code on pwsh, just whether it failed // or not, -1 is treated specially as simply failed if (entry.exitCode === -1) { description += ' failed'; } else { description += ` exitCode: ${entry.exitCode}`; } } description = description.trim(); const buttons: IQuickInputButton[] = [commandOutputButton]; // Merge consecutive commands const lastItem = items.length > 0 ? items[items.length - 1] : undefined; if (lastItem?.type !== 'separator' && lastItem?.label === label) { lastItem.id = entry.timestamp.toString(); lastItem.description = description; continue; } items.push({ label: formatLabel(label), rawLabel: label, description, id: entry.timestamp.toString(), command: entry, buttons: entry.hasOutput() ? buttons : undefined }); commandMap.add(label); } items = items.reverse(); } if (executingCommand) { items.unshift({ label: formatLabel(executingCommand), rawLabel: executingCommand, description: cmdDetection.cwd }); } if (items.length > 0) { items.unshift({ type: 'separator', label: terminalStrings.currentSessionCategory }); } // Gather previous session history const history = instantiationService.invokeFunction(getCommandHistory); const previousSessionItems: (IQuickPickItem & { rawLabel: string })[] = []; for (const [label, info] of history.entries) { // Only add previous session item if it's not in this session if (!commandMap.has(label) && info.shellType === instance.shellType) { previousSessionItems.unshift({ label: formatLabel(label), rawLabel: label, buttons: [removeFromCommandHistoryButton] }); commandMap.add(label); } } if (previousSessionItems.length > 0) { items.push( { type: 'separator', label: terminalStrings.previousSessionCategory }, ...previousSessionItems ); } // Gather shell file history const shellFileHistory = await instantiationService.invokeFunction(getShellFileHistory, instance.shellType); const dedupedShellFileItems: (IQuickPickItem & { rawLabel: string })[] = []; for (const label of shellFileHistory) { if (!commandMap.has(label)) { dedupedShellFileItems.unshift({ label: formatLabel(label), rawLabel: label }); } } if (dedupedShellFileItems.length > 0) { items.push( { type: 'separator', label: localize('shellFileHistoryCategory', '{0} history', instance.shellType) }, ...dedupedShellFileItems ); } } else { placeholder = isMacintosh ? localize('selectRecentDirectoryMac', 'Select a directory to go to (hold Option-key to edit the command)') : localize('selectRecentDirectory', 'Select a directory to go to (hold Alt-key to edit the command)'); const cwds = instance.capabilities.get(TerminalCapability.CwdDetection)?.cwds || []; if (cwds && cwds.length > 0) { for (const label of cwds) { items.push({ label, rawLabel: label }); } items = items.reverse(); items.unshift({ type: 'separator', label: terminalStrings.currentSessionCategory }); } // Gather previous session history const history = instantiationService.invokeFunction(getDirectoryHistory); const previousSessionItems: (IQuickPickItem & { rawLabel: string })[] = []; // Only add previous session item if it's not in this session and it matches the remote authority for (const [label, info] of history.entries) { if ((info === null || info.remoteAuthority === instance.remoteAuthority) && !cwds.includes(label)) { previousSessionItems.unshift({ label, rawLabel: label, buttons: [removeFromCommandHistoryButton] }); } } if (previousSessionItems.length > 0) { items.push( { type: 'separator', label: terminalStrings.previousSessionCategory }, ...previousSessionItems ); } } if (items.length === 0) { return; } const fuzzySearchToggle = new Toggle({ title: 'Fuzzy search', icon: commandHistoryFuzzySearchIcon, isChecked: filterMode === 'fuzzy', inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder), inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground), inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground) }); fuzzySearchToggle.onChange(() => { instantiationService.invokeFunction(showRunRecentQuickPick, instance, terminalInRunCommandPicker, type, fuzzySearchToggle.checked ? 'fuzzy' : 'contiguous', quickPick.value); }); const outputProvider = instantiationService.createInstance(TerminalOutputProvider); const quickPick = quickInputService.createQuickPick<IQuickPickItem & { rawLabel: string }>(); const originalItems = items; quickPick.items = [...originalItems]; quickPick.sortByLabel = false; quickPick.placeholder = placeholder; quickPick.matchOnLabelMode = filterMode || 'contiguous'; quickPick.toggles = [fuzzySearchToggle]; quickPick.onDidTriggerItemButton(async e => { if (e.button === removeFromCommandHistoryButton) { if (type === 'command') { instantiationService.invokeFunction(getCommandHistory)?.remove(e.item.label); } else { instantiationService.invokeFunction(getDirectoryHistory)?.remove(e.item.label); } } else if (e.button === commandOutputButton) { const selectedCommand = (e.item as Item).command; const output = selectedCommand?.getOutput(); if (output && selectedCommand?.command) { const textContent = await outputProvider.provideTextContent(URI.from( { scheme: TerminalOutputProvider.scheme, path: `${selectedCommand.command}... ${fromNow(selectedCommand.timestamp, true)}`, fragment: output, query: `terminal-output-${selectedCommand.timestamp}-${instance.instanceId}` })); if (textContent) { await editorService.openEditor({ resource: textContent.uri }); } } } await instantiationService.invokeFunction(showRunRecentQuickPick, instance, terminalInRunCommandPicker, type, filterMode, value); } ); quickPick.onDidChangeValue(async value => { if (!value) { await instantiationService.invokeFunction(showRunRecentQuickPick, instance, terminalInRunCommandPicker, type, filterMode, value); } }); quickPick.onDidAccept(async () => { const result = quickPick.activeItems[0]; let text: string; if (type === 'cwd') { text = `cd ${await instance.preparePathForShell(result.rawLabel)}`; } else { // command text = result.rawLabel; } quickPick.hide(); instance.runCommand(text, !quickPick.keyMods.alt); if (quickPick.keyMods.alt) { instance.focus(); } }); if (value) { quickPick.value = value; } return new Promise<void>(r => { terminalInRunCommandPicker.set(true); showWithPinnedItems(storageService, runRecentStorageKey, quickPick, true); quickPick.onDidHide(() => { terminalInRunCommandPicker.set(false); r(); }); }); } class TerminalOutputProvider implements ITextModelContentProvider { static scheme = 'TERMINAL_OUTPUT'; constructor( @ITextModelService textModelResolverService: ITextModelService, @IModelService private readonly _modelService: IModelService ) { textModelResolverService.registerTextModelContentProvider(TerminalOutputProvider.scheme, this); } async provideTextContent(resource: URI): Promise<ITextModel | null> { const existing = this._modelService.getModel(resource); if (existing && !existing.isDisposed()) { return existing; } return this._modelService.createModel(resource.fragment, null, resource, false); } }
src/vs/workbench/contrib/terminal/browser/terminalRunRecentQuickPick.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.000216521744732745, 0.00017393293092027307, 0.00016586534911766648, 0.00017273766570724547, 0.000008180244549294002 ]
{ "id": 9, "code_window": [ "\n", "\t\tsuper.show(ranges.anchor, lineHeightDiff + lineHeightPadding);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`);\n", "\t}\n", "\n", "\tprivate _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tsuper.show(ranges.anchor, heightInLines);\n", "\t\tthis._logService.debug(`[IE] diff SHOWING at ${ranges.anchor} with ${heightInLines} lines height`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 140 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const es = require('event-stream'); const vfs = require('vinyl-fs'); const { stylelintFilter } = require('./filters'); const { getVariableNameValidator } = require('./lib/stylelint/validateVariableNames'); module.exports = gulpstylelint; /** use regex on lines */ function gulpstylelint(reporter) { const variableValidator = getVariableNameValidator(); let errorCount = 0; return es.through(function (file) { const lines = file.__lines || file.contents.toString('utf8').split(/\r\n|\r|\n/); file.__lines = lines; lines.forEach((line, i) => { variableValidator(line, unknownVariable => { reporter(file.relative + '(' + (i + 1) + ',1): Unknown variable: ' + unknownVariable, true); errorCount++; }); }); this.emit('data', file); }, function () { if (errorCount > 0) { reporter('All valid variable names are in `build/lib/stylelint/vscode-known-variables.json`\nTo update that file, run `./scripts/test-documentation.sh|bat.`', false); } this.emit('end'); } ); } function stylelint() { return vfs .src(stylelintFilter, { base: '.', follow: true, allowEmpty: true }) .pipe(gulpstylelint((message, isError) => { if (isError) { console.error(message); } else { console.info(message); } })) .pipe(es.through(function () { /* noop, important for the stream to end */ })); } if (require.main === module) { stylelint().on('error', (err) => { console.error(); console.error(err); process.exit(1); }); }
build/stylelint.js
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017629505600780249, 0.00017452110478188843, 0.0001694247912382707, 0.00017595419194549322, 0.0000025139324861811474 ]
{ "id": 10, "code_window": [ "\t\t} else {\n", "\t\t\tconst ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1));\n", "\t\t\teditor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId);\n", "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`);\n", "\t\t}\n", "\t}\n", "\n", "\toverride hide(): void {\n", "\t\tthis.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${editor.getId()} with ${String(editor.getModel()?.uri)}`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 188 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.9963434338569641, 0.09780486673116684, 0.00016414646233897656, 0.0002562996814958751, 0.2776559591293335 ]
{ "id": 10, "code_window": [ "\t\t} else {\n", "\t\t\tconst ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1));\n", "\t\t\teditor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId);\n", "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`);\n", "\t\t}\n", "\t}\n", "\n", "\toverride hide(): void {\n", "\t\tthis.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${editor.getId()} with ${String(editor.getModel()?.uri)}`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 188 }
/*--------------------------------------------------------------------------------------------- * 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 { ResolvedKeybinding } from 'vs/base/common/keybindings'; import * as nls from 'vs/nls'; import { WorkbenchCompressibleObjectTree } from 'vs/platform/list/browser/listService'; import { IViewsService } from 'vs/workbench/common/views'; import { SearchView } from 'vs/workbench/contrib/search/browser/searchView'; import { FileMatch, FolderMatch, Match, RenderableMatch, searchComparer } from 'vs/workbench/contrib/search/browser/searchModel'; import { ISearchConfigurationProperties, VIEW_ID } from 'vs/workbench/services/search/common/search'; export const category = { value: nls.localize('search', "Search"), original: 'Search' }; export function isSearchViewFocused(viewsService: IViewsService): boolean { const searchView = getSearchView(viewsService); const activeElement = document.activeElement; return !!(searchView && activeElement && DOM.isAncestor(activeElement, searchView.getContainer())); } export function appendKeyBindingLabel(label: string, inputKeyBinding: ResolvedKeybinding | undefined): string { return doAppendKeyBindingLabel(label, inputKeyBinding); } export function getSearchView(viewsService: IViewsService): SearchView | undefined { return viewsService.getActiveViewWithId(VIEW_ID) as SearchView; } export function getElementsToOperateOn(viewer: WorkbenchCompressibleObjectTree<RenderableMatch, void>, currElement: RenderableMatch | undefined, sortConfig: ISearchConfigurationProperties): RenderableMatch[] { let elements: RenderableMatch[] = viewer.getSelection().filter((x): x is RenderableMatch => x !== null).sort((a, b) => searchComparer(a, b, sortConfig.sortOrder)); // if selection doesn't include multiple elements, just return current focus element. if (currElement && !(elements.length > 1 && elements.includes(currElement))) { elements = [currElement]; } return elements; } /** * @param elements elements that are going to be removed * @param focusElement element that is focused * @returns whether we need to re-focus on a remove */ export function shouldRefocus(elements: RenderableMatch[], focusElement: RenderableMatch | undefined) { if (!focusElement) { return false; } return !focusElement || elements.includes(focusElement) || hasDownstreamMatch(elements, focusElement); } function hasDownstreamMatch(elements: RenderableMatch[], focusElement: RenderableMatch) { for (const elem of elements) { if ((elem instanceof FileMatch && focusElement instanceof Match && elem.matches().includes(focusElement)) || (elem instanceof FolderMatch && ( (focusElement instanceof FileMatch && elem.getDownstreamFileMatch(focusElement.resource)) || (focusElement instanceof Match && elem.getDownstreamFileMatch(focusElement.parent().resource)) ))) { return true; } } return false; } export function openSearchView(viewsService: IViewsService, focus?: boolean): Promise<SearchView | undefined> { return viewsService.openView(VIEW_ID, focus).then(view => (view as SearchView ?? undefined)); } function doAppendKeyBindingLabel(label: string, keyBinding: ResolvedKeybinding | undefined): string { return keyBinding ? label + ' (' + keyBinding.getLabel() + ')' : label; }
src/vs/workbench/contrib/search/browser/searchActionsBase.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017424550605937839, 0.00017177322297357023, 0.00016925428644753993, 0.00017223268514499068, 0.0000020323307126091095 ]
{ "id": 10, "code_window": [ "\t\t} else {\n", "\t\t\tconst ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1));\n", "\t\t\teditor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId);\n", "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`);\n", "\t\t}\n", "\t}\n", "\n", "\toverride hide(): void {\n", "\t\tthis.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${editor.getId()} with ${String(editor.getModel()?.uri)}`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 188 }
/*--------------------------------------------------------------------------------------------- * 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 { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper'; import { EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { LinuxDistro } from 'vs/workbench/contrib/terminal/browser/terminal'; class TestTerminalConfigHelper extends TerminalConfigHelper { set linuxDistro(distro: LinuxDistro) { this._linuxDistro = distro; } } suite('Workbench - TerminalConfigHelper', function () { let fixture: HTMLElement; // This suite has retries setup because the font-related tests flake only on GitHub actions, not // ADO. It seems Electron hangs for some reason only on GH actions, so the two options are to // retry or remove the test outright (which would drop coverage). this.retries(3); setup(() => { fixture = document.body; }); test('TerminalConfigHelper - getFont fontFamily', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: 'bar' } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, 'bar, monospace', 'terminal.integrated.fontFamily should be selected over editor.fontFamily'); }); test('TerminalConfigHelper - getFont fontFamily (Linux Fedora)', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: null } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Fedora; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, '\'DejaVu Sans Mono\', monospace', 'Fedora should have its font overridden when terminal.integrated.fontFamily not set'); }); test('TerminalConfigHelper - getFont fontFamily (Linux Ubuntu)', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: null } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Ubuntu; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, '\'Ubuntu Mono\', monospace', 'Ubuntu should have its font overridden when terminal.integrated.fontFamily not set'); }); test('TerminalConfigHelper - getFont fontFamily (Linux Unknown)', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: null } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, 'foo, monospace', 'editor.fontFamily should be the fallback when terminal.integrated.fontFamily not set'); }); test('TerminalConfigHelper - getFont fontSize 10', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo', fontSize: 9 }, terminal: { integrated: { fontFamily: 'bar', fontSize: 10 } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 10, 'terminal.integrated.fontSize should be selected over editor.fontSize'); }); test('TerminalConfigHelper - getFont fontSize 0', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: null, fontSize: 0 } } }); let configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Ubuntu; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 8, 'The minimum terminal font size (with adjustment) should be used when terminal.integrated.fontSize less than it'); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 6, 'The minimum terminal font size should be used when terminal.integrated.fontSize less than it'); }); test('TerminalConfigHelper - getFont fontSize 1500', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: 0, fontSize: 1500 } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 100, 'The maximum terminal font size should be used when terminal.integrated.fontSize more than it'); }); test('TerminalConfigHelper - getFont fontSize null', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: 0, fontSize: null } } }); let configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Ubuntu; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, EDITOR_FONT_DEFAULTS.fontSize + 2, 'The default editor font size (with adjustment) should be used when terminal.integrated.fontSize is not set'); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, EDITOR_FONT_DEFAULTS.fontSize, 'The default editor font size should be used when terminal.integrated.fontSize is not set'); }); test('TerminalConfigHelper - getFont lineHeight 2', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo', lineHeight: 1 }, terminal: { integrated: { fontFamily: 0, lineHeight: 2 } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().lineHeight, 2, 'terminal.integrated.lineHeight should be selected over editor.lineHeight'); }); test('TerminalConfigHelper - getFont lineHeight 0', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo', lineHeight: 1 }, terminal: { integrated: { fontFamily: 0, lineHeight: 0 } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().lineHeight, 1, 'editor.lineHeight should be 1 when terminal.integrated.lineHeight not set'); }); test('TerminalConfigHelper - isMonospace monospace', () => { const configurationService = new TestConfigurationService({ terminal: { integrated: { fontFamily: 'monospace' } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), true, 'monospace is monospaced'); }); test('TerminalConfigHelper - isMonospace sans-serif', () => { const configurationService = new TestConfigurationService({ terminal: { integrated: { fontFamily: 'sans-serif' } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'sans-serif is not monospaced'); }); test('TerminalConfigHelper - isMonospace serif', () => { const configurationService = new TestConfigurationService({ terminal: { integrated: { fontFamily: 'serif' } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'serif is not monospaced'); }); test('TerminalConfigHelper - isMonospace monospace falls back to editor.fontFamily', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'monospace' }, terminal: { integrated: { fontFamily: null } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), true, 'monospace is monospaced'); }); test('TerminalConfigHelper - isMonospace sans-serif falls back to editor.fontFamily', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'sans-serif' }, terminal: { integrated: { fontFamily: null } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'sans-serif is not monospaced'); }); test('TerminalConfigHelper - isMonospace serif falls back to editor.fontFamily', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'serif' }, terminal: { integrated: { fontFamily: null } } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'serif is not monospaced'); }); });
src/vs/workbench/contrib/terminal/test/browser/terminalConfigHelper.test.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00025048558018170297, 0.0001735184487188235, 0.000165125573403202, 0.00017013793694786727, 0.00001535486262582708 ]
{ "id": 10, "code_window": [ "\t\t} else {\n", "\t\t\tconst ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1));\n", "\t\t\teditor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId);\n", "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`);\n", "\t\t}\n", "\t}\n", "\n", "\toverride hide(): void {\n", "\t\tthis.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._logService.debug(`[IE] diff HIDING ${ranges} for ${editor.getId()} with ${String(editor.getModel()?.uri)}`);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 188 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Composite } from 'vs/workbench/browser/composite'; import { IEditorPane, GroupIdentifier, IEditorMemento, IEditorOpenContext, isEditorInput } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { LRUCache, Touch } from 'vs/base/common/map'; import { URI } from 'vs/base/common/uri'; import { Emitter, Event } from 'vs/base/common/event'; import { isEmptyObject } from 'vs/base/common/types'; import { DEFAULT_EDITOR_MIN_DIMENSIONS, DEFAULT_EDITOR_MAX_DIMENSIONS } from 'vs/workbench/browser/parts/editor/editor'; import { MementoObject } from 'vs/workbench/common/memento'; import { joinPath, IExtUri, isEqual } from 'vs/base/common/resources'; import { indexOfPath } from 'vs/base/common/extpath'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IEditorOptions } from 'vs/platform/editor/common/editor'; import { ITextResourceConfigurationChangeEvent, ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration'; import { IBoundarySashes } from 'vs/base/browser/ui/sash/sash'; /** * The base class of editors in the workbench. Editors register themselves for specific editor inputs. * Editors are layed out in the editor part of the workbench in editor groups. Multiple editors can be * open at the same time. Each editor has a minimized representation that is good enough to provide some * information about the state of the editor data. * * The workbench will keep an editor alive after it has been created and show/hide it based on * user interaction. The lifecycle of a editor goes in the order: * * - `createEditor()` * - `setEditorVisible()` * - `layout()` * - `setInput()` * - `focus()` * - `dispose()`: when the editor group the editor is in closes * * During use of the workbench, a editor will often receive a `clearInput()`, `setEditorVisible()`, `layout()` and * `focus()` calls, but only one `create()` and `dispose()` call. * * This class is only intended to be subclassed and not instantiated. */ export abstract class EditorPane extends Composite implements IEditorPane { //#region Events readonly onDidChangeSizeConstraints = Event.None; protected readonly _onDidChangeControl = this._register(new Emitter<void>()); readonly onDidChangeControl = this._onDidChangeControl.event; //#endregion private static readonly EDITOR_MEMENTOS = new Map<string, EditorMemento<any>>(); get minimumWidth() { return DEFAULT_EDITOR_MIN_DIMENSIONS.width; } get maximumWidth() { return DEFAULT_EDITOR_MAX_DIMENSIONS.width; } get minimumHeight() { return DEFAULT_EDITOR_MIN_DIMENSIONS.height; } get maximumHeight() { return DEFAULT_EDITOR_MAX_DIMENSIONS.height; } protected _input: EditorInput | undefined; get input(): EditorInput | undefined { return this._input; } protected _options: IEditorOptions | undefined; get options(): IEditorOptions | undefined { return this._options; } private _group: IEditorGroup | undefined; get group(): IEditorGroup | undefined { return this._group; } /** * Should be overridden by editors that have their own ScopedContextKeyService */ get scopedContextKeyService(): IContextKeyService | undefined { return undefined; } constructor( id: string, telemetryService: ITelemetryService, themeService: IThemeService, storageService: IStorageService ) { super(id, telemetryService, themeService, storageService); } override create(parent: HTMLElement): void { super.create(parent); // Create Editor this.createEditor(parent); } /** * Called to create the editor in the parent HTMLElement. Subclasses implement * this method to construct the editor widget. */ protected abstract createEditor(parent: HTMLElement): void; /** * Note: Clients should not call this method, the workbench calls this * method. Calling it otherwise may result in unexpected behavior. * * Sets the given input with the options to the editor. The input is guaranteed * to be different from the previous input that was set using the `input.matches()` * method. * * The provided context gives more information around how the editor was opened. * * The provided cancellation token should be used to test if the operation * was cancelled. */ async setInput(input: EditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { this._input = input; this._options = options; } /** * Called to indicate to the editor that the input should be cleared and * resources associated with the input should be freed. * * This method can be called based on different contexts, e.g. when opening * a different input or different editor control or when closing all editors * in a group. * * To monitor the lifecycle of editor inputs, you should not rely on this * method, rather refer to the listeners on `IEditorGroup` via `IEditorGroupsService`. */ clearInput(): void { this._input = undefined; this._options = undefined; } /** * Note: Clients should not call this method, the workbench calls this * method. Calling it otherwise may result in unexpected behavior. * * Sets the given options to the editor. Clients should apply the options * to the current input. */ setOptions(options: IEditorOptions | undefined): void { this._options = options; } override setVisible(visible: boolean, group?: IEditorGroup): void { super.setVisible(visible); // Propagate to Editor this.setEditorVisible(visible, group); } /** * Indicates that the editor control got visible or hidden in a specific group. A * editor instance will only ever be visible in one editor group. * * @param visible the state of visibility of this editor * @param group the editor group this editor is in. */ protected setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void { this._group = group; } setBoundarySashes(_sashes: IBoundarySashes) { // Subclasses can implement } protected getEditorMemento<T>(editorGroupService: IEditorGroupsService, configurationService: ITextResourceConfigurationService, key: string, limit: number = 10): IEditorMemento<T> { const mementoKey = `${this.getId()}${key}`; let editorMemento = EditorPane.EDITOR_MEMENTOS.get(mementoKey); if (!editorMemento) { editorMemento = this._register(new EditorMemento(this.getId(), key, this.getMemento(StorageScope.WORKSPACE, StorageTarget.MACHINE), limit, editorGroupService, configurationService)); EditorPane.EDITOR_MEMENTOS.set(mementoKey, editorMemento); } return editorMemento; } getViewState(): object | undefined { // Subclasses to override return undefined; } protected override saveState(): void { // Save all editor memento for this editor type for (const [, editorMemento] of EditorPane.EDITOR_MEMENTOS) { if (editorMemento.id === this.getId()) { editorMemento.saveState(); } } super.saveState(); } override dispose(): void { this._input = undefined; this._options = undefined; super.dispose(); } } interface MapGroupToMemento<T> { [group: GroupIdentifier]: T; } export class EditorMemento<T> extends Disposable implements IEditorMemento<T> { private static readonly SHARED_EDITOR_STATE = -1; // pick a number < 0 to be outside group id range private cache: LRUCache<string, MapGroupToMemento<T>> | undefined; private cleanedUp = false; private editorDisposables: Map<EditorInput, IDisposable> | undefined; private shareEditorState = false; constructor( readonly id: string, private key: string, private memento: MementoObject, private limit: number, private editorGroupService: IEditorGroupsService, private configurationService: ITextResourceConfigurationService ) { super(); this.updateConfiguration(undefined); this.registerListeners(); } private registerListeners(): void { this._register(this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration(e))); } private updateConfiguration(e: ITextResourceConfigurationChangeEvent | undefined): void { if (!e || e.affectsConfiguration(undefined, 'workbench.editor.sharedViewState')) { this.shareEditorState = this.configurationService.getValue(undefined, 'workbench.editor.sharedViewState') === true; } } saveEditorState(group: IEditorGroup, resource: URI, state: T): void; saveEditorState(group: IEditorGroup, editor: EditorInput, state: T): void; saveEditorState(group: IEditorGroup, resourceOrEditor: URI | EditorInput, state: T): void { const resource = this.doGetResource(resourceOrEditor); if (!resource || !group) { return; // we are not in a good state to save any state for a resource } const cache = this.doLoad(); // Ensure mementos for resource map let mementosForResource = cache.get(resource.toString()); if (!mementosForResource) { mementosForResource = Object.create(null) as MapGroupToMemento<T>; cache.set(resource.toString(), mementosForResource); } // Store state for group mementosForResource[group.id] = state; // Store state as most recent one based on settings if (this.shareEditorState) { mementosForResource[EditorMemento.SHARED_EDITOR_STATE] = state; } // Automatically clear when editor input gets disposed if any if (isEditorInput(resourceOrEditor)) { this.clearEditorStateOnDispose(resource, resourceOrEditor); } } loadEditorState(group: IEditorGroup, resource: URI): T | undefined; loadEditorState(group: IEditorGroup, editor: EditorInput): T | undefined; loadEditorState(group: IEditorGroup, resourceOrEditor: URI | EditorInput): T | undefined { const resource = this.doGetResource(resourceOrEditor); if (!resource || !group) { return; // we are not in a good state to load any state for a resource } const cache = this.doLoad(); const mementosForResource = cache.get(resource.toString()); if (mementosForResource) { const mementoForResourceAndGroup = mementosForResource[group.id]; // Return state for group if present if (mementoForResourceAndGroup) { return mementoForResourceAndGroup; } // Return most recent state based on settings otherwise if (this.shareEditorState) { return mementosForResource[EditorMemento.SHARED_EDITOR_STATE]; } } return undefined; } clearEditorState(resource: URI, group?: IEditorGroup): void; clearEditorState(editor: EditorInput, group?: IEditorGroup): void; clearEditorState(resourceOrEditor: URI | EditorInput, group?: IEditorGroup): void { if (isEditorInput(resourceOrEditor)) { this.editorDisposables?.delete(resourceOrEditor); } const resource = this.doGetResource(resourceOrEditor); if (resource) { const cache = this.doLoad(); // Clear state for group if (group) { const mementosForResource = cache.get(resource.toString()); if (mementosForResource) { delete mementosForResource[group.id]; if (isEmptyObject(mementosForResource)) { cache.delete(resource.toString()); } } } // Clear state across all groups for resource else { cache.delete(resource.toString()); } } } clearEditorStateOnDispose(resource: URI, editor: EditorInput): void { if (!this.editorDisposables) { this.editorDisposables = new Map<EditorInput, IDisposable>(); } if (!this.editorDisposables.has(editor)) { this.editorDisposables.set(editor, Event.once(editor.onWillDispose)(() => { this.clearEditorState(resource); this.editorDisposables?.delete(editor); })); } } moveEditorState(source: URI, target: URI, comparer: IExtUri): void { const cache = this.doLoad(); // We need a copy of the keys to not iterate over // newly inserted elements. const cacheKeys = [...cache.keys()]; for (const cacheKey of cacheKeys) { const resource = URI.parse(cacheKey); if (!comparer.isEqualOrParent(resource, source)) { continue; // not matching our resource } // Determine new resulting target resource let targetResource: URI; if (isEqual(source, resource)) { targetResource = target; // file got moved } else { const index = indexOfPath(resource.path, source.path); targetResource = joinPath(target, resource.path.substr(index + source.path.length + 1)); // parent folder got moved } // Don't modify LRU state const value = cache.get(cacheKey, Touch.None); if (value) { cache.delete(cacheKey); cache.set(targetResource.toString(), value); } } } private doGetResource(resourceOrEditor: URI | EditorInput): URI | undefined { if (isEditorInput(resourceOrEditor)) { return resourceOrEditor.resource; } return resourceOrEditor; } private doLoad(): LRUCache<string, MapGroupToMemento<T>> { if (!this.cache) { this.cache = new LRUCache<string, MapGroupToMemento<T>>(this.limit); // Restore from serialized map state const rawEditorMemento = this.memento[this.key]; if (Array.isArray(rawEditorMemento)) { this.cache.fromJSON(rawEditorMemento); } } return this.cache; } saveState(): void { const cache = this.doLoad(); // Cleanup once during session if (!this.cleanedUp) { this.cleanUp(); this.cleanedUp = true; } this.memento[this.key] = cache.toJSON(); } private cleanUp(): void { const cache = this.doLoad(); // Remove groups from states that no longer exist. Since we modify the // cache and its is a LRU cache make a copy to ensure iteration succeeds const entries = [...cache.entries()]; for (const [resource, mapGroupToMementos] of entries) { for (const group of Object.keys(mapGroupToMementos)) { const groupId: GroupIdentifier = Number(group); if (groupId === EditorMemento.SHARED_EDITOR_STATE && this.shareEditorState) { continue; // skip over shared entries if sharing is enabled } if (!this.editorGroupService.getGroup(groupId)) { delete mapGroupToMementos[groupId]; if (isEmptyObject(mapGroupToMementos)) { cache.delete(resource); } } } } } }
src/vs/workbench/browser/parts/editor/editorPane.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00024346090503968298, 0.00017156887042801827, 0.00015958368021529168, 0.00016894779400900006, 0.000015556219295831397 ]
{ "id": 11, "code_window": [ "\n", "\tprotected override _doLayout(heightInPixel: number, widthInPixel: number): void {\n", "\t\tconst newDim = new Dimension(widthInPixel, heightInPixel);\n", "\t\tif (Dimension.equals(this._dim, newDim)) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (!Dimension.equals(this._dim, newDim)) {\n", "\t\t\tthis._dim = newDim;\n", "\t\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t\t\tthis._logService.debug('[IE] diff LAYOUT', this._dim);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.9984001517295837, 0.08343172818422318, 0.00016431184485554695, 0.00017332553397864103, 0.2758331000804901 ]
{ "id": 11, "code_window": [ "\n", "\tprotected override _doLayout(heightInPixel: number, widthInPixel: number): void {\n", "\t\tconst newDim = new Dimension(widthInPixel, heightInPixel);\n", "\t\tif (Dimension.equals(this._dim, newDim)) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (!Dimension.equals(this._dim, newDim)) {\n", "\t\t\tthis._dim = newDim;\n", "\t\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t\t\tthis._logService.debug('[IE] diff LAYOUT', this._dim);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc'; import { Client as IPCElectronClient } from 'vs/base/parts/ipc/electron-sandbox/ipc.electron'; import { IMainProcessService } from 'vs/platform/ipc/common/mainProcessService'; /** * An implementation of `IMainProcessService` that leverages Electron's IPC. */ export class ElectronIPCMainProcessService extends Disposable implements IMainProcessService { declare readonly _serviceBrand: undefined; private mainProcessConnection: IPCElectronClient; constructor( windowId: number ) { super(); this.mainProcessConnection = this._register(new IPCElectronClient(`window:${windowId}`)); } getChannel(channelName: string): IChannel { return this.mainProcessConnection.getChannel(channelName); } registerChannel(channelName: string, channel: IServerChannel<string>): void { this.mainProcessConnection.registerChannel(channelName, channel); } }
src/vs/platform/ipc/electron-sandbox/mainProcessService.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017448942526243627, 0.0001714912650641054, 0.000167140387929976, 0.00017216763808391988, 0.0000031160434446064755 ]
{ "id": 11, "code_window": [ "\n", "\tprotected override _doLayout(heightInPixel: number, widthInPixel: number): void {\n", "\t\tconst newDim = new Dimension(widthInPixel, heightInPixel);\n", "\t\tif (Dimension.equals(this._dim, newDim)) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (!Dimension.equals(this._dim, newDim)) {\n", "\t\t\tthis._dim = newDim;\n", "\t\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t\t\tthis._logService.debug('[IE] diff LAYOUT', this._dim);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { IObservable, autorun, keepAlive, observableFromEvent } from 'vs/base/common/observable'; import { countEOL } from 'vs/editor/common/core/eolCounter'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { Range } from 'vs/editor/common/core/range'; import { IBackgroundTokenizationStore, ILanguageIdCodec } from 'vs/editor/common/languages'; import { ITextModel } from 'vs/editor/common/model'; import { TokenizationStateStore } from 'vs/editor/common/model/textModelTokens'; import { IModelContentChange, IModelContentChangedEvent } from 'vs/editor/common/textModelEvents'; import { ContiguousMultilineTokensBuilder } from 'vs/editor/common/tokens/contiguousMultilineTokensBuilder'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ArrayEdit, MonotonousIndexTransformer, SingleArrayEdit } from 'vs/workbench/services/textMate/browser/arrayOperation'; import { TextMateTokenizationWorker } from 'vs/workbench/services/textMate/browser/worker/textMate.worker'; import type { StateDeltas } from 'vs/workbench/services/textMate/browser/workerHost/textMateWorkerHost'; import { applyStateStackDiff, StateStack } from 'vscode-textmate'; export class TextMateWorkerTokenizerController extends Disposable { private _pendingChanges: IModelContentChangedEvent[] = []; /** * These states will eventually equal the worker states. * _states[i] stores the state at the end of line number i+1. */ private readonly _states = new TokenizationStateStore<StateStack>(); private readonly _loggingEnabled = observableConfigValue('editor.experimental.asyncTokenizationLogging', false, this._configurationService); constructor( private readonly _model: ITextModel, private readonly _worker: TextMateTokenizationWorker, private readonly _languageIdCodec: ILanguageIdCodec, private readonly _backgroundTokenizationStore: IBackgroundTokenizationStore, private readonly _initialState: StateStack, private readonly _configurationService: IConfigurationService, private readonly _maxTokenizationLineLength: IObservable<number>, ) { super(); this._register(keepAlive(this._loggingEnabled)); this._register(this._model.onDidChangeContent((e) => { if (this.shouldLog) { console.log('model change', { fileName: this._model.uri.fsPath.split('\\').pop(), changes: changesToString(e.changes), }); } this._worker.acceptModelChanged(this._model.uri.toString(), e); this._pendingChanges.push(e); })); this._register(this._model.onDidChangeLanguage((e) => { const languageId = this._model.getLanguageId(); const encodedLanguageId = this._languageIdCodec.encodeLanguageId(languageId); this._worker.acceptModelLanguageChanged( this._model.uri.toString(), languageId, encodedLanguageId ); })); const languageId = this._model.getLanguageId(); const encodedLanguageId = this._languageIdCodec.encodeLanguageId(languageId); this._worker.acceptNewModel({ uri: this._model.uri, versionId: this._model.getVersionId(), lines: this._model.getLinesContent(), EOL: this._model.getEOL(), languageId, encodedLanguageId, maxTokenizationLineLength: this._maxTokenizationLineLength.get(), }); this._register(autorun('update maxTokenizationLineLength', reader => { const maxTokenizationLineLength = this._maxTokenizationLineLength.read(reader); this._worker.acceptMaxTokenizationLineLength(this._model.uri.toString(), maxTokenizationLineLength); })); } get shouldLog() { return this._loggingEnabled.get(); } public override dispose(): void { super.dispose(); this._worker.acceptRemovedModel(this._model.uri.toString()); } /** * This method is called from the worker through the worker host. */ public setTokensAndStates(versionId: number, rawTokens: ArrayBuffer, stateDeltas: StateDeltas[]): void { // _states state, change{k}, ..., change{versionId}, state delta base & rawTokens, change{j}, ..., change{m}, current renderer state // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^ // | past changes | future states let tokens = ContiguousMultilineTokensBuilder.deserialize( new Uint8Array(rawTokens) ); if (this.shouldLog) { console.log('received background tokenization result', { fileName: this._model.uri.fsPath.split('\\').pop(), updatedTokenLines: tokens.map((t) => t.getLineRange()).join(' & '), updatedStateLines: stateDeltas.map((s) => new LineRange(s.startLineNumber, s.startLineNumber + s.stateDeltas.length).toString()).join(' & '), }); } if (this.shouldLog) { const changes = this._pendingChanges.filter(c => c.versionId <= versionId).map(c => c.changes).map(c => changesToString(c)).join(' then '); console.log('Applying changes to local states', changes); } // Apply past changes to _states while ( this._pendingChanges.length > 0 && this._pendingChanges[0].versionId <= versionId ) { const change = this._pendingChanges.shift()!; this._states.acceptChanges(change.changes); } if (this._pendingChanges.length > 0) { if (this.shouldLog) { const changes = this._pendingChanges.map(c => c.changes).map(c => changesToString(c)).join(' then '); console.log('Considering non-processed changes', changes); } const curToFutureTransformerTokens = MonotonousIndexTransformer.fromMany( this._pendingChanges.map((c) => fullLineArrayEditFromModelContentChange(c.changes)) ); // Filter tokens in lines that got changed in the future to prevent flickering // These tokens are recomputed anyway. const b = new ContiguousMultilineTokensBuilder(); for (const t of tokens) { for (let i = t.startLineNumber; i <= t.endLineNumber; i++) { const result = curToFutureTransformerTokens.transform(i - 1); // If result is undefined, the current line got touched by an edit. // The webworker will send us new tokens for all the new/touched lines after it received the edits. if (result !== undefined) { b.add(i, t.getLineTokens(i) as Uint32Array); } } } tokens = b.finalize(); // Apply future changes to tokens for (const change of this._pendingChanges) { for (const innerChanges of change.changes) { for (let j = 0; j < tokens.length; j++) { tokens[j].applyEdit(innerChanges.range, innerChanges.text); } } } } const curToFutureTransformerStates = MonotonousIndexTransformer.fromMany( this._pendingChanges.map((c) => fullLineArrayEditFromModelContentChange(c.changes)) ); // Apply state deltas to _states and _backgroundTokenizationStore for (const d of stateDeltas) { let prevState = d.startLineNumber <= 1 ? this._initialState : this._states.getEndState(d.startLineNumber - 1); for (let i = 0; i < d.stateDeltas.length; i++) { const delta = d.stateDeltas[i]; let state: StateStack; if (delta) { state = applyStateStackDiff(prevState, delta)!; this._states.setEndState(d.startLineNumber + i, state); } else { state = this._states.getEndState(d.startLineNumber + i)!; } const offset = curToFutureTransformerStates.transform(d.startLineNumber + i - 1); if (offset !== undefined) { // Only set the state if there is no future change in this line, // as this might make consumers believe that the state/tokens are accurate this._backgroundTokenizationStore.setEndState(offset + 1, state); } if (d.startLineNumber + i >= this._model.getLineCount() - 1) { this._backgroundTokenizationStore.backgroundTokenizationFinished(); } prevState = state; } } // First set states, then tokens, so that events fired from set tokens don't read invalid states this._backgroundTokenizationStore.setTokens(tokens); } } function fullLineArrayEditFromModelContentChange(c: IModelContentChange[]): ArrayEdit { return new ArrayEdit( c.map( (c) => new SingleArrayEdit( c.range.startLineNumber - 1, // Expand the edit range to include the entire line c.range.endLineNumber - c.range.startLineNumber + 1, countEOL(c.text)[0] + 1 ) ) ); } function changesToString(changes: IModelContentChange[]): string { return changes.map(c => Range.lift(c.range).toString() + ' => ' + c.text).join(' & '); } function observableConfigValue<T>(key: string, defaultValue: T, configurationService: IConfigurationService): IObservable<T> { return observableFromEvent( (handleChange) => configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(key)) { handleChange(e); } }), () => configurationService.getValue<T>(key) ?? defaultValue, ); }
src/vs/workbench/services/textMate/browser/workerHost/textMateWorkerTokenizerController.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017716594447847456, 0.00017210979422088712, 0.00016355155094061047, 0.0001730259828036651, 0.000003379885356480372 ]
{ "id": 11, "code_window": [ "\n", "\tprotected override _doLayout(heightInPixel: number, widthInPixel: number): void {\n", "\t\tconst newDim = new Dimension(widthInPixel, heightInPixel);\n", "\t\tif (Dimension.equals(this._dim, newDim)) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (!Dimension.equals(this._dim, newDim)) {\n", "\t\t\tthis._dim = newDim;\n", "\t\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t\t\tthis._logService.debug('[IE] diff LAYOUT', this._dim);\n" ], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Range } from 'vs/editor/common/core/range'; import { TrackedRangeStickiness, TrackedRangeStickiness as ActualTrackedRangeStickiness } from 'vs/editor/common/model'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModel'; // // The red-black tree is based on the "Introduction to Algorithms" by Cormen, Leiserson and Rivest. // export const enum ClassName { EditorHintDecoration = 'squiggly-hint', EditorInfoDecoration = 'squiggly-info', EditorWarningDecoration = 'squiggly-warning', EditorErrorDecoration = 'squiggly-error', EditorUnnecessaryDecoration = 'squiggly-unnecessary', EditorUnnecessaryInlineDecoration = 'squiggly-inline-unnecessary', EditorDeprecatedInlineDecoration = 'squiggly-inline-deprecated' } export const enum NodeColor { Black = 0, Red = 1, } const enum Constants { ColorMask = 0b00000001, ColorMaskInverse = 0b11111110, ColorOffset = 0, IsVisitedMask = 0b00000010, IsVisitedMaskInverse = 0b11111101, IsVisitedOffset = 1, IsForValidationMask = 0b00000100, IsForValidationMaskInverse = 0b11111011, IsForValidationOffset = 2, StickinessMask = 0b00011000, StickinessMaskInverse = 0b11100111, StickinessOffset = 3, CollapseOnReplaceEditMask = 0b00100000, CollapseOnReplaceEditMaskInverse = 0b11011111, CollapseOnReplaceEditOffset = 5, IsMarginMask = 0b01000000, IsMarginMaskInverse = 0b10111111, IsMarginOffset = 6, /** * Due to how deletion works (in order to avoid always walking the right subtree of the deleted node), * the deltas for nodes can grow and shrink dramatically. It has been observed, in practice, that unless * the deltas are corrected, integer overflow will occur. * * The integer overflow occurs when 53 bits are used in the numbers, but we will try to avoid it as * a node's delta gets below a negative 30 bits number. * * MIN SMI (SMall Integer) as defined in v8. * one bit is lost for boxing/unboxing flag. * one bit is lost for sign flag. * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values */ MIN_SAFE_DELTA = -(1 << 30), /** * MAX SMI (SMall Integer) as defined in v8. * one bit is lost for boxing/unboxing flag. * one bit is lost for sign flag. * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values */ MAX_SAFE_DELTA = 1 << 30, } export function getNodeColor(node: IntervalNode): NodeColor { return ((node.metadata & Constants.ColorMask) >>> Constants.ColorOffset); } function setNodeColor(node: IntervalNode, color: NodeColor): void { node.metadata = ( (node.metadata & Constants.ColorMaskInverse) | (color << Constants.ColorOffset) ); } function getNodeIsVisited(node: IntervalNode): boolean { return ((node.metadata & Constants.IsVisitedMask) >>> Constants.IsVisitedOffset) === 1; } function setNodeIsVisited(node: IntervalNode, value: boolean): void { node.metadata = ( (node.metadata & Constants.IsVisitedMaskInverse) | ((value ? 1 : 0) << Constants.IsVisitedOffset) ); } function getNodeIsForValidation(node: IntervalNode): boolean { return ((node.metadata & Constants.IsForValidationMask) >>> Constants.IsForValidationOffset) === 1; } function setNodeIsForValidation(node: IntervalNode, value: boolean): void { node.metadata = ( (node.metadata & Constants.IsForValidationMaskInverse) | ((value ? 1 : 0) << Constants.IsForValidationOffset) ); } function getNodeIsInGlyphMargin(node: IntervalNode): boolean { return ((node.metadata & Constants.IsMarginMask) >>> Constants.IsMarginOffset) === 1; } function setNodeIsInGlyphMargin(node: IntervalNode, value: boolean): void { node.metadata = ( (node.metadata & Constants.IsMarginMaskInverse) | ((value ? 1 : 0) << Constants.IsMarginOffset) ); } function getNodeStickiness(node: IntervalNode): TrackedRangeStickiness { return ((node.metadata & Constants.StickinessMask) >>> Constants.StickinessOffset); } function _setNodeStickiness(node: IntervalNode, stickiness: TrackedRangeStickiness): void { node.metadata = ( (node.metadata & Constants.StickinessMaskInverse) | (stickiness << Constants.StickinessOffset) ); } function getCollapseOnReplaceEdit(node: IntervalNode): boolean { return ((node.metadata & Constants.CollapseOnReplaceEditMask) >>> Constants.CollapseOnReplaceEditOffset) === 1; } function setCollapseOnReplaceEdit(node: IntervalNode, value: boolean): void { node.metadata = ( (node.metadata & Constants.CollapseOnReplaceEditMaskInverse) | ((value ? 1 : 0) << Constants.CollapseOnReplaceEditOffset) ); } export function setNodeStickiness(node: IntervalNode, stickiness: ActualTrackedRangeStickiness): void { _setNodeStickiness(node, <number>stickiness); } export class IntervalNode { /** * contains binary encoded information for color, visited, isForValidation and stickiness. */ public metadata: number; public parent: IntervalNode; public left: IntervalNode; public right: IntervalNode; public start: number; public end: number; public delta: number; public maxEnd: number; public id: string; public ownerId: number; public options: ModelDecorationOptions; public cachedVersionId: number; public cachedAbsoluteStart: number; public cachedAbsoluteEnd: number; public range: Range | null; constructor(id: string, start: number, end: number) { this.metadata = 0; this.parent = this; this.left = this; this.right = this; setNodeColor(this, NodeColor.Red); this.start = start; this.end = end; // FORCE_OVERFLOWING_TEST: this.delta = start; this.delta = 0; this.maxEnd = end; this.id = id; this.ownerId = 0; this.options = null!; setNodeIsForValidation(this, false); setNodeIsInGlyphMargin(this, false); _setNodeStickiness(this, TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges); setCollapseOnReplaceEdit(this, false); this.cachedVersionId = 0; this.cachedAbsoluteStart = start; this.cachedAbsoluteEnd = end; this.range = null; setNodeIsVisited(this, false); } public reset(versionId: number, start: number, end: number, range: Range): void { this.start = start; this.end = end; this.maxEnd = end; this.cachedVersionId = versionId; this.cachedAbsoluteStart = start; this.cachedAbsoluteEnd = end; this.range = range; } public setOptions(options: ModelDecorationOptions) { this.options = options; const className = this.options.className; setNodeIsForValidation(this, ( className === ClassName.EditorErrorDecoration || className === ClassName.EditorWarningDecoration || className === ClassName.EditorInfoDecoration )); setNodeIsInGlyphMargin(this, this.options.glyphMarginClassName !== null); _setNodeStickiness(this, <number>this.options.stickiness); setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit); } public setCachedOffsets(absoluteStart: number, absoluteEnd: number, cachedVersionId: number): void { if (this.cachedVersionId !== cachedVersionId) { this.range = null; } this.cachedVersionId = cachedVersionId; this.cachedAbsoluteStart = absoluteStart; this.cachedAbsoluteEnd = absoluteEnd; } public detach(): void { this.parent = null!; this.left = null!; this.right = null!; } } export const SENTINEL: IntervalNode = new IntervalNode(null!, 0, 0); SENTINEL.parent = SENTINEL; SENTINEL.left = SENTINEL; SENTINEL.right = SENTINEL; setNodeColor(SENTINEL, NodeColor.Black); export class IntervalTree { public root: IntervalNode; public requestNormalizeDelta: boolean; constructor() { this.root = SENTINEL; this.requestNormalizeDelta = false; } public intervalSearch(start: number, end: number, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number, onlyMarginDecorations: boolean): IntervalNode[] { if (this.root === SENTINEL) { return []; } return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations); } public search(filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number, onlyMarginDecorations: boolean): IntervalNode[] { if (this.root === SENTINEL) { return []; } return search(this, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations); } /** * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes! */ public collectNodesFromOwner(ownerId: number): IntervalNode[] { return collectNodesFromOwner(this, ownerId); } /** * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes! */ public collectNodesPostOrder(): IntervalNode[] { return collectNodesPostOrder(this); } public insert(node: IntervalNode): void { rbTreeInsert(this, node); this._normalizeDeltaIfNecessary(); } public delete(node: IntervalNode): void { rbTreeDelete(this, node); this._normalizeDeltaIfNecessary(); } public resolveNode(node: IntervalNode, cachedVersionId: number): void { const initialNode = node; let delta = 0; while (node !== this.root) { if (node === node.parent.right) { delta += node.parent.delta; } node = node.parent; } const nodeStart = initialNode.start + delta; const nodeEnd = initialNode.end + delta; initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId); } public acceptReplace(offset: number, length: number, textLength: number, forceMoveMarkers: boolean): void { // Our strategy is to remove all directly impacted nodes, and then add them back to the tree. // (1) collect all nodes that are intersecting this edit as nodes of interest const nodesOfInterest = searchForEditing(this, offset, offset + length); // (2) remove all nodes that are intersecting this edit for (let i = 0, len = nodesOfInterest.length; i < len; i++) { const node = nodesOfInterest[i]; rbTreeDelete(this, node); } this._normalizeDeltaIfNecessary(); // (3) edit all tree nodes except the nodes of interest noOverlapReplace(this, offset, offset + length, textLength); this._normalizeDeltaIfNecessary(); // (4) edit the nodes of interest and insert them back in the tree for (let i = 0, len = nodesOfInterest.length; i < len; i++) { const node = nodesOfInterest[i]; node.start = node.cachedAbsoluteStart; node.end = node.cachedAbsoluteEnd; nodeAcceptEdit(node, offset, (offset + length), textLength, forceMoveMarkers); node.maxEnd = node.end; rbTreeInsert(this, node); } this._normalizeDeltaIfNecessary(); } public getAllInOrder(): IntervalNode[] { return search(this, 0, false, 0, false); } private _normalizeDeltaIfNecessary(): void { if (!this.requestNormalizeDelta) { return; } this.requestNormalizeDelta = false; normalizeDelta(this); } } //#region Delta Normalization function normalizeDelta(T: IntervalTree): void { let node = T.root; let delta = 0; while (node !== SENTINEL) { if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) { // go left node = node.left; continue; } if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) { // go right delta += node.delta; node = node.right; continue; } // handle current node node.start = delta + node.start; node.end = delta + node.end; node.delta = 0; recomputeMaxEnd(node); setNodeIsVisited(node, true); // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } node = node.parent; } setNodeIsVisited(T.root, false); } //#endregion //#region Editing const enum MarkerMoveSemantics { MarkerDefined = 0, ForceMove = 1, ForceStay = 2 } function adjustMarkerBeforeColumn(markerOffset: number, markerStickToPreviousCharacter: boolean, checkOffset: number, moveSemantics: MarkerMoveSemantics): boolean { if (markerOffset < checkOffset) { return true; } if (markerOffset > checkOffset) { return false; } if (moveSemantics === MarkerMoveSemantics.ForceMove) { return false; } if (moveSemantics === MarkerMoveSemantics.ForceStay) { return true; } return markerStickToPreviousCharacter; } /** * This is a lot more complicated than strictly necessary to maintain the same behaviour * as when decorations were implemented using two markers. */ export function nodeAcceptEdit(node: IntervalNode, start: number, end: number, textLength: number, forceMoveMarkers: boolean): void { const nodeStickiness = getNodeStickiness(node); const startStickToPreviousCharacter = ( nodeStickiness === TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges || nodeStickiness === TrackedRangeStickiness.GrowsOnlyWhenTypingBefore ); const endStickToPreviousCharacter = ( nodeStickiness === TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges || nodeStickiness === TrackedRangeStickiness.GrowsOnlyWhenTypingBefore ); const deletingCnt = (end - start); const insertingCnt = textLength; const commonLength = Math.min(deletingCnt, insertingCnt); const nodeStart = node.start; let startDone = false; const nodeEnd = node.end; let endDone = false; if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node)) { // This edit encompasses the entire decoration range // and the decoration has asked to become collapsed node.start = start; startDone = true; node.end = start; endDone = true; } { const moveSemantics = forceMoveMarkers ? MarkerMoveSemantics.ForceMove : (deletingCnt > 0 ? MarkerMoveSemantics.ForceStay : MarkerMoveSemantics.MarkerDefined); if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) { startDone = true; } if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) { endDone = true; } } if (commonLength > 0 && !forceMoveMarkers) { const moveSemantics = (deletingCnt > insertingCnt ? MarkerMoveSemantics.ForceStay : MarkerMoveSemantics.MarkerDefined); if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) { startDone = true; } if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) { endDone = true; } } { const moveSemantics = forceMoveMarkers ? MarkerMoveSemantics.ForceMove : MarkerMoveSemantics.MarkerDefined; if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) { node.start = start + insertingCnt; startDone = true; } if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) { node.end = start + insertingCnt; endDone = true; } } // Finish const deltaColumn = (insertingCnt - deletingCnt); if (!startDone) { node.start = Math.max(0, nodeStart + deltaColumn); } if (!endDone) { node.end = Math.max(0, nodeEnd + deltaColumn); } if (node.start > node.end) { node.end = node.start; } } function searchForEditing(T: IntervalTree, start: number, end: number): IntervalNode[] { // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree // Now, it is known that two intervals A and B overlap only when both // A.low <= B.high and A.high >= B.low. When searching the trees for // nodes overlapping with a given interval, you can immediately skip: // a) all nodes to the right of nodes whose low value is past the end of the given interval. // b) all nodes that have their maximum 'high' value below the start of the given interval. let node = T.root; let delta = 0; let nodeMaxEnd = 0; let nodeStart = 0; let nodeEnd = 0; const result: IntervalNode[] = []; let resultLen = 0; while (node !== SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } node = node.parent; continue; } if (!getNodeIsVisited(node.left)) { // first time seeing this node nodeMaxEnd = delta + node.maxEnd; if (nodeMaxEnd < start) { // cover case b) from above // there is no need to search this node or its children setNodeIsVisited(node, true); continue; } if (node.left !== SENTINEL) { // go left node = node.left; continue; } } // handle current node nodeStart = delta + node.start; if (nodeStart > end) { // cover case a) from above // there is no need to search this node or its right subtree setNodeIsVisited(node, true); continue; } nodeEnd = delta + node.end; if (nodeEnd >= start) { node.setCachedOffsets(nodeStart, nodeEnd, 0); result[resultLen++] = node; } setNodeIsVisited(node, true); if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) { // go right delta += node.delta; node = node.right; continue; } } setNodeIsVisited(T.root, false); return result; } function noOverlapReplace(T: IntervalTree, start: number, end: number, textLength: number): void { // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree // Now, it is known that two intervals A and B overlap only when both // A.low <= B.high and A.high >= B.low. When searching the trees for // nodes overlapping with a given interval, you can immediately skip: // a) all nodes to the right of nodes whose low value is past the end of the given interval. // b) all nodes that have their maximum 'high' value below the start of the given interval. let node = T.root; let delta = 0; let nodeMaxEnd = 0; let nodeStart = 0; const editDelta = (textLength - (end - start)); while (node !== SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } recomputeMaxEnd(node); node = node.parent; continue; } if (!getNodeIsVisited(node.left)) { // first time seeing this node nodeMaxEnd = delta + node.maxEnd; if (nodeMaxEnd < start) { // cover case b) from above // there is no need to search this node or its children setNodeIsVisited(node, true); continue; } if (node.left !== SENTINEL) { // go left node = node.left; continue; } } // handle current node nodeStart = delta + node.start; if (nodeStart > end) { node.start += editDelta; node.end += editDelta; node.delta += editDelta; if (node.delta < Constants.MIN_SAFE_DELTA || node.delta > Constants.MAX_SAFE_DELTA) { T.requestNormalizeDelta = true; } // cover case a) from above // there is no need to search this node or its right subtree setNodeIsVisited(node, true); continue; } setNodeIsVisited(node, true); if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) { // go right delta += node.delta; node = node.right; continue; } } setNodeIsVisited(T.root, false); } //#endregion //#region Searching function collectNodesFromOwner(T: IntervalTree, ownerId: number): IntervalNode[] { let node = T.root; const result: IntervalNode[] = []; let resultLen = 0; while (node !== SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); node = node.parent; continue; } if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) { // go left node = node.left; continue; } // handle current node if (node.ownerId === ownerId) { result[resultLen++] = node; } setNodeIsVisited(node, true); if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) { // go right node = node.right; continue; } } setNodeIsVisited(T.root, false); return result; } function collectNodesPostOrder(T: IntervalTree): IntervalNode[] { let node = T.root; const result: IntervalNode[] = []; let resultLen = 0; while (node !== SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); node = node.parent; continue; } if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) { // go left node = node.left; continue; } if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) { // go right node = node.right; continue; } // handle current node result[resultLen++] = node; setNodeIsVisited(node, true); } setNodeIsVisited(T.root, false); return result; } function search(T: IntervalTree, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number, onlyMarginDecorations: boolean): IntervalNode[] { let node = T.root; let delta = 0; let nodeStart = 0; let nodeEnd = 0; const result: IntervalNode[] = []; let resultLen = 0; while (node !== SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } node = node.parent; continue; } if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) { // go left node = node.left; continue; } // handle current node nodeStart = delta + node.start; nodeEnd = delta + node.end; node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId); let include = true; if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) { include = false; } if (filterOutValidation && getNodeIsForValidation(node)) { include = false; } if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) { include = false; } if (include) { result[resultLen++] = node; } setNodeIsVisited(node, true); if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) { // go right delta += node.delta; node = node.right; continue; } } setNodeIsVisited(T.root, false); return result; } function intervalSearch(T: IntervalTree, intervalStart: number, intervalEnd: number, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number, onlyMarginDecorations: boolean): IntervalNode[] { // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree // Now, it is known that two intervals A and B overlap only when both // A.low <= B.high and A.high >= B.low. When searching the trees for // nodes overlapping with a given interval, you can immediately skip: // a) all nodes to the right of nodes whose low value is past the end of the given interval. // b) all nodes that have their maximum 'high' value below the start of the given interval. let node = T.root; let delta = 0; let nodeMaxEnd = 0; let nodeStart = 0; let nodeEnd = 0; const result: IntervalNode[] = []; let resultLen = 0; while (node !== SENTINEL) { if (getNodeIsVisited(node)) { // going up from this node setNodeIsVisited(node.left, false); setNodeIsVisited(node.right, false); if (node === node.parent.right) { delta -= node.parent.delta; } node = node.parent; continue; } if (!getNodeIsVisited(node.left)) { // first time seeing this node nodeMaxEnd = delta + node.maxEnd; if (nodeMaxEnd < intervalStart) { // cover case b) from above // there is no need to search this node or its children setNodeIsVisited(node, true); continue; } if (node.left !== SENTINEL) { // go left node = node.left; continue; } } // handle current node nodeStart = delta + node.start; if (nodeStart > intervalEnd) { // cover case a) from above // there is no need to search this node or its right subtree setNodeIsVisited(node, true); continue; } nodeEnd = delta + node.end; if (nodeEnd >= intervalStart) { // There is overlap node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId); let include = true; if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) { include = false; } if (filterOutValidation && getNodeIsForValidation(node)) { include = false; } if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) { include = false; } if (include) { result[resultLen++] = node; } } setNodeIsVisited(node, true); if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) { // go right delta += node.delta; node = node.right; continue; } } setNodeIsVisited(T.root, false); return result; } //#endregion //#region Insertion function rbTreeInsert(T: IntervalTree, newNode: IntervalNode): IntervalNode { if (T.root === SENTINEL) { newNode.parent = SENTINEL; newNode.left = SENTINEL; newNode.right = SENTINEL; setNodeColor(newNode, NodeColor.Black); T.root = newNode; return T.root; } treeInsert(T, newNode); recomputeMaxEndWalkToRoot(newNode.parent); // repair tree let x = newNode; while (x !== T.root && getNodeColor(x.parent) === NodeColor.Red) { if (x.parent === x.parent.parent.left) { const y = x.parent.parent.right; if (getNodeColor(y) === NodeColor.Red) { setNodeColor(x.parent, NodeColor.Black); setNodeColor(y, NodeColor.Black); setNodeColor(x.parent.parent, NodeColor.Red); x = x.parent.parent; } else { if (x === x.parent.right) { x = x.parent; leftRotate(T, x); } setNodeColor(x.parent, NodeColor.Black); setNodeColor(x.parent.parent, NodeColor.Red); rightRotate(T, x.parent.parent); } } else { const y = x.parent.parent.left; if (getNodeColor(y) === NodeColor.Red) { setNodeColor(x.parent, NodeColor.Black); setNodeColor(y, NodeColor.Black); setNodeColor(x.parent.parent, NodeColor.Red); x = x.parent.parent; } else { if (x === x.parent.left) { x = x.parent; rightRotate(T, x); } setNodeColor(x.parent, NodeColor.Black); setNodeColor(x.parent.parent, NodeColor.Red); leftRotate(T, x.parent.parent); } } } setNodeColor(T.root, NodeColor.Black); return newNode; } function treeInsert(T: IntervalTree, z: IntervalNode): void { let delta: number = 0; let x = T.root; const zAbsoluteStart = z.start; const zAbsoluteEnd = z.end; while (true) { const cmp = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta); if (cmp < 0) { // this node should be inserted to the left // => it is not affected by the node's delta if (x.left === SENTINEL) { z.start -= delta; z.end -= delta; z.maxEnd -= delta; x.left = z; break; } else { x = x.left; } } else { // this node should be inserted to the right // => it is not affected by the node's delta if (x.right === SENTINEL) { z.start -= (delta + x.delta); z.end -= (delta + x.delta); z.maxEnd -= (delta + x.delta); x.right = z; break; } else { delta += x.delta; x = x.right; } } } z.parent = x; z.left = SENTINEL; z.right = SENTINEL; setNodeColor(z, NodeColor.Red); } //#endregion //#region Deletion function rbTreeDelete(T: IntervalTree, z: IntervalNode): void { let x: IntervalNode; let y: IntervalNode; // RB-DELETE except we don't swap z and y in case c) // i.e. we always delete what's pointed at by z. if (z.left === SENTINEL) { x = z.right; y = z; // x's delta is no longer influenced by z's delta x.delta += z.delta; if (x.delta < Constants.MIN_SAFE_DELTA || x.delta > Constants.MAX_SAFE_DELTA) { T.requestNormalizeDelta = true; } x.start += z.delta; x.end += z.delta; } else if (z.right === SENTINEL) { x = z.left; y = z; } else { y = leftest(z.right); x = y.right; // y's delta is no longer influenced by z's delta, // but we don't want to walk the entire right-hand-side subtree of x. // we therefore maintain z's delta in y, and adjust only x x.start += y.delta; x.end += y.delta; x.delta += y.delta; if (x.delta < Constants.MIN_SAFE_DELTA || x.delta > Constants.MAX_SAFE_DELTA) { T.requestNormalizeDelta = true; } y.start += z.delta; y.end += z.delta; y.delta = z.delta; if (y.delta < Constants.MIN_SAFE_DELTA || y.delta > Constants.MAX_SAFE_DELTA) { T.requestNormalizeDelta = true; } } if (y === T.root) { T.root = x; setNodeColor(x, NodeColor.Black); z.detach(); resetSentinel(); recomputeMaxEnd(x); T.root.parent = SENTINEL; return; } const yWasRed = (getNodeColor(y) === NodeColor.Red); if (y === y.parent.left) { y.parent.left = x; } else { y.parent.right = x; } if (y === z) { x.parent = y.parent; } else { if (y.parent === z) { x.parent = y; } else { x.parent = y.parent; } y.left = z.left; y.right = z.right; y.parent = z.parent; setNodeColor(y, getNodeColor(z)); if (z === T.root) { T.root = y; } else { if (z === z.parent.left) { z.parent.left = y; } else { z.parent.right = y; } } if (y.left !== SENTINEL) { y.left.parent = y; } if (y.right !== SENTINEL) { y.right.parent = y; } } z.detach(); if (yWasRed) { recomputeMaxEndWalkToRoot(x.parent); if (y !== z) { recomputeMaxEndWalkToRoot(y); recomputeMaxEndWalkToRoot(y.parent); } resetSentinel(); return; } recomputeMaxEndWalkToRoot(x); recomputeMaxEndWalkToRoot(x.parent); if (y !== z) { recomputeMaxEndWalkToRoot(y); recomputeMaxEndWalkToRoot(y.parent); } // RB-DELETE-FIXUP let w: IntervalNode; while (x !== T.root && getNodeColor(x) === NodeColor.Black) { if (x === x.parent.left) { w = x.parent.right; if (getNodeColor(w) === NodeColor.Red) { setNodeColor(w, NodeColor.Black); setNodeColor(x.parent, NodeColor.Red); leftRotate(T, x.parent); w = x.parent.right; } if (getNodeColor(w.left) === NodeColor.Black && getNodeColor(w.right) === NodeColor.Black) { setNodeColor(w, NodeColor.Red); x = x.parent; } else { if (getNodeColor(w.right) === NodeColor.Black) { setNodeColor(w.left, NodeColor.Black); setNodeColor(w, NodeColor.Red); rightRotate(T, w); w = x.parent.right; } setNodeColor(w, getNodeColor(x.parent)); setNodeColor(x.parent, NodeColor.Black); setNodeColor(w.right, NodeColor.Black); leftRotate(T, x.parent); x = T.root; } } else { w = x.parent.left; if (getNodeColor(w) === NodeColor.Red) { setNodeColor(w, NodeColor.Black); setNodeColor(x.parent, NodeColor.Red); rightRotate(T, x.parent); w = x.parent.left; } if (getNodeColor(w.left) === NodeColor.Black && getNodeColor(w.right) === NodeColor.Black) { setNodeColor(w, NodeColor.Red); x = x.parent; } else { if (getNodeColor(w.left) === NodeColor.Black) { setNodeColor(w.right, NodeColor.Black); setNodeColor(w, NodeColor.Red); leftRotate(T, w); w = x.parent.left; } setNodeColor(w, getNodeColor(x.parent)); setNodeColor(x.parent, NodeColor.Black); setNodeColor(w.left, NodeColor.Black); rightRotate(T, x.parent); x = T.root; } } } setNodeColor(x, NodeColor.Black); resetSentinel(); } function leftest(node: IntervalNode): IntervalNode { while (node.left !== SENTINEL) { node = node.left; } return node; } function resetSentinel(): void { SENTINEL.parent = SENTINEL; SENTINEL.delta = 0; // optional SENTINEL.start = 0; // optional SENTINEL.end = 0; // optional } //#endregion //#region Rotations function leftRotate(T: IntervalTree, x: IntervalNode): void { const y = x.right; // set y. y.delta += x.delta; // y's delta is no longer influenced by x's delta if (y.delta < Constants.MIN_SAFE_DELTA || y.delta > Constants.MAX_SAFE_DELTA) { T.requestNormalizeDelta = true; } y.start += x.delta; y.end += x.delta; x.right = y.left; // turn y's left subtree into x's right subtree. if (y.left !== SENTINEL) { y.left.parent = x; } y.parent = x.parent; // link x's parent to y. if (x.parent === SENTINEL) { T.root = y; } else if (x === x.parent.left) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; // put x on y's left. x.parent = y; recomputeMaxEnd(x); recomputeMaxEnd(y); } function rightRotate(T: IntervalTree, y: IntervalNode): void { const x = y.left; y.delta -= x.delta; if (y.delta < Constants.MIN_SAFE_DELTA || y.delta > Constants.MAX_SAFE_DELTA) { T.requestNormalizeDelta = true; } y.start -= x.delta; y.end -= x.delta; y.left = x.right; if (x.right !== SENTINEL) { x.right.parent = y; } x.parent = y.parent; if (y.parent === SENTINEL) { T.root = x; } else if (y === y.parent.right) { y.parent.right = x; } else { y.parent.left = x; } x.right = y; y.parent = x; recomputeMaxEnd(y); recomputeMaxEnd(x); } //#endregion //#region max end computation function computeMaxEnd(node: IntervalNode): number { let maxEnd = node.end; if (node.left !== SENTINEL) { const leftMaxEnd = node.left.maxEnd; if (leftMaxEnd > maxEnd) { maxEnd = leftMaxEnd; } } if (node.right !== SENTINEL) { const rightMaxEnd = node.right.maxEnd + node.delta; if (rightMaxEnd > maxEnd) { maxEnd = rightMaxEnd; } } return maxEnd; } export function recomputeMaxEnd(node: IntervalNode): void { node.maxEnd = computeMaxEnd(node); } function recomputeMaxEndWalkToRoot(node: IntervalNode): void { while (node !== SENTINEL) { const maxEnd = computeMaxEnd(node); if (node.maxEnd === maxEnd) { // no need to go further return; } node.maxEnd = maxEnd; node = node.parent; } } //#endregion //#region utils export function intervalCompare(aStart: number, aEnd: number, bStart: number, bEnd: number): number { if (aStart === bStart) { return aEnd - bEnd; } return aStart - bStart; } //#endregion
src/vs/editor/common/model/intervalTree.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0003297802759334445, 0.00017433185712434351, 0.00016300694551318884, 0.00017390128050465137, 0.000014549998923030216 ]
{ "id": 12, "code_window": [ "\t\t}\n", "\t\tthis._dim = newDim;\n", "\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t}\n", "}\n", "\n", "function invert(range: LineRange, model: ITextModel): LineRange[] {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 216 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Dimension, h } from 'vs/base/browser/dom'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { assertType } from 'vs/base/common/types'; import { IActiveCodeEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/browser/zoneWidget'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import * as colorRegistry from 'vs/platform/theme/common/colorRegistry'; import * as editorColorRegistry from 'vs/editor/common/core/editorColorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INTERACTIVE_EDITOR_ID, interactiveEditorDiffInserted, interactiveEditorDiffRemoved, interactiveEditorRegionHighlight } from 'vs/workbench/contrib/interactiveEditor/common/interactiveEditor'; import { LineRange } from 'vs/editor/common/core/lineRange'; import { LineRangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { Position } from 'vs/editor/common/core/position'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ILogService } from 'vs/platform/log/common/log'; export class InteractiveEditorDiffWidget extends ZoneWidget { private static readonly _hideId = 'overlayDiff'; private readonly _elements = h('div.interactive-editor-diff-widget@domNode'); private readonly _diffEditor: IDiffEditor; private readonly _sessionStore = this._disposables.add(new DisposableStore()); private _dim: Dimension | undefined; constructor( editor: IActiveCodeEditor, private readonly _textModelv0: ITextModel, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @ILogService private readonly _logService: ILogService, ) { super(editor, { showArrow: false, showFrame: false, isResizeable: false, isAccessible: true }); super.create(); const diffContributions = EditorExtensionsRegistry .getEditorContributions() .filter(c => c.id !== INTERACTIVE_EDITOR_ID); this._diffEditor = instantiationService.createInstance(EmbeddedDiffEditorWidget, this._elements.domNode, { scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false }, renderMarginRevertIcon: false, diffCodeLens: false, scrollBeyondLastLine: false, stickyScroll: { enabled: false }, renderOverviewRuler: false, diffAlgorithm: 'advanced', splitViewDefaultRatio: 0.35 }, { originalEditor: { contributions: diffContributions }, modifiedEditor: { contributions: diffContributions } }, editor); this._disposables.add(this._diffEditor); this._diffEditor.setModel({ original: this._textModelv0, modified: editor.getModel() }); const doStyle = () => { const theme = themeService.getColorTheme(); const overrides: [target: string, source: string][] = [ [colorRegistry.editorBackground, interactiveEditorRegionHighlight], [editorColorRegistry.editorGutter, interactiveEditorRegionHighlight], [colorRegistry.diffInsertedLine, interactiveEditorDiffInserted], [colorRegistry.diffInserted, interactiveEditorDiffInserted], [colorRegistry.diffRemovedLine, interactiveEditorDiffRemoved], [colorRegistry.diffRemoved, interactiveEditorDiffRemoved], ]; for (const [target, source] of overrides) { const value = theme.getColor(source); if (value) { this._elements.domNode.style.setProperty(colorRegistry.asCssVariableName(target), String(value)); } } }; doStyle(); this._disposables.add(themeService.onDidColorThemeChange(doStyle)); } protected override _fillContainer(container: HTMLElement): void { container.appendChild(this._elements.domNode); } // --- show / hide -------------------- override show(): void { throw new Error('not supported like this'); } getEndPositionForChanges(range: Range, changes: LineRangeMapping[]): Position | undefined { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); return ranges?.anchor; } showDiff(range: () => Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); this._sessionStore.clear(); this._sessionStore.add(this._diffEditor.onDidUpdateDiff(() => { const result = this._diffEditor.getDiffComputationResult(); this._doShowForChanges(range(), result?.changes2 ?? []); })); this._doShowForChanges(range(), changes); } private _doShowForChanges(range: Range, changes: LineRangeMapping[]): void { assertType(this.editor.hasModel()); const modified = this.editor.getModel(); const ranges = this._computeHiddenRanges(modified, range, changes); if (!ranges) { this.hide(); return; } this._hideEditorRanges(this.editor, [ranges.modifiedHidden]); this._hideEditorRanges(this._diffEditor.getModifiedEditor(), ranges.modifiedDiffHidden); this._hideEditorRanges(this._diffEditor.getOriginalEditor(), ranges.originalDiffHidden); this._diffEditor.revealLine(ranges.modifiedHidden.startLineNumber, ScrollType.Immediate); const lineCountModified = ranges.modifiedHidden.length; const lineCountOriginal = ranges.originalHidden.length; const lineHeightDiff = Math.max(lineCountModified, lineCountOriginal); const lineHeightPadding = (this.editor.getOption(EditorOption.lineHeight) / 12) /* padding-top/bottom*/; super.show(ranges.anchor, lineHeightDiff + lineHeightPadding); this._logService.debug(`[IE] diff SHOWING at ${ranges.anchor}`); } private _computeHiddenRanges(model: ITextModel, range: Range, changes: LineRangeMapping[]) { if (changes.length === 0) { return undefined; } let originalLineRange = changes[0].originalRange; let modifiedLineRange = changes[0].modifiedRange; for (let i = 1; i < changes.length; i++) { originalLineRange = originalLineRange.join(changes[i].originalRange); modifiedLineRange = modifiedLineRange.join(changes[i].modifiedRange); } const startDelta = modifiedLineRange.startLineNumber - range.startLineNumber; if (startDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber - startDelta, modifiedLineRange.endLineNumberExclusive); originalLineRange = new LineRange(originalLineRange.startLineNumber - startDelta, originalLineRange.endLineNumberExclusive); } const endDelta = range.endLineNumber - (modifiedLineRange.endLineNumberExclusive - 1); if (endDelta > 0) { modifiedLineRange = new LineRange(modifiedLineRange.startLineNumber, modifiedLineRange.endLineNumberExclusive + endDelta); originalLineRange = new LineRange(originalLineRange.startLineNumber, originalLineRange.endLineNumberExclusive + endDelta); } const originalDiffHidden = invert(originalLineRange, this._textModelv0); const modifiedDiffHidden = invert(modifiedLineRange, model); return { originalHidden: originalLineRange, originalDiffHidden, modifiedHidden: modifiedLineRange, modifiedDiffHidden, anchor: new Position(modifiedLineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER) }; } private _hideEditorRanges(editor: ICodeEditor, lineRanges: LineRange[]): void { lineRanges = lineRanges.filter(range => !range.isEmpty); if (lineRanges.length === 0) { // todo? this._logService.debug(`[IE] diff NOTHING to hide for ${String(editor.getModel()?.uri)}`); } else { const ranges = lineRanges.map(r => new Range(r.startLineNumber, 1, r.endLineNumberExclusive - 1, 1)); editor.setHiddenAreas(ranges, InteractiveEditorDiffWidget._hideId); this._logService.debug(`[IE] diff HIDING ${ranges} for ${String(editor.getModel()?.uri)}`); } } override hide(): void { this.editor.setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getOriginalEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); this._diffEditor.getModifiedEditor().setHiddenAreas([], InteractiveEditorDiffWidget._hideId); super.hide(); } protected override revealRange(range: Range, isLastLine: boolean): void { // ignore } // --- layout ------------------------- protected override _onWidth(widthInPixel: number): void { if (this._dim) { this._doLayout(this._dim.height, widthInPixel); } } protected override _doLayout(heightInPixel: number, widthInPixel: number): void { const newDim = new Dimension(widthInPixel, heightInPixel); if (Dimension.equals(this._dim, newDim)) { return; } this._dim = newDim; this._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */)); } } function invert(range: LineRange, model: ITextModel): LineRange[] { if (range.isEmpty) { return []; } const result: LineRange[] = []; result.push(new LineRange(1, range.startLineNumber)); result.push(new LineRange(range.endLineNumberExclusive, model.getLineCount() + 1)); return result.filter(r => !r.isEmpty); }
src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts
1
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.9991851449012756, 0.05833330377936363, 0.00016509220586158335, 0.00023840944049879909, 0.20939433574676514 ]
{ "id": 12, "code_window": [ "\t\t}\n", "\t\tthis._dim = newDim;\n", "\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t}\n", "}\n", "\n", "function invert(range: LineRange, model: ITextModel): LineRange[] {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 216 }
src/** tsconfig.json out/** extension.webpack.config.js yarn.lock .vscode
extensions/debug-server-ready/.vscodeignore
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00017526211740914732, 0.00017526211740914732, 0.00017526211740914732, 0.00017526211740914732, 0 ]
{ "id": 12, "code_window": [ "\t\t}\n", "\t\tthis._dim = newDim;\n", "\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t}\n", "}\n", "\n", "function invert(range: LineRange, model: ITextModel): LineRange[] {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 216 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fs from 'fs'; import { FileAccess } from 'vs/base/common/network'; import * as path from 'vs/base/common/path'; import * as lp from 'vs/base/node/languagePacks'; import product from 'vs/platform/product/common/product'; const metaData = path.join(FileAccess.asFileUri('').fsPath, 'nls.metadata.json'); const _cache: Map<string, Promise<lp.NLSConfiguration>> = new Map(); function exists(file: string) { return new Promise(c => fs.exists(file, c)); } export function getNLSConfiguration(language: string, userDataPath: string): Promise<lp.NLSConfiguration> { return exists(metaData).then((fileExists) => { if (!fileExists || !product.commit) { // console.log(`==> MetaData or commit unknown. Using default language.`); // The OS Locale on the remote side really doesn't matter, so we return the default locale return Promise.resolve({ locale: 'en', osLocale: 'en', availableLanguages: {} }); } const key = `${language}||${userDataPath}`; let result = _cache.get(key); if (!result) { // The OS Locale on the remote side really doesn't matter, so we pass in the same language result = lp.getNLSConfiguration(product.commit, userDataPath, metaData, language, language).then(value => { if (InternalNLSConfiguration.is(value)) { value._languagePackSupport = true; } return value; }); _cache.set(key, result); } return result; }); } export namespace InternalNLSConfiguration { export function is(value: lp.NLSConfiguration): value is lp.InternalNLSConfiguration { const candidate: lp.InternalNLSConfiguration = value as lp.InternalNLSConfiguration; return candidate && typeof candidate._languagePackId === 'string'; } }
src/vs/server/node/remoteLanguagePacks.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.0001771922834450379, 0.00017431631567887962, 0.00016646440781187266, 0.0001762602769304067, 0.0000039788028516341 ]
{ "id": 12, "code_window": [ "\t\t}\n", "\t\tthis._dim = newDim;\n", "\t\tthis._diffEditor.layout(this._dim.with(undefined, this._dim.height - 12 /* padding */));\n", "\t}\n", "}\n", "\n", "function invert(range: LineRange, model: ITextModel): LineRange[] {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveEditor/browser/interactiveEditorDiffWidget.ts", "type": "replace", "edit_start_line_idx": 216 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // NOTE: VSCode's copy of nodejs path library to be usable in common (non-node) namespace // Copied from: https://github.com/nodejs/node/blob/v16.14.2/lib/path.js /** * Copyright Joyent, Inc. and other Node contributors. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. */ import * as process from 'vs/base/common/process'; const CHAR_UPPERCASE_A = 65;/* A */ const CHAR_LOWERCASE_A = 97; /* a */ const CHAR_UPPERCASE_Z = 90; /* Z */ const CHAR_LOWERCASE_Z = 122; /* z */ const CHAR_DOT = 46; /* . */ const CHAR_FORWARD_SLASH = 47; /* / */ const CHAR_BACKWARD_SLASH = 92; /* \ */ const CHAR_COLON = 58; /* : */ const CHAR_QUESTION_MARK = 63; /* ? */ class ErrorInvalidArgType extends Error { code: 'ERR_INVALID_ARG_TYPE'; constructor(name: string, expected: string, actual: unknown) { // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && expected.indexOf('not ') === 0) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } const type = name.indexOf('.') !== -1 ? 'property' : 'argument'; let msg = `The "${name}" ${type} ${determiner} of type ${expected}`; msg += `. Received type ${typeof actual}`; super(msg); this.code = 'ERR_INVALID_ARG_TYPE'; } } function validateObject(pathObject: object, name: string) { if (pathObject === null || typeof pathObject !== 'object') { throw new ErrorInvalidArgType(name, 'Object', pathObject); } } function validateString(value: string, name: string) { if (typeof value !== 'string') { throw new ErrorInvalidArgType(name, 'string', value); } } const platformIsWin32 = (process.platform === 'win32'); function isPathSeparator(code: number | undefined) { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; } function isPosixPathSeparator(code: number | undefined) { return code === CHAR_FORWARD_SLASH; } function isWindowsDeviceRoot(code: number) { return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); } // Resolves . and .. elements in a path with directory names function normalizeString(path: string, allowAboveRoot: boolean, separator: string, isPathSeparator: (code?: number) => boolean) { let res = ''; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let code = 0; for (let i = 0; i <= path.length; ++i) { if (i < path.length) { code = path.charCodeAt(i); } else if (isPathSeparator(code)) { break; } else { code = CHAR_FORWARD_SLASH; } if (isPathSeparator(code)) { if (lastSlash === i - 1 || dots === 1) { // NOOP } else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf(separator); if (lastSlashIndex === -1) { res = ''; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); } lastSlash = i; dots = 0; continue; } else if (res.length !== 0) { res = ''; lastSegmentLength = 0; lastSlash = i; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? `${separator}..` : '..'; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `${separator}${path.slice(lastSlash + 1, i)}`; } else { res = path.slice(lastSlash + 1, i); } lastSegmentLength = i - lastSlash - 1; } lastSlash = i; dots = 0; } else if (code === CHAR_DOT && dots !== -1) { ++dots; } else { dots = -1; } } return res; } function _format(sep: string, pathObject: ParsedPath) { validateObject(pathObject, 'pathObject'); const dir = pathObject.dir || pathObject.root; const base = pathObject.base || `${pathObject.name || ''}${pathObject.ext || ''}`; if (!dir) { return base; } return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`; } export interface ParsedPath { root: string; dir: string; base: string; ext: string; name: string; } export interface IPath { normalize(path: string): string; isAbsolute(path: string): boolean; join(...paths: string[]): string; resolve(...pathSegments: string[]): string; relative(from: string, to: string): string; dirname(path: string): string; basename(path: string, ext?: string): string; extname(path: string): string; format(pathObject: ParsedPath): string; parse(path: string): ParsedPath; toNamespacedPath(path: string): string; sep: '\\' | '/'; delimiter: string; win32: IPath | null; posix: IPath | null; } export const win32: IPath = { // path.resolve([from ...], to) resolve(...pathSegments: string[]): string { let resolvedDevice = ''; let resolvedTail = ''; let resolvedAbsolute = false; for (let i = pathSegments.length - 1; i >= -1; i--) { let path; if (i >= 0) { path = pathSegments[i]; validateString(path, 'path'); // Skip empty entries if (path.length === 0) { continue; } } else if (resolvedDevice.length === 0) { path = process.cwd(); } else { // Windows has the concept of drive-specific current working // directories. If we've resolved a drive letter but not yet an // absolute path, get cwd for that drive, or the process cwd if // the drive cwd is not available. We're sure the device is not // a UNC path at this points, because UNC paths are always absolute. path = process.env[`=${resolvedDevice}`] || process.cwd(); // Verify that a cwd was found and that it actually points // to our drive. If not, default to the drive's root. if (path === undefined || (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) { path = `${resolvedDevice}\\`; } } const len = path.length; let rootEnd = 0; let device = ''; let isAbsolute = false; const code = path.charCodeAt(0); // Try to match a root if (len === 1) { if (isPathSeparator(code)) { // `path` contains just a path separator rootEnd = 1; isAbsolute = true; } } else if (isPathSeparator(code)) { // Possible UNC root // If we started with a separator, we know we at least have an // absolute path of some kind (UNC or otherwise) isAbsolute = true; if (isPathSeparator(path.charCodeAt(1))) { // Matched double path separator at beginning let j = 2; let last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { const firstPart = path.slice(last, j); // Matched! last = j; // Match 1 or more path separators while (j < len && isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j === len || j !== last) { // We matched a UNC root device = `\\\\${firstPart}\\${path.slice(last, j)}`; rootEnd = j; } } } } else { rootEnd = 1; } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { // Possible device root device = path.slice(0, 2); rootEnd = 2; if (len > 2 && isPathSeparator(path.charCodeAt(2))) { // Treat separator following drive name as an absolute path // indicator isAbsolute = true; rootEnd = 3; } } if (device.length > 0) { if (resolvedDevice.length > 0) { if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { // This path points to another device so it is not applicable continue; } } else { resolvedDevice = device; } } if (resolvedAbsolute) { if (resolvedDevice.length > 0) { break; } } else { resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; resolvedAbsolute = isAbsolute; if (isAbsolute && resolvedDevice.length > 0) { break; } } } // At this point the path should be resolved to a full absolute path, // but handle relative paths to be safe (might happen when process.cwd() // fails) // Normalize the tail path resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparator); return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || '.'; }, normalize(path: string): string { validateString(path, 'path'); const len = path.length; if (len === 0) { return '.'; } let rootEnd = 0; let device; let isAbsolute = false; const code = path.charCodeAt(0); // Try to match a root if (len === 1) { // `path` contains just a single char, exit early to avoid // unnecessary work return isPosixPathSeparator(code) ? '\\' : path; } if (isPathSeparator(code)) { // Possible UNC root // If we started with a separator, we know we at least have an absolute // path of some kind (UNC or otherwise) isAbsolute = true; if (isPathSeparator(path.charCodeAt(1))) { // Matched double path separator at beginning let j = 2; let last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { const firstPart = path.slice(last, j); // Matched! last = j; // Match 1 or more path separators while (j < len && isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j === len) { // We matched a UNC root only // Return the normalized version of the UNC root since there // is nothing left to process return `\\\\${firstPart}\\${path.slice(last)}\\`; } if (j !== last) { // We matched a UNC root with leftovers device = `\\\\${firstPart}\\${path.slice(last, j)}`; rootEnd = j; } } } } else { rootEnd = 1; } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { // Possible device root device = path.slice(0, 2); rootEnd = 2; if (len > 2 && isPathSeparator(path.charCodeAt(2))) { // Treat separator following drive name as an absolute path // indicator isAbsolute = true; rootEnd = 3; } } let tail = rootEnd < len ? normalizeString(path.slice(rootEnd), !isAbsolute, '\\', isPathSeparator) : ''; if (tail.length === 0 && !isAbsolute) { tail = '.'; } if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { tail += '\\'; } if (device === undefined) { return isAbsolute ? `\\${tail}` : tail; } return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`; }, isAbsolute(path: string): boolean { validateString(path, 'path'); const len = path.length; if (len === 0) { return false; } const code = path.charCodeAt(0); return isPathSeparator(code) || // Possible device root (len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isPathSeparator(path.charCodeAt(2))); }, join(...paths: string[]): string { if (paths.length === 0) { return '.'; } let joined; let firstPart: string | undefined; for (let i = 0; i < paths.length; ++i) { const arg = paths[i]; validateString(arg, 'path'); if (arg.length > 0) { if (joined === undefined) { joined = firstPart = arg; } else { joined += `\\${arg}`; } } } if (joined === undefined) { return '.'; } // Make sure that the joined path doesn't start with two slashes, because // normalize() will mistake it for a UNC path then. // // This step is skipped when it is very clear that the user actually // intended to point at a UNC path. This is assumed when the first // non-empty string arguments starts with exactly two slashes followed by // at least one more non-slash character. // // Note that for normalize() to treat a path as a UNC path it needs to // have at least 2 components, so we don't filter for that here. // This means that the user can use join to construct UNC paths from // a server name and a share name; for example: // path.join('//server', 'share') -> '\\\\server\\share\\') let needsReplace = true; let slashCount = 0; if (typeof firstPart === 'string' && isPathSeparator(firstPart.charCodeAt(0))) { ++slashCount; const firstLen = firstPart.length; if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) { ++slashCount; if (firstLen > 2) { if (isPathSeparator(firstPart.charCodeAt(2))) { ++slashCount; } else { // We matched a UNC path in the first part needsReplace = false; } } } } if (needsReplace) { // Find any more consecutive slashes we need to replace while (slashCount < joined.length && isPathSeparator(joined.charCodeAt(slashCount))) { slashCount++; } // Replace the slashes if needed if (slashCount >= 2) { joined = `\\${joined.slice(slashCount)}`; } } return win32.normalize(joined); }, // It will solve the relative path from `from` to `to`, for instance: // from = 'C:\\orandea\\test\\aaa' // to = 'C:\\orandea\\impl\\bbb' // The output of the function should be: '..\\..\\impl\\bbb' relative(from: string, to: string): string { validateString(from, 'from'); validateString(to, 'to'); if (from === to) { return ''; } const fromOrig = win32.resolve(from); const toOrig = win32.resolve(to); if (fromOrig === toOrig) { return ''; } from = fromOrig.toLowerCase(); to = toOrig.toLowerCase(); if (from === to) { return ''; } // Trim any leading backslashes let fromStart = 0; while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) { fromStart++; } // Trim trailing backslashes (applicable to UNC paths only) let fromEnd = from.length; while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) { fromEnd--; } const fromLen = fromEnd - fromStart; // Trim any leading backslashes let toStart = 0; while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { toStart++; } // Trim trailing backslashes (applicable to UNC paths only) let toEnd = to.length; while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) { toEnd--; } const toLen = toEnd - toStart; // Compare paths to find the longest common path from root const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i = 0; for (; i < length; i++) { const fromCode = from.charCodeAt(fromStart + i); if (fromCode !== to.charCodeAt(toStart + i)) { break; } else if (fromCode === CHAR_BACKWARD_SLASH) { lastCommonSep = i; } } // We found a mismatch before the first common path separator was seen, so // return the original `to`. if (i !== length) { if (lastCommonSep === -1) { return toOrig; } } else { if (toLen > length) { if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { // We get here if `from` is the exact base path for `to`. // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' return toOrig.slice(toStart + i + 1); } if (i === 2) { // We get here if `from` is the device root. // For example: from='C:\\'; to='C:\\foo' return toOrig.slice(toStart + i); } } if (fromLen > length) { if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { // We get here if `to` is the exact base path for `from`. // For example: from='C:\\foo\\bar'; to='C:\\foo' lastCommonSep = i; } else if (i === 2) { // We get here if `to` is the device root. // For example: from='C:\\foo\\bar'; to='C:\\' lastCommonSep = 3; } } if (lastCommonSep === -1) { lastCommonSep = 0; } } let out = ''; // Generate the relative path based on the path difference between `to` and // `from` for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { out += out.length === 0 ? '..' : '\\..'; } } toStart += lastCommonSep; // Lastly, append the rest of the destination (`to`) path that comes after // the common path parts if (out.length > 0) { return `${out}${toOrig.slice(toStart, toEnd)}`; } if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { ++toStart; } return toOrig.slice(toStart, toEnd); }, toNamespacedPath(path: string): string { // Note: this will *probably* throw somewhere. if (typeof path !== 'string' || path.length === 0) { return path; } const resolvedPath = win32.resolve(path); if (resolvedPath.length <= 2) { return path; } if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { // Possible UNC root if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { const code = resolvedPath.charCodeAt(2); if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { // Matched non-long UNC root, convert the path to a long UNC path return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; } } } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) { // Matched device root, convert the path to a long UNC path return `\\\\?\\${resolvedPath}`; } return path; }, dirname(path: string): string { validateString(path, 'path'); const len = path.length; if (len === 0) { return '.'; } let rootEnd = -1; let offset = 0; const code = path.charCodeAt(0); if (len === 1) { // `path` contains just a path separator, exit early to avoid // unnecessary work or a dot. return isPathSeparator(code) ? path : '.'; } // Try to match a root if (isPathSeparator(code)) { // Possible UNC root rootEnd = offset = 1; if (isPathSeparator(path.charCodeAt(1))) { // Matched double path separator at beginning let j = 2; let last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more path separators while (j < len && isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j === len) { // We matched a UNC root only return path; } if (j !== last) { // We matched a UNC root with leftovers // Offset by 1 to include the separator after the UNC root to // treat it as a "normal root" on top of a (UNC) root rootEnd = offset = j + 1; } } } } // Possible device root } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2; offset = rootEnd; } let end = -1; let matchedSlash = true; for (let i = len - 1; i >= offset; --i) { if (isPathSeparator(path.charCodeAt(i))) { if (!matchedSlash) { end = i; break; } } else { // We saw the first non-path separator matchedSlash = false; } } if (end === -1) { if (rootEnd === -1) { return '.'; } end = rootEnd; } return path.slice(0, end); }, basename(path: string, ext?: string): string { if (ext !== undefined) { validateString(ext, 'ext'); } validateString(path, 'path'); let start = 0; let end = -1; let matchedSlash = true; let i; // Check for a drive letter prefix so as not to mistake the following // path separator as an extra separator at the end of the path that can be // disregarded if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) { start = 2; } if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { if (ext === path) { return ''; } let extIdx = ext.length - 1; let firstNonSlashEnd = -1; for (i = path.length - 1; i >= start; --i) { const code = path.charCodeAt(i); if (isPathSeparator(code)) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { start = i + 1; break; } } else { if (firstNonSlashEnd === -1) { // We saw the first non-path separator, remember this index in case // we need it if the extension ends up not matching matchedSlash = false; firstNonSlashEnd = i + 1; } if (extIdx >= 0) { // Try to match the explicit extension if (code === ext.charCodeAt(extIdx)) { if (--extIdx === -1) { // We matched the extension, so mark this as the end of our path // component end = i; } } else { // Extension does not match, so our result is the entire path // component extIdx = -1; end = firstNonSlashEnd; } } } } if (start === end) { end = firstNonSlashEnd; } else if (end === -1) { end = path.length; } return path.slice(start, end); } for (i = path.length - 1; i >= start; --i) { if (isPathSeparator(path.charCodeAt(i))) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { start = i + 1; break; } } else if (end === -1) { // We saw the first non-path separator, mark this as the end of our // path component matchedSlash = false; end = i + 1; } } if (end === -1) { return ''; } return path.slice(start, end); }, extname(path: string): string { validateString(path, 'path'); let start = 0; let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; // Track the state of characters (if any) we see before our first dot and // after any path separator we find let preDotState = 0; // Check for a drive letter prefix so as not to mistake the following // path separator as an extra separator at the end of the path that can be // disregarded if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) { start = startPart = 2; } for (let i = path.length - 1; i >= start; --i) { const code = path.charCodeAt(i); if (isPathSeparator(code)) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { startPart = i + 1; break; } continue; } if (end === -1) { // We saw the first non-path separator, mark this as the end of our // extension matchedSlash = false; end = i + 1; } if (code === CHAR_DOT) { // If this is our first dot, mark it as the start of our extension if (startDot === -1) { startDot = i; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { // We saw a non-dot and non-path separator before our dot, so we should // have a good chance at having a non-empty extension preDotState = -1; } } if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) { return ''; } return path.slice(startDot, end); }, format: _format.bind(null, '\\'), parse(path) { validateString(path, 'path'); const ret = { root: '', dir: '', base: '', ext: '', name: '' }; if (path.length === 0) { return ret; } const len = path.length; let rootEnd = 0; let code = path.charCodeAt(0); if (len === 1) { if (isPathSeparator(code)) { // `path` contains just a path separator, exit early to avoid // unnecessary work ret.root = ret.dir = path; return ret; } ret.base = ret.name = path; return ret; } // Try to match a root if (isPathSeparator(code)) { // Possible UNC root rootEnd = 1; if (isPathSeparator(path.charCodeAt(1))) { // Matched double path separator at beginning let j = 2; let last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more path separators while (j < len && isPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators while (j < len && !isPathSeparator(path.charCodeAt(j))) { j++; } if (j === len) { // We matched a UNC root only rootEnd = j; } else if (j !== last) { // We matched a UNC root with leftovers rootEnd = j + 1; } } } } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { // Possible device root if (len <= 2) { // `path` contains just a drive root, exit early to avoid // unnecessary work ret.root = ret.dir = path; return ret; } rootEnd = 2; if (isPathSeparator(path.charCodeAt(2))) { if (len === 3) { // `path` contains just a drive root, exit early to avoid // unnecessary work ret.root = ret.dir = path; return ret; } rootEnd = 3; } } if (rootEnd > 0) { ret.root = path.slice(0, rootEnd); } let startDot = -1; let startPart = rootEnd; let end = -1; let matchedSlash = true; let i = path.length - 1; // Track the state of characters (if any) we see before our first dot and // after any path separator we find let preDotState = 0; // Get non-dir info for (; i >= rootEnd; --i) { code = path.charCodeAt(i); if (isPathSeparator(code)) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { startPart = i + 1; break; } continue; } if (end === -1) { // We saw the first non-path separator, mark this as the end of our // extension matchedSlash = false; end = i + 1; } if (code === CHAR_DOT) { // If this is our first dot, mark it as the start of our extension if (startDot === -1) { startDot = i; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { // We saw a non-dot and non-path separator before our dot, so we should // have a good chance at having a non-empty extension preDotState = -1; } } if (end !== -1) { if (startDot === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) { ret.base = ret.name = path.slice(startPart, end); } else { ret.name = path.slice(startPart, startDot); ret.base = path.slice(startPart, end); ret.ext = path.slice(startDot, end); } } // If the directory is the root, use the entire root as the `dir` including // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the // trailing slash (`C:\abc\def` -> `C:\abc`). if (startPart > 0 && startPart !== rootEnd) { ret.dir = path.slice(0, startPart - 1); } else { ret.dir = ret.root; } return ret; }, sep: '\\', delimiter: ';', win32: null, posix: null }; const posixCwd = (() => { if (platformIsWin32) { // Converts Windows' backslash path separators to POSIX forward slashes // and truncates any drive indicator const regexp = /\\/g; return () => { const cwd = process.cwd().replace(regexp, '/'); return cwd.slice(cwd.indexOf('/')); }; } // We're already on POSIX, no need for any transformations return () => process.cwd(); })(); export const posix: IPath = { // path.resolve([from ...], to) resolve(...pathSegments: string[]): string { let resolvedPath = ''; let resolvedAbsolute = false; for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) { const path = i >= 0 ? pathSegments[i] : posixCwd(); validateString(path, 'path'); // Skip empty entries if (path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); if (resolvedAbsolute) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : '.'; }, normalize(path: string): string { validateString(path, 'path'); if (path.length === 0) { return '.'; } const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; // Normalize the path path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator); if (path.length === 0) { if (isAbsolute) { return '/'; } return trailingSeparator ? './' : '.'; } if (trailingSeparator) { path += '/'; } return isAbsolute ? `/${path}` : path; }, isAbsolute(path: string): boolean { validateString(path, 'path'); return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; }, join(...paths: string[]): string { if (paths.length === 0) { return '.'; } let joined; for (let i = 0; i < paths.length; ++i) { const arg = paths[i]; validateString(arg, 'path'); if (arg.length > 0) { if (joined === undefined) { joined = arg; } else { joined += `/${arg}`; } } } if (joined === undefined) { return '.'; } return posix.normalize(joined); }, relative(from: string, to: string): string { validateString(from, 'from'); validateString(to, 'to'); if (from === to) { return ''; } // Trim leading forward slashes. from = posix.resolve(from); to = posix.resolve(to); if (from === to) { return ''; } const fromStart = 1; const fromEnd = from.length; const fromLen = fromEnd - fromStart; const toStart = 1; const toLen = to.length - toStart; // Compare paths to find the longest common path from root const length = (fromLen < toLen ? fromLen : toLen); let lastCommonSep = -1; let i = 0; for (; i < length; i++) { const fromCode = from.charCodeAt(fromStart + i); if (fromCode !== to.charCodeAt(toStart + i)) { break; } else if (fromCode === CHAR_FORWARD_SLASH) { lastCommonSep = i; } } if (i === length) { if (toLen > length) { if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { // We get here if `from` is the exact base path for `to`. // For example: from='/foo/bar'; to='/foo/bar/baz' return to.slice(toStart + i + 1); } if (i === 0) { // We get here if `from` is the root // For example: from='/'; to='/foo' return to.slice(toStart + i); } } else if (fromLen > length) { if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { // We get here if `to` is the exact base path for `from`. // For example: from='/foo/bar/baz'; to='/foo/bar' lastCommonSep = i; } else if (i === 0) { // We get here if `to` is the root. // For example: from='/foo/bar'; to='/' lastCommonSep = 0; } } } let out = ''; // Generate the relative path based on the path difference between `to` // and `from`. for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { out += out.length === 0 ? '..' : '/..'; } } // Lastly, append the rest of the destination (`to`) path that comes after // the common path parts. return `${out}${to.slice(toStart + lastCommonSep)}`; }, toNamespacedPath(path: string): string { // Non-op on posix systems return path; }, dirname(path: string): string { validateString(path, 'path'); if (path.length === 0) { return '.'; } const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; let end = -1; let matchedSlash = true; for (let i = path.length - 1; i >= 1; --i) { if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { if (!matchedSlash) { end = i; break; } } else { // We saw the first non-path separator matchedSlash = false; } } if (end === -1) { return hasRoot ? '/' : '.'; } if (hasRoot && end === 1) { return '//'; } return path.slice(0, end); }, basename(path: string, ext?: string): string { if (ext !== undefined) { validateString(ext, 'ext'); } validateString(path, 'path'); let start = 0; let end = -1; let matchedSlash = true; let i; if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { if (ext === path) { return ''; } let extIdx = ext.length - 1; let firstNonSlashEnd = -1; for (i = path.length - 1; i >= 0; --i) { const code = path.charCodeAt(i); if (code === CHAR_FORWARD_SLASH) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { start = i + 1; break; } } else { if (firstNonSlashEnd === -1) { // We saw the first non-path separator, remember this index in case // we need it if the extension ends up not matching matchedSlash = false; firstNonSlashEnd = i + 1; } if (extIdx >= 0) { // Try to match the explicit extension if (code === ext.charCodeAt(extIdx)) { if (--extIdx === -1) { // We matched the extension, so mark this as the end of our path // component end = i; } } else { // Extension does not match, so our result is the entire path // component extIdx = -1; end = firstNonSlashEnd; } } } } if (start === end) { end = firstNonSlashEnd; } else if (end === -1) { end = path.length; } return path.slice(start, end); } for (i = path.length - 1; i >= 0; --i) { if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { start = i + 1; break; } } else if (end === -1) { // We saw the first non-path separator, mark this as the end of our // path component matchedSlash = false; end = i + 1; } } if (end === -1) { return ''; } return path.slice(start, end); }, extname(path: string): string { validateString(path, 'path'); let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; // Track the state of characters (if any) we see before our first dot and // after any path separator we find let preDotState = 0; for (let i = path.length - 1; i >= 0; --i) { const code = path.charCodeAt(i); if (code === CHAR_FORWARD_SLASH) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { startPart = i + 1; break; } continue; } if (end === -1) { // We saw the first non-path separator, mark this as the end of our // extension matchedSlash = false; end = i + 1; } if (code === CHAR_DOT) { // If this is our first dot, mark it as the start of our extension if (startDot === -1) { startDot = i; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { // We saw a non-dot and non-path separator before our dot, so we should // have a good chance at having a non-empty extension preDotState = -1; } } if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) { return ''; } return path.slice(startDot, end); }, format: _format.bind(null, '/'), parse(path: string): ParsedPath { validateString(path, 'path'); const ret = { root: '', dir: '', base: '', ext: '', name: '' }; if (path.length === 0) { return ret; } const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; let start; if (isAbsolute) { ret.root = '/'; start = 1; } else { start = 0; } let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; let i = path.length - 1; // Track the state of characters (if any) we see before our first dot and // after any path separator we find let preDotState = 0; // Get non-dir info for (; i >= start; --i) { const code = path.charCodeAt(i); if (code === CHAR_FORWARD_SLASH) { // If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if (!matchedSlash) { startPart = i + 1; break; } continue; } if (end === -1) { // We saw the first non-path separator, mark this as the end of our // extension matchedSlash = false; end = i + 1; } if (code === CHAR_DOT) { // If this is our first dot, mark it as the start of our extension if (startDot === -1) { startDot = i; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { // We saw a non-dot and non-path separator before our dot, so we should // have a good chance at having a non-empty extension preDotState = -1; } } if (end !== -1) { const start = startPart === 0 && isAbsolute ? 1 : startPart; if (startDot === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) { ret.base = ret.name = path.slice(start, end); } else { ret.name = path.slice(start, startDot); ret.base = path.slice(start, end); ret.ext = path.slice(startDot, end); } } if (startPart > 0) { ret.dir = path.slice(0, startPart - 1); } else if (isAbsolute) { ret.dir = '/'; } return ret; }, sep: '/', delimiter: ':', win32: null, posix: null }; posix.win32 = win32.win32 = win32; posix.posix = win32.posix = posix; export const normalize = (platformIsWin32 ? win32.normalize : posix.normalize); export const isAbsolute = (platformIsWin32 ? win32.isAbsolute : posix.isAbsolute); export const join = (platformIsWin32 ? win32.join : posix.join); export const resolve = (platformIsWin32 ? win32.resolve : posix.resolve); export const relative = (platformIsWin32 ? win32.relative : posix.relative); export const dirname = (platformIsWin32 ? win32.dirname : posix.dirname); export const basename = (platformIsWin32 ? win32.basename : posix.basename); export const extname = (platformIsWin32 ? win32.extname : posix.extname); export const format = (platformIsWin32 ? win32.format : posix.format); export const parse = (platformIsWin32 ? win32.parse : posix.parse); export const toNamespacedPath = (platformIsWin32 ? win32.toNamespacedPath : posix.toNamespacedPath); export const sep = (platformIsWin32 ? win32.sep : posix.sep); export const delimiter = (platformIsWin32 ? win32.delimiter : posix.delimiter);
src/vs/base/common/path.ts
0
https://github.com/microsoft/vscode/commit/d3af6535b09db60e994e3def6309a2089d720915
[ 0.00023752881679683924, 0.00017262822075281292, 0.00016347093333024532, 0.00017233214748557657, 0.00000595921164858737 ]
{ "id": 0, "code_window": [ "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { ReactUtils, useStyles2 } from '@grafana/ui';\n", "\n", "import { QueryOperationRowHeader } from './QueryOperationRowHeader';\n", "\n", "export interface QueryOperationRowProps {\n", " index: number;\n", " id: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { QueryOperationRowHeader, ExpanderMessages } from './QueryOperationRowHeader';\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import React, { useCallback } from 'react'; import { useToggle } from 'react-use'; import { DataFrame, DataTransformerConfig, TransformerRegistryItem, FrameMatcherID } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ConfirmModal } from '@grafana/ui'; import { OperationRowHelp } from 'app/core/components/QueryOperationRow/OperationRowHelp'; import { QueryOperationAction, QueryOperationToggleAction, } from 'app/core/components/QueryOperationRow/QueryOperationAction'; import { QueryOperationRow, QueryOperationRowRenderProps, } from 'app/core/components/QueryOperationRow/QueryOperationRow'; import config from 'app/core/config'; import { PluginStateInfo } from 'app/features/plugins/components/PluginStateInfo'; import { TransformationEditor } from './TransformationEditor'; import { TransformationFilter } from './TransformationFilter'; import { TransformationsEditorTransformation } from './types'; interface TransformationOperationRowProps { id: string; index: number; data: DataFrame[]; uiConfig: TransformerRegistryItem<null>; configs: TransformationsEditorTransformation[]; onRemove: (index: number) => void; onChange: (index: number, config: DataTransformerConfig) => void; } export const TransformationOperationRow = ({ onRemove, index, id, data, configs, uiConfig, onChange, }: TransformationOperationRowProps) => { const [showDeleteModal, setShowDeleteModal] = useToggle(false); const [showDebug, toggleShowDebug] = useToggle(false); const [showHelp, toggleShowHelp] = useToggle(false); const disabled = !!configs[index].transformation.disabled; const filter = configs[index].transformation.filter != null; const showFilter = filter || data.length > 1; const onDisableToggle = useCallback( (index: number) => { const current = configs[index].transformation; onChange(index, { ...current, disabled: current.disabled ? undefined : true, }); }, [onChange, configs] ); const toggleExpand = useCallback(() => { if (showHelp) { return true; } // We return `undefined` here since the QueryOperationRow component ignores an `undefined` value for the `isOpen` prop. // If we returned `false` here, the row would be collapsed when the user toggles off `showHelp`, which is not what we want. return undefined; }, [showHelp]); // Adds or removes the frame filter const toggleFilter = useCallback(() => { let current = { ...configs[index].transformation }; if (current.filter) { delete current.filter; } else { current.filter = { id: FrameMatcherID.byRefId, options: '', // empty string will not do anything }; } onChange(index, current); }, [onChange, index, configs]); // Instrument toggle callback const instrumentToggleCallback = useCallback( (callback: (e: React.MouseEvent) => void, toggleId: string, active: boolean | undefined) => (e: React.MouseEvent) => { let eventName = 'panel_editor_tabs_transformations_toggle'; if (config.featureToggles.transformationsRedesign) { eventName = 'transformations_redesign_' + eventName; } reportInteraction(eventName, { action: active ? 'off' : 'on', toggleId, transformationId: configs[index].transformation.id, }); callback(e); }, [configs, index] ); const renderActions = ({ isOpen }: QueryOperationRowRenderProps) => { return ( <> {uiConfig.state && <PluginStateInfo state={uiConfig.state} />} <QueryOperationToggleAction title="Show transform help" icon="info-circle" // `instrumentToggleCallback` expects a function that takes a MouseEvent, is unused in the state setter. Instead, we simply toggle the state. onClick={instrumentToggleCallback((_e) => toggleShowHelp(!showHelp), 'help', showHelp)} active={!!showHelp} /> {showFilter && ( <QueryOperationToggleAction title="Filter" icon="filter" onClick={instrumentToggleCallback(toggleFilter, 'filter', filter)} active={filter} /> )} <QueryOperationToggleAction title="Debug" disabled={!isOpen} icon="bug" onClick={instrumentToggleCallback(toggleShowDebug, 'debug', showDebug)} active={showDebug} /> <QueryOperationToggleAction title="Disable transformation" icon={disabled ? 'eye-slash' : 'eye'} onClick={instrumentToggleCallback(() => onDisableToggle(index), 'disabled', disabled)} active={disabled} /> <QueryOperationAction title="Remove" icon="trash-alt" onClick={() => (config.featureToggles.transformationsRedesign ? setShowDeleteModal(true) : onRemove(index))} /> {config.featureToggles.transformationsRedesign && ( <ConfirmModal isOpen={showDeleteModal} title={`Delete ${uiConfig.name}?`} body="Note that removing one transformation may break others. If there is only a single transformation, you will go back to the main selection screen." confirmText="Delete" onConfirm={() => { setShowDeleteModal(false); onRemove(index); }} onDismiss={() => setShowDeleteModal(false)} /> )} </> ); }; return ( <QueryOperationRow id={id} index={index} title={uiConfig.name} draggable actions={renderActions} disabled={disabled} isOpen={toggleExpand()} // Assure that showHelp is untoggled when the row becomes collapsed. onClose={() => toggleShowHelp(false)} > {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />} {filter && ( <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} /> )} <TransformationEditor debugMode={showDebug} index={index} data={data} configs={configs} uiConfig={uiConfig} onChange={onChange} /> </QueryOperationRow> ); }; function prepMarkdown(uiConfig: TransformerRegistryItem<null>) { let helpMarkdown = uiConfig.help ?? uiConfig.description; return ` ${helpMarkdown} Go the <a href="https://grafana.com/docs/grafana/latest/panels/transformations/?utm_source=grafana" target="_blank" rel="noreferrer"> transformation documentation </a> for more. `; }
public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.9989809393882751, 0.10101602226495743, 0.00016365371993742883, 0.0008766810642555356, 0.2992301881313324 ]
{ "id": 0, "code_window": [ "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { ReactUtils, useStyles2 } from '@grafana/ui';\n", "\n", "import { QueryOperationRowHeader } from './QueryOperationRowHeader';\n", "\n", "export interface QueryOperationRowProps {\n", " index: number;\n", " id: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { QueryOperationRowHeader, ExpanderMessages } from './QueryOperationRowHeader';\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
{ "name": "@grafana-plugins/input-datasource", "version": "10.2.0-pre", "description": "Input Datasource", "private": true, "repository": { "type": "git", "url": "http://github.com/grafana/grafana.git" }, "scripts": { "build": "yarn test && webpack -c webpack.config.ts --env production", "dev": "webpack -w -c webpack.config.ts --env development", "test": "jest -c jest.config.js" }, "author": "Grafana Labs", "devDependencies": { "@grafana/tsconfig": "^1.2.0-rc1", "@types/jest": "26.0.15", "@types/react": "18.0.28", "copy-webpack-plugin": "11.0.0", "eslint-webpack-plugin": "4.0.0", "fork-ts-checker-webpack-plugin": "8.0.0", "jest": "29.3.1", "jest-environment-jsdom": "29.3.1", "ts-jest": "29.0.5", "ts-loader": "9.3.1", "ts-node": "10.9.1", "webpack": "5.76.0" }, "dependencies": { "@grafana/data": "10.2.0-pre", "@grafana/ui": "10.2.0-pre", "react": "18.2.0", "tslib": "2.5.0" } }
plugins-bundled/internal/input-datasource/package.json
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017381225188728422, 0.00017073033086489886, 0.000167112797498703, 0.0001709981297608465, 0.0000025148124223051127 ]
{ "id": 0, "code_window": [ "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { ReactUtils, useStyles2 } from '@grafana/ui';\n", "\n", "import { QueryOperationRowHeader } from './QueryOperationRowHeader';\n", "\n", "export interface QueryOperationRowProps {\n", " index: number;\n", " id: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { QueryOperationRowHeader, ExpanderMessages } from './QueryOperationRowHeader';\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import { DatasourceSrv } from 'app/features/plugins/datasource_srv'; import { RichHistoryQuery } from '../../types'; import { backendSrv } from '../services/backend_srv'; import { RichHistoryLocalStorageDTO } from './RichHistoryLocalStorage'; import { fromDTO, toDTO } from './localStorageConverter'; const dsMock = new DatasourceSrv(); dsMock.init( { // @ts-ignore 'name-of-dev-test': { uid: 'dev-test', name: 'name-of-dev-test' }, }, '' ); jest.mock('@grafana/runtime', () => ({ ...jest.requireActual('@grafana/runtime'), getBackendSrv: () => backendSrv, getDataSourceSrv: () => dsMock, })); const validRichHistory: RichHistoryQuery = { comment: 'comment', createdAt: 1, datasourceName: 'name-of-dev-test', datasourceUid: 'dev-test', id: '1', queries: [{ refId: 'A' }], starred: true, }; const validDTO: RichHistoryLocalStorageDTO = { comment: 'comment', datasourceName: 'name-of-dev-test', queries: [{ refId: 'A' }], starred: true, ts: 1, }; describe('LocalStorage converted', () => { it('converts RichHistoryQuery to local storage DTO', () => { expect(toDTO(validRichHistory)).toMatchObject(validDTO); }); it('throws an error when data source for RichHistory does not exist to avoid saving invalid items', () => { const invalidRichHistory = { ...validRichHistory, datasourceUid: 'invalid' }; expect(() => { toDTO(invalidRichHistory); }).toThrow(); }); it('converts DTO to RichHistoryQuery', () => { expect(fromDTO(validDTO)).toMatchObject(validRichHistory); }); it('uses empty uid when datasource does not exist for a DTO to fail gracefully for queries from removed datasources', () => { const invalidDto = { ...validDTO, datasourceName: 'removed' }; expect(fromDTO(invalidDto)).toMatchObject({ ...validRichHistory, datasourceName: 'removed', datasourceUid: '', }); }); });
public/app/core/history/localStorageConverter.test.ts
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001781936443876475, 0.00017309968825429678, 0.00016778564895503223, 0.00017397955525666475, 0.0000036221820209902944 ]
{ "id": 0, "code_window": [ "\n", "import { GrafanaTheme2 } from '@grafana/data';\n", "import { reportInteraction } from '@grafana/runtime';\n", "import { ReactUtils, useStyles2 } from '@grafana/ui';\n", "\n", "import { QueryOperationRowHeader } from './QueryOperationRowHeader';\n", "\n", "export interface QueryOperationRowProps {\n", " index: number;\n", " id: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { QueryOperationRowHeader, ExpanderMessages } from './QueryOperationRowHeader';\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "replace", "edit_start_line_idx": 9 }
import React, { useMemo, useRef, useState } from 'react'; import { CartesianCoords2D, compareDataFrameStructures, DataFrame, Field, FieldColorModeId, FieldType, getFieldDisplayName, PanelProps, TimeRange, VizOrientation, } from '@grafana/data'; import { PanelDataErrorView } from '@grafana/runtime'; import { SortOrder } from '@grafana/schema'; import { GraphGradientMode, GraphNG, GraphNGProps, measureText, PlotLegend, Portal, StackingMode, TooltipDisplayMode, UPlotConfigBuilder, UPLOT_AXIS_FONT_SIZE, usePanelContext, useTheme2, VizLayout, VizLegend, VizTooltipContainer, } from '@grafana/ui'; import { PropDiffFn } from '@grafana/ui/src/components/GraphNG/GraphNG'; import { HoverEvent, addTooltipSupport } from '@grafana/ui/src/components/uPlot/config/addTooltipSupport'; import { CloseButton } from 'app/core/components/CloseButton/CloseButton'; import { getFieldLegendItem } from 'app/core/components/TimelineChart/utils'; import { DataHoverView } from 'app/features/visualization/data-hover/DataHoverView'; import { Options } from './panelcfg.gen'; import { prepareBarChartDisplayValues, preparePlotConfigBuilder } from './utils'; const TOOLTIP_OFFSET = 10; /** * @alpha */ export interface BarChartProps extends Options, Omit<GraphNGProps, 'prepConfig' | 'propsToDiff' | 'renderLegend' | 'theme'> {} const propsToDiff: Array<string | PropDiffFn> = [ 'orientation', 'barWidth', 'barRadius', 'xTickLabelRotation', 'xTickLabelMaxLength', 'xTickLabelSpacing', 'groupWidth', 'stacking', 'showValue', 'xField', 'colorField', 'legend', (prev: BarChartProps, next: BarChartProps) => next.text?.valueSize === prev.text?.valueSize, ]; interface Props extends PanelProps<Options> {} export const BarChartPanel = ({ data, options, fieldConfig, width, height, timeZone, id }: Props) => { const theme = useTheme2(); const { eventBus } = usePanelContext(); const oldConfig = useRef<UPlotConfigBuilder | undefined>(undefined); const isToolTipOpen = useRef<boolean>(false); const [hover, setHover] = useState<HoverEvent | undefined>(undefined); const [coords, setCoords] = useState<{ viewport: CartesianCoords2D; canvas: CartesianCoords2D } | null>(null); const [focusedSeriesIdx, setFocusedSeriesIdx] = useState<number | null>(null); const [focusedPointIdx, setFocusedPointIdx] = useState<number | null>(null); const [isActive, setIsActive] = useState<boolean>(false); const [shouldDisplayCloseButton, setShouldDisplayCloseButton] = useState<boolean>(false); const onCloseToolTip = () => { isToolTipOpen.current = false; setCoords(null); setShouldDisplayCloseButton(false); }; const onUPlotClick = () => { isToolTipOpen.current = !isToolTipOpen.current; // Linking into useState required to re-render tooltip setShouldDisplayCloseButton(isToolTipOpen.current); }; const frame0Ref = useRef<DataFrame>(); const colorByFieldRef = useRef<Field>(); const info = useMemo(() => prepareBarChartDisplayValues(data.series, theme, options), [data.series, theme, options]); const chartDisplay = 'viz' in info ? info : null; colorByFieldRef.current = chartDisplay?.colorByField; const structureRef = useRef(10000); useMemo(() => { structureRef.current++; // eslint-disable-next-line react-hooks/exhaustive-deps }, [options]); // change every time the options object changes (while editing) const structureRev = useMemo(() => { const f0 = chartDisplay?.viz[0]; const f1 = frame0Ref.current; if (!(f0 && f1 && compareDataFrameStructures(f0, f1, true))) { structureRef.current++; } frame0Ref.current = f0; return (data.structureRev ?? 0) + structureRef.current; }, [chartDisplay, data.structureRev]); const orientation = useMemo(() => { if (!options.orientation || options.orientation === VizOrientation.Auto) { return width < height ? VizOrientation.Horizontal : VizOrientation.Vertical; } return options.orientation; }, [width, height, options.orientation]); const xTickLabelMaxLength = useMemo(() => { // If no max length is set, limit the number of characters to a length where it will use a maximum of half of the height of the viz. if (!options.xTickLabelMaxLength) { const rotationAngle = options.xTickLabelRotation; const textSize = measureText('M', UPLOT_AXIS_FONT_SIZE).width; // M is usually the widest character so let's use that as an approximation. const maxHeightForValues = height / 2; return ( maxHeightForValues / (Math.sin(((rotationAngle >= 0 ? rotationAngle : rotationAngle * -1) * Math.PI) / 180) * textSize) - 3 //Subtract 3 for the "..." added to the end. ); } else { return options.xTickLabelMaxLength; } }, [height, options.xTickLabelRotation, options.xTickLabelMaxLength]); if ('warn' in info) { return ( <PanelDataErrorView panelId={id} fieldConfig={fieldConfig} data={data} message={info.warn} needsNumberField={true} /> ); } const renderTooltip = (alignedFrame: DataFrame, seriesIdx: number | null, datapointIdx: number | null) => { const field = seriesIdx == null ? null : alignedFrame.fields[seriesIdx]; if (field) { const disp = getFieldDisplayName(field, alignedFrame); seriesIdx = info.aligned.fields.findIndex((f) => disp === getFieldDisplayName(f, info.aligned)); } const tooltipMode = options.fullHighlight && options.stacking !== StackingMode.None ? TooltipDisplayMode.Multi : options.tooltip.mode; const tooltipSort = options.tooltip.mode === TooltipDisplayMode.Multi ? options.tooltip.sort : SortOrder.None; return ( <> {shouldDisplayCloseButton && ( <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end', }} > <CloseButton onClick={onCloseToolTip} style={{ position: 'relative', top: 'auto', right: 'auto', marginRight: 0, }} /> </div> )} <DataHoverView data={info.aligned} rowIndex={datapointIdx} columnIndex={seriesIdx} sortOrder={tooltipSort} mode={tooltipMode} /> </> ); }; const renderLegend = (config: UPlotConfigBuilder) => { const { legend } = options; if (!config || legend.showLegend === false) { return null; } if (info.colorByField) { const items = getFieldLegendItem([info.colorByField], theme); if (items?.length) { return ( <VizLayout.Legend placement={legend.placement}> <VizLegend placement={legend.placement} items={items} displayMode={legend.displayMode} /> </VizLayout.Legend> ); } } return <PlotLegend data={[info.legend]} config={config} maxHeight="35%" maxWidth="60%" {...options.legend} />; }; const rawValue = (seriesIdx: number, valueIdx: number) => { return frame0Ref.current!.fields[seriesIdx].values[valueIdx]; }; // Color by value let getColor: ((seriesIdx: number, valueIdx: number) => string) | undefined = undefined; let fillOpacity = 1; if (info.colorByField) { const colorByField = info.colorByField; const disp = colorByField.display!; fillOpacity = (colorByField.config.custom.fillOpacity ?? 100) / 100; // gradientMode? ignore? getColor = (seriesIdx: number, valueIdx: number) => disp(colorByFieldRef.current?.values[valueIdx]).color!; } else { const hasPerBarColor = frame0Ref.current!.fields.some((f) => { const fromThresholds = f.config.custom?.gradientMode === GraphGradientMode.Scheme && f.config.color?.mode === FieldColorModeId.Thresholds; return ( fromThresholds || f.config.mappings?.some((m) => { // ValueToText mappings have a different format, where all of them are grouped into an object keyed by value if (m.type === 'value') { // === MappingType.ValueToText return Object.values(m.options).some((result) => result.color != null); } return m.options.result.color != null; }) ); }); if (hasPerBarColor) { // use opacity from first numeric field let opacityField = frame0Ref.current!.fields.find((f) => f.type === FieldType.number)!; fillOpacity = (opacityField.config.custom.fillOpacity ?? 100) / 100; getColor = (seriesIdx: number, valueIdx: number) => { let field = frame0Ref.current!.fields[seriesIdx]; return field.display!(field.values[valueIdx]).color!; }; } } const prepConfig = (alignedFrame: DataFrame, allFrames: DataFrame[], getTimeRange: () => TimeRange) => { const { barWidth, barRadius = 0, showValue, groupWidth, stacking, legend, tooltip, text, xTickLabelRotation, xTickLabelSpacing, fullHighlight, } = options; return preparePlotConfigBuilder({ frame: alignedFrame, getTimeRange, timeZone, theme, timeZones: [timeZone], eventBus, orientation, barWidth, barRadius, showValue, groupWidth, xTickLabelRotation, xTickLabelMaxLength, xTickLabelSpacing, stacking, legend, tooltip, text, rawValue, getColor, fillOpacity, allFrames: info.viz, fullHighlight, }); }; return ( <GraphNG theme={theme} frames={info.viz} prepConfig={prepConfig} propsToDiff={propsToDiff} preparePlotFrame={(f) => f[0]} // already processed in by the panel above! renderLegend={renderLegend} legend={options.legend} timeZone={timeZone} timeRange={{ from: 1, to: 1 } as unknown as TimeRange} // HACK structureRev={structureRev} width={width} height={height} > {(config) => { if (oldConfig.current !== config) { oldConfig.current = addTooltipSupport({ config, onUPlotClick, setFocusedSeriesIdx, setFocusedPointIdx, setCoords, setHover, isToolTipOpen, isActive, setIsActive, }); } if (options.tooltip.mode === TooltipDisplayMode.None) { return null; } return ( <Portal> {hover && coords && focusedSeriesIdx && ( <VizTooltipContainer position={{ x: coords.viewport.x, y: coords.viewport.y }} offset={{ x: TOOLTIP_OFFSET, y: TOOLTIP_OFFSET }} allowPointerEvents={isToolTipOpen.current} > {renderTooltip(info.viz[0], focusedSeriesIdx, focusedPointIdx)} </VizTooltipContainer> )} </Portal> ); }} </GraphNG> ); };
public/app/plugins/panel/barchart/BarChartPanel.tsx
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00020217994460836053, 0.0001741353771649301, 0.000164387995027937, 0.0001739016006467864, 0.000006452855359384557 ]
{ "id": 1, "code_window": [ " draggable?: boolean;\n", " collapsable?: boolean;\n", " disabled?: boolean;\n", "}\n", "\n", "export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 24 }
import { css } from '@emotion/css'; import React, { useCallback, useEffect, useState } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { useUpdateEffect } from 'react-use'; import { GrafanaTheme2 } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ReactUtils, useStyles2 } from '@grafana/ui'; import { QueryOperationRowHeader } from './QueryOperationRowHeader'; export interface QueryOperationRowProps { index: number; id: string; title?: string; headerElement?: QueryOperationRowRenderProp; actions?: QueryOperationRowRenderProp; onOpen?: () => void; onClose?: () => void; children: React.ReactNode; isOpen?: boolean; draggable?: boolean; collapsable?: boolean; disabled?: boolean; } export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode; export interface QueryOperationRowRenderProps { isOpen: boolean; onOpen: () => void; onClose: () => void; } export function QueryOperationRow({ children, actions, title, headerElement, onClose, onOpen, isOpen, disabled, draggable, collapsable, index, id, }: QueryOperationRowProps) { const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true); const styles = useStyles2(getQueryOperationRowStyles); const onRowToggle = useCallback(() => { setIsContentVisible(!isContentVisible); }, [isContentVisible, setIsContentVisible]); // Force QueryOperationRow expansion when `isOpen` prop updates in parent component. // `undefined` can be deliberately passed value here, but we only want booleans to trigger the effect. useEffect(() => { if (typeof isOpen === 'boolean') { setIsContentVisible(isOpen); } }, [isOpen]); const reportDragMousePosition = useCallback((e: React.MouseEvent) => { // When drag detected react-beautiful-dnd will preventDefault the event // Ref: https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/how-we-use-dom-events.md#a-mouse-drag-has-started-and-the-user-is-now-dragging if (e.defaultPrevented) { const rect = e.currentTarget.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; // report relative mouse position within the header element reportInteraction('query_row_reorder_drag_position', { x: x / rect.width, y: y / rect.height, width: rect.width, height: rect.height, }); } }, []); useUpdateEffect(() => { if (isContentVisible) { if (onOpen) { onOpen(); } } else { if (onClose) { onClose(); } } }, [isContentVisible]); const renderPropArgs: QueryOperationRowRenderProps = { isOpen: isContentVisible, onOpen: () => { setIsContentVisible(true); }, onClose: () => { setIsContentVisible(false); }, }; const actionsElement = actions && ReactUtils.renderOrCallToRender(actions, renderPropArgs); const headerElementRendered = headerElement && ReactUtils.renderOrCallToRender(headerElement, renderPropArgs); if (draggable) { return ( <Draggable draggableId={id} index={index}> {(provided) => { return ( <> <div ref={provided.innerRef} className={styles.wrapper} {...provided.draggableProps}> <div> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable collapsable={collapsable} dragHandleProps={provided.dragHandleProps} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> </div> {isContentVisible && <div className={styles.content}>{children}</div>} </div> </> ); }} </Draggable> ); } return ( <div className={styles.wrapper}> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable={false} collapsable={collapsable} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> {isContentVisible && <div className={styles.content}>{children}</div>} </div> ); } const getQueryOperationRowStyles = (theme: GrafanaTheme2) => { return { wrapper: css` margin-bottom: ${theme.spacing(2)}; `, content: css` margin-top: ${theme.spacing(0.5)}; margin-left: ${theme.spacing(3)}; `, }; }; QueryOperationRow.displayName = 'QueryOperationRow';
public/app/core/components/QueryOperationRow/QueryOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.9988971948623657, 0.3768991529941559, 0.0001669077028054744, 0.08776915818452835, 0.4331260025501251 ]
{ "id": 1, "code_window": [ " draggable?: boolean;\n", " collapsable?: boolean;\n", " disabled?: boolean;\n", "}\n", "\n", "export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 24 }
export { DashboardSettings } from './DashboardSettings';
public/app/features/dashboard/components/DashboardSettings/index.ts
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017065100837498903, 0.00017065100837498903, 0.00017065100837498903, 0.00017065100837498903, 0 ]
{ "id": 1, "code_window": [ " draggable?: boolean;\n", " collapsable?: boolean;\n", " disabled?: boolean;\n", "}\n", "\n", "export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 24 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M13.6,10.9C13.7,11,13.8,11,14,11h7c0.6,0,1-0.4,1-1c0-0.2,0-0.3-0.1-0.4l-3.5-7c-0.3-0.5-0.9-0.7-1.4-0.4c-0.1,0.1-0.3,0.2-0.4,0.4l-3.5,7C12.9,10,13.1,10.6,13.6,10.9z M17.5,5.2L19.4,9h-3.8L17.5,5.2z M6.5,2C4,2,2,4,2,6.5S4,11,6.5,11S11,9,11,6.5C11,4,9,2,6.5,2z M6.5,9C5.1,9,4,7.9,4,6.5S5.1,4,6.5,4S9,5.1,9,6.5C9,7.9,7.9,9,6.5,9z M10.7,13.3C10.7,13.3,10.7,13.3,10.7,13.3c-0.4-0.4-1-0.4-1.4,0c0,0,0,0,0,0l-2.8,2.8l-2.8-2.8c-0.4-0.4-1-0.4-1.4,0c-0.4,0.4-0.4,1,0,1.4l2.8,2.8l-2.8,2.8c-0.4,0.4-0.4,1,0,1.4s1,0.4,1.4,0c0,0,0,0,0,0l2.8-2.8l2.8,2.8c0.4,0.4,1,0.4,1.4,0c0.4-0.4,0.4-1,0-1.4l-2.8-2.8l2.8-2.8C11.1,14.3,11.1,13.7,10.7,13.3z M21,13h-7c-0.6,0-1,0.4-1,1v7c0,0.6,0.4,1,1,1h7c0.6,0,1-0.4,1-1v-7C22,13.4,21.6,13,21,13z M20,20h-5v-5h5V20z"/></svg>
public/img/icons/unicons/icons.svg
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00023094407515600324, 0.00023094407515600324, 0.00023094407515600324, 0.00023094407515600324, 0 ]
{ "id": 1, "code_window": [ " draggable?: boolean;\n", " collapsable?: boolean;\n", " disabled?: boolean;\n", "}\n", "\n", "export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 24 }
{ "annotations": { "list": [ { "builtIn": 1, "datasource": "-- Grafana --", "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "target": { "limit": 100, "matchAny": false, "tags": [], "type": "dashboard" }, "type": "dashboard" } ] }, "editable": true, "graphTooltip": 0, "links": [], "panels": [ { "gridPos": { "h": 26, "w": 6, "x": 0, "y": 0 }, "id": 7, "links": [], "options": { "maxItems": 100, "query": "", "showHeadings": true, "showRecentlyViewed": true, "showSearch": false, "showStarred": true, "tags": [] }, "pluginVersion": "8.1.0-pre", "tags": [], "title": "Starred", "type": "dashlist" }, { "gridPos": { "h": 13, "w": 6, "x": 6, "y": 0 }, "id": 2, "links": [], "options": { "maxItems": 1000, "query": "", "showHeadings": false, "showRecentlyViewed": false, "showSearch": true, "showStarred": false, "tags": [ "panel-tests" ] }, "pluginVersion": "8.1.0-pre", "tags": [ "panel-tests" ], "title": "tag: panel-tests", "type": "dashlist" }, { "gridPos": { "h": 13, "w": 6, "x": 12, "y": 0 }, "id": 3, "links": [], "options": { "maxItems": 1000, "query": "", "showHeadings": false, "showRecentlyViewed": false, "showSearch": true, "showStarred": false, "tags": [ "gdev", "demo" ] }, "pluginVersion": "8.1.0-pre", "tags": [ "gdev", "demo" ], "title": "tag: dashboard-demo", "type": "dashlist" }, { "gridPos": { "h": 26, "w": 6, "x": 18, "y": 0 }, "id": 5, "links": [], "options": { "maxItems": 1000, "query": "", "showHeadings": false, "showRecentlyViewed": false, "showSearch": true, "showStarred": false, "tags": [ "gdev", "datasource-test" ] }, "pluginVersion": "8.1.0-pre", "tags": [ "gdev", "datasource-test" ], "title": "Data source tests", "type": "dashlist" }, { "gridPos": { "h": 13, "w": 6, "x": 6, "y": 13 }, "id": 4, "links": [], "options": { "maxItems": 1000, "query": "", "showHeadings": false, "showRecentlyViewed": false, "showSearch": true, "showStarred": false, "tags": [ "templating", "gdev" ] }, "pluginVersion": "8.1.0-pre", "tags": [ "templating", "gdev" ], "title": "tag: templating ", "type": "dashlist" }, { "gridPos": { "h": 13, "w": 6, "x": 12, "y": 13 }, "id": 8, "links": [], "options": { "maxItems": 1000, "query": "", "showHeadings": false, "showRecentlyViewed": false, "showSearch": true, "showStarred": false, "tags": [ "gdev", "transform" ] }, "pluginVersion": "8.1.0-pre", "tags": [ "gdev", "demo" ], "title": "tag: transforms", "type": "dashlist" } ], "schemaVersion": 30, "tags": [], "templating": { "list": [] }, "time": { "from": "now-6h", "to": "now" }, "timepicker": { "refresh_intervals": [ "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ], "time_options": [ "5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d" ] }, "timezone": "", "title": "Grafana Dev Overview & Home", "uid": "j6T00KRZz", "version": 2 }
pkg/tests/api/dashboards/home.json
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017956185911316425, 0.00017457373905926943, 0.00017149155610240996, 0.00017452440806664526, 0.0000016310334558511386 ]
{ "id": 2, "code_window": [ " disabled,\n", " draggable,\n", " collapsable,\n", " index,\n", " id,\n", "}: QueryOperationRowProps) {\n", " const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true);\n", " const styles = useStyles2(getQueryOperationRowStyles);\n", " const onRowToggle = useCallback(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 47 }
import React, { useCallback } from 'react'; import { useToggle } from 'react-use'; import { DataFrame, DataTransformerConfig, TransformerRegistryItem, FrameMatcherID } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ConfirmModal } from '@grafana/ui'; import { OperationRowHelp } from 'app/core/components/QueryOperationRow/OperationRowHelp'; import { QueryOperationAction, QueryOperationToggleAction, } from 'app/core/components/QueryOperationRow/QueryOperationAction'; import { QueryOperationRow, QueryOperationRowRenderProps, } from 'app/core/components/QueryOperationRow/QueryOperationRow'; import config from 'app/core/config'; import { PluginStateInfo } from 'app/features/plugins/components/PluginStateInfo'; import { TransformationEditor } from './TransformationEditor'; import { TransformationFilter } from './TransformationFilter'; import { TransformationsEditorTransformation } from './types'; interface TransformationOperationRowProps { id: string; index: number; data: DataFrame[]; uiConfig: TransformerRegistryItem<null>; configs: TransformationsEditorTransformation[]; onRemove: (index: number) => void; onChange: (index: number, config: DataTransformerConfig) => void; } export const TransformationOperationRow = ({ onRemove, index, id, data, configs, uiConfig, onChange, }: TransformationOperationRowProps) => { const [showDeleteModal, setShowDeleteModal] = useToggle(false); const [showDebug, toggleShowDebug] = useToggle(false); const [showHelp, toggleShowHelp] = useToggle(false); const disabled = !!configs[index].transformation.disabled; const filter = configs[index].transformation.filter != null; const showFilter = filter || data.length > 1; const onDisableToggle = useCallback( (index: number) => { const current = configs[index].transformation; onChange(index, { ...current, disabled: current.disabled ? undefined : true, }); }, [onChange, configs] ); const toggleExpand = useCallback(() => { if (showHelp) { return true; } // We return `undefined` here since the QueryOperationRow component ignores an `undefined` value for the `isOpen` prop. // If we returned `false` here, the row would be collapsed when the user toggles off `showHelp`, which is not what we want. return undefined; }, [showHelp]); // Adds or removes the frame filter const toggleFilter = useCallback(() => { let current = { ...configs[index].transformation }; if (current.filter) { delete current.filter; } else { current.filter = { id: FrameMatcherID.byRefId, options: '', // empty string will not do anything }; } onChange(index, current); }, [onChange, index, configs]); // Instrument toggle callback const instrumentToggleCallback = useCallback( (callback: (e: React.MouseEvent) => void, toggleId: string, active: boolean | undefined) => (e: React.MouseEvent) => { let eventName = 'panel_editor_tabs_transformations_toggle'; if (config.featureToggles.transformationsRedesign) { eventName = 'transformations_redesign_' + eventName; } reportInteraction(eventName, { action: active ? 'off' : 'on', toggleId, transformationId: configs[index].transformation.id, }); callback(e); }, [configs, index] ); const renderActions = ({ isOpen }: QueryOperationRowRenderProps) => { return ( <> {uiConfig.state && <PluginStateInfo state={uiConfig.state} />} <QueryOperationToggleAction title="Show transform help" icon="info-circle" // `instrumentToggleCallback` expects a function that takes a MouseEvent, is unused in the state setter. Instead, we simply toggle the state. onClick={instrumentToggleCallback((_e) => toggleShowHelp(!showHelp), 'help', showHelp)} active={!!showHelp} /> {showFilter && ( <QueryOperationToggleAction title="Filter" icon="filter" onClick={instrumentToggleCallback(toggleFilter, 'filter', filter)} active={filter} /> )} <QueryOperationToggleAction title="Debug" disabled={!isOpen} icon="bug" onClick={instrumentToggleCallback(toggleShowDebug, 'debug', showDebug)} active={showDebug} /> <QueryOperationToggleAction title="Disable transformation" icon={disabled ? 'eye-slash' : 'eye'} onClick={instrumentToggleCallback(() => onDisableToggle(index), 'disabled', disabled)} active={disabled} /> <QueryOperationAction title="Remove" icon="trash-alt" onClick={() => (config.featureToggles.transformationsRedesign ? setShowDeleteModal(true) : onRemove(index))} /> {config.featureToggles.transformationsRedesign && ( <ConfirmModal isOpen={showDeleteModal} title={`Delete ${uiConfig.name}?`} body="Note that removing one transformation may break others. If there is only a single transformation, you will go back to the main selection screen." confirmText="Delete" onConfirm={() => { setShowDeleteModal(false); onRemove(index); }} onDismiss={() => setShowDeleteModal(false)} /> )} </> ); }; return ( <QueryOperationRow id={id} index={index} title={uiConfig.name} draggable actions={renderActions} disabled={disabled} isOpen={toggleExpand()} // Assure that showHelp is untoggled when the row becomes collapsed. onClose={() => toggleShowHelp(false)} > {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />} {filter && ( <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} /> )} <TransformationEditor debugMode={showDebug} index={index} data={data} configs={configs} uiConfig={uiConfig} onChange={onChange} /> </QueryOperationRow> ); }; function prepMarkdown(uiConfig: TransformerRegistryItem<null>) { let helpMarkdown = uiConfig.help ?? uiConfig.description; return ` ${helpMarkdown} Go the <a href="https://grafana.com/docs/grafana/latest/panels/transformations/?utm_source=grafana" target="_blank" rel="noreferrer"> transformation documentation </a> for more. `; }
public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.9982591271400452, 0.22636882960796356, 0.00016809180669952184, 0.0011058587115257978, 0.3930530548095703 ]
{ "id": 2, "code_window": [ " disabled,\n", " draggable,\n", " collapsable,\n", " index,\n", " id,\n", "}: QueryOperationRowProps) {\n", " const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true);\n", " const styles = useStyles2(getQueryOperationRowStyles);\n", " const onRowToggle = useCallback(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 47 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19.89,9.55A1,1,0,0,0,19,9H14V3a1,1,0,0,0-.69-1,1,1,0,0,0-1.12.36l-8,11a1,1,0,0,0-.08,1A1,1,0,0,0,5,15h5v6a1,1,0,0,0,.69.95A1.12,1.12,0,0,0,11,22a1,1,0,0,0,.81-.41l8-11A1,1,0,0,0,19.89,9.55ZM12,17.92V14a1,1,0,0,0-1-1H7l5-6.92V10a1,1,0,0,0,1,1h4Z"/></svg>
public/img/icons/unicons/bolt-alt.svg
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017368303088005632, 0.00017368303088005632, 0.00017368303088005632, 0.00017368303088005632, 0 ]